Python
fix(permissions): the read-only session grant knows its shell and fails closed (OPE-232)
Devika Vermab45f47df83f4
diff --git a/coworker/agent.py b/coworker/agent.pyindex 49ee0866..edb3a970 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -751,6 +751,10 @@ def build_engine(if _compaction_overrides:engine.compaction_settings = lambda: dict(_compaction_overrides)engine.executor = executor # type: ignore[attr-defined]+ # OPE-232: the read-only session grant judges paths from the persistent shell's+ # current folder, not the workspace folder it may have moved away from.+ if executor is not None:+ engine.permissions.shell_cwd = engine.current_shell_cwdengine.sandbox_workspace = sandbox_workspace # type: ignore[attr-defined]# OPE-219: a sandboxed session with "Only the sites you allow" holds its web tools to# the same list as its commands. They run in this process, outside the sandbox, so thediff --git a/coworker/engine.py b/coworker/engine.pyindex c5f04d52..8f9071ac 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -253,6 +253,10 @@ class TurnEngine:# into the tool message's `_display` sidecar, so the quiet provenance chips# survive reload (owner ruling 2026-08-24) — display-only, never provider-visible.self._approval_origins: dict[str, dict[str, str]] = {}+ # OPE-232: set once a shell command has been cleared in the batch being authorized.+ # The batch runs only after every call is cleared, and the shell persists, so a+ # later command's folder is unknown from then on (see `current_shell_cwd`).+ self._shell_cleared_in_batch = False# Shadow evaluation (spec Part 6 step 3): when True and a reviewer is attached, the# reviewer records what it WOULD have decided on each approval card while the human# still decides. Fire-and-forget — the card is never delayed, no decision is ever@@ -1104,6 +1108,7 @@ class TurnEngine:# verdict physically cannot land on the wrong action). The loop below stays# sequential because approval cards are interactive and must reach the human one# at a time, in call order.+ self._shell_cleared_in_batch = Falseawait self._preconsult_reviewer(tool_calls)cleared: list[ToolCall] = []for tool_call in tool_calls:@@ -1163,6 +1168,8 @@ class TurnEngine:allowed = itemif allowed:cleared.append(tool_call)+ if tool_call.name == "run_shell":+ self._shell_cleared_in_batch = Trueconcurrent = ([tc for tc in cleared if self._parallel_safe(tc)]@@ -1353,6 +1360,16 @@ class TurnEngine:)return match.render() if match else ""+ def current_shell_cwd(self) -> Optional[str]:+ """OPE-232: the persistent shell's current folder, or None when it cannot be known+ for the call being checked: no shell, or a shell command already cleared in this+ batch may move it before this one runs."""+ if self._shell_cleared_in_batch:+ return None+ executor = getattr(self, "executor", None)+ cwd = getattr(executor, "cwd", None) if executor is not None else None+ return str(cwd) if cwd else None+async def _preconsult_reviewer(self, tool_calls: list[ToolCall]) -> None:"""Fire one reviewer request per call that will escalate, all concurrently, andpark the verdicts for `_authorize` to consume. One action per request — there isdiff --git a/coworker/permissions.py b/coworker/permissions.pyindex 734f95aa..f17bc1e3 100644--- a/coworker/permissions.py+++ b/coworker/permissions.py@@ -8,8 +8,11 @@ prefixes) and a session allowlist. The engine only *decides*; the turn engine rofrom __future__ import annotations+import glob as _glob+import osimport reimport shlex+import sysfrom dataclasses import dataclass, fieldfrom enum import Enumfrom pathlib import Path@@ -402,6 +405,15 @@ class PermissionEngine:# Session-wide read-only grant (owner ask 2026-08-11): auto-allow shell commands the# conservative classifier (coworker/readonly.py) accepts. User-elected per session.session_readonly: bool = False+ # OPE-232: which shell runs `run_shell` — "bash" (macOS / Linux) or "powershell"+ # (Windows); None picks by platform. The read-only check reads the command as that+ # shell would.+ shell_kind: Optional[str] = None+ # The persistent shell's current folder, as the engine knows it right now. None (no+ # callable) means no shell is wired and the workspace folder is used, as before; a+ # callable that returns None means the folder is unknown for this call (another shell+ # command was cleared earlier in the same batch and may move it), so the grant asks.+ shell_cwd: Optional[Callable[[], Optional[str]]] = None# Task-scoped standing rules (§25): {tool: {allowed targets}}, seeded from the owning# ScheduledTask's target-shaped entries. Kept by reference and re-read every check, so a# rule minted mid-run ("Allow every time") applies to the run's next call too.@@ -431,6 +443,8 @@ class PermissionEngine:self.auto_allow_tools = set(self.auto_allow_tools)if self.roots is None:self.roots = [{"path": self.workspace_root, "writable": True}]+ if self.shell_kind is None:+ self.shell_kind = "powershell" if sys.platform == "win32" else "bash"def _resolved_roots(self) -> list[tuple[Path, bool]]:out: list[tuple[Path, bool]] = []@@ -603,16 +617,12 @@ class PermissionEngine:# Also a session grant, so §1.5 applies: in Auto-Approve the reviewer judges# these rather than the classifier waving them through.if honor_session_grants and self.session_readonly and command:- from .readonly import is_readonly_command, read_targets-# The classifier vets what a command DOES; the roots vet what it READS# (OPE-130). Without the second half, a grant the user reads as "stop# asking about my project files" also covers ~/.aws/credentials, another# repo's history, and OpenWorker's own secrets file — none of which the# self-protection floor catches, since that guards writes, not reads.- if is_readonly_command(command) and all(- self._under_root(t) for t in read_targets(command)- ):+ if self._readonly_grant_covers(command):return Decision(True, "read-only command (session grant)")if on_site_wall:return Decision(True, "site on the allowed sites")@@ -706,6 +716,38 @@ class PermissionEngine:if command:self.session_allow_commands.add(command)+ def _readonly_grant_covers(self, command: str) -> bool:+ """The read-only session grant's check (OPE-130, OPE-232): the command only reads,+ as this platform's shell runs it, and every path it reads is inside the folders.+ Paths are judged from the shell's real current folder when the engine knows it,+ and wildcards are expanded with every match checked. Fails closed."""+ from .readonly import is_readonly_command, read_targets++ try:+ if not is_readonly_command(command, shell=self.shell_kind):+ return False+ if self.shell_cwd is None:+ base = self.workspace_root+ else:+ cwd = self.shell_cwd()+ if not cwd:+ return False+ base = Path(cwd).expanduser().resolve()+ if not self._under_root(str(base)):+ return False+ for target in read_targets(command, shell=self.shell_kind):+ path = Path(os.path.expanduser(target))+ full = path if path.is_absolute() else base / path+ if any(c in target for c in "*?["):+ for match in _glob.glob(str(full)):+ if not self._under_root(str(Path(match).resolve())):+ return False+ if not self._under_root(str(full.resolve())):+ return False+ return True+ except Exception: # noqa: BLE001 - a check that cannot finish never allows+ return False+def allow_readonly_for_session(self) -> None:self.session_readonly = Truediff --git a/coworker/readonly.py b/coworker/readonly.pyindex 2b2c7684..3f84d2fa 100644--- a/coworker/readonly.py+++ b/coworker/readonly.py@@ -11,6 +11,10 @@ when THIS classifier accepts it. The contract:- **Pipelines are allowed** (`nl … | sed -n … | grep …`) — every stage must classify.All other shell operators (;, &&, ||, &, redirections, substitutions) are rejectedoutright.+- **Shell-aware** (OPE-232). The caller says which shell runs the command: `bash` (macOS,+ Linux) or `powershell` (Windows). For PowerShell only a plain command with literal+ arguments is eligible; anything that can evaluate code or expand values rejects.+- **One line.** A command spanning lines is several commands: rejected.- **Fail closed.** Unknown commands, unparseable input, path-invoked binaries, and anydoubtful flag reject. False negatives cost one manual approval; false positives costan unreviewed side effect — the asymmetry decides every edge case here.@@ -68,6 +72,18 @@ _FLAG_BAD: dict[str, tuple[str, ...]] = {}_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=[^;&|<>`]*$")+# Environment prefixes that only change formatting (locale, time zone, colour, width).+# Any other variable may name a program the command then runs, so it rejects.+_SAFE_ENV = frozenset({+ "LANG", "LANGUAGE", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_NUMERIC",+ "LC_TIME", "TZ", "NO_COLOR", "COLUMNS",+})++SHELLS = ("bash", "powershell")+# PowerShell evaluates or expands these even inside what looks like an argument:+# variables, sub-expressions and grouping, script blocks, array/hash literals, arrays of+# arguments, escapes, call / redirection / sequence operators. Fail closed on any of them.+_POWERSHELL_UNSAFE = frozenset("$`(){}[]@,;&<>")# A sed script token that invokes the `w`/`W` (write-file) command. Two spellings:# * at the start of a script command, optionally after an address —@@ -105,6 +121,8 @@ def _stages(command: str) -> list[list[str]] | None:"""Tokenize with operators surfaced; split into pipeline stages. None = reject."""if not command or not command.strip():return None+ if any(ord(c) < 32 and c != "\t" for c in command):+ return None # a line break starts another command; other controls are never needed# Shell variables are expanded after this check; single-quoted '$' is literal.if _has_unquoted_shell_variable(command) or "$(" in command or "`" in command or "<(" in command or ">(" in command:return None@@ -194,9 +212,11 @@ def _flag_denied(token: str, denied: tuple[str, ...]) -> bool:def _stage_ok(argv: list[str]) -> bool:- # Leading VAR=value assignments (LC_ALL=C grep …) are inert — skip them.+ # Leading VAR=value assignments (LC_ALL=C grep …): only formatting variables pass.i = 0while i < len(argv) and _ENV_ASSIGN.match(argv[i]):+ if argv[i].split("=", 1)[0] not in _SAFE_ENV:+ return Falsei += 1argv = argv[i:]if not argv:@@ -254,11 +274,36 @@ def _stage_ok(argv: list[str]) -> bool:return False-def is_readonly_command(command: str) -> bool:- """True iff `command` is a single command or pure pipeline of local read-only stages."""- stages = _stages(str(command or ""))+def _powershell_plain(command: str) -> bool:+ """A command PowerShell runs as written: no construct that evaluates or expands. (A+ leading `.` or `&` that would run a script is rejected too: `&` here, and `.` because+ it is not a read-only command.)"""+ if any(c in _POWERSHELL_UNSAFE for c in command):+ return False+ return "--%" not in command.split()+++def _powershell_paths(command: str) -> str:+ """PowerShell has no backslash escape: a backslash is a path separator. The tokenizer+ below is bash-style, so hand it forward slashes, which PowerShell paths accept too."""+ return command.replace(chr(92), "/")+++def is_readonly_command(command: str, shell: str = "bash") -> bool:+ """True iff `command` is a single command or pure pipeline of local read-only stages,+ as the given shell (`bash` or `powershell`) would run it."""+ if shell not in SHELLS:+ return False+ command = str(command or "")+ if shell == "powershell":+ if not _powershell_plain(command):+ return False+ command = _powershell_paths(command)+ stages = _stages(command)if stages is None:return False+ if shell == "powershell" and any(_ENV_ASSIGN.match(s[0]) for s in stages):+ return False # not an assignment in PowerShell: it would be a command namereturn all(_stage_ok(s) for s in stages)@@ -322,6 +367,30 @@ def _find_targets(args: list[str]) -> list[str]:return out+def _flag_values(args: list[str]) -> list[str]:+ """Paths a flag carries in the same token (OPE-232): `--file=PATH`, PowerShell's+ `-Path:PATH`, and a short flag with a path attached (`-f/etc/hosts`). Named as read+ targets so they are held to the folders like any operand. Values that are not paths+ (`--format=%H`) resolve inside the folder and cost nothing."""+ out: list[str] = []+ for tok in args:+ if not tok.startswith("-") or tok in {"-", "--"}:+ continue+ if "=" in tok:+ value = tok.split("=", 1)[1]+ elif ":" in tok:+ value = tok.split(":", 1)[1]+ elif not tok.startswith("--") and len(tok) > 2 and (+ "/" in tok[2:] or "\\" in tok[2:] or tok[2:].startswith(("~", "."))+ ):+ value = tok[2:]+ else:+ continue+ if value and not _NUMERIC.match(value):+ out.append(value)+ return out++def _stage_targets(argv: list[str]) -> list[str]:"""File operands of one accepted pipeline stage."""i = 0@@ -337,7 +406,7 @@ def _stage_targets(argv: list[str]) -> list[str]:if head == "git":# Only `-C <dir>` escapes the working directory; everything else the classifier# accepts reads the repo already in scope. Operands after `--` are pathspecs.- out: list[str] = []+ out: list[str] = _flag_values(args)for j, tok in enumerate(args):if tok == "-C" and j + 1 < len(args):out.append(args[j + 1])@@ -347,9 +416,9 @@ def _stage_targets(argv: list[str]) -> list[str]:return outif head == "find":- return _find_targets(args)+ return _find_targets(args) + _flag_values(args)- out = []+ out = _flag_values(args)skip_next = Falseseen_operand = Falsefor tok in args:@@ -376,7 +445,7 @@ def _stage_targets(argv: list[str]) -> list[str]:return out-def read_targets(command: str) -> list[str]:+def read_targets(command: str, shell: str = "bash") -> list[str]:"""Every file operand `command` would read, for scoping against the session's roots.Only meaningful for commands `is_readonly_command` accepts — it assumes that vetting.@@ -386,7 +455,12 @@ def read_targets(command: str) -> list[str]:Known limit: a path reached through a flag this table does not list is not returned.The positional operands that carry the real exposure are covered."""- stages = _stages(str(command or ""))+ if shell not in SHELLS:+ return []+ command = str(command or "")+ if shell == "powershell":+ command = _powershell_paths(command)+ stages = _stages(command)if stages is None:return []return [t for stage in stages for t in _stage_targets(stage)]diff --git a/tests/test_readonly_shell_aware.py b/tests/test_readonly_shell_aware.pynew file mode 100644index 00000000..ff60fdee--- /dev/null+++ b/tests/test_readonly_shell_aware.py@@ -0,0 +1,257 @@+"""OPE-232: the read-only session grant knows which shell runs the command and fails closed.++"Allow read-only commands for this session" lets the commands `coworker/readonly.py`+accepts run without a card. The check now:++* takes the shell kind: bash on macOS / Linux, PowerShell on Windows. For PowerShell only a+ plain command with literal arguments is eligible: anything that can evaluate code or+ expand values is rejected;+* treats a command on more than one line as more than one command (rejected);+* accepts only harmless environment prefixes (locale, time zone, colour);+* names the paths carried by flags (`--file=PATH`, `-fPATH`, `-Path:PATH`) as read targets;+* judges paths from the shell's real current folder when the engine knows it (the shell+ persists between calls), and stops trusting it once another shell command has been+ cleared earlier in the same batch;+* expands wildcards and checks every match.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++from coworker.permissions import Mode, PermissionEngine+from coworker.readonly import is_readonly_command, read_targets+++# -- bash -----------------------------------------------------------------------------------++[email protected]("command", ["ls\ntouch x", "ls\r\ngit status", "git status\n", "cat a\x0bb"])+def test_more_than_one_line_is_never_read_only(command):+ assert not is_readonly_command(command)+ assert not is_readonly_command(command, shell="bash")+++ "command, ok",+ [+ ("LC_ALL=C grep foo build.log", True),+ ("LANG=en_US.UTF-8 sort build.log", True),+ ("TZ=UTC date", True),+ ("NO_COLOR=1 ls", True),+ ("GIT_EXTERNAL_DIFF=./tool.sh git diff", False),+ ("PAGER=./x git log", False),+ ("GIT_PAGER=./x git log", False),+ ("LESSOPEN=x cat build.log", False),+ ("GIT_DIR=../other git log", False),+ ],+)+def test_only_harmless_environment_prefixes(command, ok):+ assert is_readonly_command(command) is ok, command+++ "command, path",+ [+ ("grep --file=/etc/hosts foo src", "/etc/hosts"),+ ("grep -f/etc/hosts foo src", "/etc/hosts"),+ ("rg --ignore-file=../x foo", "../x"),+ ("diff --from-file=../a b", "../a"),+ ],+)+def test_a_path_carried_by_a_flag_is_a_read_target(command, path):+ assert is_readonly_command(command)+ assert path in read_targets(command)+++def test_bash_behaviour_is_otherwise_unchanged():+ assert is_readonly_command("git status")+ assert is_readonly_command("nl -ba x.py | sed -n 1,20p | grep foo")+ assert is_readonly_command("awk '{print $1}' data.txt")+ assert not is_readonly_command("ls; ls")+ assert read_targets("grep -n foo src/x.py") == ["src/x.py"]+++# -- PowerShell ------------------------------------------------------------------------------+++ "command",+ [+ "git status",+ "git log --oneline -5",+ "ls",+ "ls -Recurse src",+ "cat README.md",+ "cat README.md | sort",+ "git diff --stat",+ ],+)+def test_powershell_plain_commands_stay_eligible(command):+ assert is_readonly_command(command, shell="powershell"), command+++ "command",+ [+ "cat $env:USERPROFILE\\notes.txt", # variables+ 'cat "$HOME\\notes.txt"', # expandable string+ "ls (Get-Item .)", # grouping / sub-expression+ "cat $(Get-Location)\\x",+ "cat @('a.txt')", # array literal+ "ls @{a=1}", # hash literal+ "ls | % { $_ }", # script block+ "cat a.txt,b.txt", # an array of paths+ "ls `$x", # backtick escape+ "& git status", # call operator+ ". .\\x.ps1", # dot-sourcing+ "ls; ls",+ "cat a.txt > b.txt",+ "cat [ab].txt",+ "ls --% -x", # stop-parsing token+ "awk '{print $1}' data.txt",+ "ls\ncat x",+ ],+)+def test_powershell_constructs_are_rejected(command):+ assert not is_readonly_command(command, shell="powershell"), command+++def test_powershell_named_path_values_are_targets():+ # PowerShell has no backslash escape; paths come back with forward slashes, which+ # name the same file.+ assert "C:/secret.txt" in read_targets("cat -Path C:\\secret.txt", shell="powershell")+ assert "C:/secret.txt" in read_targets("cat C:\\secret.txt", shell="powershell")+ assert ".." in read_targets("ls -Path:..", shell="powershell")+++def test_an_unknown_shell_fails_closed():+ assert not is_readonly_command("git status", shell="fish")+ assert read_targets("git status", shell="fish") == []+++# -- the session grant --------------------------------------------------------------------------+++def _grant(tmp_path: Path, shell: str = "bash") -> PermissionEngine:+ root = tmp_path / "repo"+ (root / "src").mkdir(parents=True, exist_ok=True)+ (root / "build.log").write_text("boom", encoding="utf-8")+ (root / "notes.md").write_text("n", encoding="utf-8")+ engine = PermissionEngine(workspace_root=root, mode=Mode.INTERACTIVE, shell_kind=shell)+ engine.allow_readonly_for_session()+ return engine+++def _runs(engine: PermissionEngine, command: str) -> bool:+ return engine.evaluate("run_shell", {"command": command}, None).allowed+++def test_the_default_shell_follows_the_platform(tmp_path):+ engine = PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE)+ assert engine.shell_kind == ("powershell" if sys.platform == "win32" else "bash")+++def test_the_grant_asks_for_what_it_must_not_wave_through(tmp_path):+ engine = _grant(tmp_path)+ assert _runs(engine, "cat build.log")+ for command in (+ "ls\ntouch x",+ "GIT_EXTERNAL_DIFF=./tool.sh git diff",+ "grep --file=/etc/hosts foo build.log",+ "grep -f/etc/hosts foo build.log",+ ):+ assert not _runs(engine, command), command+ assert _runs(engine, "grep --file=notes.md foo build.log") # a flag path inside is fine+++def test_the_grant_on_powershell_rejects_its_constructs(tmp_path):+ engine = _grant(tmp_path, shell="powershell")+ assert _runs(engine, "git status")+ assert _runs(engine, "cat build.log")+ assert not _runs(engine, "cat $env:USERPROFILE\\x")+ assert not _runs(engine, "cat build.log,notes.md")+ assert not _runs(engine, "cat -Path ..\\outside.txt")+++def test_the_grant_judges_paths_from_the_shells_folder(tmp_path):+ engine = _grant(tmp_path)+ root = engine.workspace_root+ engine.shell_cwd = lambda: str(root / "src")+ assert _runs(engine, "cat ../build.log") # still inside, seen from src/+ engine.shell_cwd = lambda: str(root.parent)+ assert not _runs(engine, "cat build.log") # the shell is outside the folders+ assert not _runs(engine, "ls")+ engine.shell_cwd = lambda: None # known to be unknown: ask+ assert not _runs(engine, "cat build.log")+++def test_without_shell_wiring_the_workspace_folder_is_used(tmp_path):+ engine = _grant(tmp_path)+ engine.shell_cwd = None+ assert _runs(engine, "cat build.log")+++def test_the_grant_expands_wildcards_and_checks_every_match(tmp_path):+ engine = _grant(tmp_path)+ root = engine.workspace_root+ outside = tmp_path / "outside-secret.txt"+ outside.write_text("secret", encoding="utf-8")+ try:+ os.symlink(outside, root / "notes-link.md")+ except (OSError, NotImplementedError):+ pytest.skip("this machine cannot create symlinks")+ assert not _runs(engine, "cat notes-link.md")+ assert not _runs(engine, "cat notes*") # the wildcard reaches the link+ assert _runs(engine, "cat build*")+++# -- the engine: a batch is cleared before it runs ----------------------------------------------++from coworker.providers import AssistantTurn, ToolCall # noqa: E402+from test_auto_approve import _engine, _run # noqa: E402+++def test_after_one_shell_command_clears_the_rest_of_the_batch_asks(tmp_path):+ # Every call in a batch is cleared before any runs, and the shell persists: a `cd`+ # earlier in the batch could change where a later relative path points.+ root = tmp_path / "repo"+ (root / "src").mkdir(parents=True)+ (root / "build.log").write_text("boom", encoding="utf-8")+ turn = AssistantTurn(+ tool_calls=[+ ToolCall(id="a", name="run_shell", arguments={"command": "git status"}),+ ToolCall(id="b", name="run_shell", arguments={"command": "cat build.log"}),+ ],+ finish_reason="tool_calls",+ )+ engine, _rows, approvals = _engine(root, [turn, AssistantTurn(text="ok", finish_reason="stop")], mode=Mode.INTERACTIVE)+ engine.permissions.shell_kind = "bash"+ engine.permissions.allow_readonly_for_session()+ engine.executor = SimpleNamespace(cwd=str(root))+ engine.permissions.shell_cwd = engine.current_shell_cwd+ _run(engine, "look around")+ assert approvals == ["run_shell"] # the second command got a card+++def test_a_new_batch_trusts_the_shell_folder_again(tmp_path):+ root = tmp_path / "repo"+ root.mkdir()+ (root / "build.log").write_text("boom", encoding="utf-8")+ turns = [+ AssistantTurn(tool_calls=[ToolCall(id="a", name="run_shell", arguments={"command": "git status"})], finish_reason="tool_calls"),+ AssistantTurn(tool_calls=[ToolCall(id="b", name="run_shell", arguments={"command": "cat build.log"})], finish_reason="tool_calls"),+ AssistantTurn(text="ok", finish_reason="stop"),+ ]+ engine, _rows, approvals = _engine(root, turns, mode=Mode.INTERACTIVE)+ engine.permissions.shell_kind = "bash"+ engine.permissions.allow_readonly_for_session()+ engine.executor = SimpleNamespace(cwd=str(root))+ engine.permissions.shell_cwd = engine.current_shell_cwd+ _run(engine, "look around")+ assert approvals == []