Skip to content
Draft
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Notable changes in each release, newest first. Releases before 0.9.7 are describ

## Unreleased

- 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.
Expand Down
6 changes: 3 additions & 3 deletions docs/guide/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`: 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.
Expand Down Expand Up @@ -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`) |
Expand Down
43 changes: 43 additions & 0 deletions src/prometheus/permissions/approval_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@

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
Expand Down Expand Up @@ -392,6 +396,12 @@ 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. 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)


class ApprovalQueue:
"""Manages pending LEVEL 1 approval requests via Telegram.

Expand Down Expand Up @@ -556,6 +566,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.
Expand Down Expand Up @@ -608,6 +621,33 @@ def timeout_seconds(self) -> float:
"""
return self._timeout

def digest(self, action: PendingAction) -> str:
"""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
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.
"""
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),
}
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.

Expand Down Expand Up @@ -1114,6 +1154,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)
Expand Down
21 changes: 13 additions & 8 deletions src/prometheus/sentinel/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
42 changes: 42 additions & 0 deletions src/prometheus/web/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5318,6 +5318,13 @@ 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. 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

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
Expand Down Expand Up @@ -5347,6 +5354,41 @@ 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.

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

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": "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": "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": "That digest is not this request's: fetch the request again.",
"code": "digest_mismatch"})
return None

def _worker_approve_refusal(request: Request):
"""Why a worker's request may not be approved by THIS request, or None.

Expand Down
2 changes: 2 additions & 0 deletions src/prometheus/web/ws_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion tests/test_computer_door.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading