From b4490274af26cd651060273d1e66207f724b5def Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:41:31 +0000 Subject: [PATCH 1/4] Ignore a non-list reliability.events when annotating snapshots `events` is a section extra, so a telemetry frame may carry any JSON value there. annotate_snapshots iterated whatever truthy value it found, so one host reporting a number or a boolean raised TypeError and GET /api/agent/{id}, /api/fleet/overview and /api/today answered 500 for the whole fleet until that host pushed a different snapshot. Found by crash fuzzing with a mock agent that mutates its snapshots. Only a list is collected now, matching the check the stamping loop below already makes. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNqpHNGk5hJzgn6CWt Signed-off-by: Claude --- kenny-server/kenny_server/event_categories.py | 5 +++-- kenny-server/tests/test_event_categories.py | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/kenny-server/kenny_server/event_categories.py b/kenny-server/kenny_server/event_categories.py index ec9d5c2a..be28a3ad 100644 --- a/kenny-server/kenny_server/event_categories.py +++ b/kenny-server/kenny_server/event_categories.py @@ -712,8 +712,9 @@ async def annotate_snapshots( groups: list[dict[str, Any]] = [] for snap in snapshots: rel = snap.get("reliability") if isinstance(snap, dict) else None - if isinstance(rel, dict): - groups.extend(e for e in (rel.get("events") or []) if isinstance(e, dict)) + events = rel.get("events") if isinstance(rel, dict) else None + if isinstance(events, list): + groups.extend(e for e in events if isinstance(e, dict)) if not groups: return factory = client_factory or default_client diff --git a/kenny-server/tests/test_event_categories.py b/kenny-server/tests/test_event_categories.py index 07d042f1..d1f486e8 100644 --- a/kenny-server/tests/test_event_categories.py +++ b/kenny-server/tests/test_event_categories.py @@ -215,6 +215,18 @@ def test_annotate_snapshots_no_events_is_noop(): assert snap["reliability"]["events"] == [] +@pytest.mark.parametrize("events", [3.7, 5, True, "text", {"a": 1}, None]) +def test_annotate_snapshots_ignores_events_that_are_not_a_list(events): + """`events` is a section extra, so a `telemetry` frame carries any JSON value + there. One host reporting a non-list must not raise: this runs on the fleet + overview, where it would take the page down for every host.""" + + odd = {"reliability": {"status": "ok", "summary": "", "events": events}} + good = {"reliability": {"status": "ok", "summary": "", "events": []}} + _run(ec.annotate_snapshots([odd, good], client_factory=lambda: _FakeClient("[]"))) + assert odd["reliability"]["events"] == events + + def test_annotate_snapshots_stamps_across_multiple_snapshots(monkeypatch): monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test") snap_a = {"reliability": {"status": "warn", "summary": "", "events": [ From 69348036cdcba953f175df741556005b6a9177d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:41:31 +0000 Subject: [PATCH 2/4] Check what an agent answers before storing it on the dashboard paths Found by crash fuzzing with a mock agent that answers tool calls with mutated results. Two results were stored unchecked and broke later reads: - POST /api/agent/{id}/refresh and the ticket-callback refresh stored a telemetry_collect result as a snapshot without the validation a pushed telemetry frame gets. A section that is not an object (`"win_update": -5`) then made GET /api/digest/preview answer 500. Both paths now run the result through protocol.parse_snapshot, the same map of section name to Section the frame uses, and do not store a result that fails it. - POST /api/agent/{id}/screenshot stored any `image_b64`, and GET on the same route base64-decodes the stored value, so a non-string or undecodable payload turned every later GET into a 500. ScreenshotStore.put now keeps only a string that decodes and reports whether it did; the route answers 502 for a rejected capture and the previous one stays. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNqpHNGk5hJzgn6CWt Signed-off-by: Claude --- kenny-server/kenny_server/main.py | 9 +++- kenny-server/kenny_server/protocol.py | 14 ++++++ kenny-server/kenny_server/tools.py | 20 ++++++++- kenny-server/kenny_server/webui/__init__.py | 25 ++++++++++- kenny-server/tests/test_dashboard_api.py | 49 +++++++++++++++++++++ 5 files changed, 112 insertions(+), 5 deletions(-) diff --git a/kenny-server/kenny_server/main.py b/kenny-server/kenny_server/main.py index 07878370..27d835fa 100644 --- a/kenny-server/kenny_server/main.py +++ b/kenny-server/kenny_server/main.py @@ -22,6 +22,7 @@ from functools import partial from typing import Any, AsyncIterator +from pydantic import ValidationError from fastmcp import FastMCP from starlette.applications import Starlette from starlette.middleware import Middleware @@ -50,6 +51,7 @@ from .oauth import build_oauth_routes from .oauthstore import OAuthStore from .policy import PolicyEngine, load_shell_allow_defaults +from .protocol import parse_snapshot from .registry import AgentRegistry from .reliability_suppression import SuppressionList from .store import ( @@ -867,7 +869,12 @@ async def _callback_refresh(host_id: str) -> bool: await call_log.record(host_id, "telemetry_collect", {}, ok=True, actor="system:callback") if not result: return False - await store.insert(host_id, datetime.now(timezone.utc).isoformat(), result) + try: + snapshot = parse_snapshot(result) + except ValidationError: + # Not a snapshot map: the push path would reject it, so it is not stored. + return False + await store.insert(host_id, datetime.now(timezone.utc).isoformat(), snapshot) return True ticket_callbacks = TicketCallbacks( diff --git a/kenny-server/kenny_server/protocol.py b/kenny-server/kenny_server/protocol.py index 31392673..b80c6549 100644 --- a/kenny-server/kenny_server/protocol.py +++ b/kenny-server/kenny_server/protocol.py @@ -244,6 +244,20 @@ def parse_frame(data: dict[str, Any] | str | bytes) -> Frame: return _FRAME_ADAPTER.validate_python(data) +_SNAPSHOT_ADAPTER: TypeAdapter[dict[str, Section]] = TypeAdapter(dict[str, Section]) + + +def parse_snapshot(data: Any) -> dict[str, dict[str, Any]]: + """Validate a snapshot map and return it as plain JSON-ready dicts. + + A ``telemetry`` frame's ``snapshot`` and a ``telemetry_collect`` result are the + same map of section name to section, so a snapshot that reaches the store by + either path is held to this one shape. Raises ``pydantic.ValidationError``. + """ + + return {k: v.model_dump() for k, v in _SNAPSHOT_ADAPTER.validate_python(data).items()} + + def dump_frame(model: BaseModel) -> dict[str, Any]: """Serialize a frame model into a JSON-ready dict (omitting unset/None).""" diff --git a/kenny-server/kenny_server/tools.py b/kenny-server/kenny_server/tools.py index de5af9cb..de2443f3 100644 --- a/kenny-server/kenny_server/tools.py +++ b/kenny-server/kenny_server/tools.py @@ -27,6 +27,7 @@ from __future__ import annotations +import base64 import hashlib import json import logging @@ -410,12 +411,27 @@ class ScreenshotStore: def __init__(self) -> None: self._latest: dict[str, dict[str, Any]] = {} - def put(self, agent_id: str, image_b64: str, fmt: str = "png") -> None: + def put(self, agent_id: str, image_b64: Any, fmt: Any = "png") -> bool: + """Keep ``image_b64`` as the agent's latest screenshot; ``False`` if it is not one. + + The payload is whatever the agent answered ``screen_capture`` with, so it is + checked here, where every writer passes: only a string that decodes as base64 + is kept, because the dashboard serves the stored value by decoding it. A + rejected payload leaves the previous screenshot in place. + """ + + if not isinstance(image_b64, str): + return False + try: + base64.b64decode(image_b64) + except ValueError: + return False self._latest[agent_id] = { "image_b64": image_b64, - "format": fmt, + "format": fmt if isinstance(fmt, str) else "png", "captured_at": datetime.now(timezone.utc).isoformat(), } + return True def get(self, agent_id: str) -> dict[str, Any] | None: return self._latest.get(agent_id) diff --git a/kenny-server/kenny_server/webui/__init__.py b/kenny-server/kenny_server/webui/__init__.py index 391e048a..52e4902c 100644 --- a/kenny-server/kenny_server/webui/__init__.py +++ b/kenny-server/kenny_server/webui/__init__.py @@ -18,6 +18,7 @@ from typing import Any from urllib.parse import quote, urlsplit +from pydantic import ValidationError from starlette.background import BackgroundTask from starlette.requests import Request from starlette.responses import FileResponse, JSONResponse, Response, StreamingResponse @@ -40,6 +41,7 @@ run_turn_events, ) from ..policy import PolicyEngine +from ..protocol import parse_snapshot from ..event_categories import annotate_snapshots from .. import findings, hardware_history, hardware_metrics from ..forecast import build_facts, deterministic_summary, forecast_events @@ -1027,7 +1029,22 @@ async def api_refresh(request: Request) -> JSONResponse: from datetime import datetime, timezone try: - await store.insert(agent_id, datetime.now(timezone.utc).isoformat(), result) + snapshot = parse_snapshot(result) + except ValidationError: + # A result that is not a snapshot map would be rejected as a pushed + # `telemetry` frame; storing it here would hand every reader a shape + # the push path guarantees they never see. + logger.warning("refresh of %s returned a malformed snapshot; not stored", agent_id) + return JSONResponse( + { + "ok": True, + "stored": False, + "warning": "collected, but the agent returned a malformed " + "snapshot; the panel shows the previous reading", + } + ) + try: + await store.insert(agent_id, datetime.now(timezone.utc).isoformat(), snapshot) stored = True except Exception: # noqa: BLE001 - see comment above logger.exception( @@ -1064,7 +1081,11 @@ async def api_capture(request: Request) -> JSONResponse: await call_log.record(agent_id, "screen_capture", {}, ok=False, error=message, actor=_actor_of(request)) return JSONResponse({"ok": False, "error": message}, status_code=502) if isinstance(result, dict) and "image_b64" in result: - screenshots.put(agent_id, result["image_b64"], result.get("format", "png")) + if not screenshots.put(agent_id, result["image_b64"], result.get("format", "png")): + return JSONResponse( + {"ok": False, "error": "agent returned an invalid screenshot"}, + status_code=502, + ) return JSONResponse({"ok": True}) async def api_remotehelp(request: Request) -> JSONResponse: diff --git a/kenny-server/tests/test_dashboard_api.py b/kenny-server/tests/test_dashboard_api.py index 093c0e06..7f67f112 100644 --- a/kenny-server/tests/test_dashboard_api.py +++ b/kenny-server/tests/test_dashboard_api.py @@ -540,6 +540,55 @@ def test_refresh_reports_stored_true_on_success(tmp_path): assert "warning" not in body +def test_refresh_does_not_store_a_result_the_push_path_would_reject(tmp_path) -> None: + """A `telemetry_collect` result is the same snapshot map a `telemetry` frame + carries. A section that is not an object fails that frame's validation, so it + must not reach the store through a refresh either: readers such as the digest + index into every stored section and answered 500 on one.""" + + app = build_app(db_path=str(tmp_path / "refresh-bad.sqlite")) + + async def _malformed(agent_id, tool, args, timeout_s=60): + return {"disk": {"status": "ok", "summary": ""}, "win_update": -5} + + app.state.tunnel.send_request = _malformed # type: ignore[method-assign] + + with TestClient(app) as c: + r = c.post("/api/agent/example-pc/refresh", headers=_bearer(app)) + assert r.status_code == 200 + body = r.json() + assert body["ok"] is True + assert body["stored"] is False + assert body["warning"] + assert c.portal.call(app.state.store.latest, "example-pc") is None + assert c.get("/api/digest/preview", headers=_bearer(app)).status_code == 200 + + +def test_capture_rejects_a_screenshot_the_dashboard_could_not_serve(tmp_path) -> None: + """`GET .../screenshot` serves the stored capture by base64-decoding it, so a + payload that does not decode is refused when it arrives and the previous + capture stays; it used to be stored and turn every later GET into a 500.""" + + app = build_app(db_path=str(tmp_path / "capture.sqlite")) + answers = iter([{"image_b64": "QUJD", "format": "png"}, {"image_b64": -1}, {"image_b64": "A"}]) + + async def _capture(agent_id, tool, args, timeout_s=30): + return next(answers) + + app.state.tunnel.send_request = _capture # type: ignore[method-assign] + + with TestClient(app) as c: + h = _bearer(app) + assert c.post("/api/agent/example-pc/screenshot", headers=h).json() == {"ok": True} + for _ in range(2): + r = c.post("/api/agent/example-pc/screenshot", headers=h) + assert r.status_code == 502 + assert r.json()["ok"] is False + shot = c.get("/api/agent/example-pc/screenshot", headers=h) + assert shot.status_code == 200 + assert shot.content == b"ABC" + + def test_about_reports_server_protocol_and_repo(tmp_path) -> None: """The identity the About dialog renders. From 36869996fcf3638866b1cfc8e0d8fd2907b05975 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:42:45 +0000 Subject: [PATCH 3/4] State in the contract that a telemetry_collect result is validated before storing The server holds a telemetry_collect result to the same snapshot map as a pushed telemetry frame before it stores one. The contract said the shape is the same; it now also says what happens to a result that is not. No frame or tool shape changes. The dashboard, tool and account references need no update for this branch: they describe neither route's response to a malformed agent answer, no tool or account capability is touched, and nothing a healthy agent sends is handled differently. [skip-doc-drift] Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNqpHNGk5hJzgn6CWt Signed-off-by: Claude --- docs/protocol.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/protocol.md b/docs/protocol.md index 3db55f1d..efda4475 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -399,6 +399,8 @@ without domain logic. A `telemetry_collect` **request** (see tool catalog) returns the *same* snapshot shape inside `response.result`, optionally restricted to `args.sections`. +The server stores such a result only if it validates as that map; a result that does +not is returned to the caller but never stored. ### `log` (agent → server, pushed) From 3ab1a2670b078001f159f1fb8a7650377a5f7e5c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:57:39 +0000 Subject: [PATCH 4/4] Keep the applet name when the agent_update test copies sleep wait_times_out_while_another_process_runs_target copied /bin/sleep to a file named kenny-wait-test- and ran the copy. The Linux CI job fails that test on every run that reaches it (also on an unrelated dependency PR): the child is gone before the wait looks for it. Where sleep is an applet of a multi-call binary, the binary picks the applet by the name it is run as, so the renamed copy exits at once. The copy now keeps the name `sleep` inside a private directory, which runs the same on a standalone sleep and on a multi-call one. Test-only; no agent behaviour changes. [skip-doc-drift] Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNqpHNGk5hJzgn6CWt Signed-off-by: Claude --- kenny-agent/src/handlers/agent_update.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/kenny-agent/src/handlers/agent_update.rs b/kenny-agent/src/handlers/agent_update.rs index 4773fff1..989e0c14 100644 --- a/kenny-agent/src/handlers/agent_update.rs +++ b/kenny-agent/src/handlers/agent_update.rs @@ -814,7 +814,12 @@ mod tests { if !src.exists() { return; // No `sleep` on this host; skip rather than fail. } - let target = std::env::temp_dir().join(format!("kenny-wait-test-{}", std::process::id())); + // The copy keeps the file name `sleep` inside a private directory: where + // `sleep` is an applet of a multi-call binary (uutils, busybox), the binary + // picks the applet by the name it is run as and exits at once under any other. + let dir = std::env::temp_dir().join(format!("kenny-wait-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create private dir"); + let target = dir.join("sleep"); std::fs::copy(src, &target).expect("copy sleep binary"); // Make the copy executable for hosts that don't preserve the mode bit. #[cfg(unix)] @@ -838,7 +843,7 @@ mod tests { let _ = child.kill(); let _ = child.wait(); - let _ = std::fs::remove_file(&target); + let _ = std::fs::remove_dir_all(&dir); assert!( !freed,