From 67fec228f294acb33c50f729191921b008ad8c8e Mon Sep 17 00:00:00 2001 From: mintaka Date: Sun, 22 Nov 2026 21:21:35 -0500 Subject: [PATCH] fix(hermes): mask kubectl cp and oc rsync read-backs (RIG-12066) Track copied pod paths and bounded local values per terminal session; limits fall back to destination path tracking. Registered values have at least eight characters, no whitespace, and a digit or symbol unless at least 20 characters. Over-masking of short structured values is accepted; a leak is not. Known limits: all-letter secrets under 20 characters and values containing whitespace are not registered; indirect reads can leak values from skipped files or after the value cap is reached. Non-local backends retain path tracking because their files are not host accessible. The read_file tool and background output are out of scope. Co-Authored-By: Matt Wilkinson Co-authored-by: Matt Wilkinson --- forks/hermes-agent/agent/redact.py | 258 ++++++++++++++ .../agent/test_redact_kubernetes_raw_read.py | 332 ++++++++++++++++++ forks/hermes-agent/tools/terminal_tool.py | 2 + .../tools/terminal_tool_result.py | 26 +- 4 files changed, 611 insertions(+), 7 deletions(-) diff --git a/forks/hermes-agent/agent/redact.py b/forks/hermes-agent/agent/redact.py index b5fd63b49..45fa71c12 100644 --- a/forks/hermes-agent/agent/redact.py +++ b/forks/hermes-agent/agent/redact.py @@ -2071,6 +2071,264 @@ def _is_structured_kubectl_read(command: str) -> bool: return _kubectl_outputs_structured(args) +_POD_COPY_PATHS: dict[str, dict[str, tuple[str, bool]]] = {} +_POD_COPY_LOCK = threading.Lock() +_POD_COPY_MAX_PER_SESSION = 256 +_POD_COPY_VALUE_FLAGS = _KUBECTL_GLOBAL_VALUE_FLAGS | { + "-c", "--container", "--retries", "--exclude", "--include", +} +_POD_COPY_VALUES: dict[str, dict[str, tuple[str, bool]]] = {} + + +def _register_copy_text(text: str, session_key: str, details: tuple[str, bool]) -> None: + import base64 + + candidates = [] + lines = text.splitlines() + for line in lines: + stripped = line.strip() + if stripped.startswith("- "): + stripped = stripped[2:].strip() + elif stripped.startswith("#"): + stripped = stripped[1:].strip() + padded = re.fullmatch(r"[A-Za-z0-9+/_-]+={1,2}", stripped) is not None + if stripped and not stripped.endswith(":") and ("=" not in stripped or padded) and ": " not in stripped: + candidates.append(stripped.strip("\"'")) + if "=" in line: + candidates.append(line.split("=", 1)[1].strip().strip("\"'")) + if ": " in line: + candidates.append(line.split(": ", 1)[1].strip().strip(",\"'")) + try: + obj = json.loads(text) + except (ValueError, RecursionError): + obj = None + def collect(value): + if isinstance(value, str): + candidates.append(value) + elif isinstance(value, dict): + for child in value.values(): + collect(child) + elif isinstance(value, list): + for child in value: + collect(child) + try: + collect(obj) + except RecursionError: + return + with _POD_COPY_LOCK: + values = _POD_COPY_VALUES.setdefault(session_key, {}) + for value in candidates: + if (len(value) < 8 or any(ch.isspace() for ch in value) + or (len(value) < 20 and value.isalpha())): + continue + data = value.encode("utf-8") + for variant in (value, base64.b64encode(data).decode(), base64.urlsafe_b64encode(data).decode(), data.hex()): + if variant not in values and len(values) >= _POD_COPY_MAX_PER_SESSION: + logger.info("Pod copy value bound exceeded; retaining destination path tracking") + return + values[variant] = details + + +def redact_pod_copy_values(output: str, session_key: str, *, audit: bool = True) -> str: + if not output or not _redact_enabled(): + return output + with _POD_COPY_LOCK: + values = sorted(_POD_COPY_VALUES.get(session_key, {}).items(), key=lambda item: len(item[0]), reverse=True) + matched = None + for value, details in values: + if value in output: + output = output.replace(value, "***") + matched = details + if matched and audit: + tool, known = matched + logger.info("Masked pod %scopy read-back (tool=%s, known_secret_mount=%s)", + "secret " if known else "", tool, known) + return output + + +def _register_local_copy(path: str, session_key: str, details: tuple[str, bool]) -> None: + from pathlib import Path + root = Path(path) + try: + if root.is_symlink(): + return + files = root.rglob("*") if root.is_dir() else (root,) + count = 0 + for file in files: + if file.is_symlink() or not file.is_file(): + continue + count += 1 + if count > 64: + return + with file.open("rb") as stream: + data = stream.read(65537) + if len(data) > 65536 or b"\x00" in data: + continue + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + continue + _register_copy_text(text, session_key, details) + except OSError: + logger.info("Pod copy read bound exceeded; retaining destination path tracking") + + + +def clear_pod_copies(session_key: str) -> None: + with _POD_COPY_LOCK: + _POD_COPY_PATHS.pop(session_key, None) + _POD_COPY_VALUES.pop(session_key, None) + + +def _strip_copy_prefix(tokens: list[str]) -> list[str]: + while tokens: + if _ENV_ASSIGNMENT_RE.match(tokens[0]): + tokens = tokens[1:] + elif _binary_base(tokens[0]) in {"sudo", "doas"}: + tokens = tokens[1:] + while tokens and tokens[0].startswith("-"): + flag = tokens.pop(0) + if (flag in {"-u", "-g", "-h", "-p", "-C", "-T", "--user", "--group", "--host", "--prompt"} + or (flag.startswith("-") and not flag.startswith("--") and flag[-1:] in "ughpCT")) and tokens: + tokens.pop(0) + elif _binary_base(tokens[0]) == "env": + tokens = tokens[1:] + while tokens and tokens[0].startswith("-"): + flag = tokens.pop(0) + if flag in {"-u", "--unset"} and tokens: + tokens.pop(0) + elif _binary_base(tokens[0]) == "timeout": + tokens = tokens[2:] + elif _binary_base(tokens[0]) == "stdbuf": + tokens = tokens[1:] + while tokens and tokens[0].startswith("-"): + tokens.pop(0) + elif _binary_base(tokens[0]) in {"command", "time", "nice", "nohup", "exec"}: + tokens = tokens[1:] + else: + break + return tokens + + +def _stream_destinations(command: str) -> list[str]: + lexer = shlex.shlex(command, posix=True, punctuation_chars="|;&<>") + lexer.whitespace_split = True + try: + tokens = list(lexer) + except ValueError: + return [] + destinations = [] + for i, token in enumerate(tokens[:-1]): + if token in {">", ">>", "&>", "&>>", ">|"}: + destinations.append(tokens[i + 1]) + following = _strip_copy_prefix(tokens[i + 1:]) if token == "|" else [] + if following and _binary_base(following[0]) == "tee": + for arg in following[1:]: + if arg in {"|", ";", "&&", "||", ">", ">>"}: + break + if not arg.startswith("-"): + destinations.append(arg) + return destinations + + +def _copy_path(path: str, cwd: str | None) -> str: + return os.path.normpath(os.path.join(cwd or ".", os.path.expandvars(os.path.expanduser(path)))) + + +def record_pod_copy(command: str, session_key: str, cwd: str | None, *, local: bool = False, output: str = "") -> None: + """Capture local copied values or track paths for non-local backends.""" + # Secret volumes can be mounted anywhere; track every pod copy rather than + # guessing the mount from its path. This may mask non-secret pod copies. + current_cwd = cwd + for segment in _command_segments(command): + try: + tokens = shlex.split(segment.strip().strip("()")) + except ValueError: + continue + tokens = _strip_copy_prefix(tokens) + if tokens and _binary_base(tokens[0]) in {"sh", "bash", "zsh"} and len(tokens) >= 3 and tokens[1] == "-c": + record_pod_copy(tokens[2], session_key, current_cwd, local=local, output=output) + continue + if tokens and tokens[0] in {"cd", "pushd"} and len(tokens) > 1: + current_cwd = _copy_path(tokens[1], current_cwd) + continue + if len(tokens) < 4 or _binary_base(tokens[0]) not in _KUBECTL_NAMES: + continue + verb = _kubectl_verb(tokens[1:]) + if verb not in ({"cp", "rsync"} if _binary_base(tokens[0]) == "oc" else {"cp"}): + continue + operands = tokens[tokens.index(verb) + 1:] + positional = [] + i = 0 + while i < len(operands): + arg = operands[i] + if arg in _POD_COPY_VALUE_FLAGS: + i += 2 + continue + if not arg.startswith("-") or arg == "-": + positional.append(arg) + i += 1 + if len(positional) < 2: + continue + source, destination = positional[:2] + pod, separator, remote = source.partition(":") + if not separator or not pod or not remote or ":" in destination: + continue + stream = destination in {"/dev/stdout", "/dev/fd/1", "/proc/self/fd/1"} + destinations = _stream_destinations(command) if stream else [destination] + if destination == "-": + destinations += _stream_destinations(command) + known_mount = remote.startswith(("/var/run/secrets/", "/run/secrets/")) + details = (f"{_binary_base(tokens[0])} {verb}", known_mount) + if local: + if stream: + _register_copy_text(output, session_key, details) + for dest in destinations: + _register_local_copy(_copy_path(dest, current_cwd), session_key, details) + with _POD_COPY_LOCK: + paths = _POD_COPY_PATHS.setdefault(session_key, {}) + for dest in destinations: + path = _copy_path(dest, current_cwd) + # Keep every destination: evicting a path would fail open. + paths[path] = details + + +def pod_copy_read(command: str, session_key: str, cwd: str | None) -> tuple[str, bool] | None: + """Identify a terminal read of a destination recorded for this session.""" + with _POD_COPY_LOCK: + paths = _POD_COPY_PATHS.get(session_key, {}).copy() + if not paths: + return None + has_cd = any(seg.strip().startswith("cd ") for seg in _command_segments(command)) + for segment in _command_segments(command): + try: + tokens = shlex.split(segment) + except ValueError: + continue + tokens = _strip_copy_prefix(tokens) + if tokens and _binary_base(tokens[0]) in {"echo", "rm"}: + continue + for arg in tokens[1:]: + if arg.startswith("-"): + continue + path = _copy_path(arg, cwd) + for destination, details in paths.items(): + if (path == destination or path.startswith(destination.rstrip(os.sep) + os.sep) + or (has_cd and os.path.basename(arg) == os.path.basename(destination))): + return details + return None + + +def redact_pod_copy_read(output: str, copy: tuple[str, bool] | None, *, audit: bool = True) -> str: + if output and copy and _redact_enabled(): + if audit: + verb, known_mount = copy + kind = "secret " if known_mount else "" + logger.info("Masked pod %scopy read-back (tool=%s, known_secret_mount=%s)", kind, verb, known_mount) + return "***" + return output + + REDACTION_UNAVAILABLE = "[redaction-unavailable]" # The opaque branch needs a 20-char floor (the floor the gateway/A2A sweeps always had): without it the # English word "bearer" turns "the bearer of bad news" into "Bearer [redacted] bad news" on every chat diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes_raw_read.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes_raw_read.py index c28684af6..ad351ab4f 100644 --- a/forks/hermes-agent/tests/agent/test_redact_kubernetes_raw_read.py +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes_raw_read.py @@ -23,6 +23,18 @@ def _ensure_redaction_enabled(monkeypatch): def _terminal(text, command): return [redact_terminal_output(text, command, force=True), redact_terminal_output(text, command)] +def _terminal_result(text, command, session_key): + import json + + from tools.terminal_tool_result import finalize_foreground_result + + result = finalize_foreground_result( + command=command, result={"output": text, "returncode": 0}, env=object(), env_type="local", + effective_task_id=session_key, task_id=session_key, session_id=None, session_key=session_key, + workdir=None, command_cwd="/tmp", approval_note=None, + ) + return json.loads(result)["output"] + # --- Bypass rows: the whole output is masked --------------------------------------------------- @@ -50,6 +62,7 @@ def _terminal(text, command): # R4: cp to /dev/stdout prints the copied file. R4_CP_STDOUT = [ ("cp-to-dev-stdout", "kubectl cp p:/var/run/secrets/x /dev/stdout"), + ("cp-to-dash-stdout", "kubectl cp p:/var/run/secrets/x -"), ] # R5: get --raw prints a raw API path, so a Secret comes back as a whole object. @@ -103,6 +116,325 @@ def test_r4_cp_to_stdout_masks_whole_output(command): assert out == "***", out +# R8: successful copies from a Secret mount stay tracked for later local file reads. +R8_COPY_SECRET_READBACK = [ + ("kubectl-cp", "kubectl cp p:/var/run/secrets/x ./copy", "cat ./copy"), + ("oc-rsync", "oc rsync p:/var/run/secrets/x ./copy", "cat ./copy"), +] + + +@pytest.mark.parametrize( + "copy_command,read_command", + [(copy, read) for _, copy, read in R8_COPY_SECRET_READBACK], + ids=[label for label, _, _ in R8_COPY_SECRET_READBACK], +) +def test_r8_secret_copy_readback_masks_output_and_audits(caplog, copy_command, read_command): + session_key = f"secret-copy-{copy_command.split()[0]}" + copied = _terminal_result("copy complete", copy_command, session_key) + assert copied == "***", copied + + with caplog.at_level("INFO", logger="agent.redact"): + read_back = _terminal_result(V, read_command, session_key) + assert read_back == "***", read_back + assert V not in caplog.text + assert "secret copy" in caplog.text.lower() + + other_session = _terminal_result(V, read_command, session_key + "-other") + assert V in other_session, other_session + + +def test_r8_secret_copy_detection_leaves_non_secret_source_readable(): + session_key = "non-secret-copy" + _terminal_result("copy complete", "kubectl cp ./input p:/etc/config", session_key) + read_back = _terminal_result(K, "cat ./copy", session_key) + assert K in read_back, read_back + + +@pytest.mark.parametrize("reader", ["cat", "head", "tail", "less", "grep pattern"]) +def test_r8_pod_copy_readers_and_nested_paths(reader): + session_key = f"pod-copy-reader-{reader}" + _terminal_result("done", "oc cp ns/pod:/arbitrary/mount ./directory", session_key) + assert _terminal_result(V, f"{reader} /tmp/directory/item", session_key) == "***" + + +@pytest.mark.parametrize("command", [ + "kubectl cp -n ns -c ctr pod:/x ./y", + "kubectl -n ns cp pod:/x ./y", + "oc rsync --exclude=x pod:/dir ./y", + "kubectl cp --container ctr pod:/x ./y", + "oc rsync --exclude x --include y pod:/dir ./y", + "kubectl cp --context ctx --kubeconfig cfg --retries 2 pod:/x ./y", +]) +def test_r8_copy_options_before_operands(command): + session_key = f"copy-options-{command}" + _terminal_result("done", command, session_key) + assert _terminal_result(V, "cat ./y", session_key) == "***" + + +def test_r8_failed_copy_attempt_is_tracked(): + from tools.terminal_tool_result import finalize_foreground_result + + key = "failed-pod-copy" + finalize_foreground_result(command="kubectl cp p:/data ./failed; false", result={"output": "error", "returncode": 1}, + env=object(), env_type="local", effective_task_id=key, task_id=key, + session_id=None, session_key=key, workdir=None, command_cwd="/tmp", approval_note=None) + assert _terminal_result(V, "cat ./failed", key) == "***" + + +@pytest.mark.parametrize("copy,read", [ + ("sudo -u root -E kubectl cp p:/x ./y", "sudo -E cat ./y"), + ("kubectl cp p:/x ./y", "base64 ./y"), + ("kubectl cp p:var/data ./y", "cat ./y"), + ("kubectl cp p:/x - > ./y", "cat ./y"), + ("kubectl cp p:/x - >> ./y", "cat ./y"), + ("kubectl cp p:/x - | tee -a ./y", "cat ./y"), + ("kubectl cp p:/x ./sub/y", "cd sub && cat y"), +]) +def test_r8_review_bypasses(copy, read): + key = f"review-{copy}-{read}" + _terminal_result("done", copy, key) + assert _terminal_result(V, read, key) == "***" + + +def test_r8_session_cleanup_and_limit(): + from agent.redact import _POD_COPY_MAX_PER_SESSION, _POD_COPY_PATHS + from tools.terminal_tool import _qualify_task_key, clear_session_cwd + + key = "review-cleanup" + for i in range(_POD_COPY_MAX_PER_SESSION + 1): + _terminal_result("done", f"kubectl cp p:/x ./file{i}", key) + scope = _qualify_task_key(key) + assert len(_POD_COPY_PATHS[scope]) == _POD_COPY_MAX_PER_SESSION + 1 + assert _terminal_result(V, "cat ./file0", key) == "***" + clear_session_cwd(key) + assert scope not in _POD_COPY_PATHS + assert _terminal_result(V, "cat ./file256", key) == V + + +def test_r8_audit_distinguishes_pod_copy(caplog): + key = "review-audit" + _terminal_result("done", "kubectl cp p:/other ./y", key) + with caplog.at_level("INFO", logger="agent.redact"): + assert _terminal_result(V, "cat ./y", key) == "***" + assert "pod copy read-back" in caplog.text + assert "secret copy" not in caplog.text + + +@pytest.mark.parametrize("command", [ + "grep -r . .", "grep -r s /tmp", "cat *", "cat y*", "bash -c 'cat y'", + "(cd sub && cat y)", "pushd sub && cat y", "cd\tsub && cat y", + "cd sub && cat d/file", "cat ./y", "kubectl cp p:/x - >| ./y", + "kubectl cp p:/x - | sudo tee ./y", "kubectl cp p:/x /dev/fd/1 > ./y", +]) +def test_r8_local_copy_wrappers_and_streams(tmp_path, copy): + import json + from types import SimpleNamespace + from tools.terminal_tool_result import finalize_foreground_result + + (tmp_path / "y").write_text(V) + key = f"local-copy-{copy}" + def run(cmd, text): + return json.loads(finalize_foreground_result( + command=cmd, result={"output": text, "returncode": 0}, env=SimpleNamespace(uses_host_filesystem=True), + env_type="local", effective_task_id=key, task_id=key, session_id=None, session_key=key, + workdir=None, command_cwd=str(tmp_path), approval_note=None))["output"] + run(copy, "done") + assert run("bash -c 'cat y'", V) == "***" + + +def test_r8_local_directory_values_and_limits(tmp_path): + from agent.redact import _POD_COPY_VALUES, clear_pod_copies, record_pod_copy, redact_pod_copy_values + + root = tmp_path / "copied" + root.mkdir() + (root / "one").write_text("TOKEN=" + V + "\n" + "x" * 300) + (root / "binary").write_bytes(b"\x00binary-secret-value") + (root / "oversize").write_text("z" * 65537) + key = "local-directory-values" + record_pod_copy("oc rsync p:/data ./copied", key, str(tmp_path), local=True) + assert redact_pod_copy_values(V, key) == "***" + assert redact_pod_copy_values("binary-secret-value", key) == "binary-secret-value" + assert all(len(value) <= 65536 for value in _POD_COPY_VALUES[key]) + clear_pod_copies(key) + assert key not in _POD_COPY_VALUES + + +def test_r8_local_stdout_value(tmp_path): + from agent.redact import clear_pod_copies, record_pod_copy, redact_pod_copy_values + + key = "local-stdout-value" + record_pod_copy("kubectl cp p:/data /dev/stdout", key, str(tmp_path), local=True, output=V) + assert redact_pod_copy_values(V, key) == "***" + clear_pod_copies(key) + + +def test_r8_value_formats_and_overlap(tmp_path): + import base64 + from agent.redact import clear_pod_copies, record_pod_copy, redact_pod_copy_values + + key = "formats-copy" + (tmp_path / "y").write_text('{"password": "abcdefgh12SECRETTAIL99"}') + record_pod_copy("kubectl cp p:/x y", key, str(tmp_path), local=True) + value = "abcdefgh12SECRETTAIL99" + for text in (value, base64.b64encode(value.encode()).decode(), value.encode().hex()): + assert redact_pod_copy_values(text, key) == "***" + clear_pod_copies(key) + + +@pytest.mark.parametrize("kind", ["many-files", "large", "binary", "non-utf8", "missing"]) +def test_r8_bounds_fail_closed(tmp_path, kind, caplog): + from agent.redact import clear_pod_copies, pod_copy_read, record_pod_copy, redact_pod_copy_values + + path = tmp_path / "y" + if kind == "many-files": + path.mkdir() + for n in range(65): + (path / str(n)).write_text("secret-value-123") + elif kind == "large": + path.write_bytes(b"x" * 65537) + elif kind == "binary": + path.write_bytes(b"\x00secret-value") + elif kind == "non-utf8": + path.write_bytes(b"\xffsecret-value") + key = "bounds-" + kind + record_pod_copy("kubectl cp p:/x y", key, str(tmp_path), local=True) + assert redact_pod_copy_values("hello", key) == "hello" + assert pod_copy_read("cat y", key, str(tmp_path)) is not None + assert V not in caplog.text + clear_pod_copies(key) + + +def test_r8_copy_destination_symlink_is_not_read(tmp_path): + from agent.redact import _POD_COPY_VALUES, clear_pod_copies, record_pod_copy + + target = tmp_path / "outside" + target.write_text(V) + (tmp_path / "link").symlink_to(target) + key = "link-copy" + record_pod_copy("kubectl cp p:/x link", key, str(tmp_path), local=True) + assert V not in _POD_COPY_VALUES.get(key, {}) + clear_pod_copies(key) + + + +def test_r8_plain_words_and_multiline_tokens(tmp_path): + from agent.redact import clear_pod_copies, record_pod_copy, redact_pod_copy_values + + (tmp_path / "cfg").write_text("kind: ConfigMap\nnamespace: production\nname: application\n# tokens\n" + V + "\n") + key = "plain-words" + record_pod_copy("kubectl cp p:/x cfg", key, str(tmp_path), local=True) + assert redact_pod_copy_values("kind: ConfigMap namespace: production Pod application-7f9", key) == "kind: ConfigMap namespace: production Pod application-7f9" + assert redact_pod_copy_values(V, key) == "***" + clear_pod_copies(key) + + +def test_r8_deployment_keys_remain_visible(tmp_path): + from agent.redact import clear_pod_copies, record_pod_copy, redact_pod_copy_values + + (tmp_path / "deployment").write_text("metadata:\n template:\n containers:\n - name: app\n") + key = "deployment-keys" + record_pod_copy("kubectl cp p:/x deployment", key, str(tmp_path), local=True) + text = "metadata:\n template:\n containers:" + assert redact_pod_copy_values(text, key) == text + clear_pod_copies(key) + + +@pytest.mark.parametrize("contents,value", [ + ("tokens:\n - secret-value-123\n", "secret-value-123"), + ("tokens:\nc2VjcmV0LXZhbHVlLTEyMw==\n", "c2VjcmV0LXZhbHVlLTEyMw=="), + ("tokens:\n#secret-value-123\n", "secret-value-123"), +], ids=["yaml-list", "base64-padding", "comment"]) +def test_r8_indirect_read_masks_list_and_padded_tokens(tmp_path, contents, value): + import json + from types import SimpleNamespace + from tools.terminal_tool import clear_session_cwd + from tools.terminal_tool_result import finalize_foreground_result + + (tmp_path / "tok").write_text(contents) + key = f"indirect-{contents}" + def run(command, output): + result = finalize_foreground_result( + command=command, result={"output": output, "returncode": 0}, + env=SimpleNamespace(uses_host_filesystem=True), env_type="local", + effective_task_id=key, task_id=key, session_id=None, session_key=key, + workdir=None, command_cwd=str(tmp_path), approval_note=None) + return json.loads(result)["output"] + run("kubectl cp pod:/tokens ./tok", "copied") + assert run("cat $(ls)", value) == "***" + clear_session_cwd(key) + + +def test_r8_binary_copy_does_not_black_out_session(tmp_path): + from agent.redact import clear_pod_copies, pod_copy_read, record_pod_copy, redact_pod_copy_values + + (tmp_path / "images").mkdir() + (tmp_path / "images" / "x.png").write_bytes(b"\x00PNG") + key = "binary-dir" + record_pod_copy("oc rsync p:/x images", key, str(tmp_path), local=True) + assert redact_pod_copy_values("hello", key) == "hello" + assert pod_copy_read("cat images/x.png", key, str(tmp_path)) is not None + clear_pod_copies(key) + +@pytest.mark.parametrize("command", [ + "cd sub && kubectl cp p:/x y", + "(cd sub && kubectl cp p:/x y)", + "timeout 30 kubectl cp p:/x sub/y", + "stdbuf -o0 kubectl cp p:/x sub/y", + "env -u FOO kubectl cp p:/x sub/y", + "bash -c 'kubectl cp p:/x sub/y'", + "kubectl cp p:/x ~/sub/y", + "kubectl cp p:/x $HOME/sub/y", +]) +def test_r8_local_copy_resolution(tmp_path, monkeypatch, command): + from agent.redact import clear_pod_copies, record_pod_copy, redact_pod_copy_values + + monkeypatch.setenv("HOME", str(tmp_path)) + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "y").write_text(V) + key = "resolve-" + command + record_pod_copy(command, key, str(tmp_path), local=True) + assert redact_pod_copy_values(V, key) == "***" + clear_pod_copies(key) + + +def test_r8_dash_destination(tmp_path): + from agent.redact import clear_pod_copies, record_pod_copy, redact_pod_copy_values + + (tmp_path / "-").write_text(V) + key = "dash-file" + record_pod_copy("kubectl cp p:/x -", key, str(tmp_path), local=True) + assert redact_pod_copy_values(V, key) == "***" + clear_pod_copies(key) + + @pytest.mark.parametrize("command", [c for _, c in R5_GET_RAW], ids=[i for i, _ in R5_GET_RAW]) def test_r5_get_raw_masks_whole_output(command): text = V + "\n" diff --git a/forks/hermes-agent/tools/terminal_tool.py b/forks/hermes-agent/tools/terminal_tool.py index a1f4d475d..22e5be697 100644 --- a/forks/hermes-agent/tools/terminal_tool.py +++ b/forks/hermes-agent/tools/terminal_tool.py @@ -287,6 +287,8 @@ def clear_session_cwd(session_key: str) -> None: """Drop a session's cwd record (session teardown).""" with _session_cwd_lock: _session_cwd.pop(_qualify_task_key(session_key), None) + from agent.redact import clear_pod_copies + clear_pod_copies(_qualify_task_key(str(session_key or "default"))) def _sanitize_cwd_for_live_env(env: Any, new_cwd: str) -> Optional[str]: diff --git a/forks/hermes-agent/tools/terminal_tool_result.py b/forks/hermes-agent/tools/terminal_tool_result.py index 47c9e7acd..0bfb7877e 100644 --- a/forks/hermes-agent/tools/terminal_tool_result.py +++ b/forks/hermes-agent/tools/terminal_tool_result.py @@ -167,20 +167,24 @@ def _failure_hint(command: str, returncode: int, output: str, exit_note) -> Opti return None -def _redact_spill_file(path, total_chars, command) -> list[tuple[str, Any]]: +def _redact_spill_file(path, total_chars, command, copy_read=None, copy_scope=None) -> list[tuple[str, Any]]: """Spill handle so the model can read the omitted middle instead of re-running. The collector wrote it raw; redact it with the same pass so no secret persists unmasked on disk. On failure drop the handle (and file).""" if not path: return [] try: - from agent.redact import redact_terminal_output + from agent.redact import redact_pod_copy_read, redact_pod_copy_values, redact_terminal_output from tools.ansi_strip import strip_ansi from tools.spill_safety import write_text_exclusive raw_spill = Path(path).read_text(encoding="utf-8-sig", errors="replace") # lstat-checked unlink + exclusive create: the redacted copy can't # be diverted through a symlink planted since the collector's write. - write_text_exclusive(Path(path), redact_terminal_output(strip_ansi(raw_spill), command), + safe_spill = redact_terminal_output(strip_ansi(raw_spill), command) + safe_spill = redact_pod_copy_read(safe_spill, copy_read, audit=False) + if copy_scope is not None: + safe_spill = redact_pod_copy_values(safe_spill, copy_scope, audit=False) + write_text_exclusive(Path(path), safe_spill, private=True, overwrite=True, errors="replace") except Exception: logger.debug("spill redaction failed; dropping spill handle", exc_info=True) @@ -210,7 +214,7 @@ def finalize_foreground_result( workdir: Optional[str], command_cwd: Optional[str], approval_note: Optional[str], ) -> str: """Turn a raw ``env.execute`` result into the tool's JSON result string.""" - from tools.terminal_tool import record_session_cwd + from tools.terminal_tool import _qualify_task_key, record_session_cwd # Record the cwd this command finished in as THIS session's durable cwd — # only when the command actually reported it (an interrupted/killed command @@ -232,15 +236,22 @@ def finalize_foreground_result( # Strip ANSI so the model never copies escapes into file writes, then # redact secrets; redact_terminal_output is command-aware (env-dump # commands get the KEY=value pass, source/config dumps skip it). - from agent.redact import redact_terminal_output + from agent.redact import pod_copy_read, record_pod_copy, redact_pod_copy_read, redact_pod_copy_values, redact_terminal_output from tools.ansi_strip import strip_ansi output = strip_ansi(output) + copy_scope = _qualify_task_key(str(session_key or "default")) + local_copy = env_type == "local" and getattr(env, "uses_host_filesystem", False) + record_pod_copy(command, copy_scope, command_cwd, local=local_copy, output=output) + copy_read = pod_copy_read(command, copy_scope, command_cwd) # For source/config dumps (MAX_TOKENS=100, "apiKey": "x" fixtures, postgresql:// f-string templates) the # ENV/JSON/template passes are skipped to avoid false positives (code_file=True). But for env-dump # commands (env/printenv/set/export/declare) the output IS a KEY=value credential dump, so # redact_terminal_output runs the ENV pass (code_file=False) to mask opaque tokens with no vendor # prefix. Real prefixes, auth headers, JWTs, private keys are masked in both modes. See issue #43025. - output = redact_terminal_output(output.strip(), command) if output else "" + if output: + output = redact_pod_copy_read(output.strip(), copy_read) + output = redact_pod_copy_values(output, copy_scope) + output = redact_terminal_output(output, command) exit_note = _interpret_exit_code(command, returncode) failure_hint = _failure_hint(command, returncode, output, exit_note) @@ -262,7 +273,8 @@ def finalize_foreground_result( optional_fields: list[tuple[str, Any]] = [ ("cwd", changed_cwd), ("environment_recreated", _ENV_RECREATED_NOTE if result.get("environment_recreated") else None), - *_redact_spill_file(result.get("full_output_path"), result.get("output_total_chars"), command), + *_redact_spill_file(result.get("full_output_path"), result.get("output_total_chars"), command, copy_read, + copy_scope if local_copy else None), ("verification_evidence", _verification_evidence( command, command_cwd, session_id or task_id or effective_task_id or "default", returncode, output, result.get("pipeline_status"))),