Skip to content
Python

fix(permissions): env and git config ask; the card's grant button follows the shell (OPE-232)

Devika Vermad7b3f12915d6
diff --git a/coworker/engine.py b/coworker/engine.py
index 8f9071ac..29e94a68 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -90,13 +90,13 @@ class ApprovalOutcome(str, Enum):
SUPERSEDED = "superseded"
-def _readonly_ok(arguments: dict) -> bool:
+def _readonly_ok(arguments: dict, shell: Optional[str] = "bash") -> bool:
command = str((arguments or {}).get("command", "") or "")
if not command:
return False
from .readonly import is_readonly_command
- return is_readonly_command(command)
+ return is_readonly_command(command, shell=shell or "bash")
@dataclass
@@ -1842,7 +1842,7 @@ class TurnEngine:
),
# True when this shell command classifies as read-only — the card
# offers "Allow read-only commands for this session" only then.
- "readonly_ok": _readonly_ok(tool_call.arguments),
+ "readonly_ok": _readonly_ok(tool_call.arguments, self.permissions.shell_kind),
# OPE-136 finding 4: where an MCP call actually goes, stamped at
# registration (mcp/tools.py) from the server def — so the card's
# scope chip can say "leaves this computer → host" instead of the
diff --git a/coworker/readonly.py b/coworker/readonly.py
index 155e6b42..63d32c05 100644
--- a/coworker/readonly.py
+++ b/coworker/readonly.py
@@ -663,7 +663,6 @@ _SPECS: dict[str, _Spec] = {
),
"true": _spec(max_operands=0, common=False),
"false": _spec(max_operands=0, common=False),
- "env": _spec("0", long="null", max_operands=0), # bare `env` prints; operands run things
"command": _spec("vVp", operands="none", check=_command_check, common=False),
"column": _spec("tx", "c:num s:text o:text"),
"diff": _spec(
@@ -925,6 +924,7 @@ def _actionlint_analyze(args: list[str]) -> list[str] | None:
# inside the folders, but `git diff` also compares plain files named on the command line.
# Pretty-format placeholders that verify signatures (`%G…`) run an external program, so a
# format containing them rejects; so do the flags that run diff or textconv drivers.
+# `git config` is not on the list: settings can hold credentials, so reading them asks.
_GIT_GLOBAL_FLAGS = frozenset({
"--no-pager", "-P", "--no-optional-locks", "--literal-pathspecs", "--glob-pathspecs",
@@ -973,17 +973,6 @@ def _git_list_check(flags: Flags, operands: list[str]) -> bool:
return not operands or _has(flags, "l", "list") # operands without --list create
-def _git_config_check(flags: Flags, operands: list[str]) -> bool:
- modes = [n for n, _, _ in flags if n in ("get", "get-all", "get-regexp", "get-urlmatch", "list", "l")]
- if not modes:
- if operands[:1] == ["list"]:
- return len(operands) == 1
- return operands[:1] == ["get"] and 2 <= len(operands) <= 3
- if len(modes) != 1:
- return False
- return len(operands) == 0 if modes[0] in ("list", "l") else 1 <= len(operands) <= 2
-
-
_GIT_SPECS: dict[str, _Spec] = {
"log": _GIT_REV,
"show": _GIT_REV,
@@ -1082,15 +1071,6 @@ _GIT_SPECS: dict[str, _Spec] = {
check=_git_list_check,
common=False,
),
- "config": _spec(
- "lz", "f:path",
- long="get get-all get-regexp get-urlmatch list show-origin show-scope name-only null "
- "global system local worktree includes no-includes bool int bool-or-int path "
- "expiry-date all regexp",
- lvals="file:path blob:text type:text default:text url:text",
- check=_git_config_check,
- common=False,
- ),
}
_GIT_REMOTE_GET_URL = _spec(long="push all", max_operands=1, common=False)
_GIT_REMOTE_SHOW = _spec("n", check=lambda flags, _ops: _has(flags, "n"), common=False) # -n: no network
@@ -1265,6 +1245,32 @@ def _ps_value_ok(kind: Optional[str], value: str) -> bool:
return True
+# A recursive listing may follow a directory junction out of the folders. Later stages
+# that only see names and sizes are fine; a stage that reads the listed files asks.
+_PS_NAME_ONLY = frozenset({"select-object", "sort-object", "measure-object", "write-output"})
+
+
+def _ps_recursive_listing(argv: list[str]) -> bool:
+ head = argv[0].lower()
+ if _PS_ALIASES.get(head, head) != "get-childitem":
+ return False
+ aliases = _PS_SPECS["get-childitem"].aliases
+ for tok in argv[1:]:
+ if tok.startswith("-") and len(tok) > 1:
+ name = tok[1:].partition(":")[0].lower()
+ if aliases.get(name, name) in ("recurse", "depth"):
+ return True
+ return False
+
+
+def _powershell_pipeline_ok(stages: list[list[str]]) -> bool:
+ for i, stage in enumerate(stages):
+ if _ps_recursive_listing(stage):
+ later = (s[0].lower() for s in stages[i + 1 :])
+ return all(_PS_ALIASES.get(h, h) in _PS_NAME_ONLY for h in later)
+ return True
+
+
def _powershell_stage(argv: list[str]) -> list[str] | None:
head, args = argv[0].lower(), argv[1:]
if head == "git":
@@ -1358,6 +1364,8 @@ def _analyze(command: str, shell: str) -> tuple[list[list[str]], list[list[str]
if shell == "powershell":
if any(_ENV_ASSIGN.match(s[0]) for s in stages):
return None # not an assignment in PowerShell: it would be a command name
+ if not _powershell_pipeline_ok(stages):
+ return stages, [None] * len(stages)
return stages, [_powershell_stage(s) for s in stages]
return stages, [_bash_stage(s) for s in stages]
diff --git a/tests/test_readonly_allowlist.py b/tests/test_readonly_allowlist.py
index 50a12035..1cca7de9 100644
--- a/tests/test_readonly_allowlist.py
+++ b/tests/test_readonly_allowlist.py
@@ -56,7 +56,7 @@ ACCEPT = [
# small utilities
"pwd", "whoami", "id -u", "date", "date -u +%Y", "date -d @0 +%s", "uname -a",
"basename a/b.c .c", "dirname a/b.c", "realpath x", "readlink -f x", "which -a git",
- "echo hello", "echo -n hi", "printf 'a: '", "true", "false", "env",
+ "echo hello", "echo -n hi", "printf 'a: '", "true", "false",
"command -v semgrep", "command -V git",
# git
"git status", "git status --short", "git status -sb", "git status --porcelain",
@@ -80,8 +80,7 @@ ACCEPT = [
"git branch --contains abc", "git branch --list 'feat*'", "git branch -r --merged",
"git tag", "git tag -l", "git tag -l 'v1*'", "git tag -n5 -l",
"git stash list", "git stash show -p", "git remote", "git remote -v",
- "git remote get-url origin", "git config --get user.name", "git config --list",
- "git config -l", "git config get user.name", "git reflog", "git reflog show -5",
+ "git remote get-url origin", "git reflog", "git reflog show -5",
"git --no-pager log -1", "git -C /tmp/repo log -1", "git --version",
]
@@ -116,7 +115,7 @@ REJECT = [
"df --sync", "md5sum -c sums", "sha256sum --check sums", "shasum -c sums",
"pwd x", "whoami x", "date 0101", "date -s now", "date -f list", "date -r x",
"uname -x", "basename --zzz x", "readlink --zzz x", "which --zzz git",
- "echo -x hi", "printf -v name x", "true x", "env -i ls", "env -u X ls", "env X=1",
+ "echo -x hi", "printf -v name x", "true x", "env", "printenv", "env -i ls", "env -u X ls", "env X=1",
"command ls", "command -p ls", "id -A",
# git
"git log --output=x", "git log --ext-diff", "git log --textconv", "git log --show-signature",
@@ -131,7 +130,9 @@ REJECT = [
"git tag v1", "git tag -d v1", "git tag -a v1 -m x", "git tag -v v1",
"git stash", "git stash pop", "git stash drop", "git remote add x y", "git remote show origin",
"git remote set-url origin x", "git config user.name x", "git config --unset x",
- "git config --edit", "git config --add a b", "git reflog expire --all", "git reflog delete x",
+ "git config --edit", "git config --add a b", "git config --list", "git config -l",
+ "git config --get user.name", "git config get user.name", "git config --get http.extraheader",
+ "git reflog expire --all", "git reflog delete x",
"git -c core.pager=x log", "git --git-dir=x log", "git --work-tree=x status",
"git --exec-path=x status", "git --help", "git fetch", "git checkout x", "git commit -m x",
"git status --zzz", "git rev-parse --resolve-git-dir x",
@@ -159,7 +160,7 @@ def test_any_other_flag_gets_a_card(command):
("strings @options.txt", False), # an `@file` operand is read as more options
("command -v ls", True),
("command ls", False), # runs ls
- ("env", True),
+ ("env", False), # prints every environment variable, secrets included
("env ls", False), # runs ls
("printf '%s\\n' a b", True),
],
@@ -393,7 +394,6 @@ def test_a_hash_inside_a_word_is_part_of_the_word():
("git grep -f /x/pats", "/x/pats"),
("git ls-files -X /x/l", "/x/l"),
("git ls-files --exclude-from=/x/l", "/x/l"),
- ("git config --file /x/conf --list", "/x/conf"),
("git diff --no-index /x/a b", "/x/a"), # git diff reads plain files, too
("git -C /x log", "/x"),
],
@@ -426,6 +426,10 @@ PS_ACCEPT = [
"cat README.md | sort", "cat README.md | Sort-Object -Unique", "ls | Select-Object -First 5",
"echo hello", "Get-ChildItem -Recurse -ErrorAction SilentlyContinue",
"git status", "git log --oneline -5", "git diff --stat",
+ # a recursive listing may feed cmdlets that only see names and sizes
+ "Get-ChildItem -Recurse | Select-Object -First 20", "gci -Recurse -File | Measure-Object",
+ "ls -Recurse | Sort-Object Length -Descending | Select-Object -First 5",
+ "Get-ChildItem src | Get-Content", "ls *.md | Select-String TODO",
]
@@ -443,7 +447,12 @@ PS_REJECT = [
"grep foo x", "head -n 5 x", "tail x", "wc -l x", "sed -n 1p x", "find . -name x",
"cat env:USERPROFILE", "Get-Content -Path Env:PATH", "ls HKLM:/Software", "cat Variable:x",
"Get-ChildItem Registry::HKEY_LOCAL_MACHINE", "Get-ChildItem -Path Cert:/",
- "git log --output=x", "git branch new",
+ "git log --output=x", "git branch new", "git config --list",
+ # a recursive listing feeding a cmdlet that reads the files it lists
+ "Get-ChildItem -Recurse | Select-String secret", "gci -Recurse | Get-Content",
+ "ls -r *.txt | sls password", "Get-ChildItem -Depth 3 | Get-Content",
+ "gci -Recurse -File | Select-Object -First 5 | Get-Content",
+ "Get-ChildItem -s | Get-FileHash",
]
diff --git a/tests/test_readonly_grant.py b/tests/test_readonly_grant.py
index 0613e93c..122e5033 100644
--- a/tests/test_readonly_grant.py
+++ b/tests/test_readonly_grant.py
@@ -24,7 +24,7 @@ ACCEPT = [
"git -C /tmp/repo log -1",
"git branch --show-current",
"git stash list",
- "git config --get user.name",
+ "git rev-parse HEAD",
"git remote -v",
"jq '.results | length' /tmp/report.json",
"find . -name '*.py'",
diff --git a/tests/test_readonly_shell_aware.py b/tests/test_readonly_shell_aware.py
index ff60fdee..72c0e143 100644
--- a/tests/test_readonly_shell_aware.py
+++ b/tests/test_readonly_shell_aware.py
@@ -255,3 +255,22 @@ def test_a_new_batch_trusts_the_shell_folder_again(tmp_path):
engine.permissions.shell_cwd = engine.current_shell_cwd
_run(engine, "look around")
assert approvals == []
+
+
+# -- the card's button ------------------------------------------------------------------------
+
+
+ "command, shell, expected",
+ [
+ ("grep foo notes.txt", "bash", True),
+ ("grep foo notes.txt", "powershell", False), # not a PowerShell command the grant covers
+ ("Select-String foo notes.txt", "powershell", True),
+ ("Select-String foo notes.txt", "bash", False),
+ ("", "bash", False),
+ ],
+)
+def test_the_card_offers_the_grant_only_for_commands_it_covers(command, shell, expected):
+ from coworker.engine import _readonly_ok
+
+ assert _readonly_ok({"command": command}, shell) is expected