The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): scrub the bot-chat deferred record too; trim redaction tests to two invariants; docs
teknium10db097dc22d1
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex a863e90682e..4f8e2451c7c 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -747,12 +747,14 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Optjob_id = job.get("id", "?")profile_label = profile or "(own)"# Outward lane: this text becomes an inbound turn in another profile's Bot Chat — via the- # live owner or the CLI fallback — so it gets the same fail-closed scrub as the chat message- # and the session mirror. Redact here, above both lanes, so neither can be added back unscanned.+ # live owner, the CLI fallback, or a deferred record replayed later — so it gets the same+ # fail-closed scrub as the chat message and the session mirror. Rebind ``content`` itself so+ # the durable deferred record below also carries the scrubbed copy, not the raw output.+ content = _redact_cron_payload(content, "bot-chat payload")message = (f'[Cronjob "{_redact_cron_payload(job.get("name", job_id), "job name")}" output — 'f"scheduled job, not the user. Review it, act on anything that needs action, and "- f"summarize for the chat.]\n\n{_redact_cron_payload(content, 'bot-chat payload')}"+ f"summarize for the chat.]\n\n{content}")try:source_home = get_hermes_home().resolve()diff --git a/tests/cron/test_cron_delivery_redaction.py b/tests/cron/test_cron_delivery_redaction.pyindex 3470c1d1216..2b6b4772deb 100644--- a/tests/cron/test_cron_delivery_redaction.py+++ b/tests/cron/test_cron_delivery_redaction.py@@ -1,203 +1,119 @@-"""Cron delivery text must be secret-redacted before it reaches any platform.+"""Cron output is secret-redacted on every outward lane, fail-closed.-Shell-job stdout/stderr is redacted where it is captured, but an LLM cron job's-response text reached ``_deliver_result`` unscanned, so a job that surfaced a-credential in its answer delivered it verbatim to the chat.+Shell-job stdout/stderr is redacted where it is captured, but an LLM cron job's response text+reaches ``_deliver_result`` unscanned. Every egress lane — platform send, session mirror (payload+and spliced job name), bot-chat turn — must apply ``redact_sensitive_text(force=True)``: the+``security.redact_secrets`` preference governs the user's own logs, not egress, and a raising+redactor must replace the payload rather than let it through."""+import importlib+from contextlib import ExitStackfrom unittest.mock import AsyncMock, MagicMock, patch+import pytest++# Synthetic vendor-prefixed key, long enough to trip the redactor; never a real credential.+FAKE_SECRET = "sk-" + "A" * 32+BODY = "Job finished. 3 tasks done, 1 pending."+def _telegram_cfg():from gateway.config import Platformpconfig = MagicMock()pconfig.enabled = True- mock_cfg = MagicMock()- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}- return mock_cfg---def _job():- return {- "id": "report-job",- "name": "daily-report",- "deliver": "origin",- "origin": {"platform": "telegram", "chat_id": "123"},- }---# A synthetic OpenAI-style key: long enough to trip the redactor, and not a-# real credential.-FAKE_SECRET = "sk-" + "A" * 32---class TestCronDeliveryRedaction:- def test_standalone_delivery_redacts_secret(self):- """A secret in the job's answer must not reach the platform send.-- Redaction happens once on ``cleaned_delivery_content`` right after- media extraction — i.e. before the live-adapter / standalone branch —- so both delivery paths consume the same redacted string. This test- drives the standalone branch; the live-adapter branch reads the very- same variable.- """- from cron.scheduler_delivery import _deliver_result-- send_mock = AsyncMock(return_value={"success": True})- with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \- patch("tools.send_message_tool._send_to_platform", new=send_mock), \- patch("sys.is_finalizing", return_value=False):- _deliver_result(_job(), f"Job finished. Token was {FAKE_SECRET} (oops).")-- send_mock.assert_called_once()- delivered = " ".join(str(a) for a in send_mock.call_args.args)- delivered += " " + " ".join(str(v) for v in send_mock.call_args.kwargs.values())- assert FAKE_SECRET not in delivered, "secret reached the platform send"-- def test_clean_content_is_unchanged(self):- """Redaction must not mangle ordinary delivery text."""- from cron.scheduler_delivery import _deliver_result-- body = "Daily report: 3 tasks done, 1 pending. All systems nominal."- send_mock = AsyncMock(return_value={"success": True})- with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \- patch("tools.send_message_tool._send_to_platform", new=send_mock), \- patch("sys.is_finalizing", return_value=False):- result = _deliver_result(_job(), body)-- send_mock.assert_called_once()- delivered = " ".join(str(a) for a in send_mock.call_args.args)- assert "3 tasks done" in delivered- assert result is None-- def _deliver_with_mirror(self, job, content):- """Drive a delivery with the mirror enabled, through the REAL- ``_maybe_mirror_cron_delivery``, capturing what reaches the- ``mirror_to_session`` sink. Mocking the mirror helper itself would hide- anything the sink splices in around the payload (e.g. the job-name- prefix), so only the outermost session write is stubbed."""- from cron.scheduler_delivery import _deliver_result-- send_mock = AsyncMock(return_value={"success": True})- sink_mock = MagicMock(return_value=True)- with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \- patch("tools.send_message_tool._send_to_platform", new=send_mock), \- patch("cron.scheduler_delivery._cron_mirror_delivery_enabled", return_value=True), \- patch("cron.scheduler_delivery._target_matches_origin", return_value=True), \- patch("gateway.mirror.mirror_to_session", new=sink_mock), \- patch("sys.is_finalizing", return_value=False):- _deliver_result(job, content)-- assert sink_mock.called, "mirror sink did not run — test would vacuously pass"- mirrored = " ".join(str(a) for a in sink_mock.call_args.args)- mirrored += " " + " ".join(str(v) for v in sink_mock.call_args.kwargs.values())- return mirrored-- def test_session_mirror_payload_redacts_secret(self):- """The delivery mirror must not write an unredacted secret to the session.-- ``mirror_text`` is derived from the raw ``content``, not from- ``cleaned_delivery_content``, so it does not inherit the delivery-path- redaction. With ``cron.mirror_delivery`` enabled the mirror payload is- appended to the origin chat's session transcript — an unscanned value- there is just as exposed as one sent to the chat, and survives longer.- """- mirrored = self._deliver_with_mirror(- _job(), f"Job finished. Token was {FAKE_SECRET} (oops).",- )- # An empty mirror payload would satisfy the secret assertion for the- # wrong reason, so pin that the real body still went through.- assert "Job finished." in mirrored, "mirror payload was empty — assertion below is vacuous"- assert FAKE_SECRET not in mirrored, "secret reached the session mirror payload"-- def test_session_mirror_job_name_does_not_leak_secret(self):- """The sink splices the job NAME around the redacted payload.-- The name is user-controlled config; redacting only the body would leave- ``[Cron delivery: <name-with-secret>]`` re-leaking a credential right- next to the scrubbed text.- """- job = _job()- job["name"] = f"rotate {FAKE_SECRET} daily"- mirrored = self._deliver_with_mirror(job, "Job finished. All good.")- assert "[Cron delivery:" in mirrored, "sink prefix missing — assembly path not exercised"- assert FAKE_SECRET not in mirrored, "secret in the job name reached the session mirror"-- def test_redaction_survives_disabled_logging_preference(self, monkeypatch):- """``security.redact_secrets: false`` must not disable delivery redaction.-- That preference governs how much is scrubbed from the user's own logs.- Delivery is an egress boundary, so it redacts with ``force=True`` — the- same rule the other safety boundaries in the tree already follow (e.g.- ``tools/delegation_live_log.py``, ``tools/approval.py``). Without it a- user who turned down log scrubbing would silently also turn off secret- scrubbing on the way out to the chat.- """- import importlib-- import agent.redact-- monkeypatch.setenv("HERMES_REDACT_SECRETS", "false")+ cfg = MagicMock()+ cfg.platforms = {Platform.TELEGRAM: pconfig}+ return cfg+++def _job(name: str = "daily-report") -> dict:+ return {"id": "report-job", "name": name, "deliver": "origin",+ "origin": {"platform": "telegram", "chat_id": "123"}}+++def _flat(call) -> str:+ return " ".join(str(a) for a in call.args) + " " + " ".join(str(v) for v in call.kwargs.values())+++def _deliver_platform_and_mirror(job: dict, content: str) -> tuple[str, str]:+ """Drive ``_deliver_result`` with the mirror on; stub only the outermost sinks (the platform+ send and the session write) so the real assembly — including the job-name splice — runs."""+ from cron.scheduler_delivery import _deliver_result++ send = AsyncMock(return_value={"success": True})+ sink = MagicMock(return_value=True)+ with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \+ patch("tools.send_message_tool._send_to_platform", new=send), \+ patch("cron.scheduler_delivery._cron_mirror_delivery_enabled", return_value=True), \+ patch("cron.scheduler_delivery._target_matches_origin", return_value=True), \+ patch("gateway.mirror.mirror_to_session", new=sink), \+ patch("sys.is_finalizing", return_value=False):+ _deliver_result(job, content)+ assert send.called and sink.called, "a sink did not run — assertions would be vacuous"+ return _flat(send.call_args), _flat(sink.call_args)+++def _deliver_bot_chat(job: dict, content: str) -> str:+ """Drive ``_deliver_to_bot_chat`` down to the CLI lane and capture the inbound turn."""+ from cron.scheduler_delivery import _deliver_to_bot_chat++ captured = {}++ def _fake_run(argv, **kwargs):+ with open(argv[argv.index("--query-file") + 1], encoding="utf-8") as fh:+ captured["message"] = fh.read()+ return MagicMock(returncode=0, stdout="", stderr="")++ with patch("cron.scheduler_delivery.subprocess.run", side_effect=_fake_run):+ err = _deliver_to_bot_chat(job, content, "")+ assert err is None, err+ return captured["message"]++[email protected]("lane", ["platform_send", "session_mirror", "bot_chat"])+def test_every_outward_lane_masks_secret_in_payload_and_job_name(lane):+ """Secret in the body AND in the user-controlled job name is masked on every lane, while+ ordinary text and the lane's own framing survive (no over-redaction, no empty payload)."""+ job = _job(name=f"rotate {FAKE_SECRET} daily")+ content = f"{BODY} Token was {FAKE_SECRET} (oops)."+ if lane == "bot_chat":+ out = _deliver_bot_chat(job, content)+ assert "[Cronjob " in out+ else:+ sent, mirrored = _deliver_platform_and_mirror(job, content)+ out = sent if lane == "platform_send" else mirrored+ if lane == "session_mirror":+ assert "[Cron delivery:" in out, "mirror prefix missing — assembly path not exercised"+ assert "3 tasks done" in out, "payload mangled or empty — secret assertion would be vacuous"+ assert FAKE_SECRET not in out, f"secret reached the {lane} lane"++[email protected]("mode", ["redact_secrets_off", "redactor_raises"])+def test_delivery_redaction_is_forced_and_fails_closed(mode, monkeypatch):+ """Egress redaction is independent of ``security.redact_secrets`` (force=True) and a raising+ redactor replaces the payload instead of passing the unscanned text through."""+ import agent.redact+ from cron.scheduler_delivery import _deliver_result++ send = AsyncMock(return_value={"success": True})+ try:+ with ExitStack() as stack:+ stack.enter_context(patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()))+ stack.enter_context(patch("tools.send_message_tool._send_to_platform", new=send))+ stack.enter_context(patch("sys.is_finalizing", return_value=False))+ if mode == "redact_secrets_off":+ monkeypatch.setenv("HERMES_REDACT_SECRETS", "false")+ importlib.reload(agent.redact)+ else:+ stack.enter_context(+ patch("agent.redact.redact_sensitive_text", side_effect=RuntimeError("boom")))+ _deliver_result(_job(), f"Token was {FAKE_SECRET}")+ finally:+ monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False)importlib.reload(agent.redact)- try:- from cron.scheduler_delivery import _deliver_result-- send_mock = AsyncMock(return_value={"success": True})- with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \- patch("tools.send_message_tool._send_to_platform", new=send_mock), \- patch("sys.is_finalizing", return_value=False):- _deliver_result(_job(), f"Job finished. Token was {FAKE_SECRET} (oops).")-- send_mock.assert_called_once()- delivered = " ".join(str(a) for a in send_mock.call_args.args)- delivered += " " + " ".join(str(v) for v in send_mock.call_args.kwargs.values())- assert FAKE_SECRET not in delivered, (- "logging preference disabled delivery redaction — needs force=True"- )- finally:- monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False)- importlib.reload(agent.redact)-- def test_redaction_failure_does_not_leak(self):- """If the redactor itself raises, the delivery must fail closed rather- than send the unscanned text."""- from cron.scheduler_delivery import _deliver_result-- send_mock = AsyncMock(return_value={"success": True})- with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \- patch("tools.send_message_tool._send_to_platform", new=send_mock), \- patch("agent.redact.redact_sensitive_text", side_effect=RuntimeError("boom")), \- patch("sys.is_finalizing", return_value=False):- _deliver_result(_job(), f"Token {FAKE_SECRET}")-- send_mock.assert_called_once()- delivered = " ".join(str(a) for a in send_mock.call_args.args)- assert FAKE_SECRET not in delivered- assert "REDACTED" in delivered-- def test_bot_chat_lane_redacts_secret(self):- """The bot-chat lane hands the job's output to another profile as a real inbound turn.-- That turn lands in a canonical session transcript, which outlives the message, so it needs- the same fail-closed scrub as the chat send and the mirror. Both the payload and the job- name are spliced into the prologue, so this drives a secret through each.- """- from cron.scheduler_delivery import _deliver_to_bot_chat- captured = {}-- def _fake_run(argv, **kwargs):- with open(argv[argv.index("--query-file") + 1], encoding="utf-8") as fh:- captured["message"] = fh.read()- return MagicMock(returncode=0, stdout="", stderr="")-- with patch("cron.scheduler_delivery.shutil.which", return_value="/usr/bin/hermes"), \- patch("cron.scheduler_delivery.subprocess.run", side_effect=_fake_run):- err = _deliver_to_bot_chat(- {"id": "report-job", "name": f"rotate {FAKE_SECRET} daily"},- f"Job finished. Token was {FAKE_SECRET} (oops).",- "",- )-- assert err is None, err- assert FAKE_SECRET not in captured["message"], "secret reached the bot-chat turn"+ delivered = _flat(send.call_args)+ assert FAKE_SECRET not in delivered, f"{mode}: secret reached the platform send"+ if mode == "redactor_raises":+ assert "REDACTED" in delivereddiff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 7671f5f6aa0..1e8282aad5d 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -540,6 +540,15 @@ When scheduling jobs, you specify where the output goes:The agent's final response is automatically delivered to the configured `deliver:` target — the agent does not send messages itself, so there is nothing to call in the cron prompt.+Delivered output is secret-redacted on the way out, on every lane: the platform message, the+session mirror (payload and the job name spliced around it), and a `bot-chat` turn. Credential+shapes (vendor-prefixed API keys, tokens, `KEY=value` assignments) are masked even when+`security.redact_secrets: false` — that setting governs your own logs, not what leaves the+machine — and a redactor failure replaces the payload rather than sending it unscanned.+Credential-named URL query parameters are not stripped (magic links and pre-signed URLs are+legitimate cron output), and user-chosen secrets with no recognisable shape are not detected.+The run document under `cron/output/<job_id>/` keeps the agent's response as written.+### Delivery failures are a distinct statusExecution and delivery are tracked separately. When the agent run succeeds but