Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions core/harness/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import fnmatch
import os
import re
import shlex
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from enum import Enum
Expand Down Expand Up @@ -333,6 +334,68 @@ def _is_shell_tool(tool_name: str) -> bool:
)


def _shell_symlink_alias(
command: str, cwd: str | None = None
) -> tuple[str, str] | None:
"""Return ``(alias, target)`` when a command word is a link to a secret.

A shell tool carries its operands inside the command string, under a key no
path rule names, so ``_path_values`` never sees them. Screening every word
would make ordinary commands impossible to approve, though: ``cp
.env.example .env``, ``source .env`` and ``git add .env.example`` would all
become denials that no rule can override, and builds legitimately read
files with those names.

The shape that actually hides a target from the approval prompt is narrower:
an existing symlink whose own name says nothing, but whose resolved target
is protected. The prompt then shows ``video.mp4`` while the write lands on
``.env``. Only that shape is returned here.

``argv[0]`` is skipped because it is the program name. A word that is not
an existing symlink is left alone: a plain ``.env`` is already governed by
the sandbox, which keeps shell commands away from the home credential
stores. A link whose own name is already sensitive is also left to the
ordinary path check, so this helper never weakens it.
"""
try:
tokens = shlex.split(command, posix=True)
except ValueError: # unbalanced quotes -> fall back to whitespace splitting
tokens = command.split()
for index, token in enumerate(tokens):
if not token or token.startswith("-"):
continue
# Strip shell punctuation that wraps a path (``a.mp4;``, ``(x)``).
cleaned = token.strip("'\"").rstrip(";,&|)")
if not cleaned:
continue
# argv[0] is the program name, not an operand.
if index == 0 and "/" not in cleaned and "\\" not in cleaned:
continue
path = _normalize_path(cleaned, cwd)
try:
if not os.path.islink(path):
continue
except OSError:
continue
# "Own name" is judged without resolving the link. is_sensitive_path()
# resolves realpath first, so asking it here would answer for the
# TARGET and skip the one shape this helper exists to report.
own = path.replace(os.sep, "/").casefold()
own_name = own.rsplit("/", 1)[-1]
if any(
fnmatch.fnmatchcase(own, pattern) or fnmatch.fnmatchcase(own_name, pattern)
for pattern in SENSITIVE_PATH_PATTERNS
):
continue
try:
target = os.path.realpath(path)
except (OSError, ValueError):
continue
if is_sensitive_path(target, cwd):
return cleaned, target
return None


def is_shell_tool(tool_name: str) -> bool:
"""Whether ``tool_name`` runs a shell command."""

Expand Down Expand Up @@ -461,6 +524,34 @@ def hits_sensitive_path(self, arguments: Mapping[str, object]) -> str | None:
return raw
return None

def shell_symlink_alias(
self, tool_name: str, arguments: Mapping[str, object]
) -> tuple[str, str] | None:
"""Return ``(alias, target)`` for a shell word that links to a secret.

Shell operands live inside the command string, so no path-keyed rule
sees them; the aliasing shape is described on
:func:`_shell_symlink_alias`. Kept separate from
:meth:`hits_sensitive_path` because the two answer different questions:
that one is a non-overridable deny, this one is a named confirmation.
"""
if not tool_name or not _is_shell_tool(tool_name):
return None
for key in ("command", "cmd", "commands", "script"):
value = arguments.get(key)
if isinstance(value, str):
found = _shell_symlink_alias(value, self.cwd)
if found is not None:
return found
elif isinstance(value, (list, tuple)):
for item in value:
if not isinstance(item, str):
continue
found = _shell_symlink_alias(item, self.cwd)
if found is not None:
return found
return None

def hits_hook_config_path(self, arguments: Mapping[str, object]) -> str | None:
"""Return the raw path if any argument targets a hook-discovery file."""
for raw in self._candidate_paths(arguments):
Expand Down Expand Up @@ -565,6 +656,16 @@ def _evaluate(
),
)

# A shell word that is a link to a secret hides its target from the
# approval prompt: the operator reads ``video.mp4`` and the write lands
# on ``.env``. This is a named confirmation, not a deny -- the denylist
# above stays reserved for paths that are secret by their own name.
symlink_alias = (
self.shell_symlink_alias(tool_name, arguments)
if self.protect_sensitive_paths
else None
)

read_only = (
self.is_read_only(tool_name)
if read_only_override is None
Expand Down Expand Up @@ -595,6 +696,11 @@ def _evaluate(
if rule.matches(tool_name, argument):
matched = rule
if matched is not None:
if matched.action is PermissionDecision.ALLOW and symlink_alias is not None:
return self._apply_approval_policy(
PermissionDecision.ASK,
self._alias_reason(symlink_alias),
)
if matched.action is PermissionDecision.ALLOW and hook_config is not None:
return self._apply_approval_policy(
PermissionDecision.ASK,
Expand Down Expand Up @@ -625,6 +731,11 @@ def _evaluate(
"exploration is permitted until the plan is approved.",
)
if self.mode is PermissionMode.FULL_AUTO:
if symlink_alias is not None:
return self._apply_approval_policy(
PermissionDecision.ASK,
self._alias_reason(symlink_alias),
)
if hook_config is not None:
return self._apply_approval_policy(
PermissionDecision.ASK,
Expand All @@ -641,6 +752,14 @@ def _evaluate(
return self._mode_default_allow(
tool_name, arguments, "default mode: read-only tool allowed"
)
# Ask mode is where the prompt is shown, so it is where a hidden
# target must be named: otherwise the operator approves "cp video.mp4"
# without ever seeing that the write lands on .env.
if symlink_alias is not None:
return self._apply_approval_policy(
PermissionDecision.ASK,
self._alias_reason(symlink_alias),
)
return self._apply_approval_policy(
PermissionDecision.ASK,
confirmation_reason(tool_name),
Expand All @@ -667,6 +786,16 @@ def _mode_default_allow(
feature.
"""

if symlink_alias := (
self.shell_symlink_alias(tool_name, arguments)
if self.protect_sensitive_paths
else None
):
return self._apply_approval_policy(
PermissionDecision.ASK,
self._alias_reason(symlink_alias),
)

if self.risk_evaluator is None:
return PermissionDecision.ALLOW, reason

Expand All @@ -678,6 +807,14 @@ def _mode_default_allow(
f"risk evaluator flagged this call: {risk_reason}",
)

@staticmethod
def _alias_reason(symlink_alias: tuple[str, str]) -> str:
"""Name both ends of the link: the visible word and the real target."""
alias, target = symlink_alias
return (
f"'{alias}' links to '{target}', a protected path; confirm before this runs"
)

def _risk_opinion(
self, tool_name: str, arguments: Mapping[str, object]
) -> str | None:
Expand Down
107 changes: 107 additions & 0 deletions tests/test_harness_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,3 +509,110 @@ def test_rule_reasons_name_the_users_rule():
PermissionDecision.DENY,
"Blocked by your permission rule `bash rm *`.",
)


# ---- shell command paths must reach the sensitive-path check ----------------
#
# An approval prompt shows the command text, so an innocent-looking symlink can
# hide the real target: the command touches the link, the kernel writes through
# it to a protected file. Key-based path extraction never looked inside a shell
# command string, so that shape was auto-allowed.


def _symlink_fixture(tmp_path):
"""Create a protected credential file (victim) + ``video.mp4`` link (bait)."""
import os

victim = tmp_path / ".env"
victim.write_text("SECRET=x", encoding="utf-8")
bait = tmp_path / "video.mp4"
try:
os.symlink(victim, bait)
except (OSError, NotImplementedError) as exc: # Windows without privilege
import pytest

pytest.skip(f"cannot create symlink here: {exc}")
return victim, bait


def test_shell_symlink_alias_reports_the_hidden_target(tmp_path):
"""Only an existing link with an innocent name counts as an alias."""
import os

from core.harness.permissions import _shell_symlink_alias

victim, bait = _symlink_fixture(tmp_path)
found = _shell_symlink_alias(f"cp {bait.name} out/", str(tmp_path))
assert found is not None, "a link to a protected file was not reported"
alias, target = found
assert alias == bait.name
assert os.path.realpath(target) == os.path.realpath(victim)


def test_key_only_extraction_never_saw_shell_paths():
"""Baseline of the hole: key-based extraction yields nothing."""
from core.harness.permissions import _path_values

assert list(_path_values({"command": "cp video.mp4 docs/"})) == []


def test_copy_through_symlink_asks_and_names_the_target(tmp_path):
"""The payload becomes a confirmation naming both ends, never a silent allow."""
import os

victim, bait = _symlink_fixture(tmp_path)
engine = PermissionEngine(mode=PermissionMode.FULL_AUTO, cwd=str(tmp_path))
decision, reason = engine.evaluate("bash", {"command": f"cp {bait.name} out/"})
assert decision is PermissionDecision.ASK, reason
assert bait.name in reason
assert os.path.basename(str(victim)) in reason

# Ask mode is where the prompt is shown: the same command must name the
# target there too, not fall back to the generic "needs your approval".
ask_mode = PermissionEngine(mode=PermissionMode.DEFAULT, cwd=str(tmp_path))
decision, reason = ask_mode.evaluate("bash", {"command": f"cp {bait.name} out/"})
assert decision is PermissionDecision.ASK, reason
assert bait.name in reason
assert os.path.basename(str(victim)) in reason


def test_a_symlink_alias_asks_even_when_an_allow_rule_matches(tmp_path):
"""An allow rule may not quietly wave the hidden target through."""
_victim, bait = _symlink_fixture(tmp_path)
engine = PermissionEngine(
mode=PermissionMode.DEFAULT,
cwd=str(tmp_path),
rules=[PermissionRule("*", "*", PermissionDecision.ALLOW)],
)
decision, reason = engine.evaluate("bash", {"command": f"cp {bait.name} out/"})
assert decision is PermissionDecision.ASK, reason
assert "links to" in reason


def test_ordinary_shell_commands_still_ask(tmp_path):
"""Everyday commands stay ask; naming a secret is not itself a denial."""
engine = PermissionEngine(mode=PermissionMode.DEFAULT, cwd=str(tmp_path))
for command in (
"cp .env.example .env",
"source .env",
"docker compose --env-file .env up",
"echo PORT=3000 >> .env",
"git add .env.example",
"jq -r .key package.json",
"curl -O https://curl.se/ca/cacert.pem",
"openssl req -keyout key.pem -out cert.pem",
"uvicorn --ssl-keyfile key.pem",
"grep -n id_rsa README.md",
):
decision, reason = engine.evaluate("bash", {"command": command})
assert decision is PermissionDecision.ASK, f"{command!r}: {reason}"


def test_non_shell_tool_command_arg_is_not_scanned(tmp_path):
"""Only shell tools get argv probing; an MCP ``command`` arg is untouched."""
_victim, bait = _symlink_fixture(tmp_path)
engine = PermissionEngine(mode=PermissionMode.FULL_AUTO, cwd=str(tmp_path))
arguments = {"command": f"cp {bait.name} out/"}
assert engine.shell_symlink_alias("mcp_custom", arguments) is None
# ...while the same argument on a shell tool is reported.
assert engine.shell_symlink_alias("bash", arguments) is not None
Loading