diff --git a/docs/safety/hooks.md b/docs/safety/hooks.md index 228421f375..6a5d05603e 100644 --- a/docs/safety/hooks.md +++ b/docs/safety/hooks.md @@ -425,6 +425,47 @@ plugin generations, uv tool installs, and uv cache archives. This protection applies in every session class and backend. An unresolved write target is denied with guidance to put a literal path in the command. +### Bounded Bash destinations + +The shared scanner supplies Bash destinations to the write-prefix, installation, +Git-ref, and `run_cmd` guards. Supported explicit forms include +`npm install --prefix DIR pkg`, `npm install --prefix=DIR pkg`, and +`npm --prefix DIR install pkg`. The prefix is a content destination. Without +`--prefix`, npm commands are unresolved writes except for recognized usage, +help/version, metadata, and `config get`/`config list` queries. An unresolved +destination is distinct from a command with no detected write. + +For `ln TARGET LINK`, including separate or combined `-s`/`-f`, the destination is +the link entry, not the source. `-t DIR`, `-tDIR`, and detached/equals +`--target-directory` forms derive `DIR/basename(TARGET)` for each source. A lone +source derives an entry in cwd. An existing final directory, including a symlink +to a directory, normally receives a derived child; `-T` selects the final operand +itself, and `-n` prevents following a final symlink to a directory while retaining +ordinary-directory handling. GNU `install` target-directory forms similarly +produce each actual child content destination. Missing required values, unknown +destination-affecting options, and contradictory `-t`/`-T` are unresolved writes. + +Content writes follow final symlinks. Entry replacement resolves the parent and +retains the final basename: replacing an allowed link that points outside is +separate from later writing through that link. A symlinked parent still affects +the entry's physical location. Entry targets such as `/dev/null` remain visible +even where content writes to pseudo-devices are suppressed. + +An npm prefix does not describe all npm writes. The independently configured +[cache](https://docs.npmjs.com/cli/v11/using-npm/config/#cache) and dependency +[lifecycle scripts](https://docs.npmjs.com/cli/v11/using-npm/scripts/) can cause +additional writes; the scanner models neither cache writes nor script side +effects. Installed dependencies' scripts are distinct from hooks in the prefix +project. + +Canonical containment is a point-in-time check: an ancestor or symlink can change +between scanning and execution. Separately, `ln` chooses directory versus entry +semantics from filesystem state; changing the final operand into a directory or +a symlink to one before execution can change the child entry it creates. These +time-of-check-to-time-of-use weaknesses mean the checks provide neither race +immunity nor OS-level confinement. Creating a link entry and accessing its +referent require separate validation. + ### `recipe_write_advisor.py` **Matched tools:** `Write`, `Edit` Non-blocking advisory: suggests `/autoskillit:write-recipe` or diff --git a/src/autoskillit/_destination_paths.py b/src/autoskillit/_destination_paths.py new file mode 100644 index 0000000000..9f019ddfa0 --- /dev/null +++ b/src/autoskillit/_destination_paths.py @@ -0,0 +1,14 @@ +"""Stdlib-only write-destination identity shared by hooks and in-process callers.""" + +from __future__ import annotations + +import os +from pathlib import Path + + +def destination_location(destination: str | os.PathLike[str]) -> Path: + """Resolve the parent of a write destination, preserving its final symlink entry.""" + path = Path(destination) + if not path.name or path.name == "..": + return path.resolve() + return path.parent.resolve() / path.name diff --git a/src/autoskillit/core/io/paths.py b/src/autoskillit/core/io/paths.py index 8d1cbe8fb8..c7783acb07 100644 --- a/src/autoskillit/core/io/paths.py +++ b/src/autoskillit/core/io/paths.py @@ -23,6 +23,8 @@ from pathlib import Path from typing import NamedTuple +from autoskillit._destination_paths import destination_location as destination_location + from .._install_binding import resolve_install_binding from ..fs_observation import safe_mtime @@ -79,25 +81,6 @@ def pkg_root() -> Path: return resolve_install_binding().root -def destination_location(destination: Path) -> Path: - """Resolve a write destination's location without following a final-component symlink. - - ``Path.resolve()`` follows the final component, so a destination that is - *currently* a symlink resolves to its target. For a write destination that - is the wrong question: the destination is about to be replaced, so what - matters is where it lives, not what it happens to point at right now. - Every containment check over a write destination must use this helper. - - ``core/path_containment.py`` is the read-side counterpart and deliberately - does the opposite (``strict=True``, symlinks rejected) — it validates - existing artifacts rather than future write targets. - """ - destination = Path(destination) - if not destination.name: - return destination.resolve() - return destination.parent.resolve() / destination.name - - def resolve_project_dir() -> Path: """Resolve the project root: git toplevel, falling back to cwd. diff --git a/src/autoskillit/execution/headless/_headless_evidence.py b/src/autoskillit/execution/headless/_headless_evidence.py index 96ea7afffb..b100765478 100644 --- a/src/autoskillit/execution/headless/_headless_evidence.py +++ b/src/autoskillit/execution/headless/_headless_evidence.py @@ -4,7 +4,9 @@ import dataclasses import json +import os from datetime import UTC, datetime +from pathlib import Path from typing import TYPE_CHECKING, Any from autoskillit.core import ( @@ -18,11 +20,14 @@ SessionTelemetry, SkillResult, SubagentModelOutcomeDict, + destination_location, get_logger, is_parent_assistant_record, ) +from autoskillit.execution.headless._headless_path_tokens import _is_path_outside_cwd from autoskillit.execution.session._exit_classification import _CODEX_ERROR_CODE_API_STATUS from autoskillit.execution.session._session_model import ClaudeSessionResult +from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets if TYPE_CHECKING: from autoskillit.core import AuditLog, CodingAgentBackend, GitHubApiLog @@ -176,6 +181,46 @@ def _stdout_mentions_write_tools(stdout: str) -> bool: return False +def _tool_write_path_warnings( + tool_name: Any, + inputs: dict[str, Any], + cwd: str, + write_tool_names: frozenset[str], + bash_tool_name: str, +) -> list[str]: + warnings: list[str] = [] + if tool_name == bash_tool_name: + command = inputs.get("command", "") + if isinstance(command, str): + scan = scan_write_targets(command, cwd) + unresolved = scan.unresolved or not scan.parseable + paths = [(path, cwd) for path in scan.targets] + for path in scan.entry_targets: + try: + location = str(destination_location(Path(path))) + physical_cwd = str(Path(cwd).resolve()) if os.path.isabs(cwd) else cwd + paths.append((location, physical_cwd)) + except (OSError, RuntimeError, ValueError): + unresolved = True + if unresolved: + warnings.append( + "Bash command contained a write target that could not be statically resolved. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + for path, comparison_cwd in paths: + if _is_path_outside_cwd(path, comparison_cwd): + normalized = os.path.normpath(path) + warnings.append( + f"Bash command contained write target '{normalized}'" + f" outside session cwd '{cwd}'" + ) + elif tool_name in write_tool_names: + file_path = inputs.get("file_path", "") + if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): + warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") + return warnings + + def _build_session_telemetry( *, skill_result: SkillResult, diff --git a/src/autoskillit/execution/headless/_headless_recovery.py b/src/autoskillit/execution/headless/_headless_recovery.py index 844637df21..948b47b87b 100644 --- a/src/autoskillit/execution/headless/_headless_recovery.py +++ b/src/autoskillit/execution/headless/_headless_recovery.py @@ -23,9 +23,9 @@ is_parent_assistant_record, ) from autoskillit.execution.backends._codex_parse import extract_codex_turn_usage +from autoskillit.execution.headless._headless_evidence import _tool_write_path_warnings from autoskillit.execution.headless._headless_path_tokens import ( _RECOVERABLE_PATH_TOKENS, - _is_path_outside_cwd, ) from autoskillit.execution.process import _marker_is_standalone from autoskillit.execution.session import ( @@ -40,7 +40,6 @@ merge_turn_usage, valid_token_count, ) -from autoskillit.hooks import UNRESOLVED_WRITE_TARGET_REMEDIATION, scan_write_targets if TYPE_CHECKING: from autoskillit.core import ResultParser @@ -87,37 +86,6 @@ def _is_path_capture_pattern(pattern: str) -> str | None: return token_name -def _tool_write_path_warnings( - tool_name: Any, - inputs: dict[str, Any], - cwd: str, - write_tool_names: frozenset[str], - bash_tool_name: str, -) -> list[str]: - warnings: list[str] = [] - if tool_name == bash_tool_name: - command = inputs.get("command", "") - if isinstance(command, str): - scan = scan_write_targets(command, cwd) - if scan.unresolved or not scan.parseable: - warnings.append( - "Bash command contained a write target that could not be statically resolved. " - + UNRESOLVED_WRITE_TARGET_REMEDIATION - ) - for path in scan.targets: - if _is_path_outside_cwd(path, cwd): - normalized = os.path.normpath(path) - warnings.append( - f"Bash command contained write target '{normalized}'" - f" outside session cwd '{cwd}'" - ) - elif tool_name in write_tool_names: - file_path = inputs.get("file_path", "") - if isinstance(file_path, str) and _is_path_outside_cwd(file_path, cwd): - warnings.append(f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'") - return warnings - - def _scan_jsonl_write_paths( stdout: str, cwd: str, diff --git a/src/autoskillit/hooks/__init__.py b/src/autoskillit/hooks/__init__.py index c77af911f7..0824bd38e3 100644 --- a/src/autoskillit/hooks/__init__.py +++ b/src/autoskillit/hooks/__init__.py @@ -78,6 +78,7 @@ enforce_session_scope, hook_session_shape, ) +from autoskillit.hooks._runtime._path_identity import destination_within from autoskillit.hooks._session_binding import LoadedSkillEntry from autoskillit.hooks.formatters._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS from autoskillit.hooks.guards.branch_protection_guard import BRANCH_PROTECTION_DENY_TRIGGER @@ -138,6 +139,7 @@ "capture_store_stats", "command_has_blocked_protected_path_read", "consume_exploration_request_record", + "destination_within", "generate_hooks_json", "is_terminal_outcome", "mark_assignment_running", diff --git a/src/autoskillit/hooks/_runtime/_command_classification.py b/src/autoskillit/hooks/_runtime/_command_classification.py index be409faf69..42867ea1c4 100644 --- a/src/autoskillit/hooks/_runtime/_command_classification.py +++ b/src/autoskillit/hooks/_runtime/_command_classification.py @@ -232,6 +232,21 @@ def _non_option_indices(argv: list[str], argv_tokens: Sequence[ArgvToken] | None ] +def _consume_destination_option( + argv: list[str], + argv_tokens: Sequence[ArgvToken] | None, + index: int, + spec: dict[str, _FlagArity], +) -> tuple[str | None, str | None, int, bool]: + if argv_tokens is None: + value, next_index, recognized = _consume_str_flag(argv, index, spec) + return value, None, next_index, recognized + value_token, next_index, recognized = _consume_argv_flag(argv_tokens, index, spec) + if value_token is None: + return None, None, next_index, recognized + return value_token.text, value_token.raw_span.strip(), next_index, recognized + + def _write_verb_operand_indices( verb: str, argv: list[str], argv_tokens: Sequence[ArgvToken] | None ) -> list[int]: @@ -243,14 +258,6 @@ def _write_verb_operand_indices( return operands[-1:] if verb in {"mv", "cp"}: return operands[-1:] if len(operands) >= 2 else [] - if verb == "install": - # GNU install's -t/--target-directory form takes its destination - # from a flag; otherwise the last operand is the destination. - if "-t" in argv[1:] or "--target-directory" in argv[1:]: - return operands[:1] - if len(operands) < 2: - return [] - return operands[-1:] if verb == "patch": return operands[:1] return operands diff --git a/src/autoskillit/hooks/_runtime/_path_identity.py b/src/autoskillit/hooks/_runtime/_path_identity.py index 78d41109e4..73b62b9169 100644 --- a/src/autoskillit/hooks/_runtime/_path_identity.py +++ b/src/autoskillit/hooks/_runtime/_path_identity.py @@ -10,7 +10,17 @@ from __future__ import annotations import os +import sys from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from autoskillit._destination_paths import destination_location +else: + _PACKAGE_DIR = str(Path(__file__).resolve().parents[2]) + if _PACKAGE_DIR not in sys.path: + sys.path.insert(0, _PACKAGE_DIR) + from _destination_paths import destination_location class PathIdentityError(ValueError): @@ -37,6 +47,11 @@ def hooks_relative_key(script_identity: str | os.PathLike[str], hooks_dir: Path) ) from exc +def destination_within(candidate: str | os.PathLike[str], root: str | os.PathLike[str]) -> bool: + """Compare an entry's physical location with a resolved directory boundary.""" + return destination_location(candidate).is_relative_to(Path(root).resolve()) + + def realpath_within(candidate: str | os.PathLike[str], root: str | os.PathLike[str]) -> bool: """Return whether *candidate* lies at or under *root* after resolving both.""" try: diff --git a/src/autoskillit/hooks/_runtime/_write_target_scan.py b/src/autoskillit/hooks/_runtime/_write_target_scan.py index 55375672ab..01f21f6985 100644 --- a/src/autoskillit/hooks/_runtime/_write_target_scan.py +++ b/src/autoskillit/hooks/_runtime/_write_target_scan.py @@ -13,9 +13,7 @@ from autoskillit.hooks._classification._tokenizer import ArgvToken -WRITE_VERBS: frozenset[str] = frozenset( - {"sed", "tee", "mv", "cp", "patch", "install", "rm", "unlink"} -) +WRITE_VERBS: frozenset[str] = frozenset({"sed", "tee", "mv", "cp", "patch", "rm", "unlink"}) _PSEUDO_DEVICE_PATHS: frozenset[str] = frozenset( {"/dev/null", "/dev/zero", "/dev/stdout", "/dev/stderr", "/dev/stdin"} ) @@ -32,12 +30,17 @@ class WriteTargetScan: unresolved: bool parseable: bool has_write: bool + entry_targets: tuple[str, ...] = () def __post_init__(self) -> None: - if not self.parseable and self.targets: - raise ValueError("WriteTargetScan.targets must be empty when parseable is False") - if not self.has_write and self.targets: - raise ValueError("WriteTargetScan.targets must be empty when has_write is False") + if not self.parseable and (self.targets or self.entry_targets): + raise ValueError( + "WriteTargetScan targets and entry_targets must be empty when parseable is False" + ) + if not self.has_write and (self.targets or self.entry_targets): + raise ValueError( + "WriteTargetScan targets and entry_targets must be empty when has_write is False" + ) @dataclass(slots=True) @@ -56,6 +59,308 @@ def _classification_module() -> ModuleType: return standalone_classification +@dataclass(frozen=True, slots=True) +class _DestinationOperands: + operands: tuple[int, ...] + target_directory: tuple[str, str | None] | None + no_target_directory: bool + no_dereference: bool + create_directories: bool + read_only: bool + invalid: bool + + +def _destination_operands( + verb: str, + argv: list[str], + argv_tokens: Sequence[ArgvToken] | None, +) -> _DestinationOperands: + """Parse the supported ln/install options and positional operands.""" + _classification = _classification_module() + value = _classification._FlagArity.VALUE + if verb == "ln": + value_spec = { + "-t": value, + "--target-directory": value, + "-S": value, + "--suffix": value, + } + boolean_long = { + "--backup", + "--directory", + "--interactive", + "--logical", + "--physical", + "--relative", + "--symbolic", + "--force", + "--no-dereference", + "--no-target-directory", + "--verbose", + } + boolean_short = frozenset("sfnTvbdiFLPr") + else: + value_spec = { + "-t": value, + "--target-directory": value, + "-m": value, + "--mode": value, + "-o": value, + "--owner": value, + "-g": value, + "--group": value, + "-S": value, + "--suffix": value, + } + boolean_long = { + "--backup", + "--compare", + "--directory", + "--preserve-timestamps", + "--strip", + "--no-target-directory", + "--verbose", + } + boolean_short = frozenset("cCDdpsTvbZ") + + operands: list[int] = [] + target_directory: tuple[str, str | None] | None = None + no_target_directory = False + no_dereference = False + directory_mode = False + invalid = False + read_only = False + options = True + index = 1 + while index < len(argv): + token = argv[index] + if options and token == "--": + options = False + index += 1 + continue + if options and token.startswith("-") and token != "-": + if token in {"--help", "--version"}: + read_only = True + index += 1 + continue + option_value, source, next_index, recognized = ( + _classification._consume_destination_option(argv, argv_tokens, index, value_spec) + ) + if recognized: + option = _classification._spec_key_for_token(token, value_spec) + if option_value is None or option_value == "--": + invalid = True + elif option in {"-t", "--target-directory"}: + target_directory = (option_value, source) + index = next_index + continue + if ( + token in boolean_long + or token.startswith("--backup=") + or ( + not token.startswith("--") and all(char in boolean_short for char in token[1:]) + ) + ): + no_target_directory |= token in {"-T", "--no-target-directory"} or ( + not token.startswith("--") and "T" in token[1:] + ) + no_dereference |= token in {"-n", "--no-dereference"} or ( + not token.startswith("--") and "n" in token[1:] + ) + directory_mode |= verb == "install" and ( + token in {"-d", "--directory"} + or (not token.startswith("--") and "d" in token[1:]) + ) + index += 1 + continue + invalid = True + index += 1 + continue + operands.append(index) + index += 1 + invalid |= target_directory is not None and no_target_directory + return _DestinationOperands( + operands=tuple(operands), + target_directory=target_directory, + no_target_directory=no_target_directory, + no_dereference=no_dereference, + create_directories=directory_mode, + read_only=read_only, + invalid=invalid, + ) + + +def _resolved_operand( + argv: list[str], + index: int, + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> str | None: + _classification = _classification_module() + return _classification.resolve_write_target( + argv[index], + cwd, + shell_source=_classification._shell_source(argv_tokens, index), + ) + + +def _source_basename( + argv: list[str], + index: int, + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> str | None: + source = _resolved_operand(argv, index, cwd, argv_tokens) + if source is None: + return None + return os.path.basename(source.rstrip(os.sep)) or None + + +def _directory_children( + directory: str, + source_indices: Sequence[int], + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool]: + targets: list[str] = [] + unresolved = False + for index in source_indices: + basename = _source_basename(argv, index, cwd, argv_tokens) + if basename is None: + unresolved = True + else: + targets.append(os.path.join(directory, basename)) + return targets, unresolved + + +def _target_directory_children( + target_directory: tuple[str, str | None], + source_indices: Sequence[int], + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool]: + value, source = target_directory + directory = _classification_module().resolve_write_target(value, cwd, shell_source=source) + if directory is None: + return [], True + return _directory_children(directory, source_indices, argv, cwd, argv_tokens) + + +def _install_targets( + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, + options: _DestinationOperands, +) -> tuple[list[str], bool]: + operands = options.operands + target_directory = options.target_directory + if options.invalid or not operands: + return [], True + if options.create_directories: + if target_directory is not None: + return [], True + targets = [_resolved_operand(argv, index, cwd, argv_tokens) for index in operands] + return [target for target in targets if target is not None], any( + target is None for target in targets + ) + if target_directory is not None: + return _target_directory_children(target_directory, operands, argv, cwd, argv_tokens) + if len(operands) < 2: + return [], True + + destination = _resolved_operand(argv, operands[-1], cwd, argv_tokens) + if destination is None: + return [], True + sources = operands[:-1] + if options.no_target_directory: + return ([destination], False) if len(sources) == 1 else ([], True) + if len(sources) > 1 or os.path.isdir(destination): + return _directory_children(destination, sources, argv, cwd, argv_tokens) + return [destination], False + + +def _ln_entry_targets( + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, + options: _DestinationOperands, +) -> tuple[list[str], bool]: + operands = options.operands + target_directory = options.target_directory + if options.invalid or not operands: + return [], True + if target_directory is not None: + return _target_directory_children(target_directory, operands, argv, cwd, argv_tokens) + if len(operands) == 1: + basename = _source_basename(argv, operands[0], cwd, argv_tokens) + return ([os.path.join(cwd, basename)], False) if cwd and basename else ([], True) + + destination = _resolved_operand(argv, operands[-1], cwd, argv_tokens) + if destination is None: + return [], True + sources = operands[:-1] + if options.no_target_directory and len(sources) > 1: + return [], True + follows_directory = not options.no_target_directory and os.path.isdir(destination) + if options.no_dereference and os.path.islink(destination): + follows_directory = False + if follows_directory or len(sources) > 1: + return _directory_children(destination, sources, argv, cwd, argv_tokens) + return [destination], False + + +def _npm_read_only_command(argv: list[str]) -> bool: + return ( + len(argv) == 1 + or argv[1:] in (["--help"], ["--version"], ["-h"], ["-v"]) + or argv[1] in {"help", "info", "list", "ls", "prefix", "root", "show", "view"} + or argv[1:3] in (["config", "get"], ["config", "ls"], ["config", "list"]) + ) + + +def _npm_install_targets( + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> tuple[list[str], bool, bool]: + _classification = _classification_module() + prefix_spec = {"--prefix": _classification._FlagArity.VALUE} + separator = argv.index("--") if "--" in argv[1:] else len(argv) + prefix: tuple[str, str | None] | None = None + missing_prefix = False + command_index: int | None = None + uncertain_command = False + index = 1 + while index < separator: + token = argv[index] + if token.startswith("--prefix"): + value, source, next_index, recognized = _classification._consume_destination_option( + argv, argv_tokens, index, prefix_spec + ) + if not recognized: + return [], True, True + if value is None or value == "--": + missing_prefix = True + else: + prefix = (value, source) + index = next_index + continue + if command_index is None and token in {"install", "i", "add", "ci"}: + command_index = index + elif command_index is None and not token.startswith("-"): + uncertain_command = True + index += 1 + if prefix is None and not missing_prefix: + unresolved = not _npm_read_only_command(argv) + return [], unresolved, unresolved + if command_index is None or uncertain_command or missing_prefix or prefix is None: + return [], True, True + target = _classification.resolve_write_target(prefix[0], cwd, shell_source=prefix[1]) + return ([target], False, True) if target is not None else ([], True, True) + + def _ensure_scope_state( scopes: dict[tuple[int, ...], _ShellDirectoryState], path: tuple[int, ...] ) -> _ShellDirectoryState: @@ -278,12 +583,28 @@ def _invoked_child_state( return None +def _scan_destination_command( + verb: str, + argv: list[str], + cwd: str, + argv_tokens: Sequence[ArgvToken] | None, +) -> WriteTargetScan: + options = _destination_operands(verb, argv, argv_tokens) + if options.read_only: + return WriteTargetScan((), False, True, False) + if verb == "ln": + targets, unresolved = _ln_entry_targets(argv, cwd, argv_tokens, options) + return WriteTargetScan((), unresolved, True, True, entry_targets=tuple(targets)) + targets, unresolved = _install_targets(argv, cwd, argv_tokens, options) + return WriteTargetScan(tuple(targets), unresolved, True, True) + + def _scan_executable( executable: list[str], argv_tokens: Sequence[ArgvToken] | None, state: _ShellDirectoryState, path: tuple[int, ...] | None, -) -> tuple[list[str], bool, bool, _ShellDirectoryState | None]: +) -> tuple[WriteTargetScan, _ShellDirectoryState | None]: _classification = _classification_module() start = _classification._verb_start_index(executable) @@ -292,30 +613,34 @@ def _scan_executable( if setting is not None: state.cdpath_unknown = setting[0] if start is None: - return [], False, False, None + return WriteTargetScan((), False, True, False), None handled = _apply_shell_builtin(executable, start, argv_tokens, state) if setting is not None and setting[1]: state.cdpath_unknown = previous_cdpath - if handled: - return [], False, False, None - if _classification.is_gh_command(executable): - return [], False, False, None + if handled or _classification.is_gh_command(executable): + return WriteTargetScan((), False, True, False), None argv = executable[start:] verb = argv[0] verb_cwd = _classification._wrapped_verb_cwd(executable, start, state.cwd, argv_tokens) invoked = _invoked_child_state(verb, verb_cwd, state, path) verb_tokens = None if argv_tokens is None else argv_tokens[start:] - if verb in WRITE_VERBS: + verb_name = os.path.basename(verb) + if verb_name == "npm": + targets, unresolved, has_write = _npm_install_targets(argv, verb_cwd, verb_tokens) + return WriteTargetScan(tuple(targets), unresolved, True, has_write), invoked + if verb_name in {"ln", "install"}: + return _scan_destination_command(verb_name, argv, verb_cwd, verb_tokens), invoked + if verb_name in WRITE_VERBS: targets, unresolved = _classification.extract_write_verb_targets( - verb, argv, verb_cwd, argv_tokens=verb_tokens + verb_name, argv, verb_cwd, argv_tokens=verb_tokens ) - return targets, unresolved, True, invoked + return WriteTargetScan(tuple(targets), unresolved, True, True), invoked if verb == "git" or verb.endswith("/git"): targets, unresolved, has_write = _classification._git_write_targets( argv, verb_cwd, executable[:start], verb_tokens ) - return targets, unresolved, has_write, invoked - return [], False, False, invoked + return WriteTargetScan(tuple(targets), unresolved, True, has_write), invoked + return WriteTargetScan((), False, True, False), invoked def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: @@ -329,6 +654,7 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: return WriteTargetScan((), False, False, False) targets: list[str] = [] + entry_targets: list[str] = [] unresolved = False has_write = False scopes: dict[tuple[int, ...], _ShellDirectoryState] = { @@ -356,13 +682,14 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: if record.argv_tokens is None else [record.argv_tokens[index] for index in partition.segments] ) - verb_targets, verb_unresolved, verb_has_write, invoked = _scan_executable( + verb_scan, invoked = _scan_executable( executable, executable_tokens, state, record.subshell_path ) - targets.extend(verb_targets) + targets.extend(verb_scan.targets) + entry_targets.extend(verb_scan.entry_targets) targets.extend(partition.targets) - unresolved |= verb_unresolved - has_write |= verb_has_write + unresolved |= verb_scan.unresolved + has_write |= verb_scan.has_write if record.subshell_path is not None: pending_children[record.subshell_path] = (pre_command_state, invoked) return WriteTargetScan( @@ -370,6 +697,7 @@ def scan_write_targets(command: str, cwd: str) -> WriteTargetScan: unresolved, True, has_write, + tuple(dict.fromkeys(entry_targets)), ) diff --git a/src/autoskillit/hooks/guards/git_ops_guard.py b/src/autoskillit/hooks/guards/git_ops_guard.py index e80d976095..30508e2a91 100644 --- a/src/autoskillit/hooks/guards/git_ops_guard.py +++ b/src/autoskillit/hooks/guards/git_ops_guard.py @@ -33,6 +33,7 @@ from _command_classification import ( # noqa: E402 _GIT_GLOBAL_FLAG_SPEC, StdinConsumer, + WriteTargetScan, _consume_str_flag, _extract_interpreter_segment_specs, command_verb_and_args, @@ -72,6 +73,7 @@ hook_session_shape, read_merged_hook_config, ) +from _path_identity import destination_location # noqa: E402 GIT_OPS_DENY_TRIGGER: str = DENY_TRIGGER_BY_GUARD["git_ops_guard"] CHECKED_OUT_REF_DENY_PREFIX: str = "Checked-out ref mutation blocked: " @@ -83,9 +85,7 @@ # only the destructive headless operation phase below. _DESTRUCTIVE_OP_EXEMPT_TIERS: frozenset[str] = frozenset({"orchestrator"}) -_RAW_WRITE_VERBS = frozenset( - {"cp", "mv", "install", "tee", "truncate", "rm", "unlink", "sed", "dd"} -) +_RAW_WRITE_VERBS = frozenset({"cp", "mv", "tee", "truncate", "rm", "unlink", "sed", "dd"}) # Git subcommands that can mutate checked-out refs (the same set # _classify_git_segment recognises). Used by _deny_outer_git_mutations @@ -204,9 +204,10 @@ def _raw_write_targets( additional_segments: list[list[str]], additional_owners: list[int | None], interpreter_cwd: str, -) -> tuple[list[tuple[str, str]], bool]: - scan = scan_write_targets(text, initial_cwd) + scan: WriteTargetScan, +) -> tuple[list[tuple[str, str]], list[tuple[str, str]], bool]: targets = [(target, initial_cwd) for target in scan.targets] + entry_targets = [(target, initial_cwd) for target in scan.entry_targets] ambiguous = scan.unresolved outer_cwds = _compute_outer_cwds(outer_segments, initial_cwd) segments_with_cwds = list(zip(outer_segments, outer_cwds)) @@ -238,7 +239,7 @@ def _raw_write_targets( ambiguous = True elif interpreter_paths: targets.extend((path, interpreter_cwd) for path in interpreter_paths) - return (targets, ambiguous) + return (targets, entry_targets, ambiguous) def _raw_target_mutations( @@ -250,25 +251,33 @@ def _raw_target_mutations( additional_owners: list[int | None], interpreter_cwd: str, context: dict[str, object] | None, + scan: WriteTargetScan, ) -> list[tuple[str, str, bool]]: - targets, ambiguous = _raw_write_targets( + targets, entry_targets, ambiguous = _raw_write_targets( text, initial_cwd, outer_segments, additional_segments, additional_owners, interpreter_cwd, + scan, ) if ambiguous: return [("", "", True)] resolved_targets: list[Path] = [] - for raw_target, target_cwd in targets: - target = Path(raw_target) - if not target.is_absolute(): - if not target_cwd: + for raw_targets, is_entry in ((targets, False), (entry_targets, True)): + for raw_target, target_cwd in raw_targets: + target = Path(raw_target) + if not target.is_absolute(): + if not target_cwd: + return [("", "", True)] + target = Path(target_cwd) / target + try: + resolved_targets.append( + destination_location(target) if is_entry else target.resolve() + ) + except (OSError, RuntimeError, ValueError): return [("", "", True)] - target = Path(target_cwd) / target - resolved_targets.append(target.resolve()) if context is None: return [] common = Path(str(context["common_git_dir"])).resolve() @@ -373,7 +382,7 @@ def _preflight_segments( def _is_structural_mutation( - live_text: str, outer: list[list[str]], additional: list[list[str]] + live_text: str, outer: list[list[str]], additional: list[list[str]], *, has_write: bool ) -> bool: return bool( re.search( @@ -381,8 +390,9 @@ def _is_structural_mutation( r"reset\b|fetch\b|push\b|symbolic-ref\s+HEAD)\b", live_text, ) + or has_write or any( - os.path.basename(command_verb_and_args(segment)[0]) in _RAW_WRITE_VERBS + os.path.basename(command_verb_and_args(segment)[0]) in _RAW_WRITE_VERBS | {"install"} for segment in [*outer, *additional] ) ) @@ -491,7 +501,10 @@ def _preflight_checked_out_ref_mutation( # "git push --force" as prose no longer matches, while a heredoc/pipe-fed # shell that actually runs it still does. live_text = live_command_text(command) - structural_mutation = _is_structural_mutation(live_text, outer_segments, additional_segments) + scan = scan_write_targets(live_text, execution_cwd) + structural_mutation = _is_structural_mutation( + live_text, outer_segments, additional_segments, has_write=scan.has_write + ) if not execution_cwd: if structural_mutation: _deny_checked_out_ref( @@ -523,6 +536,7 @@ def _preflight_checked_out_ref_mutation( additional_owners=additional_owners, interpreter_cwd=current_cwd, context=raw_context, + scan=scan, ) ) if interpreter_unresolved and structural_mutation: diff --git a/src/autoskillit/hooks/guards/installation_integrity_guard.py b/src/autoskillit/hooks/guards/installation_integrity_guard.py index 067853647f..5245f364b4 100644 --- a/src/autoskillit/hooks/guards/installation_integrity_guard.py +++ b/src/autoskillit/hooks/guards/installation_integrity_guard.py @@ -3,8 +3,10 @@ from __future__ import annotations +import errno import json import os +import stat import sys from pathlib import Path from typing import TYPE_CHECKING, NoReturn @@ -32,7 +34,7 @@ normalize_payload_cwd, parse_hook_command, ) -from _path_identity import realpath_within # noqa: E402 +from _path_identity import destination_location, destination_within, realpath_within # noqa: E402 from _policy_event import ( # noqa: E402 PolicyEvent, render_provenance_prefix, @@ -139,9 +141,26 @@ def _is_protected_target(path: str) -> bool: return _matches_protected_inode(normalized) -def _bash_targets(command: str, cwd: str) -> tuple[list[str], bool]: +def _is_protected_entry_target(path: str) -> bool: + location = destination_location(Path(path)) + if _has_install_layout(str(location)): + return True + for root in _known_roots(): + if location == destination_location(root) or destination_within(path, root): + return True + try: + entry = os.lstat(path) + except OSError as exc: + return exc.errno not in {errno.ENOENT, errno.ENOTDIR} + if stat.S_ISLNK(entry.st_mode): + return False + return _matches_protected_inode(str(location)) + + +def _bash_targets(command: str, cwd: str) -> tuple[list[str], list[str], bool]: scan = scan_write_targets(command, cwd) targets = list(scan.targets) + entry_targets = list(scan.entry_targets) unresolved_target = scan.unresolved or not scan.parseable interpreter_paths = extract_interpreter_write_paths(command) # ``extract_interpreter_write_paths``: None=non-write, []=interpreter write @@ -156,10 +175,10 @@ def _bash_targets(command: str, cwd: str) -> tuple[list[str], bool]: unresolved_target = True else: targets.append(resolved) - return targets, unresolved_target + return targets, entry_targets, unresolved_target -def _resolve_targets(paths: list[str], cwd: str) -> tuple[list[str], bool]: +def _resolve_targets(paths: list[str], cwd: str) -> tuple[list[str], list[str], bool]: targets: list[str] = [] unresolved_target = False for path in paths: @@ -168,13 +187,13 @@ def _resolve_targets(paths: list[str], cwd: str) -> tuple[list[str], bool]: unresolved_target = True else: targets.append(resolved) - return targets, unresolved_target + return targets, [], unresolved_target -def _collect_write_targets(data: dict[str, object]) -> tuple[list[str], bool]: +def _collect_write_targets(data: dict[str, object]) -> tuple[list[str], list[str], bool]: tool_name = data.get("tool_name") if not isinstance(tool_name, str): - return [], False + return [], [], False payload_cwd = normalize_payload_cwd(data.get("cwd")) edit_paths = edit_target_paths(data) if edit_paths: @@ -182,7 +201,7 @@ def _collect_write_targets(data: dict[str, object]) -> tuple[list[str], bool]: parsed = parse_hook_command(data) if parsed.tool_kind in {"bash", "run_cmd"}: return _bash_targets(parsed.command or "", parsed.execution_cwd) - return [], False + return [], [], False def main() -> None: @@ -193,14 +212,22 @@ def main() -> None: if not isinstance(data, dict): sys.exit(0) - targets, unresolved_target = _collect_write_targets(data) + targets, entry_targets, unresolved_target = _collect_write_targets(data) if unresolved_target: _deny( "unresolved-write-target", "Write target could not be resolved safely. " + UNRESOLVED_WRITE_TARGET_REMEDIATION, ) - if any(_is_protected_target(path) for path in targets): + try: + protected_entry = any(_is_protected_entry_target(path) for path in entry_targets) + except (OSError, RuntimeError, ValueError): + _deny( + "unresolved-write-target", + "Link entry destination could not be resolved safely. " + "Check its path components and symlinks.", + ) + if any(_is_protected_target(path) for path in targets) or protected_entry: _deny( "protected-installation-target", f"Writing a {INSTALLATION_INTEGRITY_DENY_TRIGGER} is prohibited.", diff --git a/src/autoskillit/hooks/guards/write_guard.py b/src/autoskillit/hooks/guards/write_guard.py index b715694328..87b929b131 100644 --- a/src/autoskillit/hooks/guards/write_guard.py +++ b/src/autoskillit/hooks/guards/write_guard.py @@ -36,6 +36,7 @@ from _guard_decision_diagnostics import ( # noqa: E402 record_guard_decision, ) +from _path_identity import destination_within # noqa: E402 if TYPE_CHECKING: from .._runtime._hook_output import deny_tool_use @@ -131,9 +132,12 @@ def _bash_validation_error( f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER} " "(unresolved write target). " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - if not scan.targets: + if not scan.targets and not scan.entry_targets: return None - return _paths_validation_error(list(scan.targets), norm_prefixes, display_prefix) + content_error = _paths_validation_error(list(scan.targets), norm_prefixes, display_prefix) + if content_error is not None: + return content_error + return _entry_paths_validation_error(list(scan.entry_targets), norm_prefixes, display_prefix) def _record(data: object, *, activation: str, scope: str, decision: str, reason: str) -> None: @@ -310,16 +314,36 @@ def _write_prefix_policy(data: dict[str, object], headless: bool) -> _WritePolic return _WritePolicy("active", tuple(norm_prefixes), ", ".join(raw_prefixes), "") +def _write_boundary_message(display_prefix: str) -> str: + return ( + f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " + f"Only writes to {display_prefix} are permitted." + ) + + def _paths_validation_error( paths: list[str], norm_prefixes: list[str], display_prefix: str ) -> str | None: for path in paths: resolved = os.path.realpath(path) if not any(resolved.startswith(np) or resolved == np.rstrip("/") for np in norm_prefixes): + return _write_boundary_message(display_prefix) + return None + + +def _entry_paths_validation_error( + paths: list[str], norm_prefixes: list[str], display_prefix: str +) -> str | None: + for path in paths: + try: + allowed = any(destination_within(path, prefix) for prefix in norm_prefixes) + except (OSError, RuntimeError, ValueError): return ( - f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER}. " - f"Only writes to {display_prefix} are permitted." + f"Write/Edit/apply_patch blocked: {WRITE_GUARD_DENY_TRIGGER} " + f"(unresolved write target {path!r}). Check its path components and symlinks." ) + if not allowed: + return _write_boundary_message(display_prefix) return None diff --git a/src/autoskillit/server/lifecycle/_guards.py b/src/autoskillit/server/lifecycle/_guards.py index 068a1ca7ee..7017ba3000 100644 --- a/src/autoskillit/server/lifecycle/_guards.py +++ b/src/autoskillit/server/lifecycle/_guards.py @@ -27,6 +27,7 @@ PROTECTED_SOURCE_PATH_PATTERNS, UNRESOLVED_WRITE_TARGET_REMEDIATION, command_has_blocked_protected_path_read, + destination_within, scan_write_targets, ) from autoskillit.pipeline import gate_error_result @@ -155,12 +156,25 @@ def _check_write_target_boundary( "run_cmd write target could not be resolved safely. " + UNRESOLVED_WRITE_TARGET_REMEDIATION ) - if not scan.targets: + if not scan.targets and not scan.entry_targets: return None normalized = tuple(os.path.realpath(p).rstrip("/") + "/" for p in allowed_prefixes) for target in scan.targets: resolved = os.path.realpath(target) - if not any(resolved.startswith(pfx) for pfx in normalized): + if not any(resolved.startswith(pfx) or resolved == pfx.rstrip("/") for pfx in normalized): + return gate_error_result( + f"run_cmd write target {target!r} is outside allowed write prefixes: " + f"{', '.join(allowed_prefixes)}" + ) + for target in scan.entry_targets: + try: + allowed = any(destination_within(target, prefix) for prefix in allowed_prefixes) + except (OSError, RuntimeError, ValueError): + return gate_error_result( + "run_cmd write target could not be resolved safely. " + + UNRESOLVED_WRITE_TARGET_REMEDIATION + ) + if not allowed: return gate_error_result( f"run_cmd write target {target!r} is outside allowed write prefixes: " f"{', '.join(allowed_prefixes)}" diff --git a/src/autoskillit/workspace/_installed/_projection_assets.py b/src/autoskillit/workspace/_installed/_projection_assets.py index ba971b1887..58b93cdb4c 100644 --- a/src/autoskillit/workspace/_installed/_projection_assets.py +++ b/src/autoskillit/workspace/_installed/_projection_assets.py @@ -20,6 +20,7 @@ { ".claude-plugin", ".mcp.json", + "_destination_paths.py", "_measure_aggregation.py", "_parent_assistant_turns.py", "_recipe_delivery_framing.py", diff --git a/tests/_test_filter.py b/tests/_test_filter.py index e14485a094..dbf9f847e1 100644 --- a/tests/_test_filter.py +++ b/tests/_test_filter.py @@ -1129,6 +1129,20 @@ class SourceMapRejection(enum.StrEnum): # --------------------------------------------------------------------------- LAYER_CASCADE_CONSERVATIVE: dict[str, frozenset[str]] = { + "_destination_paths": frozenset( + { + "arch", + "cli", + "contracts", + "core", + "execution", + "hooks", + "infra", + "server", + "skills", + "workspace", + } + ), "quota_constraints": frozenset({"core", "execution", "hooks", "server"}), # L0 — imported by everything "core": frozenset( @@ -1743,6 +1757,20 @@ class SourceMapRejection(enum.StrEnum): } LAYER_CASCADE_AGGRESSIVE: dict[str, frozenset[str]] = { + "_destination_paths": frozenset( + { + "arch", + "cli", + "contracts", + "core", + "execution", + "hooks", + "infra", + "server", + "skills", + "workspace", + } + ), "quota_constraints": frozenset({"core", "execution", "hooks", "server"}), "core": frozenset({"core"}), "config": frozenset({"config"}), diff --git a/tests/arch/test_hook_path_identity_guard.py b/tests/arch/test_hook_path_identity_guard.py index e73e079f6c..df6c6bf941 100644 --- a/tests/arch/test_hook_path_identity_guard.py +++ b/tests/arch/test_hook_path_identity_guard.py @@ -31,8 +31,9 @@ _ALLOWLISTED_SITES: dict[SiteKey, str] = { ("guards/git_ops_guard.py", "_relative_to"): ( - "target, common and worktree_git are each .resolve()d by _raw_target_mutations " - "before _classify_raw_write_target receives them, so both operands are canonical." + "_raw_target_mutations canonicalizes content targets with .resolve(), entry " + "targets with destination_location (resolved parent plus literal basename), " + "and common/worktree_git roots with .resolve() before classification." ), ("formatters/_fmt_response_spill.py", "_response_spill_artifact_is_trusted"): ( "resolved comes from artifact.resolve(strict=True) inline and project_temp from " diff --git a/tests/arch/test_write_target_single_authority.py b/tests/arch/test_write_target_single_authority.py index 9e5162a695..3c3dd2ef91 100644 --- a/tests/arch/test_write_target_single_authority.py +++ b/tests/arch/test_write_target_single_authority.py @@ -17,12 +17,12 @@ def test_write_target_consumers_share_hooks_scanner() -> None: import autoskillit.core as core import autoskillit.core.git as core_git - import autoskillit.execution.headless._headless_recovery as recovery + import autoskillit.execution.headless._headless_evidence as evidence import autoskillit.hooks as hooks import autoskillit.server.lifecycle._guards as guards assert guards.scan_write_targets is hooks.scan_write_targets - assert recovery.scan_write_targets is hooks.scan_write_targets + assert evidence.scan_write_targets is hooks.scan_write_targets assert not hasattr(core, "extract_bash_write_targets") assert not hasattr(core_git, "extract_bash_write_targets") diff --git a/tests/contracts/test_package_gateways.py b/tests/contracts/test_package_gateways.py index d201b9e6b7..e57c90b149 100644 --- a/tests/contracts/test_package_gateways.py +++ b/tests/contracts/test_package_gateways.py @@ -408,6 +408,7 @@ def test_root_module_allowlist() -> None: { "__init__.py", "__main__.py", + "_destination_paths.py", "_llm_triage.py", "_measure_aggregation.py", "_parent_assistant_turns.py", diff --git a/tests/contracts/test_skill_write_target_conformance.py b/tests/contracts/test_skill_write_target_conformance.py index 26d87de979..d0bdcceae9 100644 --- a/tests/contracts/test_skill_write_target_conformance.py +++ b/tests/contracts/test_skill_write_target_conformance.py @@ -124,7 +124,7 @@ def _assert_allowed(command: str, tool: str, checkout: Path, monkeypatch: pytest denials = _guard_denials(event, monkeypatch) scan = scan_write_targets(command, str(checkout)) assert not denials, ( - f"targets={scan.targets}; {'; '.join(denials)}; " + f"targets={scan.targets}; entry_targets={scan.entry_targets}; {'; '.join(denials)}; " "see skills_extended/AGENTS.md § Literal write targets" ) diff --git a/tests/core/test_resolve_temp_dir.py b/tests/core/test_resolve_temp_dir.py index 0d252bb94b..67799cf3d5 100644 --- a/tests/core/test_resolve_temp_dir.py +++ b/tests/core/test_resolve_temp_dir.py @@ -31,7 +31,7 @@ def test_resolve_temp_dir_empty_string_raises_value_error() -> None: def test_resolve_temp_dir_no_autoskillit_imports() -> None: - """core.io may import core and the stdlib-only measure authority, not higher layers. + """core.io may import core and its stdlib-only root authorities, not higher layers. Runs in an isolated subprocess so the destructive ``sys.modules`` clear cannot leak into other xdist tests sharing the same worker process. @@ -51,7 +51,7 @@ def test_resolve_temp_dir_no_autoskillit_imports() -> None: for m in sys.modules if m.startswith("autoskillit.") and not m.startswith("autoskillit.core") - and m != "autoskillit._measure_aggregation" + and m not in {"autoskillit._measure_aggregation", "autoskillit._destination_paths"} ] if leaked: print("LEAKED:" + ",".join(sorted(leaked))) diff --git a/tests/execution/headless/test_headless_scan.py b/tests/execution/headless/test_headless_scan.py index 33861e9d6b..64c03d6b18 100644 --- a/tests/execution/headless/test_headless_scan.py +++ b/tests/execution/headless/test_headless_scan.py @@ -11,6 +11,29 @@ pytestmark = [pytest.mark.layer("execution"), pytest.mark.small] +@pytest.mark.parametrize("symlinked_parent", [False, True]) +def test_entry_advisory_resolves_parent_but_not_final_symlink(tmp_path, symlinked_parent): + cwd = tmp_path / "cwd" + cwd.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + if symlinked_parent: + (cwd / "parent").symlink_to(outside, target_is_directory=True) + destination = cwd / "parent" / "entry" + else: + destination = cwd / "entry" + destination.symlink_to(outside / "target") + line = _make_tool_use_line("Bash", {"command": f"ln -sT source {destination}"}) + + warnings = _scan_jsonl_write_paths(line, str(cwd)) + + if symlinked_parent: + assert len(warnings) == 1 + assert str(outside / "entry") in warnings[0] + else: + assert warnings == [] + + class TestScanJsonlCustomToolNames: CWD = "/clone/worktree" @@ -74,11 +97,22 @@ class TestScanJsonlWriteWarnings: "Bash command contained write target '/outside/y' outside session cwd '{cwd}'", id="outside-cwd-target", ), + pytest.param( + "ln -sf /opt/tools/jq /outside/jq", + "Bash command contained write target '/outside/jq' outside session cwd '{cwd}'", + id="outside-cwd-link-entry", + ), + pytest.param( + 'ln -sf /opt/tools/jq "$LINK_NAME"', + GENERIC_UNRESOLVED_WARNING, + id="unresolved-link-entry", + ), pytest.param("printf '> q' > inside.txt", None, id="quoted-redirect-operator"), ], ) def test_bash_jsonl_write_warnings(self, tmp_path, monkeypatch, command, expected_warning): monkeypatch.delenv("F", raising=False) + monkeypatch.delenv("LINK_NAME", raising=False) cwd = str(tmp_path) line = _make_tool_use_line("Bash", {"command": command}) diff --git a/tests/hooks/_interactive_guard_harness.py b/tests/hooks/_interactive_guard_harness.py index c53a139e7c..431c99257b 100644 --- a/tests/hooks/_interactive_guard_harness.py +++ b/tests/hooks/_interactive_guard_harness.py @@ -83,6 +83,7 @@ def make_runtime(tmp_path: Path, entries: Mapping[str, Mapping[str, object]]) -> (project / ".autoskillit" / "temp").mkdir(parents=True) plugin = tmp_path / "plugin" shutil.copytree(HOOKS_DIR, plugin / "hooks") + shutil.copy2(HOOKS_DIR.parent / "_destination_paths.py", plugin) manifest_path = tmp_path / ".plugin.autoskillit-projection.json" manifest_path.write_text( json.dumps( diff --git a/tests/hooks/test_command_classification.py b/tests/hooks/test_command_classification.py index f39e0724d6..143886b5fb 100644 --- a/tests/hooks/test_command_classification.py +++ b/tests/hooks/test_command_classification.py @@ -1543,6 +1543,21 @@ def test_chained_write_bytes_on_open_not_double_counted(self): class TestScanWriteTargets: + @pytest.mark.parametrize( + ("parseable", "has_write"), + [(False, True), (True, False)], + ids=("unparseable", "not-a-write"), + ) + def test_entry_targets_obey_scan_invariants(self, parseable: bool, has_write: bool) -> None: + with pytest.raises(ValueError, match="targets and entry_targets"): + command_classification.WriteTargetScan( + targets=(), + unresolved=False, + parseable=parseable, + has_write=has_write, + entry_targets=("/tmp/link",), + ) + @pytest.mark.parametrize( ("command", "targets", "unresolved", "parseable", "has_write"), [ diff --git a/tests/hooks/test_hook_scope_authority.py b/tests/hooks/test_hook_scope_authority.py index c1f85ac92e..6173d26647 100644 --- a/tests/hooks/test_hook_scope_authority.py +++ b/tests/hooks/test_hook_scope_authority.py @@ -61,6 +61,7 @@ def _run_copied_guard( else: copied_hooks = tmp_path / "hooks" shutil.copytree(HOOKS_DIR, copied_hooks, ignore=ignore) + shutil.copy2(HOOKS_DIR.parent / "_destination_paths.py", copied_hooks.parent) table_path = copied_hooks / "_runtime" / "_hook_scope_table.py" if table_content is None: table_path.unlink() diff --git a/tests/hooks/test_installation_integrity_guard.py b/tests/hooks/test_installation_integrity_guard.py index 3808671b07..8e3370acde 100644 --- a/tests/hooks/test_installation_integrity_guard.py +++ b/tests/hooks/test_installation_integrity_guard.py @@ -2,11 +2,14 @@ from __future__ import annotations +import errno +import io import json import os import subprocess import sys from pathlib import Path +from types import SimpleNamespace import pytest @@ -290,6 +293,52 @@ def test_blocks_interpreter_write_into_install_tree(tmp_path: Path) -> None: assert _decision(stdout) == "deny" +@pytest.mark.parametrize( + "error", [errno.ENOENT, errno.ENOTDIR, errno.EACCES, errno.ELOOP, errno.EIO] +) +def test_entry_stat_errors_only_allow_absent_entries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error: int +) -> None: + from autoskillit.hooks.guards import installation_integrity_guard as guard + + target = tmp_path / "entry" + original_lstat = os.lstat + + def lstat(path, *args, **kwargs): + if os.fspath(path) == str(target): + raise OSError(error, "injected stat failure") + return original_lstat(path, *args, **kwargs) + + monkeypatch.setattr(guard, "_known_roots", lambda: ()) + monkeypatch.setattr(guard, "os", SimpleNamespace(**(vars(os) | {"lstat": lstat}))) + + assert guard._is_protected_entry_target(str(target)) is ( + error not in {errno.ENOENT, errno.ENOTDIR} + ) + + +@pytest.mark.parametrize("failure_site", ["destination_location", "destination_within"]) +def test_entry_resolution_failure_has_unresolved_reason( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys, failure_site: str +) -> None: + from autoskillit.hooks.guards import installation_integrity_guard as guard + + def fail_resolution(*args): + raise RuntimeError("injected resolution failure") + + event = _bash(f"ln -s source {tmp_path / 'entry'}") + event["cwd"] = str(tmp_path) + monkeypatch.setattr(guard, "_known_roots", lambda: (tmp_path / "protected",)) + monkeypatch.setattr(guard, failure_site, fail_resolution) + monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(event))) + with pytest.raises(SystemExit) as result: + guard.main() + assert result.value.code == 0 + output = json.loads(capsys.readouterr().out)["hookSpecificOutput"] + assert output["permissionDecision"] == "deny" + assert "code=unresolved-write-target" in output["permissionDecisionReason"] + + def test_blocks_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: home = tmp_path / "home" original = home / ".local/share/uv/tools/autoskillit/lib/site-packages/autoskillit/core.py" @@ -308,6 +357,97 @@ def test_blocks_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: assert _decision(stdout) == "deny" +def test_blocks_ln_replacement_of_hardlink_alias_of_uv_tool_file(tmp_path: Path) -> None: + home = tmp_path / "home" + original = home / ".local/share/uv/tools/autoskillit/lib/site-packages/autoskillit/core.py" + original.parent.mkdir(parents=True) + original.write_text("source", encoding="utf-8") + alias = tmp_path / "ordinary-project" / "linked.py" + alias.parent.mkdir() + os.link(original, alias) + + code, stdout = _run( + _bash(f"ln -f {tmp_path / 'replacement.py'} {alias}"), + env={"HOME": str(home)}, + ) + + assert code == 0 + assert _decision(stdout) == "deny" + + +@pytest.mark.parametrize( + "command_template", + [ + "npm install --prefix {target} package", + "ln -sf /tmp/source {target}", + ], + ids=["npm-prefix", "ln-entry"], +) +def test_blocks_explicit_install_tree_destinations(tmp_path: Path, command_template: str) -> None: + target = tmp_path / "lib/python3.13/site-packages/autoskillit/destination" + + code, stdout = _run(_bash(command_template.format(target=target))) + + assert code == 0 + assert _decision(stdout) == "deny" + assert ( + "code=protected-installation-target" + in json.loads(stdout)["hookSpecificOutput"]["permissionDecisionReason"] + ) + + +@pytest.mark.parametrize( + "command", + [ + 'npm install --prefix "$DESTINATION" package', + 'ln -sf /tmp/source "$DESTINATION"', + ], + ids=["npm-prefix", "ln-entry"], +) +def test_blocks_unresolved_explicit_destinations( + command: str, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("DESTINATION", raising=False) + code, stdout = _run(_bash(command)) + + assert code == 0 + assert _decision(stdout) == "deny" + assert ( + "code=unresolved-write-target" + in json.loads(stdout)["hookSpecificOutput"]["permissionDecisionReason"] + ) + + +def test_ln_entry_location_does_not_follow_outside_symlink_into_install_tree( + tmp_path: Path, +) -> None: + protected = tmp_path / "lib/python3.13/site-packages/autoskillit/core.py" + protected.parent.mkdir(parents=True) + protected.write_text("protected", encoding="utf-8") + outside_link = tmp_path / "ordinary-project/core.py" + outside_link.parent.mkdir() + outside_link.symlink_to(protected) + + code, stdout = _run(_bash(f"ln -sf {tmp_path / 'replacement.py'} {outside_link}")) + + assert code == 0 + assert stdout == "" + + +def test_ln_entry_location_protects_symlink_inside_install_tree(tmp_path: Path) -> None: + protected_link = tmp_path / "lib/python3.13/site-packages/autoskillit/core.py" + protected_link.parent.mkdir(parents=True) + outside = tmp_path / "ordinary-project/core.py" + outside.parent.mkdir() + outside.write_text("outside", encoding="utf-8") + protected_link.symlink_to(outside) + + code, stdout = _run(_bash(f"ln -sf {tmp_path / 'replacement.py'} {protected_link}")) + + assert code == 0 + assert _decision(stdout) == "deny" + + def test_blocks_shell_local_variable_target(tmp_path: Path) -> None: target = tmp_path / "lib/python3.13/site-packages/autoskillit/__init__.py" code, stdout = _run(_bash(f"FOO={target.parent}; cat > $FOO/__init__.py <<'EOF'\nEOF")) diff --git a/tests/hooks/test_path_identity.py b/tests/hooks/test_path_identity.py index 1495f44f2f..33c30221b8 100644 --- a/tests/hooks/test_path_identity.py +++ b/tests/hooks/test_path_identity.py @@ -6,8 +6,11 @@ import pytest +from autoskillit.core import destination_location as core_destination_location from autoskillit.hooks._runtime._path_identity import ( PathIdentityError, + destination_location, + destination_within, hooks_relative_key, realpath_within, ) @@ -73,3 +76,50 @@ def test_realpath_within_matches_commonpath_containment(tmp_path: Path) -> None: ) for candidate, container, expected in cases: assert realpath_within(candidate, container) is expected, candidate + + +def test_destination_location_resolves_parent_but_not_final_component(tmp_path: Path) -> None: + real_parent = tmp_path / "real-parent" + real_parent.mkdir() + linked_parent = tmp_path / "linked-parent" + linked_parent.symlink_to(real_parent, target_is_directory=True) + + assert destination_location(linked_parent / "entry") == real_parent / "entry" + + +def test_destination_location_preserves_dangling_final_symlink(tmp_path: Path) -> None: + dangling = tmp_path / "dangling" + dangling.symlink_to(tmp_path / "missing") + + assert destination_location(dangling) == dangling + + +def test_destination_location_handles_root_destination() -> None: + assert destination_location(Path("/")) == Path("/") + + +@pytest.mark.parametrize("name", ["entry", "final-link", "..", "."]) +def test_destination_location_core_and_hook_conformance(tmp_path: Path, name: str) -> None: + real_parent = tmp_path / "real" + real_parent.mkdir() + linked_parent = tmp_path / "linked" + linked_parent.symlink_to(real_parent, target_is_directory=True) + (real_parent / "final-link").symlink_to(tmp_path / "missing") + destination = linked_parent / name + expected = tmp_path if name == ".." else linked_parent if name == "." else real_parent / name + + for resolve_location in (destination_location, core_destination_location): + assert resolve_location(destination) == expected + + +def test_destination_within_uses_physical_parent_and_preserves_final_link(tmp_path: Path) -> None: + allowed = tmp_path / "allowed" + allowed.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + (allowed / "parent").symlink_to(outside, target_is_directory=True) + (allowed / "link").symlink_to(outside / "target") + assert destination_within(allowed / "link", allowed) + assert not destination_within(allowed / "parent" / "entry", allowed) + assert not destination_within(allowed / "..", allowed) + assert not destination_within(tmp_path / "allowed-neighbor" / "entry", allowed) diff --git a/tests/hooks/test_write_guard.py b/tests/hooks/test_write_guard.py index a8872f46e5..6c717efcca 100644 --- a/tests/hooks/test_write_guard.py +++ b/tests/hooks/test_write_guard.py @@ -590,6 +590,255 @@ def test_bash_no_prefix_allows_all(self, monkeypatch: pytest.MonkeyPatch, tmp_pa _assert_installation_floor_denies(tmp_path) +def _assert_bash_scope_decision( + monkeypatch: pytest.MonkeyPatch, + *, + command: str, + cwd, + allowed, + permitted: bool, + unresolved: bool = False, +) -> None: + monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") + monkeypatch.setenv("AUTOSKILLIT_AGENT_BACKEND", "claude-code") + monkeypatch.setenv("AUTOSKILLIT_ALLOWED_WRITE_PREFIX", str(allowed)) + monkeypatch.setenv("AUTOSKILLIT_CWD", str(cwd)) + + result = _run_hook(_build_bash_event(command)) + + if permitted: + assert result == "" + return + output = json.loads(result)["hookSpecificOutput"] + assert output["permissionDecision"] == "deny" + if unresolved: + assert UNRESOLVED_WRITE_TARGET_REMEDIATION in output["permissionDecisionReason"] + else: + reason = output["permissionDecisionReason"] + assert write_guard.WRITE_GUARD_DENY_TRIGGER in reason + assert f"Only writes to {allowed} are permitted." in reason + + +@pytest.mark.parametrize( + ("command_template", "destination", "permitted", "unresolved"), + [ + pytest.param( + "npm install --prefix {destination} node-jq", + "allowed", + True, + False, + id="npm-allowed-prefix", + ), + pytest.param( + "npm --prefix={destination} install node-jq", + "outside", + False, + False, + id="npm-outside-prefix", + ), + pytest.param( + 'npm install --prefix "$NPM_PREFIX" node-jq', + "unresolved", + False, + True, + id="npm-unresolved-prefix", + ), + pytest.param( + "ln -sf /opt/tools/jq {destination}/jq", + "allowed", + True, + False, + id="ln-external-source-allowed-entry", + ), + pytest.param( + "ln -sf /opt/tools/jq {destination}/jq", + "outside", + False, + False, + id="ln-outside-entry", + ), + pytest.param( + 'ln -sf /opt/tools/jq "$LINK_NAME"', + "unresolved", + False, + True, + id="ln-unresolved-entry", + ), + ], +) +def test_npm_and_ln_destinations_reach_bash_scope_policy( + monkeypatch: pytest.MonkeyPatch, + tmp_path, + command_template: str, + destination: str, + permitted: bool, + unresolved: bool, +) -> None: + monkeypatch.delenv("NPM_PREFIX", raising=False) + monkeypatch.delenv("LINK_NAME", raising=False) + allowed = tmp_path / "project" / ".autoskillit" / "temp" / "review-pr" + outside = tmp_path / "outside" + allowed.mkdir(parents=True) + outside.mkdir() + selected = allowed if destination == "allowed" else outside + command = command_template.format(destination=selected) + + _assert_bash_scope_decision( + monkeypatch, + command=command, + cwd=tmp_path / "project", + allowed=allowed, + permitted=permitted, + unresolved=unresolved, + ) + + +@pytest.mark.parametrize( + "command", + [ + "cd /tmp && npm install --prefix /tmp/jqinst node-jq 2>&1 | tail -10; " + "ls /tmp/jqinst/node_modules/node-jq/bin 2>/dev/null", + "ln -sf /tmp/jqinst/node_modules/node-jq/bin/jq /usr/local/bin/jq 2>&1; jq --version 2>&1", + ], + ids=["observed-npm-install", "observed-ln-install"], +) +def test_incident_commands_are_denied_by_project_temp_scope( + monkeypatch: pytest.MonkeyPatch, tmp_path, command: str +) -> None: + project = tmp_path / "project" + allowed = project / ".autoskillit" / "temp" / "review-pr" + allowed.mkdir(parents=True) + + _assert_bash_scope_decision( + monkeypatch, + command=command, + cwd=project, + allowed=allowed, + permitted=False, + ) + + +def test_ln_entry_location_does_not_follow_final_symlink( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + inside_file = allowed / "inside" + outside_file = outside / "outside" + inside_file.write_text("inside", encoding="utf-8") + outside_file.write_text("outside", encoding="utf-8") + outside_link = outside / "link" + inside_link = allowed / "link" + outside_link.symlink_to(inside_file) + inside_link.symlink_to(outside_file) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {outside_link}", + cwd=tmp_path, + allowed=allowed, + permitted=False, + ) + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {inside_link}", + cwd=tmp_path, + allowed=allowed, + permitted=True, + ) + + result = _run_hook(_build_event("Write", str(inside_link))) + assert json.loads(result)["hookSpecificOutput"]["permissionDecision"] == "deny" + + +@pytest.mark.parametrize("entry_flag", ["-sfT", "-sfn"]) +def test_ln_no_directory_dereference_replaces_allowed_symlink_entry( + monkeypatch: pytest.MonkeyPatch, tmp_path, entry_flag: str +) -> None: + allowed = tmp_path / "allowed" + outside_dir = tmp_path / "outside-dir" + allowed.mkdir() + outside_dir.mkdir() + directory_link = allowed / "directory-link" + directory_link.symlink_to(outside_dir, target_is_directory=True) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln {entry_flag} /opt/tools/jq {directory_link}", + cwd=tmp_path, + allowed=allowed, + permitted=True, + ) + + +def test_ln_ordinary_directory_semantics_follow_final_directory_symlink( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + allowed = tmp_path / "allowed" + outside_dir = tmp_path / "outside-dir" + allowed.mkdir() + outside_dir.mkdir() + directory_link = allowed / "directory-link" + directory_link.symlink_to(outside_dir, target_is_directory=True) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -s /opt/tools/jq {directory_link}", + cwd=tmp_path, + allowed=allowed, + permitted=False, + ) + + +def test_ln_directory_child_entry_does_not_follow_existing_child_symlink( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + (allowed / "jq").symlink_to(outside / "referent") + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {allowed}", + cwd=tmp_path, + allowed=allowed, + permitted=True, + ) + + +def test_ln_entry_resolves_symlinked_parent(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None: + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + (allowed / "escaped-parent").symlink_to(outside, target_is_directory=True) + + _assert_bash_scope_decision( + monkeypatch, + command=f"ln -sf /opt/tools/jq {allowed / 'escaped-parent' / 'jq'}", + cwd=tmp_path, + allowed=allowed, + permitted=False, + ) + + +def test_entry_resolution_failure_reports_unresolved_target(monkeypatch, tmp_path) -> None: + def fail_resolution(*args): + raise RuntimeError("injected resolution failure") + + monkeypatch.setattr(write_guard, "destination_within", fail_resolution) + reason = write_guard._bash_validation_error( + f"ln -s source {tmp_path / 'entry'}", str(tmp_path), [str(tmp_path)], str(tmp_path) + ) + assert reason is not None + assert "unresolved write target" in reason + assert "path components and symlinks" in reason + + @pytest.mark.parametrize("command", ['echo x > "$F"', 'cp a "$F"']) def test_denies_unresolved_bash_write_target( monkeypatch: pytest.MonkeyPatch, tmp_path, command: str diff --git a/tests/hooks/test_write_target_scan.py b/tests/hooks/test_write_target_scan.py index 7f67463ac4..4113da5204 100644 --- a/tests/hooks/test_write_target_scan.py +++ b/tests/hooks/test_write_target_scan.py @@ -2,6 +2,8 @@ from __future__ import annotations +from pathlib import Path + import pytest from autoskillit.hooks import scan_write_targets @@ -16,8 +18,10 @@ ("/autoskillit:test-skill-flat", _WORKSPACE, (), False), ("gh api /repos/owner/repo", _WORKSPACE, (), False), ("cp source.txt /path/dest.txt", _WORKSPACE, ("/path/dest.txt",), False), + ("/bin/cp /outside/source /workspace/dest", _WORKSPACE, ("/workspace/dest",), False), ("install -m 644 a /workspace/dest", _WORKSPACE, ("/workspace/dest",), False), ("sed -i 's/a/b/' /path/file.txt", _WORKSPACE, ("/path/file.txt",), False), + ("/usr/bin/sed -i 's/a/b/' /path/file.txt", _WORKSPACE, ("/path/file.txt",), False), ("mv /old/file /new/file", _WORKSPACE, ("/new/file",), False), ("cat /a | grep foo > /b", _WORKSPACE, ("/b",), False), ("cmd 2>/dev/null", _WORKSPACE, (), False), @@ -140,3 +144,331 @@ def test_scan_write_target_expectations( assert result.targets == expected_targets, f"targets for {command!r}" assert result.unresolved is expected_unresolved, f"unresolved status for {command!r}" + + +@pytest.mark.parametrize( + ("command", "targets", "unresolved", "has_write"), + [ + ("npm install --prefix /opt/app pkg", ("/opt/app",), False, True), + ("npm install --prefix=/opt/app pkg", ("/opt/app",), False, True), + ("npm --prefix /opt/app install pkg", ("/opt/app",), False, True), + ("npm install --prefix 'relative app' pkg", ("/workspace/relative app",), False, True), + ('npm install --prefix="$NPM_PREFIX" pkg', ("/resolved/npm",), False, True), + ("npm install --prefix='$NPM_UNKNOWN' pkg", ("/workspace/$NPM_UNKNOWN",), False, True), + ('npm install --prefix="$NPM_UNKNOWN" pkg', (), True, True), + ("npm install --prefix", (), True, True), + ("npm install -- --prefix /opt/app", (), True, True), + ("npm ci --prefix /opt/app", ("/opt/app",), False, True), + ("npm --prefix /opt/app i pkg", ("/opt/app",), False, True), + ("npm add pkg --prefix=/opt/app", ("/opt/app",), False, True), + ("npm --registry https://example install --prefix /opt/app pkg", (), True, True), + ("npm --prefix /opt/app unsupported", (), True, True), + ("npm install pkg", (), True, True), + ("npm run build", (), True, True), + ("npm --registry https://example run build", (), True, True), + ("npm", (), False, False), + ("npm --version", (), False, False), + ("npm help install", (), False, False), + ("npm ls", (), False, False), + ("npm config get prefix", (), False, False), + ("npm config set prefix /outside", (), True, True), + ], + ids=( + "detached-after-install", + "equals-after-install", + "detached-before-install", + "quoted-relative", + "attached-known-variable", + "attached-single-quoted-variable", + "attached-unknown-variable", + "missing-prefix-value", + "option-terminator", + "clean-install-prefix", + "install-alias-prefix", + "add-alias-prefix", + "uncertain-global-option-value", + "unsupported-prefixed-command", + "unprefixed-install", + "unprefixed-script", + "unmodelled-leading-options", + "usage", + "version", + "help-for-write-command", + "package-list", + "config-read", + "config-write", + ), +) +def test_npm_write_target_policy( + command: str, + targets: tuple[str, ...], + unresolved: bool, + has_write: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("NPM_PREFIX", "/resolved/npm") + monkeypatch.delenv("NPM_UNKNOWN", raising=False) + + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == () + assert result.unresolved is unresolved + assert result.has_write is has_write + + +@pytest.mark.parametrize( + ("command", "targets", "entry_targets"), + [ + ("/usr/bin/npm install --prefix /opt/app pkg", ("/opt/app",), ()), + ("/usr/bin/install source /opt/app", ("/opt/app",), ()), + ("/bin/ln -s source /opt/link", (), ("/opt/link",)), + ], +) +def test_path_qualified_destination_verbs( + command: str, targets: tuple[str, ...], entry_targets: tuple[str, ...] +) -> None: + result = scan_write_targets(command, _WORKSPACE) + assert result.targets == targets + assert result.entry_targets == entry_targets + assert result.has_write and not result.unresolved + + +@pytest.mark.parametrize( + ("command", "entry_targets"), + [ + ("ln source link", ("/workspace/link",)), + ("ln -s source link", ("/workspace/link",)), + ("ln -f source link", ("/workspace/link",)), + ("ln -sf source link", ("/workspace/link",)), + ("ln source", ("/workspace/source",)), + ("ln -t /links path/to/source", ("/links/source",)), + ("ln --target-directory /links source", ("/links/source",)), + ("ln --target-directory=/links source", ("/links/source",)), + ("ln -t/links source", ("/links/source",)), + ("ln -t /links one/a two/b", ("/links/a", "/links/b")), + ], +) +def test_ln_literal_entry_destinations(command: str, entry_targets: tuple[str, ...]) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == () + assert result.entry_targets == entry_targets + assert result.unresolved is False + assert result.has_write is True + + +@pytest.mark.parametrize( + "option", + [ + "-b", + "-di", + "--backup", + "--backup=numbered", + "--interactive", + "--logical", + "--physical", + "--relative", + ], +) +def test_ln_options_preserve_entry_destination(option: str) -> None: + result = scan_write_targets(f"ln {option} source link", _WORKSPACE) + assert result.entry_targets == ("/workspace/link",) + assert not result.unresolved + + +@pytest.mark.parametrize("command", ["ln --help", "install --version"]) +def test_coreutils_informational_options_do_not_write(command: str) -> None: + result = scan_write_targets(command, _WORKSPACE) + assert not result.has_write + assert not result.unresolved + + +@pytest.mark.parametrize("command", ["ln -t --help source", "ln -- --help source"]) +def test_help_spelling_as_an_operand_still_writes(command: str) -> None: + result = scan_write_targets(command, _WORKSPACE) + assert result.has_write + assert result.entry_targets + assert not result.unresolved + + +@pytest.mark.parametrize("option", ["--backup", "--backup=numbered"]) +def test_install_backup_option_preserves_destination(option: str) -> None: + result = scan_write_targets(f"install {option} source destination", _WORKSPACE) + assert result.targets == ("/workspace/destination",) + assert not result.unresolved + + +def test_ln_directory_and_final_symlink_semantics( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + directory = tmp_path / "directory" + directory.mkdir() + directory_link = tmp_path / "directory-link" + directory_link.symlink_to(directory, target_is_directory=True) + monkeypatch.delenv("LN_SOURCE", raising=False) + cases = ( + (f"ln source {directory}", (str(directory / "source"),), False), + (f"ln source {directory_link}", (str(directory_link / "source"),), False), + (f'ln -T "$LN_SOURCE" {directory_link}', (str(directory_link),), False), + (f'ln -n "$LN_SOURCE" {directory_link}', (str(directory_link),), False), + (f"ln -n source {directory}", (str(directory / "source"),), False), + (f'ln "$LN_SOURCE" {directory}', (), True), + ) + + for command, entries, unresolved in cases: + result = scan_write_targets(command, str(tmp_path)) + assert result.entry_targets == entries, command + assert result.unresolved is unresolved, command + assert result.has_write is True, command + + +@pytest.mark.parametrize( + "command", + [ + "ln --unknown value source link", + "ln -t /links -T source", + "ln --target-directory /links --no-target-directory source", + "ln --target-directory /links", + "ln source --target-directory", + "install -t /dest -T source", + "install --target-directory /dest --no-target-directory source", + "install source --target-directory", + "install --target-directory /dest", + ], +) +def test_unsupported_or_incomplete_destination_grammar_is_unresolved(command: str) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == () + assert result.entry_targets == () + assert result.unresolved is True + assert result.has_write is True + + +@pytest.mark.parametrize( + ("command", "targets"), + [ + ("install -t /dest path/to/source", ("/dest/source",)), + ("install path/to/source -t /dest", ("/dest/source",)), + ("install -t/dest path/to/source", ("/dest/source",)), + ("install --target-directory=/dest path/to/source", ("/dest/source",)), + ("install --target-directory /dest one/a two/b", ("/dest/a", "/dest/b")), + ], +) +def test_install_target_directory_emits_child_content_destinations( + command: str, targets: tuple[str, ...] +) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == () + assert result.unresolved is False + assert result.has_write is True + + +@pytest.mark.parametrize( + ("command", "children"), + [ + ("install -d {dest}/one {dest}/two", ("one", "two")), + ("install -T source {dest}/entry", ("entry",)), + ("install source {dest}", ("source",)), + ], + ids=("create-directories", "no-target-directory", "existing-directory"), +) +def test_install_destination_modes( + tmp_path: Path, command: str, children: tuple[str, ...] +) -> None: + destination = tmp_path / "destination" + destination.mkdir() + result = scan_write_targets(command.format(dest=destination), _WORKSPACE) + assert result.targets == tuple(str(destination / child) for child in children) + assert result.entry_targets == () + assert result.has_write + assert not result.unresolved + + +@pytest.mark.parametrize( + ("command", "targets", "entry_targets"), + [ + ( + 'ln --target-directory="$TARGET_DIRECTORY" source', + (), + ("/resolved/target/source",), + ), + ( + "ln --target-directory='$UNKNOWN_DIRECTORY' source", + (), + ("/workspace/$UNKNOWN_DIRECTORY/source",), + ), + ( + 'install --target-directory="$TARGET_DIRECTORY" path/to/source', + ("/resolved/target/source",), + (), + ), + ], +) +def test_attached_target_directory_preserves_value_provenance( + command: str, + targets: tuple[str, ...], + entry_targets: tuple[str, ...], + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("TARGET_DIRECTORY", "/resolved/target") + monkeypatch.delenv("UNKNOWN_DIRECTORY", raising=False) + + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == entry_targets + assert result.unresolved is False + assert result.has_write is True + + +def test_install_derived_child_preserves_spelling_and_requires_source_basename( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + destination = tmp_path / "dest" + destination.mkdir() + child = destination / "source" + child.symlink_to(tmp_path / "outside") + monkeypatch.delenv("INSTALL_SOURCE", raising=False) + + literal = scan_write_targets(f"install -t {destination} path/to/source", str(tmp_path)) + unresolved = scan_write_targets(f'install -t {destination} "$INSTALL_SOURCE"', str(tmp_path)) + + assert literal.targets == (str(child),) + assert unresolved.targets == () + assert unresolved.unresolved is True + assert unresolved.has_write is True + + +@pytest.mark.parametrize( + ("command", "targets", "entry_targets"), + [ + ( + "cd /tmp && npm install --prefix /tmp/jqinst node-jq 2>&1 | tail -10; " + "ls /tmp/jqinst/node_modules/node-jq/bin 2>/dev/null", + ("/tmp/jqinst",), + (), + ), + ( + "ln -sf /tmp/jqinst/node_modules/node-jq/bin/jq /usr/local/bin/jq 2>&1; " + "jq --version 2>&1", + (), + ("/usr/local/bin/jq",), + ), + ("echo x > /tmp/same; ln source /tmp/same", ("/tmp/same",), ("/tmp/same",)), + ("echo x > /dev/null; ln -f source /dev/null", (), ("/dev/null",)), + ], + ids=("npm-incident", "ln-incident", "same-spelling-dual-role", "entry-pseudo-device"), +) +def test_content_and_entry_aggregation( + command: str, targets: tuple[str, ...], entry_targets: tuple[str, ...] +) -> None: + result = scan_write_targets(command, _WORKSPACE) + + assert result.targets == targets + assert result.entry_targets == entry_targets + assert result.unresolved is False + assert result.has_write is True diff --git a/tests/infra/test_git_ops_guard.py b/tests/infra/test_git_ops_guard.py index b90bc99f6e..3e16357a83 100644 --- a/tests/infra/test_git_ops_guard.py +++ b/tests/infra/test_git_ops_guard.py @@ -351,10 +351,13 @@ def test_allows_when_kitchen_closed(self, tmp_path): out = _run_guard("git commit --amend", kitchen_open=False, tmpdir=tmp_path) assert out.strip() == "" - def test_allows_unrelated_command(self, tmp_path): - out = _run_guard("npm run build", kitchen_open=True, tmpdir=tmp_path) + def test_npm_read_only_and_script_policy(self, tmp_path): + out = _run_guard("npm --version", kitchen_open=True, tmpdir=tmp_path) assert out.strip() == "" + out = _run_guard("npm run build", kitchen_open=True, tmpdir=tmp_path) + assert _checked_out_ref_result(out)["attempted_value"] == "" + # --------------------------------------------------------------------------- # Bash tool format @@ -536,6 +539,15 @@ def test_denies_raw_write_verb_via_heredoc_preflight( ) assert _is_denied(out) + def test_denies_piped_install_heredoc_without_execution_cwd(self, tmp_path) -> None: + out = _run_guard( + "cat <<'EOF' | bash\ninstall source destination\nEOF", + kitchen_open=True, + tmpdir=tmp_path, + include_execution_cwd=False, + ) + assert _checked_out_ref_result(out)["execution_cwd"] == "" + def test_allows_inert_backtick_heredoc_git_push(self, tmp_path) -> None: """cat-redirect-heredoc-inline-backtick: an inert `cat` body mentioning `git push --force` inside a single backtick pair must not deny.""" @@ -552,8 +564,16 @@ def test_allows_inert_backtick_heredoc_git_push(self, tmp_path) -> None: ) assert out.strip() == "" - @pytest.mark.parametrize("include_execution_cwd", [True, False]) - def test_allows_inert_herestring_git_push(self, tmp_path, include_execution_cwd: bool) -> None: + @pytest.mark.parametrize( + ("command", "include_execution_cwd"), + [ + ("cat > f.md <<< 'git push --force origin main'", True), + ("cat <<< 'git push --force origin main'", False), + ], + ) + def test_allows_inert_herestring_git_push( + self, tmp_path, command: str, include_execution_cwd: bool + ) -> None: """A `cat` herestring containing an inert git push must not deny.""" _git(tmp_path, "init", "-b", "develop") _git(tmp_path, "config", "user.name", "Guard Test") @@ -562,7 +582,7 @@ def test_allows_inert_herestring_git_push(self, tmp_path, include_execution_cwd: _git(tmp_path, "add", "f.txt") _git(tmp_path, "commit", "-m", "initial") out = _run_guard( - "cat > f.md <<< 'git push --force origin main'", + command, kitchen_open=True, tmpdir=tmp_path, include_execution_cwd=include_execution_cwd, @@ -933,6 +953,100 @@ def test_denies_static_raw_ref_writes( after = ref_path.read_bytes() if ref_path.exists() else None assert after == before + @pytest.mark.parametrize( + ("source_name", "destination_relative"), + [("HEAD", "."), ("develop", "refs/heads")], + ids=["head", "checked-out-branch"], + ) + def test_denies_ln_directory_entry_for_checked_out_ref( + self, + linked_repo: dict[str, Path | str], + tmp_path: Path, + source_name: str, + destination_relative: str, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + source = tmp_path / "sources" / source_name + source.parent.mkdir() + source.write_text("replacement", encoding="utf-8") + destination = Path(str(linked_repo["common_git_dir"])) / destination_relative + + out = _run_guard( + f"ln -sf {shlex.quote(str(source))} {shlex.quote(str(destination))}", + kitchen_open=True, + tmpdir=linked, + ) + + threatened = _checked_out_ref_result(out)["threatened_refs"] + assert isinstance(threatened, list) + expected_ref = "HEAD" if source_name == "HEAD" else f"refs/heads/{source_name}" + assert {row["target_ref"] for row in threatened} == {expected_ref} + + def test_denies_npm_prefix_targeting_checked_out_ref( + self, linked_repo: dict[str, Path | str] + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + target = Path(str(linked_repo["common_git_dir"])) / "refs/heads/develop" + + out = _run_guard( + f"npm install --prefix {shlex.quote(str(target))} package", + kitchen_open=True, + tmpdir=linked, + ) + + threatened = _checked_out_ref_result(out)["threatened_refs"] + assert isinstance(threatened, list) + assert {row["target_ref"] for row in threatened} == {"refs/heads/develop"} + + @pytest.mark.parametrize("target_first", [True, False], ids=["target-first", "target-last"]) + def test_denies_install_target_directory_checked_out_ref_child( + self, + linked_repo: dict[str, Path | str], + tmp_path: Path, + target_first: bool, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + destination = Path(str(linked_repo["common_git_dir"])) / "refs/heads" + source = tmp_path / "sources/develop" + source.parent.mkdir() + source.write_text("replacement", encoding="utf-8") + operands = ( + f"-t {shlex.quote(str(destination))} {shlex.quote(str(source))}" + if target_first + else f"{shlex.quote(str(source))} -t {shlex.quote(str(destination))}" + ) + + out = _run_guard(f"install {operands}", kitchen_open=True, tmpdir=linked) + + threatened = _checked_out_ref_result(out)["threatened_refs"] + assert isinstance(threatened, list) + assert {row["target_ref"] for row in threatened} == {"refs/heads/develop"} + + @pytest.mark.parametrize("target_first", [True, False], ids=["target-first", "target-last"]) + def test_allows_install_from_protected_source_to_unprotected_directory( + self, + linked_repo: dict[str, Path | str], + tmp_path: Path, + target_first: bool, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + source = Path(str(linked_repo["common_git_dir"])) / "refs/heads/develop" + destination = tmp_path / "allowed" + destination.mkdir() + operands = ( + f"-t {shlex.quote(str(destination))} {shlex.quote(str(source))}" + if target_first + else f"{shlex.quote(str(source))} -t {shlex.quote(str(destination))}" + ) + + out = _run_guard(f"install {operands}", kitchen_open=True, tmpdir=linked) + + assert out.strip() == "" + class TestCheckedOutRefAmbiguity: @pytest.mark.parametrize( @@ -1036,6 +1150,71 @@ def test_valid_mutation_without_execution_cwd_fails_closed( ) assert _is_denied(out) + @pytest.mark.parametrize( + "command", + [ + 'npm install --prefix "$DESTINATION" package', + 'ln -sf /tmp/source "$DESTINATION"', + ], + ids=["npm-prefix", "ln-entry"], + ) + def test_unresolved_explicit_write_destination_fails_closed( + self, + linked_repo: dict[str, Path | str], + monkeypatch: pytest.MonkeyPatch, + command: str, + ) -> None: + monkeypatch.delenv("DESTINATION", raising=False) + linked = linked_repo["linked"] + assert isinstance(linked, Path) + + out = _run_guard(command, kitchen_open=True, tmpdir=linked) + + assert _is_denied(out) + assert _checked_out_ref_result(out)["attempted_value"] == "" + + @pytest.mark.parametrize( + "command_builder", + [ + lambda root: f"npm install --prefix {shlex.quote(str(root / 'npm-root'))} package", + lambda root: f"ln -sf /tmp/source {shlex.quote(str(root / 'link'))}", + lambda root: f"install -t {shlex.quote(str(root / 'install-root'))} /tmp/source", + lambda _root: "cat > f.md <<< 'git push --force origin main'", + ], + ids=["npm-prefix", "ln-entry", "install-target-directory", "relative-redirect"], + ) + def test_structural_write_without_execution_cwd_fails_closed( + self, + linked_repo: dict[str, Path | str], + command_builder, + ) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + + out = _run_guard( + command_builder(linked), + kitchen_open=True, + tmpdir=linked, + include_execution_cwd=False, + ) + + assert _is_denied(out) + assert _checked_out_ref_result(out)["attempted_value"] == "" + + +def test_link_entry_parent_loop_fails_closed(linked_repo: dict[str, Path | str]) -> None: + linked = linked_repo["linked"] + assert isinstance(linked, Path) + loop = linked / "loop" + loop.symlink_to(loop) + + out = _run_guard( + f"ln -s source {shlex.quote(str(loop / 'entry'))}", kitchen_open=True, tmpdir=linked + ) + + assert _is_denied(out) + assert _checked_out_ref_result(out)["attempted_value"] == "" + class TestCheckedOutRefWriteTargets: @pytest.mark.parametrize( diff --git a/tests/server/test_guards_module.py b/tests/server/test_guards_module.py index e08e5d0a82..e27928c4b6 100644 --- a/tests/server/test_guards_module.py +++ b/tests/server/test_guards_module.py @@ -79,6 +79,144 @@ def test_check_write_target_boundary_cases( assert result is None +@pytest.mark.parametrize( + ("command_template", "destination", "expected_message"), + [ + pytest.param( + "npm install --prefix {destination} node-jq", + "allowed", + None, + id="npm-prefix-equals-allowed-root", + ), + pytest.param( + "npm --prefix={destination} install node-jq", + "outside", + "outside allowed write prefixes", + id="npm-outside-prefix", + ), + pytest.param( + 'npm install --prefix "$NPM_PREFIX" node-jq', + "unresolved", + UNRESOLVED_WRITE_TARGET_REMEDIATION, + id="npm-unresolved-prefix", + ), + pytest.param( + "ln -sfT /opt/tools/jq {destination}", + "allowed", + None, + id="ln-entry-equals-allowed-root", + ), + pytest.param( + "ln -sf /opt/tools/jq {destination}/jq", + "outside", + "outside allowed write prefixes", + id="ln-outside-entry", + ), + pytest.param( + 'ln -sf /opt/tools/jq "$LINK_NAME"', + "unresolved", + UNRESOLVED_WRITE_TARGET_REMEDIATION, + id="ln-unresolved-entry", + ), + ], +) +def test_run_cmd_boundary_covers_npm_and_ln_destinations( + tmp_path, monkeypatch, command_template, destination, expected_message +) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + monkeypatch.delenv("NPM_PREFIX", raising=False) + monkeypatch.delenv("LINK_NAME", raising=False) + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + selected = allowed if destination == "allowed" else outside + command = command_template.format(destination=selected) + + result = _check_write_target_boundary(command, str(tmp_path), (str(allowed),)) + + if expected_message is None: + assert result is None + else: + assert result is not None + assert expected_message in result + + +@pytest.mark.parametrize( + "command_template", + ["echo changed > {destination}", "ln -sfT /opt/tools/jq {destination}"], + ids=["content-target", "entry-target"], +) +def test_run_cmd_boundary_denies_sibling_path_sharing_root_prefix( + tmp_path, command_template: str +) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + allowed = tmp_path / "allowed" + sibling = tmp_path / "allowed_extra" + allowed.mkdir() + sibling.mkdir() + destination = sibling / "target" + + result = _check_write_target_boundary( + command_template.format(destination=destination), str(tmp_path), (str(allowed),) + ) + + assert result is not None + assert "outside allowed write prefixes" in result + assert str(destination) in result + + +def test_run_cmd_entry_check_uses_link_location_not_referent(tmp_path) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + inside = allowed / "inside" + inside.write_text("inside", encoding="utf-8") + outside_link = outside / "link" + outside_link.symlink_to(inside) + + result = _check_write_target_boundary( + f"ln -sfT /opt/tools/jq {outside_link}", str(tmp_path), (str(allowed),) + ) + + assert result is not None + assert str(outside_link) in result + + +def test_run_cmd_empty_prefixes_still_disable_new_destination_checks(tmp_path) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + assert ( + _check_write_target_boundary('ln -sf /opt/tools/jq "$LINK_NAME"', str(tmp_path), ()) + is None + ) + + +def test_run_cmd_content_target_still_follows_final_symlink(tmp_path) -> None: + from autoskillit.server.lifecycle._guards import _check_write_target_boundary + + allowed = tmp_path / "allowed" + outside = tmp_path / "outside" + allowed.mkdir() + outside.mkdir() + outside_file = outside / "file" + outside_file.write_text("outside", encoding="utf-8") + content_link = allowed / "content-link" + content_link.symlink_to(outside_file) + + result = _check_write_target_boundary( + f"echo changed > {content_link}", str(tmp_path), (str(allowed),) + ) + + assert result is not None + assert str(content_link) in result + + def test_check_recipe_read_prohibition_importable(): from autoskillit.server.lifecycle._guards import _check_recipe_read_prohibition