The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(memory): scrub secrets on every memory-provider hand-off (#115104)
Aniruddha Adak88704223d2de
diff --git a/agent/memory_manager.py b/agent/memory_manager.pyindex d023a57f8bc..5ccbca61cdc 100644--- a/agent/memory_manager.py+++ b/agent/memory_manager.py@@ -16,6 +16,8 @@ from concurrent.futures import Future, ThreadPoolExecutor, waitfrom functools import partialfrom typing import Any, Callable, Dict, List, Optional+from agent.redact import redact_for_egress+from agent.memory_provider import MemoryProvider, PRE_COMPRESS_CHECKPOINT_API_VERSION, ctx_bound, spawn_context_threadfrom agent.skill_commands import extract_user_instruction_from_skill_messagefrom tools.hook_output_spill import get_spill_config, spill_if_oversized@@ -175,6 +177,59 @@ def sanitize_context(text: str) -> str:return text+def _scrub(text: str) -> str:+ """The shared egress scrub. Like chat-platform and cron delivery it holds even when+ ``security.redact_secrets`` is off (that setting governs local logs, not what leaves the agent)+ and fails closed."""+ return redact_for_egress(text)+++_TOKEN_RE = re.compile(r"[A-Za-z0-9_\-./+]{16,}")+++def _redact_for_provider(*values: Any) -> Any:+ """Copies of ``values`` with every string scrubbed before it reaches a memory provider.++ Providers archive whatever they are handed (#115104), so each manager fan-out (turn sync, recall+ queries, session-end and pre-compress transcripts, memory-tool mirrors, delegation results, provider+ tool args) goes through ``_scrub``. Walks dicts/lists/tuples so tool-call arguments and multimodal text+ parts are covered; ``data:`` URLs (inline media) pass through. A value the scrub masked anywhere in the+ hand-off is then masked everywhere in it, so a key detected in a tool result is also caught where the+ model repeats it bare in prose. Never mutates the caller's objects: unchanged values come back as-is,+ changed containers as shallow copies. One value in → one value out; several → a tuple.+ """+ learned: set = set()++ def walk(value: Any, fix) -> Any:+ if isinstance(value, str):+ return value if not value or value.startswith("data:") else fix(value)+ if isinstance(value, dict):+ out = {k: walk(v, fix) for k, v in value.items()}+ return value if all(out[k] is value[k] for k in value) else out+ if isinstance(value, (list, tuple)):+ items = [walk(v, fix) for v in value]+ if all(new is old for new, old in zip(items, value)):+ return value+ return tuple(items) if isinstance(value, tuple) else items+ return value++ def scrub(text: str) -> str:+ out = _scrub(text)+ if out != text:+ learned.update(set(_TOKEN_RE.findall(text)) - set(_TOKEN_RE.findall(out)))+ return out++ scrubbed = [walk(v, scrub) for v in values]+ if learned:+ pattern = re.compile("|".join(re.escape(t) for t in sorted(learned, key=len, reverse=True)))+ scrubbed = [walk(v, lambda t: pattern.sub("[redacted]", t) if pattern.search(t) else t) for v in scrubbed]+ return scrubbed[0] if len(scrubbed) == 1 else tuple(scrubbed)+++def _redact_messages_for_egress(messages: Optional[List[Any]]) -> Optional[List[Any]]:+ return None if messages is None else list(_redact_for_provider(messages))++class StreamingContextScrubber:"""Stateful scrubber for streaming text whose memory-context spans may straddle deltas.@@ -449,6 +504,7 @@ class MemoryManager:clean_query = self._strip_skill_scaffolding(query)if not clean_query:return ""+ clean_query = _redact_for_provider(clean_query)parts = self._each_provider("prefetch failed (non-fatal)", lambda p: self._prefetch_provider(p, clean_query, session_id=session_id),)@@ -519,6 +575,7 @@ class MemoryManager:clean_query = self._strip_skill_scaffolding(query) if providers else Noneif not clean_query:return+ clean_query = _redact_for_provider(clean_query)self._submit_background(lambda: self._each_provider("queue_prefetch failed (non-fatal)", lambda p: p.queue_prefetch(clean_query, session_id=session_id),providers=providers,@@ -538,12 +595,18 @@ class MemoryManager:Never inline: a provider's ``sync_turn`` may block for minutes, which kept ``run_conversation``open after the user saw the response. The single worker also serializes writes (turn N before N+1).``turn_author`` reaches only providers whose ``sync_turn`` accepts it.++ Everything forwarded is provider egress: turn strings AND the ``messages`` transcript slice+ (tool outputs included) go through ``_redact_for_provider`` so secrets are never archived+ verbatim in a provider's store (#115104)."""providers = list(self._providers)clean_user_content = self._strip_skill_scaffolding(user_content) if providers else Noneif not clean_user_content:return- optional_kwargs = {"messages": messages, "turn_author": turn_author}+ clean_user_content, assistant_content, redacted_messages = _redact_for_provider(+ clean_user_content, assistant_content, messages)+ optional_kwargs = {"messages": redacted_messages, "turn_author": turn_author}def _sync(provider: MemoryProvider) -> None:kwargs: Dict[str, Any] = {"session_id": session_id}@@ -645,6 +708,7 @@ class MemoryManager:provider = self._tool_to_provider.get(tool_name)if provider is None:return tool_error(f"No memory provider handles tool '{tool_name}'")+ args = _redact_for_provider(args)from hermes_cli.observability.shared_metrics_loop import record_provider_memory_calltry:result = provider.handle_tool_call(tool_name, args, **kwargs)@@ -656,6 +720,8 @@ class MemoryManager:return resultdef on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:+ message = _redact_for_provider(message)+def _tick(p: MemoryProvider) -> None:# A provider written before the author kwargs declares (turn_number, message) only; it still gets its tick.params = _signature_params(p.on_turn_start)@@ -665,6 +731,7 @@ class MemoryManager:self._each_provider("on_turn_start failed", _tick)def on_session_end(self, messages: List[Dict[str, Any]]) -> None:+ messages = _redact_messages_for_egress(messages or [])self._each_provider("on_session_end failed", lambda p: p.on_session_end(messages), level=logging.WARNING,exc_info=True)@@ -739,6 +806,7 @@ class MemoryManager:"""parts = []checkpoint_succeeded = False+ messages, evidence_messages = _redact_for_provider(messages or [], evidence_messages)for provider in self._providers:version = self._checkpoint_api_version(provider)if version is None:@@ -777,6 +845,7 @@ class MemoryManager:def on_memory_write(self, action: str, target: str, content: str,metadata: Optional[Dict[str, Any]] = None) -> None:"""Notify external providers when the built-in memory tool writes (skips builtin, the source)."""+ content, metadata = _redact_for_provider(content, dict(metadata or {}))def _notify(provider: MemoryProvider) -> None:mode = self._provider_memory_write_metadata_mode(provider)@@ -844,6 +913,7 @@ class MemoryManager:logger.debug("notify_memory_tool_write failed for op %s: %s", action, e)def on_delegation(self, task: str, result: str, *, child_session_id: str = "", **kwargs) -> None:+ task, result = _redact_for_provider(task, result)self._each_provider("on_delegation failed",lambda p: p.on_delegation(task, result, child_session_id=child_session_id, **kwargs),diff --git a/agent/redact.py b/agent/redact.pyindex 0b751de32a2..4822168a588 100644--- a/agent/redact.py+++ b/agent/redact.py@@ -422,6 +422,10 @@ def _should_redact_assignment(key: str, value: str, *, check_keyword: bool) -> b# JSON field patterns: "apiKey": "value", "token": "value", etc._JSON_KEY_NAMES = r"(?:api_?[Kk]ey|token|secret|password|access_token|refresh_token|auth_token|bearer|secret_value|raw_secret|secret_input|key_material)"_JSON_FIELD_RE = re.compile(rf'("{_JSON_KEY_NAMES}")\s*:\s*"([^"]+)"', re.IGNORECASE)+# The same field inside a JSON-encoded string (``{"output": "{\\"api_key\\": \\"…\\"}"}``): every tool result+# that wraps a config dump in JSON escapes the quotes, so the rule above never saw the value (#115104).+# The backreference keeps the key's and value's escape depth equal.+_JSON_FIELD_ESCAPED_RE = re.compile(rf'((\\+)"{_JSON_KEY_NAMES}\2")\s*:\s*\2"([^"\\]+)\2"', re.IGNORECASE)# Python ``repr`` uses single-quoted mapping fields, so opaque credentials in# tracebacks and pytest failure introspection bypass the double-quoted JSON rule@@ -845,6 +849,9 @@ def _redact_assignments(text: str, *, mask_nonreusable: bool = False) -> str:if ":" in text and '"' in text:text = _JSON_FIELD_RE.sub(_assignment_sub(lambda g: f'{g[0]}: "{mask(g[1])}"', check_keyword=False), text)+ if '\\"' in text:+ text = _JSON_FIELD_ESCAPED_RE.sub(+ _assignment_sub(lambda g: f'{g[0]}: {g[1]}"{mask(g[2])}{g[1]}"', check_keyword=False), text)# Python mapping repr fields ({'API_KEY': '…'}): single-quoted, so the JSON rule# above never sees them — the traceback / pytest-introspection leak shape.diff --git a/tests/agent/test_memory_sync_redaction.py b/tests/agent/test_memory_sync_redaction.pynew file mode 100644index 00000000000..15af349af1d--- /dev/null+++ b/tests/agent/test_memory_sync_redaction.py@@ -0,0 +1,104 @@+"""Every MemoryManager fan-out scrubs secrets before a memory provider sees them (#115104).++Providers archive whatever they are handed, so a key echoed into tool output used to land verbatim in the+provider's store. Asserts on absence of the secret, never on a mask format.+"""+import json++import pytest++from agent.memory_manager import MemoryManager+from agent.memory_provider import MemoryProvider++_SECRET = "sk-proj-abc123def456ghi789jkl012"+_LEAK = f"export OPENAI_API_KEY={_SECRET} and Authorization: Bearer opaque0123456789abcdef"+_IMAGE = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+++class _Recorder(MemoryProvider):+ pre_compress_checkpoint_api_version = 2++ def __init__(self):+ self.seen = []++ @property+ def name(self):+ return "recorder"++ def initialize(self, session_id="", **kw): pass+ def is_available(self): return True+ def system_prompt_block(self): return ""+ def get_tool_schemas(self): return [{"name": "rec_tool", "description": "d", "parameters": {"type": "object"}}]+ def prefetch(self, query, *, session_id=""): self.seen.append(query); return ""+ def queue_prefetch(self, query, *, session_id=""): self.seen.append(query)+ def sync_turn(self, user_content, assistant_content, *, session_id="", messages=None, **kw): self.seen.append((user_content, assistant_content, messages))+ def handle_tool_call(self, tool_name, args, **kw): self.seen.append(args); return "{}"+ def on_turn_start(self, turn_number, message, **kw): self.seen.append(message)+ def on_session_end(self, messages): self.seen.append(messages)+ def on_pre_compress(self, messages, **kw): self.seen.append(messages); return ""+ def on_delegation(self, task, result, **kw): self.seen.append((task, result))+ def on_memory_write(self, action, target, content, metadata=None): self.seen.append((content, metadata))+++def _transcript():+ return [{"role": "user", "content": "read the config"},+ {"role": "tool", "content": f"ov.conf: {_LEAK}"},+ {"role": "user", "content": [{"type": "text", "text": _LEAK}, _IMAGE]},+ {"role": "assistant", "tool_calls": [{"function": {"arguments": f'{{"cmd": "{_LEAK}"}}'}}]}]+++_TRANSCRIPT_FANOUTS = {"sync_all", "on_session_end", "on_pre_compress"}+FANOUTS = {+ "sync_all": lambda m, t: m.sync_all(f"user {_LEAK}", f"assistant {_LEAK}", messages=t),+ "prefetch_all": lambda m, t: m.prefetch_all(f"recall {_LEAK}"),+ "queue_prefetch_all": lambda m, t: m.queue_prefetch_all(f"recall {_LEAK}"),+ "handle_tool_call": lambda m, t: m.handle_tool_call("rec_tool", {"q": _LEAK, "nested": [_LEAK]}),+ "on_turn_start": lambda m, t: m.on_turn_start(1, _LEAK),+ "on_session_end": lambda m, t: m.on_session_end(t),+ "on_pre_compress": lambda m, t: m.on_pre_compress(t, evidence_messages=t),+ "on_delegation": lambda m, t: m.on_delegation(f"task {_LEAK}", f"result {_LEAK}"),+ "on_memory_write": lambda m, t: m.on_memory_write("add", "memory", _LEAK, metadata={"old_text": _LEAK}),+}+++def _manager():+ mgr, provider = MemoryManager(), _Recorder()+ mgr.add_provider(provider)+ return mgr, provider++[email protected]("fanout", sorted(FANOUTS))+def test_every_provider_fanout_scrubs_secrets_without_touching_the_live_transcript(fanout, monkeypatch):+ monkeypatch.setattr("agent.redact._REDACT_ENABLED", True)+ (mgr, provider), transcript = _manager(), _transcript()+ FANOUTS[fanout](mgr, transcript)+ mgr.flush_pending(timeout=5.0)++ assert provider.seen, f"{fanout} never reached the provider"+ seen = repr(provider.seen)+ assert _SECRET not in seen and "opaque0123456789abcdef" not in seen+ if fanout in _TRANSCRIPT_FANOUTS:+ assert "read the config" in seen and repr(_IMAGE) in seen # clean text and inline media pass through+ assert _SECRET in repr(transcript) # providers got copies; the agent's own transcript is untouched+++def test_scrub_holds_with_redact_secrets_off(monkeypatch):+ # Provider egress follows chat/cron egress: redact_secrets governs local logs, not what leaves the agent.+ monkeypatch.setattr("agent.redact._REDACT_ENABLED", False)+ mgr, provider = _manager()+ mgr.sync_all("hi", _LEAK)+ mgr.flush_pending(timeout=5.0)+ assert _SECRET not in repr(provider.seen)+++def test_key_detected_in_a_json_tool_result_is_also_masked_where_the_model_repeats_it_bare():+ # The #115104 incident shape: an opaque (no vendor prefix) key in an ov.conf dump inside a JSON tool result,+ # then echoed by the assistant in prose where no pattern alone could recognise it.+ key = "AQ.Ab8RN6Jx2kq9Zs0VwT4yLm3PbQe7HcUfGdA1nX5oIr"+ tool = json.dumps({"output": json.dumps({"embedding": {"api_key": key}, "model": "gemini"})})+ mgr, provider = _manager()+ mgr.sync_all("show my ov.conf", f"Your key is {key}.", messages=[{"role": "tool", "content": tool}])+ mgr.flush_pending(timeout=5.0)+ user, assistant, messages = provider.seen[0]+ assert key not in repr(provider.seen)+ assert user == "show my ov.conf" and json.loads(json.loads(messages[0]["content"])["output"])["model"] == "gemini"diff --git a/tests/agent/test_redact.py b/tests/agent/test_redact.pyindex beccb8146d1..4fc289a8172 100644--- a/tests/agent/test_redact.py+++ b/tests/agent/test_redact.py@@ -375,6 +375,21 @@ class TestJsonFields:result = redact_sensitive_text(text)assert result == text+ @pytest.mark.parametrize("depth", [1, 2])+ def test_json_field_inside_json_encoded_string_is_masked_and_stays_valid(self, depth):+ # A tool result wrapping a config dump escapes its quotes; the plain JSON rule never saw the value.+ import json+ key = "AQ.Ab8RN6Jx2kq9Zs0VwT4yLm3PbQe7HcUfGdA1nX5oIr"+ text = json.dumps({"api_key": key, "token": "CPU", "model": "gemini"})+ for _ in range(depth):+ text = json.dumps({"output": text})+ result = redact_sensitive_text(text)+ assert key not in result and '\\"token\\": \\"CPU\\"'.replace("\\", "\\" * (2 ** depth - 1)) in result+ inner = result+ for _ in range(depth):+ inner = json.loads(inner)["output"]+ assert json.loads(inner)["model"] == "gemini"+class TestPythonReprFields:@pytest.mark.parametrize(diff --git a/website/docs/user-guide/features/memory-providers.md b/website/docs/user-guide/features/memory-providers.mdindex b514e61119e..821cf09d8e8 100644--- a/website/docs/user-guide/features/memory-providers.md+++ b/website/docs/user-guide/features/memory-providers.md@@ -40,6 +40,8 @@ When a memory provider is active, Hermes automatically:The built-in memory (MEMORY.md / USER.md) continues to work exactly as before. The external provider is additive.+Everything Hermes hands a provider (turns, the transcript including tool output, recall queries, session-end and pre-compression transcripts, mirrored memory writes, delegation results and the arguments of the provider's own tools) passes through the same secret scrub as chat-platform and cron delivery first, so a key echoed into tool output is masked before the provider can store it. Like that delivery scrub it applies even with `security.redact_secrets: false`. Credentials with no recognisable shape (an arbitrary password, an opaque token outside a `key=value` or `Bearer` context) are not detected; your local transcript keeps the original text.+## Available Providers### Honcho