Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
9 changes: 7 additions & 2 deletions kenny-agent/src/handlers/agent_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions kenny-server/kenny_server/event_categories.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion kenny-server/kenny_server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions kenny-server/kenny_server/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""

Expand Down
20 changes: 18 additions & 2 deletions kenny-server/kenny_server/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

from __future__ import annotations

import base64
import hashlib
import json
import logging
Expand Down Expand Up @@ -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)
Expand Down
25 changes: 23 additions & 2 deletions kenny-server/kenny_server/webui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down
49 changes: 49 additions & 0 deletions kenny-server/tests/test_dashboard_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
12 changes: 12 additions & 0 deletions kenny-server/tests/test_event_categories.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
Loading