Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(telegram): keep the bot token out of errors, status, logs and tracebacks (#554)
Ruben Lütkeecdc58f85d86
diff --git a/jarvis/channels/manager.py b/jarvis/channels/manager.pyindex a3329e84d8..36af521609 100644--- a/jarvis/channels/manager.py+++ b/jarvis/channels/manager.py@@ -153,9 +153,14 @@ class ChannelManager:self._started.add(name)log.info("Channel '%s' started", name)except Exception as exc: # noqa: BLE001- self._start_errors[name] = f"{type(exc).__name__}: {exc}"- log.error("Channel '%s' start failed: %s", name, exc)- raise ChannelStartError(f"Channel '{name}' could not start: {exc}") from exc+ from jarvis.core.redact import redact_secrets++ # A channel error may carry a credential (a Telegram token sits in+ # every Bot API URL): only a redacted text is stored, logged or raised.+ detail = redact_secrets(str(exc))+ self._start_errors[name] = f"{type(exc).__name__}: {detail}"+ log.error("Channel '%s' start failed: %s", name, detail)+ raise ChannelStartError(f"Channel '{name}' could not start: {detail}") from Noneasync def reload(self, name: str) -> None:"""Stop, drop the cached instance, and start ``name`` afresh.@@ -183,7 +188,9 @@ class ChannelManager:except ChannelStartError as exc:return str(exc)except Exception as exc: # noqa: BLE001- return f"{type(exc).__name__}: {exc}"+ from jarvis.core.redact import redact_secrets++ return f"{type(exc).__name__}: {redact_secrets(str(exc))}"async def stop(self, name: str) -> None:if name not in self._started:@@ -195,10 +202,12 @@ class ChannelManager:try:await instance.stop()except Exception as exc: # noqa: BLE001- log.warning("Channel '%s' stop raised: %s", name, exc)+ from jarvis.core.redact import redact_secrets++ log.warning("Channel '%s' stop raised: %s", name, redact_secrets(str(exc)))finally:self._started.discard(name)- log.info("Channel '%s' gestoppt", name)+ log.info("Channel '%s' stopped", name)async def stop_all(self) -> None:names = list(self._started)diff --git a/jarvis/channels/telegram.py b/jarvis/channels/telegram.pyindex 183df8da03..dc2b7bba15 100644--- a/jarvis/channels/telegram.py+++ b/jarvis/channels/telegram.py@@ -62,6 +62,27 @@ log = logging.getLogger(__name__)__all__ = ["TelegramChannel", "InflightMap"]+#: Longest error text kept from a Telegram/httpx exception.+_ERROR_TEXT_MAX = 300+++def _safe_error(exc: BaseException, token: str | None = None) -> str:+ """``Type: message`` with the bot token removed.++ The token is part of every Bot API URL, and python-telegram-bot itself+ puts it into ``InvalidToken`` ("The token `…` was rejected by the+ server."). Every error text this channel logs, stores or raises goes+ through here: the exact token first, then the generic secret shapes.+ """+ from jarvis.core.redact import redact_secrets++ message = str(exc)+ if token:+ message = message.replace(token, "[redacted]")+ message = redact_secrets(message)[:_ERROR_TEXT_MAX]+ name = type(exc).__name__+ return f"{name}: {message}" if message else name+class InflightMap:"""Mapping ``trace_id -> chat_id`` with TTL-based GC."""@@ -176,16 +197,32 @@ class TelegramChannel:"Install via: pip install 'python-telegram-bot>=22,<23'") from exc+ # python-telegram-bot polls through httpx, which logs every request URL+ # at INFO — and every Bot API URL carries the token.+ from jarvis.core.redact import redact_logger++ redact_logger("httpx")await self._validate_token(token)- self._app = ApplicationBuilder().token(token).build()- self._app.add_handler(MessageHandler(filters.ALL, self._on_telegram_msg))+ failure: str | None = None+ try:+ self._app = ApplicationBuilder().token(token).build()+ self._app.add_handler(MessageHandler(filters.ALL, self._on_telegram_msg))- await self._app.initialize()- await self._app.start()- await self._app.updater.start_polling(- poll_interval=self._cfg.polling_interval_s- )+ await self._app.initialize()+ await self._app.start()+ await self._app.updater.start_polling(+ poll_interval=self._cfg.polling_interval_s+ )+ except Exception as exc: # noqa: BLE001 — reported below without the token+ # ``initialize()`` re-checks the token and raises InvalidToken with+ # the token in its message.+ self._app = None+ failure = _safe_error(exc, token)+ if failure is not None:+ # Raised outside the handler: the original error is then not even+ # reachable from this one (no ``__context__``), whatever prints it.+ raise ChannelStartError(f"Telegram start failed: {failure}")self._event_handler_ref = self._on_bus_eventself._bus.subscribe_all(self._event_handler_ref)@@ -209,7 +246,7 @@ class TelegramChannel:await self._app.stop()await self._app.shutdown()except Exception as exc: # noqa: BLE001- log.warning("Telegram stop raised: %s", exc)+ log.warning("Telegram stop raised: %s", _safe_error(exc))self._app = Noneself._started = False@@ -222,7 +259,7 @@ class TelegramChannel:tokens = TokenStore().load("telegram")except Exception as exc: # noqa: BLE001- log.debug("Telegram marketplace token fallback failed: %s", exc)+ log.debug("Telegram marketplace token fallback failed: %s", _safe_error(exc))return Noneif tokens is None or not tokens.access:return None@@ -235,21 +272,23 @@ class TelegramChannel:async def _validate_token(self, token: str) -> None:from telegram import Bot # noqa: WPS433- from telegram.error import InvalidToken, TelegramError # noqa: WPS433+ from telegram.error import InvalidToken # noqa: WPS433bot = Bot(token=token)+ failure: str | None = Nonetry:me = await bot.get_me()self._bot_username = (me.username or "").lower() or "<unknown>"- except InvalidToken as exc:- raise ChannelStartError(+ except InvalidToken: # reported below; its own message carries the token+ failure = ("Telegram token invalid (InvalidToken). ""Check the token in @BotFather or renew it via the wizard."- ) from exc- except TelegramError as exc:- raise ChannelStartError(f"Telegram getMe failed: {exc}") from exc- except Exception as exc: # noqa: BLE001- raise ChannelStartError(f"Telegram getMe failed: {exc}") from exc+ )+ except Exception as exc: # noqa: BLE001 — reported below without the token+ failure = f"Telegram getMe failed: {_safe_error(exc, token)}"+ if failure is not None:+ # Outside the handler, so the original error is not its context.+ raise ChannelStartError(failure)# ------------------------------------------------------------------# Inbound@@ -480,7 +519,7 @@ class TelegramChannel:try:await self._app.bot.send_message(chat_id=chat_id, text=cleaned)except Exception as exc: # noqa: BLE001- log.warning("Telegram send_message failed (chat=%s): %s", chat_id, exc)+ log.warning("Telegram send_message failed: %s", _safe_error(exc))# === F-FRIENDS [F4] · feature/friends-section · ruben-2026-05-01 ===async def send_status_card(@@ -512,9 +551,7 @@ class TelegramChannel:chat_id=chat_id, text=text, parse_mode="Markdown")except Exception as exc: # noqa: BLE001- log.warning(- "Telegram send_status_card failed (chat=%s): %s", chat_id, exc- )+ log.warning("Telegram send_status_card failed: %s", _safe_error(exc))async def sessions(self) -> list[ChannelSession]:return list(self._sessions_by_chat.values())diff --git a/jarvis/core/redact.py b/jarvis/core/redact.pyindex 8a682c16af..48f13aba88 100644--- a/jarvis/core/redact.py+++ b/jarvis/core/redact.py@@ -21,7 +21,9 @@ import upward into ``jarvis.memory``. The two differ in intent: ``secret_guard``from __future__ import annotationsimport json+import loggingimport re+import tracebackfrom collections.abc import Mappingfrom typing import Any@@ -146,4 +148,56 @@ def safe_preview(value: Any, *, max_chars: int = DEFAULT_PREVIEW_CHARS) -> str:return text-__all__ = ["DEFAULT_PREVIEW_CHARS", "redact_secrets", "safe_preview"]+class RedactingLogFilter(logging.Filter):+ """Mask credential shapes in a record before any handler formats it.++ httpx logs every request at INFO with its full URL, and some APIs carry+ the credential IN the URL (the Telegram Bot API: ``/bot<token>/...``).+ Rewriting the record here protects every handler — file, console, test+ capture — not only the desktop log sink.+ """++ def filter(self, record: logging.LogRecord) -> bool:+ try:+ message = record.getMessage()+ except Exception: # noqa: BLE001 — a malformed record is passed on untouched+ return True+ cleaned = redact_secrets(message)+ if cleaned != message:+ record.msg = cleaned+ record.args = ()+ # A logged exception is printed below the message: its text and the+ # texts of its causes can carry the same URL.+ if record.exc_info and record.exc_info[0] is not None:+ trace = "".join(traceback.format_exception(*record.exc_info))+ cleaned_trace = redact_secrets(trace)+ if cleaned_trace != trace:+ # Formatters print ``exc_text`` as it is; without ``exc_info``+ # no handler can format the original again.+ record.exc_text = cleaned_trace.rstrip("\n")+ record.exc_info = None+ if record.exc_text:+ record.exc_text = redact_secrets(record.exc_text)+ if record.stack_info:+ record.stack_info = redact_secrets(record.stack_info)+ return True+++_REDACTED_LOGGERS: set[str] = set()+++def redact_logger(name: str) -> None:+ """Attach one :class:`RedactingLogFilter` to logger *name* (idempotent)."""+ if name in _REDACTED_LOGGERS:+ return+ logging.getLogger(name).addFilter(RedactingLogFilter())+ _REDACTED_LOGGERS.add(name)+++__all__ = [+ "DEFAULT_PREVIEW_CHARS",+ "RedactingLogFilter",+ "redact_logger",+ "redact_secrets",+ "safe_preview",+]diff --git a/jarvis/workflows/runner.py b/jarvis/workflows/runner.pyindex e1f7a34c61..2e6936a501 100644--- a/jarvis/workflows/runner.py+++ b/jarvis/workflows/runner.py@@ -679,6 +679,9 @@ class WorkflowRunner:import httpx+ from jarvis.core.redact import redact_logger++ redact_logger("httpx") # its request log line would carry the token in the URLurl = f"https://api.telegram.org/bot{token}/sendMessage"payload: dict[str, Any] = {"chat_id": chat_id,@@ -687,19 +690,21 @@ class WorkflowRunner:if parse_mode:payload["parse_mode"] = parse_mode+ failure: str | None = Noneasync with httpx.AsyncClient(timeout=15.0) as client:try:r = await client.post(url, json=payload)- except Exception as exc: # noqa: BLE001- raise RuntimeError(f"Telegram request failed: {exc}") from exc+ except Exception as exc: # noqa: BLE001 — reported below, by type only+ # The type only: an httpx error can carry the URL, and the URL+ # carries the bot token.+ failure = type(exc).__name__+ if failure is not None:+ # Raised outside the handler, so the original error is not even+ # reachable from this one as its context.+ raise RuntimeError(f"Telegram request failed: {failure}")if r.status_code >= 400:- # Telegram responds with ``{"ok": false, "description": "..."}``- try:- detail = r.json().get("description") or r.text[:200]- except Exception: # noqa: BLE001- detail = r.text[:200]- raise RuntimeError(f"Telegram HTTP {r.status_code}: {detail}")+ raise RuntimeError(_telegram_failure(r))return f"sent to chat_id={chat_id} ({len(text)} characters)"@@ -707,6 +712,66 @@ class WorkflowRunner:# Helpers# ----------------------------------------------------------------------+#: What a failed ``sendMessage`` means, by a fragment of Telegram's+#: ``description``. The description is only matched: it is a provider error+#: body and never reaches the run record, the UI or a log (AP-34).+_TELEGRAM_REASONS: tuple[tuple[str, str], ...] = (+ (+ "chat not found",+ "the chat was not found. Check the chat ID; the recipient has to start "+ "the bot before it can write to them",+ ),+ ("bot was blocked", "the recipient blocked the bot"),+ ("can't initiate conversation", "the recipient has not started a chat with the bot yet"),+ ("user is deactivated", "the recipient's account is deactivated"),+ ("upgraded to a supergroup", "the group became a supergroup and has a new chat ID"),+ ("bot was kicked", "the bot was removed from that chat"),+ ("not a member", "the bot is not a member of that chat"),+ ("rights to send", "the bot is not allowed to post in that chat"),+ ("can't parse entities", "the message formatting is not valid for the configured parse mode"),+ ("message is too long", "the message is too long"),+ ("text is empty", "the message text is empty"),+)++#: The reason when the description names none of the above.+_TELEGRAM_STATUS_REASONS: dict[int, str] = {+ 401: "the bot token was rejected. Check it in @BotFather",+ # Telegram answers a malformed token with 404, not 401.+ 404: "the bot token was rejected. Check it in @BotFather",+ 403: "the bot is not allowed to write to that chat",+ 429: "Telegram is rate limiting the bot",+}+++def _telegram_failure(response: Any) -> str:+ """One sentence for a failed Bot API call: the status and a fixed reason.++ Every word is written here, so neither the bot token nor any text of+ Telegram's own can end up in it.+ """+ status = int(response.status_code)+ description = ""+ retry_after: int | None = None+ try:+ body = response.json()+ except ValueError: # no JSON body (a proxy page): the status decides alone+ body = None+ if isinstance(body, dict):+ description = str(body.get("description") or "").lower()+ parameters = body.get("parameters")+ if isinstance(parameters, dict) and isinstance(parameters.get("retry_after"), int):+ retry_after = parameters["retry_after"]+ reason = next(+ (text for fragment, text in _TELEGRAM_REASONS if fragment in description),+ _TELEGRAM_STATUS_REASONS.get(status),+ )+ if reason is None and status >= 500:+ reason = "Telegram is not available right now"+ if status == 429 and retry_after is not None and retry_after >= 0:+ reason = f"{_TELEGRAM_STATUS_REASONS[429]}; try again in {retry_after} s"+ return f"Telegram HTTP {status}: {reason}" if reason else f"Telegram HTTP {status}"++_TEMPLATE_RE = re.compile(r"\{\{\s*([^}]+?)\s*\}\}")diff --git a/tests/unit/channels/test_telegram_token_safety.py b/tests/unit/channels/test_telegram_token_safety.pynew file mode 100644index 0000000000..79a096c81e--- /dev/null+++ b/tests/unit/channels/test_telegram_token_safety.py@@ -0,0 +1,357 @@+"""The Telegram bot token never leaks through errors, stored status or logs.++The token sits in every Bot API URL, and python-telegram-bot 22 puts it into+``InvalidToken`` ("The token `…` was rejected by the server."). These tests+feed exactly such errors through the channel, the channel manager and the+workflow ``telegram_send`` step. The token is a fake string; nothing goes out.+"""++from __future__ import annotations++import logging+import sys+import traceback+import types+from pathlib import Path+from typing import Any++import httpx+import pytest++from jarvis.channels.manager import ChannelContext, ChannelManager, ChannelStartError+from jarvis.channels.telegram import TelegramChannel, _safe_error+from jarvis.core.bus import EventBus+from jarvis.core.config import TelegramConfig++FAKE_TOKEN = "987654321:AAFakeTokenForTestsOnly_abcdefghijklmnop" # noqa: S105 - a fake+++def _all_text(exc: BaseException) -> str:+ """Everything a traceback print of *exc* would show, causes included."""+ return "".join(traceback.format_exception(exc))+++def test_safe_error_removes_the_exact_token_and_known_shapes() -> None:+ text = _safe_error(+ RuntimeError(f"The token `{FAKE_TOKEN}` was rejected by the server."), FAKE_TOKEN+ )+ assert FAKE_TOKEN not in text and text.startswith("RuntimeError: ")+ url_error = _safe_error(httpx.ConnectError(f"https://api.telegram.org/bot{FAKE_TOKEN}/getMe"))+ assert FAKE_TOKEN not in url_error # the generic redactor knows the token shape+++# --- Channel start ----------------------------------------------------------------+++class _InvalidToken(Exception):+ pass+++def _install_fake_ptb(monkeypatch: pytest.MonkeyPatch, *, fail_on: str) -> None:+ """A stand-in for telegram / telegram.ext that fails like PTB 22.8."""++ class Bot:+ def __init__(self, token: str) -> None:+ self.token = token++ async def get_me(self) -> Any:+ if fail_on == "get_me":+ raise TelegramError(f"Bad gateway for /bot{self.token}/getMe")+ return types.SimpleNamespace(username="jarvis_bot")++ class TelegramError(Exception):+ pass++ class App:+ def __init__(self, token: str) -> None:+ self.token = token++ def add_handler(self, *_a: Any) -> None:+ return None++ async def initialize(self) -> None:+ if fail_on == "initialize":+ raise _InvalidToken(f"The token `{self.token}` was rejected by the server.")++ class Builder:+ def token(self, token: str) -> Any:+ self._token = token+ return self++ def build(self) -> App:+ return App(self._token)++ telegram_mod = types.ModuleType("telegram")+ telegram_mod.Bot = Bot # type: ignore[attr-defined]+ error_mod = types.ModuleType("telegram.error")+ error_mod.InvalidToken = _InvalidToken # type: ignore[attr-defined]+ error_mod.TelegramError = TelegramError # type: ignore[attr-defined]+ ext_mod = types.ModuleType("telegram.ext")+ ext_mod.ApplicationBuilder = Builder # type: ignore[attr-defined]+ ext_mod.MessageHandler = lambda *_a, **_k: None # type: ignore[attr-defined]+ ext_mod.filters = types.SimpleNamespace(ALL=object()) # type: ignore[attr-defined]+ monkeypatch.setitem(sys.modules, "telegram", telegram_mod)+ monkeypatch.setitem(sys.modules, "telegram.error", error_mod)+ monkeypatch.setitem(sys.modules, "telegram.ext", ext_mod)+ monkeypatch.setattr("jarvis.channels.telegram.get_secret", lambda *_a, **_k: FAKE_TOKEN)++[email protected]("fail_on", ["get_me", "initialize"])+async def test_a_failed_start_never_carries_the_token(+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, fail_on: str+) -> None:+ _install_fake_ptb(monkeypatch, fail_on=fail_on)+ channel = TelegramChannel(EventBus(), TelegramConfig(enabled=True))+ with pytest.raises(ChannelStartError) as exc:+ await channel.start()+ assert FAKE_TOKEN not in _all_text(exc.value)+ # Not merely hidden from a traceback print: the token-bearing original is+ # not reachable from the raised error at all.+ assert exc.value.__cause__ is None and exc.value.__context__ is None++ # Through the manager: stored status, log and the raised error.+ manager = ChannelManager(ChannelContext(bus=EventBus()))+ monkeypatch.setattr(manager, "get", lambda _name: channel)+ with caplog.at_level(logging.DEBUG), pytest.raises(ChannelStartError) as via_manager:+ await manager.start("telegram")+ assert FAKE_TOKEN not in _all_text(via_manager.value)+ assert FAKE_TOKEN not in repr(via_manager.value)+ assert FAKE_TOKEN not in str(manager.start_errors()) # the status payload+ assert FAKE_TOKEN not in caplog.text+++async def test_the_manager_redacts_any_channel_error(caplog: pytest.LogCaptureFixture) -> None:+ class Leaky:+ name = "leaky"++ async def start(self) -> None:+ raise RuntimeError(f"connect to https://api.telegram.org/bot{FAKE_TOKEN}/getUpdates")++ manager = ChannelManager(ChannelContext(bus=EventBus()))+ manager.get = lambda _name: Leaky() # type: ignore[method-assign]+ with caplog.at_level(logging.DEBUG), pytest.raises(ChannelStartError) as exc:+ await manager.start("leaky")+ assert FAKE_TOKEN not in _all_text(exc.value)+ assert FAKE_TOKEN not in str(manager._start_errors) and FAKE_TOKEN not in caplog.text+ assert await manager._start_safe("leaky") is not None+ assert FAKE_TOKEN not in (await manager._start_safe("leaky") or "")+++async def test_send_failures_log_no_token_and_no_chat(caplog: pytest.LogCaptureFixture) -> None:+ class _Bot:+ async def send_message(self, **_k: Any) -> None:+ raise httpx.ConnectError(f"https://api.telegram.org/bot{FAKE_TOKEN}/sendMessage")++ channel = TelegramChannel(EventBus(), TelegramConfig())+ channel._app = types.SimpleNamespace(bot=_Bot())+ with caplog.at_level(logging.DEBUG):+ await channel._send_text(55501234, "hello", language="en")+ assert caplog.records+ assert FAKE_TOKEN not in caplog.text and "55501234" not in caplog.text+++# --- Workflow telegram_send step ----------------------------------------------------+++def telegram_step(monkeypatch: pytest.MonkeyPatch) -> Any:+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: FAKE_TOKEN)+ return types.SimpleNamespace(chat_id="4242", text="hello")+++def _runner() -> Any:+ from jarvis.workflows.runner import WorkflowRunner++ return WorkflowRunner.__new__(WorkflowRunner)+++async def test_workflow_network_error_has_no_url_or_token(+ monkeypatch: pytest.MonkeyPatch, telegram_step: Any+) -> None:+ async def _post(self: Any, url: str, **_k: Any) -> Any:+ raise httpx.ConnectError(f"cannot reach {url}")++ monkeypatch.setattr(httpx.AsyncClient, "post", _post)+ with pytest.raises(RuntimeError) as exc:+ await _runner()._run_telegram_send(telegram_step, {}, {})+ assert str(exc.value) == "Telegram request failed: ConnectError"+ assert FAKE_TOKEN not in _all_text(exc.value)+ assert exc.value.__cause__ is None and exc.value.__context__ is None+++def _answer(monkeypatch: pytest.MonkeyPatch, response: httpx.Response) -> None:+ async def _post(self: Any, url: str, **_k: Any) -> Any:+ return response++ monkeypatch.setattr(httpx.AsyncClient, "post", _post)+++ ("status", "description", "expected"),+ [+ (400, "Bad Request: chat not found", "the chat was not found"),+ (403, "Forbidden: bot was blocked by the user", "the recipient blocked the bot"),+ (+ 403,+ "Forbidden: bot can't initiate conversation with a user",+ "has not started a chat with the bot",+ ),+ (400, "Bad Request: can't parse entities: Can't find end", "formatting is not valid"),+ (401, "Unauthorized", "the bot token was rejected"),+ (404, "Not Found", "the bot token was rejected"),+ (403, "Forbidden: something new", "not allowed to write to that chat"),+ (502, "Bad Gateway", "not available right now"),+ ],+)+async def test_workflow_http_error_says_why_in_its_own_words(+ monkeypatch: pytest.MonkeyPatch,+ telegram_step: Any,+ status: int,+ description: str,+ expected: str,+) -> None:+ """The person learns why the send failed, from a sentence written here:+ Telegram's own text and the token are never part of it."""+ _answer(+ monkeypatch,+ httpx.Response(+ status,+ json={"ok": False, "error_code": status, "description": f"{description} {FAKE_TOKEN}"},+ ),+ )+ with pytest.raises(RuntimeError) as exc:+ await _runner()._run_telegram_send(telegram_step, {}, {})+ text = str(exc.value)+ assert text.startswith(f"Telegram HTTP {status}: ") and expected in text+ assert FAKE_TOKEN not in _all_text(exc.value)+ assert description not in text # matched, never passed on+++async def test_workflow_rate_limit_names_the_wait(+ monkeypatch: pytest.MonkeyPatch, telegram_step: Any+) -> None:+ _answer(+ monkeypatch,+ httpx.Response(+ 429,+ json={+ "ok": False,+ "description": "Too Many Requests: retry after 17",+ "parameters": {"retry_after": 17},+ },+ ),+ )+ with pytest.raises(RuntimeError) as exc:+ await _runner()._run_telegram_send(telegram_step, {}, {})+ assert str(exc.value) == (+ "Telegram HTTP 429: Telegram is rate limiting the bot; try again in 17 s"+ )+++ "response",+ [+ httpx.Response(400, json={"ok": False, "description": f"Bad Request: new {FAKE_TOKEN}"}),+ httpx.Response(400, text=f"<html>proxy error for /bot{FAKE_TOKEN}/sendMessage</html>"),+ httpx.Response(400, json=[f"unexpected {FAKE_TOKEN}"]),+ httpx.Response(+ 429, json={"ok": False, "parameters": {"retry_after": f"soon {FAKE_TOKEN}"}}+ ),+ ],+)+async def test_workflow_unknown_http_error_keeps_only_the_status(+ monkeypatch: pytest.MonkeyPatch, telegram_step: Any, response: httpx.Response+) -> None:+ _answer(monkeypatch, response)+ with pytest.raises(RuntimeError) as exc:+ await _runner()._run_telegram_send(telegram_step, {}, {})+ assert str(exc.value).startswith(f"Telegram HTTP {response.status_code}")+ assert FAKE_TOKEN not in _all_text(exc.value)+++async def test_a_failed_workflow_run_stores_and_logs_no_token(+ monkeypatch: pytest.MonkeyPatch,+ telegram_step: Any,+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """End to end: the run record, the step record and every log line of a+ failed ``telegram_send`` step, with the token echoed in the error body."""+ import asyncio++ from jarvis.workflows import WorkflowRunner, WorkflowStore+ from jarvis.workflows.schema import ManualTrigger, TelegramSendStep, WorkflowDef++ _answer(+ monkeypatch,+ httpx.Response(+ 400,+ json={+ "ok": False,+ "description": f"Bad Request: chat not found /bot{FAKE_TOKEN}/sendMessage",+ },+ ),+ )+ store = WorkflowStore(tmp_path / "wf.sqlite")+ await store.init()+ try:+ runner = WorkflowRunner(store=store, bus=EventBus())+ workflow_id = await store.upsert_workflow(+ WorkflowDef(+ name="TG",+ trigger=ManualTrigger(),+ steps=(TelegramSendStep(text="hi", chat_id="4242"),),+ )+ )+ with caplog.at_level(logging.DEBUG):+ run_id = await runner.trigger(workflow_id)+ run: dict[str, Any] | None = None+ for _ in range(200):+ await asyncio.sleep(0.01)+ run = await store.get_run(run_id)+ if run and run["state"] in ("completed", "failed"):+ break+ assert run is not None and run["state"] == "failed"+ assert "the chat was not found" in (run["error"] or "")+ assert FAKE_TOKEN not in str(run)+ assert FAKE_TOKEN not in caplog.text+ finally:+ await store.close()+++# --- httpx request log lines (INFO, full URL) -----------------------------------------+++def test_the_redacting_filter_masks_a_bot_url_in_any_log_record(+ caplog: pytest.LogCaptureFixture,+) -> None:+ from jarvis.core.redact import redact_logger++ logger = logging.getLogger("jarvis.test.redact_probe")+ redact_logger("jarvis.test.redact_probe")+ with caplog.at_level(logging.INFO, logger="jarvis.test.redact_probe"):+ logger.info(+ 'HTTP Request: POST %s "HTTP/1.1 200 OK"',+ f"https://api.telegram.org/bot{FAKE_TOKEN}/sendMessage",+ )+ assert caplog.records and FAKE_TOKEN not in caplog.text+ assert "/sendMessage" in caplog.text # the rest of the line stays readable+++async def test_a_successful_workflow_send_logs_no_token(+ monkeypatch: pytest.MonkeyPatch, telegram_step: Any, caplog: pytest.LogCaptureFixture+) -> None:+ real_client = httpx.AsyncClient++ def _client(*_a: Any, **kw: Any) -> httpx.AsyncClient:+ return real_client(+ transport=httpx.MockTransport(lambda _r: httpx.Response(200, json={"ok": True})),+ timeout=kw.get("timeout", 5),+ )++ monkeypatch.setattr(httpx, "AsyncClient", _client)+ with caplog.at_level(logging.DEBUG):+ result = await _runner()._run_telegram_send(telegram_step, {}, {})+ assert result.startswith("sent to chat_id=")+ assert "HTTP Request" in caplog.text # httpx did log the request…+ assert FAKE_TOKEN not in caplog.text # …without the tokendiff --git a/tests/unit/core/test_redact.py b/tests/unit/core/test_redact.pyindex 0c8fd23d16..ce8b3d60c7 100644--- a/tests/unit/core/test_redact.py+++ b/tests/unit/core/test_redact.py@@ -8,6 +8,10 @@ is capped so a tool cannot smuggle a large blob into the log."""from __future__ import annotations+import logging++import pytest+from jarvis.core.redact import DEFAULT_PREVIEW_CHARS, redact_secrets, safe_preview@@ -111,3 +115,57 @@ def test_structured_values_preview_as_json_not_python_repr() -> None:assert safe_preview(["café", 2]) == '["café", 2]'# Anything JSON cannot encode still previews instead of raising.assert safe_preview({"at": object()}).startswith('{"at": "<object object')+++# --- RedactingLogFilter ----------------------------------------------------------++_BOT_TOKEN = "987654321:AAFakeTokenForTestsOnly_abcdefghijklmnop" # noqa: S105 - a fake+++ "level", [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]+)+def test_the_redacting_filter_masks_every_level_and_the_logged_exception(+ caplog: pytest.LogCaptureFixture, level: int+) -> None:+ """A record's message, its arguments, and the traceback printed under it+ (the error and the cause it was raised from) all lose the token."""+ from jarvis.core.redact import redact_logger++ name = "jarvis.test.redact_probe_levels"+ logger = logging.getLogger(name)+ redact_logger(name)+ url = f"https://api.telegram.org/bot{_BOT_TOKEN}/getUpdates"+ try:+ try:+ raise ConnectionError(f"cannot reach {url}")+ except ConnectionError as cause:+ raise RuntimeError(f"The token `{_BOT_TOKEN}` was rejected by the server.") from cause+ except RuntimeError:+ with caplog.at_level(logging.DEBUG, logger=name):+ logger.log(level, "polling %s failed", url, exc_info=True, stack_info=True)++ assert len(caplog.records) == 1+ record = caplog.records[0]+ assert _BOT_TOKEN not in caplog.text+ assert _BOT_TOKEN not in record.getMessage()+ # No handler can format the original exception again.+ assert record.exc_info is None and _BOT_TOKEN not in (record.exc_text or "")+ assert "RuntimeError" in caplog.text and "ConnectionError" in caplog.text+++def test_the_redacting_filter_leaves_a_clean_exception_alone(+ caplog: pytest.LogCaptureFixture,+) -> None:+ from jarvis.core.redact import redact_logger++ name = "jarvis.test.redact_probe_clean"+ logger = logging.getLogger(name)+ redact_logger(name)+ try:+ raise ValueError("nothing secret here")+ except ValueError:+ with caplog.at_level(logging.DEBUG, logger=name):+ logger.exception("it failed")+ assert caplog.records[0].exc_info is not None # untouched: nothing to mask+ assert "nothing secret here" in caplog.text