From eb89e139117f33daa344283c51addbe01911fa07 Mon Sep 17 00:00:00 2001 From: mintaka Date: Sat, 21 Nov 2026 15:48:36 -0500 Subject: [PATCH 1/4] fix(hermes): mask Kubernetes Secret data and env values (RIG-11725) Add a Kubernetes pass to redact_sensitive_text. It masks Secret data and stringData values (YAML and JSON, including truncated JSON), env value entries under a secret-named name (YAML, JSON either order, kubectl describe Environment blocks). Keys, ConfigMap data, valueFrom and non-secret env stay. All scans are linear; a 1 MB test runs under 1 s. Refs RIG-11725 Co-authored-by: Matt Wilkinson --- forks/hermes-agent/agent/redact.py | 160 +++++++++++++++++- .../tests/agent/test_redact_kubernetes.py | 138 +++++++++++++++ 2 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 forks/hermes-agent/tests/agent/test_redact_kubernetes.py diff --git a/forks/hermes-agent/agent/redact.py b/forks/hermes-agent/agent/redact.py index c23e67d25..754275b2d 100644 --- a/forks/hermes-agent/agent/redact.py +++ b/forks/hermes-agent/agent/redact.py @@ -1420,7 +1420,9 @@ def _redact_yaml(m): if quote and (not inner or _DSN_PW_PLACEHOLDER_RE.fullmatch(inner) or (inner.startswith("{{") and inner.endswith("}}"))): # Helm/Jinja template return m.group(0) - if not _should_redact_assignment(key, inner, check_keyword=True): + # ``kubectl describe``'s ```` names a reference, not a value. + if not _should_redact_assignment(key, inner, check_keyword=True) \ + or (inner == " bool: or password.casefold() in _USERINFO_PLACEHOLDER_WORDS) +# --- Kubernetes objects (RIG-11725) ----------------------------------------------------------- +# Secret ``data``/``stringData`` values and env ``value``s under a secret-named ``name`` reach the +# model through kubectl output; their keys are neutral (``connection``, ``value``), so the keyword +# assignment passes never see them. Every scan is a single linear pass over lines or a regex +# without nested quantifiers, so 1 MB of manifests stays well under a second. +_K8S_SECRET_NAME_RE = re.compile(r"PASSWORD|PASSWD|SECRET|CREDENTIAL|TOKEN|(?:^|[_.\-])(?:API)?KEYS?(?:$|[_.\-])", + re.IGNORECASE) +_K8S_SEGMENT_RE = re.compile(r'^[ \t]*(?:- )?apiVersion:|^---[ \t]*$|"apiVersion"[ \t]*:', re.MULTILINE) +_K8S_SECRET_KIND_RE = re.compile(r'^[ \t]*(?:- )?kind:[ \t]*["\']?Secret["\']?[ \t]*$|"kind"[ \t]*:[ \t]*"Secret"', + re.MULTILINE) +_K8S_YAML_LINE_RE = re.compile(r"^[ \t]*(?:- )?[^\s:#][^:]*:(?:[ \t]+(\S.*))?$") +_K8S_JSON_DATA_RE = re.compile(r'"(?:data|stringData)"[ \t\r\n]*:[ \t\r\n]*\{') +_K8S_JSON_STR_RE = re.compile(r'"(?:\\.|[^"\\])*"?') +_K8S_JSON_ENV_RE = re.compile( + r'"name"\s*:\s*"([^"\\]{1,256})"\s*,\s*"value"\s*:\s*"((?:\\.|[^"\\])*)"' + r'|"value"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"name"\s*:\s*"([^"\\]{1,256})"') +_K8S_YAML_ENV_RE = re.compile( + r"^([ \t]*)- name:[ \t]*[\"']?([^\s\"']+)[\"']?[ \t]*\r?\n\1 value:[ \t]*(\S[^\r\n]*?)[ \t]*$" + r"|^([ \t]*)- value:[ \t]*(\S[^\r\n]*?)[ \t]*\r?\n\4 name:[ \t]*[\"']?([^\s\"']+)[\"']?[ \t]*$", + re.MULTILINE) +_K8S_DESCRIBE_REF_RE = re.compile(r"") +_K8S_MASK = "***" + + +def _k8s_secret_name(name: str) -> bool: + return _K8S_SECRET_NAME_RE.search(name) is not None + + +def _k8s_mask_yaml_data(seg: str) -> str: + """Mask every value under a ``data:``/``stringData:`` mapping in one YAML segment.""" + lines = seg.split("\n") + data_indent = block_indent = -1 + for i, line in enumerate(lines): + stripped = line.lstrip(" \t") + indent = len(line) - len(stripped) + if block_indent >= 0: # inside a ``|``/``>`` block scalar of a data entry + if not stripped or indent > block_indent: + if stripped: + lines[i] = line[:indent] + _K8S_MASK + continue + block_indent = -1 + if data_indent >= 0: + if not stripped or stripped.startswith("#"): + continue + if indent <= data_indent: + data_indent = -1 + else: + m = _K8S_YAML_LINE_RE.match(line.rstrip()) + if m and m.group(1): + if m.group(1)[0] in "|>": + block_indent = indent + elif m.group(1) != _K8S_MASK: + lines[i] = line[:m.start(1)] + _K8S_MASK + continue + if stripped.rstrip() in ("data:", "stringData:"): + data_indent = indent + return "\n".join(lines) + + +def _k8s_mask_json_data(seg: str) -> str: + """Mask string values inside ``"data": {...}`` maps; a truncated map is masked to the end.""" + out, pos = [], 0 + for m in _K8S_JSON_DATA_RE.finditer(seg): + if m.start() < pos: + continue + out.append(seg[pos:m.end()]) + i, n, expect_value = m.end(), len(seg), False + while i < n: + c = seg[i] + if c == "}": + break + if c == '"': + s = _K8S_JSON_STR_RE.match(seg, i) + closed = len(s.group(0)) > 1 and s.group(0).endswith('"') + if expect_value: + out.append('"' + _K8S_MASK + ('"' if closed else "")) + expect_value = False + else: + out.append(s.group(0)) + i = s.end() + continue + if c == ":": + expect_value = True + elif c == ",": + expect_value = False + out.append(c) + i += 1 + pos = i + out.append(seg[pos:]) + return "".join(out) + + +def _k8s_mask_describe_env(text: str) -> str: + """``kubectl describe`` lines ``NAME: value`` inside an ``Environment:`` block.""" + lines = text.split("\n") + env_indent = -1 + for i, line in enumerate(lines): + stripped = line.lstrip(" \t") + indent = len(line) - len(stripped) + if env_indent >= 0: + if not stripped: + continue + if indent <= env_indent: + env_indent = -1 + else: + name, sep, rest = stripped.partition(":") + value = rest.strip() + if sep and value and _k8s_secret_name(name) and value != _K8S_MASK \ + and not _K8S_DESCRIBE_REF_RE.match(value): + lines[i] = line[:indent] + name + sep + rest.replace(value, _K8S_MASK, 1) + continue + if stripped.rstrip() == "Environment:": + env_indent = indent + return "\n".join(lines) + + +def _k8s_env_sub(m: "re.Match[str]", name_group: int, value_group: int, alt_name: int, alt_value: int) -> str: + if m.group(name_group) is not None: + name, start, end = m.group(name_group), m.start(value_group), m.end(value_group) + else: + name, start, end = m.group(alt_name), m.start(alt_value), m.end(alt_value) + if not _k8s_secret_name(name) or m.string[start:end] == _K8S_MASK: + return m.group(0) + return m.string[m.start():start] + _K8S_MASK + m.string[end:m.end()] + + +def _redact_kubernetes(text: str) -> str: + """Mask Kubernetes Secret data values and secret-named env values (YAML, JSON, describe).""" + if "Secret" in text and "ata" in text: + bounds = [m.start() for m in _K8S_SEGMENT_RE.finditer(text)] + if not bounds or bounds[0] != 0: + bounds.insert(0, 0) + bounds.append(len(text)) + parts = [] + for a, b in zip(bounds, bounds[1:]): + seg = text[a:b] + if _K8S_SECRET_KIND_RE.search(seg): + if "ata:" in seg: + seg = _k8s_mask_yaml_data(seg) + if '"' in seg: + seg = _k8s_mask_json_data(seg) + parts.append(seg) + text = "".join(parts) + if "value" in text and "name" in text: + if '"' in text: + text = _K8S_JSON_ENV_RE.sub(lambda m: _k8s_env_sub(m, 1, 2, 4, 3), text) + text = _K8S_YAML_ENV_RE.sub(lambda m: _k8s_env_sub(m, 2, 3, 6, 5), text) + if "Environment:" in text: + text = _k8s_mask_describe_env(text) + return text + + def _redact_userinfo_passwords(text: str) -> str: """Mask the password half of ``scheme://user:pass@host`` userinfo (#125664). @@ -1558,6 +1712,10 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F _zhipu_sub = _mask_token_nonreusable if file_read else _mask_token text = _ZHIPU_API_KEY_RE.sub(lambda m: _zhipu_sub(m.group(1)), text) + # Kubernetes Secret data / secret env values run in every mode: the source is a live object, + # never a code fixture, and kubectl output is how the model sees them (RIG-11725). + text = _redact_kubernetes(text) + if not code_file: text = _redact_assignments(text, mask_nonreusable=file_read) diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes.py new file mode 100644 index 000000000..bb82d3ad2 --- /dev/null +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes.py @@ -0,0 +1,138 @@ +"""Kubernetes secret values that leaked past agent.redact (RIG-11725). + +The shapes match the upstream secret-redact extension: the ``data`` and ``stringData`` of a +``kind: Secret`` object, and the ``value`` of an env entry whose ``name`` is secret-named, in YAML, +JSON and ``kubectl describe`` output. Neutral keys, non-Secret kinds, ``valueFrom`` entries and +non-secret names stay byte-identical. +""" + +import base64 +import time + +import pytest + +from agent.redact import redact_sensitive_text + +V = "zzqq-fixture-8k2Lm4Pq9Wx" +B64 = base64.b64encode(V.encode()).decode() +# The part of V that no head/tail mask shows. +MIDDLE = V[6:-4] + +SECRET_YAML = f"apiVersion: v1\nkind: Secret\nmetadata:\n name: db\ntype: Opaque\ndata:\n connection: {B64}\n" +SECRET_STRING_DATA_YAML = f"kind: Secret\nstringData:\n connection: {V}\n" +SECRET_JSON_PRETTY = '{\n "kind": "Secret",\n "data": {\n "connection": "' + B64 + '"\n }\n}' +SECRET_JSON_COMPACT = '{"kind":"Secret","data":{"connection":"' + B64 + '"}}' +SECRET_STRING_DATA_JSON = '{"kind":"Secret","stringData":{"connection":"' + V + '"}}' + +ENV_YAML = ( + "spec:\n containers:\n - name: app\n env:\n" + f" - name: DB_PASSWORD\n value: {V}\n" + " - name: LOG_LEVEL\n value: info\n" +) +ENV_JSON_COMPACT = '{"name":"DB_PASSWORD","value":"' + V + '"}' +ENV_JSON_PRETTY = '{\n "name": "DB_PASSWORD",\n "value": "' + V + '"\n}' +ENV_JSON_REVERSED = '{"value":"' + V + '","name":"DB_PASSWORD"}' + +DESCRIBE = ( + "Name: web-0\nNamespace: app\nContainers:\n app:\n Image: example/app:1\n" + " Environment:\n" + f" DB_PASSWORD: {V}\n" + " LOG_LEVEL: info\n" + " API_TOKEN: \n" + " Mounts:\n /data from data (rw)\n" +) + + +@pytest.fixture(autouse=True) +def _ensure_redaction_enabled(monkeypatch): + monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False) + monkeypatch.setattr("agent.redact._REDACT_ENABLED", True) + + +def _modes(text: str) -> list[str]: + return [redact_sensitive_text(text, force=True), + redact_sensitive_text(text, force=True, file_read=True, secret_file=True), + redact_sensitive_text(text)] + + +class TestSecretData: + """A value under ``data:`` or ``stringData:`` of a kind: Secret object is a credential.""" + + @pytest.mark.parametrize("text, secret", [ + (SECRET_YAML, B64), + (SECRET_JSON_PRETTY, B64), + (SECRET_JSON_COMPACT, B64), + (SECRET_STRING_DATA_YAML, V), + (SECRET_STRING_DATA_JSON, V), + ]) + def test_value_masked_in_every_mode(self, text, secret): + for out in _modes(text): + assert secret not in out, out + + @pytest.mark.parametrize("text", [SECRET_YAML, SECRET_JSON_COMPACT]) + def test_object_keys_kept(self, text): + out = redact_sensitive_text(text, force=True) + assert "connection" in out and "Secret" in out + + def test_configmap_data_kept(self): + text = f"apiVersion: v1\nkind: ConfigMap\ndata:\n connection: {B64}\n" + assert _modes(text) == [text, text, text] + + +class TestEnvValues: + """An env ``value`` whose sibling ``name`` is secret-named is masked; the rest stay.""" + + @pytest.mark.parametrize("text", [ENV_YAML, ENV_JSON_COMPACT, ENV_JSON_PRETTY, ENV_JSON_REVERSED]) + def test_secret_named_value_masked(self, text): + for out in _modes(text): + assert V not in out, out + assert MIDDLE not in out, out + + def test_truncated_secret_json_masked(self): + text = '{"kind":"Secret","data":{"a":"' + B64 + '","connection":"' + B64[:20] + for out in _modes(text): + assert B64[:20] not in out, out + + @pytest.mark.parametrize("text", [ENV_YAML, "[" + ENV_JSON_COMPACT + ',{"name":"LOG_LEVEL","value":"info"}]']) + def test_plain_name_value_kept(self, text): + out = redact_sensitive_text(text, force=True) + assert "LOG_LEVEL" in out + assert "value: info" in out or '"value":"info"' in out + + @pytest.mark.parametrize("text", [ + " - name: DB_PASSWORD\n valueFrom:\n secretKeyRef:\n name: db\n key: password\n", + '{"name":"DB_PASSWORD","valueFrom":{"secretKeyRef":{"name":"db","key":"password"}}}', + ]) + def test_value_from_kept(self, text): + assert _modes(text) == [text, text, text] + + +class TestDescribe: + """``kubectl describe`` env lines: ``NAME: value``, read only inside an Environment block.""" + + def test_secret_named_value_masked(self): + for out in _modes(DESCRIBE): + assert MIDDLE not in out, out + + def test_plain_name_and_reference_kept(self): + for out in _modes(DESCRIBE): + assert "LOG_LEVEL: info" in out, out + assert "" in out, out + + +class TestPerformance: + def test_one_megabyte_under_a_second(self): + block = SECRET_YAML + ENV_YAML + SECRET_JSON_PRETTY + ENV_JSON_PRETTY + big = block * (1_000_000 // len(block) + 1) + assert len(big) >= 1_000_000 + start = time.perf_counter() + out = redact_sensitive_text(big, force=True) + elapsed = time.perf_counter() - start + assert elapsed < 1.0, elapsed + assert V not in out and B64 not in out + + def test_one_megabyte_mixed_shapes_leaks_nothing(self): + block = SECRET_YAML + ENV_YAML + SECRET_JSON_COMPACT + ENV_JSON_COMPACT + DESCRIBE + big = block * (1_000_000 // len(block) + 1) + out = redact_sensitive_text(big, force=True) + assert V not in out and B64 not in out From 994ffb3d75bf22ea5ef0cebca2cbed248fbbacb4 Mon Sep 17 00:00:00 2001 From: mintaka Date: Sat, 21 Nov 2026 17:10:50 -0500 Subject: [PATCH 2/4] fix(hermes): mask cut-off, listed and annotated Kubernetes secrets Move the Kubernetes pass to agent/redact_kubernetes.py, a span-based module. JSON is read in one token pass with an object stack. Each object is decided when it closes or when the text ends, so kubectl key order (data before kind), cut-off output, Lists, SecretList and the last-applied-configuration annotation are masked. YAML is read in one line pass. Helm flow env, Go-map env and describe lines are covered. Secret names add PASS, PWD and AUTH; _TTL, _PATH and _FILE names stay visible. Every review probe row is a test; 1 MB perf rows run under 1 s. Refs RIG-11725 Co-authored-by: Matt Wilkinson --- forks/hermes-agent/agent/redact.py | 155 +------ forks/hermes-agent/agent/redact_kubernetes.py | 423 ++++++++++++++++++ .../agent/test_redact_kubernetes_shapes.py | 174 +++++++ 3 files changed, 599 insertions(+), 153 deletions(-) create mode 100644 forks/hermes-agent/agent/redact_kubernetes.py create mode 100644 forks/hermes-agent/tests/agent/test_redact_kubernetes_shapes.py diff --git a/forks/hermes-agent/agent/redact.py b/forks/hermes-agent/agent/redact.py index 754275b2d..0c62d7ce3 100644 --- a/forks/hermes-agent/agent/redact.py +++ b/forks/hermes-agent/agent/redact.py @@ -17,6 +17,7 @@ # drift: a blocked file_tools read that falls back to ``cat`` is still caught. from agent.file_safety import _BLOCKED_PROJECT_ENV_BASENAMES as _ENV_FILE_BASENAMES from agent.redact_connstr import _KV_CONNSTR_GATE_RE, _redact_kv_connection_strings +from agent.redact_kubernetes import redact_kubernetes from agent.redact_headers import ( _COOKIE_HEADER_JSON_RE, _COOKIE_HEADER_JSON_UNTERMINATED_RE, _SECRET_HEADER_JSON_RE, _SECRET_HEADER_JSON_UNTERMINATED_RE, json_header_value_is_credential, redact_cookie_assignments, @@ -1446,158 +1447,6 @@ def _is_userinfo_placeholder(password: str) -> bool: or password.casefold() in _USERINFO_PLACEHOLDER_WORDS) -# --- Kubernetes objects (RIG-11725) ----------------------------------------------------------- -# Secret ``data``/``stringData`` values and env ``value``s under a secret-named ``name`` reach the -# model through kubectl output; their keys are neutral (``connection``, ``value``), so the keyword -# assignment passes never see them. Every scan is a single linear pass over lines or a regex -# without nested quantifiers, so 1 MB of manifests stays well under a second. -_K8S_SECRET_NAME_RE = re.compile(r"PASSWORD|PASSWD|SECRET|CREDENTIAL|TOKEN|(?:^|[_.\-])(?:API)?KEYS?(?:$|[_.\-])", - re.IGNORECASE) -_K8S_SEGMENT_RE = re.compile(r'^[ \t]*(?:- )?apiVersion:|^---[ \t]*$|"apiVersion"[ \t]*:', re.MULTILINE) -_K8S_SECRET_KIND_RE = re.compile(r'^[ \t]*(?:- )?kind:[ \t]*["\']?Secret["\']?[ \t]*$|"kind"[ \t]*:[ \t]*"Secret"', - re.MULTILINE) -_K8S_YAML_LINE_RE = re.compile(r"^[ \t]*(?:- )?[^\s:#][^:]*:(?:[ \t]+(\S.*))?$") -_K8S_JSON_DATA_RE = re.compile(r'"(?:data|stringData)"[ \t\r\n]*:[ \t\r\n]*\{') -_K8S_JSON_STR_RE = re.compile(r'"(?:\\.|[^"\\])*"?') -_K8S_JSON_ENV_RE = re.compile( - r'"name"\s*:\s*"([^"\\]{1,256})"\s*,\s*"value"\s*:\s*"((?:\\.|[^"\\])*)"' - r'|"value"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"name"\s*:\s*"([^"\\]{1,256})"') -_K8S_YAML_ENV_RE = re.compile( - r"^([ \t]*)- name:[ \t]*[\"']?([^\s\"']+)[\"']?[ \t]*\r?\n\1 value:[ \t]*(\S[^\r\n]*?)[ \t]*$" - r"|^([ \t]*)- value:[ \t]*(\S[^\r\n]*?)[ \t]*\r?\n\4 name:[ \t]*[\"']?([^\s\"']+)[\"']?[ \t]*$", - re.MULTILINE) -_K8S_DESCRIBE_REF_RE = re.compile(r"") -_K8S_MASK = "***" - - -def _k8s_secret_name(name: str) -> bool: - return _K8S_SECRET_NAME_RE.search(name) is not None - - -def _k8s_mask_yaml_data(seg: str) -> str: - """Mask every value under a ``data:``/``stringData:`` mapping in one YAML segment.""" - lines = seg.split("\n") - data_indent = block_indent = -1 - for i, line in enumerate(lines): - stripped = line.lstrip(" \t") - indent = len(line) - len(stripped) - if block_indent >= 0: # inside a ``|``/``>`` block scalar of a data entry - if not stripped or indent > block_indent: - if stripped: - lines[i] = line[:indent] + _K8S_MASK - continue - block_indent = -1 - if data_indent >= 0: - if not stripped or stripped.startswith("#"): - continue - if indent <= data_indent: - data_indent = -1 - else: - m = _K8S_YAML_LINE_RE.match(line.rstrip()) - if m and m.group(1): - if m.group(1)[0] in "|>": - block_indent = indent - elif m.group(1) != _K8S_MASK: - lines[i] = line[:m.start(1)] + _K8S_MASK - continue - if stripped.rstrip() in ("data:", "stringData:"): - data_indent = indent - return "\n".join(lines) - - -def _k8s_mask_json_data(seg: str) -> str: - """Mask string values inside ``"data": {...}`` maps; a truncated map is masked to the end.""" - out, pos = [], 0 - for m in _K8S_JSON_DATA_RE.finditer(seg): - if m.start() < pos: - continue - out.append(seg[pos:m.end()]) - i, n, expect_value = m.end(), len(seg), False - while i < n: - c = seg[i] - if c == "}": - break - if c == '"': - s = _K8S_JSON_STR_RE.match(seg, i) - closed = len(s.group(0)) > 1 and s.group(0).endswith('"') - if expect_value: - out.append('"' + _K8S_MASK + ('"' if closed else "")) - expect_value = False - else: - out.append(s.group(0)) - i = s.end() - continue - if c == ":": - expect_value = True - elif c == ",": - expect_value = False - out.append(c) - i += 1 - pos = i - out.append(seg[pos:]) - return "".join(out) - - -def _k8s_mask_describe_env(text: str) -> str: - """``kubectl describe`` lines ``NAME: value`` inside an ``Environment:`` block.""" - lines = text.split("\n") - env_indent = -1 - for i, line in enumerate(lines): - stripped = line.lstrip(" \t") - indent = len(line) - len(stripped) - if env_indent >= 0: - if not stripped: - continue - if indent <= env_indent: - env_indent = -1 - else: - name, sep, rest = stripped.partition(":") - value = rest.strip() - if sep and value and _k8s_secret_name(name) and value != _K8S_MASK \ - and not _K8S_DESCRIBE_REF_RE.match(value): - lines[i] = line[:indent] + name + sep + rest.replace(value, _K8S_MASK, 1) - continue - if stripped.rstrip() == "Environment:": - env_indent = indent - return "\n".join(lines) - - -def _k8s_env_sub(m: "re.Match[str]", name_group: int, value_group: int, alt_name: int, alt_value: int) -> str: - if m.group(name_group) is not None: - name, start, end = m.group(name_group), m.start(value_group), m.end(value_group) - else: - name, start, end = m.group(alt_name), m.start(alt_value), m.end(alt_value) - if not _k8s_secret_name(name) or m.string[start:end] == _K8S_MASK: - return m.group(0) - return m.string[m.start():start] + _K8S_MASK + m.string[end:m.end()] - - -def _redact_kubernetes(text: str) -> str: - """Mask Kubernetes Secret data values and secret-named env values (YAML, JSON, describe).""" - if "Secret" in text and "ata" in text: - bounds = [m.start() for m in _K8S_SEGMENT_RE.finditer(text)] - if not bounds or bounds[0] != 0: - bounds.insert(0, 0) - bounds.append(len(text)) - parts = [] - for a, b in zip(bounds, bounds[1:]): - seg = text[a:b] - if _K8S_SECRET_KIND_RE.search(seg): - if "ata:" in seg: - seg = _k8s_mask_yaml_data(seg) - if '"' in seg: - seg = _k8s_mask_json_data(seg) - parts.append(seg) - text = "".join(parts) - if "value" in text and "name" in text: - if '"' in text: - text = _K8S_JSON_ENV_RE.sub(lambda m: _k8s_env_sub(m, 1, 2, 4, 3), text) - text = _K8S_YAML_ENV_RE.sub(lambda m: _k8s_env_sub(m, 2, 3, 6, 5), text) - if "Environment:" in text: - text = _k8s_mask_describe_env(text) - return text - - def _redact_userinfo_passwords(text: str) -> str: """Mask the password half of ``scheme://user:pass@host`` userinfo (#125664). @@ -1714,7 +1563,7 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F # Kubernetes Secret data / secret env values run in every mode: the source is a live object, # never a code fixture, and kubectl output is how the model sees them (RIG-11725). - text = _redact_kubernetes(text) + text = redact_kubernetes(text) if not code_file: text = _redact_assignments(text, mask_nonreusable=file_read) diff --git a/forks/hermes-agent/agent/redact_kubernetes.py b/forks/hermes-agent/agent/redact_kubernetes.py new file mode 100644 index 000000000..4c2a3c6b5 --- /dev/null +++ b/forks/hermes-agent/agent/redact_kubernetes.py @@ -0,0 +1,423 @@ +"""Kubernetes secret values in tool output (RIG-11725). + +A Secret's ``data``/``stringData`` values and an env ``value`` under a secret-named ``name`` +reach the model through kubectl output. Their keys are neutral (``connection``, ``value``), so +the keyword assignment passes in agent.redact never see them. + +Each pass collects ``(start, end)`` spans and the text is rebuilt once. Every pass is linear in +the text: one tokenizer pass for JSON, one pass over lines for YAML and ``kubectl describe``, and +regexes whose repeated parts cannot overlap. + +kubectl sorts keys, so ``data`` comes before ``kind``, and output cut off by ``head -c`` ends +inside it. An object's verdict is made when it closes, or at the end of the text: ``kind: +Secret`` masks; any other kind keeps; no kind masks when the object has a Kubernetes +``apiVersion`` or sits in a ``SecretList``. That fails closed on a cut-off Secret and keeps a +ConfigMap and plain JSON visible. +""" + +import json +import re + +MASK = "***" + +_SECRET_NAME_RE = re.compile( + r"PASSWORD|PASSWD|PWD|SECRET|CREDENTIAL|TOKEN" + r"|(?:^|[_.\-])(?:PASS|AUTH|(?:API|PRIVATE[_.\-]?)?KEYS?)(?:$|[_.\-])", + re.IGNORECASE) +# A name that holds metadata about a credential, not the credential itself. +_NOT_SECRET_SUFFIX_RE = re.compile(r"[_.\-](?:TTL|PATH|FILE|DIR|URL|NAME|ID)$", re.IGNORECASE) +_API_VERSION_RE = re.compile(r"(?:[a-z0-9.\-]+/)?v\d+(?:(?:alpha|beta)\d+)?") +_LAST_APPLIED = "kubectl.kubernetes.io/last-applied-configuration" + + +def secret_name(name: str) -> bool: + name = name.strip().strip("\"'") + return _SECRET_NAME_RE.search(name) is not None and _NOT_SECRET_SUFFIX_RE.search(name) is None + + +def _apply(text: str, spans: list) -> str: + if not spans: + return text + spans.sort() + out, pos = [], 0 + for start, end, repl in spans: + if start < pos: + continue + out.append(text[pos:start]) + out.append(repl) + pos = end + out.append(text[pos:]) + return "".join(out) + + +# --- JSON -------------------------------------------------------------------------------------- +# A string never spans a line in JSON, so a stray quote on an earlier line cannot shift the +# string parity of the object below it. A string cut off by a newline or the end of the text is +# read as an unterminated string and masks to its end. +_JSON_TOKEN_RE = re.compile(r'"(?:[^"\\\n]|\\[^\n])*"?|[{}\[\]:,\n]') + + +def _string_content(tok: str): + """(content start, content end) of a string token, relative to the token. The token regex + consumes every escape, so a token that ends in a quote is closed.""" + return 1, len(tok) - 1 if len(tok) > 1 and tok.endswith('"') else len(tok) + + +def _decode(tok: str) -> str: + try: + return json.loads(tok) + except ValueError: + return tok.strip('"') + + +class _Frame: + __slots__ = ( + "api", + "data", + "data_children", + "env_ctx", + "is_obj", + "key", + "kind", + "name", + "parent", + "value", + ) + + def __init__(self, is_obj, parent, key, env_ctx): + self.is_obj = is_obj + self.parent = parent # parent _Frame or None + self.key = key # the key this container is the value of + self.env_ctx = env_ctx # an object here may be an env entry + self.kind = self.api = self.name = self.value = None + self.data = [] # spans of string values in data/stringData + self.data_children = [] # value spans when this container is a data map + + +def _json_spans(text: str) -> list: + spans = [] + stack = [] + key = None # last key token seen in the current object + expect_key = True + # True while the current line holds only JSON tokens and whitespace. A top-level object after + # other text (``const opts = [{...}]``) is source code, not kubectl output. + line_json = True + prev_end = 0 + + def owner_kind(frame): + # The object that owns the array this object sits in, e.g. a SecretList. + arr = frame.parent + if arr is not None and not arr.is_obj and arr.parent is not None: + return arr.parent.kind + return None + + def close(frame): + """Decide a container when it closes or when the text ends inside it.""" + parent = frame.parent + if frame.is_obj: + if frame.data and (frame.kind == "Secret" or ( + frame.kind is None and (frame.api or owner_kind(frame) == "SecretList"))): + spans.extend(frame.data) + if frame.env_ctx and frame.name is not None and frame.value is not None \ + and secret_name(frame.name): + spans.append(frame.value) + # A data map's values belong to the object that holds the map. + if parent is not None and parent.is_obj and frame.key in ("data", "stringData"): + parent.data.extend(frame.data_children) + + for m in _JSON_TOKEN_RE.finditer(text): + tok = m.group() + c = tok[0] + if line_json and not text[prev_end:m.start()].isspace() and m.start() > prev_end: + line_json = False + prev_end = m.end() + if c == "\n": + line_json = True + continue + top = stack[-1] if stack else None + if c == "{" or c == "[": + if top is None: + env_ctx = line_json + elif top.is_obj: + env_ctx = key == "env" + else: # an element of an array + env_ctx = top.env_ctx + frame = _Frame(c == "{", top, key if top is not None and top.is_obj else None, env_ctx) + stack.append(frame) + expect_key = frame.is_obj + key = None + elif c == "}" or c == "]": + if stack: + frame = stack.pop() + close(frame) + top = stack[-1] if stack else None + expect_key = False + elif c == ":": + expect_key = False + elif c == ",": + expect_key = top is not None and top.is_obj + elif c == '"': + if top is not None and top.is_obj and expect_key: + key = _decode(tok) + elif top is not None and top.is_obj: + a, b = _string_content(tok) + start, end = m.start() + a, m.start() + b + if key == "kind": + top.kind = _decode(tok) + elif key == "apiVersion": + if _API_VERSION_RE.fullmatch(_decode(tok)): + top.api = True + elif key == "name": + top.name = _decode(tok) + elif key == "value": + top.value = (start, end, MASK) + elif key == _LAST_APPLIED: + spans.extend(_last_applied_span(tok, m.start(), start, end)) + if top.parent is not None and top.key in ("data", "stringData") and top.parent.is_obj: + top.data_children.append((start, end, MASK)) + while stack: # cut-off text: decide every open object now + close(stack.pop()) + return spans + + +def _last_applied_span(tok: str, offset: int, start: int, end: int) -> list: + """The annotation holds the object as escaped JSON: redact it and re-escape it.""" + try: + inner = json.loads(tok) + except ValueError: + return [(start, end, MASK)] # cut off: its content cannot be read, so fail closed + redacted = redact_kubernetes(inner) + if redacted == inner: + return [] + return [(offset, offset + len(tok), json.dumps(redacted, ensure_ascii=False))] + + +# --- YAML -------------------------------------------------------------------------------------- +_YAML_KEY_RE = re.compile(r"""(-[ \t]+)?("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s#"'][^:#]*?):(?:[ \t]+|$)""") +_DOC_SEP_RE = re.compile(r"(?:---|\.\.\.)(?:[ \t].*)?") +_FLOW_VALUE_RE = re.compile(r"(:[ \t]*)([^,{}]*)") + + +def _plain_scalar(s: str) -> str: + s = s.split(" #", 1)[0].strip() + return s.strip("\"'") + + +class _Map: + __slots__ = ("api", "col", "data", "kind", "name", "parent_kind", "value") + + def __init__(self, col, parent_kind): + self.col = col + self.kind = self.api = self.name = self.value = None + self.data = [] + self.parent_kind = parent_kind + + +def _value_span(line_off: int, body: str, vstart: int): + """Span of a scalar value on its key line: inside quotes, else up to a trailing comment.""" + value = body[vstart:] + if value[:1] in "\"'": + q = value[0] + close = value.find(q, 1) + end = vstart + (close if close > 0 else len(value)) + return line_off + vstart + 1, line_off + end + cut = value.find(" #") + end = vstart + (cut if cut >= 0 else len(value.rstrip())) + return line_off + vstart, line_off + end + + +def _yaml_spans(text: str) -> list: + spans = [] + lines = text.split("\n") + offs, pos = [], 0 + for line in lines: + offs.append(pos) + pos += len(line) + 1 + bodies = [ln.removesuffix("\r") for ln in lines] + indents = [len(b) - len(b.lstrip(" \t")) for b in bodies] + + def deeper_block(i, col): + """Spans of every line after ``i`` indented past ``col`` (blank lines included).""" + out, j = [], i + 1 + while j < len(bodies): + b = bodies[j] + if b.strip(): + if indents[j] <= col: + break + out.append((offs[j] + indents[j], offs[j] + len(b), MASK)) + j += 1 + return out, j + + stack = [] + + def close(mp): + if mp.data and (mp.kind == "Secret" or (mp.kind is None and (mp.api or mp.parent_kind == "SecretList"))): + spans.extend(mp.data) + if mp.name is not None and mp.value is not None and secret_name(mp.name): + spans.extend(mp.value) + + i, n = 0, len(bodies) + while i < n: + body = bodies[i] + stripped = body.strip() + if not stripped or stripped.startswith("#"): + i += 1 + continue + if _DOC_SEP_RE.fullmatch(body): + while stack: + close(stack.pop()) + i += 1 + continue + ind = indents[i] + m = _YAML_KEY_RE.match(body, ind) + if not m: + i += 1 + continue + dash = m.group(1) + col = ind + (len(dash) if dash else 0) + while stack and (stack[-1].col > col or (dash and stack[-1].col >= col)): + close(stack.pop()) + if not stack or stack[-1].col != col: + parent_kind = stack[-1].kind if stack else None + stack.append(_Map(col, parent_kind)) + mp = stack[-1] + key = m.group(2).strip("\"'") + vstart = m.end() + rest = body[vstart:] + scalar = _plain_scalar(rest) + nxt = i + 1 + if key == "kind": + mp.kind = scalar + # Items of a SecretList are its children. + elif key == "apiVersion": + mp.api = _API_VERSION_RE.fullmatch(scalar) is not None + elif key == "name": + mp.name = scalar + elif key == "value": + if not rest.strip() or rest.lstrip()[:1] in "|>": + block, nxt = deeper_block(i, col) + mp.value = block + else: + s, e = _value_span(offs[i], body, vstart) + block, nxt = deeper_block(i, col) + mp.value = [(s, e, MASK)] + block + elif key in ("data", "stringData"): + if rest.lstrip().startswith("{"): + for fm in _FLOW_VALUE_RE.finditer(body, vstart + rest.index("{")): + if fm.group(2).strip(): + s = offs[i] + fm.start(2) + mp.data.append((s, s + len(fm.group(2).rstrip()), MASK)) + elif not rest.strip() or rest.strip().startswith("#"): + nxt = _yaml_data_block(bodies, indents, offs, i, col, mp.data) + i = nxt + # (a key line with no case above is a plain key; its map stays on the stack) + while stack: + close(stack.pop()) + return spans + + +def _yaml_data_block(bodies, indents, offs, i, col, out) -> int: + """Collect value spans of a ``data:`` map at ``col``; return the next line to read.""" + j, n, child = i + 1, len(bodies), -1 + while j < n: + b = bodies[j] + st = b.strip() + if not st or st.startswith("#"): + j += 1 + continue + ind = indents[j] + if ind <= col: + break + if child < 0: + child = ind + if ind == child: + m = _YAML_KEY_RE.match(b, ind) + if m and not m.group(1): + rest = b[m.end():] + if rest.strip() and rest.lstrip()[:1] not in "|>": + s, e = _value_span(offs[j], b, m.end()) + out.append((s, e, MASK)) + else: + out.append((offs[j] + ind, offs[j] + len(b), MASK)) + else: # a block scalar line or the value of a key on the next line + out.append((offs[j] + ind, offs[j] + len(b), MASK)) + j += 1 + return j + + +# --- Helm flow env, Go maps and kubectl describe ----------------------------------------------- +_FLOW_ENV_RE = re.compile( + r"\{[ \t]*name:[ \t]*([\"']?)([\w.\-]+)\1[ \t]*,[ \t]*value:[ \t]*([^,}\]\n]*)" + r"|\{[ \t]*value:[ \t]*([^,}\]\n]*),[ \t]*name:[ \t]*([\"']?)([\w.\-]+)\5") +_GO_MAP_RE = re.compile(r"map\[([^\[\]\n]*)\]") +_GO_NAME_RE = re.compile(r"(?:^| )name:(\S+)") +_GO_VALUE_RE = re.compile(r"(?:^| )value:") +_GO_NEXT_KEY_RE = re.compile(r" [A-Za-z]+:") +_DESCRIBE_REF_RE = re.compile(r"|.*\(v1:") + + +def _flow_spans(text: str) -> list: + spans = [] + if "{" in text: + for m in _FLOW_ENV_RE.finditer(text): + if m.group(2) is not None: + name, g = m.group(2), 3 + else: + name, g = m.group(6), 4 + value = m.group(g).rstrip() + if value and secret_name(name): + s = m.start(g) + if value[0] in "\"'" and value.endswith(value[0]) and len(value) > 1: + spans.append((s + 1, s + len(value) - 1, MASK)) + else: + spans.append((s, s + len(value), MASK)) + if "map[" in text: + for m in _GO_MAP_RE.finditer(text): + inner = m.group(1) + nm = _GO_NAME_RE.search(inner) + vm = _GO_VALUE_RE.search(inner) + if not nm or not vm or not secret_name(nm.group(1)): + continue + vs = vm.end() + nk = _GO_NEXT_KEY_RE.search(inner, vs) + ve = nk.start() if nk else len(inner) + if ve > vs: + spans.append((m.start(1) + vs, m.start(1) + ve, MASK)) + return spans + + +def _describe_spans(text: str) -> list: + spans, pos, env_indent = [], 0, -1 + for line in text.split("\n"): + body = line.removesuffix("\r") + stripped = body.lstrip(" \t") + indent = len(body) - len(stripped) + if env_indent >= 0 and stripped: + if indent <= env_indent: + env_indent = -1 + else: + name, sep, rest = stripped.partition(":") + value = rest.strip() + if sep and value and " " not in name and secret_name(name) \ + and not _DESCRIBE_REF_RE.match(value): + s = pos + indent + len(name) + 1 + (len(rest) - len(rest.lstrip())) + spans.append((s, s + len(value), MASK)) + if stripped.rstrip() == "Environment:": + env_indent = indent + pos += len(line) + 1 + return spans + + +def redact_kubernetes(text: str) -> str: + """Mask Kubernetes Secret data values and secret-named env values.""" + spans = [] + if '"' in text and ('"data"' in text or '"stringData"' in text or '"value"' in text + or _LAST_APPLIED in text): + spans += _json_spans(text) + if "ata:" in text or "value:" in text: + spans += _yaml_spans(text) + if "value:" in text: + spans += _flow_spans(text) + if "Environment:" in text: + spans += _describe_spans(text) + return _apply(text, spans) diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes_shapes.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes_shapes.py new file mode 100644 index 000000000..c1eaa5b16 --- /dev/null +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes_shapes.py @@ -0,0 +1,174 @@ +"""Review probe rows for the Kubernetes pass (RIG-11725): leak shapes, keep shapes and perf.""" + +import time + +import pytest + +from agent.redact import redact_sensitive_text as r + +V = "zzqq" + "-fixture-leak-value-77" +P = "zzqq" + "-fixture-pw-value-88" +K = "keep-visible-r5" +LA = "kubectl.kubernetes.io/last-applied-configuration" + + +@pytest.fixture(autouse=True) +def _ensure_redaction_enabled(monkeypatch): + monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False) + monkeypatch.setattr("agent.redact._REDACT_ENABLED", True) + + +def _modes(t): + return [r(t, force=True), r(t), r(t, force=True, file_read=True, secret_file=True), + r(t, force=True, code_file=True)] + + +LEAK_ROWS = { + "trunc_secret_kind_first": f'{{"kind":"Secret","metadata":{{"name":"s"}},"data":{{"k":"{V}', + "trunc_full_kubectl_order": f'{{"apiVersion":"v1","kind":"Secret","metadata":{{"name":"s","namespace":"d"}},"type":"Opaque","data":{{"token":"{V}', + "trunc_secret_pretty": f'{{\n "kind": "Secret",\n "metadata": {{\n "name": "s",\n "labels": {{"a": "b"}}\n }},\n "data": {{\n "k": "{V}', + "trunc_kubectl_order_no_kind_pretty": f'{{\n "apiVersion": "v1",\n "data": {{\n "k": "{V}', + "trunc_kubectl_order_no_kind_compact": f'{{"apiVersion":"v1","data":{{"k":"{V}', + "trunc_kubectl_order_two_keys": f'{{\n "apiVersion": "v1",\n "data": {{\n "a": "x",\n "k": "{V}', + "complete_kubectl_order_compact": f'{{"apiVersion":"v1","data":{{"k":"{V}"}},"kind":"Secret","metadata":{{"name":"s"}},"type":"Opaque"}}', + "complete_kubectl_order_pretty": f'{{\n "apiVersion": "v1",\n "data": {{\n "k": "{V}"\n }},\n "kind": "Secret",\n "metadata": {{\n "name": "s"\n }}\n}}', + "trunc_list_of_secrets": f'{{"apiVersion":"v1","items":[{{"apiVersion":"v1","data":{{"k":"{V}', + "trunc_secretlist": f'{{"kind":"SecretList","items":[{{"metadata":{{"name":"s"}},"data":{{"k":"{V}', + "complete_secretlist_nested_items": f'{{"apiVersion":"v1","items":[{{"apiVersion":"v1","data":{{"k":"{V}"}},"kind":"Secret","metadata":{{"name":"s"}}}}],"kind":"List"}}', + "trunc_stringdata_after_data": f'{{"kind":"Secret","data":{{"a":"b"}},"stringData":{{"k":"{V}', + "trunc_close_brace_in_string": f'{{"kind":"Secret","metadata":{{"name":"s}}","labels":{{"a":"}}}}}}"}}}},"data":{{"k":"{V}', + "trunc_data_value_with_brace": f'{{"kind":"Secret","metadata":{{"name":"s"}},"data":{{"a":"}}{{","k":"{V}', + "trunc_escaped_quote": f'{{"kind":"Secret","metadata":{{"name":"a\\"}}","x":"b\\\\"}},"data":{{"k":"{V}', + "trunc_two_secrets_second": f'{{"kind":"Secret","metadata":{{"name":"a"}},"data":{{"x":"q"}}}}\n{{"kind":"Secret","metadata":{{"name":"s"}},"data":{{"k":"{V}', + "annot_last_applied_in_secret": f'{{"kind":"Secret","metadata":{{"annotations":{{"{LA}":"{{\\"apiVersion\\":\\"v1\\",\\"data\\":{{\\"k\\":\\"{V}\\"}},\\"kind\\":\\"Secret\\"}}"}}}}}}', + "annot_last_applied_cm_wraps_secret": f'{{"kind":"ConfigMap","metadata":{{"annotations":{{"{LA}":"{{\\"kind\\":\\"Secret\\",\\"data\\":{{\\"k\\":\\"{V}\\"}}}}"}}}}}}', + "yaml_annot_last_applied": f'apiVersion: v1\nkind: Secret\nmetadata:\n annotations:\n {LA}: |\n {{"apiVersion":"v1","data":{{"k":"{V}"}},"kind":"Secret"}}\ndata:\n k: eA==\n', + # stray quote + "oq_then_trunc": f'say "\n{{"kind":"Secret","metadata":{{"name":"s"}},"data":{{"k":"{V}', + "oq_then_trunc_pretty": f'warn: "x\n{{\n "kind": "Secret",\n "metadata": {{"name": "s"}},\n "data": {{\n "k": "{V}', + "oq_apiversion_nokind": f'x"\n{{"apiVersion":"v1","data":{{"k":"{V}', + "oq_three_quotes": f'a"b"c"\n{{"kind":"Secret","metadata":{{"name":"s"}},"data":{{"k":"{V}', + # List pod then secret + "list_pod_then_secret_trunc": f'{{"apiVersion":"v1","items":[{{"apiVersion":"v1","kind":"Pod","metadata":{{"name":"p"}}}},{{"apiVersion":"v1","data":{{"k":"{V}', + "list_pod_then_secret_complete": f'{{"apiVersion":"v1","items":[{{"apiVersion":"v1","kind":"Pod","metadata":{{"name":"p"}}}},{{"apiVersion":"v1","data":{{"k":"{V}"}},"kind":"Secret","metadata":{{"name":"s"}}}}],"kind":"List"}}', + "get_pod_secret_real_pretty_trunc": f'$ kubectl get pod,secret -o json | head -c 400\n{{\n "apiVersion": "v1",\n "items": [\n {{\n "apiVersion": "v1",\n "kind": "Pod",\n "metadata": {{\n "name": "web"\n }}\n }},\n {{\n "apiVersion": "v1",\n "data": {{\n "token": "{V}', + "list_cm_then_secret_trunc": f'{{"apiVersion":"v1","items":[{{"apiVersion":"v1","data":{{"a":"b"}},"kind":"ConfigMap","metadata":{{"name":"c"}}}},{{"apiVersion":"v1","data":{{"k":"{V}', + # YAML + "yaml_data": f'apiVersion: v1\nkind: Secret\nmetadata:\n name: s\ndata:\n connection: {V}\n', + "yaml_data_before_kind": f'apiVersion: v1\ndata:\n connection: {V}\nkind: Secret\nmetadata:\n name: s\ntype: Opaque\n', + "yaml_stringdata": f'apiVersion: v1\nkind: Secret\nstringData:\n connection: {V}\n', + "yaml_stringdata_block": f'apiVersion: v1\nkind: Secret\nstringData:\n config.yaml: |\n url: http://x\n blob: {V}\n', + "yaml_quoted_value": f'kind: Secret\ndata:\n connection: "{V}"\n', + "yaml_trunc_no_kind": f'apiVersion: v1\ndata:\n connection: {V}\n', + "yaml_list_items_secret": f'apiVersion: v1\nitems:\n- apiVersion: v1\n data:\n connection: {V}\n kind: Secret\n metadata:\n name: s\nkind: List\n', + "yaml_list_pod_then_secret": f'apiVersion: v1\nitems:\n- apiVersion: v1\n kind: Pod\n metadata:\n name: p\n- apiVersion: v1\n data:\n connection: {V}\n kind: Secret\n metadata:\n name: s\nkind: List\n', + "yaml_data_key_with_dot_colon": f'kind: Secret\ndata:\n "a:b": {V}\n', + "yaml_flow_map": f'kind: Secret\ndata: {{connection: {V}}}\n', + "yaml_crlf": f'apiVersion: v1\r\nkind: Secret\r\ndata:\r\n connection: {V}\r\n', + "yaml_tab_data": f'kind: Secret\ndata:\n\tconnection: {V}\n', + "yaml_multiline_plain": f'kind: Secret\ndata:\n connection:\n {V}\n', +} +ENV_ROWS = { + "yaml_deploy_env": f'kind: Deployment\nspec:\n template:\n spec:\n containers:\n - name: app\n env:\n - name: DB_PASSWORD\n value: {P}\n', + "yaml_deploy_env_second_container": f'kind: Deployment\nspec:\n template:\n spec:\n containers:\n - name: a\n image: x\n - name: b\n env:\n - name: API_TOKEN\n value: {P}\n', + "yaml_init_containers": f'spec:\n initContainers:\n - name: init\n env:\n - name: DB_PASSWORD\n value: {P}\n', + "yaml_env_quoted": f'env:\n- name: "DB_PASSWORD"\n value: "{P}"\n', + "yaml_env_name_comment": f'env:\n- name: DB_PASSWORD # db\n value: {P}\n', + "yaml_env_with_between_key": f'env:\n- name: DB_PASSWORD\n # comment\n value: {P}\n', + "yaml_env_block_scalar": f'env:\n- name: DB_PASSWORD\n value: |\n {P}\n', + "yaml_env_flow": f'env: [{{name: DB_PASSWORD, value: {P}}}]\n', + "yaml_env_crlf": f'env:\r\n- name: DB_PASSWORD\r\n value: {P}\r\n', + "json_env": f'{{"kind":"Deployment","spec":{{"template":{{"spec":{{"containers":[{{"env":[{{"name":"DB_PASSWORD","value":"{P}"}}]}}]}}}}}}}}', + "json_env_second_container": f'{{"spec":{{"containers":[{{"env":[{{"name":"A","value":"b"}}]}},{{"name":"c2","env":[{{"name":"API_TOKEN","value":"{P}"}}]}}]}}}}', + "json_env_initcontainers": f'{{"spec":{{"containers":[],"initContainers":[{{"env":[{{"name":"DB_PASSWORD","value":"{P}"}}]}}]}}}}', + "json_env_trunc": f'{{"spec":{{"containers":[{{"env":[{{"name":"DB_PASSWORD","value":"{P}', + "json_env_pretty_trunc": f'{{\n "env": [\n {{\n "name": "DB_PASSWORD",\n "value": "{P}', + "json_env_escaped_name": f'{{"name":"DB_PASS\\u0057ORD","value":"{P}"}}', + "gomap_env": f'[map[name:DB_PASSWORD value:{P}]]', + "gomap_env_multi": f'[map[name:LOG_LEVEL value:info] map[name:DB_PASSWORD value:{P}]]', + "gomap_env_reversed": f'[map[value:{P} name:DB_PASSWORD]]', + "jsonpath_env_json": f'[{{"name":"DB_PASSWORD","value":"{P}"}}]', + "describe_env": f'Containers:\n app:\n Environment:\n DB_PASSWORD: {P}\n', + "describe_env_secretref_variant": f' Environment:\n DB_PASSWORD: Optional: false\n API_KEY: {P}\n', + "env_names_misc_DATABASE_URL": f'env:\n- name: DATABASE_URL\n value: postgres://u:{P}@h/db\n', + "env_name_AUTH": f'env:\n- name: AUTH\n value: {P}\n', + "env_name_PRIVATE_KEY": f'env:\n- name: PRIVATE_KEY\n value: {P}\n', + "env_name_DB_PASS": f'env:\n- name: DB_PASS\n value: {P}\n', + "env_name_PWD": f'env:\n- name: MYSQL_PWD\n value: {P}\n', + "env_name_APIKEY": f'env:\n- name: STRIPE_APIKEY\n value: {P}\n', +} + +KEEP_ROWS = { + "configmap_yaml": f"apiVersion: v1\nkind: ConfigMap\ndata:\n connection: {K}\n", + "configmap_json": f'{{"apiVersion":"v1","kind":"ConfigMap","data":{{"connection":"{K}"}}}}', + "plain_json_data": f'{{"name":"app","version":"1.0","data":{{"x":"{K}"}}}}', + "plain_json_data_trunc": f'{{"name":"pkg","apiVersion":"2","data":{{"x":"{K}"', + "yaml_data_unrelated": f"data:\n title: {K}\n", + "env_PATH_yaml": f"env:\n- name: PATH\n value: /usr/bin:{K}\n", + "env_PATH_json": f'{{"name":"PATH","value":"/usr/bin:{K}"}}', + "env_LOG_LEVEL": f"env:\n- name: LOG_LEVEL\n value: {K}\n", + "env_KEYCLOAK_URL": f"env:\n- name: KEYCLOAK_URL\n value: https://{K}.example\n", + "env_TOKEN_TTL": f"env:\n- name: TOKEN_TTL\n value: {K}\n", + "env_SECRET_NAME_ref": f"env:\n- name: VAULT_SECRET_PATH\n value: kv/{K}\n", + "env_KEY_FILE": f"env:\n- name: TLS_KEY_FILE\n value: /etc/{K}\n", + "html_form": f'', + "js_literal": f'function f() {{ return {{"name":"b", "value":"{K}"}} }}', + "js_literal_secretname": f'const opts = [{{"name":"token", "value":"{K}"}}];', + "har_headers": f'{{"headers":[{{"name":"Content-Type","value":"{K}"}}]}}', + "har_cookie_tokenish": f'{{"cookies":[{{"name":"csrftoken","value":"{K}"}}]}}', + "crd_schema_trunc": f'{{"apiVersion":"apiextensions.k8s.io/v1","kind":"CustomResourceDefinition","spec":{{"properties":{{"data":{{"type":"object","description":"{K}"', + "secret_kind_prose_then_json": f'The Secret kind holds data.\n{{"data":{{"x":"{K}"}}}}', + "secret_doc_then_cm_doc": f"apiVersion: v1\nkind: Secret\ndata:\n a: eA==\n---\napiVersion: v1\nkind: ConfigMap\ndata:\n b: {K}\n", + "secret_list_yaml_then_cm": f"apiVersion: v1\nitems:\n- apiVersion: v1\n kind: Secret\n data:\n a: eA==\n- kind: ConfigMap\n data:\n b: {K}\n", + "secret_json_then_cm_json_sameline_no_apiv": f'{{"kind":"Secret","data":{{"a":"x"}}}} {{"kind":"ConfigMap","data":{{"b":"{K}"}}}}', + "json_list_secret_cm": f'{{"apiVersion":"v1","items":[{{"apiVersion":"v1","kind":"Secret","data":{{"a":"x"}}}},{{"apiVersion":"v1","kind":"ConfigMap","data":{{"b":"{K}"}}}}]}}', + "describe_set_literal": f" Environment:\n DB_PASSWORD: \n", + "python_dict_secret_kind": f'kind = "Secret"\ncfg = {{"data": {{"label": "{K}"}}}}\n', + "go_map_PATH": f"[map[name:PATH value:{K}]]", +} + + +@pytest.mark.parametrize("text", LEAK_ROWS.values(), ids=LEAK_ROWS.keys()) +def test_secret_data_masked(text): + for out in _modes(text): + assert V not in out, out + + +@pytest.mark.parametrize("text", ENV_ROWS.values(), ids=ENV_ROWS.keys()) +def test_secret_env_masked(text): + for out in _modes(text): + assert P not in out, out + + +@pytest.mark.parametrize("text", KEEP_ROWS.values(), ids=KEEP_ROWS.keys()) +def test_neutral_value_kept(text): + for out in [r(text, force=True), r(text), r(text, force=True, code_file=True)]: + assert K in out, out + + +KB = 1024 + + +def _rep(unit, n): + return unit * (-(-n // len(unit))) + + +PERF_ROWS = { + "yaml-env-interior-ws": "- name: A\n value: x" + " " * KB * KB + "y\n", + "yaml-env-value-first-ws": "- value: x" + " " * KB * KB + "y\n name: A\n", + "yaml-env-interior-tab-many": "- name: A\n value: x" + " \t" * (KB * KB // 2) + "y\n", + "yaml-env-128k-spaces-secret": "- name: DB_PASSWORD\n value: x" + " " * 128 * KB + "y\n", + "json-data-ws": '{"kind":"Secret","data"' + " " * KB * KB + "x", + "unclosed-objects": '{"kind":"Secret",' + _rep('{"name":"a",', KB * KB), + "env-secret-unclosed": '{"env":[' + _rep('{"name":"DB_PASSWORD","value":"b",', KB * KB), + "deep-open": '{"kind":"Secret",' + "{" * (KB * KB), + "yaml-env-many": _rep("- name: DB_PASSWORD\n value: x\n", KB * KB), + "describe-long-line": " Environment:\n DB_PASSWORD:" + " " * KB * KB + "x\n", +} + + +@pytest.mark.parametrize("text", PERF_ROWS.values(), ids=PERF_ROWS.keys()) +def test_one_megabyte_shape_under_a_second(text): + start = time.perf_counter() + r(text, force=True) + assert time.perf_counter() - start < 1.0 From 376c7e2937627361c831e26e44f8667f38154c32 Mon Sep 17 00:00:00 2001 From: mintaka Date: Sat, 21 Nov 2026 18:03:18 -0500 Subject: [PATCH 3/4] fix(hermes): close round-2 Kubernetes redaction gaps Run the PEM block pass before the Kubernetes pass, and mask every continuation line of a describe env value. A list item with no kind is decided by its list (SecretList, or unknown at end of text). A kind cut off mid-word counts as unknown. JSON env after a one-word jsonpath prefix is checked again. Setting names (MAX_, _TOKENS, _ENABLED, _MODE, _LENGTH, _DAYS and similar) stay visible through a name allowlist; the _ID exemption is gone. file_read masks with the non-reusable sentinel. JSON nesting is capped at 512. Refs RIG-11725 Co-authored-by: Matt Wilkinson --- forks/hermes-agent/agent/redact.py | 5 +- forks/hermes-agent/agent/redact_kubernetes.py | 370 ++++++++++-------- .../tests/agent/test_redact_kubernetes_r2.py | 183 +++++++++ 3 files changed, 387 insertions(+), 171 deletions(-) create mode 100644 forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py diff --git a/forks/hermes-agent/agent/redact.py b/forks/hermes-agent/agent/redact.py index 0c62d7ce3..adf035fd4 100644 --- a/forks/hermes-agent/agent/redact.py +++ b/forks/hermes-agent/agent/redact.py @@ -1561,9 +1561,11 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F _zhipu_sub = _mask_token_nonreusable if file_read else _mask_token text = _ZHIPU_API_KEY_RE.sub(lambda m: _zhipu_sub(m.group(1)), text) + # PEM blocks first: a multi-line key under a secret env name must be masked as a whole block. + text = _redact_private_key_blocks(text) # Kubernetes Secret data / secret env values run in every mode: the source is a live object, # never a code fixture, and kubectl output is how the model sees them (RIG-11725). - text = redact_kubernetes(text) + text = redact_kubernetes(text, _mask_token_nonreusable("") if file_read else "***") if not code_file: text = _redact_assignments(text, mask_nonreusable=file_read) @@ -1571,7 +1573,6 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F # Flags and connection-string keys carry a credential in command text, so they are not # gated on code_file: the shape (``--password=`` / ``;AccountKey=``) is unambiguous, and # the surfaces that leaked them (approval cards, chat status) run this pass anyway. - text = _redact_private_key_blocks(text) text = _redact_cli_secrets(text, _mask_token_nonreusable if file_read else None) if force and "=" in text: diff --git a/forks/hermes-agent/agent/redact_kubernetes.py b/forks/hermes-agent/agent/redact_kubernetes.py index 4c2a3c6b5..13543a88a 100644 --- a/forks/hermes-agent/agent/redact_kubernetes.py +++ b/forks/hermes-agent/agent/redact_kubernetes.py @@ -4,66 +4,93 @@ reach the model through kubectl output. Their keys are neutral (``connection``, ``value``), so the keyword assignment passes in agent.redact never see them. -Each pass collects ``(start, end)`` spans and the text is rebuilt once. Every pass is linear in -the text: one tokenizer pass for JSON, one pass over lines for YAML and ``kubectl describe``, and -regexes whose repeated parts cannot overlap. +Each pass collects ``(start, end, replacement)`` spans and the text is rebuilt once. A ``None`` +replacement takes the caller's mask. Every pass is linear in the text: one tokenizer pass for +JSON (its nesting capped at ``_MAX_DEPTH``), one pass over lines for YAML and ``kubectl +describe``, and regexes whose repeated parts cannot overlap. kubectl sorts keys, so ``data`` comes before ``kind``, and output cut off by ``head -c`` ends -inside it. An object's verdict is made when it closes, or at the end of the text: ``kind: -Secret`` masks; any other kind keeps; no kind masks when the object has a Kubernetes -``apiVersion`` or sits in a ``SecretList``. That fails closed on a cut-off Secret and keeps a -ConfigMap and plain JSON visible. +inside it. An object is decided when it closes, or at the end of the text: + +* ``kind: Secret`` masks; any other complete kind keeps. +* No kind (or a kind cut off mid-word) masks when the text ends inside the object and it has a + Kubernetes ``apiVersion``. A complete object with no kind keeps its own values. +* A list item with no kind hands its values to the list, which masks them when its kind is + ``SecretList``, or when its kind is still unknown at the end of the text. """ import json import re -MASK = "***" - _SECRET_NAME_RE = re.compile( r"PASSWORD|PASSWD|PWD|SECRET|CREDENTIAL|TOKEN" r"|(?:^|[_.\-])(?:PASS|AUTH|(?:API|PRIVATE[_.\-]?)?KEYS?)(?:$|[_.\-])", re.IGNORECASE) -# A name that holds metadata about a credential, not the credential itself. -_NOT_SECRET_SUFFIX_RE = re.compile(r"[_.\-](?:TTL|PATH|FILE|DIR|URL|NAME|ID)$", re.IGNORECASE) +# A name allowlist for settings about a credential, not the credential itself: limits, counts, +# switches and locations. ``*_SECRET_ID`` is not on it, as a Vault AppRole secret_id is live. +_NOT_SECRET_NAME_RE = re.compile( + r"(?:^|[_.\-])(?:MAX|MIN)[_.\-]|TOKENIZER" + r"|[_.\-](?:TTL|PATH|FILE|DIR|URL|NAME|ENABLED|DISABLED|MODE|TYPE|LENGTH|DAYS|HOURS|SECONDS" + r"|TIMEOUT|COUNT|SIZE|LIMIT|PARALLELISM|TOKENS)$", + re.IGNORECASE) _API_VERSION_RE = re.compile(r"(?:[a-z0-9.\-]+/)?v\d+(?:(?:alpha|beta)\d+)?") _LAST_APPLIED = "kubectl.kubernetes.io/last-applied-configuration" -def secret_name(name: str) -> bool: +def _secret_name(name: str) -> bool: name = name.strip().strip("\"'") - return _SECRET_NAME_RE.search(name) is not None and _NOT_SECRET_SUFFIX_RE.search(name) is None + return _SECRET_NAME_RE.search(name) is not None and _NOT_SECRET_NAME_RE.search(name) is None -def _apply(text: str, spans: list) -> str: +def _apply(text: str, spans: list, mask: str) -> str: if not spans: return text - spans.sort() + spans.sort(key=lambda s: (s[0], s[1])) out, pos = [], 0 for start, end, repl in spans: if start < pos: continue out.append(text[pos:start]) - out.append(repl) + out.append(mask if repl is None else repl) pos = end out.append(text[pos:]) return "".join(out) +def _redact_last_applied(encoded: str, mask: str): + """The annotation holds the object as escaped JSON: redact it and re-escape it. None when + nothing changed; the mask when the value cannot be read (cut off), so it fails closed.""" + try: + inner = json.loads(encoded) + except ValueError: + return mask + if not isinstance(inner, str): + return None + redacted = redact_kubernetes(inner, mask) + return None if redacted == inner else json.dumps(redacted, ensure_ascii=False) + + # --- JSON -------------------------------------------------------------------------------------- # A string never spans a line in JSON, so a stray quote on an earlier line cannot shift the # string parity of the object below it. A string cut off by a newline or the end of the text is # read as an unterminated string and masks to its end. _JSON_TOKEN_RE = re.compile(r'"(?:[^"\\\n]|\\[^\n])*"?|[{}\[\]:,\n]') +# Deeper nesting is read as the end of the text. Kubernetes objects are far shallower. +_MAX_DEPTH = 512 +# The text before a top-level env entry on its line: nothing, or one word followed by blanks or +# ``=``/``:`` (jsonpath ``web\t[{...}]``, ``env=[{...}]``). Code (``const opts = [``) or an +# indented literal in a call or list is not kubectl output. +_ENV_PREFIX_RE = re.compile(r"(?:[\w.\-/]+(?:[ \t]+|[=:][ \t]*))?") -def _string_content(tok: str): - """(content start, content end) of a string token, relative to the token. The token regex - consumes every escape, so a token that ends in a quote is closed.""" - return 1, len(tok) - 1 if len(tok) > 1 and tok.endswith('"') else len(tok) +def _closed(tok: str) -> bool: + # The token regex consumes every escape, so a token that ends in a quote is closed. + return len(tok) > 1 and tok.endswith('"') def _decode(tok: str) -> str: + if "\\" not in tok: + return tok[1:-1] if _closed(tok) else tok[1:] try: return json.loads(tok) except ValueError: @@ -71,127 +98,106 @@ def _decode(tok: str) -> str: class _Frame: - __slots__ = ( - "api", - "data", - "data_children", - "env_ctx", - "is_obj", - "key", - "kind", - "name", - "parent", - "value", - ) - - def __init__(self, is_obj, parent, key, env_ctx): + __slots__ = ("api", "data", "data_owner", "deferred", "env_ctx", "is_obj", "key", "kind", + "name", "parent", "value") + + def __init__(self, is_obj, parent, key, env_ctx, data_owner): self.is_obj = is_obj - self.parent = parent # parent _Frame or None - self.key = key # the key this container is the value of - self.env_ctx = env_ctx # an object here may be an env entry + self.parent = parent # parent _Frame or None + self.key = key # the key this container is the value of + self.env_ctx = env_ctx # an object here may be an env entry + self.data_owner = data_owner # the object whose data map holds this container self.kind = self.api = self.name = self.value = None - self.data = [] # spans of string values in data/stringData - self.data_children = [] # value spans when this container is a data map + self.data = [] # spans of string values in this object's data maps + self.deferred = [] # data spans of list items with no kind -def _json_spans(text: str) -> list: - spans = [] - stack = [] - key = None # last key token seen in the current object - expect_key = True - # True while the current line holds only JSON tokens and whitespace. A top-level object after - # other text (``const opts = [{...}]``) is source code, not kubectl output. - line_json = True - prev_end = 0 - - def owner_kind(frame): - # The object that owns the array this object sits in, e.g. a SecretList. - arr = frame.parent - if arr is not None and not arr.is_obj and arr.parent is not None: - return arr.parent.kind - return None +def _list_owner(frame): + arr = frame.parent + if arr is not None and not arr.is_obj and arr.parent is not None and arr.parent.is_obj: + return arr.parent + return None - def close(frame): - """Decide a container when it closes or when the text ends inside it.""" - parent = frame.parent - if frame.is_obj: - if frame.data and (frame.kind == "Secret" or ( - frame.kind is None and (frame.api or owner_kind(frame) == "SecretList"))): + +def _json_spans(text: str, mask: str) -> list: + spans, stack = [], [] + key = None # the last key read in the current object + expect_key = False + seg_start = 0 # start of the line, or end of the last top-level value on it + + def close(frame, eof): + if not frame.is_obj: + return + if frame.data: + if frame.kind == "Secret" or (frame.kind is None and eof and frame.api): spans.extend(frame.data) - if frame.env_ctx and frame.name is not None and frame.value is not None \ - and secret_name(frame.name): - spans.append(frame.value) - # A data map's values belong to the object that holds the map. - if parent is not None and parent.is_obj and frame.key in ("data", "stringData"): - parent.data.extend(frame.data_children) + elif frame.kind is None: + owner = _list_owner(frame) + if owner is not None: + owner.deferred.extend(frame.data) + if frame.deferred and (frame.kind == "SecretList" or (frame.kind is None and eof)): + spans.extend(frame.deferred) + # A name cut off before it is read fails closed. + if frame.env_ctx and frame.value is not None and ( + (frame.name is None and eof) or (frame.name is not None and _secret_name(frame.name))): + spans.append(frame.value) for m in _JSON_TOKEN_RE.finditer(text): tok = m.group() c = tok[0] - if line_json and not text[prev_end:m.start()].isspace() and m.start() > prev_end: - line_json = False - prev_end = m.end() if c == "\n": - line_json = True + seg_start = m.end() continue top = stack[-1] if stack else None if c == "{" or c == "[": + if len(stack) >= _MAX_DEPTH: + break if top is None: - env_ctx = line_json - elif top.is_obj: - env_ctx = key == "env" - else: # an element of an array - env_ctx = top.env_ctx - frame = _Frame(c == "{", top, key if top is not None and top.is_obj else None, env_ctx) - stack.append(frame) - expect_key = frame.is_obj + env_ctx = _ENV_PREFIX_RE.fullmatch(text, seg_start, m.start()) is not None + owner = None + else: + env_ctx = key == "env" if top.is_obj else top.env_ctx + owner = top if top.is_obj and key in ("data", "stringData") else top.data_owner + stack.append(_Frame(c == "{", top, key if top is not None and top.is_obj else None, + env_ctx, owner)) + expect_key = c == "{" key = None elif c == "}" or c == "]": if stack: - frame = stack.pop() - close(frame) - top = stack[-1] if stack else None + close(stack.pop(), False) + if not stack: + seg_start = m.end() expect_key = False elif c == ":": expect_key = False elif c == ",": expect_key = top is not None and top.is_obj - elif c == '"': - if top is not None and top.is_obj and expect_key: + elif top is not None: # a string + if top.is_obj and expect_key: key = _decode(tok) - elif top is not None and top.is_obj: - a, b = _string_content(tok) - start, end = m.start() + a, m.start() + b + continue + start, end = m.start() + 1, m.end() - (1 if _closed(tok) else 0) + if top.is_obj: if key == "kind": - top.kind = _decode(tok) + if _closed(tok): # a kind cut off mid-word stays unknown + top.kind = _decode(tok) elif key == "apiVersion": - if _API_VERSION_RE.fullmatch(_decode(tok)): - top.api = True + top.api = _API_VERSION_RE.fullmatch(_decode(tok)) is not None elif key == "name": top.name = _decode(tok) elif key == "value": - top.value = (start, end, MASK) + top.value = (start, end, None) elif key == _LAST_APPLIED: - spans.extend(_last_applied_span(tok, m.start(), start, end)) - if top.parent is not None and top.key in ("data", "stringData") and top.parent.is_obj: - top.data_children.append((start, end, MASK)) + repl = _redact_last_applied(tok, mask) + if repl is not None: + spans.append((m.start(), m.end(), repl)) + if top.data_owner is not None: + top.data_owner.data.append((start, end, None)) while stack: # cut-off text: decide every open object now - close(stack.pop()) + close(stack.pop(), True) return spans -def _last_applied_span(tok: str, offset: int, start: int, end: int) -> list: - """The annotation holds the object as escaped JSON: redact it and re-escape it.""" - try: - inner = json.loads(tok) - except ValueError: - return [(start, end, MASK)] # cut off: its content cannot be read, so fail closed - redacted = redact_kubernetes(inner) - if redacted == inner: - return [] - return [(offset, offset + len(tok), json.dumps(redacted, ensure_ascii=False))] - - # --- YAML -------------------------------------------------------------------------------------- _YAML_KEY_RE = re.compile(r"""(-[ \t]+)?("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s#"'][^:#]*?):(?:[ \t]+|$)""") _DOC_SEP_RE = re.compile(r"(?:---|\.\.\.)(?:[ \t].*)?") @@ -203,14 +209,23 @@ def _plain_scalar(s: str) -> str: return s.strip("\"'") +def _strip_props(rest: str) -> str: + """The value after any ``&anchor`` and ``!tag`` properties.""" + rest = rest.strip() + while rest[:1] in ("&", "!"): + rest = rest.partition(" ")[2].strip() + return rest + + class _Map: - __slots__ = ("api", "col", "data", "kind", "name", "parent_kind", "value") + __slots__ = ("api", "col", "data", "deferred", "kind", "name", "parent", "value") - def __init__(self, col, parent_kind): + def __init__(self, col, parent): self.col = col + self.parent = parent self.kind = self.api = self.name = self.value = None self.data = [] - self.parent_kind = parent_kind + self.deferred = [] def _value_span(line_off: int, body: str, vstart: int): @@ -220,13 +235,13 @@ def _value_span(line_off: int, body: str, vstart: int): q = value[0] close = value.find(q, 1) end = vstart + (close if close > 0 else len(value)) - return line_off + vstart + 1, line_off + end + return line_off + vstart + 1, line_off + end, None cut = value.find(" #") end = vstart + (cut if cut >= 0 else len(value.rstrip())) - return line_off + vstart, line_off + end + return line_off + vstart, line_off + end, None -def _yaml_spans(text: str) -> list: +def _yaml_spans(text: str, mask: str) -> list: spans = [] lines = text.split("\n") offs, pos = [], 0 @@ -235,6 +250,7 @@ def _yaml_spans(text: str) -> list: pos += len(line) + 1 bodies = [ln.removesuffix("\r") for ln in lines] indents = [len(b) - len(b.lstrip(" \t")) for b in bodies] + cut_last = not text.endswith("\n") def deeper_block(i, col): """Spans of every line after ``i`` indented past ``col`` (blank lines included).""" @@ -244,16 +260,22 @@ def deeper_block(i, col): if b.strip(): if indents[j] <= col: break - out.append((offs[j] + indents[j], offs[j] + len(b), MASK)) + out.append((offs[j] + indents[j], offs[j] + len(b), None)) j += 1 return out, j stack = [] - def close(mp): - if mp.data and (mp.kind == "Secret" or (mp.kind is None and (mp.api or mp.parent_kind == "SecretList"))): - spans.extend(mp.data) - if mp.name is not None and mp.value is not None and secret_name(mp.name): + def close(mp, eof): + # YAML has no closing bracket, so a map with an apiVersion and no kind masks either way. + if mp.data: + if mp.kind == "Secret" or (mp.kind is None and mp.api): + spans.extend(mp.data) + elif mp.kind is None and mp.parent is not None: + mp.parent.deferred.extend(mp.data) + if mp.deferred and (mp.kind == "SecretList" or (mp.kind is None and eof and mp.api)): + spans.extend(mp.deferred) + if mp.name is not None and mp.value is not None and _secret_name(mp.name): spans.extend(mp.value) i, n = 0, len(bodies) @@ -265,7 +287,7 @@ def close(mp): continue if _DOC_SEP_RE.fullmatch(body): while stack: - close(stack.pop()) + close(stack.pop(), False) i += 1 continue ind = indents[i] @@ -276,43 +298,44 @@ def close(mp): dash = m.group(1) col = ind + (len(dash) if dash else 0) while stack and (stack[-1].col > col or (dash and stack[-1].col >= col)): - close(stack.pop()) + close(stack.pop(), False) if not stack or stack[-1].col != col: - parent_kind = stack[-1].kind if stack else None - stack.append(_Map(col, parent_kind)) + stack.append(_Map(col, stack[-1] if stack else None)) mp = stack[-1] key = m.group(2).strip("\"'") vstart = m.end() rest = body[vstart:] - scalar = _plain_scalar(rest) nxt = i + 1 if key == "kind": - mp.kind = scalar - # Items of a SecretList are its children. + if not (cut_last and i == n - 1): # a kind cut off mid-word stays unknown + mp.kind = _plain_scalar(rest) elif key == "apiVersion": - mp.api = _API_VERSION_RE.fullmatch(scalar) is not None + mp.api = _API_VERSION_RE.fullmatch(_plain_scalar(rest)) is not None elif key == "name": - mp.name = scalar + mp.name = _plain_scalar(rest) elif key == "value": - if not rest.strip() or rest.lstrip()[:1] in "|>": - block, nxt = deeper_block(i, col) - mp.value = block - else: - s, e = _value_span(offs[i], body, vstart) - block, nxt = deeper_block(i, col) - mp.value = [(s, e, MASK)] + block + block, nxt = deeper_block(i, col) + if rest.strip() and rest.lstrip()[:1] not in "|>": + block.insert(0, _value_span(offs[i], body, vstart)) + mp.value = block elif key in ("data", "stringData"): - if rest.lstrip().startswith("{"): - for fm in _FLOW_VALUE_RE.finditer(body, vstart + rest.index("{")): + value = _strip_props(rest) + if value.startswith("{"): + for fm in _FLOW_VALUE_RE.finditer(body, body.index("{", vstart)): if fm.group(2).strip(): s = offs[i] + fm.start(2) - mp.data.append((s, s + len(fm.group(2).rstrip()), MASK)) - elif not rest.strip() or rest.strip().startswith("#"): + mp.data.append((s, s + len(fm.group(2).rstrip()), None)) + elif not value or value.startswith("#"): nxt = _yaml_data_block(bodies, indents, offs, i, col, mp.data) + elif key == _LAST_APPLIED and rest.lstrip().startswith('"'): + value = rest.strip() + repl = _redact_last_applied(value, mask) + if repl is not None: + s = offs[i] + vstart + (len(rest) - len(rest.lstrip())) + spans.append((s, s + len(value), repl)) i = nxt - # (a key line with no case above is a plain key; its map stays on the stack) while stack: - close(stack.pop()) + close(stack.pop(), True) return spans @@ -335,24 +358,25 @@ def _yaml_data_block(bodies, indents, offs, i, col, out) -> int: if m and not m.group(1): rest = b[m.end():] if rest.strip() and rest.lstrip()[:1] not in "|>": - s, e = _value_span(offs[j], b, m.end()) - out.append((s, e, MASK)) + out.append(_value_span(offs[j], b, m.end())) else: - out.append((offs[j] + ind, offs[j] + len(b), MASK)) + out.append((offs[j] + ind, offs[j] + len(b), None)) else: # a block scalar line or the value of a key on the next line - out.append((offs[j] + ind, offs[j] + len(b), MASK)) + out.append((offs[j] + ind, offs[j] + len(b), None)) j += 1 return j # --- Helm flow env, Go maps and kubectl describe ----------------------------------------------- +_FLOW_SCALAR = r"""("(?:[^"\\\n]|\\.)*"|'(?:[^'\n]|'')*'|[^,}\]\n]*)""" _FLOW_ENV_RE = re.compile( - r"\{[ \t]*name:[ \t]*([\"']?)([\w.\-]+)\1[ \t]*,[ \t]*value:[ \t]*([^,}\]\n]*)" - r"|\{[ \t]*value:[ \t]*([^,}\]\n]*),[ \t]*name:[ \t]*([\"']?)([\w.\-]+)\5") + r"\{[ \t]*name:[ \t]*([\"']?)([\w.\-]+)\1[ \t]*,[ \t]*value:[ \t]*" + _FLOW_SCALAR + + r"|\{[ \t]*value:[ \t]*" + _FLOW_SCALAR + r",[ \t]*name:[ \t]*([\"']?)([\w.\-]+)\5") _GO_MAP_RE = re.compile(r"map\[([^\[\]\n]*)\]") _GO_NAME_RE = re.compile(r"(?:^| )name:(\S+)") _GO_VALUE_RE = re.compile(r"(?:^| )value:") _GO_NEXT_KEY_RE = re.compile(r" [A-Za-z]+:") +_DESCRIBE_NAME_RE = re.compile(r"([A-Za-z_][\w.\-]*):(?:[ \t]+|$)") _DESCRIBE_REF_RE = re.compile(r"|.*\(v1:") @@ -365,59 +389,67 @@ def _flow_spans(text: str) -> list: else: name, g = m.group(6), 4 value = m.group(g).rstrip() - if value and secret_name(name): + if value and _secret_name(name): s = m.start(g) if value[0] in "\"'" and value.endswith(value[0]) and len(value) > 1: - spans.append((s + 1, s + len(value) - 1, MASK)) + spans.append((s + 1, s + len(value) - 1, None)) else: - spans.append((s, s + len(value), MASK)) + spans.append((s, s + len(value), None)) if "map[" in text: for m in _GO_MAP_RE.finditer(text): inner = m.group(1) nm = _GO_NAME_RE.search(inner) vm = _GO_VALUE_RE.search(inner) - if not nm or not vm or not secret_name(nm.group(1)): + if not nm or not vm or not _secret_name(nm.group(1)): continue vs = vm.end() nk = _GO_NEXT_KEY_RE.search(inner, vs) ve = nk.start() if nk else len(inner) if ve > vs: - spans.append((m.start(1) + vs, m.start(1) + ve, MASK)) + spans.append((m.start(1) + vs, m.start(1) + ve, None)) return spans def _describe_spans(text: str) -> list: - spans, pos, env_indent = [], 0, -1 + """``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 for line in text.split("\n"): body = line.removesuffix("\r") stripped = body.lstrip(" \t") - indent = len(body) - len(stripped) + lead = len(body) - len(stripped) + indent = len(body[:lead].expandtabs(8)) if env_indent >= 0 and stripped: if indent <= env_indent: - env_indent = -1 + env_indent, in_value = -1, False else: - name, sep, rest = stripped.partition(":") - value = rest.strip() - if sep and value and " " not in name and secret_name(name) \ - and not _DESCRIBE_REF_RE.match(value): - s = pos + indent + len(name) + 1 + (len(rest) - len(rest.lstrip())) - spans.append((s, s + len(value), MASK)) + 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)) \ + 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 = indent + env_indent, in_value = indent, False pos += len(line) + 1 return spans -def redact_kubernetes(text: str) -> str: - """Mask Kubernetes Secret data values and secret-named env values.""" +def redact_kubernetes(text: str, mask: str = "***") -> str: + """Mask Kubernetes Secret data values and secret-named env values with ``mask``.""" spans = [] - if '"' in text and ('"data"' in text or '"stringData"' in text or '"value"' in text - or _LAST_APPLIED in text): - spans += _json_spans(text) - if "ata:" in text or "value:" in text: - spans += _yaml_spans(text) + if '"' in text and ":" in text: + spans += _json_spans(text, mask) + if "ata:" in text or "value:" in text or _LAST_APPLIED in text: + spans += _yaml_spans(text, mask) if "value:" in text: spans += _flow_spans(text) if "Environment:" in text: spans += _describe_spans(text) - return _apply(text, spans) + return _apply(text, spans, mask) diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py new file mode 100644 index 000000000..686cdaf97 --- /dev/null +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py @@ -0,0 +1,183 @@ +"""Round-2 review rows for the Kubernetes pass (RIG-11725).""" + +import json +import time + +import pytest + +from agent.redact import redact_sensitive_text as r, redact_terminal_output + +V = "zzqq" + "-fixture-leak-value-77" +K = "keep-visible-r5" +LA = "kubectl.kubernetes.io/last-applied-configuration" +PEM_BODY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC" + V +sec = {"apiVersion": "v1", "data": {"k": V}, "kind": "Secret", "metadata": {"name": "s"}, "type": "Opaque"} +la_sec = dict(sec) +la_sec["metadata"] = {"name": "s", "annotations": {LA: json.dumps(sec) + "\n"}} + + +@pytest.fixture(autouse=True) +def _ensure_redaction_enabled(monkeypatch): + monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False) + monkeypatch.setattr("agent.redact._REDACT_ENABLED", True) + + +def _modes(t): + return [r(t, force=True), r(t), r(t, force=True, file_read=True, secret_file=True), + r(t, force=True, code_file=True)] + + +LEAK_ROWS = { + # value split across lines (YAML folded/plain continuation, JSON can't) + "yaml_data_plain_multiline": f"apiVersion: v1\nkind: Secret\ndata:\n k: {V[:10]}\n {V[10:]}\n", + "yaml_data_folded": f"apiVersion: v1\nkind: Secret\ndata:\n k: >-\n {V}\n", + "yaml_data_dq_multiline": f'apiVersion: v1\nkind: Secret\ndata:\n k: "abc\n {V}"\n', + "yaml_stringdata_dq_multiline": f'apiVersion: v1\nkind: Secret\nstringData:\n k: "abc\n {V}"\n', + "yaml_data_sq_multiline": f"apiVersion: v1\nkind: Secret\ndata:\n k: 'abc\n {V}'\n", + # nested Lists + "json_list_in_list": json.dumps({"apiVersion": "v1", "kind": "List", "items": [{"apiVersion": "v1", "kind": "List", "items": [sec]}]}), + "json_list_in_list_pretty_trunc": json.dumps({"apiVersion": "v1", "kind": "List", "items": [{"apiVersion": "v1", "kind": "List", "items": [sec]}]}, indent=4)[:-60], + "json_secretlist_in_list": json.dumps({"apiVersion": "v1", "kind": "List", "items": [{"apiVersion": "v1", "kind": "SecretList", "items": [{"data": {"k": V}, "metadata": {"name": "s"}}]}]}), + "json_secretlist_in_list_trunc": json.dumps({"apiVersion": "v1", "kind": "List", "items": [{"apiVersion": "v1", "kind": "SecretList", "items": [{"data": {"k": V}, "metadata": {"name": "s"}}]}]})[:-30], + "json_secretlist_items_nokind_complete": json.dumps({"apiVersion": "v1", "kind": "SecretList", "items": [{"data": {"k": V}, "metadata": {"name": "s"}}]}), + "json_secretlist_items_kind_first_after": '{"items":[{"data":{"k":"' + V + '"},"metadata":{"name":"s"}}],"kind":"SecretList"}', + "yaml_secretlist": f"apiVersion: v1\nkind: SecretList\nitems:\n- data:\n k: {V}\n metadata:\n name: s\n", + "yaml_secretlist_kind_last": f"apiVersion: v1\nitems:\n- data:\n k: {V}\n metadata:\n name: s\nkind: SecretList\n", + "yaml_list_in_list": f"apiVersion: v1\nkind: List\nitems:\n- apiVersion: v1\n kind: List\n items:\n - apiVersion: v1\n data:\n k: {V}\n kind: Secret\n", + "yaml_list_items_no_api": f"apiVersion: v1\nkind: List\nitems:\n- data:\n k: {V}\n kind: Secret\n", + # stringData + "json_stringdata_only": json.dumps({"apiVersion": "v1", "kind": "Secret", "stringData": {"k": V}}), + "json_stringdata_trunc": json.dumps({"apiVersion": "v1", "stringData": {"k": V}})[:-3], + "json_stringdata_nested_obj": '{"apiVersion":"v1","kind":"Secret","stringData":{"k":{"inner":"' + V + '"}}}', + "json_data_number_bool": '{"apiVersion":"v1","kind":"Secret","data":{"k":' + "1234567890123" + "}}", + # cut mid-key + "json_cut_mid_kind_key": json.dumps(sec)[: json.dumps(sec).index('"kind"') + 3], + "json_cut_mid_data_key": '{"apiVersion":"v1","data":{"k":"' + V + '","ot', + "json_cut_after_colon_kind": '{"apiVersion":"v1","data":{"k":"' + V + '"},"kind":', + "json_cut_mid_kind_value": '{"apiVersion":"v1","data":{"k":"' + V + '"},"kind":"Sec', + "json_cut_kind_value_cm_prefix": '{"apiVersion":"v1","data":{"k":"' + V + '"},"kind":"Conf', + "yaml_cut_mid_kind": f"apiVersion: v1\ndata:\n k: {V}\nki", + "yaml_cut_kind_prefix": f"apiVersion: v1\ndata:\n k: {V}\nkind: Sec", + # last-applied with escaped quotes + "la_json_pretty": json.dumps(la_sec, indent=4), + "la_json_value_with_quote": json.dumps({"apiVersion": "v1", "kind": "Secret", "metadata": {"annotations": {LA: json.dumps({"apiVersion": "v1", "kind": "Secret", "stringData": {"k": V + '"x\\y'}})}}}), + "la_in_configmap_wrap_secret": json.dumps({"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"annotations": {LA: json.dumps(sec)}}}), + "la_in_pod_with_env": json.dumps({"apiVersion": "v1", "kind": "Pod", "metadata": {"annotations": {LA: json.dumps({"spec": {"containers": [{"env": [{"name": "DB_PASSWORD", "value": V}]}]}})}}}), + "la_cut": json.dumps(la_sec)[: json.dumps(la_sec).index(V) + 30], + "la_yaml_singleline": f"apiVersion: v1\nkind: Secret\nmetadata:\n annotations:\n {LA}: '{json.dumps(sec)}'\n", + "la_yaml_in_cm": f"apiVersion: v1\nkind: ConfigMap\nmetadata:\n annotations:\n {LA}: |\n {json.dumps(sec)}\ndata:\n x: y\n", + "la_yaml_in_pod_env": f"apiVersion: v1\nkind: Pod\nmetadata:\n annotations:\n {LA}: |\n " + json.dumps({"spec": {"containers": [{"env": [{"name": "DB_PASSWORD", "value": V}]}]}}) + "\n", + "la_unicode_escape_key": '{"kind":"Secret","metadata":{"annotations":{"' + LA + '":"{\\"kind\\":\\"Secret\\",\\"d\\u0061ta\\":{\\"k\\":\\"' + V + '\\"}}"}}}', + # describe + "describe_env_block": f"Containers:\n app:\n Environment:\n DB_PASSWORD: {V}\n LOG: info\n", + "describe_env_from_and_env": f" Environment Variables from:\n s Secret Optional: false\n Environment:\n API_TOKEN: {V}\n", + "describe_env_tab": f" Environment:\n\tDB_PASSWORD:\t{V}\n", + "describe_env_multiline_value": f" Environment:\n DB_PASSWORD: line1\n {V}\n", + "describe_secret": "Name: s\nType: Opaque\n\nData\n====\nk: 22 bytes\n", + "describe_env_crlf": f" Environment:\r\n DB_PASSWORD: {V}\r\n", + # _URL etc names + "env_SECRET_ID": f"env:\n- name: CLIENT_SECRET_ID\n value: {V}\n", + "env_KEY_ID_aws": f"env:\n- name: AWS_SECRET_ACCESS_KEY_ID\n value: {V}\n", + # other env shapes + "json_env_value_before_name": '{"spec":{"containers":[{"env":[{"value":"' + V + '","name":"DB_PASSWORD"}]}]}}', + "json_env_trunc_value_before_name": '{"spec":{"containers":[{"env":[{"value":"' + V, + "json_env_pretty_list": json.dumps({"apiVersion": "apps/v1", "kind": "Deployment", "spec": {"template": {"spec": {"containers": [{"env": [{"name": "DB_PASSWORD", "value": V}]}]}}}}, indent=2), + "json_env_after_text_line": 'output: {"env":[{"name":"DB_PASSWORD","value":"' + V + '"}]}', + "jsonpath_env_after_prefix": 'env=[{"name":"DB_PASSWORD","value":"' + V + '"}]', + "yaml_env_value_first": f"env:\n- value: {V}\n name: DB_PASSWORD\n", + "yaml_env_name_after_valueFrom_sibling": f"env:\n- name: DB_PASSWORD\n value: {V}\n other: x\n", + "yaml_env_dq_multiline": f'env:\n- name: DB_PASSWORD\n value: "abc\n {V}"\n', + "yaml_env_indent_deeper_value": f"env:\n - name: DB_PASSWORD\n value: {V}\n", + "yaml_env_flow_seq_compact": f"env: [{{name: DB_PASSWORD, value: '{V}'}}]\n", + "yaml_env_flow_value_with_comma": f'env: [{{name: DB_PASSWORD, value: "a,{V}"}}]\n', + "gomap_value_with_space": f"[map[name:DB_PASSWORD value:abc {V}]]", + # helm values + "yaml_data_with_dash_items": f"apiVersion: v1\nkind: Secret\ndata:\n - {V}\n", + "yaml_data_tab_indent_after_space": f"apiVersion: v1\nkind: Secret\ndata:\n a: x\n\tk: {V}\n", + "yaml_kind_quoted": f'apiVersion: v1\nkind: "Secret"\ndata:\n k: {V}\n', + "yaml_kind_comment": f"apiVersion: v1\nkind: Secret # s\ndata:\n k: {V}\n", + "yaml_data_indent_zero_list": f"items:\n- apiVersion: v1\n kind: Secret\n data:\n k: {V}\n", + "yaml_data_doc_sep_mid": f"---\napiVersion: v1\ndata:\n k: {V}\n---\nkind: Secret\n", + "yaml_data_anchor": f"apiVersion: v1\nkind: Secret\ndata: &d\n k: {V}\n", + "yaml_data_tag": f"apiVersion: v1\nkind: Secret\ndata: !!map\n k: {V}\n", + "yaml_data_comment_after_key": f"apiVersion: v1\nkind: Secret\ndata: # c\n k: {V}\n", + "yaml_kubectl_prefixed_lines": f"$ kubectl get secret s -o yaml\napiVersion: v1\ndata:\n k: {V}\nkind: Secret\n", + "json_kind_secret_ns_prefix_line": f'secret.json: {{"apiVersion":"v1","data":{{"k":"{V}"}},"kind":"Secret"}}', + "json_kind_secret_escaped_name": '{"apiVersion":"v1","d\\u0061ta":{"k":"' + V + '"},"kind":"Secret"}', + "json_kind_secret_escaped_kind": '{"apiVersion":"v1","data":{"k":"' + V + '"},"kind":"S\\u0065cret"}', + "json_crlf_pretty": json.dumps(sec, indent=2).replace("\n", "\r\n"), + "json_apiversion_nonk8s_kind_secret": '{"apiVersion":"2","kind":"Secret","data":{"k":"' + V + '"}}', +} +LEAK_ROWS_2 = { + "raw_api_sorted_secretlist": '{"apiVersion":"v1","items":[{"data":{"k":"' + V + '"},"metadata":{"name":"s"},"type":"Opaque"}],"kind":"SecretList","metadata":{}}', + "raw_api_sorted_secretlist_pretty": json.dumps({"apiVersion": "v1", "items": [{"data": {"k": V}, "metadata": {"name": "s"}}], "kind": "SecretList", "metadata": {}}, indent=2, sort_keys=True), + "raw_api_sorted_secretlist_yaml": f"apiVersion: v1\nitems:\n- data:\n k: {V}\n metadata:\n name: s\nkind: SecretList\nmetadata: {{}}\n", + "raw_api_unsorted_secretlist": '{"kind":"SecretList","apiVersion":"v1","metadata":{},"items":[{"metadata":{"name":"s"},"data":{"k":"' + V + '"},"type":"Opaque"}]}', + "jsonpath_range_env": 'web\t[{"name":"DB_PASSWORD","value":"' + V + '"}]\n', + "jsonpath_range_env2": 'web [{"name":"LOG","value":"x"},{"name":"API_TOKEN","value":"' + V + '"}]\n', + "describe_env_pem": f" Environment:\n TLS_PRIVATE_KEY: -----BEGIN PRIVATE KEY-----\n {PEM_BODY}\n -----END PRIVATE KEY-----\n", + "describe_env_multiline": f" Environment:\n DB_PASSWORD: line1\n {V}\n", + "env_VAULT_SECRET_ID": f"env:\n- name: VAULT_SECRET_ID\n value: {V}\n", + "env_APPROLE_SECRET_ID_json": '{"spec":{"containers":[{"env":[{"name":"APPROLE_SECRET_ID","value":"' + V + '"}]}]}}', + "env_CLIENT_SECRET_ID_describe": f" Environment:\n CLIENT_SECRET_ID: {V}\n", + "json_env_pretty_after_cmd_line": '$ kubectl get pod p -o jsonpath="{.spec.containers[0].env}"\n[{"name":"DB_PASSWORD","value":"' + V + '"}]', + "secret_yaml_last_applied_dq_scalar": 'apiVersion: v1\nkind: Secret\nmetadata:\n annotations:\n kubectl.kubernetes.io/last-applied-configuration: "{\\"apiVersion\\":\\"v1\\",\\"data\\":{\\"k\\":\\"' + V + '\\"},\\"kind\\":\\"Secret\\"}"\ndata:\n k: eA==\n', +} +KEEP_ROWS = { + "env_MAX_TOKENS_yaml": f'env:\n- name: MAX_TOKENS\n value: "{K}"\n', + "env_TOKENIZERS_PARALLELISM": f'env:\n- name: TOKENIZERS_PARALLELISM\n value: "{K}"\n', + "env_PASSWORD_MIN_LENGTH": f'env:\n- name: PASSWORD_MIN_LENGTH\n value: "{K}"\n', + "env_AUTH_ENABLED": f'env:\n- name: AUTH_ENABLED\n value: "{K}"\n', + "env_AUTH_MODE_json": '{"spec":{"containers":[{"env":[{"name":"AUTH_MODE","value":"' + K + '"}]}]}}', + "env_SECRET_ROTATION_DAYS": f'env:\n- name: SECRET_ROTATION_DAYS\n value: "{K}"\n', + "jsonl_metric_tokens": '{"name":"llm.total_tokens","value":"' + K + '"}\n', + "python_call_dict_line": 'add(\n {"name": "token", "value": "' + K + '"},\n)\n', + "python_list_dict_line": 'FIELDS = [\n {"name": "password", "value": "' + K + '"},\n]\n', + "api_envelope_v1": '{"apiVersion":"v1","data":{"title":"' + K + '"}}', + "api_envelope_v2_pretty": json.dumps({"apiVersion": "v2", "data": {"items": [{"title": K}], "title": K}}, indent=2), + "api_envelope_v1_nested_kind": '{"apiVersion":"v1","data":{"kind":"user","title":"' + K + '"}}', + "kubeconfig": f"apiVersion: v1\nclusters:\n- cluster:\n server: https://{K}\n name: c\nkind: Config\n", + "chart_yaml": f"apiVersion: v2\nname: app\ndescription: {K}\ndata:\n x: {K}\n", + "configmap_list_sorted": json.dumps({"apiVersion": "v1", "items": [{"data": {"k": K}, "metadata": {"name": "c"}}], "kind": "ConfigMapList"}), + "configmap_list_sorted_yaml": f"apiVersion: v1\nitems:\n- data:\n k: {K}\n metadata:\n name: c\nkind: ConfigMapList\n", + "log_line_value_colon": f"2026-01-01 INFO value: {K}\nname: token\n", + "yaml_name_value_generic": f"params:\n- name: token-url\n value: {K}\n", + "markdown_value_colon": f"- name: api key rotation\n value: {K}\n", + "go_struct_print": f"{{Name:token Value:{K}}}", + "gomap_tokens": f"map[name:max_tokens value:{K}]", + "helm_flow_env_plain": f"env: [{{name: LOG_LEVEL, value: {K}}}]\n", + "yaml_data_secret_kind_in_other_doc_no_sep": f"apiVersion: v1\nkind: Secret\ndata:\n a: eA==\napiVersion: v1\nkind: ConfigMap\ndata:\n b: {K}\n", + "json_secret_then_cm_newline": '{"apiVersion":"v1","kind":"Secret","data":{"a":"x"}}\n{"apiVersion":"v1","kind":"ConfigMap","data":{"b":"' + K + '"}}', +} +ALL_LEAK = {**LEAK_ROWS, **LEAK_ROWS_2} + + +@pytest.mark.parametrize("text", ALL_LEAK.values(), ids=ALL_LEAK.keys()) +def test_secret_masked(text): + for out in _modes(text): + assert V not in out, out + + +@pytest.mark.parametrize("text", KEEP_ROWS.values(), ids=KEEP_ROWS.keys()) +def test_setting_value_kept(text): + for out in [r(text, force=True), r(text), r(text, force=True, code_file=True), r(text, file_read=True)]: + assert K in out, out + + +def test_describe_pem_env_masked_in_terminal_output(): + text = (" Environment:\n TLS_PRIVATE_KEY: -----BEGIN PRIVATE KEY-----\n" + f" {PEM_BODY}\n -----END PRIVATE KEY-----\n") + out = redact_terminal_output(text, "kubectl describe pod web", force=True) + assert V not in out and "MIIEvQIBADAN" not in out, out + + +def test_file_read_uses_non_reusable_sentinel(): + out = r(f"apiVersion: v1\nkind: Secret\ndata:\n k: {V}\n", file_read=True) + assert "k: «redacted-secret»" in out, out + + +def test_one_megabyte_open_brackets_under_a_second(): + text = '{"apiVersion":"v1","data":' + "[" * (1 << 20) + start = time.perf_counter() + r(text, force=True) + assert time.perf_counter() - start < 1.0 From 2d4fc6f9d6d76d185e7cb47af066fe1ea73f2585 Mon Sep 17 00:00:00 2001 From: mintaka Date: Sat, 21 Nov 2026 18:33:20 -0500 Subject: [PATCH 4/4] fix(redact): linear prop strip and exact allowlist for secret-word env names Refs RIG-11725 Co-authored-by: Matt Wilkinson --- forks/hermes-agent/agent/redact_kubernetes.py | 55 +++++++++++++------ .../tests/agent/test_redact_kubernetes.py | 19 ++++--- ...py => test_redact_kubernetes_leak_rows.py} | 29 ++++++++++ 3 files changed, 78 insertions(+), 25 deletions(-) rename forks/hermes-agent/tests/agent/{test_redact_kubernetes_r2.py => test_redact_kubernetes_leak_rows.py} (88%) diff --git a/forks/hermes-agent/agent/redact_kubernetes.py b/forks/hermes-agent/agent/redact_kubernetes.py index 13543a88a..6af5fa2d4 100644 --- a/forks/hermes-agent/agent/redact_kubernetes.py +++ b/forks/hermes-agent/agent/redact_kubernetes.py @@ -26,20 +26,31 @@ r"PASSWORD|PASSWD|PWD|SECRET|CREDENTIAL|TOKEN" r"|(?:^|[_.\-])(?:PASS|AUTH|(?:API|PRIVATE[_.\-]?)?KEYS?)(?:$|[_.\-])", re.IGNORECASE) -# A name allowlist for settings about a credential, not the credential itself: limits, counts, -# switches and locations. ``*_SECRET_ID`` is not on it, as a Vault AppRole secret_id is live. -_NOT_SECRET_NAME_RE = re.compile( - r"(?:^|[_.\-])(?:MAX|MIN)[_.\-]|TOKENIZER" - r"|[_.\-](?:TTL|PATH|FILE|DIR|URL|NAME|ENABLED|DISABLED|MODE|TYPE|LENGTH|DAYS|HOURS|SECONDS" - r"|TIMEOUT|COUNT|SIZE|LIMIT|PARALLELISM|TOKENS)$", - re.IGNORECASE) +# Exact names of settings about a credential, not the credential itself: counters, limits, +# switches and locations. A suffix alone never unmasks a name (``API_TOKENS`` is a token list). +# ``*_SECRET_ID`` is not here, as a Vault AppRole secret_id is live. +_NOT_SECRET_NAMES = frozenset(( + "MAX_TOKENS", "MIN_TOKENS", "TOTAL_TOKENS", "NUM_TOKENS", "MAX_NEW_TOKENS", + "MAX_INPUT_TOKENS", "MAX_OUTPUT_TOKENS", "MAX_COMPLETION_TOKENS", "PROMPT_TOKENS", + "COMPLETION_TOKENS", "TOKENIZERS_PARALLELISM", "TOKEN_TTL", "TOKEN_URL", + "PASSWORD_MIN_LENGTH", "AUTH_ENABLED", "AUTH_DISABLED", "AUTH_MODE", "AUTH_TYPE", + "SECRET_ROTATION_DAYS", "VAULT_SECRET_PATH", +)) +_SEP_RE = re.compile(r"[.\-]") _API_VERSION_RE = re.compile(r"(?:[a-z0-9.\-]+/)?v\d+(?:(?:alpha|beta)\d+)?") _LAST_APPLIED = "kubectl.kubernetes.io/last-applied-configuration" -def _secret_name(name: str) -> bool: +def _secret_name(name: str, value: str = "") -> bool: + """Whether the value of env entry ``name`` is masked. A ``*_FILE`` value stays visible only + when it is an absolute path.""" name = name.strip().strip("\"'") - return _SECRET_NAME_RE.search(name) is not None and _NOT_SECRET_NAME_RE.search(name) is None + if _SECRET_NAME_RE.search(name) is None: + return False + if name.upper().endswith(("_FILE", ".FILE", "-FILE")): + return not value.strip().strip("\"'").startswith("/") + # A dotted metric namespace (``llm.total_tokens``) is not part of the name. + return _SEP_RE.sub("_", name.rpartition(".")[2]).upper() not in _NOT_SECRET_NAMES def _apply(text: str, spans: list, mask: str) -> str: @@ -139,7 +150,8 @@ def close(frame, eof): spans.extend(frame.deferred) # A name cut off before it is read fails closed. if frame.env_ctx and frame.value is not None and ( - (frame.name is None and eof) or (frame.name is not None and _secret_name(frame.name))): + (frame.name is None and eof) or (frame.name is not None and _secret_name( + frame.name, text[frame.value[0]:frame.value[1]]))): spans.append(frame.value) for m in _JSON_TOKEN_RE.finditer(text): @@ -212,9 +224,15 @@ def _plain_scalar(s: str) -> str: def _strip_props(rest: str) -> str: """The value after any ``&anchor`` and ``!tag`` properties.""" rest = rest.strip() - while rest[:1] in ("&", "!"): - rest = rest.partition(" ")[2].strip() - return rest + i, n = 0, len(rest) + while i < n and rest[i] in "&!": + sp = rest.find(" ", i) + if sp < 0: + return "" + i = sp + while i < n and rest[i].isspace(): + i += 1 + return rest[i:] class _Map: @@ -275,7 +293,8 @@ def close(mp, eof): mp.parent.deferred.extend(mp.data) if mp.deferred and (mp.kind == "SecretList" or (mp.kind is None and eof and mp.api)): spans.extend(mp.deferred) - if mp.name is not None and mp.value is not None and _secret_name(mp.name): + if mp.name is not None and mp.value is not None and _secret_name( + mp.name, text[mp.value[0][0]:mp.value[0][1]] if mp.value else ""): spans.extend(mp.value) i, n = 0, len(bodies) @@ -389,7 +408,7 @@ def _flow_spans(text: str) -> list: else: name, g = m.group(6), 4 value = m.group(g).rstrip() - if value and _secret_name(name): + if value and _secret_name(name, value): s = m.start(g) if value[0] in "\"'" and value.endswith(value[0]) and len(value) > 1: spans.append((s + 1, s + len(value) - 1, None)) @@ -400,12 +419,12 @@ def _flow_spans(text: str) -> list: inner = m.group(1) nm = _GO_NAME_RE.search(inner) vm = _GO_VALUE_RE.search(inner) - if not nm or not vm or not _secret_name(nm.group(1)): + if not nm or not vm: continue vs = vm.end() nk = _GO_NEXT_KEY_RE.search(inner, vs) ve = nk.start() if nk else len(inner) - if ve > vs: + if ve > vs and _secret_name(nm.group(1), inner[vs:ve]): spans.append((m.start(1) + vs, m.start(1) + ve, None)) return spans @@ -430,7 +449,7 @@ def _describe_spans(text: str) -> list: spans.append((pos + lead, pos + len(body), None)) else: value = stripped[m.end():].rstrip() - in_value = bool(value) and _secret_name(m.group(1)) \ + 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() diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes.py index bb82d3ad2..468e0487f 100644 --- a/forks/hermes-agent/tests/agent/test_redact_kubernetes.py +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes.py @@ -121,14 +121,19 @@ def test_plain_name_and_reference_kept(self): class TestPerformance: - def test_one_megabyte_under_a_second(self): + def test_one_megabyte_scales_linearly(self): block = SECRET_YAML + ENV_YAML + SECRET_JSON_PRETTY + ENV_JSON_PRETTY - big = block * (1_000_000 // len(block) + 1) - assert len(big) >= 1_000_000 - start = time.perf_counter() - out = redact_sensitive_text(big, force=True) - elapsed = time.perf_counter() - start - assert elapsed < 1.0, elapsed + + def run(size): + text = block * (size // len(block) + 1) + start = time.perf_counter() + out = redact_sensitive_text(text, force=True) + return time.perf_counter() - start, out + + run(100_000) # warm up + small = min(run(100_000)[0] for _ in range(3)) + big, out = run(1_000_000) + assert big / max(small, 1e-4) < 25, (small, big) assert V not in out and B64 not in out def test_one_megabyte_mixed_shapes_leaks_nothing(self): diff --git a/forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py b/forks/hermes-agent/tests/agent/test_redact_kubernetes_leak_rows.py similarity index 88% rename from forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py rename to forks/hermes-agent/tests/agent/test_redact_kubernetes_leak_rows.py index 686cdaf97..349ea66e1 100644 --- a/forks/hermes-agent/tests/agent/test_redact_kubernetes_r2.py +++ b/forks/hermes-agent/tests/agent/test_redact_kubernetes_leak_rows.py @@ -122,6 +122,17 @@ def _modes(t): "env_CLIENT_SECRET_ID_describe": f" Environment:\n CLIENT_SECRET_ID: {V}\n", "json_env_pretty_after_cmd_line": '$ kubectl get pod p -o jsonpath="{.spec.containers[0].env}"\n[{"name":"DB_PASSWORD","value":"' + V + '"}]', "secret_yaml_last_applied_dq_scalar": 'apiVersion: v1\nkind: Secret\nmetadata:\n annotations:\n kubectl.kubernetes.io/last-applied-configuration: "{\\"apiVersion\\":\\"v1\\",\\"data\\":{\\"k\\":\\"' + V + '\\"},\\"kind\\":\\"Secret\\"}"\ndata:\n k: eA==\n', + # a suffix alone does not unmask a secret-word name + "env_API_TOKENS": f"env:\n- name: API_TOKENS\n value: {V}\n", + "env_ACCESS_TOKENS_json": json.dumps({"spec": {"containers": [{"env": [{"name": "ACCESS_TOKENS", "value": V + ",o"}]}]}}), + "env_AUTH_TOKEN_TYPE_describe": f" Environment:\n AUTH_TOKEN_TYPE: {V}\n", + "env_SECRET_KEY_NAME": f"env:\n- name: SECRET_KEY_NAME\n value: {V}\n", + "env_DB_PASSWORD_ENC_MODE_describe": f" Environment:\n DB_PASSWORD_ENC_MODE: {V}\n", + "env_DB_PASSWORD_ENC_MODE_json": json.dumps({"spec": {"containers": [{"env": [{"name": "DB_PASSWORD_ENC_MODE", "value": V}]}]}}), + # a *_FILE value that is not an absolute path is the secret itself + "env_DB_PASSWORD_FILE_inline": f"env:\n- name: DB_PASSWORD_FILE\n value: {V}\n", + "env_API_KEY_FILE_json": json.dumps({"spec": {"containers": [{"env": [{"name": "API_KEY_FILE", "value": V}]}]}}), + "env_API_KEY_FILE_describe": f" Environment:\n API_KEY_FILE: {V}\n", } KEEP_ROWS = { "env_MAX_TOKENS_yaml": f'env:\n- name: MAX_TOKENS\n value: "{K}"\n', @@ -129,6 +140,11 @@ def _modes(t): "env_PASSWORD_MIN_LENGTH": f'env:\n- name: PASSWORD_MIN_LENGTH\n value: "{K}"\n', "env_AUTH_ENABLED": f'env:\n- name: AUTH_ENABLED\n value: "{K}"\n', "env_AUTH_MODE_json": '{"spec":{"containers":[{"env":[{"name":"AUTH_MODE","value":"' + K + '"}]}]}}', + "env_TOTAL_TOKENS": f'env:\n- name: TOTAL_TOKENS\n value: "{K}"\n', + "env_NUM_TOKENS": f'env:\n- name: NUM_TOKENS\n value: "{K}"\n', + "env_MAX_TOKENS_json": json.dumps({"spec": {"containers": [{"env": [{"name": "MAX_TOKENS", "value": K}]}]}}), + "env_DB_PASSWORD_FILE_path": f"env:\n- name: DB_PASSWORD_FILE\n value: /run/secrets/{K}\n", + "env_API_KEY_FILE_path_json": json.dumps({"spec": {"containers": [{"env": [{"name": "API_KEY_FILE", "value": "/etc/" + K}]}]}}), "env_SECRET_ROTATION_DAYS": f'env:\n- name: SECRET_ROTATION_DAYS\n value: "{K}"\n', "jsonl_metric_tokens": '{"name":"llm.total_tokens","value":"' + K + '"}\n', "python_call_dict_line": 'add(\n {"name": "token", "value": "' + K + '"},\n)\n', @@ -181,3 +197,16 @@ def test_one_megabyte_open_brackets_under_a_second(): start = time.perf_counter() r(text, force=True) assert time.perf_counter() - start < 1.0 + + +@pytest.mark.parametrize("unit", ["& ", "!a "]) +def test_prop_chain_scales_linearly(unit): + def cost(n): + text = "data: " + unit * (n // len(unit)) + start = time.perf_counter() + r(text, force=True) + return time.perf_counter() - start + + cost(100_000) # warm up + small, big = min(cost(100_000) for _ in range(3)), min(cost(1_000_000) for _ in range(3)) + assert big / max(small, 1e-4) < 25, (small, big)