From 72fae9f69d9e647112d1b8dfc204b11137f88115 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:32:51 +0000 Subject: [PATCH 1/6] fix(tickets): treat an unbindable ticket number as a miss Discord's /close and /cancel take a free-text ticket reference. A digit string that int() parses but SQLite cannot bind as a 64-bit INTEGER ("9" * 40, or KEN-<40 digits>) raised OverflowError in TicketStore.get_by_number. The service loop logged it and the interaction was never answered. Such a number names no ticket, so get_by_number now returns None for it. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc --- kenny-server/kenny_server/ticketstore.py | 4 ++++ kenny-server/tests/test_discord_service.py | 5 +++++ kenny-server/tests/test_ticketstore.py | 3 +++ 3 files changed, 12 insertions(+) diff --git a/kenny-server/kenny_server/ticketstore.py b/kenny-server/kenny_server/ticketstore.py index 7ffe73ea..2de36f52 100644 --- a/kenny-server/kenny_server/ticketstore.py +++ b/kenny-server/kenny_server/ticketstore.py @@ -797,6 +797,10 @@ async def get(self, ticket_id: str) -> Ticket | None: async def get_by_number(self, number: int) -> Ticket | None: """Return one ticket by its display number, or None.""" + # A number outside SQLite's 64-bit INTEGER range names no ticket, and + # binding it would raise OverflowError instead of finding nothing. + if not -_SQLITE_MAX_INT - 1 <= number <= _SQLITE_MAX_INT: + return None async with self._conn.execute( f"SELECT {_TICKET_COLUMNS} FROM tickets WHERE number = ?", (number,) ) as cur: diff --git a/kenny-server/tests/test_discord_service.py b/kenny-server/tests/test_discord_service.py index 8e20e6dc..7924b9a1 100644 --- a/kenny-server/tests/test_discord_service.py +++ b/kenny-server/tests/test_discord_service.py @@ -1675,6 +1675,11 @@ async def test_close_ticket_with_a_unicode_digit_ref_is_a_plain_miss(world: Worl assert "could not find" in await service.close_ticket( discord_user_id=D_LENA, guild_id=GUILD, ticket_ref="9" * 5000 ) + # A number ``int()`` parses but SQLite cannot bind is a miss as well. + for ref in ("9" * 40, "KEN-" + "9" * 40): + assert "could not find" in await service.close_ticket( + discord_user_id=D_LENA, guild_id=GUILD, ticket_ref=ref + ) async def test_close_this_resolves_the_ticket_bound_to_the_calling_thread( diff --git a/kenny-server/tests/test_ticketstore.py b/kenny-server/tests/test_ticketstore.py index e9c7ad06..db2f649e 100644 --- a/kenny-server/tests/test_ticketstore.py +++ b/kenny-server/tests/test_ticketstore.py @@ -62,6 +62,9 @@ async def test_ticket_round_trips(tmp_path) -> None: fetched = await store.get(ticket.id) assert fetched == ticket assert await store.get_by_number(1) == ticket + # A number SQLite cannot bind names no ticket; it is a miss, not an error. + assert await store.get_by_number(2**63) is None + assert await store.get_by_number(-(2**63) - 1) is None assert await store.get("nope") is None patched = await store.update( From d40daaf89fb69bc0899cb920a12adaa6f8324e96 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:32:51 +0000 Subject: [PATCH 2/6] fix(toolloop): answer a server tool call without an id with bad_args select_agent, agent_health, agent_snapshot and agent_availability read args["id"] directly. The arguments are whatever the model sent, and a call without id raised KeyError. _execute_one only turns ToolError into a tool result, so the KeyError ended the turn: POST /api/chat answered 502 and the stream emitted an in-band error. The call is now a bad_args tool result the model can correct, and the turn continues. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc --- kenny-server/kenny_server/toolloop.py | 22 +++++++++++++---- kenny-server/tests/test_chat.py | 34 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/kenny-server/kenny_server/toolloop.py b/kenny-server/kenny_server/toolloop.py index bba51834..a101de51 100644 --- a/kenny-server/kenny_server/toolloop.py +++ b/kenny-server/kenny_server/toolloop.py @@ -1001,7 +1001,7 @@ async def run_server_tool( if tool == "list_agents": return await self._list_agents(session) if tool == "select_agent": - result = await self._select_agent(str(args["id"])) + result = await self._select_agent(_required_agent_id(args)) if session is not None: # The session's own selection is the only state this changes # (ADR-0038) — no shared registry slot is written, so concurrent @@ -1011,14 +1011,14 @@ async def run_server_tool( if tool == "fleet_overview": return await self._fleet_overview() if tool == "agent_health": - return await self._agent_health(str(args["id"])) + return await self._agent_health(_required_agent_id(args)) if tool == "agent_snapshot": return await self._agent_snapshot( - str(args["id"]), args.get("section"), withhold=withheld_sections(session) + _required_agent_id(args), args.get("section"), withhold=withheld_sections(session) ) if tool == "agent_availability": return await availability_summary( - str(args["id"]), + _required_agent_id(args), args.get("days"), registry=self.registry, store=self.store, @@ -1363,6 +1363,20 @@ async def _execute_one( return {"error": {"code": exc.code, "message": exc.message}}, True +def _required_agent_id(args: dict[str, Any]) -> str: + """The ``id`` argument of a server tool that names one agent. + + The arguments are whatever the model sent. A call without a usable ``id`` + is answered with ``bad_args`` so the model can correct it; it must not end + the turn. + """ + + agent_id = args.get("id") + if not isinstance(agent_id, str) or not agent_id: + raise ToolError("bad_args", "id is required and must be a string") + return agent_id + + def _tool_started_event( tool: str, args: dict[str, Any], agent_id: str | None, *, auto_run: bool ) -> dict[str, Any]: diff --git a/kenny-server/tests/test_chat.py b/kenny-server/tests/test_chat.py index 911cbe3e..b74c2fe8 100644 --- a/kenny-server/tests/test_chat.py +++ b/kenny-server/tests/test_chat.py @@ -799,6 +799,40 @@ async def test_run_capability_fails_closed_without_a_target( assert excinfo.value.code == "no_agent" +@pytest.mark.parametrize( + "tool", ["select_agent", "agent_health", "agent_snapshot", "agent_availability"] +) +@pytest.mark.parametrize("args", [{}, {"id": None}, {"id": 5}, {"id": ""}]) +async def test_server_tool_without_a_usable_id_is_a_tool_error_the_model_can_fix( + store: TelemetryStore, tool: str, args: dict[str, Any] +) -> None: + """The arguments are whatever the model sent. A missing ``id`` used to raise + ``KeyError`` out of the turn; it is a ``bad_args`` tool result instead, and + the turn goes on.""" + + executor, _registry, _tunnel = _executor(store) + client = FakeAnthropic( + [ + _Response([tool_use_block("tu1", tool, args)], "tool_use"), + _Response([text_block("recovered")], "end_turn"), + ] + ) + + result = await run_turn(FleetSession(id="s1"), "hi", executor=executor, client=client) + + assert result.done is True + assert result.assistant_text == "recovered" + fed_back = [ + b + for m in client.messages.calls[1]["messages"] + if isinstance(m.get("content"), list) + for b in m["content"] + if isinstance(b, dict) and b.get("type") == "tool_result" + ] + assert fed_back and fed_back[0]["is_error"] is True + assert json.loads(fed_back[0]["content"])["error"]["code"] == "bad_args" + + async def test_run_capability_rejects_non_numeric_timeout_s( store: TelemetryStore, ) -> None: From f7697181af8d87026cadda0d624a332bc9ea5d45 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:32:52 +0000 Subject: [PATCH 3/6] fix(server): refuse JSON bodies that carry a lone surrogate json.loads accepts a lone UTF-16 surrogate, as the escape "\ud800" or as its raw three-byte encoding. The string cannot be encoded as UTF-8, so the first SQLite bind that met it raised UnicodeEncodeError and the request answered 500 (POST /api/tickets, POST /api/users, POST /api/chat, and any other route that stores a body string). StorableJsonTextMiddleware sits inside the auth gate and answers such a body with 400 before a handler runs. It parses a body only when a cheap byte scan says a surrogate is possible, and leaves the MCP endpoint and form posts untouched. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc --- kenny-server/kenny_server/json_text.py | 117 ++++++++++++++++++ kenny-server/kenny_server/main.py | 5 +- .../tests/test_hostile_input_no_500.py | 49 ++++++++ 3 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 kenny-server/kenny_server/json_text.py diff --git a/kenny-server/kenny_server/json_text.py b/kenny-server/kenny_server/json_text.py new file mode 100644 index 00000000..d760d718 --- /dev/null +++ b/kenny-server/kenny_server/json_text.py @@ -0,0 +1,117 @@ +"""Refuse JSON request bodies whose text cannot be stored. + +JSON may carry a lone UTF-16 surrogate, as the escape ``"\\ud800"`` or as the +raw bytes of one, and Python's parser accepts both. Such a string cannot be +encoded as UTF-8, so the first SQLite bind, log line or outbound request that +meets it raises ``UnicodeEncodeError`` — after the handler may already have done +part of its work. :class:`StorableJsonTextMiddleware` answers those bodies with +``400`` before any handler runs, which keeps every route's own validation free +of the case. +""" + +from __future__ import annotations + +import json +import re + +from .urls import MCP_PATH + +# A body can only decode to a surrogate if it holds a ``\uD8xx``-``\uDFxx`` +# escape or the lead byte (0xED) of a raw three-byte surrogate encoding. Every +# other body is passed on without being parsed here. +_SURROGATE_HINT = re.compile(rb"\\u[dD][89a-fA-F]|\xed[\xa0-\xbf]") + +_BODY_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"}) +_FORM_TYPES = (b"application/x-www-form-urlencoded", b"multipart/form-data") + +_REJECTION = json.dumps( + {"error": "request body contains text that is not valid Unicode (a lone surrogate)"} +).encode("utf-8") + + +def has_unstorable_text(body: bytes) -> bool: + """True when ``body`` is JSON holding a string that cannot be UTF-8 encoded. + + A body that is not JSON at all is not this function's concern — the route + that reads it reports that itself — so it answers ``False``. + """ + + if not _SURROGATE_HINT.search(body): + return False + try: + parsed = json.loads(body) + except (ValueError, RecursionError): + return False + try: + json.dumps(parsed, ensure_ascii=False).encode("utf-8") + except UnicodeEncodeError: + return True + except (ValueError, RecursionError): + return False + return False + + +class StorableJsonTextMiddleware: + """Pure-ASGI gate: a JSON body with a lone surrogate gets ``400``. + + Only requests that can carry a JSON body to one of the server's own routes + are read here; the MCP endpoint, form posts and every other scope pass + through untouched. The body is buffered (each of those routes reads it whole + anyway) and replayed to the application unchanged. + """ + + def __init__(self, app) -> None: + self.app = app + + async def __call__(self, scope, receive, send) -> None: + if not self._applies(scope): + await self.app(scope, receive, send) + return + + chunks: list[bytes] = [] + while True: + message = await receive() + if message["type"] != "http.request": + # The client went away before the body was complete; there is + # nobody to answer. + return + chunks.append(message.get("body", b"")) + if not message.get("more_body", False): + break + body = b"".join(chunks) + + if has_unstorable_text(body): + await send( + { + "type": "http.response.start", + "status": 400, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(_REJECTION)).encode("ascii")), + ], + } + ) + await send({"type": "http.response.body", "body": _REJECTION}) + return + + replayed = False + + async def replay(): + nonlocal replayed + if not replayed: + replayed = True + return {"type": "http.request", "body": body, "more_body": False} + return await receive() + + await self.app(scope, replay, send) + + @staticmethod + def _applies(scope) -> bool: + if scope["type"] != "http" or scope.get("method") not in _BODY_METHODS: + return False + if scope.get("path", "").startswith(MCP_PATH): + return False + for name, value in scope.get("headers", ()): + if name == b"content-type": + return not value.lower().startswith(_FORM_TYPES) + return True diff --git a/kenny-server/kenny_server/main.py b/kenny-server/kenny_server/main.py index 07878370..5c760a6e 100644 --- a/kenny-server/kenny_server/main.py +++ b/kenny-server/kenny_server/main.py @@ -44,6 +44,7 @@ from .discord_service import SLASH_COMMANDS, DiscordService from .agent_updates import AgentUpdateTools, UpdateOffers, build_update_routes from .distribution import ShareLinks, build_download_routes +from .json_text import StorableJsonTextMiddleware from .keystore import KeyStore from .logging_config import StoreLogHandler, configure_logging, drain_log_queue from .notify import Notification, NotifierProvider @@ -1453,7 +1454,9 @@ async def lifespan(app: Starlette) -> AsyncIterator[None]: token=operator_tokens, user_store=user_store, oauth_store=oauth_store, - ) + ), + # Inside the auth gate, so only a request that may reach a route is read. + Middleware(StorableJsonTextMiddleware), ] app = Starlette(routes=routes, middleware=middleware, lifespan=lifespan) diff --git a/kenny-server/tests/test_hostile_input_no_500.py b/kenny-server/tests/test_hostile_input_no_500.py index cb447e8f..c1b28172 100644 --- a/kenny-server/tests/test_hostile_input_no_500.py +++ b/kenny-server/tests/test_hostile_input_no_500.py @@ -5,6 +5,8 @@ - A numeric path id beyond SQLite's 64-bit INTEGER range used to raise ``OverflowError`` at bind time; it names no row, so it is "not found". - ``/assets/`` used to raise ``ValueError`` from ``Path.resolve``. +- A JSON body holding a lone UTF-16 surrogate parses, but its text cannot be + encoded as UTF-8; it is refused before any handler binds it to SQLite. """ from __future__ import annotations @@ -88,3 +90,50 @@ def test_installer_download_survives_hostile_agent_id(client, agent_id, query) - disposition = r.headers.get("content-disposition", "") assert disposition.count('"') in (0, 2) assert "\r" not in disposition and "\n" not in disposition + + +_LONE_SURROGATE_BODIES = [ + ("POST", "/api/tickets", b'{"title": "x\\ud800", "summary": "s"}'), + ("POST", "/api/tickets", b'{"title": "x", "summary": "\\uDFFF tail"}'), + # The raw three-byte encoding of U+D800: json.loads decodes bytes leniently. + ("POST", "/api/tickets", b'{"title": "x\xed\xa0\x80", "summary": "s"}'), + ("POST", "/api/users", b'{"username": "u\\ud800", "password": "pw123456789", "role": "user"}'), + ("POST", "/api/chat", b'{"message": "hi \\ud800", "agent_id": "dev"}'), + ("PUT", "/api/me/theme", b'{"\\ud800": 1}'), +] + + +@pytest.mark.parametrize(("method", "path", "body"), _LONE_SURROGATE_BODIES) +def test_lone_surrogate_in_a_json_body_is_400(client, method, path, body) -> None: + r = client.request(method, path, content=body, headers={"content-type": "application/json"}) + assert r.status_code == 400 + assert "surrogate" in r.json()["error"] + + +def test_lone_surrogate_is_refused_before_anything_is_stored(client) -> None: + body = b'{"title": "fine", "summary": "s\\ud800"}' + assert client.post("/api/tickets", content=body).status_code == 400 + assert client.get("/api/tickets").json()["tickets"] == [] + + +def test_paired_surrogates_and_plain_unicode_still_pass(client) -> None: + """A surrogate *pair* is an ordinary character; so is text whose UTF-8 + happens to contain the byte the cheap pre-check looks for.""" + + body = b'{"title": "smile \\ud83d\\ude00", "summary": "\xed\x95\x9c\xea\xb8\x80 \xf0\x9f\x98\x80"}' + r = client.post("/api/tickets", content=body, headers={"content-type": "application/json"}) + assert r.status_code == 201, r.text + assert r.json()["title"] == "smile \U0001f600" + assert r.json()["summary"] == "\ud55c\uae00 \U0001f600" + + +def test_a_form_post_is_not_read_as_json(client) -> None: + """The login form is not JSON; the surrogate check leaves it to its route.""" + + r = client.post( + "/login", + content=b"username=%5Cud800&password=x", + headers={"content-type": "application/x-www-form-urlencoded"}, + follow_redirects=False, + ) + assert r.status_code < 500 From 69e06ef5d1754d3ad511da98b331b856108ee029 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:46:34 +0000 Subject: [PATCH 4/6] fix(agent): read one lastlog record per account, not the whole file /var/log/lastlog is sparse and as long as the highest uid that ever logged in: one login by uid 5,000,000 makes it 1.4 GiB. The Linux local_accounts collector read it whole on every snapshot to look at four bytes per account, so resident memory grew by the file's apparent size, up to an OOM kill on a host with directory-backed uids. The collector now opens the file and reads the four bytes of each account's record by position. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc --- .../telemetry/collectors/local_accounts.rs | 93 +++++++++++++++---- 1 file changed, 73 insertions(+), 20 deletions(-) diff --git a/kenny-agent/src/telemetry/collectors/local_accounts.rs b/kenny-agent/src/telemetry/collectors/local_accounts.rs index 0c2a9d2f..7f35ec3a 100644 --- a/kenny-agent/src/telemetry/collectors/local_accounts.rs +++ b/kenny-agent/src/telemetry/collectors/local_accounts.rs @@ -1088,17 +1088,31 @@ pub mod linux_impl { Path::new("/run/systemd/seats").exists() || Path::new("/run/systemd/sessions").exists() } - /// The last-login timestamp for `uid`, from the fixed-record `/var/log/lastlog`. + /// Size of one `/var/log/lastlog` record: `int32 time`, `char line[32]`, + /// `char host[256]`. Records are indexed by uid. + const LASTLOG_RECORD: u64 = 292; + + /// The login-time field of `uid`'s record in an open `/var/log/lastlog`. + /// + /// Reads the four bytes it needs and nothing else. The file is sparse and as + /// long as the highest uid that ever logged in — over a gigabyte on a host + /// with directory-backed uids in the millions — so it is never read whole. + /// `None` when the record lies past the end of the file. + fn lastlog_secs(lastlog: &impl std::os::unix::fs::FileExt, uid: u32) -> Option { + let mut secs = [0u8; 4]; + lastlog + .read_exact_at(&mut secs, u64::from(uid) * LASTLOG_RECORD) + .ok()?; + Some(u32::from_ne_bytes(secs)) + } + + /// The last-login timestamp from a `lastlog` login-time field. /// - /// Records are 292 bytes indexed by uid: `int32 time`, `char line[32]`, - /// `char host[256]`. Best-effort — distros migrating to `lastlog2` have no such - /// file, and a never-logged-in account has a zero record. Reporting `null` in - /// both cases matches what Windows does for an account that never signed in. - fn last_logon(lastlog: &[u8], uid: u32) -> Option { - const RECORD: usize = 292; - let start = (uid as usize).checked_mul(RECORD)?; - let secs = lastlog.get(start..start + 4)?; - let secs = i64::from(u32::from_ne_bytes([secs[0], secs[1], secs[2], secs[3]])); + /// Best-effort — distros migrating to `lastlog2` have no such file, and a + /// never-logged-in account has a zero record. Reporting `null` in both cases + /// matches what Windows does for an account that never signed in. + fn last_logon(secs: Option) -> Option { + let secs = i64::from(secs?); if secs == 0 { return None; } @@ -1118,7 +1132,8 @@ pub mod linux_impl { pub sudoers_users: &'a [String], pub sudoers_groups: &'a [String], pub ssh_denied: &'a [String], - pub lastlog: &'a [u8], + /// The `lastlog` login-time field for a uid, `None` when there is no record. + pub lastlog: &'a dyn Fn(u32) -> Option, pub today_days: i64, } @@ -1205,7 +1220,7 @@ pub mod linux_impl { // blank-password crit on every unprivileged dev build. password_required: facts.map(|f| f.password_required).unwrap_or(true), password_last_set: facts.and_then(|f| f.password_last_set.clone()), - last_logon: last_logon(src.lastlog, uid), + last_logon: last_logon((src.lastlog)(uid)), // root is the built-in, undeletable administrator — the same fact // `builtin_admin` records for Windows RID 500, so the portable // guard protects it with no Linux-specific rule. @@ -1367,7 +1382,8 @@ pub mod linux_impl { }; let group = std::fs::read_to_string("/etc/group").unwrap_or_default(); let shadow = std::fs::read_to_string("/etc/shadow").ok(); - let lastlog = std::fs::read("/var/log/lastlog").unwrap_or_default(); + let lastlog = std::fs::File::open("/var/log/lastlog").ok(); + let lastlog = |uid: u32| lastlog.as_ref().and_then(|file| lastlog_secs(file, uid)); let ssh_denied = std::fs::read_to_string(SSHD_DROPIN) .map(|text| parse_deny_users(&text)) .unwrap_or_default(); @@ -1441,7 +1457,7 @@ devs:x:1100:deploy sudoers_users: &[], sudoers_groups: &[], ssh_denied: denied, - lastlog: &[], + lastlog: &|_| None, today_days: 20_500, } } @@ -1601,16 +1617,53 @@ kid:$6$a$b:20000:0:99999:7::1: assert!(!sshd_includes_dropin_dir("Port 22\n")); } + /// An empty scratch file, already unlinked so nothing is left behind. + fn scratch_lastlog(tag: &str) -> std::fs::File { + let path = + std::env::temp_dir().join(format!("kenny-lastlog-{tag}-{}", std::process::id())); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&path) + .unwrap(); + std::fs::remove_file(&path).unwrap(); + file + } + #[test] fn lastlog_reads_a_record_and_tolerates_a_missing_file() { - let mut buf = vec![0u8; 292 * 2]; - buf[292..296].copy_from_slice(&1_700_000_000u32.to_ne_bytes()); - assert_eq!(last_logon(&buf, 1).as_deref(), Some("2023-11-14T22:13:20Z")); + use std::os::unix::fs::FileExt as _; + + let file = scratch_lastlog("record"); + file.set_len(292 * 2).unwrap(); + file.write_all_at(&1_700_000_000u32.to_ne_bytes(), 292) + .unwrap(); + assert_eq!( + last_logon(lastlog_secs(&file, 1)).as_deref(), + Some("2023-11-14T22:13:20Z") + ); // uid 0 has a zero record: never logged in, not "logged in at epoch". - assert_eq!(last_logon(&buf, 0), None); + assert_eq!(last_logon(lastlog_secs(&file, 0)), None); // Past the end of the file, or no file at all. - assert_eq!(last_logon(&buf, 9999), None); - assert_eq!(last_logon(&[], 0), None); + assert_eq!(lastlog_secs(&file, 9999), None); + assert_eq!(last_logon(None), None); + } + + #[test] + fn lastlog_lookup_reads_one_record_of_a_file_sized_by_the_highest_uid() { + use std::os::unix::fs::FileExt as _; + + // One login by uid 5,000,000 makes the sparse file 1.4 GiB long. + let uid = 5_000_000u32; + let file = scratch_lastlog("sparse"); + file.set_len((u64::from(uid) + 1) * 292).unwrap(); + file.write_all_at(&1_700_000_000u32.to_ne_bytes(), u64::from(uid) * 292) + .unwrap(); + assert_eq!(lastlog_secs(&file, uid), Some(1_700_000_000)); + assert_eq!(lastlog_secs(&file, uid - 1), Some(0)); + assert_eq!(lastlog_secs(&file, u32::MAX), None); } } } From 65155d304767be30943cd86a3b11a58793b030ee Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:46:34 +0000 Subject: [PATCH 5/6] fix(agent): cap the profile files the browser_extensions collector reads manifest.json, _locales/*/messages.json and Firefox's extensions.json live in user profiles, so any local user chooses their size, and the agent read them whole as LocalSystem on every snapshot. A sparse 1.5 GiB manifest cost the agent 1.5 GiB. The errors list also grew by one entry per broken manifest, with no limit. Files over 16 MiB are skipped like unreadable ones, at most one byte past the cap is ever held, and the errors list stops at 50 entries. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc --- .../collectors/browser_extensions.rs | 93 ++++++++++++++++++- 1 file changed, 88 insertions(+), 5 deletions(-) diff --git a/kenny-agent/src/telemetry/collectors/browser_extensions.rs b/kenny-agent/src/telemetry/collectors/browser_extensions.rs index 9d778af1..9f265372 100644 --- a/kenny-agent/src/telemetry/collectors/browser_extensions.rs +++ b/kenny-agent/src/telemetry/collectors/browser_extensions.rs @@ -53,6 +53,42 @@ pub mod core { /// Contract cap on the `extensions` list. pub const MAX_EXTENSIONS: usize = 200; + /// Largest manifest, locale catalogue or Firefox `extensions.json` the + /// collector reads. These files sit in user profiles, so any local user + /// chooses their size; real ones stay far below this. + pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; + + /// Cap on the `errors` list — one entry per unreadable file would otherwise + /// let a user profile grow the section without bound. + pub const MAX_ERRORS: usize = 50; + + /// Read a profile file as text, refusing one larger than [`MAX_FILE_BYTES`]. + /// + /// At most one byte past the cap is ever held, whatever the file claims + /// about its size. + pub fn read_text(path: &Path) -> std::io::Result { + use std::io::Read as _; + + let mut text = String::new(); + std::fs::File::open(path)? + .take(MAX_FILE_BYTES + 1) + .read_to_string(&mut text)?; + if text.len() as u64 > MAX_FILE_BYTES { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "file too large", + )); + } + Ok(text) + } + + /// Record a per-file problem, up to [`MAX_ERRORS`] of them. + pub fn note_error(errors: &mut Vec, message: String) { + if errors.len() < MAX_ERRORS { + errors.push(message); + } + } + /// One installed extension, already stripped of any per-user attribution. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Extension { @@ -199,11 +235,14 @@ pub mod core { versions.sort(); for vdir in versions.iter().rev() { let manifest_path = vdir.join("manifest.json"); - let Ok(text) = std::fs::read_to_string(&manifest_path) else { + let Ok(text) = read_text(&manifest_path) else { continue; }; let Some(manifest) = parse_chromium_manifest(&text) else { - errors.push(format!("{}: invalid manifest", manifest_path.display())); + note_error( + errors, + format!("{}: invalid manifest", manifest_path.display()), + ); continue; }; let name = resolve_chromium_name(&manifest, vdir, &id); @@ -241,7 +280,7 @@ pub mod core { .join("_locales") .join(&locale) .join("messages.json"); - if let Ok(text) = std::fs::read_to_string(&path) { + if let Ok(text) = read_text(&path) { if let Some(name) = resolve_msg(&text, key) { return name; } @@ -373,6 +412,50 @@ pub mod core { assert!(parse_firefox_extensions("garbage").is_empty()); } + /// A profile file is as large as its owner makes it; the scan must not + /// hold more than the cap, and must not report one error per planted file. + #[test] + fn scan_skips_an_oversized_manifest_and_caps_the_error_list() { + let dir = std::env::temp_dir().join(format!( + "kenny-brext-{}-{}", + std::process::id(), + line!() + )); + let ext_root = dir.join("Extensions"); + // A sparse 1 GiB manifest: skipped like an unreadable one. + let huge = ext_root.join("aaaahugeid").join("1.0_0"); + std::fs::create_dir_all(&huge).unwrap(); + let manifest = huge.join("manifest.json"); + std::fs::File::create(&manifest) + .unwrap() + .set_len(1 << 30) + .unwrap(); + assert_eq!( + read_text(&manifest).unwrap_err().kind(), + std::io::ErrorKind::InvalidData + ); + for i in 0..MAX_ERRORS + 20 { + let broken = ext_root.join(format!("broken{i:04}")).join("1.0_0"); + std::fs::create_dir_all(&broken).unwrap(); + std::fs::write(broken.join("manifest.json"), "not json").unwrap(); + } + let good = ext_root.join("zzzzgoodid").join("1.0_0"); + std::fs::create_dir_all(&good).unwrap(); + std::fs::write( + good.join("manifest.json"), + r#"{ "name": "Good", "version": "1.0" }"#, + ) + .unwrap(); + + let mut errors = Vec::new(); + let exts = scan_chromium_extensions(&ext_root, "chrome", &mut errors); + std::fs::remove_dir_all(&dir).ok(); + + assert_eq!(exts.len(), 1); + assert_eq!(exts[0].name, "Good"); + assert_eq!(errors.len(), MAX_ERRORS); + } + /// Fabricate a Chromium `Extensions` tree and scan it — exercises version /// selection, `__MSG_*__` resolution, and error recording on Linux CI. #[test] @@ -512,12 +595,12 @@ mod windows_impl { if !file.is_file() { continue; } - match std::fs::read_to_string(&file) { + match core::read_text(&file) { Ok(text) => { profiles_read += 1; extensions.extend(core::parse_firefox_extensions(&text)); } - Err(e) => errors.push(format!("{}: {e}", file.display())), + Err(e) => core::note_error(&mut errors, format!("{}: {e}", file.display())), } } } From 6221eca01db494e37f150c03164ffa515304f532 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:57:39 +0000 Subject: [PATCH 6/6] 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 (cherry picked from commit 3ab1a2670b078001f159f1fb8a7650377a5f7e5c) --- 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,