Skip to content
Python

OPE-130: scope read-only session grants to the session's folders

Devika Verma5cbd3249d2f7
diff --git a/coworker/permissions.py b/coworker/permissions.py
index 1951a7f0..e2e1cda8 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -407,9 +407,16 @@ 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
-
- if is_readonly_command(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)
+ ):
return Decision(True, "read-only command (session grant)")
if is_egress:
url = str(arguments.get("url", ""))
diff --git a/coworker/readonly.py b/coworker/readonly.py
index c899af46..ae75e6f7 100644
--- a/coworker/readonly.py
+++ b/coworker/readonly.py
@@ -156,3 +156,96 @@ def is_readonly_command(command: str) -> bool:
if stages is None:
return False
return all(_stage_ok(s) for s in stages)
+
+
+# -- read targets (OPE-130) ------------------------------------------------------------
+# The classifier above decides what a command may DO. It says nothing about what the
+# command may READ, so a session grant meant for "stop asking about my project files" also
+# covered ~/.aws/credentials, ~/.ssh/id_rsa and OpenWorker's own secrets file. These
+# helpers name the file operands so the caller can hold them to the session's roots — the
+# same shape as the fix for browser uploads in OPE-122.
+#
+# Extracting read targets from arbitrary shell is not possible in general; it is tractable
+# here only because the classifier has already narrowed the input to the verbs above.
+
+# Operands are not paths: arguments are strings, charsets, or command names.
+_NO_PATH_OPERANDS = {
+ "echo", "printf", "pwd", "whoami", "id", "date", "uname", "true", "false",
+ "which", "basename", "dirname", "tr", "command", "env",
+}
+# The FIRST non-flag operand is a pattern/program, not a path; the rest are files.
+_PATTERN_FIRST = {"grep", "egrep", "fgrep", "rg", "ugrep", "jq", "awk", "gawk", "mawk", "nawk", "sed"}
+# Flags whose VALUE is a path, for the commands that accept them.
+_PATH_VALUE_FLAGS = {"-f", "--file", "--exclude-from", "--include-from"}
+# `head -n 5`, `cut -f 1`, `sed -n 2p`: a bare number is some flag's count, never a file
+# worth scoping. Dropping them keeps the target list honest without a per-flag table.
+_NUMERIC = re.compile(r"^[0-9]+([,:.-][0-9]+)*[a-zA-Z]?$")
+
+
+def _stage_targets(argv: list[str]) -> list[str]:
+ """File operands of one accepted pipeline stage."""
+ i = 0
+ while i < len(argv) and _ENV_ASSIGN.match(argv[i]):
+ i += 1
+ argv = argv[i:]
+ if not argv:
+ return []
+ head, args = argv[0], argv[1:]
+ if head in _NO_PATH_OPERANDS:
+ return []
+
+ 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] = []
+ for j, tok in enumerate(args):
+ if tok == "-C" and j + 1 < len(args):
+ out.append(args[j + 1])
+ elif tok == "--":
+ out.extend(t for t in args[j + 1 :] if not t.startswith("-"))
+ break
+ return out
+
+ out = []
+ skip_next = False
+ seen_operand = False
+ for tok in args:
+ if skip_next:
+ # `-f` is a pattern FILE for grep but a field NUMBER for cut; the numeric test
+ # separates them without needing a per-command flag table.
+ if not _NUMERIC.match(tok):
+ out.append(tok)
+ # `grep -f patterns.txt build.log`: the pattern came from the flag, so the
+ # first positional is already a FILE and must not be skipped as the pattern.
+ seen_operand = True
+ skip_next = False
+ continue
+ if tok.startswith("-"):
+ if tok in _PATH_VALUE_FLAGS:
+ skip_next = True
+ elif head == "find":
+ break # find's predicates start here; paths precede them
+ continue
+ if head in _PATTERN_FIRST and not seen_operand:
+ seen_operand = True # the pattern/script/filter, not a file
+ continue
+ seen_operand = True
+ if not _NUMERIC.match(tok):
+ out.append(tok)
+ return out
+
+
+def read_targets(command: str) -> 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.
+ Errs toward naming MORE operands: an extra one costs a manual approval, a missed one
+ is an unscoped read, and that asymmetry decides the edge cases here as it does above.
+
+ 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 stages is None:
+ return []
+ return [t for stage in stages for t in _stage_targets(stage)]
diff --git a/tests/test_readonly_scoping.py b/tests/test_readonly_scoping.py
new file mode 100644
index 00000000..98b888bb
--- /dev/null
+++ b/tests/test_readonly_scoping.py
@@ -0,0 +1,150 @@
+"""The read-only session grant reads the session's folders, not the machine (OPE-130).
+
+`readonly.py` vets what a command DOES — carefully, and fail-closed. It said nothing about
+what a command READS, so a grant the user reads as "stop asking about my project files"
+also covered ~/.aws/credentials, another repository's history, and OpenWorker's own secrets
+file. The self-protection floor does not cover that: it guards those files against
+modification, not reading.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from coworker.permissions import Mode, PermissionEngine
+from coworker.readonly import is_readonly_command, read_targets
+
+
+def session(tmp_path):
+ """A session whose granted root is `repo/`, with the grant already clicked."""
+ root = tmp_path / "repo"
+ (root / "src").mkdir(parents=True)
+ (root / "build.log").write_text("boom", encoding="utf-8")
+ engine = PermissionEngine(workspace_root=root, mode=Mode.INTERACTIVE)
+ engine.allow_readonly_for_session()
+ return engine
+
+
+def runs(engine, command: str) -> bool:
+ return engine.evaluate("run_shell", {"command": command}, None).allowed
+
+
+# -- the grant still does the job it was built for --------------------------------
+# Born of ~15 hand-approvals per security-scan run; scoping must not undo that.
+ "command",
+ [
+ "cat build.log",
+ "grep AWS_SECRET build.log",
+ "head -n 5 build.log",
+ "ls src",
+ "git status",
+ "git log --oneline",
+ "pwd",
+ "whoami",
+ "cat build.log | grep error",
+ "find . -name '*.py'",
+ ],
+)
+def test_reads_inside_the_granted_folder_still_run_unprompted(session, command):
+ assert runs(session, command), command
+
+
+# -- and no longer reads the rest of the machine ----------------------------------
+ "command",
+ [
+ "cat ~/.aws/credentials",
+ "strings ~/.ssh/id_rsa",
+ "cat /etc/shadow",
+ "grep -r AWS_SECRET /",
+ "find / -name id_rsa",
+ "head -n 5 ~/.aws/credentials",
+ ],
+)
+def test_reads_outside_every_root_now_ask(session, command):
+ assert not runs(session, command), command
+
+
+def test_openworkers_own_secrets_are_no_longer_readable(session):
+ # The floor hard-denies WRITES to this file in every mode and cannot be overridden.
+ # Reading was never checked, so one click on a convenience button dumped it into the
+ # transcript — and from there to the model provider on the next turn.
+ assert not runs(session, "cat ~/.config/coworker/secrets.json")
+ assert not runs(session, "jq . ~/.config/coworker/secrets.json")
+
+
+def test_another_repository_is_not_in_scope(session):
+ # `git -C <dir>` is the one accepted way to leave the working directory.
+ assert not runs(session, "git -C ~/other-private-repo log -p")
+
+
+def test_traversal_is_resolved_not_string_matched(session):
+ assert not runs(session, "cat ../../../etc/passwd")
+ assert not runs(session, "cat ./../../etc/passwd")
+
+
+def test_a_second_granted_root_is_in_scope(tmp_path):
+ from coworker.roots import RootDir
+
+ repo, notes = tmp_path / "repo", tmp_path / "notes"
+ repo.mkdir()
+ notes.mkdir()
+ (notes / "todo.md").write_text("x", encoding="utf-8")
+ engine = PermissionEngine(
+ workspace_root=repo,
+ mode=Mode.INTERACTIVE,
+ roots=[RootDir(path=repo, writable=True), RootDir(path=notes, writable=False)],
+ )
+ engine.allow_readonly_for_session()
+ # Reading needs read access, not write access.
+ assert runs(engine, f"cat {notes / 'todo.md'}")
+ assert not runs(engine, "cat ~/.aws/credentials")
+
+
+def test_a_pipeline_is_only_as_scoped_as_its_stages(session):
+ assert runs(session, "cat build.log | grep -i error")
+ # One out-of-scope stage is enough to stop the whole pipeline.
+ assert not runs(session, "cat build.log | grep -f ~/.ssh/id_rsa")
+
+
+def test_scoping_never_loosens_the_verb_rules(session):
+ # The classifier's own rejections stand: a path inside the workspace does not make
+ # an executing or networking command acceptable.
+ for command in ("python -c 'print(1)'", "curl https://x.io", "pytest -q", "rm build.log"):
+ assert not runs(session, command), command
+
+
+def test_without_the_grant_nothing_changes(tmp_path):
+ engine = PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE)
+ assert not runs(engine, "cat build.log") # still asks — no grant was made
+
+
+# -- target extraction ------------------------------------------------------------
+ "command,expected",
+ [
+ ("cat a.txt b.txt", ["a.txt", "b.txt"]),
+ ("grep PATTERN a.txt", ["a.txt"]), # the pattern is not a file
+ ("grep -f patterns.txt a.txt", ["patterns.txt", "a.txt"]), # -f supplies it instead
+ ("head -n 5 a.txt", ["a.txt"]), # a count is not a file
+ ("cut -f 1 data.csv", ["data.csv"]), # -f is a FIELD here, not a file
+ ("git -C /elsewhere log", ["/elsewhere"]),
+ ("git status", []),
+ ("echo hello", []),
+ ("pwd", []),
+ ("jq .foo data.json", ["data.json"]), # the filter is not a file
+ ("find /tmp -name x", ["/tmp"]), # predicates end the path list
+ ("nl a.txt | sed -n 2p", ["a.txt"]),
+ ],
+)
+def test_read_targets_names_the_files_and_not_the_arguments(command, expected):
+ assert read_targets(command) == expected
+
+
+def test_read_targets_is_empty_for_commands_the_classifier_rejects():
+ # Nothing to scope when the command never gets that far.
+ assert not is_readonly_command("curl https://x.io > out")
+ assert read_targets("curl https://x.io > out") == []