From bfd6f8e0e2c66bd5af960d1c7761798d4c75b88d Mon Sep 17 00:00:00 2001 From: OAra Labs Date: Fri, 13 Nov 2026 19:13:20 -0500 Subject: [PATCH 1/5] test(approvals): red: approving a critical request needs its digest Co-Authored-By: Claude Opus 5.5 --- tests/test_critical_approve_needs_digest.py | 197 ++++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 tests/test_critical_approve_needs_digest.py diff --git a/tests/test_critical_approve_needs_digest.py b/tests/test_critical_approve_needs_digest.py new file mode 100644 index 00000000..732d066f --- /dev/null +++ b/tests/test_critical_approve_needs_digest.py @@ -0,0 +1,197 @@ +"""Approving a CRITICAL request needs the request's digest (Beacon iOS item 3, Will's suggestion, 2026-11-13). + +The ``critical`` flag (#917) keeps a request off the lock screen: its push has no Approve button. The daemon now +enforces part of that itself. Every served request carries ``digest``, a sha256 over exactly what the client is +shown (request id, tool, description, arguments view, created and expiry times, the critical flag). It is served +wherever the request is served (``GET /api/approvals``, the ``approval_pending`` frame) and NEVER in a push. A +critical request is approved only with ``{"digest": }`` in the body: missing is ``409 digest_required``, +different is ``409 digest_mismatch``, and nothing is approved either way. A request that is not critical approves +as before, and denying never needs it. + +What it proves, stated plainly: the client fetched this exact request. It does not prove a person read it in the +app (a notification extension that fetches holds the digest too); keeping critical requests off the lock screen +still rests on the client not offering Approve there. +""" + +from __future__ import annotations + +import asyncio +import secrets +import types + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient # noqa: E402 + +from prometheus.config.device_store import DeviceStore # noqa: E402 +from prometheus.permissions.approval_queue import ( # noqa: E402 + ApprovalQueue, + ApprovalResult, + PendingAction, +) + +GLOBAL = "digest-test-" + secrets.token_hex(8) + + +class _Gate: + def add_grant(self, *a, **kw): + return None + + +@pytest.fixture +def d(tmp_path): + from prometheus.web.server import create_app + + app = create_app({"web": {"api_token": GLOBAL}}, device_store=DeviceStore(tmp_path / "devices.db")) + queue = ApprovalQueue(security_gate=_Gate(), telegram_adapter=None) + app.state.approval_queue = queue + critical = PendingAction(request_id="c0c0c001", tool_name="bash", description="rm -rf build", + session_id="web:s1", arguments={"command": "rm -rf build"}, + critical_matches=("command:rm -rf",)) + plain = PendingAction(request_id="c0c0c002", tool_name="bash", description="ls", session_id="web:s1", + arguments={"command": "ls"}) + for a in (critical, plain): + queue._register(a) + client = TestClient(app, client=("127.0.0.1", 50123)) + return client, queue, critical, plain + + +H = {"Authorization": f"Bearer {GLOBAL}"} + + +def _served(client, rid): + rows = client.get("/api/approvals", headers=H).json() + rows = rows.get("pending", rows) if isinstance(rows, dict) else rows + return next(r for r in rows if r["request_id"] == rid) + + +def test_every_served_request_carries_a_digest(d): + client, queue, critical, plain = d + c, p = _served(client, critical.request_id), _served(client, plain.request_id) + assert c["critical"] is True and p["critical"] is False + for row in (c, p): + assert isinstance(row["digest"], str) and len(row["digest"]) == 64 + int(row["digest"], 16) + assert c["digest"] != p["digest"] + + +def test_a_critical_approve_without_the_digest_answers_nothing(d): + client, queue, critical, _ = d + r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json={"scope": "once"}) + assert r.status_code == 409 and r.json()["error"] == "digest_required" + assert critical._result == ApprovalResult.TIMEOUT and critical.request_id in queue.pending + + +@pytest.mark.parametrize("wrong", ["", "0" * 64, "not-hex", 7, None]) +def test_a_critical_approve_with_another_digest_answers_nothing(d, wrong): + client, queue, critical, plain = d + body = {"scope": "once", "digest": wrong} + r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json=body) + assert r.status_code == 409 and r.json()["error"] in ("digest_required", "digest_mismatch") + assert critical._result == ApprovalResult.TIMEOUT + + +def test_another_requests_digest_is_not_this_ones(d): + client, queue, critical, plain = d + body = {"scope": "once", "digest": _served(client, plain.request_id)["digest"]} + r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json=body) + assert r.status_code == 409 and r.json()["error"] == "digest_mismatch" + assert critical._result == ApprovalResult.TIMEOUT + + +def test_a_critical_approve_with_the_served_digest_approves_it(d): + client, queue, critical, _ = d + body = {"scope": "once", "digest": _served(client, critical.request_id)["digest"]} + r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json=body) + assert r.status_code == 200 and r.json()["ok"] is True, r.text + assert critical._result == ApprovalResult.APPROVED + + +def test_a_request_that_is_not_critical_approves_as_before(d): + client, queue, _, plain = d + r = client.post(f"/api/approvals/{plain.request_id}/approve", headers=H, json={"scope": "once"}) + assert r.status_code == 200 and plain._result == ApprovalResult.APPROVED + + +def test_denying_a_critical_request_never_needs_it(d): + client, queue, critical, _ = d + r = client.post(f"/api/approvals/{critical.request_id}/deny", headers=H) + assert r.status_code == 200 and critical._result == ApprovalResult.DENIED + + +def test_approve_all_never_approves_a_critical_request(d): + """Until the REST route takes only single ids, `all` is refused while a critical request is pending: a + critical request is approved one at a time, with its digest.""" + client, queue, critical, plain = d + r = client.post("/api/approvals/all/approve", headers=H, json={"scope": "once"}) + assert r.status_code == 409 and r.json()["error"] == "digest_required" + assert critical._result == ApprovalResult.TIMEOUT and plain._result == ApprovalResult.TIMEOUT + + +def test_the_digest_is_the_same_in_the_list_and_the_frame_and_never_in_a_push(): + from prometheus.push.apns import SendResult + from prometheus.push.dispatcher import PushDispatcher + + q = ApprovalQueue(security_gate=_Gate(), telegram_adapter=None) + signals: list = [] + + class _Bus: + async def emit(self, signal): + signals.append(signal) + + q.signal_bus = _Bus() + + seen: dict = {} + + async def go(): + waiter = asyncio.create_task(q.request_approval("bash", "rm -rf build", arguments={"command": "rm -rf b"})) + for _ in range(50): + await asyncio.sleep(0) + if signals: + break + action = q.pending[signals[-1].payload["request_id"]] + seen.update(served=q.serialize_pending(action)["digest"], direct=q.digest(action)) + waiter.cancel() + + asyncio.run(go()) + frame = signals[-1].payload + assert frame["digest"] == seen["served"] == seen["direct"] + + sent: list[dict] = [] + + class _Sender: + async def send(self, **kwargs): + sent.append(kwargs) + return SendResult(outcome="ok", status=200) + + class _Store: + def push_targets(self): + return [types.SimpleNamespace(id="d1", apns_token="tok", environment="sandbox", bundle_id="", + push_failures=0)] + + def owner_device_ids(self): + return {"d1"} + + def approval_push_targets(self, *, desktop): + return self.push_targets() + + asyncio.run(PushDispatcher(_Store(), _Sender(), bridge=None).on_signal( + types.SimpleNamespace(kind="approval_pending", payload=frame, source="test"))) + assert sent and all(frame["digest"] not in str(s["payload"]) for s in sent) + + +def test_the_digest_does_not_change_while_the_request_waits(d): + client, queue, critical, _ = d + first = _served(client, critical.request_id)["digest"] + queue.critical_rules = None # nothing the digest covers depends on these + assert _served(client, critical.request_id)["digest"] == first + + +def test_server_capabilities_lists_approval_digest(): + from prometheus.web.ws_server import WebSocketBridge + + bridge = WebSocketBridge.__new__(WebSocketBridge) + bridge.config = {} + assert "approval_digest" in bridge._server_capabilities() From 53aaa5ce50181912a9ac3dbf6eeb46ef250b4035 Mon Sep 17 00:00:00 2001 From: OAra Labs Date: Fri, 13 Nov 2026 19:18:11 -0500 Subject: [PATCH 2/5] feat(approvals): approving a critical request needs its digest Every served request carries digest, a sha256 over what the client is shown (id, tool, description, arguments view, created/expiry, critical), never in a push. The REST approve of a critical request needs it: none is 409 digest_required, another 409 digest_mismatch, nothing approved. It is the last check, after every refusal about who may answer. 'all' is refused while a critical request it would approve is pending. Two tests send the served digest on purpose (a desktop prompt and a hold lift are critical), so they still prove the person checks with a valid digest. server_capabilities lists approval_digest. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/guide/api.md | 4 +- src/prometheus/permissions/approval_queue.py | 30 +++++++++++++++ src/prometheus/web/server.py | 40 ++++++++++++++++++++ src/prometheus/web/ws_server.py | 2 + tests/test_computer_door.py | 3 +- tests/test_device_hold_needs_a_person.py | 6 ++- 7 files changed, 81 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a99b283c..62f5bee0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Notable changes in each release, newest first. Releases before 0.9.7 are describ ## Unreleased +- Approvals: approving a critical request needs its digest. Every served approval request (`GET /api/approvals`, the `approval_pending` frame) carries `digest`, a sha256 over what the client is shown, and never in a push. `POST /api/approvals/{id}/approve` on a critical request without it answers `409 digest_required`, with another `409 digest_mismatch`, and approves nothing; `all` is refused while a critical request it would approve is pending. It proves the client fetched that exact request, not that a person read it. Other requests, and denying, are unchanged. `server_capabilities` lists `approval_digest`. - Approvals: every serialized approval request (`GET /api/approvals`, the `approval_pending` frame, the push) now says `critical`: whether it must be answered in the app rather than from a notification. Built in: desktop prompts, lifting a device's hold, arguments cut or masked for display, and a description over 600 characters or 8 lines. On top of that, three owner-editable lists, `push.critical_tools`, `push.critical_commands` and `push.critical_paths`, whose defaults cover deletes, `git push`, commands and tools that send or spend, and changes to devices, permissions or the agent's own configuration (leave a key out for the default, `[]` for none). A critical request's push has no category, so the notification offers no Approve, and carries `"critical": true`. The `subscribed` ack lists `approval_critical` in `server_capabilities`. This decides only where a request is answered, not whether: the lists are best effort and are not a security guard (every request already needs a person). Classifying never blocks or fails a request, and on any error the request is critical. - Push: an approval push now reaches owner devices only, and, for a desktop prompt (whose push carries no content), also the devices marked for computer use, which are the ones that may answer it. It went to every registered device with a push registration, scoped devices included, which see only their own sessions everywhere else and cannot approve. A device store that cannot name owner devices sends no approval push. Other pushes are unchanged. - Docs: `docs/reference/pairing-join-requests.md` is the reference for how a new device asks to join and how the owner lets it in: the routes and who may call them, every request and response field, the statuses, the expiry and rate limits, the sealed token, the operator's WebSocket frames and the owner code (the explicit, single-use grant that makes an owner device). It is written from the code and pinned to it by `tests/test_pairing_reference.py`. No behaviour changes. diff --git a/docs/guide/api.md b/docs/guide/api.md index c4fd9c88..896e99ab 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -237,8 +237,8 @@ Artifacts are **content-addressed**: ids are a sha256 prefix of the file bytes, | Method | Path | Purpose | |---|---|---| -| GET | `/api/approvals` | Poll pending approval requests. Each carries `critical`: `true` means answer it in the app, never from a notification (its push has no Approve). Rules: `permissions/critical.py`, owner lists `push.critical_*`. A nudge about where to answer, not a security guard: every request already needs a person, and a request judged ordinary is still read and approved by one | -| POST | `/api/approvals/{request_id}/approve` | Approve a request | +| GET | `/api/approvals` | Poll pending approval requests. Each carries `critical`: `true` means answer it in the app, never from a notification (its push has no Approve). Rules: `permissions/critical.py`, owner lists `push.critical_*`. A nudge about where to answer, not a security guard: every request already needs a person, and a request judged ordinary is still read and approved by one. Each also carries `digest`: a sha256 over what the client is shown (id, tool, description, arguments view, created and expiry times, the critical flag), served with the request and never in a push | +| POST | `/api/approvals/{request_id}/approve` | Approve a request. Body `{scope?, digest?}`. A **critical** request is approved only with the `digest` it was served (`GET /api/approvals`, the `approval_pending` frame): none is `409 digest_required`, another is `409 digest_mismatch`, and nothing is approved. That proves the client fetched this exact request, not that a person read it in the app. `all` is refused (`409 digest_required`) while a critical request it would approve is pending. Other requests need no digest. `server_capabilities` lists `approval_digest` | | POST | `/api/approvals/{request_id}/deny` | Deny a request | **A request that has ended cannot be answered.** Approving or denying a request that is no longer pending acts on nothing and is **410** `{"ok": false, "error": "no_longer_active", "resolution", "detail", ...}` (the approve route's usual `remembered`, `grant_id`, `message` and `skipped` keys are there too). `resolution` says how it ended: `withdrawn` (with the reason in `detail`), `approved`, `denied`, `expired`, or `null` when this daemon has no record of it (the queue is in memory, so a restart ends every request). A scoped device still gets 404 for a request that is not its own conversation's. `all` is not a request id. diff --git a/src/prometheus/permissions/approval_queue.py b/src/prometheus/permissions/approval_queue.py index 11b02677..a6bc1541 100644 --- a/src/prometheus/permissions/approval_queue.py +++ b/src/prometheus/permissions/approval_queue.py @@ -9,6 +9,8 @@ import asyncio import contextlib +import hashlib +import json import logging import time from collections import OrderedDict @@ -556,6 +558,9 @@ def serialize_pending(self, action: PendingAction) -> dict: # Answer in the app, never from a notification (permissions/critical.py). Computed HERE, once, so the # REST list, the approval_pending frame and the push cannot disagree. "critical": is_critical(action), + # What approving a critical request must echo back (``digest``). The push builds its own narrow body + # and never carries it. + "digest": self.digest(action), # Already redacted and truncated (see PendingAction.arguments). # None means "this call had no arguments worth showing", which is # different from {} and Beacon may render the difference. @@ -608,6 +613,28 @@ def timeout_seconds(self) -> float: """ return self._timeout + def digest(self, action: PendingAction) -> str: + """sha256 over exactly what a client is shown of *action*: its id, tool, description, arguments view, + created and expiry times and critical flag (Beacon iOS item 3). + + Served with the request wherever it is served (``serialize_pending``) and never in a push, so a client holds + it only by fetching the request. Approving a CRITICAL request needs it (the REST approve route): that proves + the client fetched this exact request, not that a person read it in the app. The derived ``extents`` are + left out on purpose: they can change with the grants while the request waits, and nothing approved depends + on the client having seen them. + """ + shown = { + "request_id": action.request_id, + "tool_name": action.tool_name, + "description": action.description, + "arguments": action.arguments, + "created_at": action.created_at, + "expires_at": self.expires_at(action), + "critical": is_critical(action), + } + canonical = json.dumps(shown, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + def expires_at(self, action: PendingAction) -> float: """Epoch seconds at which this request's window closes. @@ -1114,6 +1141,9 @@ def serialize_pending(self, action: PendingAction) -> dict: def expires_at(self, action: PendingAction) -> float: return self._for(action).expires_at(action) + def digest(self, action: PendingAction) -> str: + return self._for(action).digest(action) + async def approve(self, request_id: str, *, by: Approver, scope: str | None = None, grant=None) -> bool: owner = self.owner_of(request_id) diff --git a/src/prometheus/web/server.py b/src/prometheus/web/server.py index dabfcda5..a73d08bc 100644 --- a/src/prometheus/web/server.py +++ b/src/prometheus/web/server.py @@ -5318,6 +5318,12 @@ async def approve_action( if refusal is not None: return refusal + # A CRITICAL request is approved only with its digest (Beacon iOS item 3), which is served with the request + # and never in a push: the client fetched exactly this request. Last, so every refusal about WHO may answer + # is said first; never through "all". + if (refusal := _digest_refusal(queue, request_id, _desk, body)) is not None: + return refusal + arg_text = request_id if scope == "once" else f"{scope} {request_id}" # STRUCTURED, NOT INFERRED FROM THE PROSE. This was # `ok = not text.startswith("No pending request")`, which reported @@ -5347,6 +5353,40 @@ async def approve_action( "skipped": outcome.skipped, } + def _digest_refusal(queue: Any, request_id: str, action: Any, body: dict | None) -> JSONResponse | None: + """409 when approving a critical request without its digest (or with another), else None. + + ``digest_required``: no digest, or approving ``all`` while a critical request it would approve is pending + (``all`` already leaves desktop, worker and hold requests alone; any other critical request is approved on + its own, with its digest). ``digest_mismatch``: a digest that is not this request's. Compared in constant + time. A request that is not critical needs none; denying never does. + """ + import hmac + + from prometheus.permissions.approval_queue import is_desktop_request, is_hold_request, is_worker_request + from prometheus.permissions.critical import is_critical + + if request_id == "all": + pending = list((getattr(queue, "pending", {}) or {}).values()) + left_alone = (is_desktop_request, is_worker_request, is_hold_request) + if any(is_critical(a) and not any(f(a) for f in left_alone) for a in pending): + return JSONResponse(status_code=409, content={ + "error": "digest_required", + "detail": "a critical request is pending: approve each critical request on its own, with the " + "digest served with it"}) + return None + if action is None or not is_critical(action): + return None + given = (body or {}).get("digest") + if not isinstance(given, str) or not given: + return JSONResponse(status_code=409, content={ + "error": "digest_required", + "detail": "this request is critical: approve it with the digest served with it (GET /api/approvals)"}) + if not hmac.compare_digest(given.encode("utf-8", "replace"), queue.digest(action).encode("ascii")): + return JSONResponse(status_code=409, content={ + "error": "digest_mismatch", "detail": "that digest is not this request's: fetch it again"}) + return None + def _worker_approve_refusal(request: Request): """Why a worker's request may not be approved by THIS request, or None. diff --git a/src/prometheus/web/ws_server.py b/src/prometheus/web/ws_server.py index 633247fc..ea298085 100644 --- a/src/prometheus/web/ws_server.py +++ b/src/prometheus/web/ws_server.py @@ -1082,6 +1082,8 @@ def _server_capabilities(self) -> list[str]: # Every serialized approval request says whether it must be answered in the app (permissions/critical.py), # so a client can tell a missing ``critical`` (an older daemon) from ``false``. capabilities.append("approval_critical") + # Approving a critical request needs the digest served with it (permissions/approval_queue.digest). + capabilities.append("approval_digest") return capabilities async def _system_note(self, session_id: str, content: str) -> None: diff --git a/tests/test_computer_door.py b/tests/test_computer_door.py index 5d437d35..007c4e2f 100644 --- a/tests/test_computer_door.py +++ b/tests/test_computer_door.py @@ -918,8 +918,9 @@ def test_an_old_ios_build_cannot_approve_typed_text(rest): assert res.status_code == 409, res.text assert "desktop or Telegram" in res.json()["error"] assert action._result is not ApprovalResult.APPROVED + # A desktop prompt is critical: a client that can show the text approves it with the digest it was served. res = rest.client.post(f"/api/approvals/{action.request_id}/approve", - json={"scope": "once"}, + json={"scope": "once", "digest": rest.rig.channel.digest(action)}, headers={**_h(rest.phone["token"]), "X-Beacon-Caps": "approval-arguments"}) assert res.status_code == 200, res.text diff --git a/tests/test_device_hold_needs_a_person.py b/tests/test_device_hold_needs_a_person.py index 4449e5b4..3abae830 100644 --- a/tests/test_device_hold_needs_a_person.py +++ b/tests/test_device_hold_needs_a_person.py @@ -153,9 +153,11 @@ async def test_a_denied_lift_leaves_the_hold(rig): async def test_only_a_person_can_approve_a_lift(rig, who): await _held_by_token(rig) rid = (await rig.put_hold(None)).json()["pending"]["request_id"] + # A hold lift is critical: each credential sends the digest it was served, so what refuses is who it is. + digest = rig.queue.digest(rig.queue.pending[rid]) if who == "global-token": async with rig.client(GLOBAL) as c: - r = await c.post(f"/api/approvals/{rid}/approve", json={"scope": "once"}) + r = await c.post(f"/api/approvals/{rid}/approve", json={"scope": "once", "digest": digest}) assert r.status_code in (401, 403) or r.json().get("ok") is False, r.text elif who == "held-device": async with rig.client(rig.relay["token"]) as c: @@ -167,7 +169,7 @@ async def test_only_a_person_can_approve_a_lift(rig, who): # An owner device is the operator's credential, and its token is minted by a local route a model can # reach: it asks like the token does, and is not the approval. async with rig.client(rig.owner["token"]) as c: - r = await c.post(f"/api/approvals/{rid}/approve", json={"scope": "once"}) + r = await c.post(f"/api/approvals/{rid}/approve", json={"scope": "once", "digest": digest}) assert r.status_code in (401, 403) or r.json().get("ok") is False, r.text await _settle() assert rig.held() == "relay", f"{who} lifted the hold" From 174e997063fca37fd6b7ad33f600defce5e4cd92 Mon Sep 17 00:00:00 2001 From: OAra Labs Date: Fri, 13 Nov 2026 20:05:32 -0500 Subject: [PATCH 3/5] test(approvals): red tests for #925's review findings The 409 shape, all's own code, a digest that never raises and cannot be rebuilt without fetching, no digest in the stored frame; the full-tools hold test sends the served digest so the person check is what refuses. Co-Authored-By: Claude Opus 5.5 --- tests/test_critical_approve_needs_digest.py | 58 ++++++++++++++++++--- tests/test_device_hold_needs_a_person.py | 6 ++- 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/tests/test_critical_approve_needs_digest.py b/tests/test_critical_approve_needs_digest.py index 732d066f..8d6ee3ef 100644 --- a/tests/test_critical_approve_needs_digest.py +++ b/tests/test_critical_approve_needs_digest.py @@ -80,7 +80,7 @@ def test_every_served_request_carries_a_digest(d): def test_a_critical_approve_without_the_digest_answers_nothing(d): client, queue, critical, _ = d r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json={"scope": "once"}) - assert r.status_code == 409 and r.json()["error"] == "digest_required" + assert r.status_code == 409 and r.json()["code"] == "digest_required" and "digest" in r.json()["error"] assert critical._result == ApprovalResult.TIMEOUT and critical.request_id in queue.pending @@ -89,7 +89,7 @@ def test_a_critical_approve_with_another_digest_answers_nothing(d, wrong): client, queue, critical, plain = d body = {"scope": "once", "digest": wrong} r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json=body) - assert r.status_code == 409 and r.json()["error"] in ("digest_required", "digest_mismatch") + assert r.status_code == 409 and r.json()["code"] in ("digest_required", "digest_mismatch") assert critical._result == ApprovalResult.TIMEOUT @@ -97,7 +97,7 @@ def test_another_requests_digest_is_not_this_ones(d): client, queue, critical, plain = d body = {"scope": "once", "digest": _served(client, plain.request_id)["digest"]} r = client.post(f"/api/approvals/{critical.request_id}/approve", headers=H, json=body) - assert r.status_code == 409 and r.json()["error"] == "digest_mismatch" + assert r.status_code == 409 and r.json()["code"] == "digest_mismatch" assert critical._result == ApprovalResult.TIMEOUT @@ -126,7 +126,7 @@ def test_approve_all_never_approves_a_critical_request(d): critical request is approved one at a time, with its digest.""" client, queue, critical, plain = d r = client.post("/api/approvals/all/approve", headers=H, json={"scope": "once"}) - assert r.status_code == 409 and r.json()["error"] == "digest_required" + assert r.status_code == 409 and r.json()["code"] == "critical_pending" # no digest can satisfy "all" assert critical._result == ApprovalResult.TIMEOUT and plain._result == ApprovalResult.TIMEOUT @@ -185,8 +185,54 @@ def approval_push_targets(self, *, desktop): def test_the_digest_does_not_change_while_the_request_waits(d): client, queue, critical, _ = d first = _served(client, critical.request_id)["digest"] - queue.critical_rules = None # nothing the digest covers depends on these - assert _served(client, critical.request_id)["digest"] == first + assert _served(client, critical.request_id)["digest"] == first == queue.digest(critical) + + +# ── #925 review ────────────────────────────────────────────────────────────── + +def test_arguments_with_a_lone_surrogate_still_serialize_and_digest(): + """Review M1: a lone surrogate (json.loads accepts one, a model can send one) made the digest raise after the + request was registered, so it sat in the queue until restart and the list answered 500.""" + q = ApprovalQueue(security_gate=_Gate(), telegram_adapter=None) + a = PendingAction(request_id="c0c0c009", tool_name="bash", description="x", session_id="web:s1", + arguments={"command": "echo \ud800"}, critical_matches=("command:echo",)) + q._register(a) + served = q.serialize_pending(a) + assert len(served["digest"]) == 64 and served["digest"] == q.digest(a) + a2 = PendingAction(request_id="c0c0c00a", tool_name="bash", description="x", session_id="web:s1", + arguments={1: "int key", "a": "str key"}) + assert len(q.digest(a2)) == 64 # mixed keys: never raises either + + +def test_the_digest_cannot_be_computed_from_what_a_push_or_a_guess_gives(): + """Review L4: an unkeyed hash of the shown fields could be rebuilt from the push and a guess. It is keyed per + daemon process, so a client holds it only by fetching the request.""" + import hashlib + import json + + from prometheus.permissions.critical import is_critical + + q = ApprovalQueue(security_gate=_Gate(), telegram_adapter=None) + a = PendingAction(request_id="c0c0c00b", tool_name="bash", description="rm -rf build", session_id="web:s1", + arguments={"command": "rm -rf build"}, critical_matches=("command:rm -rf",)) + q._register(a) + shown = {"request_id": a.request_id, "tool_name": a.tool_name, "description": a.description, + "arguments": a.arguments, "created_at": a.created_at, "expires_at": q.expires_at(a), + "critical": is_critical(a)} + for ensure_ascii in (True, False): + plain = hashlib.sha256(json.dumps(shown, sort_keys=True, separators=(",", ":"), ensure_ascii=ensure_ascii, + default=str).encode("utf-8")).hexdigest() + assert q.digest(a) != plain + + +def test_the_stored_copy_of_the_frame_has_no_digest(): + """Review session low: the approval_pending payload is stored (signal_events); the digest stays on the wire.""" + from prometheus.sentinel.signals import ActivitySignal, SignalBus + + live = ActivitySignal(kind="approval_pending", payload={"request_id": "c0c0c001", "digest": "ab" * 32}, + source="test") + stored = SignalBus.at_rest(live) + assert "digest" not in stored.payload and live.payload["digest"] == "ab" * 32 def test_server_capabilities_lists_approval_digest(): diff --git a/tests/test_device_hold_needs_a_person.py b/tests/test_device_hold_needs_a_person.py index 3abae830..c1cc10fb 100644 --- a/tests/test_device_hold_needs_a_person.py +++ b/tests/test_device_hold_needs_a_person.py @@ -237,8 +237,12 @@ async def stream_message(self, request): # noqa: ANN001 "method": "PUT", "path": f"/api/devices/{rig.relay['id']}/profile", "body": {"profile": None}})] elif self.round == 2: rid = replies[-1].json().get("pending", {}).get("request_id", "none") + # It fetched the request first (GET /api/approvals), so it sends the digest it was served: what + # refuses is the person check, not a missing digest (#925 review). + digest = rig.queue.digest(rig.queue.pending[rid]) if rid in rig.queue.pending else "" content = [ToolUseBlock(id="t2", name="curl", input={ - "method": "POST", "path": f"/api/approvals/{rid}/approve", "body": {"scope": "once"}})] + "method": "POST", "path": f"/api/approvals/{rid}/approve", + "body": {"scope": "once", "digest": digest}})] else: content = [TextBlock(text="done")] yield ApiMessageCompleteEvent( From c90d1a9bd7902874403274813c3bf67ec72531be Mon Sep 17 00:00:00 2001 From: OAra Labs Date: Fri, 13 Nov 2026 20:06:25 -0500 Subject: [PATCH 4/5] fix(approvals): #925's review findings - The digest never raises (ASCII JSON, a repr fallback for keys that cannot be sorted), so an odd argument no longer leaves a request stuck in the queue until restart. - It is an HMAC under a key minted per daemon process, and the stored copy of the frame drops it, so a client holds it only by fetching. - The 409s use the route's shape (prose in error, the word in code); all gets its own code, critical_pending (no digest satisfies it). - The comment says where the hold lift's person check runs; REST only. - CHANGELOG and API guide: the default critical kinds, that a client which does not send the digest can no longer approve them over REST, chat gateways unchanged, and the subscribed capabilities. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/guide/api.md | 6 ++--- src/prometheus/permissions/approval_queue.py | 19 +++++++++++--- src/prometheus/sentinel/signals.py | 21 ++++++++++------ src/prometheus/web/server.py | 26 +++++++++++--------- 5 files changed, 46 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62f5bee0..35f53576 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Notable changes in each release, newest first. Releases before 0.9.7 are describ ## Unreleased -- Approvals: approving a critical request needs its digest. Every served approval request (`GET /api/approvals`, the `approval_pending` frame) carries `digest`, a sha256 over what the client is shown, and never in a push. `POST /api/approvals/{id}/approve` on a critical request without it answers `409 digest_required`, with another `409 digest_mismatch`, and approves nothing; `all` is refused while a critical request it would approve is pending. It proves the client fetched that exact request, not that a person read it. Other requests, and denying, are unchanged. `server_capabilities` lists `approval_digest`. +- Approvals: approving a critical request over REST needs its digest. Every served approval request (`GET /api/approvals`, the `approval_pending` frame) carries `digest`, an HMAC (keyed per daemon process) over what the client is shown, never in a push or in the stored copy of the frame. `POST /api/approvals/{id}/approve` on a critical request answers `409` with `code: digest_required` without it or `digest_mismatch` with another, and approves nothing; `all` answers `409 critical_pending` while a critical request it would approve is pending. Critical by default: desktop-task prompts, device hold lifts, requests whose arguments were cut or masked or whose description is long, and the owner's critical lists (by default deleting, `git push`, sending, spending and changing config). **A client that does not send the digest can no longer approve these over REST**, Beacon builds before this change included, until it does; Telegram, Slack and Discord `/approve` are unchanged. It proves the client fetched that exact request, not that a person read it. Other requests, and denying, are unchanged. `server_capabilities` lists `approval_digest`. - Approvals: every serialized approval request (`GET /api/approvals`, the `approval_pending` frame, the push) now says `critical`: whether it must be answered in the app rather than from a notification. Built in: desktop prompts, lifting a device's hold, arguments cut or masked for display, and a description over 600 characters or 8 lines. On top of that, three owner-editable lists, `push.critical_tools`, `push.critical_commands` and `push.critical_paths`, whose defaults cover deletes, `git push`, commands and tools that send or spend, and changes to devices, permissions or the agent's own configuration (leave a key out for the default, `[]` for none). A critical request's push has no category, so the notification offers no Approve, and carries `"critical": true`. The `subscribed` ack lists `approval_critical` in `server_capabilities`. This decides only where a request is answered, not whether: the lists are best effort and are not a security guard (every request already needs a person). Classifying never blocks or fails a request, and on any error the request is critical. - Push: an approval push now reaches owner devices only, and, for a desktop prompt (whose push carries no content), also the devices marked for computer use, which are the ones that may answer it. It went to every registered device with a push registration, scoped devices included, which see only their own sessions everywhere else and cannot approve. A device store that cannot name owner devices sends no approval push. Other pushes are unchanged. - Docs: `docs/reference/pairing-join-requests.md` is the reference for how a new device asks to join and how the owner lets it in: the routes and who may call them, every request and response field, the statuses, the expiry and rate limits, the sealed token, the operator's WebSocket frames and the owner code (the explicit, single-use grant that makes an owner device). It is written from the code and pinned to it by `tests/test_pairing_reference.py`. No behaviour changes. diff --git a/docs/guide/api.md b/docs/guide/api.md index 896e99ab..dc68ecac 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -237,8 +237,8 @@ Artifacts are **content-addressed**: ids are a sha256 prefix of the file bytes, | Method | Path | Purpose | |---|---|---| -| GET | `/api/approvals` | Poll pending approval requests. Each carries `critical`: `true` means answer it in the app, never from a notification (its push has no Approve). Rules: `permissions/critical.py`, owner lists `push.critical_*`. A nudge about where to answer, not a security guard: every request already needs a person, and a request judged ordinary is still read and approved by one. Each also carries `digest`: a sha256 over what the client is shown (id, tool, description, arguments view, created and expiry times, the critical flag), served with the request and never in a push | -| POST | `/api/approvals/{request_id}/approve` | Approve a request. Body `{scope?, digest?}`. A **critical** request is approved only with the `digest` it was served (`GET /api/approvals`, the `approval_pending` frame): none is `409 digest_required`, another is `409 digest_mismatch`, and nothing is approved. That proves the client fetched this exact request, not that a person read it in the app. `all` is refused (`409 digest_required`) while a critical request it would approve is pending. Other requests need no digest. `server_capabilities` lists `approval_digest` | +| GET | `/api/approvals` | Poll pending approval requests. Each carries `critical`: `true` means answer it in the app, never from a notification (its push has no Approve). Rules: `permissions/critical.py`, owner lists `push.critical_*`. A nudge about where to answer, not a security guard: every request already needs a person, and a request judged ordinary is still read and approved by one. Each also carries `digest`: an HMAC, keyed per daemon process, over what the client is shown (id, tool, description, arguments view, created and expiry times, the critical flag), served with the request and never in a push or the stored copy of the frame | +| POST | `/api/approvals/{request_id}/approve` | Approve a request. Body `{scope?, digest?}`. A **critical** request is approved only with the `digest` it was served (`GET /api/approvals`, the `approval_pending` frame): none is `409` with `code: digest_required`, another is `code: digest_mismatch` (fetch again), and nothing is approved. That proves the client fetched this exact request, not that a person read it in the app. `all` is refused (`409`, `code: critical_pending`) while a critical request it would approve is pending. Other requests need no digest; Telegram, Slack and Discord `/approve` are unchanged. `server_capabilities` lists `approval_digest` | | POST | `/api/approvals/{request_id}/deny` | Deny a request | **A request that has ended cannot be answered.** Approving or denying a request that is no longer pending acts on nothing and is **410** `{"ok": false, "error": "no_longer_active", "resolution", "detail", ...}` (the approve route's usual `remembered`, `grant_id`, `message` and `skipped` keys are there too). `resolution` says how it ended: `withdrawn` (with the reason in `detail`), `approved`, `denied`, `expired`, or `null` when this daemon has no record of it (the queue is in memory, so a restart ends every request). A scoped device still gets 404 for a request that is not its own conversation's. `all` is not a request id. @@ -398,7 +398,7 @@ Chat lifecycle: | Type | Purpose | |---|---| | `connected` | Auth accepted; connection metadata | -| `subscribed` | Subscription ack. `server_capabilities` lists what this daemon can do for the client: `voice_input` when an audio `chat_upload` can be transcribed here (`stt.url`, `whisper.url` or an approved voice box is set, or a local Whisper engine and ffmpeg are installed) | +| `subscribed` | Subscription ack. `server_capabilities` lists what this daemon can do for the client: `voice_input` when an audio `chat_upload` can be transcribed here (`stt.url`, `whisper.url` or an approved voice box is set, or a local Whisper engine and ffmpeg are installed); `approval_critical`: every approval request says `critical`; `approval_digest`: approving a critical request over REST needs its `digest` | | `chat_message` | A complete message (user echo, assistant reply, or slash-command result) | | `chat_delta` | Streaming token delta | | `agent_state` | Agent thinking/idle state changes (carries `session_id`) | diff --git a/src/prometheus/permissions/approval_queue.py b/src/prometheus/permissions/approval_queue.py index a6bc1541..0c28669f 100644 --- a/src/prometheus/permissions/approval_queue.py +++ b/src/prometheus/permissions/approval_queue.py @@ -10,8 +10,10 @@ import asyncio import contextlib import hashlib +import hmac import json import logging +import secrets import time from collections import OrderedDict from dataclasses import dataclass, field @@ -394,6 +396,10 @@ def _humanise_window(seconds) -> str: return f"{int(seconds)} s" +#: The key :meth:`ApprovalQueue.digest` is keyed with: one per daemon process, never stored, never sent. +_DIGEST_KEY = secrets.token_bytes(32) + + class ApprovalQueue: """Manages pending LEVEL 1 approval requests via Telegram. @@ -617,8 +623,10 @@ def digest(self, action: PendingAction) -> str: """sha256 over exactly what a client is shown of *action*: its id, tool, description, arguments view, created and expiry times and critical flag (Beacon iOS item 3). - Served with the request wherever it is served (``serialize_pending``) and never in a push, so a client holds - it only by fetching the request. Approving a CRITICAL request needs it (the REST approve route): that proves + An HMAC under a key minted per daemon process (requests do not outlive the process either), so it cannot be + rebuilt from a push and a guess: served with the request wherever it is served (``serialize_pending``), + never in a push, and left out of the stored copy of the frame, so a client holds it only by fetching the + request. Never raises (an odd character or key in the arguments still digests). Approving a CRITICAL request needs it (the REST approve route): that proves the client fetched this exact request, not that a person read it in the app. The derived ``extents`` are left out on purpose: they can change with the grants while the request waits, and nothing approved depends on the client having seen them. @@ -632,8 +640,11 @@ def digest(self, action: PendingAction) -> str: "expires_at": self.expires_at(action), "critical": is_critical(action), } - canonical = json.dumps(shown, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str) - return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + try: + canonical = json.dumps(shown, sort_keys=True, separators=(",", ":"), default=str) + except (TypeError, ValueError): + canonical = repr(shown) # keys sort_keys cannot order: still fixed per request + return hmac.new(_DIGEST_KEY, canonical.encode("utf-8", "backslashreplace"), hashlib.sha256).hexdigest() def expires_at(self, action: PendingAction) -> float: """Epoch seconds at which this request's window closes. diff --git a/src/prometheus/sentinel/signals.py b/src/prometheus/sentinel/signals.py index f3fc82df..f2de4cb8 100644 --- a/src/prometheus/sentinel/signals.py +++ b/src/prometheus/sentinel/signals.py @@ -115,15 +115,20 @@ def at_rest(signal: ActivitySignal) -> ActivitySignal: return them. """ payload = signal.payload - if (signal.kind == "approval_pending" and isinstance(payload, dict) - and payload.get("task_id") is not None - and payload.get("arguments") is not None): - stored = dict(payload) + if signal.kind != "approval_pending" or not isinstance(payload, dict): + return signal + blank_arguments = payload.get("task_id") is not None and payload.get("arguments") is not None + # The digest a critical approve must echo (approval_queue.digest) is held only by a client that fetched + # the request: the stored copy never carries it. + if not blank_arguments and "digest" not in payload: + return signal + stored = dict(payload) + stored.pop("digest", None) + if blank_arguments: stored["arguments"] = None - return ActivitySignal(kind=signal.kind, payload=stored, - source=signal.source, - timestamp=signal.timestamp) - return signal + return ActivitySignal(kind=signal.kind, payload=stored, + source=signal.source, + timestamp=signal.timestamp) async def emit(self, signal: ActivitySignal) -> None: """Broadcast *signal* to matching subscribers and wildcards. diff --git a/src/prometheus/web/server.py b/src/prometheus/web/server.py index a73d08bc..f0ce6b4d 100644 --- a/src/prometheus/web/server.py +++ b/src/prometheus/web/server.py @@ -5319,8 +5319,9 @@ async def approve_action( return refusal # A CRITICAL request is approved only with its digest (Beacon iOS item 3), which is served with the request - # and never in a push: the client fetched exactly this request. Last, so every refusal about WHO may answer - # is said first; never through "all". + # and never in a push: the client fetched exactly this request. After the route's own refusals about who + # may answer (a hold lift's person check runs later, inside its queue); never through "all". REST only: + # the chat gateways' /approve is the owner typing in chat, where a critical request may be answered. if (refusal := _digest_refusal(queue, request_id, _desk, body)) is not None: return refusal @@ -5356,10 +5357,11 @@ async def approve_action( def _digest_refusal(queue: Any, request_id: str, action: Any, body: dict | None) -> JSONResponse | None: """409 when approving a critical request without its digest (or with another), else None. - ``digest_required``: no digest, or approving ``all`` while a critical request it would approve is pending - (``all`` already leaves desktop, worker and hold requests alone; any other critical request is approved on - its own, with its digest). ``digest_mismatch``: a digest that is not this request's. Compared in constant - time. A request that is not critical needs none; denying never does. + The body has the route's 409 shape: prose in ``error``, the machine word in ``code``. ``digest_required``: no + digest. ``digest_mismatch``: a digest that is not this request's (fetch it again). ``critical_pending``: + approving ``all`` while a critical request it would approve is pending (``all`` already leaves desktop, + worker and hold requests alone; no digest can satisfy ``all``, so each critical request is approved on its + own). Compared in constant time. A request that is not critical needs none; denying never does. """ import hmac @@ -5371,20 +5373,20 @@ def _digest_refusal(queue: Any, request_id: str, action: Any, body: dict | None) left_alone = (is_desktop_request, is_worker_request, is_hold_request) if any(is_critical(a) and not any(f(a) for f in left_alone) for a in pending): return JSONResponse(status_code=409, content={ - "error": "digest_required", - "detail": "a critical request is pending: approve each critical request on its own, with the " - "digest served with it"}) + "error": "A critical request is pending: approve each critical request on its own, in the app.", + "code": "critical_pending"}) return None if action is None or not is_critical(action): return None given = (body or {}).get("digest") if not isinstance(given, str) or not given: return JSONResponse(status_code=409, content={ - "error": "digest_required", - "detail": "this request is critical: approve it with the digest served with it (GET /api/approvals)"}) + "error": "This request is critical: approve it in the app, with the digest served with it.", + "code": "digest_required"}) if not hmac.compare_digest(given.encode("utf-8", "replace"), queue.digest(action).encode("ascii")): return JSONResponse(status_code=409, content={ - "error": "digest_mismatch", "detail": "that digest is not this request's: fetch it again"}) + "error": "That digest is not this request's: fetch the request again.", + "code": "digest_mismatch"}) return None def _worker_approve_refusal(request: Request): From bee80be62069159ec4b80b6a4556c0e4ebd62b4b Mon Sep 17 00:00:00 2001 From: OAra Labs Date: Fri, 13 Nov 2026 20:23:36 -0500 Subject: [PATCH 5/5] docs(approvals): the digest docstring says HMAC; the key is the daemon process's own Co-Authored-By: Claude Opus 5.5 --- src/prometheus/permissions/approval_queue.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/prometheus/permissions/approval_queue.py b/src/prometheus/permissions/approval_queue.py index 0c28669f..c738c4ef 100644 --- a/src/prometheus/permissions/approval_queue.py +++ b/src/prometheus/permissions/approval_queue.py @@ -396,7 +396,9 @@ def _humanise_window(seconds) -> str: return f"{int(seconds)} s" -#: The key :meth:`ApprovalQueue.digest` is keyed with: one per daemon process, never stored, never sent. +#: The key :meth:`ApprovalQueue.digest` is keyed with: one per daemon process, never stored, never sent. Every +#: digest is made and checked in the daemon process (worker children never compute one); a route that ever moved +#: out of it would need this key shared with it. _DIGEST_KEY = secrets.token_bytes(32) @@ -620,7 +622,7 @@ def timeout_seconds(self) -> float: return self._timeout def digest(self, action: PendingAction) -> str: - """sha256 over exactly what a client is shown of *action*: its id, tool, description, arguments view, + """HMAC-SHA256 over exactly what a client is shown of *action*: its id, tool, description, arguments view, created and expiry times and critical flag (Beacon iOS item 3). An HMAC under a key minted per daemon process (requests do not outlive the process either), so it cannot be