diff --git a/client/agent/patch_guard.py b/client/agent/patch_guard.py new file mode 100644 index 0000000..7d4fbac --- /dev/null +++ b/client/agent/patch_guard.py @@ -0,0 +1,77 @@ +"""Refuse the fuzzy matches that rewrite literal text instead of whitespace. + +The Hermes matching chain (hermes/fuzzy_match.py, kept unmodified) falls back +to strategies that strip leading whitespace or accept lines that are only +similar. In a unified diff the first column is a marker, not indentation: a +'+' line sent without its '+', or a ' ' context line sent as an empty one, +matched anyway, and the replacement dropped or grafted the markers -- a +corrupt patch reported as a successful edit. The same similarity let a model's +diff-prefixed text match plain C lines and write the '+' into the source. + +Two rules, applied only when the chain matched through a non-exact strategy: +diff content (hunk headers plus file headers) is matched exactly or not at +all, and no aligned line pair may differ by a leading '+' or '-'. Both refuse +the edit; nothing is repaired. +""" + +from __future__ import annotations + +import re + +from .hermes import fuzzy_match + +DIFF_HUNK = re.compile(r"^@@ -\d+(,\d+)? \+\d+(,\d+)? @@", re.MULTILINE) +DIFF_FILE = re.compile(r"^(---|\+\+\+) \S", re.MULTILINE) + +DIFF_EXACT_ONLY = ( + "This file is a unified diff: old_string must match it exactly, first-column " + "markers included (' ' for context, '+' for added, '-' for removed lines). " + "Re-read the lines and copy them verbatim, or edit the source tree and " + "regenerate the patch with the project's workflow.") + +MARKER_DRIFT = ( + "old_string only resembles the file here: line {line} of old_string starts " + "with {pattern!r} where the file's line starts with {content!r}. A leading " + "'+' or '-' is text, not indentation; copy the lines exactly as the file " + "has them.") + + +def is_unified_diff(content: str) -> bool: + return bool(DIFF_HUNK.search(content) and DIFF_FILE.search(content)) + + +def _lead(line: str) -> str: + return line.lstrip(" \t")[:1] + + +def marker_drift(content: str, matches: list, old_string: str) -> str | None: + """The refusal for a match whose lines differ by a leading +/- marker.""" + pattern_lines = old_string.split("\n") + + for start, end in matches: + for number, (pattern, found) in enumerate(zip(pattern_lines, content[start:end].split("\n")), 1): + a, b = _lead(pattern), _lead(found) + + if a != b and {a, b} & {"+", "-"}: + return MARKER_DRIFT.format(line=number, pattern=a, content=b) + return None + + +def find_and_replace(content: str, old_string: str, new_string: str, + replace_all: bool = False): + """fuzzy_find_and_replace with the two literal-text rules on top.""" + new_content, count, strategy, error = fuzzy_match.fuzzy_find_and_replace( + content, old_string, new_string, replace_all) + + if error or not count or strategy == "exact": + return new_content, count, strategy, error + + if is_unified_diff(content): + return content, 0, None, DIFF_EXACT_ONLY + + matches = getattr(fuzzy_match, f"_strategy_{strategy}")(content, old_string) + refusal = marker_drift(content, matches, old_string) + + if refusal: + return content, 0, None, refusal + return new_content, count, strategy, error diff --git a/client/agent/tools.py b/client/agent/tools.py index a707b91..8bfc8b7 100644 --- a/client/agent/tools.py +++ b/client/agent/tools.py @@ -39,10 +39,11 @@ import stat import subprocess +from . import patch_guard from .hermes.ansi_strip import strip_ansi from .hermes.binary_extensions import has_binary_extension from .hermes.exit_codes import _interpret_exit_code -from .hermes.fuzzy_match import format_no_match_hint, fuzzy_find_and_replace, is_already_applied +from .hermes.fuzzy_match import format_no_match_hint, is_already_applied from .hermes.file_helpers import ( LINTERS_INPROC, _FAIL_CLOSED_INPROC_EXTS, _READ_DEDUP_STATUS_MESSAGE, _detect_line_ending, _is_internal_file_tool_content, _is_likely_binary_bytes, @@ -882,7 +883,7 @@ def patch(state: dict, display: str, resolved: str, old_string, new_string, raw = handle.read() content, _ = _strip_bom(raw) - new_content, match_count, _strategy, error = fuzzy_find_and_replace( + new_content, match_count, _strategy, error = patch_guard.find_and_replace( content, old_string, new_string, replace_all) if error or match_count == 0: diff --git a/client/cli/rag_chat.py b/client/cli/rag_chat.py index ebeacba..71d6900 100755 --- a/client/cli/rag_chat.py +++ b/client/cli/rag_chat.py @@ -37,6 +37,7 @@ from runtime.tracing import EventStatus, EventType, new_task_id from runtime.working_state import StateEventType, WorkingState from context.context_engine import ContextLayer +from context import workspace_context from context.workspace_context import project_families from runtime.compaction import CompactionMode, CompactionPolicy from runtime.agent_context import AgentContext @@ -966,12 +967,16 @@ def read_user_input(): # its own words is answered from those words and the document. bound_turn = bool(turn_binding) + projects = load_projects() + project_bound = workspace_context.project_bound( + registered=session_workspace.PROJECT in projects, + spec=projects.get(session_workspace.PROJECT)) said_before = next((message["content"] for message in reversed(hist) if message["role"] == "user"), "") prior_scope = answer_scope.of(answer_scope.spoken_part(said_before), - standard_bound=bound_turn) + standard_bound=bound_turn, project_bound=project_bound) turn_scope = answer_scope.of(user_input, prior=prior_scope, - standard_bound=bound_turn) + standard_bound=bound_turn, project_bound=project_bound) hist = answer_scope.carried( hist, turn_scope, standard_bound=bound_turn, self_contained=answer_scope.self_contained(user_input)) diff --git a/client/cli/session_workspace.py b/client/cli/session_workspace.py index 861cfdf..17a9b7c 100644 --- a/client/cli/session_workspace.py +++ b/client/cli/session_workspace.py @@ -6,9 +6,10 @@ import hashlib import readline import subprocess +from dataclasses import replace from pathlib import Path from runtime import work_phase -from harness.command_policy import CommandPolicy, ToolPolicy +from harness.command_policy import AuthorizationResult, CommandPolicy, ToolPolicy from harness.resource_control import ExecutionProfile from harness.sandbox import BubblewrapSandbox from harness.tool_primitives import ( @@ -16,6 +17,7 @@ ) from harness.tool_runtime import CommandRunner from harness.workspace import SandboxSpec, Workspace, effective_mount_root +from harness import attach_control, provenance, target_policy, write_protection from runtime.tracing import EventStatus, EventType, new_action_id from cli.chat_settings import AUDIT_LOGGER, STATE_DIR from cli.corpus_registry import load_projects @@ -155,6 +157,12 @@ def set_project(spec): if "COMMAND_POLICY" in globals(): COMMAND_POLICY.bind_workspace(WORKSPACE) + # What the trees hold now is what the session did not create: only the + # rest is its to clean up (provenance.py). + + provenance.capture(WORKSPACE.roots) + attach_control.pin_pristine() + PROJECT_KIND = spec["kind"] # Corpus identity (index/history/memories) is keyed by the CORPUS root, @@ -508,15 +516,314 @@ def read_file(path): SIGPIPE_EXIT = 141 +# What the carried-over session may export that would steer git, or a +# program git runs, while it writes its records. + +_STEERING_EXPORT = re.compile(r"^(?:GIT_(?!PAGER$)\w+|XDG_\w+|LD_\w+|BASH_ENV|ENV|EDITOR|VISUAL)$") + + +def _session_exports(script): + """{name: value} that a terminal session script restores before its command.""" + found = {} + + for line in (script or "").splitlines(): + match = re.match(r'declare -x ([A-Za-z_]\w*)(?:="((?:[^"\\]|\\.)*)")?$', line) + + if match: + found[match.group(1)] = re.sub(r"\\(.)", r"\1", match.group(2) or "") + + return found + + +def _git_is_steered(cmd, script, aliases): + """Whether the session around `cmd` makes its git something else. + + An export that redirects git or loads code into it, a HOME other than + the sandbox's, or a writable directory ahead of the system's git on PATH + that holds a `git`, or could by the time a second git command runs. + """ + spec = SandboxSpec() + exports = _session_exports(script) + + if any(_STEERING_EXPORT.match(name) for name in exports): + return True + + if exports.get("HOME", spec.home) != spec.home: + return True + + writable = [str(root) for root in WORKSPACE.roots] + [spec.home] + list(aliases.values()) + several = sum(argv[0] == "git" for argv in COMMAND_POLICY.stage_argvs(cmd)) > 1 + + for entry in exports.get("PATH", spec.path).split(":"): + if entry in ("/usr/bin", "/bin"): + return False + + if not entry.startswith("/"): + return True + + host = next((path + entry[len(inside):] for inside, path in aliases.items() + if entry == inside or entry.startswith(inside.rstrip("/") + "/")), entry) + + if write_protection.within(os.path.realpath(host), writable) and ( + several or os.path.lexists(os.path.join(host, "git"))): + return True + + return False + + +def _host_paths(): + """A function from a path as the sandbox names it to the host's.""" + mount = effective_mount_root(WORKSPACE.root) + aliases = {inside: host for host, inside in WORKSPACE.mount_map( + mount, identity=mount != SandboxSpec().workspace_mount).items() if inside != host} + + def host(path): + for inside, outside in aliases.items(): + if path == inside or path.startswith(inside.rstrip("/") + "/"): + return outside + path[len(inside):] + + return path + + return host + + +_UNREAD_WORD = re.compile(r"[$`*?\[\]{}~]") + + +def _stages_where(cmd, cwd, host): + """(directory, argv) for each stage of `cmd`, its `cd`s followed. + + The directory is None once a `cd` names a place that cannot be read. + """ + directory = host(cwd) + + for argv in COMMAND_POLICY.stage_argvs(cmd): + if argv[0] == "cd": + operands = [word for word in argv[1:] if word not in ("-P", "-L", "--")] + + if directory is None or len(operands) != 1 or _UNREAD_WORD.search(operands[0]): + directory = None + else: + directory = os.path.normpath(os.path.join(directory, host(operands[0]))) + + continue + + yield directory, argv + + +def _sourced_refusal(cmd, cwd): + """Why `cmd` may not source a script, or "". + + `. ./x.sh` runs the script's commands in the shell itself, none of them + judged. A script from the start state (env.sh) is the project's own; one + written or changed in this session is the model's, and would run what + the model may not. + """ + host = _host_paths() + + for directory, argv in _stages_where(cmd, cwd, host): + if argv[0] not in (".", "source") or len(argv) < 2: + continue + + word = argv[1] + + if _UNREAD_WORD.search(word) or (directory is None and not word.startswith("/")): + return (f"'{argv[0]} {word}': which script it runs cannot be read here, so " + f"the command cannot run") + + path = os.path.normpath(os.path.join(directory or "/", host(word))) + + try: + changed = os.path.getmtime(path) >= write_protection.started() + except OSError: + continue + + if changed or provenance.created(path): + return (f"'{argv[0]} {word}' runs a script written in this session, whose " + f"commands would run unjudged: run them as commands instead") + + return "" + + +def _authored_programs(cmd, cwd): + """The programs `cmd` runs by path that this session made. + + A binary the session compiled, a script of the project it rewrote, or + anything it put in its scratch, runs code the model wrote: `gcc -o t t.c + && ./t` did what `python3 t.py` was refused. Such a program gets what a + test module the session wrote gets: the trees read-only. A program of the + start state, unchanged, runs as it always did. + """ + host = _host_paths() + found = [] + + for directory, argv in _stages_where(cmd, cwd, host): + program = argv[0] + + if "/" not in program: + continue + + if directory is None or _UNREAD_WORD.search(program): + found.append(program) + continue + + path = os.path.normpath(os.path.join(directory, host(program))) + + if path.startswith(("/tmp/", SandboxSpec().tmpdir.rstrip("/") + "/")) or ( + provenance.known(path) and (not os.path.lexists(path) or provenance.created(path) + or _changed_since_start(path))): + found.append(path) + + return tuple(found) + + +def _changed_since_start(path): + try: + return os.path.getmtime(path) >= write_protection.started() + except OSError: + return False + + +def _git_clean_targets(cmd, cwd): + """(objects, refusal) for the `git clean` stages of `cmd`. + + What git clean removes is listed first by the same command with -n, and + each object is judged as delete_file would judge it (provenance.py): the + session's own objects may go; one from the start state, a protected one + or one in a tree whose start state is unknown stops the command. A clean + whose deletion set cannot be listed does not run. + """ + host = _host_paths() + targets = [] + + for directory, argv in _stages_where(cmd, cwd, host): + if argv[0] != "git": + continue + + parsed = COMMAND_POLICY.git_command(argv) + + if parsed is None or parsed[0] != "clean": + if parsed is None and "clean" in argv: + return (), "git clean with these options cannot be read here, so it cannot run" + + continue + + if (directory is None or COMMAND_POLICY.steers_git(cmd) + or any(_UNREAD_WORD.search(word) for word in argv)): + return (), "what this git clean would remove cannot be read here, so it cannot run" + + for word in parsed[1]: + directory = os.path.normpath(os.path.join(directory, host(word))) + + options = [] + arguments = argv[argv.index("clean") + 1:] + + # A dry run removes nothing. + + if any(word in ("-n", "--dry-run") or (re.fullmatch(r"-[a-zA-Z]+", word) and "n" in word) + for word in arguments if word != "--"): + continue + + for word in arguments: + if word in ("-i", "--interactive") or ( + re.fullmatch(r"-[a-zA-Z]+", word) and "i" in word): + return (), "an interactive git clean cannot run here" + + if word in ("-q", "--quiet"): + continue + + options.append(word.replace("q", "") if re.fullmatch(r"-[a-zA-Z]+", word) else word) + + try: + listing = subprocess.run( + ["git", "-c", "core.fsmonitor=false", "clean", "-n", + *options], + cwd=directory, capture_output=True, text=True, timeout=60, + env={key: value for key, value in os.environ.items() + if not key.startswith("GIT_")}) + except (OSError, subprocess.TimeoutExpired): + return (), "what this git clean would remove could not be listed, so it cannot run" + + if listing.returncode != 0: + return (), "what this git clean would remove could not be listed, so it cannot run" + + for line in listing.stdout.splitlines(): + if not line.startswith("Would remove "): + continue + + name = line[len("Would remove "):] + path = os.path.normpath(os.path.join(directory, name)) + + if not provenance.known(path): + return (), (f"git clean would remove {name}, in a tree whose start state is " + f"not known, so it cannot run") + + refusal = provenance.removal_refusal(path, name.rstrip("/")) + + if refusal: + return (), (f"git clean: {target_policy.deletion_set_refusal(refusal)}. " + f"git clean removes only what this session created") + + targets.append(os.path.join(os.path.realpath(os.path.dirname(path)), + os.path.basename(path))) + + return tuple(targets), "" + + +def _session_cleanup(cmd, cwd): + """(objects, refusal) for a command that only removes named objects. + + ((), "") when the command is not such a command; the objects, as host + paths, when every one was created in this session; a refusal naming the + first that was not. + """ + plan = COMMAND_POLICY.cleanup_plan(cmd) + + if plan is None: + return (), "" + + host = _host_paths() + directory, targets = host(cwd), [] + + for kind, words, _ in plan: + if kind == "cd": + directory = os.path.normpath(os.path.join(directory, host(words[0]))) + continue + + for word in words: + path = os.path.normpath(os.path.join(directory, host(word))) + + if not os.path.lexists(path): + continue + + # With no start state for the tree, nothing is the session's: the + # command keeps the refusal it had. + + if not provenance.known(path): + return (), "" + + refusal = provenance.removal_refusal(path, word) + + if refusal: + return (), (f"{refusal}. A command removes only what this session created; " + f"a file from the start state is deleted with delete_file.") + + targets.append(os.path.join(os.path.realpath(os.path.dirname(path)), + os.path.basename(path))) + + return tuple(targets), "" + + def run_cmd_result(cmd, need_confirm=True, cancellation=None, execution_mode=None, - exec_cmd=None, timeout=None, output_chars=None): + exec_cmd=None, timeout=None, output_chars=None, cwd=None): """Return the security substrate's structured command result. `cmd` is what is classified and authorised. `exec_cmd`, when given, is what runs in its place: the same command inside a harness-built script (the terminal's carried-over session), never anything the policy did not judge -- and judged as the script it runs in. `timeout` replaces the - sandbox's default for this call. + sandbox's default for this call. `cwd` is where the command starts, for + reading the relative paths it names. """ # The coding core's control plane answers gateway commands before they # get here. One that arrives anyway came from a runtime that has no @@ -533,6 +840,52 @@ def run_cmd_result(cmd, need_confirm=True, cancellation=None, execution_mode=Non authorization = COMMAND_POLICY.authorize(assessment, mode, approve=confirm) + # A command that only removes what this session created gets the + # authority delete_file has, no more (provenance.py): every object it + # names must have been created in this session. + + cleanup = () + + if assessment.classification == CommandClassification.DANGEROUS and WORKSPACE is not None: + cleanup, refusal = _session_cleanup(cmd, cwd or str(WORKSPACE.root)) + + if refusal: + authorization = AuthorizationResult(ToolResult("denied", f"command denied: {refusal}")) + elif cleanup: + assessment = replace( + assessment, classification=CommandClassification.WORKSPACE_MUTATING, + reason="session cleanup", required_capabilities=frozenset({ + Capability.FILESYSTEM_READ, Capability.WORKSPACE_WRITE, + Capability.SHELL_COMPLEX})) + authorization = COMMAND_POLICY.authorize(assessment, mode, approve=confirm) + + # The other routes to a deletion or to unjudged commands: git clean + # removes only what this session created, and a script this session + # wrote is not sourced. + + if authorization.allowed and WORKSPACE is not None: + refusal = _sourced_refusal(cmd, cwd or str(WORKSPACE.root)) + cleaned = () + + if not refusal: + cleaned, refusal = _git_clean_targets(cmd, cwd or str(WORKSPACE.root)) + + if refusal: + authorization = AuthorizationResult(ToolResult("denied", f"command denied: {refusal}")) + else: + cleanup = tuple(cleanup) + cleaned + + # A test runner is no authority: a test module this session wrote runs + # with the trees read-only, so it reaches nothing the model could not + # reach directly (write_protection.authored_test_modules). + + authored = () + + if authorization.allowed and WORKSPACE is not None: + authored = write_protection.authored_test_modules( + cmd, WORKSPACE.roots, cwd=cwd or str(WORKSPACE.root)) + authored += _authored_programs(cmd, cwd or str(WORKSPACE.root)) + if authorization.result is not None: if (assessment.classification != CommandClassification.READ_ONLY or assessment.required_capabilities): @@ -545,9 +898,47 @@ def run_cmd_result(cmd, need_confirm=True, cancellation=None, execution_mode=Non return authorization.result granted_capabilities = authorization.granted_capabilities + + if authored: + granted_capabilities = granted_capabilities - {Capability.WORKSPACE_WRITE} + + builds = COMMAND_POLICY.builds(cmd) + protected = () + git_dirs = () + + # What the command names that no tool may change is bound read-only + # under it, whatever program would write it (write_protection.py). + + if Capability.WORKSPACE_WRITE in granted_capabilities and WORKSPACE is not None: + mount = effective_mount_root(WORKSPACE.root) + aliases = {inside: host for host, inside in WORKSPACE.mount_map( + mount, identity=mount != SandboxSpec().workspace_mount).items() if inside != host} + tmpdir = getattr(COMMAND_RUNNER.sandbox, "session_tmpdir", None) + + if tmpdir: + aliases[SandboxSpec().tmpdir] = tmpdir + + protected = write_protection.command_files( + cmd, WORKSPACE.roots, cwd=cwd or str(WORKSPACE.root), build=builds, + aliases=aliases) + protected = tuple(path for path in protected + if not any(path == target or path.startswith(target + "/") + for target in cleanup)) + + # A git command keeps its own repository's records, and only when the + # command is git's alone, run as itself (CommandPolicy.git_writes). + + steps = COMMAND_POLICY.git_writes(cmd) + + if steps and not _git_is_steered(cmd, exec_cmd, aliases): + git_dirs = write_protection.git_dirs(steps, WORKSPACE.roots, + cwd=cwd or str(WORKSPACE.root), aliases=aliases) + profile = ExecutionProfile.from_capabilities( granted_capabilities, assessment.host_read_paths if Capability.HOST_READ in granted_capabilities else (), + git_dirs=git_dirs, guard_outputs=not builds, protected_paths=protected, + cleanup_paths=cleanup, ) sandboxed = False @@ -566,6 +957,15 @@ def run_cmd_result(cmd, need_confirm=True, cancellation=None, execution_mode=Non default_timeout = getattr(sandbox, "timeout_seconds", None) default_chars = getattr(sandbox, "max_output_chars", None) + # The attach state is the attach's own, and what a build removes from + # the start state must be its own output (attach_control.py). + + watched = Capability.WORKSPACE_WRITE in granted_capabilities and WORKSPACE is not None + attach_before = attach_control.snapshot() if watched else {} + objects_before = attach_control.present_start_objects() if watched and builds else [] + pristine_before = attach_control.pristine_state() if watched and builds else {} + started = attach_control.now() + try: if timeout and default_timeout is not None: sandbox.timeout_seconds = timeout @@ -584,6 +984,16 @@ def run_cmd_result(cmd, need_confirm=True, cancellation=None, execution_mode=Non if default_chars is not None: sandbox.max_output_chars = default_chars + if watched: + result = _attach_and_build_effects(cmd, result, mode, attach_before, objects_before, + pristine_before, started, builds) + + # A clone adds a repository, and a build a generated tree, that the + # next command must find protected. + + if builds or COMMAND_POLICY.writes_git(cmd): + write_protection.forget() + sandboxed = True else: result = availability @@ -621,6 +1031,79 @@ def run_cmd_result(cmd, need_confirm=True, cancellation=None, execution_mode=Non return result +def _attach_and_build_effects(cmd, result, mode, attach_before, objects_before, pristine_before, + started, builds): + """Undo what a command did to the attach state, report what a build + removed that it did not own, and, after a successful updiff, record the + attached tree as the state its series reproduces.""" + notes = [] + restored = attach_control.enforce(attach_before, build=builds) + + if restored: + notes.append(f"policy: the attach state is control-plane metadata; restored " + f"{', '.join(_label(path) for path in restored[:5])}") + AUDIT_LOGGER.record_mutation( + action="attach_metadata_restored", mode=mode, workspace=WORKSPACE, + paths=restored, command=cmd, approved=False, + result=ToolResult("denied", "attach metadata changed by a command, restored")) + + if builds: + attach_control.pin_pristine(pristine_before) + bad = attach_control.violations(attach_control.removed_by(objects_before)) + + if bad: + notes.append(f"policy violation: the build removed {len(bad)} object(s) of the start " + f"state it does not own (sources, not build output): " + f"{', '.join(_label(path) for path in bad[:5])}") + AUDIT_LOGGER.record_mutation( + action="build_effect_violation", mode=mode, workspace=WORKSPACE, + paths=bad[:200], command=cmd, approved=False, + result=ToolResult("denied", f"build removed {len(bad)} start-state source objects")) + + if result.status == "ok" and result.exit_code in (None, 0): + for recipe in attach_control.updiff_recipes(COMMAND_POLICY.stage_argvs(cmd)): + written, why, check = attach_control.refresh(recipe, started) + + if check is not None: + AUDIT_LOGGER.record_mutation( + action="persistence_verification", mode=mode, workspace=WORKSPACE, + paths=(), command=cmd, approved=check.verified, + result=ToolResult("ok" if check.verified else "denied", check.summary())) + + if not check.verified: + shown = "; ".join(check.differences[:5]) + notes.append(f"SPEAR did not record the attached tree of {recipe}: {why}" + f"{f' ({shown})' if shown else ''}. The updiff captured what " + f"it could, the attach guard stays in force, and a re-attach " + f"will refuse until the series reproduces the tree") + + if written: + notes.append(f"SPEAR recorded the attached tree of {recipe} as the state its " + f"patch series now reproduces ({_label(written)}): the next " + f"attach re-attaches from the series") + AUDIT_LOGGER.record_mutation( + action="attach_state_refresh", mode=mode, workspace=WORKSPACE, + paths=(written,), command=cmd, approved=True, + result=ToolResult("ok", f"trusted attach-state refresh after updiff of {recipe}")) + else: + AUDIT_LOGGER.record_mutation( + action="attach_state_refresh", mode=mode, workspace=WORKSPACE, + paths=(), command=cmd, approved=False, + result=ToolResult("denied", f"no refresh after updiff of {recipe}: {why}")) + + if not notes: + return result + + return replace(result, stderr=(result.stderr + "\n" if result.stderr else "") + "\n".join(notes)) + + +def _label(path): + try: + return WORKSPACE.relative(path) + except Exception: + return path + + def command_result_text(result): """Preserve the historical command text at the UI/model boundary.""" @@ -734,34 +1217,19 @@ def edit_file(path, old_text, new_text, *, execution_context=None): if not fpath: return f"ERROR: file not found: {path}" - # guard: a bad/incomplete path can fuzzy-resolve to a SNAPSHOT or - # third-party tree (e.g. avz.back/…, u-boot/…). Never write there — it - # corrupts the pristine copy and is never the file the user meant. + # A bad or incomplete path can fuzzy-resolve to a snapshot copy, generated + # output or git metadata. The same policy every other mutation asks. - if is_excluded_path(fpath): - return (f"ERROR: {os.path.relpath(fpath, PROJECT_ROOT)} is a snapshot / " - f"third-party copy (.back/.0/.pristine/u-boot/atf/qemu) — never " - f"edit it. Use the LIVE source path (re-check it with ls/find).") + from harness import target_policy + + protected = target_policy.refusal(str(fpath), path) + + if protected: + return f"ERROR: {protected}." with fpath.open("r", encoding="utf-8") as f: content = f.read() - # guard: never edit a GENERATED / DO-NOT-MODIFY file — it is overwritten on - # the next build/regen and editing it hides the real fix (must change the - # source that generates it, or the Kconfig/config instead). - # str(): resolve_path returns a Path, and re.search refuses one. This - # raised TypeError on EVERY edit of an existing file, so edit_file has been - # dead since the workspace started resolving to Path objects — which is why - # the model always fell back to rewriting whole files with write_file. - - if re.search(r"/generated/|/build/tmp/", str(fpath)) or re.search( - r"DO NOT (?:MODIFY|EDIT)|auto(?:matically)?[ -]?generated|@generated", - content[:600], re.IGNORECASE): - return (f"ERROR: {path} is a GENERATED / DO-NOT-MODIFY file (it gets " - f"overwritten on the next build). Do NOT edit it — fix the " - f"source that generates it (a script, Kconfig, .config, or a " - f"template), not the generated output.") - # guard: a no-op edit changes nothing but reports success — the model then # believes it acted. The comparison is EXACT. It used to normalise # whitespace, which made every whitespace-only edit impossible: inserting a @@ -1016,7 +1484,7 @@ def apply_unified_diff(fpath, diff_text): def is_excluded_path(p): - """Third-party / snapshot trees we must NEVER auto-write into.""" + """Snapshot copies we must NEVER auto-write into.""" from harness import target_policy return target_policy.is_snapshot(str(p)) diff --git a/client/cli/terminal_ui.py b/client/cli/terminal_ui.py index 1cfa78f..9f9a4c1 100644 --- a/client/cli/terminal_ui.py +++ b/client/cli/terminal_ui.py @@ -345,12 +345,27 @@ class Liveness: def __init__(self): self.at = time.monotonic() + self.until = 0.0 def touch(self): self.at = time.monotonic() + @contextmanager + def bounded(self, seconds): + """A command that runs under its own timeout is alive until that + timeout: a 600 s build is silent while it compiles, and the sandbox, + not this watchdog, ends it if it overruns.""" + self.until = time.monotonic() + seconds + + try: + yield + finally: + self.until = 0.0 + self.touch() + def silent_for(self): - return time.monotonic() - self.at + now = time.monotonic() + return 0.0 if now < self.until else now - max(self.at, self.until) LIVENESS = Liveness() diff --git a/client/cli/tool_handlers.py b/client/cli/tool_handlers.py index 470a67d..8677ed8 100644 --- a/client/cli/tool_handlers.py +++ b/client/cli/tool_handlers.py @@ -1,6 +1,7 @@ """The concrete tool handlers the registry routes to, and their bookkeeping.""" import os +import shutil import re import sys import shlex @@ -20,7 +21,7 @@ COMMAND_POLICY, _capture_checkpoint_path, _forget_cached_reads, _record_mutation, apply_unified_diff, audit_denied_mutation, audit_mutation_result, audit_rejected_mutation, authorize_mutation, - command_result_text, edit_file, find_file, is_excluded_path, + command_result_text, edit_file, find_file, preserve_third_party_header, resolve_path, run_cmd_result, safe_mode_refusal, ) @@ -464,6 +465,59 @@ def _sandbox_down_result(label, path): ) +def _protected_result(action, path, fpath, *, follow=True, deleting=False): + """The target policy's refusal of `fpath`, shown and audited, or None. + + The same question the coding core's write and delete ports ask: a file + one tool may not change, no tool may. + """ + from harness import target_policy + + refusal = target_policy.refusal(str(fpath), path, follow=follow, deleting=deleting) + + if not refusal: + return None + + result = f"ERROR: {refusal}." + audit_rejected_mutation(action, "protected target", paths=(fpath,)) + tool_result(result) + print() + + return _classified_handler_result(result) + + +def _override_result(action, fpath, content, *, appending=False): + """The refusal of a write that throws a guard's override switch, or None + (control_overrides.py).""" + from harness import control_overrides + + try: + with open(fpath, encoding="utf-8", errors="replace") as handle: + before = handle.read() + except OSError: + before = "" + + # A diff adds its "+" lines to what is there. + + if looks_like_diff(content): + content = "\n".join(line[1:] for line in content.splitlines() + if line.startswith("+") and not line.startswith("+++")) + appending = True + + refusal = control_overrides.content_refusal( + before, before + "\n" + content if appending else content) + + if not refusal: + return None + + result = f"ERROR: {refusal}." + audit_rejected_mutation(action, "control-plane override", paths=(fpath,)) + tool_result(result) + print() + + return _classified_handler_result(result) + + def _registered_edit_file(context, args): path = (args.get("path") or "").strip() @@ -496,6 +550,12 @@ def _registered_edit_file(context, args): result = f"ERROR: {exc}" audit_rejected_mutation("apply_patch", str(exc), paths=(path,)) else: + protected = (_protected_result("apply_patch", path, fpath) + or _override_result("apply_patch", fpath, diff)) + + if protected is not None: + return protected + blocked = authorize_mutation( f"Apply patch to {C_BOLD}{path}{C_RST} ?", action="apply_patch", paths=(fpath,), @@ -558,6 +618,13 @@ def _registered_append_file(context, args): fpath = find_file(path) + if fpath and (protected := _protected_result("append_file", path, fpath)) is not None: + return protected + + if fpath and (protected := _override_result("append_file", fpath, content, + appending=True)) is not None: + return protected + if not fpath: result = f"ERROR: file not found: {path}" elif (blocked := authorize_mutation( @@ -601,6 +668,53 @@ def named_link(path): return named if named.is_symlink() else None +def _delete_session_tree(context, path, fpath): + """Remove a directory the session created, with everything in it. + + Only when the directory and every object under it were created in this + session and none is protected (provenance.removal_refusal): a tree that + holds one file from the start state is refused whole, never pruned. + """ + from harness import provenance + + refusal = provenance.removal_refusal(str(fpath), path) + + if refusal: + result = (f"ERROR: {path} is a directory, and delete_file removes one only when " + f"this session created it and everything in it: {refusal}. Nothing was " + f"deleted.") + audit_rejected_mutation("delete_file", "not session-created", paths=(fpath,)) + tool_result(result) + print() + + return _classified_handler_result(result) + + blocked = authorize_mutation( + f"Delete the directory {C_BOLD}{path}{C_RST} ?", action="delete_file", paths=(fpath,)) + + if blocked is not None: + result = blocked.to_legacy_text() + else: + count = sum(len(subdirectories) + len(files) + for _, subdirectories, files in os.walk(fpath, followlinks=False)) + + try: + shutil.rmtree(fpath) + result = (f"OK: deleted the directory {path} and the {count} objects this " + f"session created in it") + _forget_cached_reads(context) + except OSError as exc: + result = f"ERROR: could not delete {path}: {exc.strerror}" + + audit_mutation_result("delete_file", result, paths=(fpath,)) + + tool_result(result) + print() + affected = (_workspace_label(fpath),) if result.startswith("OK") else () + + return _classified_handler_result(result, mutation=True, affected_paths=affected) + + def _registered_delete_file(context, args): """Remove a file, having first captured it so /undo can bring it back. @@ -633,24 +747,23 @@ def _registered_delete_file(context, args): return _classified_handler_result(result) + if os.path.isdir(fpath) and not os.path.islink(fpath): + return _delete_session_tree(context, path, fpath) + if not os.path.isfile(fpath) and not os.path.islink(fpath): - result = (f"ERROR: {path} is not an existing regular file. Nothing " - f"was deleted." if not os.path.isdir(fpath) else - f"ERROR: {path} is a directory. delete_file removes one " - f"file at a time.") + result = f"ERROR: {path} is not an existing regular file. Nothing was deleted." tool_result(result) print() return _classified_handler_result(result) - if is_excluded_path(fpath): - result = (f"ERROR: {path} is in a third-party or snapshot tree that is " - f"never modified from here.") - audit_rejected_mutation("delete_file", "excluded tree", paths=(fpath,)) - tool_result(result) - print() + # A link is judged as itself: deleting it leaves what it names alone. - return _classified_handler_result(result) + protected = _protected_result("delete_file", path, fpath, + follow=not os.path.islink(fpath), deleting=True) + + if protected is not None: + return protected blocked = authorize_mutation( f"Delete {C_BOLD}{path}{C_RST} ?", action="delete_file", paths=(fpath,)) @@ -737,6 +850,14 @@ def _registered_write_file(context, args): return _classified_handler_result(refused) + protected = _protected_result("write_file", path, fpath) + + if protected is not None: + return protected + + if (protected := _override_result("write_file", fpath, content)) is not None: + return protected + if looks_like_diff(content) and os.path.isfile(fpath): print() tool_use("Update", path, color=C_ACCENT) @@ -1056,6 +1177,15 @@ def _fetch_url_to_disk(context, url, save_as): if os.path.isdir(fpath): return f"ERROR fetch_url: '{save_as}' is a directory." + from harness import target_policy + + protected = target_policy.refusal(str(fpath), save_as) + + if protected: + audit_rejected_mutation("fetch_url", "protected target", paths=(fpath,)) + + return f"ERROR fetch_url: {protected}." + with Spinner("Downloading…"): data, content_type, final_url = web_fetch.download(url) diff --git a/client/cli/tool_routing.py b/client/cli/tool_routing.py index 6b5706d..aaa4a6f 100644 --- a/client/cli/tool_routing.py +++ b/client/cli/tool_routing.py @@ -23,7 +23,8 @@ authorize_mutation, resolve_path, run_cmd_result, safe_mode_refusal, ) from cli.terminal_ui import ( - C_ACCENT, C_BOLD, C_RST, C_TOOL, tool_result, tool_step, tool_step_result, tool_use, + C_ACCENT, C_BOLD, C_RST, C_TOOL, LIVENESS, tool_result, tool_step, + tool_step_result, tool_use, ) from cli.tool_handlers import ( NETWORK_ENABLED, SANDBOX_DOWN, WORK_PHASE, _classified_handler_result, @@ -59,6 +60,10 @@ def coding_host(agent_context, cache, record): from harness.control_plane import SpearHost from agent.host import CommandOutcome + # Where the terminal call last authorized runs, for the command it runs. + + command_cwd = [None] + def context(): return _execution_context(agent_context, cache, task_id=getattr(agent_context, "task_id", None), @@ -73,6 +78,9 @@ def authorize(name, arguments, cwd=None): if cwd: ctx.metadata = {**ctx.metadata, "command_cwd": cwd} + if name == "terminal": + command_cwd[0] = cwd + return TOOL_ROUTER.authorize(ctx, name, arguments) def resolve(path, purpose): @@ -101,6 +109,22 @@ def write(resolved, content, action): if protected: return protected + # And what the write would say: a line that throws a guard's + # override switch is the operator's to write (control_overrides.py). + + from harness import control_overrides + + try: + with open(resolved, encoding="utf-8", errors="replace") as handle: + before = handle.read() + except OSError: + before = "" + + override = control_overrides.content_refusal(before, content) + + if override: + return override + blocked = authorize_mutation(f"Modify {C_BOLD}{label}{C_RST} ?", action=action, paths=(Path(resolved),)) @@ -128,7 +152,8 @@ def delete(resolved, reason): # A file no write may change may not be deleted either: deleted, it # could be written afresh, with nothing left to say it was protected. - protected = target_policy.refusal(resolved, _workspace_label(Path(resolved))) + protected = target_policy.refusal(resolved, _workspace_label(Path(resolved)), + deleting=True) if protected: return protected @@ -138,13 +163,16 @@ def delete(resolved, reason): def run(command, script, timeout, output_chars): ctx = context() - result = run_cmd_result( - command, need_confirm=False, cancellation=ctx.cancellation, - exec_cmd=script, timeout=timeout, output_chars=output_chars, - execution_mode=(ExecutionMode.SAFE - if ctx.read_only or _write_gate_closed(ctx) - or ctx.role in {"explorer", "reviewer", "planning"} - else None)) + + with LIVENESS.bounded(timeout + 30): + result = run_cmd_result( + command, need_confirm=False, cancellation=ctx.cancellation, + exec_cmd=script, timeout=timeout, output_chars=output_chars, + cwd=command_cwd[0], + execution_mode=(ExecutionMode.SAFE + if ctx.read_only or _write_gate_closed(ctx) + or ctx.role in {"explorer", "reviewer", "planning"} + else None)) status = {"ok": "ok", "failed": "ok", "denied": "denied", "cancelled": "cancelled", "timeout": "timeout"}.get(result.status, "error") diff --git a/client/context/answer_scope.py b/client/context/answer_scope.py index 3c27802..7990f6e 100644 --- a/client/context/answer_scope.py +++ b/client/context/answer_scope.py @@ -87,7 +87,7 @@ ToolCategory.FILE_WRITE}) -def of(message, *, prior=None, standard_bound=False): +def of(message, *, prior=None, standard_bound=False, project_bound=False): """The scope of this turn, from its own words. `prior` is the previous turn's scope, consulted only where this message @@ -96,6 +96,12 @@ def of(message, *, prior=None, standard_bound=False): names no subject at all a question about that document -- the same principle the normative policy already works on, where activation is the binding and never the phrasing. + + `project_bound` says the session runs in a registered project that + declares a project family: the same principle again, from the workspace. + "Enable CONFIG_SCHEDSTATS in the kernel configuration" names no subject + this module's vocabulary knows, and in such a project it is about that + project's tree all the same, so its rules and skills become eligible. """ text = (message or "").strip() local = (bool(_LOCAL_SUBJECT.search(text)) or bool(_CHANGE.search(text)) @@ -122,8 +128,12 @@ def of(message, *, prior=None, standard_bound=False): return prior # Names no subject of its own. With a document bound, that is a question - # about the document; without one there is nothing for this to mean. - return NORMATIVE if standard_bound else GENERAL + # about the document; in a project of a declared family, about its tree; + # otherwise there is nothing for this to mean. + if standard_bound: + return NORMATIVE + + return IMPLEMENTATION if project_bound else GENERAL #: The machine payload a finished turn appends to what the operator typed: @@ -268,7 +278,7 @@ def operator_messages(conversation): return said -def prior_scope(conversation, *, standard_bound=False): +def prior_scope(conversation, *, standard_bound=False, project_bound=False): """The scope of the turn before this one, for a message that refers back. Read from the conversation rather than remembered between turns: the @@ -280,4 +290,4 @@ def prior_scope(conversation, *, standard_bound=False): if len(said) < 2: return None - return of(said[-2], standard_bound=standard_bound) + return of(said[-2], standard_bound=standard_bound, project_bound=project_bound) diff --git a/client/context/request_scope.py b/client/context/request_scope.py index b20036f..e9baa9c 100644 --- a/client/context/request_scope.py +++ b/client/context/request_scope.py @@ -485,6 +485,51 @@ def _at(directory: str, token: str) -> str: return os.path.join(directory, token) +_VARIABLE = re.compile(r"\$(?:\{(\w+)\}|(\w+))") +_LITERAL_ASSIGNMENT = re.compile(r"^([A-Za-z_]\w*)=([^$`]*)$") + + +def _with_assignments(stages): + """Each stage with the variables assigned literally before it substituted. + + `F=board/x; echo P >> $F` writes board/x. A value the command computes is + left as `$F`, which counts as a destination known only at run time. + """ + values = {} + found = [] + + for argv in stages: + argv = [_VARIABLE.sub(lambda match: values.get(match.group(1) or match.group(2), + match.group(0)), token) + for token in argv] + + for token in (argv[1:] if argv[0] in ("export", "local", "readonly") else argv): + assignment = _LITERAL_ASSIGNMENT.match(token) + + if not assignment: + break + + values[assignment.group(1)] = assignment.group(2) + + found.append(argv) + + return found + + +def _copied_into(argv) -> list[str]: + """What `cp src dir/` writes: dir/src's name, not the directory.""" + if Path(argv[0]).name not in ("cp", "mv", "install"): + return [] + + operands = [arg for arg in argv[1:] if not arg.startswith("-")] + + if len(operands) < 2 or not (operands[-1].endswith("/") or os.path.isdir(operands[-1])): + return [] + + return [os.path.join(operands[-1], os.path.basename(source.rstrip("/"))) + for source in operands[:-1]] + + def shell_write_targets(command: str, scope: RequestScope, cwd: str | None = None) -> list[str]: """Every path a shell command may write: a redirection, the destination of cp/mv/install/ln, the operands of rm/touch/mkdir/tee/truncate/sed -i. @@ -501,7 +546,7 @@ def shell_write_targets(command: str, scope: RequestScope, cwd: str | None = Non if not command: return [] - words = list(_split_stages(command)) + words = _with_assignments(list(_split_stages(command))) patterns = [argv[index + 1] for argv in words for index, arg in enumerate(argv[:-1]) if arg in ("-name", "-iname")] @@ -511,26 +556,190 @@ def shell_write_targets(command: str, scope: RequestScope, cwd: str | None = Non for index, token in enumerate(argv) if index] for argv, directory in zip(words, directories)] # What the whole command names, globs expanded in the project: the - # candidates when a write's destination is only known at run time. - mentioned = [path for argv in stages for token in argv[1:] - for path in _expand_in(scope, token)] - mentioned += [path for item in list(mentioned) - for path in _children_matching(scope, item, patterns)] + # candidates when a write's destination is only known at run time. A + # directory a stage only enters (`cd`) is where it runs, not a file it + # names. What lies inside a named directory is reached only by a writer + # fed from a walk of it (find -exec, xargs): counted for every unknown + # destination, `cd root && build.sh > $LOG` was refused for the first + # generated file the walk of the whole project met. + mentioned = [path for argv in stages if Path(argv[0]).name not in ("cd", "pushd") + for token in argv[1:] for path in _expand_in(scope, token)] + walked = mentioned + [path for item in list(mentioned) + for path in _children_matching(scope, item, patterns)] targets = [] for argv in stages: destinations = _shell_destinations(argv) targets += [path for item in destinations for path in _expand_in(scope, item)] + targets += _copied_into(argv) + fed = _writes_fed(argv) or any("{}" in item for item in destinations) if _opaque(argv) or any("$" in item or "{}" in item for item in destinations) or ( _writes_fed(argv) and not destinations): - targets += mentioned + targets += walked if fed else mentioned targets += _WORD_PATH.findall(" ".join(argv[1:])) return list(dict.fromkeys(targets)) +def shell_overwrite_targets(command: str, scope: RequestScope, + cwd: str | None = None) -> list[str]: + """The files a shell command writes by name: a redirection, tee, + truncate, dd of=, and the destination of cp, install, ln and rsync (a + directory's entry named after each source). A destination only decided + at run time is "$" in the result: what it reaches cannot be read.""" + if not command: + return [] + + words = _with_assignments(list(_split_stages(command))) + directories = _stage_directories(words, cwd or scope.root or ".") + found = [] + + # Scratch is no start file: /tmp, and a directory mktemp made. + + scratch = re.findall(r"\b([A-Za-z_]\w*)=[\"']?(?:\$\(mktemp\b|/tmp/)", command) + + def at_scratch(target): + return target.startswith("/tmp/") or any( + re.search(rf"(?:^|/)[\"']?\$\{{?{name}\b", target) for name in scratch) + + # Where a `cd` to a name read at run time leads is not known here: a + # patch run after it changes files that cannot be named. + + entered = "known" + + for argv, directory in zip(words, directories): + binary = Path(argv[0]).name + operands = [arg for arg in argv[1:] if not arg.startswith("-")] + + if binary in ("cd", "pushd") and operands and re.search(r"[$`]", operands[0]): + entered = "scratch" if at_scratch(operands[0]) else "unknown" + + named = [target for target in _shell_destinations(argv) + if binary not in ("rm", "rmdir", "unlink", "touch", "mkdir", "chmod", + "chown", "shred", "mv")] + + if binary in ("cp", "install", "ln", "rsync") and len(operands) >= 2: + destination = _at(directory, operands[-1]) + + if os.path.isdir(destination): + named = [target for target in named if target != operands[-1]] + found += [os.path.join(destination, os.path.basename(source.rstrip("/"))) + for source in operands[:-1]] + + for target in named: + if at_scratch(target): + continue + + found.append("$" if "$" in target or "`" in target else _at(directory, target)) + + if binary == "patch" and entered == "unknown": + found.append("$") + elif binary == "patch" and entered == "known" and not directory.startswith("/tmp"): + found += _patched_files(argv, directory) + + return list(dict.fromkeys(found)) + + +def _patched_files(argv, directory): + """The files a `patch` run changes, read from its diff: "$" when the + diff or the files cannot be read, none for a dry run.""" + if "--dry-run" in argv: + return [] + + strip, source, named = 0, "", [] + index = 1 + + while index < len(argv): + arg = argv[index] + value = argv[index + 1] if index + 1 < len(argv) else "" + + if arg in ("-d", "--directory"): + directory, index = _at(directory, value), index + 2 + continue + + if arg in ("-i", "--input", "<"): + source, index = value, index + 2 + continue + + if arg.startswith("--input="): + source = arg.split("=", 1)[1] + elif arg.startswith("--directory="): + directory = _at(directory, arg.split("=", 1)[1]) + elif re.fullmatch(r"-p\d+", arg): + strip = int(arg[2:]) + elif arg in ("-p", "--strip") and value.isdigit(): + strip, index = int(value), index + 2 + continue + elif not arg.startswith("-"): + named.append(arg) + + index += 1 + + if named: + return [_at(directory, named[0])] + + if not source or "$" in source: + return ["$"] + + try: + with open(_at(directory, source), encoding="utf-8", errors="replace") as handle: + lines = handle.read(4_000_000).splitlines() + except OSError: + return ["$"] + + found = [] + + for previous, line in zip([""] + lines, lines): + if not line.startswith("+++ ") or not previous.startswith("--- "): + continue + + name = line[4:].split("\t")[0].strip() + + if name == "/dev/null": + name = previous[4:].split("\t")[0].strip() + + parts = name.split("/")[strip:] + + if parts: + found.append(_at(directory, "/".join(parts))) + + return found + + +def shell_removal_targets(command: str, scope: RequestScope, cwd: str | None = None) -> list[str]: + """The paths a command removes by name: rm, rmdir and unlink operands, + and the start points of a find that deletes. A subset of + shell_write_targets, judged as deletions (target_policy, provenance).""" + if not command: + return [] + + words = _with_assignments(list(_split_stages(command))) + directories = _stage_directories(words, cwd or scope.root or ".") + found = [] + + for argv, directory in zip(words, directories): + name = Path(argv[0]).name + + if name in ("rm", "rmdir", "unlink"): + found += [_at(directory, arg) for arg in argv[1:] if not arg.startswith("-")] + elif name == "find" and ("-delete" in argv or any( + argv[index] == "-exec" and index + 1 < len(argv) and argv[index + 1] in ("rm", "rmdir") + for index in range(len(argv)))): + starts = [] + + for arg in argv[1:]: + if arg.startswith(("-", "(", "!")): + break + + starts.append(_at(directory, arg)) + + found += starts + + return list(dict.fromkeys(found)) + + def shell_write_refusal(command: str, scope: RequestScope | None, cwd: str | None = None) -> str: """Why this command writes outside the requested target, or "". @@ -572,12 +781,43 @@ def shell_write_refusal(command: str, scope: RequestScope | None, "(", "exec", "nohup", "env", "sudo", "command"}) +def _detach_redirections(stage: str) -> str: + """`echo P>>t` as `echo P >>t`: an unquoted `>` ends the word before it. + + Left joined, shlex hands over `P>>t` as one word and the file it writes + is never seen. A word of digits before it is the descriptor (`2>x`). + """ + out: list[str] = [] + word: list[str] = [] + quote = "" + + for char in stage: + if quote: + quote = "" if char == quote else quote + elif char in "'\"": + quote = char + elif (char == ">" and word and word[-1] not in ">&|<" + and not "".join(word).isdigit()): + out.append("".join(word) + " ") + word = [] + + if char.isspace() and not quote: + out.append("".join(word) + char) + word = [] + else: + word.append(char) + + return "".join(out) + "".join(word) + + def _split_stages(command: str): # find's `-exec ... \;` terminator is not a command separator; `+` ends # the same -exec without looking like one. command = command.replace("\\;", "+").replace("';'", "+") for stage in re.split(r"&&|\|\||[;|\n]", command): + stage = _detach_redirections(stage) + try: argv = shlex.split(stage, posix=True) except ValueError: diff --git a/client/context/workspace_context.py b/client/context/workspace_context.py index 078a0e9..e3f2897 100644 --- a/client/context/workspace_context.py +++ b/client/context/workspace_context.py @@ -91,6 +91,12 @@ def names(self) -> frozenset[str]: return frozenset(names) + @property + def project_bound(self) -> bool: + """A registered project that declares a family: a request that names + no subject is about its tree (answer_scope.of).""" + return self.registered and bool(self.project_families) + def under(self, directory: str) -> bool: """Whether this workspace's trees lie under a host directory.""" base = os.path.realpath(os.path.expanduser(directory)).rstrip("/") @@ -128,6 +134,11 @@ def _declared_standards(spec) -> tuple[tuple[str, str], ...]: return tuple(dict.fromkeys(found)) +def project_bound(*, registered: bool, spec) -> bool: + """WorkspaceContext.project_bound, before the workspace is built.""" + return bool(registered) and bool(project_families(spec)[0]) + + def from_session(*, project: str, spec: dict | None, registered: bool, project_root: str, corpus_root: str, project_commands=None, binding=None) -> WorkspaceContext: """The workspace of the current session, from what the client already knows.""" diff --git a/client/harness/attach_control.py b/client/harness/attach_control.py new file mode 100644 index 0000000..dab5e9f --- /dev/null +++ b/client/harness/attach_control.py @@ -0,0 +1,549 @@ +"""The attach mechanism's own state, and what may change it. + +A layered build attaches a component's source to a tree (linux/linux, u-boot/) +and keeps beside it what its guard reads: `.attach.sha256`, the files +it wrote, and `.attach.pf`, the recipe that owns the tree. The whole +`.attach.*` family is control-plane metadata (target_policy): the +model changes none of it, by any route. A command that does is undone here, +whatever wrote it -- a tool, git apply, a wrapped script. + +Two trusted effects maintain it instead: + +- a build (bitbake, a build driver) attaches and records, as it always did; +- after an updiff, SPEAR records the attached tree as the state the patch + series reproduces, once a clean reconstruction has shown that it does + (persistence_check.py). The build's updiff folds an edit into the series + but leaves the manifest naming the pre-edit tree, so the guard refused + every later rebuild as "not captured in the patch set", and the only exits + were the override or a hand-edited manifest. An updiff that succeeded has + only captured something: until it is verified the guard stays armed. + +A build may also remove what it owns: an object of the start state it +removes is allowed when the project itself marks it generated (under +build/tmp or generated/, ignored by the project's version control, or, in +an attached tree, absent from the files the attach wrote). Removing a +source, the attach state or anything else is a violation, reported; the +attach state is put back. +""" + +from __future__ import annotations + +import glob +import hashlib +import os +import re +import subprocess +import time + +from harness import persistence_check, provenance, target_policy + +_MANIFEST = ".attach.sha256" +_OWNER = ".attach.pf" +_PRUNED = (".pc", "patches") +_HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") + + +def is_attach_metadata(path: str) -> bool: + return bool(target_policy.attach_metadata_tree(path)) + + +# The family's files, as they stand: in every directory that held one at the +# start, the only places the attach writes them. + +def _directories() -> set[str]: + return {os.path.dirname(path) for path in provenance.start_paths() + if ".attach." in os.path.basename(path)} + + +def snapshot() -> dict[str, bytes | None]: + found: dict[str, bytes | None] = {} + + for directory in _directories(): + try: + entries = list(os.scandir(directory)) + except OSError: + continue + + for entry in entries: + if not is_attach_metadata(entry.path): + continue + + try: + with open(entry.path, "rb") as handle: + found[entry.path] = handle.read() + except OSError: + found[entry.path] = None + + return found + + +def enforce(before: dict[str, bytes | None], *, build: bool) -> list[str]: + """Undo what a command did to the attach state; the paths it changed. + + A build may write the state (it attaches); no command may remove it, and + nothing else may write it. + """ + after = snapshot() + changed = [] + + for path, content in before.items(): + if path not in after: + changed.append(path) + _put(path, content) + elif after[path] != content and not build: + changed.append(path) + _put(path, content) + + for path in after.keys() - before.keys(): + if not build: + changed.append(path) + + try: + os.remove(path) + except OSError: + pass + + return changed + + +def _put(path: str, content: bytes | None) -> None: + if content is None: + return + + try: + with open(path, "wb") as handle: + handle.write(content) + except OSError: + pass + + +# What a build removed from the start state, and whether it was its own. + +def present_start_objects() -> list[str]: + return [path for path in provenance.start_paths() if os.path.lexists(path)] + + +def removed_by(before: list[str]) -> list[str]: + return [path for path in before if not os.path.lexists(path)] + + +def build_owned(path: str) -> bool: + """Whether the project marks `path` as output a build may remove.""" + if re.search(r"/build/tmp/|/generated/", path): + return True + + tree = _attached_tree(path) + + # In an attached tree the attach's own manifest names what it wrote: + # what it did not write, a build made. What it wrote the component's own + # ignore rules may still call generated (U-Boot ships tools/lib/*.c + # wrappers and ignores them as build output). A re-attach moves the + # tree to .back. + + if tree: + relative = os.path.relpath(path, tree) + + if os.path.lexists(os.path.join(tree + ".back", relative)): + return True + + listed = _manifest_files(tree) + + if listed is not None and relative not in listed: + return True + + return _component_ignored(tree, relative) + + return _ignored(path) + + +def _attached_tree(path: str) -> str: + directory = os.path.dirname(path) + + while directory and directory != os.path.dirname(directory): + if os.path.isfile(directory + _MANIFEST): + return directory + + directory = os.path.dirname(directory) + + return "" + + +_LISTED: dict[str, set[str] | None] = {} + + +def _manifest_files(tree: str) -> set[str] | None: + if tree not in _LISTED: + try: + with open(tree + _MANIFEST, encoding="utf-8", errors="replace") as handle: + _LISTED[tree] = {line.split(" ", 1)[1].rstrip("\n").removeprefix("./") + for line in handle if " " in line} + except OSError: + _LISTED[tree] = None + + return _LISTED[tree] + + +_EMPTY_GIT: list[str] = [] + + +def _component_ignored(tree: str, relative: str) -> bool: + """Whether the attached tree's own .gitignore files ignore `relative`, + read alone: the project's rules, which ignore the whole tree, are not.""" + import tempfile + + if not _EMPTY_GIT: + directory = tempfile.mkdtemp(prefix="spear-attach-git-") + subprocess.run(["git", "init", "-q", directory], capture_output=True, check=True) + _EMPTY_GIT.append(os.path.join(directory, ".git")) + + done = subprocess.run(["git", "-c", "core.excludesFile=/dev/null", "--git-dir", _EMPTY_GIT[0], + "--work-tree", tree, "check-ignore", "-q", "--no-index", "--", relative], + capture_output=True, timeout=30) + + return done.returncode == 0 + + +def _ignored(path: str) -> bool: + directory = os.path.dirname(path) + + while directory and directory != os.path.dirname(directory): + if os.path.exists(os.path.join(directory, ".git")): + done = subprocess.run(["git", "-C", directory, "check-ignore", "-q", "--no-index", "--", + os.path.relpath(path, directory)], + capture_output=True, timeout=30) + + return done.returncode == 0 + + directory = os.path.dirname(directory) + + return False + + +def violations(removed: list[str]) -> list[str]: + """The removed objects no build owned; attach state is reported apart.""" + _LISTED.clear() + + return [path for path in removed + if not is_attach_metadata(path) and not build_owned(path)] + + +# What the persistence check starts from, pinned before a turn can reach it: +# each pristine copy, again when a build rewrites one, and the project's +# build-output rules, once. + +_PINS: dict[str, str] = {} +_RULES: dict[str, list[str]] = {} +_PIN_SCOPE: list[set[str]] = [] + + +def _pristine_copies() -> list[str]: + found = [] + + for tree, pf in _owners(): + root = _project_root(tree) + + if root: + found += glob.glob(os.path.join(root, "build/tmp/work", pf, "*.pristine")) + + return found + + +def _rules_root(tree: str) -> str: + """The project above `tree`, by its class: a start state may have built + nothing yet, so there is no build/tmp/work to find it by.""" + directory = os.path.dirname(tree) + + while directory and directory != os.path.dirname(directory): + if os.path.isfile(os.path.join(directory, persistence_check.CLASS)): + return directory + + directory = os.path.dirname(directory) + + return "" + + +def _signature(path: str) -> tuple[int, int]: + status = os.stat(path) + + return status.st_ino, status.st_ctime_ns + + +def pristine_state() -> dict[str, tuple[int, int]]: + """Each pristine copy as it stands, to tell what a build then changed.""" + found = {} + + for path in _pristine_copies(): + try: + found[path] = _signature(path) + except OSError: + pass + + return found + + +def pin_pristine(before: dict[str, tuple[int, int]] | None = None) -> None: + """Pin what a session finds when it first looks; given the state before a + build, pin what that build changed. A copy anything else changed or made + keeps its pin or has none, and fails the check.""" + directories = _directories() + first = not _PIN_SCOPE or _PIN_SCOPE[0] != directories + + if before is None and not first: + return + + _PIN_SCOPE[:] = [directories] + + if first: + _PINS.clear() + _RULES.clear() + + for root in {_rules_root(tree) for tree, _ in _owners()} - {""}: + try: + _RULES[root] = persistence_check.exclude_patterns(root) + except (OSError, ValueError, SyntaxError): + pass + + for path, signature in pristine_state().items(): + if first or before.get(path) != signature: + try: + _PINS[path] = persistence_check.tree_digest(path) + except OSError: + _PINS.pop(path, None) + + +# The trusted refresh after an updiff. + +def updiff_recipes(stages) -> list[str]: + """The recipes a command runs updiff on: `updiff.sh X`, `bitbake X -c updiff`.""" + found = [] + + for argv in stages: + name = os.path.basename(argv[0]) + + if name == "updiff.sh" and len(argv) > 1: + found.append(argv[1]) + elif name == "bitbake" and any(word in ("updiff", "do_updiff") for word in argv): + index = argv.index("-c") if "-c" in argv else -1 + found += [word for position, word in enumerate(argv[1:], 1) + if not word.startswith("-") and position != index + 1] + + return found + + +def _owners() -> list[tuple[str, str]]: + """(attached tree, recipe PF) of every tree with an owner beside it.""" + owners = [] + + for directory in _directories(): + try: + entries = list(os.scandir(directory)) + except OSError: + continue + + for entry in entries: + if entry.name.endswith(_OWNER) and os.path.isdir(entry.path[:-len(_OWNER)]): + try: + with open(entry.path, encoding="utf-8") as handle: + owners.append((entry.path[:-len(_OWNER)], handle.read().strip())) + except OSError: + continue + + return owners + + +def refresh(recipe: str, started: float) -> tuple[str, str, persistence_check.Verification | None]: + """After an updiff of `recipe`: (manifest written, why not, the check). + + UPDIFF_CAPTURED is what the log says; PERSISTENCE_VERIFIED is the check. + The manifest is written only on the second, and the check runs only on the + first: without a capture the third item is None. + """ + owners = [(tree, pf) for tree, pf in _owners() + if pf == recipe or pf.startswith(recipe + "-")] + + if len(owners) != 1: + return "", f"{len(owners)} attached trees belong to {recipe}", None + + tree, pf = owners[0] + root = _project_root(tree) + + if not root: + return "", f"no project build directory above {tree}", None + + log = os.path.join(root, "build/tmp/work", pf, "temp/log.do_updiff") + + try: + if os.path.getmtime(log) < started: + return "", "updiff did not run in this command", None + + with open(log, encoding="utf-8", errors="replace") as handle: + if re.search(r"^ERROR:", handle.read(), re.MULTILINE): + return "", "updiff reported an error", None + except OSError: + return "", "no updiff log", None + + problem = _series_problem(root, pf) + + if problem: + return "", problem, None + + check = _verify(root, tree, pf) + + if not check.verified: + return "", check.reason, check + + _write_manifest(tree) + + return tree + _MANIFEST, "", check + + +def _verify(root: str, tree: str, pf: str) -> persistence_check.Verification: + def failed(reason: str) -> persistence_check.Verification: + return persistence_check.Verification(False, reason) + + if not os.path.isfile(tree + _MANIFEST): + return failed(f"no attach manifest beside {os.path.basename(tree)}") + + copies = glob.glob(os.path.join(root, "build/tmp/work", pf, "*.pristine")) + + if len(copies) != 1: + return failed(f"{len(copies)} pristine copies for {pf}") + + if copies[0] not in _PINS: + return failed(f"the pristine copy of {pf} was never pinned") + + if root not in _RULES: + return failed("the project's build-output rules were not readable") + + patch_dir, listed = _series(root, pf) + + return persistence_check.verify(tree, copies[0], _PINS[copies[0]], _RULES[root], + patch_dir, listed) + + +def _project_root(tree: str) -> str: + directory = os.path.dirname(tree) + + while directory and directory != os.path.dirname(directory): + if os.path.isdir(os.path.join(directory, "build/tmp/work")): + return directory + + directory = os.path.dirname(directory) + + return "" + + +def _series(root: str, pf: str) -> tuple[str, list[str]]: + """The patch directory of `pf` and the patches its series lists, in order.""" + patch_dir = glob.glob(os.path.join(root, "build", "*", "recipes-*", "*", "files", f"0001-{pf}"))[0] + + with open(patch_dir + "-patches.inc", encoding="utf-8", errors="replace") as handle: + return patch_dir, re.findall(r"file://([^\s\\\"']+\.patch)", handle.read()) + + +def _series_problem(root: str, pf: str) -> str: + """Why the patch series of `pf` is not one the attach can apply, or "".""" + patchsets = glob.glob(os.path.join(root, "build", "*", "recipes-*", "*", "files", f"0001-{pf}")) + + if len(patchsets) != 1: + return f"{len(patchsets)} patch sets for {pf}" + + series = patchsets[0] + "-patches.inc" + + try: + with open(series, encoding="utf-8", errors="replace") as handle: + text = handle.read() + except OSError: + return f"no series file for {pf}" + + # A parameter (;striplevel=, ;patchdir=) changes how a patch applies, and + # the check applies every patch alike. + + if re.search(r"\.patch;", text): + return f"the series of {pf} carries patch parameters" + + for name in re.findall(r"file://([^\s\\\"']+\.patch)", text): + path = os.path.join(patchsets[0], name) + + try: + with open(path, encoding="utf-8", errors="replace") as handle: + problem = _patch_problem(handle.read()) + except OSError: + return f"{name} is listed but missing" + + if problem: + return f"{name}: {problem}" + + return "" + + +def _patch_problem(text: str) -> str: + """A hunk whose lines disagree with its header, or no hunk at all.""" + lines = text.split("\n") + hunks = 0 + index = 0 + + while index < len(lines): + found = _HUNK.match(lines[index]) + index += 1 + + if not found: + continue + + hunks += 1 + old = int(found.group(2) if found.group(2) is not None else 1) + new = int(found.group(4) if found.group(4) is not None else 1) + + while (old > 0 or new > 0) and index < len(lines): + line = lines[index] + index += 1 + + if line.startswith("\\"): + continue + + if line.startswith(" ") or line == "": + old, new = old - 1, new - 1 + elif line.startswith("-"): + old -= 1 + elif line.startswith("+"): + new -= 1 + else: + return f"hunk {hunks} ends early" + + if old or new: + return f"hunk {hunks} disagrees with its header" + + return "" if hunks else "no hunk" + + +def _write_manifest(tree: str) -> None: + """The manifest the attach task writes: every regular file under the + tree, .pc and patches pruned, sorted bytewise, `sha256 ./path`.""" + files = [] + + for directory, subdirectories, names in os.walk(tree): + subdirectories[:] = [name for name in subdirectories if name not in _PRUNED] + + for name in names: + path = os.path.join(directory, name) + + if name not in _PRUNED and os.path.isfile(path) and not os.path.islink(path): + files.append("./" + os.path.relpath(path, tree)) + + lines = [] + + for relative in sorted(files, key=lambda item: item.encode("utf-8", "surrogateescape")): + digest = hashlib.sha256() + + with open(os.path.join(tree, relative), "rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + + lines.append(f"{digest.hexdigest()} {relative}\n") + + with open(tree + _MANIFEST, "w", encoding="utf-8", errors="surrogateescape") as handle: + handle.writelines(lines) + + +def now() -> float: + return time.time() diff --git a/client/harness/command_policy.py b/client/harness/command_policy.py index 0715fab..3ec2936 100644 --- a/client/harness/command_policy.py +++ b/client/harness/command_policy.py @@ -14,6 +14,7 @@ from pathlib import Path from typing import AbstractSet, Callable, Sequence +from harness import control_overrides, target_policy from harness.tool_primitives import ( DEFAULT_CAPABILITY_POLICY, Capability, @@ -25,6 +26,11 @@ from harness.workspace import SandboxSpec, Workspace, effective_mount_root +# A redirection that duplicates a descriptor: `>&2`, the `>&1` of `2>&1`. + +_FD_DUPLICATE = re.compile(r"[<>]&(?:\d+|-)(?![\w./])") + + @dataclass(frozen=True) class CommandAssessment: command: str @@ -72,6 +78,8 @@ class CommandPolicy: # Matches -i, -i.bak, -ni and --in-place[=SUFFIX]. _SED_IN_PLACE = re.compile(r"^(--in-place|-[a-hj-zA-Z]*i)") + _SHELL_EDITORS = frozenset({"ed", "red", "ex", "vi", "vim", "nvim", "view", "vimdiff", + "emacs", "nano", "pico", "joe", "mcedit"}) GIT_READ_ONLY = frozenset({ "status", "log", "diff", "show", "branch", "ls-files", "blame", "describe", "rev-parse", "reflog", @@ -109,8 +117,27 @@ class CommandPolicy: "sudo", "su", "doas", "rm", "mv", "dd", "mkfs", "mount", "umount", "chmod", "chown", "kill", "pkill", "shutdown", "reboot", "rsync", "python", "python3", "bash", "sh", "zsh", "fish", "env", + "dash", "ash", "ksh", "mksh", "csh", "tcsh", "busybox", "pypy", "pypy3", + "perl", "ruby", "node", "nodejs", "php", "lua", "tclsh", "Rscript", }) + # Every interpreter is one program whatever its version: refused as + # `python3`, `python3.12` ran the same script unjudged. + + _VERSIONED_INTERPRETER = re.compile( + r"(?:python|pypy|perl|ruby|lua|php|tclsh|node)\d[\d.]*") + + # An awk program that starts a command runs what this cannot read. + + _AWK_BINS = frozenset({"awk", "gawk", "mawk", "nawk"}) + _AWK_RUNS = re.compile(r"\bsystem\s*\(|\|\s*\"|\"\s*\|\s*getline|\|&") + + # find's actions: -exec and -ok run a command, judged as that command; + # the others write or delete themselves. + + _FIND_RUNS = frozenset({"-exec", "-execdir", "-ok", "-okdir"}) + _FIND_WRITES = frozenset({"-delete", "-fprint", "-fprint0", "-fprintf", "-fls"}) + # Builtins carry no capability of their own: `cd` and `.` act through the # stage that follows them, and treating them as unknown programs would ask # for write on every pipeline that merely changes directory. @@ -122,6 +149,12 @@ class CommandPolicy: CONTAINER_BINS = frozenset({"docker", "podman"}) GPU_BINS = frozenset({"nvidia-smi"}) GIT_NETWORK_WRITE = frozenset({"clone", "fetch", "pull"}) + + # The git commands that keep their own repository's records as they work: + # the index, the stash, HEAD. What they change in the worktree is judged + # like any other write. + + GIT_LOCAL_WRITE = frozenset({"add", "restore", "checkout", "switch", "stash", "clean"}) GIT_NETWORK_ONLY = frozenset({"push"}) _SHELL_SYNTAX = re.compile(r"[|&;<>`$()\n]") @@ -520,7 +553,10 @@ def _simple_capabilities( return frozenset({Capability.FILESYSTEM_READ, Capability.WORKSPACE_WRITE}) if binary == "git": - subcommand = self._git_subcommand(argv) + subcommand = (self.git_command(argv) or ("", ()))[0] + + if subcommand in self.GIT_LOCAL_WRITE: + return frozenset({Capability.FILESYSTEM_READ, Capability.WORKSPACE_WRITE}) if subcommand in self.GIT_NETWORK_WRITE: return frozenset({ @@ -555,21 +591,6 @@ def _simple_capabilities( return frozenset() - # Global git options that take their value as the next argument. - - _GIT_VALUE_OPTIONS = frozenset({"-C", "-c", "--git-dir", "--work-tree", - "--namespace", "--exec-path"}) - - @classmethod - def _git_subcommand(cls, argv: Sequence[str]) -> str: - """The subcommand, past git's own options: `git -C dir status`.""" - index = 1 - - while index < len(argv) and argv[index].startswith("-"): - index += 2 if argv[index] in cls._GIT_VALUE_OPTIONS else 1 - - return argv[index] if index < len(argv) else "" - @staticmethod def _curl_remote_write(argv: Sequence[str]) -> bool: """Recognize common explicit Curl request bodies/methods, not all syntax.""" @@ -627,10 +648,184 @@ def _is_known_binary(self, binary: str) -> bool: or binary in self.SSH_BINS or binary in self.CONTAINER_BINS or binary in self.GPU_BINS - or binary in self.DANGEROUS_BINS + or self._runs_code(binary) or binary in self.SHELL_BUILTINS or binary == "git") + def _runs_code(self, binary: str) -> bool: + """Whether `binary` is refused as what it runs: a privileged, removing + or interpreting program.""" + return binary in self.DANGEROUS_BINS or bool(self._VERSIONED_INTERPRETER.fullmatch(binary)) + + @classmethod + def _syntax_check(cls, argv: Sequence[str]) -> bool: + """`bash -n script`: the shell reads the script and runs none of it.""" + options = [arg for arg in argv[1:] if arg.startswith("-")] + operands = [arg for arg in argv[1:] if not arg.startswith("-")] + + return (Path(argv[0]).name in cls._SCRIPT_SHELLS and len(operands) == 1 + and argv[1].startswith("-") and len(options) == len(argv) - 2 + and all(re.fullmatch(r"-[eunx]+", option) for option in options) + and any("n" in option for option in options)) + + def _stage_danger(self, argv: Sequence[str], depth: int) -> str: + """Why one stage may not run whatever wraps it, or "". + + The rules that judge what a program does rather than what it names: + an interpreter, an awk program that starts a command, and find's + actions. The same answer for a command alone and inside a script. + """ + binary = Path(argv[0]).name + + if self._syntax_check(argv): + return "" + + if not self._is_module_test_run(argv) and ( + self._runs_code(binary) + or ("/" in argv[0] and not self._is_workspace_program(argv[0]))): + if binary in self._PYTHON_BINS or self._VERSIONED_INTERPRETER.fullmatch(binary): + return f"{self._PYTHON_HINT} — so this command cannot run." + + if binary in self._SCRIPT_SHELLS: + return (f"'{binary}' running a script file runs commands this cannot " + f"judge as written, so it is not allowlisted: run them as " + f"commands.") + + return (f"'{argv[0]}' is not allowlisted, so the pipeline that " + f"contains it cannot run.") + + if binary in self._AWK_BINS and any(self._AWK_RUNS.search(arg) for arg in argv[1:]): + return "an awk program that starts a command runs what this cannot read." + + if binary == "find": + if any(arg in self._FIND_WRITES for arg in argv[1:]): + return "mutating find action" + + for index, arg in enumerate(argv): + if arg not in self._FIND_RUNS: + continue + + inner = [] + + for word in argv[index + 1:]: + if word in (";", "+"): + break + + if word != "{}": + inner.append(word) + + if not inner: + return f"find {arg} without a command" + + if depth >= self._MAX_UNWRAP: + return "commands nested this deep cannot be read." + + found = self._stage_danger(inner, depth + 1) + + if found: + return found + + return "" + + # Session cleanup (provenance.py): a command that only removes named + # objects may run when every one of them was created in this session. + # The shape is read here, the objects are judged where the command's + # directory is known. Anything this cannot read literally -- a variable, + # a glob, a substitution, another program -- leaves the command refused. + + _REMOVERS = frozenset({"rm", "rmdir", "unlink"}) + _REMOVE_OPTION = re.compile(r"-[rRfvd]+|--(?:recursive|force|verbose|dir)") + _BESIDE_CLEANUP = frozenset({"ls", "echo", "true", "false", "test", "[", "pwd", "stat", + "cat", "head", "tail", "wc", "du"}) + _FIND_VALUED = frozenset({"-name", "-iname", "-path", "-ipath", "-type", "-maxdepth", + "-mindepth"}) + _UNREAD = re.compile(r"[$`*?\[\]{}~]") + + def cleanup_plan(self, command: str) -> "list[tuple[str, tuple[str, ...], bool]] | None": + """[(kind, words, recursive)] when `command` only removes named objects. + + Kinds: "cd" (words: the directory) and "remove" (words: the objects; + recursive for -r and for find's -delete and -exec rm, whose start + points are removed in full). None for anything else. + """ + command = re.sub(r"(?:^|\s)\d*(?:>>?\s*/dev/null|>&\d)(?=\s|$|[;&|])", " ", command or "") + + if not command.strip() or re.search(r"[$`<>]", command): + return None + + plan = [] + + for argv in self.stage_argvs(command): + name = argv[0] + + if name == "cd" and len(argv) == 2 and not self._UNREAD.search(argv[1]): + plan.append(("cd", (argv[1],), False)) + elif name in self._REMOVERS: + options = [arg for arg in argv[1:] if arg.startswith("-") and arg != "--"] + operands = [arg for arg in argv[1:] if not arg.startswith("-")] + + if (not operands or not all(self._REMOVE_OPTION.fullmatch(arg) for arg in options) + or any(self._UNREAD.search(arg) for arg in operands)): + return None + + plan.append(("remove", tuple(operands), + any(re.search(r"[rR]|recursive", arg) for arg in options))) + elif name == "find": + found = self._find_removal(argv) + + if found is None: + return None + + if found: + plan.append(("remove", found, True)) + elif name not in self._BESIDE_CLEANUP: + return None + + return plan if any(kind == "remove" for kind, _, _ in plan) else None + + def _find_removal(self, argv: Sequence[str]) -> "tuple[str, ...] | None": + """find's start points when it deletes, () when it only lists, None + when its expression is not one read here.""" + index = 1 + + while index < len(argv) and not argv[index].startswith(("-", "(", "!")): + index += 1 + + starts, expression = tuple(argv[1:index]), list(argv[index:]) + removes = False + + if any(self._UNREAD.search(start) for start in starts): + return None + + while expression: + word = expression.pop(0) + + if word in self._FIND_VALUED and expression: + expression.pop(0) + elif word in ("-delete",): + removes = True + elif word in ("-print", "-depth", "-xdev"): + continue + elif word == "-exec" and expression and expression[0] in self._REMOVERS: + command = [] + + while expression and expression[0] not in (";", "+"): + command.append(expression.pop(0)) + + if not expression or not all(self._REMOVE_OPTION.fullmatch(arg) or arg == "{}" + for arg in command[1:]): + return None + + expression.pop(0) + removes = True + else: + return None + + if removes and not starts: + return None + + return starts if removes else () + def _sensitive_classification( self, argv: Sequence[str] ) -> CommandClassification: @@ -647,6 +842,12 @@ def _sensitive_classification( return CommandClassification.READ_ONLY + # A literal assignment: `F=x`, `F='x'`. A value built from a substitution + # is not known before the command runs. + + _LITERAL_ASSIGNMENT = re.compile( + r"(?:^|[\s;&|(])([A-Za-z_]\w*)=(?:'([^']*)'|\"([^\"$`]*)\"|([^\s;&|()<>'\"$`]*))") + @classmethod def _writes_via_redirection(cls, command: str) -> bool: """True when a redirection actually creates or extends a file. @@ -654,23 +855,44 @@ def _writes_via_redirection(cls, command: str) -> bool: `2>/dev/null` is a redirection that writes nothing, and demanding workspace:write for it made every read-only pipeline carrying the idiom unavailable in SAFE — the mode where searching a tree is the whole - point. + point. Nor do `2>&1` and `>&2`, which only duplicate a descriptor: read + as writes, they handed `git apply x 2>&1` a writable tree. + + A destination held in a variable is the value the command assigned it, + when that value is literal. Otherwise nothing says what it is, and it + earns no write: the tree stays read-only and the write fails there. """ + return any(not target.startswith("$") for target in cls._redirect_targets(command)) - for match in re.finditer(r"(?{1,2}\s*(&\d+|&-|[^\s;|&()]*)", - command): - target = match.group(1) + @classmethod + def _redirect_targets(cls, command: str) -> "list[str]": + """The files the redirections of `command` write, sinks set aside. - # `2>&1` duplicates a descriptor and `2>&-` closes one: neither - # names a file. The target also stops at a control operator, so - # `2>/dev/null;` is the sink it reads as. + A variable destination is its literal value; one with no literal + value is returned as written, starting with `$`. + """ + values = {match.group(1): next(group for group in match.groups()[1:] if group is not None) + for match in cls._LITERAL_ASSIGNMENT.finditer(command)} + found = [] - if target.startswith("&") or target in cls._REDIRECT_SINKS: + for match in re.finditer(r"(?{1,2}\|?(&?)\s*([^\s;|&()<>]*)", command): + duplicate, target = match.groups() + + if duplicate and re.fullmatch(r"\d+|-", target): continue - return True + variable = re.match(r"\$(?:\{(\w+)\}|(\w+))", target) - return False + if variable: + name = variable.group(1) or variable.group(2) + + if name in values: + target = values[name] + target[variable.end():] + + if target not in cls._REDIRECT_SINKS: + found.append(target) + + return found _HEREDOC_RE = re.compile(r"<<-?\s*([\'\"]?)([A-Za-z_][\w-]*)\1") @@ -696,7 +918,9 @@ def _strip_heredoc_bodies(cls, command: str) -> str: proposing to paste the file by hand. Bodies that feed an interpreter are kept, because there the body is - commands and dropping it would hide them from the danger scan. + commands and dropping it would hide them from the danger scan. A + dropped body takes its closing delimiter with it: on a line of its + own, the word would read as a program. """ lines = command.split("\n") kept: list[str] = [] @@ -715,9 +939,7 @@ def _strip_heredoc_bodies(cls, command: str) -> str: while index < len(lines) and lines[index].strip() != delimiter: index += 1 - if index < len(lines): - kept.append(lines[index]) - index += 1 + index += 1 return "\n".join(kept) @@ -744,19 +966,35 @@ def _shell_stages(command: str) -> "list[str]": cannot run", about a path the command never named. The same flaw makes ``grep 'foo(bar)' file`` -- an everyday idiom -- look like a pipeline. + A process substitution `<(cmd)` is a stage of its own, opened by "<(" + and closed by ")<": what follows it is more of the command around it, + its operands (`diff <(git show HEAD:a.c) a.c`), not a program. + Returns text and separators interleaved, the shape re.split produced. """ parts: list[str] = [] current: list[str] = [] quote = "" index, length = 0, len(command) + opened: list[bool] = [] while index < length: char = command[index] + # Inside double quotes a backslash still escapes: `"a \" ; b"` is + # one word. Read as the closing quote, `\"` let the `;` after it + # split a `python3 -c "..."` program into stages, none of which + # was the interpreter. + if quote: current.append(char) + if quote == '"' and char == "\\" and index + 1 < length: + current.append(command[index + 1]) + index += 2 + + continue + if char == quote: quote = "" @@ -764,6 +1002,15 @@ def _shell_stages(command: str) -> "list[str]": continue + # A `#` that starts a word starts a comment, to the end of the + # line: its apostrophes open no quote. + + if char == "#" and (not current or current[-1] in " \t"): + end = command.find("\n", index) + index = length if end < 0 else end + + continue + if char in "'\"": quote = char current.append(char) @@ -786,7 +1033,43 @@ def _shell_stages(command: str) -> "list[str]": continue - if char in "|;&()<>": + # `2>&1` and `>&2` duplicate a descriptor and name no file: they + # stay inside the word, or the `1` reads as a program. + + duplicate = _FD_DUPLICATE.match(command, index) + + if duplicate: + current.append(duplicate.group(0)) + index = duplicate.end() + + continue + + # A newline ends a command as `;` does: `cat > x <" and command[index + 1:index + 2] == "(": + parts.append("".join(current)) + parts.append(command[index:index + 2]) + opened.append(True) + current = [] + index += 2 + + continue + + if char in "()": + substitution = char == ")" and bool(opened) and opened.pop() + + if char == "(": + opened.append(False) + + parts.append("".join(current)) + parts.append(")<" if substitution else char) + current = [] + index += 1 + + continue + + if char in "|;&<>\n": parts.append("".join(current)) parts.append(char) current = [] @@ -801,6 +1084,79 @@ def _shell_stages(command: str) -> "list[str]": return parts + @staticmethod + def _substitutions(command: str) -> "list[str] | None": + """The commands substituted where the stages cannot see them. + + A `$(...)` outside quotes splits into stages of its own; one inside + double quotes, and any backquoted one, does not, and ran unjudged: + `echo "$(rm -rf src)"`. Their bodies, or None when one is not closed. + """ + bodies: list[str] = [] + quote = "" + index, length = 0, len(command) + + while index < length: + char = command[index] + + if quote == "'": + quote = "" if char == "'" else quote + index += 1 + + continue + + if char == "\\": + index += 2 + + continue + + if char == "`": + end = index + 1 + + while end < length and command[end] != "`": + end += 2 if command[end] == "\\" else 1 + + if end >= length: + return None + + bodies.append(command[index + 1:end].replace("\\`", "`")) + index = end + 1 + + continue + + if quote == '"' and command.startswith("$(", index) \ + and not command.startswith("$((", index): + depth, end, inner = 1, index + 2, "" + + while end < length and depth: + if inner: + inner = "" if command[end] == inner else inner + elif command[end] == "\\": + end += 1 + elif command[end] in "'\"": + inner = command[end] + elif command[end] == "(": + depth += 1 + elif command[end] == ")": + depth -= 1 + + end += 1 + + if depth: + return None + + bodies.append(command[index + 2:end - 1]) + index = end + + continue + + if char in "'\"" and not (quote == '"' and char == "'"): + quote = "" if quote == char else char + + index += 1 + + return bodies + # Reserved words that introduce a command inside a compound one, and the # ones that only close it. @@ -842,7 +1198,7 @@ def _past_shell_keywords(cls, argv: "tuple[str, ...]") -> "tuple[str, ...]": return argv def _shell_capabilities( - self, command: str + self, command: str, depth: int = 0 ) -> "tuple[frozenset[Capability], str, list[str], str]": """Best-effort stage analysis; this intentionally is not a shell parser. @@ -876,6 +1232,24 @@ def _shell_capabilities( danger = "" + substituted = self._substitutions(command) + + if substituted is None: + danger = "a command substitution is not closed, so what it runs cannot be read." + substituted = [] + + for body in substituted: + if depth >= self._MAX_UNWRAP: + danger = danger or "substitutions nested this deep cannot be read." + break + + found, inner_danger, inner_outside, inner_refusal = self._shell_capabilities( + self._strip_heredoc_bodies(body), depth + 1) + capabilities.update(found) + danger = danger or inner_danger + refusal = refusal or inner_refusal + outside.extend(path for path in inner_outside if path not in outside) + # `2>&1` names no file and no program. Left in, the stage splitter # cuts it at `>` and `&` and reads the trailing `1` as a command, # which no allowlist knows and which therefore asked for write. @@ -884,6 +1258,7 @@ def _shell_capabilities( stdin_from_pipeline = False redirect_target = False redirect_reads = False + operands_only = False for stage in stages: token = stage.strip() @@ -891,8 +1266,9 @@ def _shell_capabilities( if not token: continue - if token in {"|", "||", "&&", ";", "&", "(", ")", "<", ">"}: + if token in self._SEPARATORS: stdin_from_pipeline = token == "|" + operands_only = token == ")<" # `<` and `>` introduce a FILE, not a command. Analysing the # next token as a command stage made `2>/dev/null` hit the @@ -920,11 +1296,21 @@ def _shell_capabilities( and (target.startswith("/") or target.startswith("../") or "/../" in target or target == "..")) + # A relative `..` is judged as the traversal rule judges any + # operand: where the command stands is not known here, so + # neither is where it leads. Called a write, an input `< + # ../x.patch` read to the model as a refusal of something it + # never asked for. + if escapes: if redirect_reads and target.startswith("/"): found, denied = self._outside_reads([target]) refusal = refusal or denied outside.extend(p for p in found if p not in outside) + elif not target.startswith("/"): + danger = danger or ( + f"relative path leaves the workspace: '{target}' — " + f"name it by absolute path instead.") else: danger = danger or ( f"a redirection would write outside the workspace: " @@ -939,9 +1325,24 @@ def _shell_capabilities( if not token: continue + # A stage whose quoting does not close cannot be read, and what + # cannot be read does not run. + try: argv = tuple(shlex.split(token, posix=True)) except ValueError: + danger = danger or (f"its quoting cannot be read ({token[:40]!r}): " + f"close every quote, or write the text with write_file.") + continue + + # After a process substitution, the words are the operands of the + # command around it: checked as paths, never run. + + if operands_only: + operands_only = False + found, denied = self._outside_reads(list(argv)) + refusal = refusal or denied + outside.extend(path for path in found if path not in outside) continue # `VAR=value cmd` runs cmd: the assignments are its environment, @@ -953,6 +1354,38 @@ def _shell_capabilities( if not argv: continue + argv, script, unreadable = self._peeled(argv, token) + + if unreadable: + danger = danger or (f"{unreadable}: what it would run cannot be read here, so " + f"the pipeline that contains it cannot run.") + continue + + if script is not None: + if depth >= self._MAX_UNWRAP: + danger = danger or "shells nested this deep cannot be read." + continue + + inner, inner_danger, inner_outside, inner_refusal = self._shell_capabilities( + self._strip_heredoc_bodies(script), depth + 1) + capabilities.update(inner) + danger = danger or inner_danger + refusal = refusal or inner_refusal + outside.extend(path for path in inner_outside if path not in outside) + stdin_from_pipeline = False + continue + + if not argv: + continue + + # In a script handed to a shell, a program that is an expansion + # runs what it expands to, unseen. + + if depth and argv[0].startswith("$"): + danger = danger or (f"'{argv[0]}' runs a program this cannot read, so the " + f"pipeline that contains it cannot run.") + continue + binary = Path(argv[0]).name # The in-place sed rule lives in the single-command classifier, so @@ -972,14 +1405,15 @@ def _shell_capabilities( "existing surrounding line(s) as old_text and those same " "lines plus the new one as new_text.") - if not self._is_module_test_run(argv) and ( - binary in self.DANGEROUS_BINS or ( - "/" in argv[0] and not self._is_workspace_program(argv[0]))): + # An editor run from the shell edits in place as `sed -i` does: + # `printf '1a\nX\n.\nw\n' | ed -s f` wrote what sed -i was refused. + + if binary in self._SHELL_EDITORS: danger = danger or ( - f"{self._PYTHON_HINT} — so this command cannot run." - if binary in self._PYTHON_BINS else - f"'{argv[0]}' is not allowlisted, so the pipeline that " - f"contains it cannot run.") + f"'{binary}' edits files in place, outside the checkpoint, so its " + f"change cannot be rolled back: use edit_file.") + + danger = danger or self._stage_danger(argv, depth) stage_caps = self._simple_capabilities( argv, stdin_from_pipeline=stdin_from_pipeline) @@ -1012,6 +1446,363 @@ def _shell_capabilities( return frozenset(capabilities), danger, outside, refusal + _STAGE_KEYWORDS = frozenset({"do", "then", "else", "elif", "!", "{"}) + + _SEPARATORS = frozenset({"|", "||", "&&", ";", "&", "(", ")", "<", ">", "<(", ">(", ")<"}) + + # Launchers run the command they are handed, and that command is what is + # judged: wrapped, it keeps the authority it has alone and gains none. + # A shell's -c hands over a script, judged as a script; xargs runs its + # command with operands read at run time. A launcher whose options are + # not read here runs something unseen, and is refused. + + _LAUNCHER_OPTIONS = { + "timeout": ({"--preserve-status", "--foreground", "-v", "--verbose"}, + ("-s", "--signal", "-k", "--kill-after")), + "nice": (set(), ("-n", "--adjustment")), + "env": ({"-i", "--ignore-environment"}, ("-u", "--unset")), + "nohup": (set(), ()), + "exec": ({"-c", "-l", "-cl", "-lc"}, ("-a",)), + "command": ({"-p"}, ()), + "time": ({"-p"}, ()), + "xargs": ({"-0", "--null", "-r", "--no-run-if-empty", "-t", "--verbose", "-x", + "--exit", "-o", "--open-tty"}, + ("-n", "--max-args", "-L", "--max-lines", "-P", "--max-procs", "-s", + "--max-chars", "-d", "--delimiter", "-E", "-a", "--arg-file", "-I", + "--replace")), + } + _LAUNCHERS = frozenset(_LAUNCHER_OPTIONS) + _SCRIPT_SHELLS = frozenset({"bash", "sh", "dash", "ash", "ksh", "mksh", "zsh"}) + _MAX_UNWRAP = 4 + _DURATION = re.compile(r"\d+(?:\.\d+)?[smhd]?") + _DUPLICATION = re.compile(r"\d*[<>]&(?:\d+|-)") + + def _launched(self, argv: Sequence[str], raw: str = "") -> "tuple[str, object]": + """What one stage runs: ("argv", argv), ("script", text), or ("", why). + + A stage that launches nothing comes back unchanged, as does a launcher + given nothing to run (`env` alone prints the environment). + """ + name, rest = argv[0], list(argv[1:]) + + if name in self._SCRIPT_SHELLS: + return self._shell_script(argv, raw) + + if name not in self._LAUNCHERS: + return "argv", tuple(argv) + + flags, valued = self._LAUNCHER_OPTIONS[name] + + while rest and rest[0].startswith("-") and rest[0] != "-": + option = rest.pop(0) + + if option == "--": + break + + if name == "command" and option in ("-v", "-V"): + return "argv", tuple(argv) + + if option in valued and rest: + rest.pop(0) + elif not (option in flags + or any(option.startswith(long + "=") for long in valued if long[1] == "-") + or any(option.startswith(short) for short in valued if short[1] != "-") + or (name == "nice" and re.fullmatch(r"-\d+", option))): + return "", f"{name} {option}" + + if name == "timeout": + if not rest or not self._DURATION.fullmatch(rest[0]): + return "", "timeout without a duration" + + rest.pop(0) + + while name == "env" and rest and self._ASSIGNMENT.match(rest[0]): + rest.pop(0) + + return "argv", tuple(rest) if rest else tuple(argv) + + def _shell_script(self, argv: Sequence[str], raw: str = "") -> "tuple[str, object]": + """The script of `bash -c SCRIPT`; any other use of the shell unchanged. + + Options are the inert ones only: -e, -u, -x, -o pipefail. Words after + the script would become its $0, $1..., which the script then runs + unseen, so they are refused. So is an expansion the outer shell makes + inside the script: `bash -c "$(cat x)"` runs what x holds. In single + quotes (`raw`, the stage as written, shows them) the script reaches + the inner shell as it reads here. + """ + rest = list(argv[1:]) + script = None + + while rest: + option = rest.pop(0) + + if option in ("-o", "+o") and rest and rest[0] in ("pipefail", "errexit", "nounset", + "xtrace"): + rest.pop(0) + continue + + if not re.fullmatch(r"-[euxc]+", option): + return "argv", tuple(argv) + + if "c" in option: + if not rest: + return "", f"{argv[0]} -c without a script" + + script = rest.pop(0) + break + + if script is None: + return "argv", tuple(argv) + + if rest: + return "", f"{argv[0]} -c with arguments for its script" + + if re.search(r"[$`]", script) and f"'{script}'" not in raw: + return "", (f"{argv[0]} -c with a script the outer shell expands (single quotes " + f"pass it as written)") + + return "script", script + + def _peeled(self, argv: Sequence[str], raw: str = "") -> "tuple[tuple[str, ...], str | None, str]": + """(argv, script, unreadable) of one stage, its launchers taken off. + + A descriptor duplication (`2>&1`) stays in its stage's words and is + no argument of the command. + """ + argv = tuple(word for index, word in enumerate(argv) + if index == 0 or not self._DUPLICATION.fullmatch(word)) + + for _ in range(self._MAX_UNWRAP): + kind, value = self._launched(argv, raw) + + if not kind: + return argv, None, value + + if kind == "script": + return argv, value, "" + + if value == argv: + break + + argv = value + + while argv and self._ASSIGNMENT.match(argv[0]): + argv = argv[1:] + + if not argv: + break + + return argv, None, "" + + def unwrapped(self, argv: Sequence[str], depth: int = 0, + raw: str = "") -> "list[tuple[str, ...]]": + """The argvs one stage really runs, launchers taken off. + + An unreadable launcher is kept as it is, so that whatever asks about + builds or git finds no build and no git in it. + """ + peeled, script, unreadable = self._peeled(argv, raw) + + if unreadable: + return [tuple(argv)] + + if script is not None: + return self.stage_argvs(script, depth + 1) if depth < self._MAX_UNWRAP else [tuple(argv)] + + return [peeled] if peeled else [] + + def stage_argvs(self, command: str, depth: int = 0) -> "list[tuple[str, ...]]": + """The argv each stage of `command` runs, environment prefixes and + launchers set aside.""" + found = [] + redirect_target = False + operands_only = False + + for part in self._shell_stages(self._strip_heredoc_bodies(command or "")): + if part.strip() in self._SEPARATORS: + redirect_target = part.strip() in {"<", ">"} + operands_only = part.strip() == ")<" + continue + + if operands_only: + operands_only = False + continue + + try: + argv = tuple(shlex.split(part, posix=True)) + except ValueError: + continue + + # What follows `>` or `<` is its file; the rest of the fragment + # is the command that continues. + + if redirect_target and argv: + argv = argv[1:] + redirect_target = False + + # A descriptor duplication left after a `$(...)` is no program. + + while argv and (self._ASSIGNMENT.match(argv[0]) + or argv[0] in self._STAGE_KEYWORDS + or self._DUPLICATION.fullmatch(argv[0])): + argv = argv[1:] + + if argv: + found.extend(self.unwrapped(argv, depth, part)) + + return found + + # What builds or tests: the build tools and test runners the policy lets + # write, BitBake, and a project's own build drivers: its build script, + # its configure step, and a BitBake layer's updiff.sh, which regenerates a + # recipe's patch series from its unpacked tree. + + BUILD_BINS = (WORKSPACE_MUTATING_BINS - {"tee"}) | frozenset({ + "gmake", "meson", "scons", "ctest", "bitbake"}) + _BUILD_SCRIPT = re.compile( + r"(?:^|[-_])build(?:[-_][\w-]*)?\.sh$|^configure$|^autogen\.sh$|^updiff\.sh$") + + # What may run beside a build without taking its authority: what writes + # no file. `tee` qualifies for a file outside the generated trees. + + _BESIDE_A_BUILD = SHELL_BUILTINS | READ_ONLY_BINS | frozenset({ + "printf", "nproc", "sleep", "wait", "date", "uname"}) + _OUTPUT_PATH = re.compile(r"(?:^|/)(?:generated|build/tmp)(?:/|$)") + + def _writes_output(self, path: str) -> bool: + return (path.startswith("$") or bool(self._OUTPUT_PATH.search(path)) + or target_policy.is_snapshot(path)) + + def builds(self, command: str) -> bool: + """Whether `command` builds or tests: its output is the build's to write. + + The authority is the build's alone. Every other stage must write + nothing, and no redirection may write into a generated tree: a + command beside a build, or a launcher around one, gains nothing from + it (stage_argvs judges what a launcher runs). + """ + found = False + + for argv in self.stage_argvs(command): + name = Path(argv[0]).name + + if (name in self.BUILD_BINS or self._is_module_test_run(argv) + or self._BUILD_SCRIPT.search(name)): + found = True + elif argv[0] == "tee": + if any(self._writes_output(arg) for arg in argv[1:] if not arg.startswith("-")): + return False + elif argv[0] not in self._BESIDE_A_BUILD: + return False + + return found and not any(self._writes_output(target) + for target in self._redirect_targets(command)) + + # Global options that leave git where it is and reading what it reads. + + _GIT_PLAIN_OPTIONS = frozenset({ + "--no-pager", "-P", "-p", "--paginate", "--no-optional-locks", "--literal-pathspecs", + "--glob-pathspecs", "--noglob-pathspecs", "--icase-pathspecs", "--no-replace-objects", + "--no-lazy-fetch", "--no-advice"}) + + def git_command(self, argv: Sequence[str]) -> "tuple[str, tuple[str, ...]] | None": + """(subcommand, the -C directories in order) of a git argv. + + None when a global option sends git somewhere else or runs something + of its own: -c, --git-dir, --work-tree, --exec-path, --namespace... + """ + directories: list[str] = [] + index = 1 + + while index < len(argv) and argv[index].startswith("-"): + option = argv[index] + + if option == "-C" and index + 1 < len(argv): + directories.append(argv[index + 1]) + index += 2 + elif option in self._GIT_PLAIN_OPTIONS: + index += 1 + else: + return None + + return (argv[index] if index < len(argv) else ""), tuple(directories) + + def writes_git(self, command: str) -> bool: + """Whether `command` runs a git command that writes a repository's records.""" + return any(argv[0] == "git" + and (self.git_command(argv) or ("", ()))[0] in (self.GIT_NETWORK_WRITE + | self.GIT_LOCAL_WRITE) + for argv in self.stage_argvs(command)) + + # What may run beside a git command that writes its records: what runs + # no program of the command's choosing and writes no file. + + _BESIDE_GIT = (READ_ONLY_BINS - {"find"}) | frozenset({"echo", "printf", "true", "false", + "test", "[", "pwd"}) + + # Interactive forms hand the change to an editor or a prompt. + + _GIT_INTERACTIVE = re.compile(r"^(?:-[a-zA-Z]*[pie][a-zA-Z]*|--(?:patch|interactive|edit)\b.*)$") + + # Words that steer git, or a program it runs, from the environment. + + _GIT_STEERING = re.compile( + r"GIT_|(?:^|[^\w$])(?:HOME|PATH|XDG_\w+|LD_\w+|BASH_ENV|ENV|EDITOR|VISUAL|PAGER)=") + + def steers_git(self, command: str) -> bool: + """Whether `command` steers git, or a program it runs, from the environment.""" + return bool(self._GIT_STEERING.search(command)) + + def git_writes(self, command: str) -> "list[tuple[str, tuple[str, ...]]] | None": + """Where the git commands that write their repository's records run. + + The steps in order: ("cd", directory) and ("git", its -C + directories). None unless the command is git's alone -- every other + stage reads, and nothing writes a file, substitutes, defines a + function, sources a script or steers git (-c, --git-dir, + --work-tree, a GIT_ variable, HOME, PATH, an editor). Only then may + the repositories it names keep their records (write_protection.py). + Clone writes no repository that exists, and adds no step. + """ + if (self._GIT_STEERING.search(command) or re.search(r"[`]|\$\(|<<|\(\s*\)|\bfunction\b", + command) + or self._writes_via_redirection(command)): + return None + + steps: list[tuple[str, tuple[str, ...]]] = [] + + for argv in self.stage_argvs(command): + if argv[0] == "cd": + operands = [word for word in argv[1:] if word not in ("-P", "-L", "--")] + steps.append(("cd", tuple(operands[:1]) if len(operands) == 1 else ("",))) + continue + + if argv[0] != "git": + if argv[0] in self._BESIDE_GIT and not (argv[0] == "sed" and any( + self._SED_IN_PLACE.match(arg) for arg in argv[1:])): + continue + + return None + + parsed = self.git_command(argv) + + if parsed is None: + return None + + subcommand, directories = parsed + + if subcommand in self.GIT_LOCAL_WRITE | {"fetch", "pull"}: + if any(self._GIT_INTERACTIVE.match(word) + for word in argv[argv.index(subcommand) + 1:]): + return None + + steps.append(("git", directories)) + elif subcommand not in self.GIT_READ_ONLY | {"clone"}: + return None + + return steps + def classify(self, command: str) -> CommandAssessment: if not command or not command.strip(): return self._assessment(command, (), CommandClassification.DANGEROUS, "empty command") @@ -1019,6 +1810,14 @@ def classify(self, command: str) -> CommandAssessment: if "\x00" in command: return self._assessment(command, (), CommandClassification.DANGEROUS, "NUL byte") + # Read before the heredoc bodies go: a line written into a script or + # a configuration file throws the same switch later. + + override = control_overrides.command_refusal(command) + + if override: + return self._assessment(command, (), CommandClassification.DANGEROUS, override) + command = self._strip_heredoc_bodies(command) if self._SHELL_SYNTAX.search(command): @@ -1040,9 +1839,9 @@ def classify(self, command: str) -> CommandAssessment: argv = tuple(shlex.split(command, posix=True)) except ValueError as exc: return self._assessment( - command, (), CommandClassification.SHELL_COMPLEX, str(exc), - (Capability.SHELL_COMPLEX,), - ) + command, (), CommandClassification.DANGEROUS, + f"its quoting cannot be read ({exc}): close every quote, or write the " + f"text with write_file.") if not argv: return self._assessment(command, (), CommandClassification.DANGEROUS, "empty argv") @@ -1089,6 +1888,9 @@ def classify_script(self, command: str) -> CommandAssessment: """ assessment = self.classify(command) + if control_overrides.command_refusal(command or ""): + return assessment + if (assessment.classification != CommandClassification.DANGEROUS or not command or not command.strip() or "\x00" in command or self._SHELL_SYNTAX.search(self._strip_heredoc_bodies(command))): @@ -1144,9 +1946,17 @@ def _classify_argv(self, command: str, argv: Sequence[str]) -> CommandAssessment return self._assessment(command, argv, CommandClassification.WORKSPACE_MUTATING, capabilities=self._simple_capabilities(argv)) - if binary in self.DANGEROUS_BINS or ( + if self._syntax_check(argv): + return self._assessment(command, argv, CommandClassification.READ_ONLY, + capabilities=(Capability.FILESYSTEM_READ,)) + + if binary in self._AWK_BINS and self._stage_danger(argv, 0): + return self._assessment(command, argv, CommandClassification.DANGEROUS, + self._stage_danger(argv, 0)) + + if self._runs_code(binary) or ( "/" in argv[0] and not self._is_workspace_program(argv[0])): - if binary in self._PYTHON_BINS: + if binary in self._PYTHON_BINS or self._VERSIONED_INTERPRETER.fullmatch(binary): # The way out comes before the refusal: a model reads the # first clause and acts on it. @@ -1154,6 +1964,10 @@ def _classify_argv(self, command: str, argv: Sequence[str]) -> CommandAssessment command, argv, CommandClassification.DANGEROUS, f"{self._PYTHON_HINT} — so '{argv[0]}' as written is refused") + if binary in self._SCRIPT_SHELLS: + return self._assessment(command, argv, CommandClassification.DANGEROUS, + self._stage_danger(argv, 0)) + return self._assessment( command, argv, CommandClassification.DANGEROUS, f"unapproved executable: '{argv[0]}'" @@ -1171,7 +1985,7 @@ def _classify_argv(self, command: str, argv: Sequence[str]) -> CommandAssessment capabilities=(Capability.FILESYSTEM_READ, Capability.WORKSPACE_WRITE)) if binary == "git": - subcommand = self._git_subcommand(argv) + subcommand = (self.git_command(argv) or ("", ()))[0] if subcommand in self.GIT_READ_ONLY: return self._assessment(command, argv, CommandClassification.READ_ONLY, @@ -1181,7 +1995,7 @@ def _classify_argv(self, command: str, argv: Sequence[str]) -> CommandAssessment return self._assessment(command, argv, CommandClassification.READ_ONLY, capabilities=self._simple_capabilities(argv)) - if subcommand in self.GIT_NETWORK_WRITE: + if subcommand in self.GIT_NETWORK_WRITE | self.GIT_LOCAL_WRITE: return self._assessment(command, argv, CommandClassification.WORKSPACE_MUTATING, capabilities=self._simple_capabilities(argv)) diff --git a/client/harness/control_overrides.py b/client/harness/control_overrides.py new file mode 100644 index 0000000..eac05bb --- /dev/null +++ b/client/harness/control_overrides.py @@ -0,0 +1,116 @@ +"""Switches that turn an integrity guard off, and who may throw them. + +A layered build's attach guard refuses to re-attach a tree whose fingerprint no +longer matches it; IB_FORCE_ATTACH=1 tells it to proceed anyway. The switch +is documented, which makes it the operator's, not the model's: a model that +had its deletion of the fingerprint refused set the variable on the next +call and got the effect the refusal had withheld. + +A model may not set such a switch, by any spelling: a command's environment, +an export, a declaration, a bitbake configuration line a write would add. An +operator who wants it for a session names it in SPEAR_AUTHORIZED_OVERRIDES +before SPEAR starts, where no command of the session can reach. + +Only the switches listed here are judged. Every other variable is the +model's to set, except one whose name a command builds at run time +(`export "$name=1"`): what it sets cannot be read, so it is refused. +""" + +from __future__ import annotations + +import os +import re + +# Name -> the guard it turns off. + +OVERRIDES = { + "IB_FORCE_ATTACH": "the attach guard", +} + +_AUTHORIZED_ENV = "SPEAR_AUTHORIZED_OVERRIDES" + +# A shell or bitbake assignment, with bitbake's operators and override +# suffixes: NAME=1, NAME ?= "1", NAME:pn-buildroot = "1". + +_ASSIGNMENT = r"\b{name}(?::[\w-]+)*\s*(?:\?\?=|\?=|:=|\+=|=\+|\.=|=\.|=)" + +# A builtin that sets or exports variables it names among its arguments. + +_SETTERS = re.compile(r"(?:^|[\s;&|(`])(export|declare|typeset|readonly|local|read|env)\b" + r"([^;&|\n`)]*)") +_PRINTF_V = re.compile(r"\bprintf\s+(?:-\w+\s+)*-v\s*(\S+)") + + +def authorized() -> frozenset[str]: + """The switches the operator granted this session.""" + names = os.environ.get(_AUTHORIZED_ENV, "") + + return frozenset(name.strip() for name in names.split(",") if name.strip()) + + +def _guarded() -> dict[str, str]: + granted = authorized() + + return {name: guard for name, guard in OVERRIDES.items() if name not in granted} + + +def _refusal(name: str, guard: str) -> str: + return (f"{name} is a control-plane override: it turns off {guard}, and only the " + f"operator may enable it. Nothing in this session can set it; if the guard " + f"is wrong, say so and leave it to the operator") + + +def command_refusal(command: str) -> str: + """Why `command` may not run because it sets an override, or "". + + The whole text is read, heredoc bodies included: a line written into a + configuration file or a script is the same switch, thrown later. + """ + command = command or "" + + for name, guard in _guarded().items(): + if not re.search(rf"\b{name}\b", command): + continue + + if re.search(_ASSIGNMENT.format(name=name), command): + return _refusal(name, guard) + + for match in _SETTERS.finditer(command): + if re.search(rf"(?:^|\s)-?\w*\s*{name}\b", match.group(2)): + return _refusal(name, guard) + + for match in _PRINTF_V.finditer(command): + if match.group(1).strip("'\"") == name: + return _refusal(name, guard) + + for match in _SETTERS.finditer(command): + words = match.group(2).split() + + if any(re.match(r"""^['"]?[^=\s'"]*[$`]""", word) for word in words + if not word.startswith("-")): + return (f"'{match.group(1)}' sets a variable whose name is built at run " + f"time, so what it sets cannot be read here; name the variable " + f"literally") + + for match in _PRINTF_V.finditer(command): + if re.search(r"[$`]", match.group(1)): + return ("'printf -v' sets a variable whose name is built at run time, so " + "what it sets cannot be read here; name the variable literally") + + return "" + + +def content_refusal(old: str, new: str) -> str: + """Why a write that turns `old` into `new` may not happen, or "". + + Only an assignment the write adds counts: a class that declares the + default (IB_FORCE_ATTACH ??= "0") stays editable. + """ + for name, guard in _guarded().items(): + pattern = re.compile(rf"^.*{_ASSIGNMENT.format(name=name)}.*$", re.MULTILINE) + before = {line.strip() for line in pattern.findall(old or "")} + + if any(line.strip() not in before for line in pattern.findall(new or "")): + return _refusal(name, guard) + + return "" diff --git a/client/harness/control_plane.py b/client/harness/control_plane.py index 3cba760..79cac8c 100644 --- a/client/harness/control_plane.py +++ b/client/harness/control_plane.py @@ -66,6 +66,36 @@ ) +#: The policy class of a refusal, named after its reason so that the model +#: can tell a protected file from an interpreter or a boundary without +#: parsing prose. Generic on purpose: the class says what kind of rule +#: refused, never how the rule decides. +POLICY_CLASSES = ( + ("control_plane_override", re.compile(r"control-plane override|name is built at run time")), + ("deletion_set", re.compile(r"deletion set holds protected or pre-existing content|" + r"git clean")), + ("control_plane", re.compile(r"control-plane metadata")), + ("start_state_edit", re.compile(r"a shell command does not overwrite it|" + r"file named only at run time")), + ("unreadable", re.compile(r"cannot be read here|quoting cannot be read|" + r"substitution is not closed")), + ("protected_target", re.compile(r"generated file|snapshot copy|git metadata")), + ("interpreter", re.compile(r"interpreter|running a script file|python3 -m unittest|" + r"awk program|test runner|script written in this session")), + ("outside_workspace", re.compile(r"outside the workspace|escapes the workspace|" + r"leaves the workspace|another tree|outside the project|" + r"sandbox's own mounts")), + ("scope", re.compile(r"member of the same family|requested target")), + ("not_allowlisted", re.compile(r"not allowlisted|unapproved executable|mutating find " + r"action|in-place sed|find -\w+ without")), +) + + +def policy_class(text: str) -> str: + """The class of the rule behind a refusal, or "" for any other failure.""" + return next((name for name, pattern in POLICY_CLASSES if pattern.search(text)), "") + + def core_vocabulary(text: str) -> str: """A SPEAR refusal in the coding core's tool vocabulary.""" for pattern, replacement in CORE_VOCABULARY: @@ -114,7 +144,10 @@ def _short(message: str) -> str: if text.startswith(prefix): text = text[len(prefix):] - return REFUSED.format(core_vocabulary(text.split("\n", 1)[0])) + line = core_vocabulary(text.split("\n", 1)[0]) + kind = policy_class(line) + + return REFUSED.format(f"{line} [policy: {kind}]" if kind else line) def command_cwd(self, arguments: Mapping[str, object]) -> str: """Where a terminal call runs: its workdir, the session's, or the root.""" diff --git a/client/harness/persistence_check.py b/client/harness/persistence_check.py new file mode 100644 index 0000000..4ac727e --- /dev/null +++ b/client/harness/persistence_check.py @@ -0,0 +1,277 @@ +"""Whether a patch series reproduces an attached tree. + +An updiff that succeeds has only captured what it chose to capture: it skips +a file with a chain of patches, a binary, an excluded name. Whether the +series persists the tree is a separate fact, established here from outside +the turn: the recipe's pristine copy and its series, in a disposable +directory, with the patch tool as do_patch drives it, compared against the +attached tree. The working tree contributes nothing to the reconstruction. + +Three things are never decided by the attached tree or the turn: + +- the base: the pristine copy is pinned by digest when the session first sees + it and when a build rewrites it, so a turn that changes it fails the check; +- the build-output rules: patch.bbclass's own exclude list as the session + found it, and the ignore rules of the pristine copy, so a turn cannot + declare its own change to be output; +- the verdict: nothing here reads what a command or the model reported. + +Only a file on one side alone can be build output. A file both trees hold +must be identical whatever its name, because the exclude list also stops an +updiff from capturing a real source named like an artefact. + +A recipe's do_handle_symlinks adds links after do_patch, declared in the +recipe, not in the series. A link the attached tree alone holds is the recipe's +when the patched source beside the pristine copy holds the same link. + +An updiff writes a deletion with `diff -N`, as a patch that empties the file, +and the patch tool then leaves it empty. So a file the reconstruction holds +empty and the attached tree does not hold is the same state. Not the reverse: +an empty file only the attached tree holds is not reproduced. + +Every failure to establish the result, of any kind, is a failure of the check. +""" + +from __future__ import annotations + +import ast +import fnmatch +import hashlib +import os +import re +import shutil +import subprocess +import tempfile +import time +from dataclasses import dataclass + +TIMEOUT_SECONDS = 300 +PATCH = ("patch", "-p1", "--forward", "--batch", "--quiet", "--no-backup-if-mismatch") +CLASS = "build/meta/classes/patch.bbclass" + +# What the attach leaves at the top of a tree and no series describes: the +# quilt staging do_patch made, and a fetched repository's own metadata. + +_STAGING = (".git", ".pc", "patches") + + +@dataclass(frozen=True) +class Verification: + """The result of one check; `verified` is PERSISTENCE_VERIFIED.""" + + verified: bool + reason: str = "" + differences: tuple[str, ...] = () + patches: int = 0 + base: str = "" + series: str = "" + reconstructed: str = "" + attached: str = "" + seconds: float = 0.0 + + def summary(self) -> str: + fields = [f"PERSISTENCE_VERIFIED={'true' if self.verified else 'false'}", + f"patches={self.patches}", f"differences={len(self.differences)}", + f"seconds={self.seconds:.1f}", f"base={self.base[:16]}", + f"series={self.series[:16]}", f"reconstructed={self.reconstructed[:16]}", + f"attached={self.attached[:16]}"] + + return " ".join(fields + ([f"reason={self.reason}"] if self.reason else [])) + + +class _Failed(Exception): + pass + + +def _file_digest(path: str) -> str: + digest = hashlib.sha256() + + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + + return digest.hexdigest() + + +def _objects(root: str) -> dict[str, tuple[str, str]]: + """{relative path: (kind, path or link target)}, the staging left out.""" + found = {} + + for directory, subdirectories, names in os.walk(root): + if directory == root: + subdirectories[:] = [name for name in subdirectories if name not in _STAGING] + + for name in names + [item for item in subdirectories + if os.path.islink(os.path.join(directory, item))]: + path = os.path.join(directory, name) + relative = os.path.relpath(path, root) + + if os.path.islink(path): + found[relative] = ("link", os.readlink(path)) + elif os.path.isfile(path): + found[relative] = ("file", path) + else: + found[relative] = ("other", "") + + return found + + +def _identity(item: tuple[str, str]) -> str: + kind, value = item + + return f"file:{_file_digest(value)}" if kind == "file" else f"{kind}:{value}" + + +def _digest_of(identities: dict[str, str]) -> str: + digest = hashlib.sha256() + + for relative in sorted(identities, key=lambda path: path.encode("utf-8", "surrogateescape")): + digest.update(f"{relative}\0{identities[relative]}\n".encode("utf-8", "surrogateescape")) + + return digest.hexdigest() + + +def tree_digest(root: str) -> str: + return _digest_of({relative: _identity(item) for relative, item in _objects(root).items()}) + + +def series_digest(patch_dir: str, listed: list[str]) -> str: + return _digest_of({name: _file_digest(os.path.join(patch_dir, name)) for name in listed}) + + +def exclude_patterns(project: str) -> list[str]: + """do_diffcompose's exclude list, read from the project's own class.""" + with open(os.path.join(project, CLASS), encoding="utf-8") as handle: + source = handle.read() + + block = source[source.index("exclude_patterns = ["):] + block = block[block.index("["):block.index("]") + 1] + + return list(ast.literal_eval(re.sub(r"#.*", "", block))) + + +def _ignored_by_base(base: str, paths: list[str], deadline: float) -> set[str]: + """The paths the pristine copy's own .gitignore files ignore. A throwaway + repository, so that no project or user rule takes part.""" + if not paths: + return set() + + with tempfile.TemporaryDirectory(prefix="spear-ignore-") as directory: + subprocess.run(["git", "init", "-q", directory], capture_output=True, check=True, + timeout=_left(deadline)) + done = subprocess.run( + ["git", "-c", "core.excludesFile=/dev/null", "--git-dir", + os.path.join(directory, ".git"), "--work-tree", base, "check-ignore", "--no-index", + "-z", "--stdin"], + input="\0".join(paths).encode("utf-8", "surrogateescape"), capture_output=True, + timeout=_left(deadline)) + + if done.returncode not in (0, 1): + raise _Failed("the ignore rules could not be read") + + return {name.decode("utf-8", "surrogateescape") for name in done.stdout.split(b"\0") if name} + + +def _left(deadline: float) -> float: + left = deadline - time.monotonic() + + if left <= 0: + raise _Failed("reconstruction timed out") + + return left + + +def _apply(patch_dir: str, listed: list[str], top: str, deadline: float) -> None: + for name in listed: + with open(os.path.join(patch_dir, name), "rb") as handle: + done = subprocess.run((*PATCH, "-d", top), stdin=handle, capture_output=True, + timeout=_left(deadline)) + + if done.returncode != 0: + raise _Failed(f"{name} does not apply") + + +def _deleted(item: tuple[str, str]) -> bool: + return item[0] == "file" and os.path.getsize(item[1]) == 0 + + +def _recipe_link(base: str, path: str, item: tuple[str, str]) -> bool: + source = os.path.join(base.removesuffix(".pristine"), path) + + return item[0] == "link" and os.path.islink(source) and os.readlink(source) == item[1] + + +def differences(attached: str, rebuilt: str, base: str, patterns: list[str], + deadline: float) -> tuple[list[str], str, str]: + """(what differs, digest of the attached state, digest of the rebuilt one).""" + mine, theirs = _objects(attached), _objects(rebuilt) + alone = sorted(set(mine) ^ set(theirs)) + named = {path for path in alone + if any(fnmatch.fnmatch(part, pattern) for part in path.split("/") + for pattern in patterns)} + output = named | _ignored_by_base(base, [path for path in alone if path not in named], deadline) + found, left, right = [], {}, {} + + for path in alone: + if path in output or (path in theirs and _deleted(theirs[path])): + continue + + if path in mine and _recipe_link(base, path, mine[path]): + continue + + if path in mine: + found.append(f"{path}: not reproduced by the series") + left[path] = _identity(mine[path]) + else: + found.append(f"{path}: in the series, not in the attached tree") + right[path] = _identity(theirs[path]) + + for path in sorted(set(mine) & set(theirs)): + _left(deadline) + left[path], right[path] = _identity(mine[path]), _identity(theirs[path]) + + if left[path] != right[path]: + found.append(f"{path}: differs from the series") + + return found, _digest_of(left), _digest_of(right) + + +def verify(tree: str, base: str, pinned: str, patterns: list[str], patch_dir: str, + listed: list[str], *, timeout: float = TIMEOUT_SECONDS) -> Verification: + """Reconstruct `tree` from `base` and the series, and compare. Never raises.""" + started = time.monotonic() + deadline = started + timeout + scratch = "" + facts: dict[str, object] = {"patches": len(listed)} + + try: + scratch = tempfile.mkdtemp(prefix="spear-persistence-") + top = os.path.join(scratch, "tree") + facts["series"] = series_digest(patch_dir, listed) + subprocess.run(["cp", "-a", "--reflink=auto", base, top], check=True, capture_output=True, + timeout=_left(deadline)) + facts["base"] = tree_digest(top) + + if facts["base"] != pinned: + raise _Failed("the pristine copy is not the one this session pinned") + + _apply(patch_dir, listed, top, deadline) + found, facts["attached"], facts["reconstructed"] = differences( + tree, top, base, patterns, deadline) + facts["differences"] = tuple(found) + + if found: + raise _Failed("the series does not reproduce the attached tree") + + return Verification(True, seconds=time.monotonic() - started, **facts) + except _Failed as failure: + reason = str(failure) + except subprocess.TimeoutExpired: + reason = "reconstruction timed out" + except Exception as failure: + reason = f"reconstruction failed: {type(failure).__name__}: {failure}" + finally: + if scratch: + shutil.rmtree(scratch, ignore_errors=True) + + return Verification(False, reason, seconds=time.monotonic() - started, **facts) diff --git a/client/harness/provenance.py b/client/harness/provenance.py new file mode 100644 index 0000000..8b0fdcd --- /dev/null +++ b/client/harness/provenance.py @@ -0,0 +1,243 @@ +"""Which objects of the workspace this session created. + +Deleting what the session itself made is cleanup; deleting what was there +before is a change to the project. The policy refused both alike, so a +model that had built into a scratch directory could neither remove it nor +keep it out of the patch series it regenerated, and left the change +unpersisted rather than leak the scratch files. + +The inventory of the declared trees is taken when a session binds its +workspace: every path present then, and every (device, inode). An object +is SESSION_CREATED when neither its path nor its inode was in it: a file +recreated at a path that existed, or a hard link to a file that existed, +stays what it was. A tree too large to inventory is never anyone's to +delete. +""" + +from __future__ import annotations + +import os + +from harness import target_policy + +# A walk of a whole build tree is a few hundred thousand entries; past this +# the root is left out of the inventory and nothing in it counts as created. + +_MAX_ENTRIES = 2_000_000 +_MAX_REMOVED = 200_000 + +_paths: set[int] = set() +_inodes: set[tuple[int, int]] = set() +# The start objects by name, for what a build removed (attach_control.py). +_names: list[str] = [] +# The roots last asked for, so that a rebind of the same workspace keeps its +# inventory, and the ones whose walk completed: only those hold created objects. +_asked: tuple[str, ...] = () +_complete: tuple[str, ...] = () + + +def _key(path: str) -> int: + return hash(path) + + +def _where(path: str) -> str: + """`path` with its directories resolved and its last component as named: + a link is judged as the link, as rm and delete_file remove the link.""" + path = os.path.abspath(path).rstrip("/") or "/" + + return os.path.join(os.path.realpath(os.path.dirname(path)), os.path.basename(path)) + + +def _walk(root: str): + """(path keys, inodes, names) of everything under `root`, or None past + the bound.""" + paths, inodes, names = {_key(root)}, set(), [] + pending = [root] + count = 0 + + while pending: + try: + entries = list(os.scandir(pending.pop())) + except OSError: + continue + + for entry in entries: + count += 1 + + if count > _MAX_ENTRIES: + return None + + paths.add(_key(entry.path)) + names.append(entry.path) + + try: + status = entry.stat(follow_symlinks=False) + except OSError: + continue + + inodes.add((status.st_dev, status.st_ino)) + + if entry.is_dir(follow_symlinks=False): + pending.append(entry.path) + + return paths, inodes, names + + +def capture(roots) -> None: + """Take the start inventory of `roots`, once per set of roots.""" + global _asked, _complete + + roots = tuple(sorted(os.path.realpath(str(root)) for root in roots)) + + if roots == _asked: + return + + _paths.clear() + _inodes.clear() + _names.clear() + complete = [] + + for root in roots: + found = _walk(root) + + if found is not None: + _paths.update(found[0]) + _inodes.update(found[1]) + _names.extend(found[2]) + complete.append(root) + + _asked, _complete = roots, tuple(complete) + + +def forget() -> None: + """Start over: no inventory, nothing counts as created.""" + global _asked, _complete + + _paths.clear() + _inodes.clear() + _names.clear() + _asked, _complete = (), () + + +def start_paths() -> list[str]: + """Every object of the inventoried trees at the start, by name.""" + return _names + + +def known(path: str) -> bool: + """Whether `path` lies in a tree whose start state was inventoried.""" + return bool(_inside(_where(path))) + + +def _inside(path: str) -> str: + return next((root for root in _complete + if path == root or path.startswith(root + "/")), "") + + +def created(path: str) -> bool: + """Whether the object at `path` was created in this session.""" + where = _where(path) + root = _inside(where) + + if not root or where == root: + return False + + try: + status = os.lstat(where) + except OSError: + return False + + return _key(where) not in _paths and (status.st_dev, status.st_ino) not in _inodes + + +def start_state_file(path: str) -> bool: + """Whether `path` is a file of the start state: inventoried, present, + and not this session's. Its changes go through the checkpointed tools.""" + where = _where(path) + + if not _inside(where) or not os.path.lexists(where) or os.path.isdir(where): + return False + + return not created(where) + + +def _protected(path: str) -> str: + """What no provenance makes deletable: git state, a snapshot copy, a + guard's fingerprint.""" + if target_policy.is_git_metadata(path): + return "git metadata" + + if target_policy.is_snapshot(path + ("/" if os.path.isdir(path) and not os.path.islink(path) else "")): + return "a snapshot copy" + + if target_policy.fingerprinted_tree(path): + return "control-plane metadata" + + return "" + + +def removal_refusal(path: str, label: str | None = None) -> str: + """Why the session may not delete `path` as cleanup, or "". + + A file or link: created in this session, and not protected. A + directory: the same for itself and for every object under it, links + judged as links and refused when they point at anything the session did + not create. + """ + label = label or path + where = _where(path) + + if not os.path.lexists(where): + return f"{label} does not exist" + + if not _inside(where): + return f"{label} is outside the trees whose start state is known" + + found = _protected(where) + + if found: + return f"{label} is {found}" + + if not created(where): + return f"{label} existed when the session started, so it is not the session's to delete" + + if os.path.islink(where) or not os.path.isdir(where): + return _link_refusal(where, label) + + count = 0 + + for directory, subdirectories, files in os.walk(where, followlinks=False): + for name in subdirectories + files: + count += 1 + item = os.path.join(directory, name) + relative = os.path.join(label, os.path.relpath(item, where)) + + if count > _MAX_REMOVED: + return f"{label} holds more than {_MAX_REMOVED} objects: delete it in parts" + + found = _protected(item) + + if found: + return f"{relative} is {found}" + + if not created(item): + return f"{relative} existed when the session started, so {label} is not the session's to delete" + + refusal = _link_refusal(item, relative) if os.path.islink(item) else "" + + if refusal: + return refusal + + return "" + + +def _link_refusal(path: str, label: str) -> str: + if not os.path.islink(path): + return "" + + target = os.path.realpath(path) + + if os.path.lexists(target) and not created(target): + return f"{label} is a link to {target}, which the session did not create" + + return "" diff --git a/client/harness/repeat_breaker.py b/client/harness/repeat_breaker.py new file mode 100644 index 0000000..b7ea36c --- /dev/null +++ b/client/harness/repeat_breaker.py @@ -0,0 +1,64 @@ +"""Stop a turn that keeps making the same successful call to no effect. + +The Hermes streak guard only appends a "do not repeat" note: in an FT-3A run +the model wrote the same one-line file 486 times in a row, each call +succeeding with a byte-identical result, and ignored the note until the round +budget ended the turn. Nobody is at the keyboard during a core turn. + +Four consecutive calls with the same tool, the same canonical arguments and a +byte-identical successful result are the same evidence four times: the turn +is stopped, truthfully, as `repeated_success_loop`. A failed or refused call +never counts here (refusal_breaker owns those); any other call, a changed +result, or a poller resets the count. +""" + +from __future__ import annotations + +import hashlib +import json +import os + +from agent.hermes.tool_guardrails import is_stall_guard_repeatable + +LIMIT = int(os.environ.get("SPEAR_SUCCESS_REPEATS", "4")) +REASON = "repeated_success_loop" + + +def _key(name: str, arguments, result: str) -> tuple[str, str, str]: + canonical = json.dumps(arguments if isinstance(arguments, dict) else {}, + sort_keys=True, default=str) + return name, canonical, hashlib.sha256(str(result).encode()).hexdigest() + + +class RepeatBreaker: + """Counts consecutive identical successful calls; trips at `limit`.""" + + def __init__(self, limit: int = LIMIT): + self.limit = max(2, int(limit)) + self.last: tuple[str, str, str] | None = None + self.count = 0 + self.tripped: tuple[str, str] | None = None + + def observe(self, name: str, arguments, result: str, ok: bool) -> bool: + if self.tripped is not None: + return True + + if not ok or is_stall_guard_repeatable(name): + self.last, self.count = None, 0 + return False + + key = _key(name, arguments, result) + self.count = self.count + 1 if key == self.last else 1 + self.last = key + + if self.count >= self.limit: + self.tripped = (name, key[1]) + + return self.tripped is not None + + def conclusion(self) -> str: + name, arguments = self.tripped + return (f"I stopped: the same {name} call ({arguments[:160]}) succeeded " + f"{self.count} times in a row with an identical result, so repeating it " + f"changed nothing. This is a safety stop, not a claim that the task is " + f"done; the changes made before this point, if any, are listed above.") diff --git a/client/harness/resource_control.py b/client/harness/resource_control.py index 3150b67..559ba5d 100644 --- a/client/harness/resource_control.py +++ b/client/harness/resource_control.py @@ -49,10 +49,24 @@ class ExecutionProfile: #: Host paths to expose read-only, at their own path, in addition to the #: workspace. Empty unless host:read was granted. host_read_paths: tuple[str, ...] = () + #: Git directories the command's own git commands keep their records in + #: (write_protection.git_dirs): the only ones it may write. + git_dirs: tuple[str, ...] = () + #: The command is not a build or a test: generated trees and snapshot + #: copies are bound read-only for it. + guard_outputs: bool = False + #: Further protected host paths the command names or reaches. + protected_paths: tuple[str, ...] = () + #: What a session-cleanup command removes (provenance.py), each verified + #: created in this session: its directory is bound writable again. + cleanup_paths: tuple[str, ...] = () @classmethod def from_capabilities(cls, capabilities: Sequence[Capability], - host_read_paths: Sequence[str] = ()) -> "ExecutionProfile": + host_read_paths: Sequence[str] = (), *, + git_dirs: Sequence[str] = (), guard_outputs: bool = False, + protected_paths: Sequence[str] = (), + cleanup_paths: Sequence[str] = ()) -> "ExecutionProfile": granted = frozenset(capabilities) workspace_read = Capability.FILESYSTEM_READ in granted workspace_write = Capability.WORKSPACE_WRITE in granted @@ -82,6 +96,10 @@ def from_capabilities(cls, capabilities: Sequence[Capability], container_runtime=Capability.CONTAINER_RUNTIME in granted, secrets_allowed=Capability.SECRETS in granted, host_read_paths=tuple(host_read_paths), + git_dirs=tuple(git_dirs), + guard_outputs=guard_outputs, + protected_paths=tuple(protected_paths), + cleanup_paths=tuple(cleanup_paths), ) def audit_metadata(self) -> Mapping[str, bool]: @@ -245,8 +263,11 @@ def systemd_properties(self) -> list[str]: # Production contract, calibrated in STEP 1d-3d against real workloads on this # host (62 GiB RAM, 22 CPUs). The measured peaks over read-only work, Python # test runs, shell pipelines, git and parallel builds were 518 MiB of memory -# and 47 tasks, both reached by ``make -j22``; the values below keep a 4.1x and -# 5.4x margin on those. ``CPUQuota=800%`` was the only point of the grid that +# and 47 tasks, both reached by ``make -j22``. A bitbake kernel build +# (``build.sh linux``: bitbake plus a parallel kernel make) peaks at 2.9 GiB +# and 111 tasks: under the first 2 GiB cap the OOM killer ended it with no +# output. The memory cap keeps a 2x margin on that build, the task cap a +# 2.3x margin. ``CPUQuota=800%`` was the only point of the grid that # left every workload except a massively parallel build entirely un-throttled # (1.77x on ``make -j22``, versus 3.14x at 400% and 6.36x at 200%). # @@ -259,7 +280,7 @@ def systemd_properties(self) -> list[str]: # would both need revisiting on a many-core machine. DEFAULT_CGROUP_LIMITS = CgroupLimits( - memory_max_bytes=2 * 1024 * 1024 * 1024, + memory_max_bytes=6 * 1024 * 1024 * 1024, memory_swap_max_bytes=0, tasks_max=256, cpu_quota_percent=800, diff --git a/client/harness/sandbox.py b/client/harness/sandbox.py index dae84e2..940a9dd 100644 --- a/client/harness/sandbox.py +++ b/client/harness/sandbox.py @@ -21,6 +21,7 @@ from pathlib import Path from typing import Sequence +from harness import write_protection from harness.resource_control import ( CgroupLimits, ExecutionProfile, @@ -186,6 +187,11 @@ def _tmpdir_argv(self) -> "list[str]": return ["--bind", self._session_tmpdir, self.spec.tmpdir] + @property + def session_tmpdir(self) -> str | None: + """The host directory bound at /tmp, once the first command made it.""" + return self._session_tmpdir + def mount_root( self, workspace: Workspace, profile: ExecutionProfile | None = None ) -> str: @@ -233,6 +239,74 @@ def _workspace_mount_argv( for extra in workspace.extra_roots: argv.extend([flag, str(extra), mounts[str(extra)]]) + if profile is not None and profile.workspace_write: + argv.extend(self._protection_argv(workspace, profile, mounts)) + + return argv + + @staticmethod + def _protected_paths(workspace: Workspace, + profile: ExecutionProfile) -> "list[tuple[str, bool]]": + """Host paths under the writable trees bound again: (path, writable). + + Read-only, what the command may not write. Writable again, the git + directories its own git commands keep their records in, when one lies + under a path bound read-only (a submodule's, under its superproject's + .git). Outermost first; a path bound the way the nearest bound one + around it already is adds nothing. + """ + roots = [str(root) for root in workspace.roots] + unlocked = {os.path.realpath(path) for path in profile.git_dirs} + + # A cleanup removes what the session created; the directory it sits + # in may lie in a tree bound read-only, and removing needs it writable. + + unlocked |= {os.path.dirname(path.rstrip("/")) for path in profile.cleanup_paths} + found: dict[str, bool] = {} + + for root in roots: + trees = write_protection.trees(root) + found.update(dict.fromkeys( + (path for path in trees.git if os.path.realpath(path) not in unlocked), False)) + + if profile.guard_outputs: + found.update(dict.fromkeys(trees.outputs, False)) + found.update(dict.fromkeys(trees.control, False)) + + found.update(dict.fromkeys(profile.protected_paths, False)) + found.update(dict.fromkeys(unlocked, True)) + kept: list[tuple[str, bool]] = [] + + for path in sorted(found): + if not write_protection.within(path, roots) or path in roots: + continue + + around = [(parent, writable) for parent, writable in kept + if path.startswith(parent.rstrip("/") + "/")] + + if found[path] == (around[-1][1] if around else True): + continue + + kept.append((path, found[path])) + + return kept + + def _protection_argv(self, workspace: Workspace, profile: ExecutionProfile, + mounts: dict[str, str]) -> list[str]: + """Bind what may not be written back read-only, over the writable trees. + + After the workspace binds, since in bwrap the later bind is the one in + force, and at the path the tree has inside. ``-try``: a path that is + gone by then has nothing left to protect. + """ + argv: list[str] = [] + roots = [str(root) for root in workspace.roots] + + for path, writable in self._protected_paths(workspace, profile): + root = write_protection.within(path, roots) + inside = mounts[root] + path[len(root):] + argv.extend(["--bind-try" if writable else "--ro-bind-try", path, inside]) + return argv def _host_read_argv(self, profile: "ExecutionProfile | None") -> list[str]: @@ -494,13 +568,61 @@ def _pidfd_status() -> ToolResult | None: return None - def _result_from_completed(self, completed: subprocess.CompletedProcess[str]) -> ToolResult: + def _output_left_since(self, started: float) -> str: + """What a killed command had written so far, from the session /tmp. + + The session wrapper writes the command's output to a file under /tmp, + which is a host directory bound for the whole session: a sandbox the + cgroup killed takes its processes, not that file.""" + if not self._session_tmpdir: + return "" + + found = [] + + for path in Path(self._session_tmpdir).glob("*/out"): + try: + if path.stat().st_mtime >= started - 1: + found.append((path.stat().st_mtime, path)) + except OSError: + continue + + if not found: + return "" + + data = max(found)[1].read_bytes() + return decode_command_output(data[-self.max_output_chars:]) + + def _result_from_completed(self, completed: subprocess.CompletedProcess[str], + cgroup_limits: CgroupLimits | None = None, + started: float | None = None) -> ToolResult: stdout = decode_command_output(completed.stdout)[: self.max_output_chars] stderr = decode_command_output(completed.stderr)[: self.max_output_chars] if completed.returncode == 0: return ToolResult("ok", "bubblewrap sandbox command completed", stdout, stderr) + # A sandbox ended by a signal, with a resource contract active, is the + # cgroup's doing: the kernel OOM-kills the process over the cap (SIGKILL) + # and systemd's OOM policy then stops the whole scope (SIGTERM). Timeouts + # never reach this point. The session wrapper died with it, so the + # output it had written and the limits are the evidence left. + + killed = {signal.SIGKILL, signal.SIGTERM} + + if (-completed.returncode in killed or completed.returncode - 128 in killed) \ + and cgroup_limits is not None and cgroup_limits.active: + left = self._output_left_since(started) if started is not None else "" + return ToolResult( + "failed", + "bubblewrap sandbox command killed: it most likely exceeded the " + f"sandbox's resource limits ({', '.join(cgroup_limits.systemd_properties())}); " + + ("its output up to the kill follows. " if left else "no output was kept. ") + + "Run less in parallel or a smaller step.", + stdout=left or stdout, + stderr=stderr, + exit_code=completed.returncode, + ) + return ToolResult( "failed", "bubblewrap sandbox command failed", @@ -598,6 +720,7 @@ def run( env = {} if unit is None else self.scope_runner.supervisor_env() try: + started = time.time() process = subprocess.Popen( argv, stdout=subprocess.PIPE, @@ -663,7 +786,7 @@ def run( self.availability = SandboxAvailability.INEXECUTABLE return ToolResult("failed", f"bubblewrap sandbox unavailable: {exc}") - return self._result_from_completed(completed) + return self._result_from_completed(completed, cgroup_limits, started) @staticmethod def _safe_close(fd: int | None) -> None: @@ -854,6 +977,7 @@ def _run_with_slirp( scoped_argv = bwrap_argv scope_env = {} + started = time.time() bwrap_process = subprocess.Popen( scoped_argv, stdout=subprocess.PIPE, @@ -994,7 +1118,7 @@ def _run_with_slirp( completed = subprocess.CompletedProcess(bwrap_argv, bwrap_process.returncode, stdout, stderr) - return self._result_from_completed(completed) + return self._result_from_completed(completed, cgroup_limits, started) # The coordinator must not leak an in-flight namespace/helper if a # Python-level failure occurs while reading control data. diff --git a/client/harness/target_policy.py b/client/harness/target_policy.py index 3c96fdb..b2322a7 100644 --- a/client/harness/target_policy.py +++ b/client/harness/target_policy.py @@ -1,10 +1,14 @@ """Which files no mutation may touch, whatever tool attempts it. A refusal attaches to the target, not to the tool. Generated output and -snapshot or third-party copies were protected only from write_file and +snapshot copies were protected only from write_file and patch: delete_file then a fresh write_file, a shell redirection, cp, tee, truncate or ln -sf reached the same file. Every mutation path asks here, about the path as written and about the file it actually reaches. + +A repository's own state is a target too: no tool edits git metadata, and +the sandbox binds it read-only under every command that may write +(write_protection.py). """ from __future__ import annotations @@ -13,11 +17,46 @@ import re _GENERATED_PATH = re.compile(r"/generated/|/build/tmp/") -_SNAPSHOT_PATH = re.compile(r"/(?:u-boot|atf|qemu)(?:\.back)?/|\.back/|\.pristine/|\.0/|" - r"/build/tmp/") + +# A directory named as a copy is one wherever it sits. ".0" names a version as +# often as a copy (zynq-rev1.0, linux-6.0), so it counts only beside the live +# tree it copies (rootfs.0 next to rootfs). A component's name never decides: +# an attached u-boot/ or a recipes-qemu/qemu/ layer is the project's source. + +_SNAPSHOT_SUFFIXES = (".back", ".pristine") +_COPY_SUFFIX = ".0" _GENERATED_MARK = re.compile( r"DO NOT (?:MODIFY|EDIT)|auto(?:matically)?[ -]?generated|@generated", re.IGNORECASE) +# A generator says so in a comment at the top of what it writes. The same +# words in prose are not that: Linux's init/Kconfig mentions "auto-generated" +# in the help text of its first option. + +_COMMENT_LINE = re.compile(r"\s*(?:#|//|/\*|\*|;|--|%|\n\n", "; autogenerated, DO NOT MODIFY\n", + '"""Auto-generated by protoc."""\n'): + with self.subTest(head=head): + self.assertTrue(target_policy.says_generated(head)) + + def test_the_words_in_prose_or_code_do_not(self): + for head in (LINUX_INIT_KCONFIG, 'print("DO NOT EDIT this by hand")\n', + "int main(void) { return 0; } /* x */\nchar *s = \"auto-generated\";\n", + "\n" * 10 + "# DO NOT EDIT\n"): + with self.subTest(head=head[:40]): + self.assertFalse(target_policy.says_generated(head)) + + def test_linux_init_kconfig_is_editable(self): + self.assertEqual(target_policy.refusal(self.file("init/Kconfig", LINUX_INIT_KCONFIG)), "") + + def test_a_saved_configuration_is_a_source(self): + for relative in ("configs/rpi4_64_defconfig", "arch/arm64/configs/defconfig", + "board/defconfig"): + with self.subTest(path=relative): + self.assertEqual(target_policy.refusal(self.file(relative, SAVED_CONFIG)), "") + + self.assertIn("generated", target_policy.refusal(self.file(".config", SAVED_CONFIG))) + self.assertIn("generated", target_policy.refusal( + self.file("out/generated/x_defconfig", SAVED_CONFIG))) + self.assertIn("generated", target_policy.refusal( + self.file("configs/defconfig.h", SAVED_CONFIG))) + + def test_a_refused_file_is_remembered_for_the_session(self): + path = self.file("gen.h", "/* DO NOT EDIT */\n") + target_policy.refusal(path) + + self.assertIn(path, target_policy.refused_paths()) + + if __name__ == "__main__": unittest.main() diff --git a/client/tests/test_turn_liveness.py b/client/tests/test_turn_liveness.py index bc820dc..abf5e24 100644 --- a/client/tests/test_turn_liveness.py +++ b/client/tests/test_turn_liveness.py @@ -37,6 +37,31 @@ def test_the_spinner_alone_is_not_life(self): self.assertGreater(terminal_ui.LIVENESS.silent_for(), 30) +class ABoundedCommand(unittest.TestCase): + """A build is silent while it compiles: under the 300 s heartbeat alone, + the watchdog interrupted a 600 s `build.sh linux` the sandbox was still + running within its own timeout.""" + + def test_a_running_command_is_alive_until_its_own_timeout(self): + with terminal_ui.LIVENESS.bounded(600): + terminal_ui.LIVENESS.at = time.monotonic() - 400 + + self.assertEqual(terminal_ui.LIVENESS.silent_for(), 0.0) + + def test_past_its_timeout_the_silence_counts_again(self): + with terminal_ui.LIVENESS.bounded(600): + terminal_ui.LIVENESS.at = time.monotonic() - 400 + terminal_ui.LIVENESS.until = time.monotonic() - 310 + + self.assertGreater(terminal_ui.LIVENESS.silent_for(), 300) + + def test_the_end_of_the_command_is_a_sign_of_life(self): + with terminal_ui.LIVENESS.bounded(600): + terminal_ui.LIVENESS.at = time.monotonic() - 400 + + self.assertLess(terminal_ui.LIVENESS.silent_for(), 1) + + class TheWatchdog(unittest.TestCase): def run_turn(self, *, silence, threshold, work=0.6): source = CancellationSource() diff --git a/client/tests/test_validation_repair.py b/client/tests/test_validation_repair.py index c640795..b107cb5 100644 --- a/client/tests/test_validation_repair.py +++ b/client/tests/test_validation_repair.py @@ -230,8 +230,64 @@ def test_the_request_bounds_the_output_it_carries(self): self.assertLess(len(request), agent_core_turn.REPAIR_OUTPUT_CHARS + 800) +def sed(old, new): + """A turn that changes a.sh through the terminal, not a write tool.""" + return turn("", call(f"s-{old}", "terminal", command=f"sed -i s/{old}/{new}/ a.sh")) + + +class TerminalChanges(unittest.TestCase): + """`git apply` or `sed -i` change source without a write tool: the project + validation still runs on the state they leave, its failure still earns + the one repair, and a repair made that way is validated again.""" + + run_turn = ValidationRepair.run_turn + repairs = ValidationRepair.repairs + + def test_a_terminal_only_change_is_validated_and_repaired(self): + result, context = self.run_turn( + [sed("alpha", "beta"), turn("Done."), sed("beta", "gamma"), + turn("Fixed: it prints gamma.")], + verifier=Verifier(None, wanted="gamma")) + + self.assertEqual(len(self.repairs()), 1) + self.assertEqual(len(context.project_verifier.calls), 2) + self.assertEqual(context.core_verdict.state, "VERIFIED") + + def test_a_passing_model_check_does_not_outweigh_a_failing_project_validation(self): + result, context = self.run_turn( + [sed("alpha", "beta"), turn("", call("c2", "terminal", command="./a.sh")), + turn("Done."), turn("I cannot see what to change.")], + verifier=Verifier(None, wanted="")) + + self.assertEqual(len(self.repairs()), 1) + self.assertEqual(context.core_verdict.state, "UNVERIFIED") + self.assertTrue(result.final_response.startswith("**UNVERIFIED**")) + + def test_a_repair_made_through_the_terminal_is_validated_again(self): + result, context = self.run_turn( + [turn("", call("c1", "patch", path="a.sh", old_string="alpha", new_string="beta")), + turn("Done."), sed("beta", "gamma"), turn("Fixed: it prints gamma.")], + verifier=Verifier(None, wanted="gamma")) + + self.assertEqual(len(self.repairs()), 1) + self.assertEqual(len(context.project_verifier.calls), 2) + self.assertEqual(context.core_verdict.state, "VERIFIED") + + def test_the_final_validation_runs_once_per_epoch(self): + result, context = self.run_turn([sed("alpha", "beta"), turn("Done.")], + verifier=Verifier(None, wanted="beta")) + + self.assertEqual(self.repairs(), []) + self.assertEqual(len(context.project_verifier.calls), 1) + self.assertEqual(context.core_verdict.state, "VERIFIED") + + class TheCodingCoreIsUnchanged(unittest.TestCase): - """The repair pass is SPEAR's; the core it runs is the one v0.3.0 shipped.""" + """The repair pass is SPEAR's; the core it runs is the released one. + + core-v0.3.1 is v0.3.0's core with one change: the patch tool refuses a + fuzzy match that would rewrite literal diff markers (agent/patch_guard.py). + """ def test_the_core_tree_is_the_released_one(self): def tree(revision): @@ -240,11 +296,11 @@ def tree(revision): return done.stdout.strip() if done.returncode == 0 else "" - released = tree("v0.3.0:spear/agent") + released = tree("core-v0.3.1:client/agent") current = tree("HEAD:client/agent") if not released or not current: - self.skipTest("not a git checkout carrying the v0.3.0 tag") + self.skipTest("not a git checkout carrying the core-v0.3.1 tag") dirty = subprocess.run(["git", "status", "--porcelain", "--", "agent"], cwd=ROOT, capture_output=True, text=True).stdout diff --git a/doc/source/harness/resource_control.rst b/doc/source/harness/resource_control.rst index cbca801..614a1ed 100644 --- a/doc/source/harness/resource_control.rst +++ b/doc/source/harness/resource_control.rst @@ -362,7 +362,7 @@ container's own limits): .. code-block:: python DEFAULT_CGROUP_LIMITS = CgroupLimits( - memory_max_bytes = 2_147_483_648, # 2 GiB — 4.1x the 518 MiB peak + memory_max_bytes = 6_442_450_944, # 6 GiB — 2x the 2.9 GiB kernel build memory_swap_max_bytes = 0, # measured swap delta: 0 kB tasks_max = 256, # 5.4x the observed peak of 47 cpu_quota_percent = 800, # no throttling except a massive build @@ -433,10 +433,11 @@ Portability * - ``memory_swap_max_bytes=0`` - **yes** - depends on no host resource - * - ``memory_max_bytes=2 GiB`` + * - ``memory_max_bytes=6 GiB`` - reasonably - - 3 % of RAM here; 50 % of a 4 GiB machine — permissive in relative terms - but still protective in absolute ones + - 10 % of RAM here; sized for a bitbake kernel build (2.9 GiB peak), + which a 2 GiB cap OOM-killed with no output; on an 8 GiB machine it no + longer protects the host * - ``tasks_max=256`` - **fragile** - the peak tracks ``nproc``: 47 for ``make -j22``. On a 192-thread host, diff --git a/doc/source/harness/sandbox.rst b/doc/source/harness/sandbox.rst index 1b57667..67c52c0 100644 --- a/doc/source/harness/sandbox.rst +++ b/doc/source/harness/sandbox.rst @@ -107,6 +107,17 @@ Filesystem * - the workspace - **the only host-writable mount**, at its own host path by default (see below); the registered corpora beside it unless ``--single-root`` + * - git metadata + - when the workspace is writable: every ``.git`` directory and file in + it, and the git directories ``.git`` files name, bound back read-only + (``--ro-bind-try``) after the workspace, at their path inside it — + except the git directories of the repository a git command keeps its + records in, when the command is git's alone (:doc:`security_model`) + * - protected targets + - the same way: the protected files the command names or reaches + through the files it runs or feeds, the files refused earlier in the + session, and — unless the command builds or tests — the generated and + snapshot trees (:doc:`security_model`) Environment: @@ -127,6 +138,24 @@ Workspace binding follows the profile A read-only profile therefore cannot write even by accident: the restriction is a mount option, not a check in Python. +A writable profile is narrowed the same way. The repositories in the tree are +found by a walk that reads directories only (never file contents, and not +``build/tmp``, ``build/downloads`` or ``build/sstate-cache``), cached per root +for the session and walked again when a root changes or a ``git clone`` ran. +Each is bound read-only over the writable tree, so ``rm .git/index`` or a +script appending to ``.git/config`` fail with *Read-only file system* +whatever spells them; ``git status`` and ``git log`` read and run. A git +command that keeps its repository's records (``add``, ``checkout``, +``restore``, ``switch``, ``stash``, ``clean``, ``fetch``, ``pull``) finds +that repository's git directories writable, and only those: one nested +inside another stays read-only, and one under a read-only one is bound +writable again after it (``--bind-try``). +The same walk finds the generated and snapshot trees (``generated/``, +``build/tmp``, ``.back``, ``.pristine``, a ``.0`` beside its live tree), +bound read-only for a command that is not a build or a test run; the +protected files a command reaches are found from its words and from the +files it names, never by reading the whole tree. + ```` is the workspace's own host path, so a build tree configured outside the sandbox keeps working inside it — CMake caches, generated Makefiles and ``compile_commands.json`` all embed absolute paths. diff --git a/doc/source/harness/security_model.rst b/doc/source/harness/security_model.rst index 0ce749b..980ea5f 100644 --- a/doc/source/harness/security_model.rst +++ b/doc/source/harness/security_model.rst @@ -58,8 +58,9 @@ same judgement is applied to what a shell command writes — a redirection, the destination of ``cp``, ``mv``, ``install``, ``ln`` or ``rsync``, the ``of=`` of ``dd``, the operands of ``rm``, ``touch``, ``mkdir``, ``tee``, ``truncate`` or ``sed -i``, and any path an inline interpreter program names — -with relative operands read from the directory the command runs in -(``request_scope.py``). **A terminal command cannot make a change the file +with relative operands read from the directory the command runs in, a ``$VAR`` +read as the value the command assigned it, ``x>>file`` read without its +spaces, and ``cp src dir/`` judged on ``dir/src`` (``request_scope.py``). **A terminal command cannot make a change the file tools would refuse.** **Project scope.** A command that searches outside the project (``find`` or @@ -68,14 +69,71 @@ home directory outside it, is refused unless the operator named that path: another checkout is another project, not a source of this one's build. **Generated and protected trees.** Build outputs (``/generated/``, -``/build/tmp/``, files whose head says *DO NOT MODIFY*, *DO NOT EDIT*, -*auto-generated* or ``@generated``) and snapshot or third-party copies -(``.back``, ``.pristine``, ``.0`` trees, vendored ``u-boot``, ``atf``, -``qemu``) are never written; the refusal points at the source to change -instead. The rule belongs to the target, not to the tool -(``target_policy.py``): ``write_file``, ``patch``, ``delete_file`` and every -shell write listed above ask the same question, about the path as written and -about its ``realpath``, so a link or a ``..`` does not change the answer. +``/build/tmp/``, files that say *DO NOT MODIFY*, *DO NOT EDIT*, +*auto-generated* or ``@generated`` in a comment within their first ten lines) +and snapshot copies (``.back`` and ``.pristine`` trees, a ``.0`` tree beside +its live one, never a directory because of its name) are never written; the +refusal points at the source to change instead. The same words in prose do not +count (Linux's ``init/Kconfig`` uses *auto-generated* in a help text), nor do +they in the ``+`` lines of a patch, and a saved Kconfig configuration +(``defconfig``, ``*_defconfig``) is a source even under its *Automatically +generated file; DO NOT EDIT.* header. The rule belongs to the target, not to +the tool (``target_policy.py``): ``write_file``, ``patch``, ``delete_file`` +and every shell write listed above ask the same question, about the path as +written and about its ``realpath``, so a link or a ``..`` does not change the +answer. + +The parser is not the boundary: a program may write what no word of its +command names. So for a command granted workspace write, the sandbox binds +back read-only the protected files the command can reach — those its words +name, those named in the files it runs or feeds (a diff given to ``patch``, a +script, the tests a runner discovers, a here-document) and every file refused +earlier in the session — and, unless the command builds or tests, the +generated and snapshot trees themselves (``write_protection.py``). A build +(``make``, ``cmake``, ``ninja``, ``bitbake``, a project's ``build.sh``, +``configure`` or a layer's ``updiff.sh``, a compiler, a test runner) keeps +writing its output, which is how generated files are meant to change; only +the files its own words name stay protected. The authority is the build's +alone: every other stage of the command must write nothing, and no +redirection or ``tee`` may write into a generated tree. + +A launcher — ``timeout``, ``nice``, ``env``, ``nohup``, ``exec``, +``command``, ``time``, ``bash -c`` or ``sh -c`` — is judged by what it runs, +read through its options and, for a shell, through its script: a wrapped +build stays a build, and a wrapped write stays a write, refused the same. +A launcher this cannot read (an option it does not know, ``env -S``, words +after a ``-c`` script, a script the outer shell expands, a program that is +an expansion) is refused. + +**Git metadata.** A repository's own state — a ``.git`` directory, a ``.git`` +file (a worktree's or a submodule's) and the git directory it names, or any +directory holding git's ``HEAD`` beside its ``objects`` — is never edited by a +tool: the coding core's file tools, the legacy ones (``edit_file``, +``append_file`` and ``fetch_url``'s ``save_as`` included) and every shell +write are refused it (``target_policy.py``). Since a terminal command +may run a program whose writes no parser sees — a script, ``patch`` fed on +stdin, a Makefile rule — the sandbox also binds every ``.git`` and the git +directories they name read-only, on top of the writable tree, for every +command granted workspace write (``write_protection.py``, :doc:`sandbox`). +``git status``, ``log``, ``diff`` and ``show`` keep working. + +Git itself keeps its records. ``add``, ``checkout``, ``restore``, +``switch``, ``stash``, ``clean``, ``fetch`` and ``pull`` find writable the +git directories of the repository they run in — followed through the +command's ``cd`` and ``-C`` steps, and through a ``.git`` file to the git +directory it names and that one's common directory, all canonically — and +no other (``write_protection.git_dirs``). Only when the command is git's +alone and run as itself (``CommandPolicy.git_writes``): every other stage +reads; nothing writes a file, substitutes, defines a function or sources a +script; no ``-c``, ``--git-dir``, ``--work-tree`` or interactive form +(``-p``, ``-i``, ``-e``); no ``GIT_*``, ``HOME``, ``PATH``, ``LD_*`` or +editor in the command or exported by the session; no directory outside the +roots or inside git's own state; no writable directory ahead of the system's +``git`` on ``PATH`` that holds a ``git`` or could before a second git +command runs. Otherwise the repository stays read-only and the git command +fails there. What git changes in the worktree is judged like any other +write: a protected file it names and the generated trees stay read-only +under it. ``reset``, ``commit``, ``config`` and the rest keep no records. **Read-only and advisory turns.** A turn that only asks to be told something, or is told not to change anything, keeps its reading tools and runs its diff --git a/doc/source/harness/tool_harness.rst b/doc/source/harness/tool_harness.rst index 0458c9c..dcb1f51 100644 --- a/doc/source/harness/tool_harness.rst +++ b/doc/source/harness/tool_harness.rst @@ -174,7 +174,12 @@ Every one of the step-9 checks returns a ``failed`` ``ToolResult`` rather than proceeding in a degraded mode (:ref:`fail_closed`). A refusal of the :term:`target policy` attaches to the file, not to the tool -(:ref:`control_plane`). +(:ref:`control_plane`). The decision is taken on the path as written and on +the file it reaches, so a link or a ``..`` does not change it. Git metadata +(``.git`` and the git directory a ``.git`` file names) is refused the same +way, and the sandbox binds it read-only under every command that may write, +together with the protected files the command reaches and, unless it builds or +tests, the generated and snapshot trees. .. _refusal_breaker: diff --git a/doc/source/overview/glossary.rst b/doc/source/overview/glossary.rst index 89f1ed5..61b6b39 100644 --- a/doc/source/overview/glossary.rst +++ b/doc/source/overview/glossary.rst @@ -155,9 +155,9 @@ Glossary Target policy The rule that a refusal attaches to the file, not to the tool: generated - output and snapshot copies refused to ``write_file`` and ``patch`` are - refused to every other mutation as well, ``delete_file`` and shell - redirection included. + output, snapshot copies and git metadata refused to ``write_file`` and + ``patch`` are refused to every other mutation as well, ``delete_file`` + and shell redirection included. Refusal breaker The guard that stops a turn which keeps asking for an operation already diff --git a/doc/source/reasoning/implementation.rst b/doc/source/reasoning/implementation.rst index b14bcea..e1452ad 100644 --- a/doc/source/reasoning/implementation.rst +++ b/doc/source/reasoning/implementation.rst @@ -113,8 +113,8 @@ Every call the coding core makes crosses SpearHost, whichever tool made it: ``write`` / ``delete`` the protected-target policy (generated output, snapshot and third-party - copies), the confirmation the mode requires, and the checkpoint that makes - ``/undo`` possible. + copies, git metadata), the confirmation the mode requires, and the + checkpoint that makes ``/undo`` possible. ``run_command`` the command policy (what may run, what it may write, whether it may reach @@ -149,6 +149,13 @@ change the file tools would refuse cannot be made through the terminal instead. third-party copies are refused to every tool, the terminal included, with a pointer to the source to change (:term:`target policy`, :ref:`control_plane`). +**Git metadata.** No tool edits a repository's state: ``.git`` (directory or +file), the git directory a ``.git`` file names, and anything under them are +refused to every tool, and bound read-only by the sandbox under every command +that may write, so a script writing there fails too. A git command run alone +keeps its own repository's records — ``git add``, ``checkout``, ``stash``, +``clean`` work — and nothing else is let in with it. + **Advisory and read-only turns.** A turn that asks only to be told something, or is told not to change anything, keeps its reading tools and loses every write — including the terminal's ability to write. @@ -188,7 +195,10 @@ command, its exit status, the bounded output and the source epoch it judged. Whatever the repair pass leaves is validated again at its own epoch; a failure then, a validation that could not run, or a repair pass that stopped before finishing is ``UNVERIFIED``. There is no second repair, and a pass that changes -nothing ends the turn with the same failure. +nothing ends the turn with the same failure. A change is a change whatever made +it: source that a terminal command rewrote (``sed -i``, ``git apply``) starts a +new epoch, which the project validation judges like one written by the file +tools. The repair is not offered when the validation did not run, nor to a turn stopped by its budget, a repeated refusal, a truncation or the operator. A