diff --git a/forks/hermes-agent/agent/redact_kubernetes.py b/forks/hermes-agent/agent/redact_kubernetes.py index dacc92ddb..41de68de1 100644 --- a/forks/hermes-agent/agent/redact_kubernetes.py +++ b/forks/hermes-agent/agent/redact_kubernetes.py @@ -398,7 +398,16 @@ def _yaml_data_block(bodies, indents, offs, i, col, out) -> int: _GO_NAME_RE = re.compile(r"(?:^| )name:([^\s\]]+)") _GO_VALUE_RE = re.compile(r"(?:^| )value:") _DESCRIBE_NAME_RE = re.compile(r"([A-Za-z_][\w.\-]*):(?:[ \t]+|$)") -_DESCRIBE_REF_RE = re.compile(r"|.*\(v1:") +_DESCRIBE_REF_RE = re.compile(r"]*>(?:\s+Optional: \w+)?\s*$|\s*$") +# An inline ``Command: argv`` or ``Args: argv`` header line: the value after the header. +_DESCRIBE_ARGV_RE = re.compile(r"(?:Command|Args):[ \t]+") +# A bare ``Key:`` sub-header in a Spec block (``Chart:``, ``Values:``): no value on the line. +_DESCRIBE_KEY_LINE_RE = re.compile(r"[A-Za-z_][\w.\-]*:") +# A plain Spec key (no ``/``, space, ``$``): anything else is masked whole. +_DESCRIBE_PLAIN_KEY_RE = re.compile(r"[A-Za-z_][\w\-]*") +# A ``kubectl describe`` header: a column-zero ``Name:`` or ``Namespace:`` line. Python source and +# docstrings never print one at column zero, so the Command/Args/Spec rules need it. +_DESCRIBE_HEADER_RE = re.compile(r"^(?:Name|Namespace):[ \t]", re.MULTILINE) def _flow_spans(text: str) -> list: @@ -430,32 +439,72 @@ def _flow_spans(text: str) -> list: def _describe_spans(text: str) -> list: - """``NAME: value`` lines inside an ``Environment:`` block. A value that runs over several - lines (a PEM key, a multi-line string) masks every following line up to the next - ``NAME:`` line or the end of the block.""" - spans, pos, env_indent, in_value = [], 0, -1, False + """Values in ``kubectl describe`` output that must not reach the model. + + ``Environment:``: a ``NAME: value`` line is masked when NAME is secret-named. A value that + runs over several lines (a PEM key) masks every following line up to the next ``NAME:``. + ``Command:`` / ``Args:``: every line under the header is masked. Argv carries literal + values with no name to match on (``--db-pass=``, a bare token). + ``Spec:`` (CRD describe): every ``key: value`` scalar under the header is masked, so a + credential under a neutral key (``adminPassword``, a HelmRelease ``values``) stays hidden. + A ```` reference is not a value. Other sections (``Status:``, ``Name:``) + are not touched. + """ + describe = _DESCRIBE_HEADER_RE.search(text) is not None + spans, pos = [], 0 + env_indent, in_value = -1, False + block_indent, block_kind, key_indent = -1, "", -1 for line in text.split("\n"): body = line.removesuffix("\r") stripped = body.lstrip(" \t") lead = len(body) - len(stripped) indent = len(body[:lead].expandtabs(8)) - if env_indent >= 0 and stripped: - if indent <= env_indent: + if stripped: + if block_indent >= 0 and indent <= block_indent: + block_indent, block_kind, key_indent = -1, "", -1 + if env_indent >= 0 and indent <= env_indent: env_indent, in_value = -1, False - else: - m = _DESCRIBE_NAME_RE.match(stripped) - if m is None: - if in_value: - spans.append((pos + lead, pos + len(body), None)) + if block_indent >= 0 and stripped and not stripped.startswith("#"): + m = _DESCRIBE_NAME_RE.match(stripped) + if block_kind == "Spec" and m is not None and (key_indent < 0 or indent <= key_indent) \ + and _DESCRIBE_PLAIN_KEY_RE.fullmatch(m.group(1)): + if key_indent < 0: + key_indent = indent # the first key under the header sets the key column + if _DESCRIBE_KEY_LINE_RE.fullmatch(stripped): + key_indent = indent # a bare sub-header: its value lines are deeper else: value = stripped[m.end():].rstrip() - in_value = bool(value) and _secret_name(m.group(1), value) \ - and not _DESCRIBE_REF_RE.match(value) - if in_value: + if value and not _DESCRIBE_REF_RE.match(value): s = pos + lead + m.end() spans.append((s, s + len(value), None)) + elif block_kind == "Spec" and indent > key_indent >= 0: + spans.append((pos + lead, pos + len(body), None)) # block-scalar continuation + elif block_kind == "Spec" and key_indent < 0 or block_kind == "Spec" and indent <= key_indent: + spans.append((pos + lead, pos + len(body), None)) # not a plain key: mask whole + elif block_kind != "Spec": + spans.append((pos + lead, pos + len(body), None)) + if env_indent >= 0 and stripped: + m = _DESCRIBE_NAME_RE.match(stripped) + if m is None: + if in_value: + spans.append((pos + lead, pos + len(body), None)) + else: + value = stripped[m.end():].rstrip() + in_value = bool(value) and _secret_name(m.group(1), value) \ + and not _DESCRIBE_REF_RE.match(value) + if in_value: + s = pos + lead + m.end() + spans.append((s, s + len(value), None)) if stripped.rstrip() == "Environment:": env_indent, in_value = indent, False + elif block_indent < 0 and stripped.rstrip() in ("Command:", "Args:", "Spec:") and ( + describe or (indent == 0 and stripped.rstrip() == "Spec:")): + block_indent, block_kind, key_indent = indent, stripped.rstrip()[:-1], -1 + else: + m = _DESCRIBE_ARGV_RE.match(stripped) if describe else None + if m is not None and m.end() < len(stripped): + s = pos + lead + m.end() + spans.append((s, pos + len(body.rstrip()), None)) pos += len(line) + 1 return spans @@ -469,6 +518,6 @@ def redact_kubernetes(text: str, mask: str = "***") -> str: spans += _yaml_spans(text, mask) if "value:" in text: spans += _flow_spans(text) - if "Environment:" in text: + if "Environment:" in text or "Command:" in text or "Args:" in text or "Spec:" in text: spans += _describe_spans(text) return _apply(text, spans, mask) diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes_describe_12026.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes_describe_12026.py new file mode 100644 index 000000000..518e027d9 --- /dev/null +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes_describe_12026.py @@ -0,0 +1,184 @@ +"""RIG-12026: ``kubectl describe`` leaks the values under ``Command:``, ``Args:`` and a CRD's +``Spec:``. Rows go through ``redact_terminal_output`` (the entry point tool output uses), with +``force`` on and off, so a row passes whichever layer masks it. + +Leak rows: a literal value in Command, Args, or a CRD Spec must not reach the output. +Keep rows: Name, Status, Events, and node or namespace describes stay readable. +""" + +import pytest + +from agent.redact import redact_terminal_output + +V = "zzqq" + "-fixture-leak-value-A12026" +K = "keep-visible-a12026" + + +@pytest.fixture(autouse=True) +def _ensure_redaction_enabled(monkeypatch): + monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False) + monkeypatch.setattr("agent.redact._REDACT_ENABLED", True) + + +def _terminal(text, command): + return [redact_terminal_output(text, command, force=True), redact_terminal_output(text, command)] + + +POD_ARGS = ( + "Name: web\n" + "Containers:\n" + " app:\n" + " Image: nginx\n" + " Args:\n" + " --db-pass=" + V + "\n" + " State: Running\n" +) + +POD_COMMAND = ( + "Name: web\n" + "Containers:\n" + " app:\n" + " Command:\n" + " /bin/sh\n" + " -c\n" + " run.sh " + V + "\n" + " State: Running\n" +) + +DEPLOY_COMMAND_INLINE = ( + "Name: web\n" + "Pod Template:\n" + " Containers:\n" + " app:\n" + " Command: run.sh --token=" + V + "\n" + " Replicas: 2\n" +) + +CRD_SPEC = ( + "Name: foo\n" + "Namespace: flux-system\n" + "Kind: HelmRelease\n" + "Spec:\n" + " Chart:\n" + " Spec:\n" + " Chart: podinfo\n" + " Values:\n" + " adminPassword: " + V + "\n" + "Status:\n" + " Conditions:\n" + " Type: Ready\n" + " Status: True\n" +) + +POD_ENV_SECRET = ( + "Name: web\n" + "Containers:\n" + " app:\n" + " Environment:\n" + " DB_PASSWORD: " + V + "\n" + " LOG_LEVEL: info\n" +) + + +# --- Leak rows: the value must not reach the output ------------------------------------------- + +@pytest.mark.parametrize("command", ["kubectl describe pod web", "kubectl describe pod web -n default"]) +def test_describe_pod_args_value_masked(command): + for out in _terminal(POD_ARGS, command): + assert V not in out, out + + +def test_describe_pod_command_value_masked(): + for out in _terminal(POD_COMMAND, "kubectl describe pod web"): + assert V not in out, out + assert "State: Running" in out, out + + +def test_describe_deploy_command_inline_value_masked(): + for out in _terminal(DEPLOY_COMMAND_INLINE, "kubectl describe deploy web"): + assert V not in out, out + assert "Replicas: 2" in out, out + + +def test_describe_crd_spec_value_masked(): + for out in _terminal(CRD_SPEC, "kubectl describe crd helmreleases.helm.toolkit.fluxcd.io foo"): + assert V not in out, out + + +def test_describe_pod_env_secret_value_masked(): + # Already masked before RIG-12026; pinned so the workload env path cannot regress. + for out in _terminal(POD_ENV_SECRET, "kubectl describe pod web"): + assert V not in out, out + assert "LOG_LEVEL: info" in out, out + + +# --- Keep rows: harmless describe fields stay readable ----------------------------------------- + +def test_keep_crd_name_and_status_readable(): + for out in _terminal(CRD_SPEC, "kubectl describe crd helmreleases.helm.toolkit.fluxcd.io foo"): + assert "Name: foo" in out, out + assert "Namespace: flux-system" in out, out + assert "Type: Ready" in out, out + + +def test_keep_pod_events_readable(): + text = ( + "Name: web\n" + "Containers:\n" + " app:\n" + " State: Running\n" + "Events:\n" + " Type Reason Age From Message\n" + " Normal Pulled 2m kubelet Container image pulled " + K + "\n" + ) + for out in _terminal(text, "kubectl describe pod web"): + assert K in out, out + assert "Pulled" in out, out + + +def test_keep_node_describe_unmasked(): + text = ( + "Name: node-1\n" + "Roles: worker\n" + "Labels: zone=" + K + "\n" + "Conditions:\n" + " Type Status\n" + " Ready True\n" + ) + for out in _terminal(text, "kubectl describe node node-1"): + assert out != "***", out + assert K in out, out + + +def test_keep_namespace_describe_unmasked(): + text = "Name: team-" + K + "\nLabels: env=dev\nStatus: Active\n" + for out in _terminal(text, "kubectl describe namespace team"): + assert out != "***", out + assert K in out, out + + +# --- Known gaps pinned as xfail (RIG-12026 review, low) ----------------------------------------- + +@pytest.mark.xfail(reason="known gap: an indented Name: header disables the describe gate", strict=True) +def test_known_gap_indented_name_header_spec_value(): + text = " Name: web\n Spec:\n adminPassword: " + V + "\n" + for out in _terminal(text, "kubectl describe crd foo"): + assert V not in out, out + + +# --- Round-2 regressions (interdiff review of 295215dd): Spec shapes the key rule misses --------- + +ROUND2_SPEC_SHAPES = [ + ("dotted-key", "Name: foo\nSpec:\n example.com/api-key: " + V + "\n"), + ("space-key", "Name: foo\nSpec:\n Admin Password: " + V + "\n"), + ("list-under-key", "Name: foo\nSpec:\n args:\n - " + V + "\n"), + ("list-under-spec", "Name: foo\nSpec:\n - " + V + "\n"), + ("bare-key-column-line", "Name: foo\nSpec:\n a: 1\n " + V + "\n"), + ("command-key-in-spec", "Name: foo\nSpec:\n Command:\n /bin/sh -c " + V + "\n"), +] + + +@pytest.mark.parametrize("name,text", ROUND2_SPEC_SHAPES, ids=[n for n, _ in ROUND2_SPEC_SHAPES]) +def test_round2_spec_shape_masked(name, text): + for out in _terminal(text, "kubectl describe crd foo"): + assert V not in out, out