From af9336a40f91ec30102dcf8d9ecc9a8c2148cf4b Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:19:14 +0200 Subject: [PATCH 01/10] Add ADR-0019 for approval of reverse-migration rollback An allowlisted socket peer can send a plain Rollback and run every reverse migration without an approval token. ADR-0019 amends ADR-0014 so any rollback that runs reverse migrations passes the approval gate, with a default key location and automatic token minting in the CLI. Point ADR-0014 and threat-model row TM-002 at the new ADR. Per-operation authorization for other requests stays open. --- ...0014-destructive-rollback-approval-gate.md | 1 + ...approval-for-reverse-migration-rollback.md | 133 ++++++++++++++++++ git.agentic-threat-model.md | 7 +- 3 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 docs/adr/0019-approval-for-reverse-migration-rollback.md diff --git a/docs/adr/0014-destructive-rollback-approval-gate.md b/docs/adr/0014-destructive-rollback-approval-gate.md index db2fb697..e7615b4c 100644 --- a/docs/adr/0014-destructive-rollback-approval-gate.md +++ b/docs/adr/0014-destructive-rollback-approval-gate.md @@ -5,6 +5,7 @@ **Deciders:** Toni **Closes:** [`git.agentic-threat-model.md`](../../git.agentic-threat-model.md) TM-002 (sibling worker triggers destructive down-migration via `Rollback { accept_data_loss: true }`) **Closed in:** `beacd65` / PR #121 (2026-07-10) — approval gate implemented; interim hard-reject shipped earlier in `aabcbda` / PR #114 +**Amended by:** [ADR-0019](./0019-approval-for-reverse-migration-rollback.md) (2026-11-20): rollbacks that run reverse migrations pass the same gate, with or without `accept_data_loss`. **Relates to:** [ADR-0002](./0002-substrate-and-supercommit.md) Decision 5 (bounded rollback for destructive migrations), [ADR-0004](./0004-realtime-agenticd-for-executor.md) Decision 4 (loud-fail discipline), [ADR-0012](./0012-socket-peer-authentication.md) Decision 2 (`peer_uid` on every accepted connection), [issue #37 / audit §A8](../ops/2026-05-21-agenticd-architectural-analysis.md#a8) (the reverse-migration outer-transaction work that wired `accept_data_loss` end-to-end). ## Context diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md new file mode 100644 index 00000000..d7d86ce4 --- /dev/null +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -0,0 +1,133 @@ +# ADR-0019: Approval for Reverse-Migration Rollback + +**Status:** Accepted +**Owner:** Toni Bergholm +**Date:** 2026-11-20 +**Amends:** [ADR-0014](./0014-destructive-rollback-approval-gate.md) (the approval gate now also covers rollbacks that run reverse migrations) +**Threat model:** [`git.agentic-threat-model.md`](../../git.agentic-threat-model.md) TM-002, plain-rollback residual (TM-001 shares the per-operation authorization question, which stays open) +**Relates to:** [ADR-0012](./0012-socket-peer-authentication.md) Decision 2 (`peer_uid`), [ADR-0002](./0002-substrate-and-supercommit.md) Decision 5 (bounded rollback for destructive migrations) + +## Context + +ADR-0014 gates `Request::Rollback { accept_data_loss: true }` behind an operator approval token. +It leaves a plain rollback (`accept_data_loss: false`) ungated. +The 2026-11-20 threat-model reconciliation recorded the consequence in TM-002: an allowlisted socket peer, which in the sidecar shape is the adversarial worker, can send a plain `Rollback`. +The daemon then runs every reverse migration that is not marked `IRREVERSIBLE` and restores memory, with no approval token. +A reverse migration drops columns, tables and indexes. +Whether or not it carries the `IRREVERSIBLE` marker, it is a schema change on the per-tenant database that the worker could trigger at will. + +ADR-0012 limits who can talk to the daemon. +It does not limit which of those peers may run a schema change. +The owner decided that any rollback that runs reverse migrations needs the ADR-0014 approval token, from any peer. + +## Decision summary + +| # | Decision | One-line rationale | +|---|---|---| +| 1 | A non-dry-run rollback whose plan includes at least one reverse migration passes the ADR-0014 gate, whether or not `accept_data_loss` is set. | The schema change is the dangerous operation, not the flag that acknowledges it. | +| 2 | Without an approval key, such a rollback is refused, and the error names `--approval-key-file`. | Fail closed, as ADR-0014 Decision 4. | +| 3 | If `--approval-key-file` is not given, the daemon uses `/.agentic/approval.key` when that file exists. | The operator needs no extra flag, and the CLI and daemon share one default location. | +| 4 | The `agentic` CLI attaches a token to rollback requests on its own when it can read the key. | The operator's commands stay the same. A socket client without the key cannot run reverse migrations. | + +## Decisions + +### Decision 1: Reverse migrations pass the ADR-0014 gate + +Once the daemon knows the plan, it checks whether the plan includes at least one reverse migration. +That means the live schema version differs from the target's and the backend reports at least one migration to reverse. +If so, and the request is not a dry run, the request passes the same gate as an `accept_data_loss` rollback. +The token format, the HMAC binding to the target commit and the peer UID, the five-minute window and the single-use ledger are the ADR-0014 ones, unchanged. + +The gate runs before any side effect. +The code that builds the plan only reads: it resolves the ref, loads the target, checks the prompts tree and queries the backend for the live schema version and the pending migration names. +The gate sits right after that, before the reverse migrations run, the memory restore, the prompts write-back and the forward-record. +A refused request changes nothing. + +A request with `accept_data_loss: true` already passed the gate at the start. +It is not checked a second time, so one token covers both reasons and is consumed once. + +Rollbacks with no schema change are unchanged. +That includes a rollback whose target has no `schema_version`, and one whose target schema equals the live schema. + +Audit. +The gate emits the existing `RollbackForcedDataLoss` event, with the same `decision` values. +The event gains a `reason` field: `accept_data_loss` for the ADR-0014 trigger and `reverse_migration` for this one. +Events from before this ADR carry no `reason` and mean `accept_data_loss`. +An alert on forced data loss should filter on `reason = "accept_data_loss"`, so routine operator rollbacks that run reverse migrations do not trip it. +An alert on rejected attempts, `decision = "rejected_*"`, should cover both reasons. + +Dry runs. +A dry run reports that approval will be required, as an extra line in the plan output, when the plan includes a reverse migration. +A dry run without a token is not refused, so an operator can preview. +A dry run that carries a token still verifies it and does not consume it, as for `accept_data_loss` today. + +Wire errors. +The refusals reuse the ADR-0014 codes: `approval_key_not_configured`, `approval_no_peer_uid`, `approval_required`, `approval_token_malformed`, `approval_token_expired`, `approval_token_invalid_signature` and `approval_token_replayed`. +All are non-retryable validation errors. +The messages name both triggers. + +### Decision 2: Fail closed without a key + +If no approval key is configured, a rollback that runs reverse migrations is refused with `approval_key_not_configured`. +The message says to start `agenticd` with `--approval-key-file `, or to place a 32-byte key at `/.agentic/approval.key`. +There is no override flag. + +A daemon running with `--insecure-allow-any-uid` has no attested peer UID, so no token can bind to a peer. +Such a rollback is refused with `approval_no_peer_uid`, as ADR-0014 already does for `accept_data_loss`. +A deployment that wants reverse migrations must run with `--allowed-uid`. + +### Decision 3: Key discovery + +If `--approval-key-file` is not given, the daemon uses `/.agentic/approval.key` when that file exists. +When the flag is given, the flag wins and the default file is ignored. +A missing default file means no key, so Decision 2 applies. + +The file is read with the checks ADR-0014 and its 2026-11-20 amendment set. +A file with any group or other mode bit set aborts startup with an error that names the path and says to `chmod 600` it. +A key that is not exactly 32 bytes aborts startup. +An empty or unreadable file leaves the daemon running without a key. + +### Decision 4: The CLI attaches a token + +`agentic rollback` looks for a key: the `--key-file` flag if given, else `/.agentic/approval.key` if that file exists. +The flag already exists for token issuance (`--approval`), and the rollback command reuses it. +If it finds a key, it resolves the target ref to a commit hash with a `ResolveRef` request and mints a token for that hash and the CLI process's effective UID, which is the UID the daemon reads from the socket. +It attaches the token to the rollback request, to the preview request and to the real one, so the operator is not asked for anything. +A token passed explicitly with `--approval-token` is sent as given. +If the CLI finds no key, it sends no token, and the daemon decides whether one is needed. + +The CLI sends the token whenever it has a key, not only when a reverse migration is coming. +The daemon ignores a token it does not need. +A token is consumed only when the gate passes on a non-dry-run request. + +This also lets an operator who holds the key run `--accept-data-loss` without minting a token by hand. +The flag is still required. + +## Consequences + +**Positive:** + +- A worker without the key cannot run reverse migrations. + The TM-002 plain-rollback residual closes for that case. +- The operator's CLI keeps working with no new steps, as long as the key sits at the default path or is passed with `--key-file`. +- No new wire fields, error codes or ledger. + The change is one more call site for the ADR-0014 gate. + +**Negative:** + +- Breaking for deployments that ran token-less rollbacks with reverse migrations. + They now need an approval key on the daemon and a token from the caller. + The daemon must also run with `--allowed-uid`. +- The broken-prompt demo creates a key and starts the daemon with `--allowed-uid`. + Its current rollback has no schema change, so it consumes no token. +- Any process under the same UID that can read the key can mint tokens. + ADR-0014's amendment says this already. + The mode check only excludes other UIDs. +- The Python SDK sends no token, so an SDK client cannot run reverse migrations. + That is intended, because the SDK is what the worker uses. + +**Not covered:** + +- A rollback with no schema change still restores memory without a token. + Per-operation authorization for the other requests, `ReadObject` among them, stays an open decision in TM-001 and TM-002. +- The ledger is per process, as in ADR-0014. diff --git a/git.agentic-threat-model.md b/git.agentic-threat-model.md index 6aa789f3..6fed933d 100644 --- a/git.agentic-threat-model.md +++ b/git.agentic-threat-model.md @@ -14,6 +14,7 @@ Merged: PRs #145 to #150 (approval-token hardening, strict checkpoint deserializ Also merged: PR #151 (object address collision, ADR-0018, `1e6bd9f`) and PR #152 (sidecar state isolation). Added TM-011, TM-012 and TM-013. TM-001 and TM-002 are reopened for the per-operation authorization residual. +Later the same day, [ADR-0019](docs/adr/0019-approval-for-reverse-migration-rollback.md) gated rollbacks that run reverse migrations behind the ADR-0014 approval token (TM-002). The unrevised original is in git history. ## Executive summary @@ -155,7 +156,7 @@ flowchart LR | Threat ID | Threat source | Prerequisites | Threat action | Impact | Impacted assets | Existing controls (evidence) | Gaps | Recommended mitigations | Detection ideas | Likelihood | Impact severity | Priority | |---|---|---|---|---|---|---|---|---|---|---|---|---| | TM-001 | Sibling worker | Reachable Unix socket; shares UID | `ReadObject` enumeration to dump tuple history | Confidentiality break across tenant tuple state | Tuple snapshots, memory snapshots | `SO_PEERCRED` UID allowlist at accept — `--allowed-uid`, fail-closed startup ([ADR-0012](docs/adr/0012-socket-peer-authentication.md), `864b5c3`, `main.rs`); per-UID connection/rate admission control (issue #118, `limits.rs`); 10 MiB cap on the `ReadObject` payload before base64 encoding (`server.rs`); object keys are content-addressed | No per-operation authorization: an allowlisted UID can call every `Request` variant, `ReadObject` included. In the sidecar shape the worker must be allowlisted to commit, so it can read the objects that the typed getter returns (blobs, trees and commits), subject to the 10 MiB payload cap. `SO_PEERCRED` negative paths are Linux-CI-only (macOS uses `getpeereid`). Per-UID rate limits slow enumeration but do not stop it | ~~Require `SO_PEERCRED`-derived UID match~~ **shipped** (ADR-0012); rate-limit ~~ReadObject~~ **shipped** (#118). **Open, needs a decision (owner not yet assigned):** per-operation authorization, for example a capability token or a separate read-only socket, if the worker must not read history | Audit-log every ReadObject with peer credential; alert on rate spike | high | high | ~~**critical**~~ **residual reopened 2026-11-20:** the peer check and admission control are shipped (ADR-0012, #118); per-operation authorization is open and awaiting an owner decision | -| TM-002 | Sibling worker | Reachable Unix socket | `Rollback` with `accept_data_loss=true` against an IRREVERSIBLE down-migration, or a plain `Rollback` (`accept_data_loss=false`) that needs no token | Production data loss | Postgres state | Approval gate ([ADR-0014](docs/adr/0014-destructive-rollback-approval-gate.md), `beacd65`/#121): `accept_data_loss=true` rejected unless a signed approval token bound to the requesting peer UID is presented; fail-closed without `--approval-key-file`, no override flag; structured `RollbackForcedDataLoss` audit event; A8 outer-tx atomicity (`migrate::run_reverse`). PR #149 (merged): tokens are single-use for non-dry-run rollbacks within one daemon process (dry runs verify without consuming), and a key file readable by group or other aborts startup | The gate covers only `accept_data_loss=true`. A plain rollback (`accept_data_loss=false`) by an allowlisted UID runs reverse migrations not marked IRREVERSIBLE and restores memory without an approval token. The single-use ledger is per process, so a restart or a second daemon accepts a token again until its time window closes. The key-file mode check excludes other UIDs only; a process with the daemon's UID can read a 0600 key. Key custody is an operator responsibility | ~~Require an out-of-band operator approval + audit event~~ **shipped** (ADR-0014, hardened by #149). **Open, needs a decision (owner not yet assigned):** whether plain rollback also needs per-operation authorization, which is the same decision as TM-001 | Alert on every `accept_data_loss=true` commit; correlate `RollbackForcedDataLoss` with ADR-0012 peer-UID audit lines | medium | high | ~~**high**~~ **destructive path closed by ADR-0014 (2026-07-10); residual reopened 2026-11-20:** plain rollback is not gated | +| TM-002 | Sibling worker | Reachable Unix socket | `Rollback` with `accept_data_loss=true` against an IRREVERSIBLE down-migration, or a plain `Rollback` (`accept_data_loss=false`) that runs reverse migrations without a token | Production data loss | Postgres state | Approval gate ([ADR-0014](docs/adr/0014-destructive-rollback-approval-gate.md), `beacd65`/#121): `accept_data_loss=true` rejected unless a signed approval token bound to the requesting peer UID is presented; fail-closed without `--approval-key-file`, no override flag; structured `RollbackForcedDataLoss` audit event; A8 outer-tx atomicity (`migrate::run_reverse`). [ADR-0019](docs/adr/0019-approval-for-reverse-migration-rollback.md): a non-dry-run rollback whose plan includes a reverse migration passes the same gate whether or not `accept_data_loss` is set, with a distinct audit `reason`; the daemon reads a default `/.agentic/approval.key`, and the `agentic` CLI mints the token itself. PR #149 (merged): tokens are single-use for non-dry-run rollbacks within one daemon process (dry runs verify without consuming), and a key file readable by group or other aborts startup | The gate covers `accept_data_loss=true` and rollbacks that run reverse migrations. A plain rollback with no schema change still restores memory without an approval token. The single-use ledger is per process, so a restart or a second daemon accepts a token again until its time window closes. The key-file mode check excludes other UIDs only; a process with the daemon's UID can read a 0600 key. Key custody is an operator responsibility | ~~Require an out-of-band operator approval + audit event~~ **shipped** (ADR-0014, hardened by #149). **Open, needs a decision (owner not yet assigned):** whether a plain rollback with no schema change, and the other requests, need per-operation authorization, which is the same decision as TM-001 | Alert on every `RollbackForcedDataLoss` with `reason="accept_data_loss"` and `decision="accepted"`, and on every `rejected_*` decision of either reason; correlate `RollbackForcedDataLoss` with ADR-0012 peer-UID audit lines | medium | high | ~~**high**~~ **destructive path closed by ADR-0014 (2026-07-10); reverse-migration path closed by ADR-0019 (2026-11-20); residual open:** a plain rollback with no schema change is not gated | | TM-003 | Sibling worker | Reachable Unix socket | Craft `CommitInput` with hostile prompts/tools bytes, no_memory=true | Integrity break: forged tuple recorded as honest snapshot | Tuple snapshots, branch refs | `SO_PEERCRED` allowlist at accept + peer-UID stamped on every Commit (`commit.rs`, threaded from the ADR-0012 dispatch context); frame size cap (16 MiB); commit-lock serializes | No daemon-signed attestation beyond the peer UID; an allowlisted worker can still stage hostile content as its own honest state | ~~Tag commits with peer-UID at the daemon side~~ **shipped** (ADR-0012). Remaining: attestation field signed by the daemon's run identity, if stronger provenance is needed | Diff agent_id field against historical pattern; alert on mismatch | high | medium | ~~**high**~~ **largely closed by ADR-0012** (2026-07-10); residual = attestation depth | | TM-004 | Sibling worker | Reachable Unix socket | Pipeline `Commit` to hold commit-lock | DoS — worker tickets fail | Daemon availability | Single commit-lock; LocalSet single-threaded. Issue #118 (`crates/agenticd/src/limits.rs`), with three separate controls: global and per-UID connection caps checked at accept time after the ADR-0012 UID check; a per-UID token-bucket request rate and read/write idle deadlines checked on the connection after accept; and a global bound on requests queued or executing on `commit_lock`. Limit values are validated at startup | The commit queue bound is global, with no per-peer queue cap, so one allowlisted worker can fill the shared queue and other callers get `commit_queue_full`. Queue depth is an internal counter visible only through debug-level tracing, and there is no lock-wait histogram. Limits are static per process | ~~Add per-peer queue depth and a request-rate cap~~ **partly shipped** (#118): connection caps and a per-UID rate exist. Remaining: per-peer queue share, and an exported queue-depth and lock-wait metric | Lock-wait latency histogram; alert on p99 > N | medium | medium | ~~**medium**~~ **reduced by issue #118** (2026-11-20 reconciliation); residual = shared queue saturation and visibility | | TM-005 | Hostile MCP server | Operator-configured URL; HTTPS reachable | `tools/list` returns adversarial canonicalizable payload | Integrity break on tools dimension | Tuple snapshots (tools sub-tree) | Transport and resource controls (PR #117, [ADR-0016](docs/adr/0016-mcp-url-policy.md)): per-call 10 s timeout; 8-way concurrency cap; response body capped at 1 MiB while streaming; redirects disabled; https only, with http allowed for loopback hosts, validated at startup. A JSON depth limit of 32 applies to the parsed `result`, and the canonical manifest is capped at 1 MiB (`mcp.rs`) | Manifest integrity is unchanged: no schema validation of the `result.tools` shape was found, so an arbitrary result shape within the caps can be canonicalized and recorded. No operator marking of MCP servers as trusted or untrusted | ~~Add explicit response-body byte cap~~ **shipped** (#117). Remaining: schema-validate `result.tools`; optional per-server trust marking | Log canonical size + JSON depth; alert on outliers | medium | medium | **medium** (unchanged): transport and resource exposure reduced by PR #117 and ADR-0016; the manifest-integrity residual is open | @@ -184,7 +185,7 @@ flowchart LR | `crates/agenticd/src/commit.rs` | `execute` orchestrates the 2PC; peer-UID tagging lives here (ADR-0012, shipped); a signed attestation field would too | TM-003 | | `crates/agenticd/src/limits.rs` | Per-UID connection and rate admission control, bounded commit queue (issue #118) | TM-004 | | `crates/agenticd/src/state_dir.rs` (PR #152, merged) and `docs/integration/executor-sidecar.md` | Startup ownership and mode checks on daemon state; sidecar volume layout | TM-012, TM-007 | -| `crates/agenticd/src/rollback/mod.rs` + `migrate.rs` | `approval_gate` (only for `accept_data_loss=true`, single-use tokens), reverse migration outer-tx (A8); plain rollback is ungated | TM-002 | +| `crates/agenticd/src/rollback/mod.rs` + `migrate.rs` | `approval_gate` (for `accept_data_loss=true` and for rollbacks that run reverse migrations, ADR-0019; single-use tokens), reverse migration outer-tx (A8); a rollback with no schema change is ungated | TM-002 | | `crates/agenticd/src/rollback/writeback.rs` | Path-traversal defense surface: preflight, symlink refusal, private temp directory (PR #150); Unicode normalization gap and write-time swap race remain | TM-008 | | `crates/agenticd/src/mcp.rs` (`fingerprint_one`) | Untrusted response parsing; body, depth and manifest caps, redirect refusal and URL policy shipped (PR #117, ADR-0016); no `result.tools` shape check | TM-005, TM-006 | | `crates/agentic-core/src/gcs_store.rs` | Bearer token handling, GCS request authorization; address collision and overwrite behavior (PR #151 merged, ADR-0018) | TM-007, TM-011 | @@ -204,7 +205,7 @@ flowchart LR **Done** — shipped 2026-05-21 ([ADR-0012](docs/adr/0012-socket-peer-authentication.md), `864b5c3`), later hardened by issue #118 admission control; residual is per-operation authz and daemon-signed attestation. - Rows TM-004 and TM-005 were reconciled on 2026-11-20: per-UID admission control and a global commit queue bound (issue #118, `limits.rs`) and the MCP transport and resource controls (PR #117, [ADR-0016](docs/adr/0016-mcp-url-policy.md)) shipped. Residual for TM-004 is shared queue saturation and visibility; for TM-005 it is manifest integrity (no `result.tools` shape validation). -- **Open decision (owner not yet assigned):** per-operation authorization on the socket. TM-001 and TM-002 are reopened because an allowlisted UID can call every `Request` variant, and a plain rollback runs without an approval token. +- **Open decision (owner not yet assigned):** per-operation authorization on the socket. TM-001 and TM-002 are reopened because an allowlisted UID can call every `Request` variant, while a rollback with no schema change runs without an approval token (ADR-0019 gates the reverse-migration case). - TM-007 stays open in substance: PR #152 added an opt-in file credential path (`AGENTIC_GCS_TOKEN_FILE`, `--postgres-url-file`) and Debug redaction for `GcsObjectStore` and `MemoryBackendSpec` only. The env and argv exposure is removed only for credentials supplied through those file options. The daemon has no workload-identity support, and [ADR-0015](docs/adr/0015-gcs-workload-identity.md) (Proposed) would keep the sidecar inside the shared Cloud Run identity, so identity isolation from a co-located worker remains open. From 379ee4d18fefc847b4eae783c24ef4c1844acc7f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:19:15 +0200 Subject: [PATCH 02/10] Require the approval token for rollbacks that run reverse migrations Once the rollback plan is known and before any side effect, a non-dry-run rollback with at least one reverse migration passes the ADR-0014 gate, whether or not accept_data_loss is set. A request that already passed the gate for accept_data_loss is not checked twice, so one token is consumed once. Dry runs report that approval is required and still verify a supplied token without consuming it. The audit event gains a reason field so alerts can tell the two triggers apart. agenticd uses .agentic/approval.key when --approval-key-file is absent, with the same mode check. The agentic CLI resolves the target and attaches a token when it can read the key, so operator commands do not change. The demo creates a key and starts the daemon with --allowed-uid, because a token binds to a peer uid. Tests cover refusal before side effects, single use, the missing-key message, no-schema-change rollbacks, key discovery and the CLI attaching a token. --- Cargo.lock | 2 + crates/agentic-cli/Cargo.toml | 6 + crates/agentic-cli/src/main.rs | 145 ++++++++-- crates/agentic-cli/tests/rollback_token.rs | 158 +++++++++++ crates/agenticd/src/main.rs | 51 +++- crates/agenticd/src/rollback/mod.rs | 110 ++++++-- .../agenticd/tests/approval_key_discovery.rs | 148 +++++++++++ crates/agenticd/tests/rollback_in_memory.rs | 250 +++++++++++++++++- examples/langgraph-rollback/README.md | 12 +- .../langgraph-rollback/scripts/run-demo.sh | 13 +- 10 files changed, 844 insertions(+), 51 deletions(-) create mode 100644 crates/agentic-cli/tests/rollback_token.rs create mode 100644 crates/agenticd/tests/approval_key_discovery.rs diff --git a/Cargo.lock b/Cargo.lock index 198b90d8..ba8fd7ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,8 +10,10 @@ dependencies = [ "agentic-proto", "anyhow", "clap", + "libc", "serde", "serde_json", + "tempfile", "tokio", "tracing", "tracing-subscriber", diff --git a/crates/agentic-cli/Cargo.toml b/crates/agentic-cli/Cargo.toml index 87476642..edeb48a7 100644 --- a/crates/agentic-cli/Cargo.toml +++ b/crates/agentic-cli/Cargo.toml @@ -22,3 +22,9 @@ serde_json.workspace = true anyhow.workspace = true tracing.workspace = true tracing-subscriber.workspace = true + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[dev-dependencies] +tempfile = "3.10" diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index 62a85c42..ecf6f489 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -135,9 +135,11 @@ enum Command { /// migrations whose reverse loses data between snapshot and now. #[arg(long)] accept_data_loss: bool, - /// Operator approval token authorizing an `--accept-data-loss` - /// rollback (ADR-0014). Obtained out-of-band from an operator via - /// the `--approval` issuance mode. + /// Operator approval token for a rollback that needs one + /// (`--accept-data-loss` per ADR-0014, or one that runs reverse + /// migrations per ADR-0019). Optional: when omitted, the CLI mints + /// a token itself if it can read the approval key (`--key-file`, + /// else `/.agentic/approval.key`). #[arg(long)] approval_token: Option, /// Issuance mode: mint an approval token for this commit hash and @@ -148,7 +150,8 @@ enum Command { /// Worker UID the minted token is bound to (issuance mode). #[arg(long)] uid: Option, - /// Path to the 32-byte approval key (issuance mode). + /// Path to the 32-byte approval key. Used by the issuance mode and + /// to attach a token to a rollback automatically (ADR-0019). #[arg(long)] key_file: Option, }, @@ -195,6 +198,13 @@ async fn main() -> anyhow::Result<()> { } let target = target .ok_or_else(|| anyhow!("rollback requires a target ref (or use --approval)"))?; + // The daemon only demands a token for some rollbacks; sending one + // that is not needed is harmless, so attach it whenever the key + // is readable. + let approval_token = match approval_token { + Some(t) => Some(t), + None => auto_approval_token(&repo, &target, key_file).await?, + }; cmd_rollback( &repo, target, @@ -209,8 +219,26 @@ async fn main() -> anyhow::Result<()> { } } -/// ADR-0014 operator token issuer. Reads the 32-byte key, mints a token -/// bound to `(commit_hash, uid, now)`, prints it to stdout. Does not +/// Mint an approval token bound to `(commit_hash, uid, now)` from the +/// 32-byte key at `key_file`. +fn mint_token(key_file: &Path, commit_hash: &str, uid: u32) -> anyhow::Result { + let bytes = std::fs::read(key_file) + .with_context(|| format!("reading approval key {}", key_file.display()))?; + let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes) + .with_context(|| format!("approval key {} is malformed", key_file.display()))?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .map_err(|_| anyhow!("system clock is before the Unix epoch"))?; + Ok(agentic_core::approval::generate_token( + &key, + commit_hash, + uid, + now, + )) +} + +/// ADR-0014 operator token issuer. Prints a token to stdout. Does not /// require the daemon. fn cmd_mint_approval( commit_hash: &str, @@ -219,19 +247,62 @@ fn cmd_mint_approval( ) -> anyhow::Result<()> { let uid = uid.ok_or_else(|| anyhow!("--approval requires --uid "))?; let key_file = key_file.ok_or_else(|| anyhow!("--approval requires --key-file "))?; - let bytes = std::fs::read(&key_file) - .with_context(|| format!("reading approval key {}", key_file.display()))?; - let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes) - .with_context(|| format!("approval key {} is malformed", key_file.display()))?; - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .map_err(|_| anyhow!("system clock is before the Unix epoch"))?; - let token = agentic_core::approval::generate_token(&key, commit_hash, uid, now); - println!("{token}"); + println!("{}", mint_token(&key_file, commit_hash, uid)?); Ok(()) } +/// The key a rollback mints its own token from (ADR-0019 Decision 4): the +/// `--key-file` flag, else `/.agentic/approval.key` when it exists. +fn rollback_key_path(repo: &Path, key_file: Option) -> Option { + key_file.or_else(|| { + let default = repo.join(".agentic").join("approval.key"); + default.exists().then_some(default) + }) +} + +/// The caller's effective uid, which the daemon reads from the socket peer +/// credentials and binds the token to. +#[cfg(unix)] +fn current_uid() -> u32 { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() } +} + +#[cfg(not(unix))] +fn current_uid() -> u32 { + 0 +} + +/// Resolve `target` to the commit hash the daemon will gate on, then mint +/// a token for it. `None` when no approval key is available. +async fn auto_approval_token( + repo: &Path, + target: &str, + key_file: Option, +) -> anyhow::Result> { + let Some(key_file) = rollback_key_path(repo, key_file) else { + return Ok(None); + }; + let hash = match round_trip( + repo, + Request::ResolveRef { + name: target.to_string(), + }, + ) + .await? + { + Response::ResolveRef { hash } => hash, + Response::Error { + class, + code, + message, + retryable, + } => return Err(daemon_error(class, &code, &message, retryable)), + other => return Err(anyhow!("unexpected response: {other:?}")), + }; + mint_token(&key_file, &hash, current_uid()).map(Some) +} + async fn cmd_rollback( repo: &Path, target: String, @@ -605,3 +676,45 @@ fn read_git_head(repo: &Path) -> anyhow::Result { } Ok(String::from_utf8(output.stdout)?.trim().to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rollback_key_path_prefers_flag_then_default_file() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(rollback_key_path(dir.path(), None), None); + let flag = PathBuf::from("/elsewhere/k"); + assert_eq!( + rollback_key_path(dir.path(), Some(flag.clone())), + Some(flag.clone()) + ); + std::fs::create_dir(dir.path().join(".agentic")).unwrap(); + let default = dir.path().join(".agentic/approval.key"); + std::fs::write(&default, [7u8; 32]).unwrap(); + assert_eq!(rollback_key_path(dir.path(), None), Some(default)); + assert_eq!( + rollback_key_path(dir.path(), Some(flag.clone())), + Some(flag) + ); + } + + #[test] + fn minted_token_verifies_for_the_commit_and_uid() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("approval.key"); + std::fs::write(&path, [7u8; 32]).unwrap(); + let hash = "ab".repeat(32); + let token = mint_token(&path, &hash, 1234).unwrap(); + let key = agentic_core::approval::ApprovalKey::from_bytes(&[7u8; 32]).unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + agentic_core::approval::verify_token(&key, &hash, 1234, &token, now).unwrap(); + assert!(agentic_core::approval::verify_token(&key, &hash, 1235, &token, now).is_err()); + std::fs::write(&path, [7u8; 5]).unwrap(); + assert!(mint_token(&path, &hash, 1234).is_err()); + } +} diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs new file mode 100644 index 00000000..8c429c19 --- /dev/null +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -0,0 +1,158 @@ +//! ADR-0019 Decision 4: `agentic rollback` attaches an approval token on its +//! own when it can read the approval key. The CLI binary runs against a fake +//! daemon that answers `ResolveRef` and records every `Rollback` request. +#![cfg(unix)] + +use std::path::Path; +use std::process::Command; +use std::sync::{Arc, Mutex}; + +use agentic_core::approval::{verify_token, ApprovalKey}; +use agentic_proto::framing::{read_frame, write_frame}; +use agentic_proto::{Envelope, Request, Response, RollbackOutput}; +use tokio::net::UnixListener; + +const KEY: [u8; 32] = [9u8; 32]; + +fn target_hash() -> String { + "ab".repeat(32) +} + +type Seen = Arc>>>; + +/// Serve forever on `sock` in a background thread; returns the approval +/// tokens (one entry per `Rollback` request) the CLI sent. +fn fake_daemon(sock: &Path) -> Seen { + let seen: Seen = Arc::default(); + let recorded = Arc::clone(&seen); + let sock = sock.to_path_buf(); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + rt.block_on(async move { + let listener = UnixListener::bind(&sock).unwrap(); + ready_tx.send(()).unwrap(); + loop { + let (mut s, _) = listener.accept().await.unwrap(); + let (r, w) = s.split(); + let mut r = tokio::io::BufReader::new(r); + let mut w = tokio::io::BufWriter::new(w); + let Some(env): Option> = read_frame(&mut r).await.unwrap() else { + continue; + }; + let reply = match env.payload { + Request::ResolveRef { .. } => Response::ResolveRef { + hash: target_hash(), + }, + Request::Rollback { approval_token, .. } => { + recorded.lock().unwrap().push(approval_token); + Response::Rollback(RollbackOutput { + planned_steps: Vec::new(), + executed: true, + new_head_hash: Some(target_hash()), + }) + } + other => panic!("unexpected request {other:?}"), + }; + write_frame(&mut w, &Envelope::new(env.correlation_id, reply)) + .await + .unwrap(); + } + }); + }); + ready_rx.recv().unwrap(); + seen +} + +struct Fixture { + repo: tempfile::TempDir, + sock_dir: tempfile::TempDir, + seen: Seen, +} + +fn fixture() -> Fixture { + let repo = tempfile::tempdir().unwrap(); + std::fs::create_dir(repo.path().join(".agentic")).unwrap(); + let sock_dir = tempfile::Builder::new() + .prefix("agc") + .tempdir_in("/tmp") + .unwrap(); + let seen = fake_daemon(&sock_dir.path().join("d.sock")); + Fixture { + repo, + sock_dir, + seen, + } +} + +fn run_rollback(f: &Fixture, extra: &[&str]) { + let out = Command::new(env!("CARGO_BIN_EXE_agentic")) + .arg("--repo") + .arg(f.repo.path()) + .args(["rollback", "main", "--yes"]) + .args(extra) + .env("AGENTIC_SOCKET", f.sock_dir.path().join("d.sock")) + .output() + .unwrap(); + assert!( + out.status.success(), + "agentic rollback failed: {}", + String::from_utf8_lossy(&out.stderr) + ); +} + +fn euid() -> u32 { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() } +} + +fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() +} + +#[test] +fn attaches_a_token_from_the_default_key_file() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + run_rollback(&f, &[]); + + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + let token = seen[0].as_deref().expect("token must be attached"); + let key = ApprovalKey::from_bytes(&KEY).unwrap(); + verify_token(&key, &target_hash(), euid(), token, now()) + .expect("token must verify for the resolved commit and the caller's uid"); +} + +#[test] +fn attaches_a_token_from_the_key_file_flag() { + let f = fixture(); + let key_path = f.repo.path().join("custom.key"); + std::fs::write(&key_path, KEY).unwrap(); + run_rollback(&f, &["--key-file", key_path.to_str().unwrap()]); + assert!(f.seen.lock().unwrap()[0].is_some()); +} + +#[test] +fn sends_no_token_without_a_key() { + let f = fixture(); + run_rollback(&f, &[]); + assert_eq!(*f.seen.lock().unwrap(), vec![None]); +} + +#[test] +fn explicit_token_is_not_replaced() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + run_rollback(&f, &["--approval-token", "1:deadbeef"]); + assert_eq!( + *f.seen.lock().unwrap(), + vec![Some("1:deadbeef".to_string())] + ); +} diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index 867f207b..a2fc3f6c 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -135,9 +135,11 @@ struct Args { #[arg(long = "scanner-exempt-entropy-prefix", default_values_t = vec!["__langgraph__/".to_string()])] scanner_exempt_entropy_prefixes: Vec, - /// Path to the 32-byte operator approval key for destructive rollback - /// (ADR-0014). Without it, every `accept_data_loss = true` rollback is - /// rejected fail-closed. If the flag is passed but the file exists and + /// Path to the 32-byte operator approval key (ADR-0014, ADR-0019). + /// Without a key, every `accept_data_loss = true` rollback and every + /// rollback that runs reverse migrations is rejected fail-closed. + /// Default: `/.agentic/approval.key` when that file exists. + /// If a key path is configured but the file exists and /// is readable yet is not exactly 32 bytes, the daemon aborts startup /// (an operator who configured a key but got it wrong should find out /// loudly); an absent, unreadable, or empty file leaves the daemon @@ -177,6 +179,20 @@ struct Args { write_idle_secs: u64, } +/// The approval key path: the explicit flag, else `/approval.key` +/// when that file exists (ADR-0019 Decision 3). `Path::exists` follows +/// symlinks, so a dangling link counts as absent. +fn approval_key_path( + explicit: Option<&std::path::Path>, + agentic_dir: &std::path::Path, +) -> Option { + if let Some(p) = explicit { + return Some(p.to_path_buf()); + } + let default = agentic_dir.join("approval.key"); + default.exists().then_some(default) +} + /// Load the ADR-0014 approval key per Decisions 4 and 6. /// /// Reconciliation of the two decisions, keeping the abort case narrow so a @@ -463,7 +479,9 @@ async fn main() -> anyhow::Result<()> { // ADR-0014: load the approval key (or fail-closed None) BEFORE binding // the socket, so a malformed key aborts startup before accepting work. - let approval_key = load_approval_key(args.approval_key_file.as_deref())?; + let approval_key = load_approval_key( + approval_key_path(args.approval_key_file.as_deref(), &agentic_dir).as_deref(), + )?; let peer_auth = Arc::new(peer_auth); let state = Arc::new( @@ -638,7 +656,30 @@ async fn main() -> anyhow::Result<()> { #[cfg(test)] mod tests { - use super::{load_approval_key, validate_exempt_prefixes}; + use super::{approval_key_path, load_approval_key, validate_exempt_prefixes}; + + // ADR-0019 Decision 3: the flag wins; otherwise the default file is used + // only when it exists. + #[test] + fn approval_key_path_discovers_the_default_file() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(approval_key_path(None, dir.path()), None); + let explicit = std::path::Path::new("/elsewhere/k"); + assert_eq!( + approval_key_path(Some(explicit), dir.path()), + Some(explicit.to_path_buf()) + ); + std::fs::write(dir.path().join("approval.key"), [7u8; 32]).unwrap(); + assert_eq!( + approval_key_path(None, dir.path()), + Some(dir.path().join("approval.key")) + ); + // The flag still wins over an existing default. + assert_eq!( + approval_key_path(Some(explicit), dir.path()), + Some(explicit.to_path_buf()) + ); + } #[cfg(unix)] #[test] diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index 10cf2b83..f6a448b1 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -56,14 +56,34 @@ pub struct RollbackArgs { pub target: String, pub dry_run: bool, pub accept_data_loss: bool, - /// Operator approval token for the ADR-0014 destructive-rollback gate. - /// Only consulted when `accept_data_loss` is `true`. + /// Operator approval token for the ADR-0014 gate. Consulted when + /// `accept_data_loss` is `true` or when the plan runs reverse + /// migrations (ADR-0019). pub approval_token: Option, /// Filesystem root of the repo (where `prompts/` lives). pub repo: PathBuf, } -/// Rejection from the ADR-0014 destructive-rollback approval gate. Every +/// Why a rollback must pass the approval gate. Carried on every audit event +/// as `reason` so alerts can tell the two apart. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum GateReason { + /// `accept_data_loss = true` (ADR-0014). + AcceptDataLoss, + /// The plan runs at least one reverse migration (ADR-0019). + ReverseMigration, +} + +impl GateReason { + fn as_str(self) -> &'static str { + match self { + GateReason::AcceptDataLoss => "accept_data_loss", + GateReason::ReverseMigration => "reverse_migration", + } + } +} + +/// Rejection from the ADR-0014 / ADR-0019 approval gate. Every /// variant maps to a `RollbackForcedDataLoss` audit `decision` (emitted by /// [`approval_gate`] before the error is returned) and is classified on the /// wire as non-retryable `Validation` — the caller must obtain a valid @@ -71,22 +91,24 @@ pub struct RollbackArgs { #[derive(Debug, thiserror::Error)] pub enum ApprovalError { #[error( - "accept_data_loss=true requires an operator approval token (ADR-0014), but this \ - daemon has no --approval-key-file configured — failing closed. Destructive rollback \ - is unavailable until an approval key is provisioned." + "this rollback requires an operator approval token (accept_data_loss=true per \ + ADR-0014, or a reverse schema migration per ADR-0019), but this daemon has no \ + approval key configured — failing closed. Start agenticd with \ + --approval-key-file (or place a 32-byte key at /.agentic/approval.key)." )] KeyNotConfigured, #[error( - "accept_data_loss=true cannot be authorized because the connection has no attested \ + "this rollback requires an operator approval token, but the connection has no attested \ peer UID (the daemon is running with --insecure-allow-any-uid). An approval token \ - binds to a specific worker UID (ADR-0014 Decision 2), so destructive rollback is \ - refused in this mode." + binds to a specific peer UID (ADR-0014 Decision 2), so the rollback is refused in \ + this mode. Run agenticd with --allowed-uid instead." )] NoPeerUid, #[error( - "accept_data_loss=true requires an approval_token, but none was supplied (ADR-0014). \ - Have the operator mint one with `agentic rollback --approval --uid \ - --key-file `." + "this rollback requires an approval_token (accept_data_loss=true per ADR-0014, or a \ + reverse schema migration per ADR-0019), but none was supplied. The `agentic` CLI \ + attaches one automatically when it can read the approval key; otherwise mint one \ + with `agentic rollback --approval --uid --key-file `." )] TokenRequired, #[error("approval token rejected: {0}")] @@ -117,17 +139,20 @@ fn token_prefix_for_audit(token: &str) -> String { hmac_part.chars().take(8).collect() } -/// Emit the ADR-0014 Decision 5 audit event for one `accept_data_loss=true` -/// attempt. Fires on EVERY branch — accepted and every rejection — so an +/// Emit the ADR-0014 Decision 5 audit event for one gated rollback attempt. +/// Fires on EVERY branch — accepted and every rejection — so an /// attacker probing for the gate shows up and operators can alert on /// `decision = "rejected_*"` rates. `warn` for rejections, `info` for the -/// accepted path. +/// accepted path. `reason` (ADR-0019) says which gate fired, so an alert on +/// forced data loss can exclude the routine reverse-migration approvals. fn audit_forced_data_loss( peer_uid: Option, target_commit_hash: &str, decision: &str, token: Option<&str>, + reason: GateReason, ) { + let reason = reason.as_str(); let token_prefix = token.map(token_prefix_for_audit); if decision == "accepted" { tracing::info!( @@ -137,6 +162,7 @@ fn audit_forced_data_loss( ?peer_uid, target_commit_hash, decision, + reason, ?token_prefix, ); } else { @@ -147,15 +173,16 @@ fn audit_forced_data_loss( ?peer_uid, target_commit_hash, decision, + reason, ?token_prefix, ); } } -/// The ADR-0014 approval gate. Called only when `accept_data_loss == true`, -/// before any object-store or Postgres work and before the dry-run branch, -/// so a rejected request has zero side effects. Emits exactly one audit -/// event and returns `Ok(())` only when a valid token is present. +/// The ADR-0014 approval gate, also used for reverse migrations (ADR-0019). +/// Called before any side effect, so a rejected request has zero side +/// effects. Emits exactly one audit event and returns `Ok(())` only when a +/// valid token is present. /// /// A token is single-use for non-dry-run rollbacks: the decoded HMAC tag is /// recorded in `state.used_approval_tokens` and a second use is rejected as @@ -168,10 +195,17 @@ fn approval_gate( peer_uid: Option, approval_token: Option<&str>, dry_run: bool, + reason: GateReason, ) -> Result<(), ApprovalError> { let commit_hash = target_hash.to_hex(); // lowercase 64-hex (Decision 2) let reject = |err: ApprovalError| -> ApprovalError { - audit_forced_data_loss(peer_uid, &commit_hash, err.audit_decision(), approval_token); + audit_forced_data_loss( + peer_uid, + &commit_hash, + err.audit_decision(), + approval_token, + reason, + ); err }; @@ -211,7 +245,7 @@ fn approval_gate( } } // (e) Valid — audit the accepted path too. - audit_forced_data_loss(peer_uid, &commit_hash, "accepted", approval_token); + audit_forced_data_loss(peer_uid, &commit_hash, "accepted", approval_token, reason); Ok(()) } @@ -240,8 +274,11 @@ pub async fn execute( // ADR-0014 destructive-rollback approval gate. Evaluated before any // object-store or Postgres work and before the dry-run branch, so a - // rejected request has zero side effects. Only destructive rollbacks - // (`accept_data_loss = true`) pass through it. + // rejected request has zero side effects. `accept_data_loss = true` + // passes through it here; a plain rollback that runs reverse migrations + // passes through it below, once the plan is known (ADR-0019). `gated` + // stops the second check from consuming the same single-use token twice. + let mut gated = false; if args.accept_data_loss { approval_gate( &state, @@ -249,8 +286,10 @@ pub async fn execute( peer_uid, args.approval_token.as_deref(), args.dry_run, + GateReason::AcceptDataLoss, ) .map_err(anyhow::Error::new)?; + gated = true; } let target = load_commit(&state, &target_hash)?; @@ -344,6 +383,31 @@ pub async fn execute( plan.push(format!( "reverse schema migrations: {live_schema} → {target_schema}" )); + // ADR-0019: a rollback that runs reverse migrations needs the + // approval token whether or not accept_data_loss is set. Nothing + // above this point has a side effect. A dry run without a token + // only reports the requirement; a supplied token is still + // verified (and, being a dry run, not consumed). + if !migration_names.is_empty() && !gated { + if args.dry_run { + plan.push( + "operator approval token required: this rollback runs reverse \ + migrations (ADR-0019)" + .into(), + ); + } + if !args.dry_run || args.approval_token.is_some() { + approval_gate( + &state, + &target_hash, + peer_uid, + args.approval_token.as_deref(), + args.dry_run, + GateReason::ReverseMigration, + ) + .map_err(anyhow::Error::new)?; + } + } // Phase 2: synchronous filesystem I/O — no adapter call in // flight. `accept_data_loss` is forwarded so // `check_irreversible` can honor the operator's opt-in for diff --git a/crates/agenticd/tests/approval_key_discovery.rs b/crates/agenticd/tests/approval_key_discovery.rs new file mode 100644 index 00000000..574c79d4 --- /dev/null +++ b/crates/agenticd/tests/approval_key_discovery.rs @@ -0,0 +1,148 @@ +//! ADR-0019 Decision 3: without `--approval-key-file`, the daemon uses +//! `/.agentic/approval.key` when that file exists, with the same mode +//! check as an explicit key. Runs the real daemon binary and talks to it over +//! its socket. +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use agentic_proto::framing::{read_frame, write_frame}; +use agentic_proto::{CommitInput, Envelope, Request, Response}; +use tokio::net::UnixStream; + +fn uid() -> u32 { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() } +} + +fn write_key(repo: &std::path::Path, mode: u32) { + let state = repo.join(".agentic"); + std::fs::create_dir_all(&state).unwrap(); + let key = state.join("approval.key"); + std::fs::write(&key, [5u8; 32]).unwrap(); + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(mode)).unwrap(); +} + +fn spawn_daemon(repo: &std::path::Path, sock: &std::path::Path) -> Child { + Command::new(env!("CARGO_BIN_EXE_agenticd")) + .arg("--repo") + .arg(repo) + .arg("--socket") + .arg(sock) + .arg("--allowed-uid") + .arg(uid().to_string()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn agenticd") +} + +async fn send(sock: &std::path::Path, request: Request) -> Response { + let conn = UnixStream::connect(sock).await.unwrap(); + let (r, w) = conn.into_split(); + let mut r = tokio::io::BufReader::new(r); + let mut w = tokio::io::BufWriter::new(w); + write_frame(&mut w, &Envelope::new("t", request)) + .await + .unwrap(); + let reply: Envelope = read_frame(&mut r).await.unwrap().expect("reply"); + reply.payload +} + +/// Commit once, then send `Rollback { accept_data_loss: true }` with no +/// token. Which error comes back says whether the daemon holds a key. +async fn rollback_error_code(repo: &std::path::Path) -> String { + let sock_dir = tempfile::Builder::new() + .prefix("agd") + .tempdir_in("/tmp") + .unwrap(); + let sock = sock_dir.path().join("d.sock"); + let mut child = spawn_daemon(repo, &sock); + let deadline = Instant::now() + Duration::from_secs(20); + while !sock.exists() && Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(sock.exists(), "daemon did not bind its socket"); + + let Response::Commit(c) = send( + &sock, + Request::Commit(CommitInput { + message: "c".into(), + author: None, + code_sha: None, + branch: None, + prompts: Default::default(), + mcp_servers: Vec::new(), + model: None, + no_memory: true, + }), + ) + .await + else { + panic!("commit failed"); + }; + let reply = send( + &sock, + Request::Rollback { + target: c.commit_hash, + dry_run: true, + accept_data_loss: true, + approval_token: None, + }, + ) + .await; + let _ = child.kill(); + let _ = child.wait(); + match reply { + Response::Error { code, .. } => code, + other => panic!("expected an approval error, got {other:?}"), + } +} + +#[tokio::test] +async fn default_key_file_is_picked_up() { + let repo = tempfile::tempdir().unwrap(); + write_key(repo.path(), 0o600); + assert_eq!(rollback_error_code(repo.path()).await, "approval_required"); +} + +#[tokio::test] +async fn no_key_file_means_no_key() { + let repo = tempfile::tempdir().unwrap(); + assert_eq!( + rollback_error_code(repo.path()).await, + "approval_key_not_configured" + ); +} + +#[test] +fn group_or_other_readable_default_key_aborts_startup() { + let repo = tempfile::tempdir().unwrap(); + write_key(repo.path(), 0o644); + let sock_dir = tempfile::Builder::new() + .prefix("agd") + .tempdir_in("/tmp") + .unwrap(); + let mut child = spawn_daemon(repo.path(), &sock_dir.path().join("d.sock")); + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + if let Some(st) = child.try_wait().unwrap() { + break Some(st); + } + if Instant::now() > deadline { + break None; + } + std::thread::sleep(Duration::from_millis(50)); + }; + if status.is_none() { + let _ = child.kill(); + } + let out = child.wait_with_output().unwrap(); + assert!( + status.is_some_and(|s| !s.success()), + "daemon should refuse to start with a 0644 default key" + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("chmod 600"), "stderr: {stderr}"); +} diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 47de6443..582e0bd4 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -73,7 +73,9 @@ async fn rollback_reverses_schema_and_restores_memory_in_memory_backend() { .build() .unwrap(), peer_auth: Arc::new(agenticd::peer_auth::PeerAuthPolicy::InsecureAllowAny), - approval_key: None, + // ADR-0019: a rollback that runs reverse migrations needs an + // operator approval token. + approval_key: Some(test_key()), used_approval_tokens: Default::default(), limits: agenticd::limits::LimitsConfig::default(), rate: agenticd::limits::RateLimiter::new( @@ -95,6 +97,7 @@ async fn rollback_reverses_schema_and_restores_memory_in_memory_backend() { .await .expect("baseline commit with memory should succeed"); let baseline_ref = baseline.commit_hash.clone(); + let token = generate_token(&test_key(), &baseline_ref, 1000, now_secs()); // -- Act 1: contaminate — bump schema and dirty the data. ------------ adapter.apply_migration("002_bump").await; @@ -123,10 +126,10 @@ async fn rollback_reverses_schema_and_restores_memory_in_memory_backend() { target: baseline_ref, dry_run: false, accept_data_loss: false, - approval_token: None, + approval_token: Some(token), repo: repo_root.clone(), }, - None, + Some(1000), ) .await .expect("rollback against InMemoryAdapter should succeed"); @@ -876,3 +879,244 @@ async fn rollback_refuses_legacy_ambiguous_blob_before_any_side_effect() { assert!(!state.repo_root.join("prompts").exists()); } } + +// --------------------------------------------------------------------------- +// ADR-0019: a rollback that runs reverse migrations passes the approval gate +// whether or not accept_data_loss is set. +// --------------------------------------------------------------------------- + +/// Bump the schema, dirty the data and provide the down.sql, so a rollback to +/// the baseline has a reverse migration to run. +async fn contaminate(state: &DaemonState, adapter: &InMemoryAdapter) { + adapter.apply_migration("002_bump").await; + adapter + .insert_rows( + "messages", + vec![serde_json::json!({"id": 99, "body": "bad"})], + ) + .await; + let schema_dir = state.refs.agentic_dir().join("schema"); + std::fs::create_dir_all(&schema_dir).unwrap(); + std::fs::write(schema_dir.join("002_bump.down.sql"), "-- no-op\n").unwrap(); +} + +fn plain_args( + state: &DaemonState, + target: &str, + token: Option, + dry_run: bool, +) -> RollbackArgs { + RollbackArgs { + target: target.to_string(), + dry_run, + accept_data_loss: false, + approval_token: token, + repo: state.repo_root.clone(), + } +} + +/// Nothing a rollback touches has changed: schema, memory, branch tip. +async fn assert_untouched( + state: &DaemonState, + adapter: &InMemoryAdapter, + tip: Option, +) { + assert_eq!(adapter.current_schema_version().await.unwrap(), "002_bump"); + let rows = adapter.rows_of("messages").await; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0]["body"], "bad"); + assert_eq!(state.refs.read_branch("main").unwrap(), tip); +} + +#[tokio::test] +async fn reverse_migration_rollback_without_token_is_refused_before_side_effects() { + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tip = state.refs.read_branch("main").unwrap(); + let err = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, None, false), + Some(1000), + ) + .await + .expect_err("a plain reverse-migration rollback needs a token"); + assert!(matches!( + downcast_approval(&err), + ApprovalError::TokenRequired + )); + assert_untouched(&state, &adapter, tip).await; + assert!( + !state.repo_root.join("prompts").exists(), + "prompts must not be written back" + ); +} + +#[tokio::test] +async fn reverse_migration_rollback_with_wrong_uid_or_no_peer_is_refused() { + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tip = state.refs.read_branch("main").unwrap(); + let tok = generate_token(&test_key(), &baseline, 2000, now_secs()); + let err = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok.clone()), false), + Some(1000), + ) + .await + .expect_err("token for another uid must be refused"); + assert!(matches!( + downcast_approval(&err), + ApprovalError::Rejected(agentic_core::approval::ApprovalRejection::InvalidSignature) + )); + let err = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + None, + ) + .await + .expect_err("no attested peer uid must be refused"); + assert!(matches!(downcast_approval(&err), ApprovalError::NoPeerUid)); + assert_untouched(&state, &adapter, tip).await; +} + +#[tokio::test] +async fn reverse_migration_rollback_with_valid_token_succeeds_once() { + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok.clone()), false), + Some(1000), + ) + .await + .expect("valid token lets the rollback run"); + assert!(out.executed); + assert_eq!(adapter.current_schema_version().await.unwrap(), "001_init"); + + // Single use: with the schema bumped again, the same token is a replay. + contaminate(&state, &adapter).await; + let tip = state.refs.read_branch("main").unwrap(); + let err = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + Some(1000), + ) + .await + .expect_err("second use must be refused"); + assert!(is_replayed(&err), "got: {err:#}"); + assert_untouched(&state, &adapter, tip).await; +} + +#[tokio::test] +async fn reverse_migration_rollback_without_a_key_names_the_flag() { + let (state, adapter, baseline, _dir) = setup_gate_state(false).await; + contaminate(&state, &adapter).await; + let tip = state.refs.read_branch("main").unwrap(); + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + let err = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + Some(1000), + ) + .await + .expect_err("no key configured must refuse"); + assert!(matches!( + downcast_approval(&err), + ApprovalError::KeyNotConfigured + )); + assert!( + format!("{err:#}").contains("--approval-key-file"), + "message must name the flag: {err:#}" + ); + assert_untouched(&state, &adapter, tip).await; +} + +#[tokio::test] +async fn rollback_without_schema_change_needs_no_token() { + // Key configured and no key configured: both run with no token. + for with_key in [true, false] { + let (state, _adapter, baseline, _dir) = setup_gate_state(with_key).await; + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, None, false), + Some(1000), + ) + .await + .expect("no reverse migration, no approval needed"); + assert!(out.executed); + } +} + +#[tokio::test] +async fn reverse_migration_dry_run_reports_approval_and_verifies_a_supplied_token() { + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tip = state.refs.read_branch("main").unwrap(); + + // No token: the plan says approval is required; nothing is refused. + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, None, true), + Some(1000), + ) + .await + .expect("a dry run without a token reports the requirement"); + assert!(!out.executed); + assert!( + out.planned_steps + .iter() + .any(|s| s.contains("approval token required")), + "plan: {:?}", + out.planned_steps + ); + + // A bad token is still verified on a dry run. + let bad = generate_token(&test_key(), &baseline, 2000, now_secs()); + rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(bad), true), + Some(1000), + ) + .await + .expect_err("a supplied token is verified on a dry run"); + + // A good token is verified but not consumed. + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + for _ in 0..2 { + rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok.clone()), true), + Some(1000), + ) + .await + .expect("dry run with a valid token"); + } + assert_untouched(&state, &adapter, tip).await; + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + Some(1000), + ) + .await + .expect("the token survived the dry runs"); + assert!(out.executed); +} + +#[tokio::test] +async fn accept_data_loss_with_reverse_migration_consumes_one_token_once() { + // Both gates apply; the single token must not be checked (and consumed) + // twice within one request. + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + let out = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok)), + Some(1000), + ) + .await + .expect("one token covers accept_data_loss plus reverse migrations"); + assert!(out.executed); + assert_eq!(state.used_approval_tokens.lock().unwrap().len(), 1); +} diff --git a/examples/langgraph-rollback/README.md b/examples/langgraph-rollback/README.md index f3191568..31f093e3 100644 --- a/examples/langgraph-rollback/README.md +++ b/examples/langgraph-rollback/README.md @@ -43,7 +43,8 @@ The script: 1. brings up Postgres + pgvector via `podman compose` or `docker compose` (auto-detected; override with `CONTAINER_RUNTIME=docker|podman`), 2. seeds 5 baseline `episodes` rows, -3. builds `agenticd` and `agentic`, starts the daemon bound to this +3. builds `agenticd` and `agentic`, creates `.agentic/approval.key` (the + operator approval key, see below), starts the daemon bound to this directory with `--postgres … --tables episodes:id`, 4. asks the agent *"I'm thinking about cancelling my subscription."* — gets an empathetic answer, @@ -93,7 +94,11 @@ history reflects the rollback action rather than rewriting it. NULL` column added in v0.8 and reverse-migrated on rollback; that requires the reverse SQL migration runner which is the next planned ADR-0002 §5 follow-up. Today the demo exercises prompts + memory - rollback only. + rollback only. A rollback that does run reverse migrations needs an + operator approval token ([ADR-0019](../../docs/adr/0019-approval-for-reverse-migration-rollback.md)). + The daemon reads `.agentic/approval.key` and the `agentic` CLI mints + the token from the same file, so `agentic rollback` is typed the same + way; a socket client without the key cannot run reverse migrations. - **Compose covers the database only.** `docker-compose.yml` starts Postgres + pgvector. `agenticd` and the Python agent are built and run locally by `scripts/run-demo.sh` — they are not containerised. @@ -136,7 +141,8 @@ cd ../.. && cargo build --release -p agenticd -p agentic-cli && cd examples/lang # 3. Seed baseline + start daemon psql 'postgres://agentic:agentic@localhost:54322/agentic' -f seed.sql ../../target/release/agentic --repo . init -../../target/release/agenticd --repo . \ +( umask 077 && head -c 32 /dev/urandom > .agentic/approval.key ) +../../target/release/agenticd --repo . --allowed-uid "$(id -u)" \ --postgres 'postgres://agentic:agentic@localhost:54322/agentic' \ --tables episodes:id & diff --git a/examples/langgraph-rollback/scripts/run-demo.sh b/examples/langgraph-rollback/scripts/run-demo.sh index 1e042761..39df5682 100755 --- a/examples/langgraph-rollback/scripts/run-demo.sh +++ b/examples/langgraph-rollback/scripts/run-demo.sh @@ -108,9 +108,20 @@ rm -rf "${DEMO_DIR}/.agentic" # agenticd refuses a repo or .agentic that is group- or world-writable. # A checkout or `init` under umask 002 creates them 0775. chmod go-w "${DEMO_DIR}" "${DEMO_DIR}/.agentic" +# The rollback in step 10 reverses a schema migration, which needs an +# operator approval token (ADR-0019). The daemon reads this key and the +# `agentic` CLI mints the token from it, so the visible commands stay the +# same. The key must be 0600 or the daemon refuses to start. +APPROVAL_KEY="${DEMO_DIR}/.agentic/approval.key" +if [[ ! -f "${APPROVAL_KEY}" ]]; then + ( umask 077 && head -c 32 /dev/urandom > "${APPROVAL_KEY}" ) + chmod 600 "${APPROVAL_KEY}" +fi +# A token binds to the caller's uid, so the daemon must attest peers: +# --allowed-uid, not --insecure-allow-any-uid. "${AGENTICD_BIN}" --repo "${DEMO_DIR}" --postgres "${DATABASE_URL}" --tables episodes:id \ --socket "${AGENTIC_SOCKET}" \ - --insecure-allow-any-uid \ + --allowed-uid "$(id -u)" \ > "${DEMO_DIR}/.agentic/daemon.log" 2>&1 & DAEMON_PID=$! From 49da59968178a3bcffff5878a4d6779cd3d79f95 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:22:55 +0200 Subject: [PATCH 03/10] Send no approval token when the default key file is unusable An empty or wrong-length .agentic/approval.key leaves the daemon running without a key, so agentic rollback no longer fails on it for rollbacks that need no token. A key named with --key-file stays a hard error. --- crates/agentic-cli/src/main.rs | 13 ++++++++++- crates/agentic-cli/tests/rollback_token.rs | 27 +++++++++++++++++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index ecf6f489..d04c5cff 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -280,6 +280,7 @@ async fn auto_approval_token( target: &str, key_file: Option, ) -> anyhow::Result> { + let explicit = key_file.is_some(); let Some(key_file) = rollback_key_path(repo, key_file) else { return Ok(None); }; @@ -300,7 +301,17 @@ async fn auto_approval_token( } => return Err(daemon_error(class, &code, &message, retryable)), other => return Err(anyhow!("unexpected response: {other:?}")), }; - mint_token(&key_file, &hash, current_uid()).map(Some) + match mint_token(&key_file, &hash, current_uid()) { + Ok(token) => Ok(Some(token)), + // A key the operator named must work. An unusable default file + // (empty, wrong length) leaves the daemon keyless too, so send no + // token and let the daemon decide whether one is needed. + Err(e) if !explicit => { + tracing::warn!("not attaching an approval token: {e:#}"); + Ok(None) + } + Err(e) => Err(e), + } } async fn cmd_rollback( diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index 8c429c19..4d38fa9e 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -88,15 +88,19 @@ fn fixture() -> Fixture { } } -fn run_rollback(f: &Fixture, extra: &[&str]) { - let out = Command::new(env!("CARGO_BIN_EXE_agentic")) +fn rollback_cmd(f: &Fixture, extra: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_agentic")) .arg("--repo") .arg(f.repo.path()) .args(["rollback", "main", "--yes"]) .args(extra) .env("AGENTIC_SOCKET", f.sock_dir.path().join("d.sock")) .output() - .unwrap(); + .unwrap() +} + +fn run_rollback(f: &Fixture, extra: &[&str]) { + let out = rollback_cmd(f, extra); assert!( out.status.success(), "agentic rollback failed: {}", @@ -156,3 +160,20 @@ fn explicit_token_is_not_replaced() { vec![Some("1:deadbeef".to_string())] ); } + +#[test] +fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { + let f = fixture(); + // Wrong length: the daemon would run keyless, so the CLI must not fail. + std::fs::write(f.repo.path().join(".agentic/approval.key"), [1u8; 5]).unwrap(); + run_rollback(&f, &[]); + assert_eq!(*f.seen.lock().unwrap(), vec![None]); + + let bad = f.repo.path().join(".agentic/approval.key"); + let out = rollback_cmd(&f, &["--key-file", bad.to_str().unwrap()]); + assert!( + !out.status.success(), + "an explicit bad key must be an error" + ); + assert_eq!(f.seen.lock().unwrap().len(), 1, "no second request sent"); +} From c522a44cf7d465536d0450660ef5a3aea24d5cea Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:44:43 +0200 Subject: [PATCH 04/10] Pin and late-mint the CLI approval token, and check down migrations first The CLI now sends the resolved commit hash, not the ref name, in both the preview and the applied rollback, so the token, the preview and the applied commit name the same commit. It refuses to sign a resolved hash that is not 64 lowercase hex characters. An auto-minted token goes only on the confirmed, non-dry-run request and is minted after confirmation. A destructive preview still gets its own short-lived token, because the daemon refuses it without one. A token the user supplies is passed through unchanged. The unusable-default-key warning goes to stderr so --json output stays parseable. The daemon loads the down-migration files before the approval gate, so a missing or IRREVERSIBLE file is refused before the token is consumed and before an accepted audit event. The key-discovery tests create the state dir with mode 0700 so they pass under umask 002. Fix two comments: an unusable default key aborts daemon startup when the length is wrong, and the demo's step 10 has no schema change today. --- crates/agentic-cli/src/main.rs | 147 ++++++++++---- crates/agentic-cli/tests/rollback_token.rs | 189 ++++++++++++++++-- crates/agenticd/src/rollback/mod.rs | 24 ++- .../agenticd/tests/approval_key_discovery.rs | 15 +- crates/agenticd/tests/rollback_in_memory.rs | 48 +++++ ...approval-for-reverse-migration-rollback.md | 25 ++- .../langgraph-rollback/scripts/run-demo.sh | 7 +- 7 files changed, 376 insertions(+), 79 deletions(-) diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index d04c5cff..02b93046 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -198,46 +198,53 @@ async fn main() -> anyhow::Result<()> { } let target = target .ok_or_else(|| anyhow!("rollback requires a target ref (or use --approval)"))?; - // The daemon only demands a token for some rollbacks; sending one - // that is not needed is harmless, so attach it whenever the key - // is readable. - let approval_token = match approval_token { - Some(t) => Some(t), - None => auto_approval_token(&repo, &target, key_file).await?, - }; cmd_rollback( &repo, - target, - dry_run, - yes, - accept_data_loss, - approval_token, - cli.json, + RollbackOpts { + target, + dry_run, + yes, + accept_data_loss, + approval_token, + key_file, + json: cli.json, + }, ) .await } } } -/// Mint an approval token bound to `(commit_hash, uid, now)` from the -/// 32-byte key at `key_file`. -fn mint_token(key_file: &Path, commit_hash: &str, uid: u32) -> anyhow::Result { +fn read_key(key_file: &Path) -> anyhow::Result { let bytes = std::fs::read(key_file) .with_context(|| format!("reading approval key {}", key_file.display()))?; - let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes) - .with_context(|| format!("approval key {} is malformed", key_file.display()))?; + agentic_core::approval::ApprovalKey::from_bytes(&bytes) + .with_context(|| format!("approval key {} is malformed", key_file.display())) +} + +/// Mint an approval token bound to `(commit_hash, uid, now)`. +fn mint_with_key( + key: &agentic_core::approval::ApprovalKey, + commit_hash: &str, + uid: u32, +) -> anyhow::Result { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .map_err(|_| anyhow!("system clock is before the Unix epoch"))?; Ok(agentic_core::approval::generate_token( - &key, + key, commit_hash, uid, now, )) } +/// Mint a token from the 32-byte key at `key_file`. +fn mint_token(key_file: &Path, commit_hash: &str, uid: u32) -> anyhow::Result { + mint_with_key(&read_key(key_file)?, commit_hash, uid) +} + /// ADR-0014 operator token issuer. Prints a token to stdout. Does not /// require the daemon. fn cmd_mint_approval( @@ -273,17 +280,39 @@ fn current_uid() -> u32 { 0 } -/// Resolve `target` to the commit hash the daemon will gate on, then mint -/// a token for it. `None` when no approval key is available. -async fn auto_approval_token( +/// The key a rollback mints its own tokens from, if there is a usable one. +/// A key the operator named with `--key-file` must work, so a bad one is an +/// error. A default file the CLI cannot use (empty or the wrong length) gets +/// a warning on stderr and no token: the daemon runs keyless on an empty +/// file and refuses to start on a wrong-length one, so there is nothing a +/// token could do. The warning goes to stderr so `--json` stdout stays +/// parseable. +fn load_rollback_key( repo: &Path, - target: &str, key_file: Option, -) -> anyhow::Result> { +) -> anyhow::Result> { let explicit = key_file.is_some(); - let Some(key_file) = rollback_key_path(repo, key_file) else { + let Some(path) = rollback_key_path(repo, key_file) else { return Ok(None); }; + match read_key(&path) { + Ok(key) => Ok(Some(key)), + Err(e) if !explicit => { + eprintln!("warning: not attaching an approval token: {e:#}"); + Ok(None) + } + Err(e) => Err(e), + } +} + +/// A commit hash the CLI is willing to sign: exactly 64 lowercase hex +/// characters. The CLI signs whatever the daemon returns, so check it. +fn is_signable_hash(hash: &str) -> bool { + hash.len() == 64 && hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +/// Resolve `target` to the commit hash the daemon will gate on. +async fn resolve_pinned_hash(repo: &Path, target: &str) -> anyhow::Result { let hash = match round_trip( repo, Request::ResolveRef { @@ -301,28 +330,59 @@ async fn auto_approval_token( } => return Err(daemon_error(class, &code, &message, retryable)), other => return Err(anyhow!("unexpected response: {other:?}")), }; - match mint_token(&key_file, &hash, current_uid()) { - Ok(token) => Ok(Some(token)), - // A key the operator named must work. An unusable default file - // (empty, wrong length) leaves the daemon keyless too, so send no - // token and let the daemon decide whether one is needed. - Err(e) if !explicit => { - tracing::warn!("not attaching an approval token: {e:#}"); - Ok(None) - } - Err(e) => Err(e), + if !is_signable_hash(&hash) { + return Err(anyhow!( + "daemon resolved {target:?} to {hash:?}, which is not a 64-character lowercase hex \ + commit hash; refusing to sign an approval token for it" + )); } + Ok(hash) } -async fn cmd_rollback( - repo: &Path, +struct RollbackOpts { target: String, dry_run: bool, yes: bool, accept_data_loss: bool, + /// Token the user supplied. Passed through unchanged. approval_token: Option, + key_file: Option, json: bool, -) -> anyhow::Result<()> { +} + +async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { + let RollbackOpts { + target, + dry_run, + yes, + accept_data_loss, + approval_token, + key_file, + json, + } = o; + // ADR-0019 Decision 4. With no user-supplied token and a usable key, pin + // the target to the resolved commit hash so the token, the preview and + // the applied rollback all name the same commit, even if a branch moves. + let key = if approval_token.is_none() { + load_rollback_key(repo, key_file)? + } else { + None + }; + let target = if key.is_some() { + resolve_pinned_hash(repo, &target).await? + } else { + target + }; + let mint = + |key: &agentic_core::approval::ApprovalKey| mint_with_key(key, &target, current_uid()); + // A preview is a dry run, which verifies a token without consuming it. + // It carries only a token the user supplied, except that a destructive + // preview is refused without one, so it gets its own short-lived mint. + let preview_token = match (&approval_token, &key) { + (Some(t), _) => Some(t.clone()), + (None, Some(k)) if accept_data_loss => Some(mint(k)?), + _ => None, + }; if !dry_run && !yes { // First show the plan, then confirm. let plan = match round_trip( @@ -331,7 +391,7 @@ async fn cmd_rollback( target: target.clone(), dry_run: true, accept_data_loss, - approval_token: approval_token.clone(), + approval_token: preview_token, }, ) .await? @@ -359,6 +419,15 @@ async fn cmd_rollback( } } + // An auto-minted token goes only on the confirmed, non-dry-run request, + // minted now so the time spent at the prompt does not eat its window. + let approval_token = match (approval_token, &key) { + (Some(t), _) => Some(t), + // With --dry-run there is no later request, so this one is the + // preview and follows the preview rule above. + (None, Some(k)) if !dry_run || accept_data_loss => Some(mint(k)?), + _ => None, + }; let resp = round_trip( repo, Request::Rollback { diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index 4d38fa9e..1b169ba4 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -18,11 +18,19 @@ fn target_hash() -> String { "ab".repeat(32) } -type Seen = Arc>>>; +/// One `Rollback` request as the fake daemon saw it. +#[derive(Debug, PartialEq)] +struct Seen1 { + target: String, + dry_run: bool, + token: Option, +} + +type Seen = Arc>>; -/// Serve forever on `sock` in a background thread; returns the approval -/// tokens (one entry per `Rollback` request) the CLI sent. -fn fake_daemon(sock: &Path) -> Seen { +/// Serve forever on `sock` in a background thread, answering `ResolveRef` +/// with `resolved`; returns every `Rollback` request the CLI sent. +fn fake_daemon(sock: &Path, resolved: String) -> Seen { let seen: Seen = Arc::default(); let recorded = Arc::clone(&seen); let sock = sock.to_path_buf(); @@ -45,10 +53,19 @@ fn fake_daemon(sock: &Path) -> Seen { }; let reply = match env.payload { Request::ResolveRef { .. } => Response::ResolveRef { - hash: target_hash(), + hash: resolved.clone(), }, - Request::Rollback { approval_token, .. } => { - recorded.lock().unwrap().push(approval_token); + Request::Rollback { + target, + dry_run, + approval_token, + .. + } => { + recorded.lock().unwrap().push(Seen1 { + target, + dry_run, + token: approval_token, + }); Response::Rollback(RollbackOutput { planned_steps: Vec::new(), executed: true, @@ -74,13 +91,17 @@ struct Fixture { } fn fixture() -> Fixture { + fixture_resolving(target_hash()) +} + +fn fixture_resolving(resolved: String) -> Fixture { let repo = tempfile::tempdir().unwrap(); std::fs::create_dir(repo.path().join(".agentic")).unwrap(); let sock_dir = tempfile::Builder::new() .prefix("agc") .tempdir_in("/tmp") .unwrap(); - let seen = fake_daemon(&sock_dir.path().join("d.sock")); + let seen = fake_daemon(&sock_dir.path().join("d.sock"), resolved); Fixture { repo, sock_dir, @@ -88,15 +109,34 @@ fn fixture() -> Fixture { } } -fn rollback_cmd(f: &Fixture, extra: &[&str]) -> std::process::Output { - Command::new(env!("CARGO_BIN_EXE_agentic")) +/// Run `agentic rollback main` with `args`, answering the confirmation +/// prompt (when there is one) with `stdin`. +fn agentic(f: &Fixture, args: &[&str], stdin: &str) -> std::process::Output { + use std::io::Write; + use std::process::Stdio; + let mut child = Command::new(env!("CARGO_BIN_EXE_agentic")) .arg("--repo") .arg(f.repo.path()) - .args(["rollback", "main", "--yes"]) - .args(extra) + .args(args) .env("AGENTIC_SOCKET", f.sock_dir.path().join("d.sock")) - .output() + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() .unwrap() + .write_all(stdin.as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() +} + +fn rollback_cmd(f: &Fixture, extra: &[&str]) -> std::process::Output { + let mut args = vec!["rollback", "main", "--yes"]; + args.extend_from_slice(extra); + agentic(f, &args, "") } fn run_rollback(f: &Fixture, extra: &[&str]) { @@ -128,7 +168,7 @@ fn attaches_a_token_from_the_default_key_file() { let seen = f.seen.lock().unwrap(); assert_eq!(seen.len(), 1); - let token = seen[0].as_deref().expect("token must be attached"); + let token = seen[0].token.as_deref().expect("token must be attached"); let key = ApprovalKey::from_bytes(&KEY).unwrap(); verify_token(&key, &target_hash(), euid(), token, now()) .expect("token must verify for the resolved commit and the caller's uid"); @@ -140,14 +180,20 @@ fn attaches_a_token_from_the_key_file_flag() { let key_path = f.repo.path().join("custom.key"); std::fs::write(&key_path, KEY).unwrap(); run_rollback(&f, &["--key-file", key_path.to_str().unwrap()]); - assert!(f.seen.lock().unwrap()[0].is_some()); + assert!(f.seen.lock().unwrap()[0].token.is_some()); } #[test] fn sends_no_token_without_a_key() { let f = fixture(); run_rollback(&f, &[]); - assert_eq!(*f.seen.lock().unwrap(), vec![None]); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].token, None); + assert_eq!( + seen[0].target, "main", + "no key: the target is sent as given" + ); } #[test] @@ -155,9 +201,12 @@ fn explicit_token_is_not_replaced() { let f = fixture(); std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); run_rollback(&f, &["--approval-token", "1:deadbeef"]); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].token.as_deref(), Some("1:deadbeef")); assert_eq!( - *f.seen.lock().unwrap(), - vec![Some("1:deadbeef".to_string())] + seen[0].target, "main", + "a user token leaves the target alone" ); } @@ -167,7 +216,7 @@ fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { // Wrong length: the daemon would run keyless, so the CLI must not fail. std::fs::write(f.repo.path().join(".agentic/approval.key"), [1u8; 5]).unwrap(); run_rollback(&f, &[]); - assert_eq!(*f.seen.lock().unwrap(), vec![None]); + assert_eq!(f.seen.lock().unwrap()[0].token, None); let bad = f.repo.path().join(".agentic/approval.key"); let out = rollback_cmd(&f, &["--key-file", bad.to_str().unwrap()]); @@ -177,3 +226,105 @@ fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { ); assert_eq!(f.seen.lock().unwrap().len(), 1, "no second request sent"); } + +#[test] +fn preview_and_applied_rollback_name_the_pinned_hash_and_only_the_applied_one_is_signed() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + // No --yes: preview, then confirm. + let out = agentic(&f, &["rollback", "main"], "y\n"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "preview then apply: {seen:?}"); + let (preview, applied) = (&seen[0], &seen[1]); + assert!(preview.dry_run && !applied.dry_run); + assert_eq!(preview.target, target_hash(), "preview must be pinned"); + assert_eq!(applied.target, target_hash(), "apply must be pinned"); + assert_eq!(preview.token, None, "a preview carries no auto token"); + let key = ApprovalKey::from_bytes(&KEY).unwrap(); + verify_token( + &key, + &applied.target, + euid(), + applied.token.as_deref().expect("applied request is signed"), + now(), + ) + .unwrap(); +} + +#[test] +fn destructive_preview_gets_its_own_token_and_the_apply_is_minted_fresh() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + let out = agentic(&f, &["rollback", "main", "--accept-data-loss"], "y\n"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let seen = f.seen.lock().unwrap(); + assert!(seen[0].dry_run && seen[0].token.is_some()); + assert!(!seen[1].dry_run && seen[1].token.is_some()); +} + +#[test] +fn declining_the_prompt_sends_no_signed_apply() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + let out = agentic(&f, &["rollback", "main"], "n\n"); + assert!(!out.status.success()); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + assert!(seen[0].dry_run && seen[0].token.is_none()); +} + +#[test] +fn dry_run_flag_carries_no_auto_token() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + run_rollback(&f, &["--dry-run"]); + let seen = f.seen.lock().unwrap(); + assert!(seen[0].dry_run); + assert_eq!(seen[0].token, None); +} + +#[test] +fn refuses_to_sign_a_resolved_hash_that_is_not_64_lowercase_hex() { + for bad in [ + "AB".repeat(32), + "ab".repeat(31), + format!("{}:x", "ab".repeat(31)), + "ab".repeat(32) + "\n", + ] { + let f = fixture_resolving(bad.clone()); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + let out = rollback_cmd(&f, &[]); + assert!(!out.status.success(), "{bad:?} must be refused"); + assert!( + String::from_utf8_lossy(&out.stderr).contains("refusing to sign"), + "{bad:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(f.seen.lock().unwrap().is_empty(), "nothing is sent"); + } +} + +#[test] +fn key_warning_goes_to_stderr_and_json_stdout_stays_parseable() { + let f = fixture(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), [1u8; 5]).unwrap(); + let out = agentic(&f, &["--json", "rollback", "main", "--yes"], ""); + assert!(out.status.success()); + serde_json::from_slice::(&out.stdout).unwrap_or_else(|e| { + panic!( + "stdout is not JSON ({e}): {}", + String::from_utf8_lossy(&out.stdout) + ) + }); + assert!(String::from_utf8_lossy(&out.stderr).contains("warning")); +} diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index f6a448b1..62afc236 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -383,6 +383,20 @@ pub async fn execute( plan.push(format!( "reverse schema migrations: {live_schema} → {target_schema}" )); + // Phase 2: synchronous filesystem I/O — no adapter call in + // flight. `accept_data_loss` is forwarded so + // `check_irreversible` can honor the operator's opt-in for + // IRREVERSIBLE-marked migrations. Read-only, and ahead of the + // approval gate so a missing or IRREVERSIBLE `.down.sql` is + // refused before a single-use token is consumed and before an + // `accepted` audit event. + let steps = migrate::load_steps( + state.refs.agentic_dir(), + &migration_names, + args.accept_data_loss, + ) + .context("loading reverse migration files")?; + // ADR-0019: a rollback that runs reverse migrations needs the // approval token whether or not accept_data_loss is set. Nothing // above this point has a side effect. A dry run without a token @@ -408,16 +422,6 @@ pub async fn execute( .map_err(anyhow::Error::new)?; } } - // Phase 2: synchronous filesystem I/O — no adapter call in - // flight. `accept_data_loss` is forwarded so - // `check_irreversible` can honor the operator's opt-in for - // IRREVERSIBLE-marked migrations. - let steps = migrate::load_steps( - state.refs.agentic_dir(), - &migration_names, - args.accept_data_loss, - ) - .context("loading reverse migration files")?; // Phase 3: execute — atomic inside the backend. if !args.dry_run { diff --git a/crates/agenticd/tests/approval_key_discovery.rs b/crates/agenticd/tests/approval_key_discovery.rs index 574c79d4..e6f2bf4b 100644 --- a/crates/agenticd/tests/approval_key_discovery.rs +++ b/crates/agenticd/tests/approval_key_discovery.rs @@ -17,10 +17,20 @@ fn uid() -> u32 { unsafe { libc::geteuid() } } -fn write_key(repo: &std::path::Path, mode: u32) { +/// Create the state dir the way an operator would: the daemon refuses a +/// group-writable repo or state dir, and `create_dir_all` follows the umask +/// (0775 under umask 002), so pin both to 0700. +fn state_dir(repo: &std::path::Path) -> std::path::PathBuf { let state = repo.join(".agentic"); std::fs::create_dir_all(&state).unwrap(); - let key = state.join("approval.key"); + for dir in [repo, state.as_path()] { + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + state +} + +fn write_key(repo: &std::path::Path, mode: u32) { + let key = state_dir(repo).join("approval.key"); std::fs::write(&key, [5u8; 32]).unwrap(); std::fs::set_permissions(&key, std::fs::Permissions::from_mode(mode)).unwrap(); } @@ -110,6 +120,7 @@ async fn default_key_file_is_picked_up() { #[tokio::test] async fn no_key_file_means_no_key() { let repo = tempfile::tempdir().unwrap(); + state_dir(repo.path()); assert_eq!( rollback_error_code(repo.path()).await, "approval_key_not_configured" diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 582e0bd4..45558988 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -1120,3 +1120,51 @@ async fn accept_data_loss_with_reverse_migration_consumes_one_token_once() { assert!(out.executed); assert_eq!(state.used_approval_tokens.lock().unwrap().len(), 1); } + +#[tokio::test] +async fn refused_down_migration_load_does_not_consume_the_token() { + // The down.sql is checked before the gate, so a missing or IRREVERSIBLE + // file is refused with the token unspent. + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let down = state.refs.agentic_dir().join("schema/002_bump.down.sql"); + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + let tip = state.refs.read_branch("main").unwrap(); + + for (what, contents, expect) in [ + ( + "irreversible", + Some("-- IRREVERSIBLE\nDROP TABLE t;\n"), + "IRREVERSIBLE", + ), + ("missing", None, "002_bump"), + ] { + match contents { + Some(c) => std::fs::write(&down, c).unwrap(), + None => std::fs::remove_file(&down).unwrap(), + } + let err = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok.clone()), false), + Some(1000), + ) + .await + .expect_err("an unloadable down migration must refuse the rollback"); + assert!(format!("{err:#}").contains(expect), "{what}: {err:#}"); + assert!( + state.used_approval_tokens.lock().unwrap().is_empty(), + "{what}: the token must not be consumed" + ); + assert_untouched(&state, &adapter, tip).await; + } + + // With the file fixed, the same token still works. + std::fs::write(&down, "-- no-op\n").unwrap(); + rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + Some(1000), + ) + .await + .expect("the unspent token authorizes the corrected rollback"); +} diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md index d7d86ce4..f6d9efa3 100644 --- a/docs/adr/0019-approval-for-reverse-migration-rollback.md +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -39,6 +39,7 @@ If so, and the request is not a dry run, the request passes the same gate as an The token format, the HMAC binding to the target commit and the peer UID, the five-minute window and the single-use ledger are the ADR-0014 ones, unchanged. The gate runs before any side effect. +The down-migration files are loaded (read-only) just before it, so a missing or `IRREVERSIBLE` file is refused before a token is consumed or an `accepted` audit event is written. The code that builds the plan only reads: it resolves the ref, loads the target, checks the prompts tree and queries the backend for the live schema version and the pending migration names. The gate sits right after that, before the reverse migrations run, the memory restore, the prompts write-back and the forward-record. A refused request changes nothing. @@ -91,12 +92,24 @@ An empty or unreadable file leaves the daemon running without a key. `agentic rollback` looks for a key: the `--key-file` flag if given, else `/.agentic/approval.key` if that file exists. The flag already exists for token issuance (`--approval`), and the rollback command reuses it. -If it finds a key, it resolves the target ref to a commit hash with a `ResolveRef` request and mints a token for that hash and the CLI process's effective UID, which is the UID the daemon reads from the socket. -It attaches the token to the rollback request, to the preview request and to the real one, so the operator is not asked for anything. -A token passed explicitly with `--approval-token` is sent as given. -If the CLI finds no key, it sends no token, and the daemon decides whether one is needed. - -The CLI sends the token whenever it has a key, not only when a reverse migration is coming. +A key named with `--key-file` must work, or the command fails. +A default file the CLI cannot use, empty or the wrong length, gets a warning on stderr and no token. +The warning goes to stderr so `--json` output stays parseable. +(The daemon runs keyless on an empty file and refuses to start on a wrong-length one.) + +If it has a key and the user supplied no token, the CLI pins the target. +It resolves the ref with a `ResolveRef` request, refuses a result that is not exactly 64 lowercase hex characters, and sends that hash, not the ref name, in both the preview and the applied request. +The token, the preview and the applied commit therefore name the same commit, even if a branch moves in between. + +Tokens are minted as late as possible. +The preview, which is a dry run, carries no auto-minted token. +After the operator confirms, the CLI mints a fresh token for the pinned hash and the CLI process's effective UID, which is the UID the daemon reads from the socket, and attaches it to the applied request only. +A `--dry-run` request carries none either. +The one exception is a destructive preview (`--accept-data-loss`): the daemon refuses that without a token before it reaches the dry-run branch, so the preview gets its own freshly minted token, which a dry run does not consume. +A token passed explicitly with `--approval-token` is sent as given, on both requests, and the target is left as typed. +If the CLI finds no usable key, it sends no token, and the daemon decides whether one is needed. + +The CLI mints whenever it has a key, not only when a reverse migration is coming. The daemon ignores a token it does not need. A token is consumed only when the gate passes on a non-dry-run request. diff --git a/examples/langgraph-rollback/scripts/run-demo.sh b/examples/langgraph-rollback/scripts/run-demo.sh index 39df5682..efd2b4fc 100755 --- a/examples/langgraph-rollback/scripts/run-demo.sh +++ b/examples/langgraph-rollback/scripts/run-demo.sh @@ -108,10 +108,11 @@ rm -rf "${DEMO_DIR}/.agentic" # agenticd refuses a repo or .agentic that is group- or world-writable. # A checkout or `init` under umask 002 creates them 0775. chmod go-w "${DEMO_DIR}" "${DEMO_DIR}/.agentic" -# The rollback in step 10 reverses a schema migration, which needs an -# operator approval token (ADR-0019). The daemon reads this key and the +# Operator approval key (ADR-0019). A rollback that reverses a schema +# migration needs an approval token; the daemon reads this key and the # `agentic` CLI mints the token from it, so the visible commands stay the -# same. The key must be 0600 or the daemon refuses to start. +# same. The demo's step 10 rollback has no schema change today and so +# consumes no token. The key must be 0600 or the daemon refuses to start. APPROVAL_KEY="${DEMO_DIR}/.agentic/approval.key" if [[ ! -f "${APPROVAL_KEY}" ]]; then ( umask 077 && head -c 32 /dev/urandom > "${APPROVAL_KEY}" ) From 149e64598cf992463799c3f18806066c064619d4 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:56:45 +0200 Subject: [PATCH 05/10] Sign the CLI rollback only when the preview needed approval The rollback output gains approval_required, set when the plan runs reverse migrations or the request set accept_data_loss. It defaults to false when absent, so older clients and daemons are unaffected. The CLI mints a token for the applied request only if the preview it just got reported approval_required. A forward migration that lands between the preview and the apply is then refused by the daemon's gate and the operator previews again, instead of being reversed under a token minted for a plan nobody saw. With --yes the CLI previews silently, when it holds a key, to read the field. Before sending a minted token the CLI reads the socket peer uid and sends the token only if that uid owns the key file, with a warning on stderr otherwise. The CLI reads at most 33 bytes of the key file, as the daemon does. Add a Postgres-backed test in the reverse_migration suite: commit at schema A, migrate forward to B, refuse the rollback without a token, then reverse to A with a valid one. --- crates/agentic-cli/src/client.rs | 60 +++++++ crates/agentic-cli/src/main.rs | 134 ++++++++++----- crates/agentic-cli/tests/rollback_token.rs | 69 +++++++- crates/agentic-proto/src/lib.rs | 15 ++ crates/agenticd/src/rollback/mod.rs | 8 + crates/agenticd/tests/reverse_migration.rs | 160 ++++++++++++++++++ crates/agenticd/tests/rollback_in_memory.rs | 37 ++++ ...approval-for-reverse-migration-rollback.md | 12 ++ 8 files changed, 447 insertions(+), 48 deletions(-) diff --git a/crates/agentic-cli/src/client.rs b/crates/agentic-cli/src/client.rs index ae8b09e8..af5f8c10 100644 --- a/crates/agentic-cli/src/client.rs +++ b/crates/agentic-cli/src/client.rs @@ -46,10 +46,60 @@ pub fn socket_path(repo: &Path) -> PathBuf { /// Send one request envelope and return the response payload. pub async fn round_trip(repo: &Path, request: Request) -> anyhow::Result { + round_trip_signed(repo, request, None).await +} + +/// An auto-minted approval token and the uid that owns the key it came from. +pub struct AutoToken { + pub token: String, + pub key_owner_uid: u32, +} + +/// Decide whether an auto-minted token may be sent to the server on this +/// connection. The token is a bearer credential for one rollback, so it goes +/// only to a server whose peer uid is the owner of the key it was minted +/// from. Otherwise it is withheld, with a warning on stderr (not stdout, so +/// `--json` stays parseable). `peer` is the connection's peer uid, taken +/// from the kernel (SO_PEERCRED, or getpeereid on macOS). +pub fn token_for_peer( + peer: std::io::Result, + key_owner_uid: u32, + token: String, +) -> Option { + match peer { + Ok(uid) if uid == key_owner_uid => Some(token), + Ok(uid) => { + eprintln!( + "warning: not sending the approval token: the daemon socket is served by uid \ + {uid}, but the approval key belongs to uid {key_owner_uid}" + ); + None + } + Err(e) => { + eprintln!( + "warning: not sending the approval token: could not read the daemon socket's \ + peer uid: {e}" + ); + None + } + } +} + +/// Like [`round_trip`]. If `auto` is given and `request` is a rollback, the +/// token is attached only after the connection's peer uid is checked. +pub async fn round_trip_signed( + repo: &Path, + mut request: Request, + auto: Option, +) -> anyhow::Result { let path = socket_path(repo); let mut sock = UnixStream::connect(&path) .await .with_context(|| format!("connecting to daemon at {}", path.display()))?; + if let (Some(auto), Request::Rollback { approval_token, .. }) = (auto, &mut request) { + let peer = sock.peer_cred().map(|c| c.uid()); + *approval_token = token_for_peer(peer, auto.key_owner_uid, auto.token); + } let envelope = Envelope::new(new_correlation_id(), request); let (read_half, write_half) = sock.split(); let mut reader = tokio::io::BufReader::new(read_half); @@ -80,6 +130,16 @@ fn new_correlation_id() -> String { mod tests { use super::*; + #[test] + fn token_is_sent_only_to_a_peer_owned_by_the_key_owner() { + let t = || "1:ab".to_string(); + assert_eq!(token_for_peer(Ok(501), 501, t()), Some(t())); + assert_eq!(token_for_peer(Ok(0), 501, t()), None); + assert_eq!(token_for_peer(Ok(502), 501, t()), None); + let err = std::io::Error::other("no cred"); + assert_eq!(token_for_peer(Err(err), 501, t()), None); + } + // Both assertions live in one test: AGENTIC_SOCKET is process-global // state and separate parallel tests would race on it. #[test] diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index 02b93046..7d1e7ebb 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -12,7 +12,7 @@ use agentic_proto::{CommitInput, ErrorClass, Request, Response}; use anyhow::{anyhow, Context}; use clap::{Parser, Subcommand}; -use crate::client::{resolve_repo, round_trip}; +use crate::client::{resolve_repo, round_trip, round_trip_signed, AutoToken}; /// Format a structured `Response::Error` as a human-readable error string /// suitable for `anyhow!`. The shape is `[class:code] message`, e.g. @@ -215,11 +215,34 @@ async fn main() -> anyhow::Result<()> { } } -fn read_key(key_file: &Path) -> anyhow::Result { - let bytes = std::fs::read(key_file) - .with_context(|| format!("reading approval key {}", key_file.display()))?; - agentic_core::approval::ApprovalKey::from_bytes(&bytes) - .with_context(|| format!("approval key {} is malformed", key_file.display())) +/// An approval key and the uid that owns its file. +struct LoadedKey { + key: agentic_core::approval::ApprovalKey, + /// Owner of the key file. A token minted from this key is sent only to + /// a daemon socket served by this uid (see `client::token_for_peer`). + owner_uid: u32, +} + +/// Read at most one byte past the key length: enough to reject a +/// wrong-length file, and a default path that points at an endless or huge +/// file cannot exhaust memory (the daemon does the same). +fn read_capped(reader: impl std::io::Read) -> std::io::Result> { + use std::io::Read as _; + let mut bytes = Vec::new(); + let limit = (agentic_core::approval::APPROVAL_KEY_LEN + 1) as u64; + reader.take(limit).read_to_end(&mut bytes)?; + Ok(bytes) +} + +fn read_key(key_file: &Path) -> anyhow::Result { + use std::os::unix::fs::MetadataExt; + let ctx = || format!("reading approval key {}", key_file.display()); + let file = std::fs::File::open(key_file).with_context(ctx)?; + let owner_uid = file.metadata().with_context(ctx)?.uid(); + let bytes = read_capped(&file).with_context(ctx)?; + let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes) + .with_context(|| format!("approval key {} is malformed", key_file.display()))?; + Ok(LoadedKey { key, owner_uid }) } /// Mint an approval token bound to `(commit_hash, uid, now)`. @@ -242,7 +265,7 @@ fn mint_with_key( /// Mint a token from the 32-byte key at `key_file`. fn mint_token(key_file: &Path, commit_hash: &str, uid: u32) -> anyhow::Result { - mint_with_key(&read_key(key_file)?, commit_hash, uid) + mint_with_key(&read_key(key_file)?.key, commit_hash, uid) } /// ADR-0014 operator token issuer. Prints a token to stdout. Does not @@ -287,10 +310,7 @@ fn current_uid() -> u32 { /// file and refuses to start on a wrong-length one, so there is nothing a /// token could do. The warning goes to stderr so `--json` stdout stays /// parseable. -fn load_rollback_key( - repo: &Path, - key_file: Option, -) -> anyhow::Result> { +fn load_rollback_key(repo: &Path, key_file: Option) -> anyhow::Result> { let explicit = key_file.is_some(); let Some(path) = rollback_key_path(repo, key_file) else { return Ok(None); @@ -373,26 +393,36 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { } else { target }; - let mint = - |key: &agentic_core::approval::ApprovalKey| mint_with_key(key, &target, current_uid()); + let auto = |k: &LoadedKey| -> anyhow::Result { + Ok(AutoToken { + token: mint_with_key(&k.key, &target, current_uid())?, + key_owner_uid: k.owner_uid, + }) + }; // A preview is a dry run, which verifies a token without consuming it. // It carries only a token the user supplied, except that a destructive // preview is refused without one, so it gets its own short-lived mint. - let preview_token = match (&approval_token, &key) { - (Some(t), _) => Some(t.clone()), - (None, Some(k)) if accept_data_loss => Some(mint(k)?), + let preview_auto = match &key { + Some(k) if accept_data_loss => Some(auto(k)?), _ => None, }; - if !dry_run && !yes { - // First show the plan, then confirm. - let plan = match round_trip( + // The apply is signed only if the preview reported that this plan needs + // approval. Otherwise a forward migration landing after the preview + // would be reversed under a token minted for a plan nobody saw; the + // daemon's gate refuses it instead and the operator previews again. + // `--yes` shows no plan, but the CLI still previews silently (when it + // holds a key) to learn the flag. + let mut preview_needs_approval = false; + if !dry_run && (!yes || key.is_some()) { + let plan = match round_trip_signed( repo, Request::Rollback { target: target.clone(), dry_run: true, accept_data_loss, - approval_token: preview_token, + approval_token: approval_token.clone(), }, + preview_auto, ) .await? { @@ -405,30 +435,37 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { } => return Err(daemon_error(class, &code, &message, retryable)), other => return Err(anyhow!("unexpected response: {other:?}")), }; - println!("Planned rollback to {target}:"); - for step in &plan.planned_steps { - println!(" - {step}"); - } - eprint!("Proceed? [y/N] "); - use std::io::{BufRead, Write}; - std::io::stderr().flush().ok(); - let mut line = String::new(); - std::io::stdin().lock().read_line(&mut line)?; - if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") { - return Err(anyhow!("rollback aborted by user")); + preview_needs_approval = plan.approval_required; + if !yes { + // Show the plan, then confirm. + println!("Planned rollback to {target}:"); + for step in &plan.planned_steps { + println!(" - {step}"); + } + eprint!("Proceed? [y/N] "); + use std::io::{BufRead, Write}; + std::io::stderr().flush().ok(); + let mut line = String::new(); + std::io::stdin().lock().read_line(&mut line)?; + if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") { + return Err(anyhow!("rollback aborted by user")); + } } } - // An auto-minted token goes only on the confirmed, non-dry-run request, - // minted now so the time spent at the prompt does not eat its window. - let approval_token = match (approval_token, &key) { - (Some(t), _) => Some(t), - // With --dry-run there is no later request, so this one is the - // preview and follows the preview rule above. - (None, Some(k)) if !dry_run || accept_data_loss => Some(mint(k)?), + // An auto-minted token goes only on the confirmed, non-dry-run request + // whose preview said it needs one, minted now so the time spent at the + // prompt does not eat its window. With --dry-run there is no later + // request, so that request is the preview and follows the preview rule. + let apply_auto = match (&approval_token, &key) { + (None, Some(k)) + if (!dry_run && preview_needs_approval) || (dry_run && accept_data_loss) => + { + Some(auto(k)?) + } _ => None, }; - let resp = round_trip( + let resp = round_trip_signed( repo, Request::Rollback { target, @@ -436,6 +473,7 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { accept_data_loss, approval_token, }, + apply_auto, ) .await?; match resp { @@ -761,6 +799,24 @@ fn read_git_head(repo: &Path) -> anyhow::Result { mod tests { use super::*; + /// A reader that never ends and counts what it hands out. + struct Endless(std::cell::Cell); + impl std::io::Read for &Endless { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.0.set(self.0.get() + buf.len()); + buf.fill(1); + Ok(buf.len()) + } + } + + #[test] + fn key_read_stops_one_byte_past_the_key_length() { + let endless = Endless(Default::default()); + let bytes = read_capped(&endless).unwrap(); + assert_eq!(bytes.len(), agentic_core::approval::APPROVAL_KEY_LEN + 1); + assert!(endless.0.get() <= 4096, "read {} bytes", endless.0.get()); + } + #[test] fn rollback_key_path_prefers_flag_then_default_file() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index 1b169ba4..ab372529 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -29,8 +29,8 @@ struct Seen1 { type Seen = Arc>>; /// Serve forever on `sock` in a background thread, answering `ResolveRef` -/// with `resolved`; returns every `Rollback` request the CLI sent. -fn fake_daemon(sock: &Path, resolved: String) -> Seen { +/// with `resolved` and reporting `approval_required = needs_approval`; returns every `Rollback` request the CLI sent. +fn fake_daemon(sock: &Path, resolved: String, needs_approval: bool) -> Seen { let seen: Seen = Arc::default(); let recorded = Arc::clone(&seen); let sock = sock.to_path_buf(); @@ -68,8 +68,9 @@ fn fake_daemon(sock: &Path, resolved: String) -> Seen { }); Response::Rollback(RollbackOutput { planned_steps: Vec::new(), - executed: true, - new_head_hash: Some(target_hash()), + executed: !dry_run, + new_head_hash: (!dry_run).then(target_hash), + approval_required: needs_approval, }) } other => panic!("unexpected request {other:?}"), @@ -95,13 +96,22 @@ fn fixture() -> Fixture { } fn fixture_resolving(resolved: String) -> Fixture { + fixture_with(resolved, true) +} + +/// A daemon whose previews report that the plan needs no approval. +fn fixture_no_approval() -> Fixture { + fixture_with(target_hash(), false) +} + +fn fixture_with(resolved: String, needs_approval: bool) -> Fixture { let repo = tempfile::tempdir().unwrap(); std::fs::create_dir(repo.path().join(".agentic")).unwrap(); let sock_dir = tempfile::Builder::new() .prefix("agc") .tempdir_in("/tmp") .unwrap(); - let seen = fake_daemon(&sock_dir.path().join("d.sock"), resolved); + let seen = fake_daemon(&sock_dir.path().join("d.sock"), resolved, needs_approval); Fixture { repo, sock_dir, @@ -167,8 +177,10 @@ fn attaches_a_token_from_the_default_key_file() { run_rollback(&f, &[]); let seen = f.seen.lock().unwrap(); - assert_eq!(seen.len(), 1); - let token = seen[0].token.as_deref().expect("token must be attached"); + // --yes with a key: a silent preview, then the applied request. + assert_eq!(seen.len(), 2); + assert!(seen[0].dry_run && seen[0].token.is_none()); + let token = seen[1].token.as_deref().expect("token must be attached"); let key = ApprovalKey::from_bytes(&KEY).unwrap(); verify_token(&key, &target_hash(), euid(), token, now()) .expect("token must verify for the resolved commit and the caller's uid"); @@ -180,7 +192,7 @@ fn attaches_a_token_from_the_key_file_flag() { let key_path = f.repo.path().join("custom.key"); std::fs::write(&key_path, KEY).unwrap(); run_rollback(&f, &["--key-file", key_path.to_str().unwrap()]); - assert!(f.seen.lock().unwrap()[0].token.is_some()); + assert!(f.seen.lock().unwrap().last().unwrap().token.is_some()); } #[test] @@ -217,6 +229,7 @@ fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { std::fs::write(f.repo.path().join(".agentic/approval.key"), [1u8; 5]).unwrap(); run_rollback(&f, &[]); assert_eq!(f.seen.lock().unwrap()[0].token, None); + f.seen.lock().unwrap().clear(); let bad = f.repo.path().join(".agentic/approval.key"); let out = rollback_cmd(&f, &["--key-file", bad.to_str().unwrap()]); @@ -224,7 +237,7 @@ fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { !out.status.success(), "an explicit bad key must be an error" ); - assert_eq!(f.seen.lock().unwrap().len(), 1, "no second request sent"); + assert!(f.seen.lock().unwrap().is_empty(), "nothing is sent"); } #[test] @@ -328,3 +341,41 @@ fn key_warning_goes_to_stderr_and_json_stdout_stays_parseable() { }); assert!(String::from_utf8_lossy(&out.stderr).contains("warning")); } + +#[test] +fn apply_is_not_signed_when_the_preview_reported_no_approval_needed() { + // A forward migration could land between the preview and the apply; a + // token minted for a plan that needed none would then authorize a + // reverse migration nobody saw. The daemon's gate refuses it instead. + for extra in [&[][..], &["--yes"][..]] { + let f = fixture_no_approval(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + let mut args = vec!["rollback", "main"]; + args.extend_from_slice(extra); + let out = agentic(&f, &args, "y\n"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "{extra:?}: {seen:?}"); + assert!(seen[0].dry_run && !seen[1].dry_run); + assert_eq!(seen[1].token, None, "{extra:?}: apply must not be signed"); + } +} + +#[test] +fn oversized_default_key_file_is_rejected_without_a_token() { + let f = fixture(); + // Far longer than a key; only the first 33 bytes may be read. + std::fs::write( + f.repo.path().join(".agentic/approval.key"), + vec![7u8; 1 << 20], + ) + .unwrap(); + run_rollback(&f, &[]); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 1, "no key, so no pinning preview: {seen:?}"); + assert_eq!(seen[0].token, None); +} diff --git a/crates/agentic-proto/src/lib.rs b/crates/agentic-proto/src/lib.rs index ae508ad4..3c4a4a9a 100644 --- a/crates/agentic-proto/src/lib.rs +++ b/crates/agentic-proto/src/lib.rs @@ -394,6 +394,12 @@ pub struct RollbackOutput { pub planned_steps: Vec, pub executed: bool, pub new_head_hash: Option, + /// The plan needs an operator approval token: it runs reverse + /// migrations or the request set `accept_data_loss` (ADR-0014, + /// ADR-0019). Additive: older daemons omit it and it reads as `false`, + /// and older clients ignore it. + #[serde(default)] + pub approval_required: bool, } #[cfg(test)] @@ -555,4 +561,13 @@ mod tests { let v1: Request = v0.into(); assert!(matches!(v1, Request::Ping)); } + + #[test] + fn rollback_output_without_approval_required_reads_as_false() { + // A daemon from before ADR-0019 omits the field. + let out: RollbackOutput = + serde_json::from_str(r#"{"planned_steps":[],"executed":false,"new_head_hash":null}"#) + .unwrap(); + assert!(!out.approval_required); + } } diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index 62afc236..b6a6a90a 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -279,6 +279,9 @@ pub async fn execute( // passes through it below, once the plan is known (ADR-0019). `gated` // stops the second check from consuming the same single-use token twice. let mut gated = false; + // Reported to the caller so a client can tell whether a token will be + // needed before it asks for one to be minted. + let mut approval_required = args.accept_data_loss; if args.accept_data_loss { approval_gate( &state, @@ -402,6 +405,9 @@ pub async fn execute( // above this point has a side effect. A dry run without a token // only reports the requirement; a supplied token is still // verified (and, being a dry run, not consumed). + if !migration_names.is_empty() { + approval_required = true; + } if !migration_names.is_empty() && !gated { if args.dry_run { plan.push( @@ -503,6 +509,7 @@ pub async fn execute( planned_steps: plan, executed: false, new_head_hash: None, + approval_required, }); } @@ -540,6 +547,7 @@ pub async fn execute( planned_steps: plan, executed: true, new_head_hash: Some(out.commit_hash.to_hex()), + approval_required, }) } diff --git a/crates/agenticd/tests/reverse_migration.rs b/crates/agenticd/tests/reverse_migration.rs index 57f0ebf3..28429d39 100644 --- a/crates/agenticd/tests/reverse_migration.rs +++ b/crates/agenticd/tests/reverse_migration.rs @@ -366,3 +366,163 @@ async fn ac3c_accept_data_loss_reverses_irreversible_migration() { drop_schema(&admin, &schema).await; } + +// --------------------------------------------------------------------------- +// ADR-0019 — a rollback that runs a reverse migration needs an operator +// approval token, end to end against real Postgres: commit at schema A, +// migrate forward to B, then roll back through `rollback::execute`. +// --------------------------------------------------------------------------- + +#[tokio::test] +#[ignore] +async fn adr_0019_reverse_migration_rollback_needs_a_token_against_postgres() { + use agentic_core::approval::{generate_token, ApprovalKey}; + use agentic_core::refs::Refs; + use agentic_core::ObjectStore; + use agentic_proto::CommitInput; + use agenticd::rollback::{self, ApprovalError, RollbackArgs}; + use agenticd::server::DaemonState; + + let Some(url) = database_url() else { + eprintln!("DATABASE_URL not set — skipping integration test"); + return; + }; + let admin = PgPool::connect(&url).await.expect("admin pool"); + let schema = fresh_schema_name("adr0019"); + admin + .execute(format!("CREATE SCHEMA \"{schema}\"").as_str()) + .await + .unwrap(); + + let dir = TempDir::new().unwrap(); + let agentic_dir = dir.path().join(".agentic"); + std::fs::create_dir_all(agentic_dir.join("objects")).unwrap(); + let store: Arc = + Arc::new(FsObjectStore::open(agentic_dir.join("objects")).unwrap()); + let refs = Refs::open(&agentic_dir).unwrap(); + + let mut adapter = PostgresAdapter::connect( + PgConfig::new(schema_scoped_url(&url, &schema), Vec::new()), + Arc::clone(&store), + ) + .await + .expect("connect adapter"); + adapter.init().await.expect("install helpers"); + // Schema A: one applied migration. + admin + .execute( + format!("INSERT INTO \"{schema}\".agentic_migrations (name) VALUES ('001_a')").as_str(), + ) + .await + .unwrap(); + + let key = ApprovalKey::from_bytes(&[42u8; 32]).unwrap(); + let state = Arc::new( + DaemonState { + repo_root: dir.path().to_path_buf(), + store: Arc::clone(&store), + refs, + commit_lock: Arc::new(tokio::sync::Mutex::new(())), + shutdown: tokio_util::sync::CancellationToken::new(), + memory: Some(Arc::new(adapter)), + mcp_servers: Vec::new(), + http: reqwest::Client::builder() + .user_agent("agenticd-test") + .build() + .unwrap(), + peer_auth: Arc::new(agenticd::peer_auth::PeerAuthPolicy::InsecureAllowAny), + approval_key: None, + used_approval_tokens: Default::default(), + limits: agenticd::limits::LimitsConfig::default(), + rate: agenticd::limits::RateLimiter::new( + agenticd::limits::LimitsConfig::default().rate_per_uid, + ), + commit_slots: Arc::new(tokio::sync::Semaphore::new( + agenticd::limits::LimitsConfig::default().commit_queue_depth, + )), + commit_queue_depth: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + exempt_entropy_prefixes: Vec::new(), + } + .with_approval_key(Some(key)), + ); + + let mut prompts = std::collections::BTreeMap::new(); + prompts.insert("system.md".to_string(), b"you are helpful".to_vec()); + let baseline = agenticd::commit::execute( + Arc::clone(&state), + CommitInput { + message: "schema A".into(), + author: Some("tester".into()), + code_sha: None, + branch: Some("main".into()), + prompts, + mcp_servers: Vec::new(), + model: None, + no_memory: false, + }, + Some(1000), + ) + .await + .expect("baseline commit at schema A") + .commit_hash; + + // Forward migration to schema B, with its down.sql. + admin + .execute(format!("CREATE TABLE \"{schema}\".step_b (id int)").as_str()) + .await + .unwrap(); + admin + .execute( + format!("INSERT INTO \"{schema}\".agentic_migrations (name) VALUES ('002_b')").as_str(), + ) + .await + .unwrap(); + let schema_dir = agentic_dir.join("schema"); + std::fs::create_dir_all(&schema_dir).unwrap(); + std::fs::write(schema_dir.join("002_b.down.sql"), "DROP TABLE step_b;").unwrap(); + + let args = |token: Option| RollbackArgs { + target: baseline.clone(), + dry_run: false, + accept_data_loss: false, + approval_token: token, + repo: dir.path().to_path_buf(), + }; + let tip = state.refs.read_branch("main").unwrap(); + + // (1) No token: refused, and the schema stays at B. + let err = rollback::execute(Arc::clone(&state), args(None), Some(1000)) + .await + .expect_err("a reverse-migration rollback without a token must be refused"); + assert!( + err.chain().any(|e| matches!( + e.downcast_ref::(), + Some(ApprovalError::TokenRequired) + )), + "expected TokenRequired, got: {err:#}" + ); + assert_eq!(migration_row_count(&admin, &schema).await.unwrap(), 2); + assert!(table_exists(&admin, &schema, "step_b").await.unwrap()); + assert_eq!(state.refs.read_branch("main").unwrap(), tip); + + // (2) Valid token: the rollback reverses B to A. + let now = std::time::SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let token = generate_token( + &ApprovalKey::from_bytes(&[42u8; 32]).unwrap(), + &baseline, + 1000, + now, + ); + let out = rollback::execute(Arc::clone(&state), args(Some(token)), Some(1000)) + .await + .expect("a valid token authorizes the reverse migration"); + assert!(out.executed && out.approval_required); + assert_eq!(migration_row_count(&admin, &schema).await.unwrap(), 1); + assert!(!table_exists(&admin, &schema, "step_b").await.unwrap()); + assert_ne!(state.refs.read_branch("main").unwrap(), tip); + + drop_schema(&admin, &schema).await; +} diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 45558988..116a0317 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -1168,3 +1168,40 @@ async fn refused_down_migration_load_does_not_consume_the_token() { .await .expect("the unspent token authorizes the corrected rollback"); } + +#[tokio::test] +async fn plans_report_whether_approval_is_required() { + // Reverse migration in the plan: true, on a dry run with no token. + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, None, true), + Some(1000), + ) + .await + .unwrap(); + assert!(out.approval_required); + + // No schema change and no accept_data_loss: false. + let (state, _adapter, baseline, _dir) = setup_gate_state(true).await; + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, None, true), + Some(1000), + ) + .await + .unwrap(); + assert!(!out.approval_required); + + // accept_data_loss: true, even with no schema change. + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + let out = rollback::execute( + Arc::clone(&state), + dry_run_args(&state, &baseline, tok), + Some(1000), + ) + .await + .unwrap(); + assert!(out.approval_required); +} diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md index f6d9efa3..f1433197 100644 --- a/docs/adr/0019-approval-for-reverse-migration-rollback.md +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -106,6 +106,18 @@ The preview, which is a dry run, carries no auto-minted token. After the operator confirms, the CLI mints a fresh token for the pinned hash and the CLI process's effective UID, which is the UID the daemon reads from the socket, and attaches it to the applied request only. A `--dry-run` request carries none either. The one exception is a destructive preview (`--accept-data-loss`): the daemon refuses that without a token before it reaches the dry-run branch, so the preview gets its own freshly minted token, which a dry run does not consume. +The CLI signs the applied request only if the preview it just got reported that the plan needs approval. +The rollback output carries a new field for this, `approval_required: bool`, set when the plan includes a reverse migration or the request set `accept_data_loss`. +The field is additive: it defaults to `false` when absent, so older daemons and clients are unaffected. +Without this rule, a forward migration that lands between the preview and the apply would be reversed under a token minted for a plan the operator never saw. +With the rule, the daemon's gate refuses that apply and the operator previews again. +With `--yes` no plan is shown, but the CLI still sends the preview request silently, when it holds a key, to read the field. + +The CLI also checks who it is talking to before it sends a minted token. +It reads the connected socket's peer uid from the kernel and sends the token only if that uid owns the key file the token came from. +Otherwise it sends no token and warns on stderr. +It reads at most 33 bytes of the key file, as the daemon does. + A token passed explicitly with `--approval-token` is sent as given, on both requests, and the target is left as typed. If the CLI finds no usable key, it sends no token, and the daemon decides whether one is needed. From 968775a2509f9bc58601c90adf04e34cb63c8c97 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:21:29 +0200 Subject: [PATCH 06/10] Bind approval tokens to a scope and check every CLI request's peer Tokens now carry a scope in the signed input, not in the token text. A DataLoss token signs the ADR-0014 input unchanged, so tokens from older issuers keep verifying for accept_data_loss. A ReverseMigration token signs the same fields under a distinct domain string. accept_data_loss needs a DataLoss token, so a reverse-migration token can no longer be replayed with accept_data_loss to switch off the IRREVERSIBLE check. A plain reverse-migration rollback accepts either scope. The CLI mints DataLoss for --accept-data-loss and ReverseMigration otherwise. Every request in a CLI auto-signing flow (resolving the target, the preview, the applied request) now goes over a connection whose peer uid is the key owner's. On a mismatch the CLI warns without naming uids, gives up on signing and carries on unsigned, and the daemon's gate refuses if a token was needed. With --accept-data-loss the applied request is signed after a successful preview even if an older daemon's reply omits approval_required. The CLI skips a default key path that is a symlink, FIFO or other special file, and the daemon treats such a default path as no key, so neither can block on it. A key named explicitly must be a regular file. ADR-0019 gains a decision for the scope binding and a note that the token authorizes the target commit, not a migration list. --- Cargo.lock | 3 + crates/agentic-cli/src/client.rs | 222 ++++++++++++++++-- crates/agentic-cli/src/main.rs | 166 +++++++++---- crates/agentic-cli/tests/rollback_token.rs | 98 +++++++- crates/agentic-core/src/approval.rs | 147 ++++++++++-- crates/agenticd/Cargo.toml | 3 + crates/agenticd/src/main.rs | 50 +++- crates/agenticd/src/rollback/mod.rs | 13 +- .../agenticd/tests/approval_key_discovery.rs | 51 +++- crates/agenticd/tests/reverse_migration.rs | 5 +- crates/agenticd/tests/rollback_in_memory.rs | 79 +++++++ ...approval-for-reverse-migration-rollback.md | 34 ++- 12 files changed, 766 insertions(+), 105 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ba8fd7ee..4815a693 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -83,10 +83,13 @@ dependencies = [ "chrono", "clap", "futures", + "hex", + "hmac", "libc", "reqwest", "serde", "serde_json", + "sha2", "sqlx", "tempfile", "thiserror 1.0.69", diff --git a/crates/agentic-cli/src/client.rs b/crates/agentic-cli/src/client.rs index af5f8c10..e3acfb81 100644 --- a/crates/agentic-cli/src/client.rs +++ b/crates/agentic-cli/src/client.rs @@ -46,7 +46,7 @@ pub fn socket_path(repo: &Path) -> PathBuf { /// Send one request envelope and return the response payload. pub async fn round_trip(repo: &Path, request: Request) -> anyhow::Result { - round_trip_signed(repo, request, None).await + send_to(connect(&socket_path(repo)).await?, request).await } /// An auto-minted approval token and the uid that owns the key it came from. @@ -55,51 +55,122 @@ pub struct AutoToken { pub key_owner_uid: u32, } +/// The daemon socket is served by a uid other than the owner of the approval +/// key (or its peer uid could not be read), so the CLI will not take part in +/// an auto-signed flow with it. +#[derive(Debug)] +pub struct PeerMismatch(pub String); + +impl std::fmt::Display for PeerMismatch { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for PeerMismatch {} + +/// Check a connection's peer uid, taken from the kernel (SO_PEERCRED, or +/// getpeereid on macOS), against the uid that owns the approval key. +pub fn check_peer(peer: std::io::Result, key_owner_uid: u32) -> Result<(), PeerMismatch> { + match peer { + Ok(uid) if uid == key_owner_uid => Ok(()), + Ok(_) => Err(PeerMismatch( + "the daemon socket's peer is not the owner of the approval key".to_string(), + )), + Err(e) => Err(PeerMismatch(format!( + "could not read the daemon socket's peer uid: {e}" + ))), + } +} + /// Decide whether an auto-minted token may be sent to the server on this /// connection. The token is a bearer credential for one rollback, so it goes /// only to a server whose peer uid is the owner of the key it was minted /// from. Otherwise it is withheld, with a warning on stderr (not stdout, so -/// `--json` stays parseable). `peer` is the connection's peer uid, taken -/// from the kernel (SO_PEERCRED, or getpeereid on macOS). +/// `--json` stays parseable). pub fn token_for_peer( peer: std::io::Result, key_owner_uid: u32, token: String, ) -> Option { - match peer { - Ok(uid) if uid == key_owner_uid => Some(token), - Ok(uid) => { - eprintln!( - "warning: not sending the approval token: the daemon socket is served by uid \ - {uid}, but the approval key belongs to uid {key_owner_uid}" - ); - None - } + match check_peer(peer, key_owner_uid) { + Ok(()) => Some(token), Err(e) => { - eprintln!( - "warning: not sending the approval token: could not read the daemon socket's \ - peer uid: {e}" - ); + eprintln!("warning: not sending the approval token: {e}"); None } } } -/// Like [`round_trip`]. If `auto` is given and `request` is a rollback, the -/// token is attached only after the connection's peer uid is checked. +/// Like [`round_trip`], for a request in an auto-signing flow (resolving the +/// target, the preview). Nothing is sent unless the connection's peer uid is +/// `key_owner_uid`; otherwise the error is a [`PeerMismatch`]. `token`, if +/// any, is attached to a rollback request after that check. +pub async fn round_trip_pinned( + repo: &Path, + request: Request, + key_owner_uid: u32, + token: Option, +) -> anyhow::Result { + exchange_at( + &socket_path(repo), + request, + Some(key_owner_uid), + token, + true, + ) + .await +} + +/// Like [`round_trip`], for the applied request. If `auto` is given and +/// `request` is a rollback, the token is attached only after the connection's +/// peer uid is checked; on a mismatch the request is still sent, without a +/// token, and the daemon decides whether one was needed. pub async fn round_trip_signed( repo: &Path, - mut request: Request, + request: Request, auto: Option, ) -> anyhow::Result { - let path = socket_path(repo); - let mut sock = UnixStream::connect(&path) - .await - .with_context(|| format!("connecting to daemon at {}", path.display()))?; - if let (Some(auto), Request::Rollback { approval_token, .. }) = (auto, &mut request) { + let (owner, token) = match auto { + Some(a) => (Some(a.key_owner_uid), Some(a.token)), + None => (None, None), + }; + exchange_at(&socket_path(repo), request, owner, token, false).await +} + +/// Connect to `path`. If `owner` is set, check the connection's peer uid +/// against it: `strict` turns a mismatch into an error before anything is +/// sent, otherwise the token is withheld with a warning. A token is attached +/// to a rollback request only if the check passed. +async fn exchange_at( + path: &Path, + mut request: Request, + owner: Option, + token: Option, + strict: bool, +) -> anyhow::Result { + let sock = connect(path).await?; + if let Some(owner) = owner { let peer = sock.peer_cred().map(|c| c.uid()); - *approval_token = token_for_peer(peer, auto.key_owner_uid, auto.token); + if strict { + check_peer(peer, owner)?; + if let (Some(t), Request::Rollback { approval_token, .. }) = (token, &mut request) { + *approval_token = Some(t); + } + } else if let (Some(t), Request::Rollback { approval_token, .. }) = (token, &mut request) { + *approval_token = token_for_peer(peer, owner, t); + } } + send_to(sock, request).await +} + +async fn connect(path: &Path) -> anyhow::Result { + UnixStream::connect(path) + .await + .with_context(|| format!("connecting to daemon at {}", path.display())) +} + +async fn send_to(mut sock: UnixStream, request: Request) -> anyhow::Result { let envelope = Envelope::new(new_correlation_id(), request); let (read_half, write_half) = sock.split(); let mut reader = tokio::io::BufReader::new(read_half); @@ -130,6 +201,107 @@ fn new_correlation_id() -> String { mod tests { use super::*; + use agentic_proto::framing::{read_frame, write_frame}; + use tokio::net::UnixListener; + + fn my_uid() -> u32 { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() } + } + + /// Serve one connection on a fresh socket; the task yields the request + /// it received, or `None` if the client closed without sending one. + fn one_shot_server() -> ( + tempfile::TempDir, + PathBuf, + tokio::task::JoinHandle>, + ) { + let dir = tempfile::Builder::new() + .prefix("agc") + .tempdir_in("/tmp") + .unwrap(); + let path = dir.path().join("d.sock"); + let listener = UnixListener::bind(&path).unwrap(); + let task = tokio::spawn(async move { + let (mut s, _) = listener.accept().await.unwrap(); + let (r, w) = s.split(); + let mut r = tokio::io::BufReader::new(r); + let mut w = tokio::io::BufWriter::new(w); + let env: Envelope = read_frame(&mut r).await.ok()??; + let reply = Response::Pong; + write_frame(&mut w, &Envelope::new(env.correlation_id, reply)) + .await + .unwrap(); + Some(env.payload) + }); + (dir, path, task) + } + + fn rollback_request() -> Request { + Request::Rollback { + target: "t".into(), + dry_run: false, + accept_data_loss: false, + approval_token: None, + } + } + + #[tokio::test] + async fn pinned_round_trip_sends_nothing_to_a_peer_the_key_owner_does_not_run() { + let (_dir, path, server) = one_shot_server(); + let err = exchange_at(&path, Request::Ping, Some(my_uid() + 1), None, true) + .await + .expect_err("a mismatched peer must abort the flow"); + assert!(err.downcast_ref::().is_some(), "{err:#}"); + assert!(server.await.unwrap().is_none(), "no request may be sent"); + } + + #[tokio::test] + async fn pinned_round_trip_talks_to_the_key_owners_daemon() { + let (_dir, path, server) = one_shot_server(); + let resp = exchange_at(&path, Request::Ping, Some(my_uid()), None, true) + .await + .unwrap(); + assert!(matches!(resp, Response::Pong)); + assert!(matches!(server.await.unwrap(), Some(Request::Ping))); + } + + #[tokio::test] + async fn pinned_round_trip_with_a_token_aborts_on_a_mismatched_peer_before_sending() { + let (_dir, path, server) = one_shot_server(); + let err = exchange_at( + &path, + rollback_request(), + Some(my_uid() + 1), + Some("1:ab".into()), + true, + ) + .await + .expect_err("strict mode aborts"); + assert!(err.downcast_ref::().is_some()); + assert!(server.await.unwrap().is_none()); + } + + #[tokio::test] + async fn signed_round_trip_withholds_the_token_from_a_mismatched_peer() { + for (owner, expect_token) in [(my_uid() + 1, false), (my_uid(), true)] { + let (_dir, path, server) = one_shot_server(); + exchange_at( + &path, + rollback_request(), + Some(owner), + Some("1:ab".into()), + false, + ) + .await + .unwrap(); + let Some(Request::Rollback { approval_token, .. }) = server.await.unwrap() else { + panic!("server saw no rollback"); + }; + assert_eq!(approval_token.is_some(), expect_token, "owner {owner}"); + } + } + #[test] fn token_is_sent_only_to_a_peer_owned_by_the_key_owner() { let t = || "1:ab".to_string(); diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index 7d1e7ebb..7f300351 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -12,7 +12,9 @@ use agentic_proto::{CommitInput, ErrorClass, Request, Response}; use anyhow::{anyhow, Context}; use clap::{Parser, Subcommand}; -use crate::client::{resolve_repo, round_trip, round_trip_signed, AutoToken}; +use crate::client::{ + resolve_repo, round_trip, round_trip_pinned, round_trip_signed, AutoToken, PeerMismatch, +}; /// Format a structured `Response::Error` as a human-readable error string /// suitable for `anyhow!`. The shape is `[class:code] message`, e.g. @@ -235,19 +237,35 @@ fn read_capped(reader: impl std::io::Read) -> std::io::Result> { } fn read_key(key_file: &Path) -> anyhow::Result { - use std::os::unix::fs::MetadataExt; + use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; let ctx = || format!("reading approval key {}", key_file.display()); - let file = std::fs::File::open(key_file).with_context(ctx)?; - let owner_uid = file.metadata().with_context(ctx)?.uid(); + // O_NONBLOCK so opening a FIFO returns at once instead of waiting for a + // writer; the regular-file check below then refuses it. + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(key_file) + .with_context(ctx)?; + let meta = file.metadata().with_context(ctx)?; + if !meta.is_file() { + return Err(anyhow!( + "approval key {} is not a regular file", + key_file.display() + )); + } let bytes = read_capped(&file).with_context(ctx)?; let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes) .with_context(|| format!("approval key {} is malformed", key_file.display()))?; - Ok(LoadedKey { key, owner_uid }) + Ok(LoadedKey { + key, + owner_uid: meta.uid(), + }) } -/// Mint an approval token bound to `(commit_hash, uid, now)`. +/// Mint an approval token of `scope` bound to `(commit_hash, uid, now)`. fn mint_with_key( key: &agentic_core::approval::ApprovalKey, + scope: agentic_core::approval::ApprovalScope, commit_hash: &str, uid: u32, ) -> anyhow::Result { @@ -255,17 +273,25 @@ fn mint_with_key( .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .map_err(|_| anyhow!("system clock is before the Unix epoch"))?; - Ok(agentic_core::approval::generate_token( + Ok(agentic_core::approval::generate_token_scoped( key, + scope, commit_hash, uid, now, )) } -/// Mint a token from the 32-byte key at `key_file`. +/// Mint a token from the 32-byte key at `key_file`. The issuance mode signs +/// the data-loss scope, which also authorizes a plain reverse-migration +/// rollback and is what older issuers produced. fn mint_token(key_file: &Path, commit_hash: &str, uid: u32) -> anyhow::Result { - mint_with_key(&read_key(key_file)?.key, commit_hash, uid) + mint_with_key( + &read_key(key_file)?.key, + agentic_core::approval::ApprovalScope::DataLoss, + commit_hash, + uid, + ) } /// ADR-0014 operator token issuer. Prints a token to stdout. Does not @@ -282,12 +308,25 @@ fn cmd_mint_approval( } /// The key a rollback mints its own token from (ADR-0019 Decision 4): the -/// `--key-file` flag, else `/.agentic/approval.key` when it exists. +/// `--key-file` flag, else `/.agentic/approval.key` when it exists as a +/// regular file. A default path that is a symlink, FIFO or other special file +/// is skipped with a warning on stderr, so it cannot block the command. fn rollback_key_path(repo: &Path, key_file: Option) -> Option { - key_file.or_else(|| { - let default = repo.join(".agentic").join("approval.key"); - default.exists().then_some(default) - }) + if key_file.is_some() { + return key_file; + } + let default = repo.join(".agentic").join("approval.key"); + match std::fs::symlink_metadata(&default) { + Err(_) => None, + Ok(m) if m.is_file() => Some(default), + Ok(_) => { + eprintln!( + "warning: not attaching an approval token: {} is not a regular file", + default.display() + ); + None + } + } } /// The caller's effective uid, which the daemon reads from the socket peer @@ -332,12 +371,18 @@ fn is_signable_hash(hash: &str) -> bool { } /// Resolve `target` to the commit hash the daemon will gate on. -async fn resolve_pinned_hash(repo: &Path, target: &str) -> anyhow::Result { - let hash = match round_trip( +async fn resolve_pinned_hash( + repo: &Path, + target: &str, + key_owner_uid: u32, +) -> anyhow::Result { + let hash = match round_trip_pinned( repo, Request::ResolveRef { name: target.to_string(), }, + key_owner_uid, + None, ) .await? { @@ -383,29 +428,35 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { // ADR-0019 Decision 4. With no user-supplied token and a usable key, pin // the target to the resolved commit hash so the token, the preview and // the applied rollback all name the same commit, even if a branch moves. - let key = if approval_token.is_none() { + let mut key = if approval_token.is_none() { load_rollback_key(repo, key_file)? } else { None }; - let target = if key.is_some() { - resolve_pinned_hash(repo, &target).await? - } else { - target - }; - let auto = |k: &LoadedKey| -> anyhow::Result { - Ok(AutoToken { - token: mint_with_key(&k.key, &target, current_uid())?, - key_owner_uid: k.owner_uid, - }) + // Every request of an auto-signing flow goes over a connection whose + // peer uid is the key owner's. If one is not, give up on signing: warn, + // carry on unsigned, and let the daemon refuse if it needs a token. + let abandon = |e: &anyhow::Error| eprintln!("warning: not auto-signing the rollback: {e}"); + let target = match &key { + Some(k) => match resolve_pinned_hash(repo, &target, k.owner_uid).await { + Ok(hash) => hash, + Err(e) if e.downcast_ref::().is_some() => { + abandon(&e); + key = None; + target + } + Err(e) => return Err(e), + }, + None => target, }; - // A preview is a dry run, which verifies a token without consuming it. - // It carries only a token the user supplied, except that a destructive - // preview is refused without one, so it gets its own short-lived mint. - let preview_auto = match &key { - Some(k) if accept_data_loss => Some(auto(k)?), - _ => None, + // ADR-0019: a data-loss token for --accept-data-loss, a reverse-migration + // token otherwise. + let scope = if accept_data_loss { + agentic_core::approval::ApprovalScope::DataLoss + } else { + agentic_core::approval::ApprovalScope::ReverseMigration }; + let mint = |k: &LoadedKey| mint_with_key(&k.key, scope, &target, current_uid()); // The apply is signed only if the preview reported that this plan needs // approval. Otherwise a forward migration landing after the preview // would be reversed under a token minted for a plan nobody saw; the @@ -414,18 +465,34 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { // holds a key) to learn the flag. let mut preview_needs_approval = false; if !dry_run && (!yes || key.is_some()) { - let plan = match round_trip_signed( - repo, - Request::Rollback { - target: target.clone(), - dry_run: true, - accept_data_loss, - approval_token: approval_token.clone(), - }, - preview_auto, - ) - .await? - { + let preview = |token: Option| Request::Rollback { + target: target.clone(), + dry_run: true, + accept_data_loss, + approval_token: token, + }; + let reply = match &key { + // A preview is a dry run, which verifies a token without + // consuming it. A destructive preview is refused without one, + // so it gets its own short-lived mint. + Some(k) => { + let token = if accept_data_loss { + Some(mint(k)?) + } else { + None + }; + match round_trip_pinned(repo, preview(None), k.owner_uid, token).await { + Err(e) if e.downcast_ref::().is_some() => { + abandon(&e); + key = None; + round_trip(repo, preview(None)).await? + } + other => other?, + } + } + None => round_trip(repo, preview(approval_token.clone())).await?, + }; + let plan = match reply { Response::Rollback(p) => p, Response::Error { class, @@ -435,7 +502,9 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { } => return Err(daemon_error(class, &code, &message, retryable)), other => return Err(anyhow!("unexpected response: {other:?}")), }; - preview_needs_approval = plan.approval_required; + // A destructive request always needs a token, even if an older + // daemon's reply omits the field. + preview_needs_approval = plan.approval_required || accept_data_loss; if !yes { // Show the plan, then confirm. println!("Planned rollback to {target}:"); @@ -461,7 +530,10 @@ async fn cmd_rollback(repo: &Path, o: RollbackOpts) -> anyhow::Result<()> { (None, Some(k)) if (!dry_run && preview_needs_approval) || (dry_run && accept_data_loss) => { - Some(auto(k)?) + Some(AutoToken { + token: mint(k)?, + key_owner_uid: k.owner_uid, + }) } _ => None, }; diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index ab372529..cb31603f 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -7,7 +7,7 @@ use std::path::Path; use std::process::Command; use std::sync::{Arc, Mutex}; -use agentic_core::approval::{verify_token, ApprovalKey}; +use agentic_core::approval::{verify_token, verify_token_any, ApprovalKey, ApprovalScope}; use agentic_proto::framing::{read_frame, write_frame}; use agentic_proto::{Envelope, Request, Response, RollbackOutput}; use tokio::net::UnixListener; @@ -119,8 +119,9 @@ fn fixture_with(resolved: String, needs_approval: bool) -> Fixture { } } -/// Run `agentic rollback main` with `args`, answering the confirmation -/// prompt (when there is one) with `stdin`. +/// Run `agentic` with `args`, answering the confirmation prompt (when there +/// is one) with `stdin`. A run that does not finish in 20s is killed and +/// fails the test, so a regression that blocks is a failure, not a hang. fn agentic(f: &Fixture, args: &[&str], stdin: &str) -> std::process::Output { use std::io::Write; use std::process::Stdio; @@ -140,6 +141,14 @@ fn agentic(f: &Fixture, args: &[&str], stdin: &str) -> std::process::Output { .unwrap() .write_all(stdin.as_bytes()) .unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while child.try_wait().unwrap().is_none() { + if std::time::Instant::now() > deadline { + let _ = child.kill(); + panic!("agentic {args:?} did not finish in 20s"); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } child.wait_with_output().unwrap() } @@ -182,8 +191,18 @@ fn attaches_a_token_from_the_default_key_file() { assert!(seen[0].dry_run && seen[0].token.is_none()); let token = seen[1].token.as_deref().expect("token must be attached"); let key = ApprovalKey::from_bytes(&KEY).unwrap(); - verify_token(&key, &target_hash(), euid(), token, now()) - .expect("token must verify for the resolved commit and the caller's uid"); + verify_token_any( + &key, + &[ApprovalScope::ReverseMigration], + &target_hash(), + euid(), + token, + now(), + ) + .expect("token must verify for the resolved commit and the caller's uid"); + // A plain rollback's token is reverse-migration scope: it cannot + // authorize accept_data_loss. + assert!(verify_token(&key, &target_hash(), euid(), token, now()).is_err()); } #[test] @@ -260,8 +279,9 @@ fn preview_and_applied_rollback_name_the_pinned_hash_and_only_the_applied_one_is assert_eq!(applied.target, target_hash(), "apply must be pinned"); assert_eq!(preview.token, None, "a preview carries no auto token"); let key = ApprovalKey::from_bytes(&KEY).unwrap(); - verify_token( + verify_token_any( &key, + &[ApprovalScope::ReverseMigration], &applied.target, euid(), applied.token.as_deref().expect("applied request is signed"), @@ -283,6 +303,12 @@ fn destructive_preview_gets_its_own_token_and_the_apply_is_minted_fresh() { let seen = f.seen.lock().unwrap(); assert!(seen[0].dry_run && seen[0].token.is_some()); assert!(!seen[1].dry_run && seen[1].token.is_some()); + // --accept-data-loss tokens, preview and apply, are data-loss scope. + let key = ApprovalKey::from_bytes(&KEY).unwrap(); + for r in seen.iter() { + verify_token(&key, &r.target, euid(), r.token.as_deref().unwrap(), now()) + .expect("a destructive request carries a data-loss-scope token"); + } } #[test] @@ -379,3 +405,63 @@ fn oversized_default_key_file_is_rejected_without_a_token() { assert_eq!(seen.len(), 1, "no key, so no pinning preview: {seen:?}"); assert_eq!(seen[0].token, None); } + +#[test] +fn accept_data_loss_apply_is_signed_even_if_the_preview_omits_approval_required() { + // An older daemon's reply has no approval_required (it reads as false). + let f = fixture_no_approval(); + std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + let out = agentic(&f, &["rollback", "main", "--accept-data-loss"], "y\n"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert!(!seen[1].dry_run && seen[1].token.is_some(), "{seen:?}"); +} + +fn mkfifo(path: &Path) { + use std::os::unix::ffi::OsStrExt; + let c = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `c` is a valid NUL-terminated path for the call's duration. + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0); +} + +#[test] +fn a_fifo_at_the_default_key_path_is_skipped_not_blocked_on() { + let f = fixture(); + mkfifo(&f.repo.path().join(".agentic/approval.key")); + let out = rollback_cmd(&f, &[]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(String::from_utf8_lossy(&out.stderr).contains("not a regular file")); + let seen = f.seen.lock().unwrap(); + assert_eq!(seen.len(), 1, "no key, so no silent preview: {seen:?}"); + assert_eq!(seen[0].token, None); +} + +#[test] +fn a_symlinked_default_key_is_skipped() { + let f = fixture(); + let real = f.repo.path().join("real.key"); + std::fs::write(&real, KEY).unwrap(); + std::os::unix::fs::symlink(&real, f.repo.path().join(".agentic/approval.key")).unwrap(); + run_rollback(&f, &[]); + assert_eq!(f.seen.lock().unwrap()[0].token, None); +} + +#[test] +fn an_explicit_key_that_is_not_a_regular_file_is_an_error() { + let f = fixture(); + let fifo = f.repo.path().join("k.fifo"); + mkfifo(&fifo); + let out = rollback_cmd(&f, &["--key-file", fifo.to_str().unwrap()]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("not a regular file")); + assert!(f.seen.lock().unwrap().is_empty()); +} diff --git a/crates/agentic-core/src/approval.rs b/crates/agentic-core/src/approval.rs index 8b8a070b..4dba3459 100644 --- a/crates/agentic-core/src/approval.rs +++ b/crates/agentic-core/src/approval.rs @@ -19,6 +19,12 @@ //! The `v1` domain-separation prefix guarantees a token minted for //! rollback approval can never be reused for a different signed-message //! format on the same key. +//! +//! ADR-0019 adds a second scope on the same token text format. A +//! [`ApprovalScope::DataLoss`] token signs the input above, unchanged, so +//! tokens from older issuers keep verifying for `accept_data_loss`. A +//! [`ApprovalScope::ReverseMigration`] token signs the same fields under a +//! distinct domain string, so it can never authorize `accept_data_loss`. use hmac::{Hmac, Mac}; use sha2::Sha256; @@ -35,6 +41,22 @@ pub const APPROVAL_TOKEN_TTL_SECONDS: u64 = 300; /// the same key MUST use a different domain string (Decision 2). const DOMAIN: &str = "git.agentic/rollback-approval/v1"; +/// Domain string of the reverse-migration scope (ADR-0019). It differs from +/// [`DOMAIN`] at the byte after `v1` (`/` against `:`), so no choice of +/// commit hash, uid or timestamp can make the two signed inputs equal. +const DOMAIN_REVERSE_MIGRATION: &str = "git.agentic/rollback-approval/v1/reverse-migration"; + +/// What an approval token authorizes (ADR-0019). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ApprovalScope { + /// `accept_data_loss = true`: the pre-ADR-0019 signing input. Legacy + /// tokens are this scope. It also covers a plain reverse-migration + /// rollback, the weaker action. + DataLoss, + /// A rollback that runs reverse migrations without `accept_data_loss`. + ReverseMigration, +} + /// Required approval-key length in bytes (256-bit, Decision 6). pub const APPROVAL_KEY_LEN: usize = 32; @@ -106,17 +128,32 @@ impl ApprovalRejection { /// The canonical signed payload for a `(commit_hash, peer_uid, timestamp)` /// tuple. `commit_hash` is normalized to lowercase hex by the caller. -fn signing_input(commit_hash: &str, peer_uid: u32, timestamp: u64) -> Vec { - format!("{DOMAIN}:{commit_hash}:{peer_uid}:{timestamp}").into_bytes() +fn signing_input( + scope: ApprovalScope, + commit_hash: &str, + peer_uid: u32, + timestamp: u64, +) -> Vec { + let domain = match scope { + ApprovalScope::DataLoss => DOMAIN, + ApprovalScope::ReverseMigration => DOMAIN_REVERSE_MIGRATION, + }; + format!("{domain}:{commit_hash}:{peer_uid}:{timestamp}").into_bytes() } /// Compute the raw HMAC-SHA256 tag for a tuple. -fn tag(key: &ApprovalKey, commit_hash: &str, peer_uid: u32, timestamp: u64) -> Vec { +fn tag( + key: &ApprovalKey, + scope: ApprovalScope, + commit_hash: &str, + peer_uid: u32, + timestamp: u64, +) -> Vec { // INVARIANT: HMAC accepts a key of any length; `new_from_slice` only // errors for algorithms with a fixed key size, which HMAC is not — so // this never returns Err. The `expect` documents that. let mut mac = HmacSha256::new_from_slice(&key.0).expect("HMAC accepts any key length"); - mac.update(&signing_input(commit_hash, peer_uid, timestamp)); + mac.update(&signing_input(scope, commit_hash, peer_uid, timestamp)); mac.finalize().into_bytes().to_vec() } @@ -127,8 +164,20 @@ fn tag(key: &ApprovalKey, commit_hash: &str, peer_uid: u32, timestamp: u64) -> V /// upper/mixed-case hash still verifies against the daemon's normalized /// target hash. pub fn generate_token(key: &ApprovalKey, commit_hash: &str, peer_uid: u32, now: u64) -> String { + generate_token_scoped(key, ApprovalScope::DataLoss, commit_hash, peer_uid, now) +} + +/// [`generate_token`] for a given scope (ADR-0019). The token text format is +/// the same for every scope. +pub fn generate_token_scoped( + key: &ApprovalKey, + scope: ApprovalScope, + commit_hash: &str, + peer_uid: u32, + now: u64, +) -> String { let commit_hash = commit_hash.to_ascii_lowercase(); - let mac = tag(key, &commit_hash, peer_uid, now); + let mac = tag(key, scope, &commit_hash, peer_uid, now); format!("{now}:{}", hex::encode(mac)) } @@ -152,9 +201,10 @@ impl VerifiedToken { } /// Verify a token against the expected `(commit_hash, peer_uid)` at time -/// `now`. The comparison is constant-time: the supplied hex tag is decoded -/// and checked with `Mac::verify_slice`, never a short-circuiting string -/// compare of the hex (Decision 2). +/// `now`, for `accept_data_loss` ([`ApprovalScope::DataLoss`], which is what +/// legacy tokens are). The comparison is constant-time: the supplied hex tag +/// is decoded and checked with `Mac::verify_slice`, never a short-circuiting +/// string compare of the hex (Decision 2). /// /// `commit_hash` is normalized to lowercase before verification, matching /// `generate_token`. @@ -164,6 +214,28 @@ pub fn verify_token( peer_uid: u32, token: &str, now: u64, +) -> Result { + verify_token_any( + key, + &[ApprovalScope::DataLoss], + commit_hash, + peer_uid, + token, + now, + ) +} + +/// [`verify_token`] accepting a token of any of `scopes` (ADR-0019). A plain +/// reverse-migration rollback passes `[ReverseMigration, DataLoss]`, because +/// a data-loss approval also covers the weaker action; `accept_data_loss` +/// passes `[DataLoss]` only. A token that fits none is `InvalidSignature`. +pub fn verify_token_any( + key: &ApprovalKey, + scopes: &[ApprovalScope], + commit_hash: &str, + peer_uid: u32, + token: &str, + now: u64, ) -> Result { let (ts_str, hex_tag) = token.split_once(':').ok_or(ApprovalRejection::Malformed)?; let timestamp: u64 = ts_str.parse().map_err(|_| ApprovalRejection::Malformed)?; @@ -188,12 +260,15 @@ pub fn verify_token( } let commit_hash = commit_hash.to_ascii_lowercase(); - let mut mac = HmacSha256::new_from_slice(&key.0).expect("HMAC accepts any key length"); - mac.update(&signing_input(&commit_hash, peer_uid, timestamp)); - // Constant-time comparison of the decoded tag bytes. - mac.verify_slice(&tag) - .map_err(|_| ApprovalRejection::InvalidSignature)?; - Ok(VerifiedToken { timestamp, tag }) + for scope in scopes { + let mut mac = HmacSha256::new_from_slice(&key.0).expect("HMAC accepts any key length"); + mac.update(&signing_input(*scope, &commit_hash, peer_uid, timestamp)); + // Constant-time comparison of the decoded tag bytes. + if mac.verify_slice(&tag).is_ok() { + return Ok(VerifiedToken { timestamp, tag }); + } + } + Err(ApprovalRejection::InvalidSignature) } #[cfg(test)] @@ -364,4 +439,48 @@ mod tests { ); } } + + // ADR-0019: the scopes sign different inputs for the same tuple, and a + // token of one scope does not verify as the other. + #[test] + fn scopes_sign_distinct_inputs() { + let h = "a".repeat(64); + assert_ne!( + signing_input(ApprovalScope::DataLoss, &h, 1000, 5_000), + signing_input(ApprovalScope::ReverseMigration, &h, 1000, 5_000) + ); + let dl = generate_token_scoped(&key(), ApprovalScope::DataLoss, &h, 1000, 5_000); + let rm = generate_token_scoped(&key(), ApprovalScope::ReverseMigration, &h, 1000, 5_000); + assert_ne!(dl, rm); + } + + #[test] + fn legacy_signing_input_is_unchanged() { + // Pinned byte for byte: tokens minted by older CLIs must keep verifying. + assert_eq!( + signing_input(ApprovalScope::DataLoss, "abc", 1000, 5), + b"git.agentic/rollback-approval/v1:abc:1000:5".to_vec() + ); + // And a token built the way the old code built it verifies as DataLoss. + let mut mac = HmacSha256::new_from_slice(&[7u8; APPROVAL_KEY_LEN]).unwrap(); + mac.update(b"git.agentic/rollback-approval/v1:abc:1000:5"); + let legacy = format!("5:{}", hex::encode(mac.finalize().into_bytes())); + assert!(verify_token(&key(), "abc", 1000, &legacy, 5).is_ok()); + assert_eq!(legacy, generate_token(&key(), "abc", 1000, 5)); + } + + #[test] + fn a_reverse_migration_token_does_not_verify_for_data_loss() { + let h = "a".repeat(64); + let rm = generate_token_scoped(&key(), ApprovalScope::ReverseMigration, &h, 1000, 5_000); + assert_eq!( + verify_token(&key(), &h, 1000, &rm, 5_000), + Err(ApprovalRejection::InvalidSignature) + ); + let both = [ApprovalScope::ReverseMigration, ApprovalScope::DataLoss]; + assert!(verify_token_any(&key(), &both, &h, 1000, &rm, 5_000).is_ok()); + // A data-loss token also covers the weaker action. + let dl = generate_token(&key(), &h, 1000, 5_000); + assert!(verify_token_any(&key(), &both, &h, 1000, &dl, 5_000).is_ok()); + } } diff --git a/crates/agenticd/Cargo.toml b/crates/agenticd/Cargo.toml index 49f7e301..497204b8 100644 --- a/crates/agenticd/Cargo.toml +++ b/crates/agenticd/Cargo.toml @@ -39,3 +39,6 @@ tempfile = "3.10" sqlx.workspace = true libc = "0.2" wiremock = "0.6" +hmac.workspace = true +sha2.workspace = true +hex.workspace = true diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index a2fc3f6c..64aeb162 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -180,8 +180,7 @@ struct Args { } /// The approval key path: the explicit flag, else `/approval.key` -/// when that file exists (ADR-0019 Decision 3). `Path::exists` follows -/// symlinks, so a dangling link counts as absent. +/// when that is a regular file (ADR-0019 Decision 3). fn approval_key_path( explicit: Option<&std::path::Path>, agentic_dir: &std::path::Path, @@ -190,7 +189,20 @@ fn approval_key_path( return Some(p.to_path_buf()); } let default = agentic_dir.join("approval.key"); - default.exists().then_some(default) + match std::fs::symlink_metadata(&default) { + Err(_) => None, + Ok(m) if m.is_file() => Some(default), + // A FIFO or other special file at the default path must not block + // startup. Treat it like an unreadable key: warn, run without one. + Ok(_) => { + tracing::warn!( + target: "agenticd::approval", + path = %default.display(), + "default approval key path is not a regular file; ignoring it (fail-closed)" + ); + None + } + } } /// Load the ADR-0014 approval key per Decisions 4 and 6. @@ -223,13 +235,24 @@ fn load_approval_key( "approval key file unreadable; destructive rollback disabled (fail-closed)" ); }; - let mut file = match std::fs::File::open(path) { + // O_NONBLOCK so opening a FIFO returns at once instead of waiting for a + // writer; the regular-file check below then rejects it. + use std::os::unix::fs::OpenOptionsExt; + let opened = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(path); + let mut file = match opened { Ok(f) => f, Err(e) => { unreadable(e); return Ok(None); } }; + if !file.metadata().is_ok_and(|m| m.is_file()) { + unreadable(std::io::Error::other("not a regular file")); + return Ok(None); + } let mut bytes = Vec::new(); // Cap the read: one byte past the key length is enough to reject a wrong-length // file, and a misconfigured path to an endless source cannot exhaust memory. @@ -681,6 +704,25 @@ mod tests { ); } + // ADR-0019 Decision 3: only a regular file counts as the default key. A + // FIFO would block the open, a symlink is not followed. + #[cfg(unix)] + #[test] + fn approval_key_path_ignores_a_non_regular_default() { + use std::os::unix::ffi::OsStrExt; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("approval.key"); + let c = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap(); + // SAFETY: `c` is a valid NUL-terminated path for the call's duration. + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0); + assert_eq!(approval_key_path(None, dir.path()), None); + std::fs::remove_file(&fifo).unwrap(); + let real = dir.path().join("real"); + std::fs::write(&real, [7u8; 32]).unwrap(); + std::os::unix::fs::symlink(&real, &fifo).unwrap(); + assert_eq!(approval_key_path(None, dir.path()), None); + } + #[cfg(unix)] #[test] fn approval_key_file_mode_is_enforced() { diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index b6a6a90a..65bd2a39 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -37,7 +37,7 @@ mod writeback; use std::path::PathBuf; -use agentic_core::approval::{verify_token, ApprovalRejection}; +use agentic_core::approval::{verify_token_any, ApprovalRejection, ApprovalScope}; use agentic_core::commit::{stage_and_commit, CommitInputs}; use agentic_core::refs::HeadRef; use agentic_core::{check_blob_unambiguous, Commit, Hash}; @@ -225,7 +225,16 @@ fn approval_gate( }; // (d) Verify. let now = now_unix_seconds(); - let verified = match verify_token(key, &commit_hash, uid, token, now) { + // ADR-0019 scope binding: accept_data_loss needs a data-loss token (which + // is also what legacy tokens are). A plain reverse-migration rollback + // accepts either scope, because a data-loss approval covers the weaker + // action. A reverse-migration token therefore cannot be replayed with + // accept_data_loss=true to switch off the IRREVERSIBLE check. + let scopes: &[ApprovalScope] = match reason { + GateReason::AcceptDataLoss => &[ApprovalScope::DataLoss], + GateReason::ReverseMigration => &[ApprovalScope::ReverseMigration, ApprovalScope::DataLoss], + }; + let verified = match verify_token_any(key, scopes, &commit_hash, uid, token, now) { Ok(v) => v, Err(rej) => return Err(reject(ApprovalError::Rejected(rej))), }; diff --git a/crates/agenticd/tests/approval_key_discovery.rs b/crates/agenticd/tests/approval_key_discovery.rs index e6f2bf4b..451374a4 100644 --- a/crates/agenticd/tests/approval_key_discovery.rs +++ b/crates/agenticd/tests/approval_key_discovery.rs @@ -35,8 +35,24 @@ fn write_key(repo: &std::path::Path, mode: u32) { std::fs::set_permissions(&key, std::fs::Permissions::from_mode(mode)).unwrap(); } +fn mkfifo(path: &std::path::Path) { + use std::os::unix::ffi::OsStrExt; + let c = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `c` is a valid NUL-terminated path for the call's duration. + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0); +} + fn spawn_daemon(repo: &std::path::Path, sock: &std::path::Path) -> Child { + spawn_daemon_with(repo, sock, &[]) +} + +fn spawn_daemon_with( + repo: &std::path::Path, + sock: &std::path::Path, + extra: &[&std::ffi::OsStr], +) -> Child { Command::new(env!("CARGO_BIN_EXE_agenticd")) + .args(extra) .arg("--repo") .arg(repo) .arg("--socket") @@ -63,17 +79,26 @@ async fn send(sock: &std::path::Path, request: Request) -> Response { /// Commit once, then send `Rollback { accept_data_loss: true }` with no /// token. Which error comes back says whether the daemon holds a key. async fn rollback_error_code(repo: &std::path::Path) -> String { + rollback_error_code_with(repo, &[]).await +} + +async fn rollback_error_code_with(repo: &std::path::Path, extra: &[&std::ffi::OsStr]) -> String { let sock_dir = tempfile::Builder::new() .prefix("agd") .tempdir_in("/tmp") .unwrap(); let sock = sock_dir.path().join("d.sock"); - let mut child = spawn_daemon(repo, &sock); + let mut child = spawn_daemon_with(repo, &sock, extra); let deadline = Instant::now() + Duration::from_secs(20); while !sock.exists() && Instant::now() < deadline { tokio::time::sleep(Duration::from_millis(50)).await; } - assert!(sock.exists(), "daemon did not bind its socket"); + if !sock.exists() { + // A daemon blocked on a FIFO never binds; do not leave it behind. + let _ = child.kill(); + let _ = child.wait(); + panic!("daemon did not bind its socket"); + } let Response::Commit(c) = send( &sock, @@ -157,3 +182,25 @@ fn group_or_other_readable_default_key_aborts_startup() { let stderr = String::from_utf8_lossy(&out.stderr); assert!(stderr.contains("chmod 600"), "stderr: {stderr}"); } + +#[tokio::test] +async fn a_fifo_at_the_default_key_path_does_not_block_startup() { + let repo = tempfile::tempdir().unwrap(); + mkfifo(&state_dir(repo.path()).join("approval.key")); + assert_eq!( + rollback_error_code(repo.path()).await, + "approval_key_not_configured" + ); +} + +#[tokio::test] +async fn a_fifo_named_with_the_flag_does_not_block_startup_either() { + let repo = tempfile::tempdir().unwrap(); + let fifo = state_dir(repo.path()).join("k.fifo"); + mkfifo(&fifo); + let flag = std::ffi::OsString::from("--approval-key-file"); + assert_eq!( + rollback_error_code_with(repo.path(), &[flag.as_os_str(), fifo.as_os_str()]).await, + "approval_key_not_configured" + ); +} diff --git a/crates/agenticd/tests/reverse_migration.rs b/crates/agenticd/tests/reverse_migration.rs index 28429d39..c41a72be 100644 --- a/crates/agenticd/tests/reverse_migration.rs +++ b/crates/agenticd/tests/reverse_migration.rs @@ -376,7 +376,7 @@ async fn ac3c_accept_data_loss_reverses_irreversible_migration() { #[tokio::test] #[ignore] async fn adr_0019_reverse_migration_rollback_needs_a_token_against_postgres() { - use agentic_core::approval::{generate_token, ApprovalKey}; + use agentic_core::approval::{generate_token_scoped, ApprovalKey, ApprovalScope}; use agentic_core::refs::Refs; use agentic_core::ObjectStore; use agentic_proto::CommitInput; @@ -510,8 +510,9 @@ async fn adr_0019_reverse_migration_rollback_needs_a_token_against_postgres() { .duration_since(UNIX_EPOCH) .unwrap() .as_secs(); - let token = generate_token( + let token = generate_token_scoped( &ApprovalKey::from_bytes(&[42u8; 32]).unwrap(), + ApprovalScope::ReverseMigration, &baseline, 1000, now, diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 116a0317..12df3a09 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -1205,3 +1205,82 @@ async fn plans_report_whether_approval_is_required() { .unwrap(); assert!(out.approval_required); } + +// --------------------------------------------------------------------------- +// ADR-0019 scope binding. +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn reverse_migration_token_cannot_authorize_accept_data_loss() { + use agentic_core::approval::{generate_token_scoped, ApprovalScope}; + // The attack: a token issued for an ordinary reverse-migration rollback + // replayed with accept_data_loss=true, which would switch off the + // IRREVERSIBLE check. It must be refused before any SQL. + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let down = state.refs.agentic_dir().join("schema/002_bump.down.sql"); + std::fs::write(&down, "-- IRREVERSIBLE\nDROP TABLE messages;\n").unwrap(); + let tip = state.refs.read_branch("main").unwrap(); + let rm = generate_token_scoped( + &test_key(), + ApprovalScope::ReverseMigration, + &baseline, + 1000, + now_secs(), + ); + for dry_run in [true, false] { + let args = RollbackArgs { + dry_run, + ..real_args(&state, &baseline, Some(rm.clone())) + }; + let err = rollback::execute(Arc::clone(&state), args, Some(1000)) + .await + .expect_err("a reverse-migration token must not authorize accept_data_loss"); + assert!(matches!( + downcast_approval(&err), + ApprovalError::Rejected(agentic_core::approval::ApprovalRejection::InvalidSignature) + )); + } + assert!(state.used_approval_tokens.lock().unwrap().is_empty()); + assert_untouched(&state, &adapter, tip).await; +} + +#[tokio::test] +async fn either_scope_authorizes_a_plain_reverse_migration_rollback() { + use agentic_core::approval::{generate_token_scoped, ApprovalScope}; + for scope in [ApprovalScope::ReverseMigration, ApprovalScope::DataLoss] { + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tok = generate_token_scoped(&test_key(), scope, &baseline, 1000, now_secs()); + let out = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + Some(1000), + ) + .await + .unwrap_or_else(|e| panic!("{scope:?}: {e:#}")); + assert!(out.executed, "{scope:?}"); + assert_eq!(adapter.current_schema_version().await.unwrap(), "001_init"); + } +} + +#[tokio::test] +async fn legacy_format_token_still_authorizes_accept_data_loss() { + // A token built the way pre-ADR-0019 issuers built it (the signing input + // is pinned in agentic-core), not through the scoped API. + use hmac::{Hmac, Mac}; + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let now = now_secs(); + let mut mac = Hmac::::new_from_slice(&TEST_KEY_BYTES).unwrap(); + mac.update(format!("git.agentic/rollback-approval/v1:{baseline}:1000:{now}").as_bytes()); + let legacy = format!("{now}:{}", hex::encode(mac.finalize().into_bytes())); + let out = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(legacy)), + Some(1000), + ) + .await + .expect("a legacy token keeps working for accept_data_loss"); + assert!(out.executed); +} diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md index f1433197..be7e0f9a 100644 --- a/docs/adr/0019-approval-for-reverse-migration-rollback.md +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -28,6 +28,7 @@ The owner decided that any rollback that runs reverse migrations needs the ADR-0 | 2 | Without an approval key, such a rollback is refused, and the error names `--approval-key-file`. | Fail closed, as ADR-0014 Decision 4. | | 3 | If `--approval-key-file` is not given, the daemon uses `/.agentic/approval.key` when that file exists. | The operator needs no extra flag, and the CLI and daemon share one default location. | | 4 | The `agentic` CLI attaches a token to rollback requests on its own when it can read the key. | The operator's commands stay the same. A socket client without the key cannot run reverse migrations. | +| 5 | A token is bound to a scope, `DataLoss` or `ReverseMigration`, by domain-separating the signed input. The token text format is unchanged. | One token must not authorize both modes: a reverse-migration approval replayed with `accept_data_loss` would switch off the `IRREVERSIBLE` check. | ## Decisions @@ -113,9 +114,12 @@ Without this rule, a forward migration that lands between the preview and the ap With the rule, the daemon's gate refuses that apply and the operator previews again. With `--yes` no plan is shown, but the CLI still sends the preview request silently, when it holds a key, to read the field. -The CLI also checks who it is talking to before it sends a minted token. -It reads the connected socket's peer uid from the kernel and sends the token only if that uid owns the key file the token came from. -Otherwise it sends no token and warns on stderr. +The CLI also checks who it is talking to. +In a flow that may auto-sign, every request (resolving the target, the preview, the applied request) goes over a connection whose peer uid, read from the kernel, is the uid that owns the key file. +If a check fails, the CLI gives up on signing: it warns on stderr and carries on without a token, and the daemon's gate refuses if one was needed. +With `--accept-data-loss` the applied request is signed after a successful preview even if the reply omits `approval_required`, as an older daemon's would. +The CLI skips a default key path that is a symlink, FIFO or other special file, with a warning, and the daemon treats such a default path as no key, so a special file cannot block either. +A key named explicitly must be a regular file (the CLI fails; the daemon warns and runs without a key, as for an unreadable file). It reads at most 33 bytes of the key file, as the daemon does. A token passed explicitly with `--approval-token` is sent as given, on both requests, and the target is left as typed. @@ -128,6 +132,27 @@ A token is consumed only when the gate passes on a non-dry-run request. This also lets an operator who holds the key run `--accept-data-loss` without minting a token by hand. The flag is still required. +### Decision 5: Tokens are bound to a scope + +One token format now covers two modes, so a token issued for an ordinary reverse-migration rollback could be replayed with `accept_data_loss=true`. +The daemon would then load the down migrations with the `IRREVERSIBLE` check off. +Approval tokens therefore carry a scope. + +The scope is part of the signed input, not of the token text. +The text stays `:`. +A `DataLoss` token signs exactly the ADR-0014 input, `git.agentic/rollback-approval/v1:::`, so every token minted by an older CLI is a `DataLoss` token and keeps verifying. +A `ReverseMigration` token signs the same fields under the domain string `git.agentic/rollback-approval/v1/reverse-migration`. +The two domain strings differ at a fixed position before any variable field, so no commit, uid or timestamp can make the inputs equal. + +Verification: + +- An `accept_data_loss` request needs a `DataLoss` token. +- A plain reverse-migration rollback accepts either scope, because a data-loss approval also covers the weaker action. +- The single-use ledger keys on the decoded tag as before. + +The CLI mints a `DataLoss` token for `--accept-data-loss` requests and a `ReverseMigration` token otherwise. +The `agentic rollback --approval` issuance mode keeps minting `DataLoss` tokens, which cover both. + ## Consequences **Positive:** @@ -153,6 +178,9 @@ The flag is still required. **Not covered:** +- The token authorizes the target commit, not a specific migration list, because ADR-0014 binds approval to the target commit. + A rollback to that commit reverses whatever is above it at apply time. + The CLI's preview rule (Decision 4) narrows the window, but binding approval to the plan would need a token format change. - A rollback with no schema change still restores memory without a token. Per-operation authorization for the other requests, `ReadObject` among them, stays an open decision in TM-001 and TM-002. - The ledger is per process, as in ADR-0014. From 13872cd59fb0873b902943031614d2e0c9bbce3e Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:32:40 +0200 Subject: [PATCH 07/10] Add an issuer scope flag, refuse symlinked and loose keys, audit the scope The offline issuer (agentic rollback --approval) takes --scope reverse-migration|data-loss, defaulting to data-loss so existing callers keep their tokens. The daemon's missing-token diagnostic now recommends --scope reverse-migration for an ordinary reverse-migration rollback, since a data-loss token would also authorize accept_data_loss, and keeps pointing accept_data_loss at --scope data-loss. Both keep the wire code approval_required. Open the key file with O_NOFOLLOW in the CLI and the daemon, so a symlink swapped in after the default-path check is never followed. The CLI applies the daemon's mode check: a key that group or other can access is refused with a chmod 600 hint, or skipped with a warning when it is the default. The accepted audit event carries the scope the token verified under, next to reason. Say precisely in the code comment and ADR-0019 that the down-migration files load before the gate only for a plain reverse-migration rollback; with accept_data_loss the gate still runs first. Tests drop the uid values from the CLI client test messages. --- crates/agentic-cli/src/client.rs | 7 +- crates/agentic-cli/src/main.rs | 118 ++++++++++++--- crates/agentic-cli/tests/rollback_token.rs | 135 +++++++++++++++--- crates/agentic-core/src/approval.rs | 34 ++++- crates/agenticd/src/main.rs | 5 +- crates/agenticd/src/rollback/mod.rs | 50 +++++-- crates/agenticd/src/wire_error.rs | 6 +- .../agenticd/tests/approval_key_discovery.rs | 29 ++++ crates/agenticd/tests/reverse_migration.rs | 4 +- crates/agenticd/tests/rollback_in_memory.rs | 105 +++++++++++++- ...approval-for-reverse-migration-rollback.md | 11 +- 11 files changed, 444 insertions(+), 60 deletions(-) diff --git a/crates/agentic-cli/src/client.rs b/crates/agentic-cli/src/client.rs index e3acfb81..a1996249 100644 --- a/crates/agentic-cli/src/client.rs +++ b/crates/agentic-cli/src/client.rs @@ -284,7 +284,10 @@ mod tests { #[tokio::test] async fn signed_round_trip_withholds_the_token_from_a_mismatched_peer() { - for (owner, expect_token) in [(my_uid() + 1, false), (my_uid(), true)] { + for (owner, expect_token, label) in [ + (my_uid() + 1, false, "other uid"), + (my_uid(), true, "key owner"), + ] { let (_dir, path, server) = one_shot_server(); exchange_at( &path, @@ -298,7 +301,7 @@ mod tests { let Some(Request::Rollback { approval_token, .. }) = server.await.unwrap() else { panic!("server saw no rollback"); }; - assert_eq!(approval_token.is_some(), expect_token, "owner {owner}"); + assert_eq!(approval_token.is_some(), expect_token, "{label}"); } } diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index 7f300351..b20997e5 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -53,6 +53,24 @@ struct Cli { json: bool, } +/// What an issued approval token authorizes (ADR-0019 Decision 5). +#[derive(Clone, Copy, Debug, clap::ValueEnum)] +enum IssueScope { + /// `--accept-data-loss`. Also covers a plain reverse-migration rollback. + DataLoss, + /// A rollback that runs reverse migrations, without `--accept-data-loss`. + ReverseMigration, +} + +impl From for agentic_core::approval::ApprovalScope { + fn from(s: IssueScope) -> Self { + match s { + IssueScope::DataLoss => Self::DataLoss, + IssueScope::ReverseMigration => Self::ReverseMigration, + } + } +} + #[derive(Subcommand, Debug)] enum Command { /// Initialise a new agentic repository in the current directory. @@ -120,9 +138,9 @@ enum Command { /// rollback as a new commit so history is preserved. /// /// Also the operator's approval-token issuer (ADR-0014): pass - /// `--approval --uid --key-file ` to - /// mint a destructive-rollback token to stdout without contacting the - /// daemon. + /// `--approval --uid --key-file + /// [--scope reverse-migration|data-loss]` to mint a token to stdout + /// without contacting the daemon. Rollback { /// Target ref (commit hash or branch name). Required for an actual /// rollback; ignored in `--approval` token-issuance mode. @@ -152,6 +170,12 @@ enum Command { /// Worker UID the minted token is bound to (issuance mode). #[arg(long)] uid: Option, + /// Scope of the minted token (issuance mode). `reverse-migration` + /// authorizes only a rollback that runs reverse migrations; + /// `data-loss` (the default, as before) also authorizes + /// `--accept-data-loss`. Hand a worker the narrowest scope. + #[arg(long, value_enum, default_value_t = IssueScope::DataLoss)] + scope: IssueScope, /// Path to the 32-byte approval key. Used by the issuance mode and /// to attach a token to a rollback automatically (ADR-0019). #[arg(long)] @@ -192,11 +216,12 @@ async fn main() -> anyhow::Result<()> { approval_token, approval, uid, + scope, key_file, } => { if let Some(commit_hash) = approval { // Issuance mode: mint a token, no daemon contact. - return cmd_mint_approval(&commit_hash, uid, key_file); + return cmd_mint_approval(&commit_hash, uid, key_file, scope.into()); } let target = target .ok_or_else(|| anyhow!("rollback requires a target ref (or use --approval)"))?; @@ -240,10 +265,11 @@ fn read_key(key_file: &Path) -> anyhow::Result { use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; let ctx = || format!("reading approval key {}", key_file.display()); // O_NONBLOCK so opening a FIFO returns at once instead of waiting for a - // writer; the regular-file check below then refuses it. + // writer; the regular-file check below then refuses it. O_NOFOLLOW so a + // symlink swapped in after the default-path check is never followed. let file = std::fs::OpenOptions::new() .read(true) - .custom_flags(libc::O_NONBLOCK) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) .open(key_file) .with_context(ctx)?; let meta = file.metadata().with_context(ctx)?; @@ -253,6 +279,17 @@ fn read_key(key_file: &Path) -> anyhow::Result { key_file.display() )); } + // The same mode check as the daemon: a key that group or other can read + // lets them mint tokens. + let mode = meta.mode() & 0o777; + if mode & 0o077 != 0 { + return Err(anyhow!( + "approval key {} has mode {mode:03o}; it must not be accessible by group or \ + other. Run `chmod 600 {}`", + key_file.display(), + key_file.display() + )); + } let bytes = read_capped(&file).with_context(ctx)?; let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes) .with_context(|| format!("approval key {} is malformed", key_file.display()))?; @@ -282,16 +319,14 @@ fn mint_with_key( )) } -/// Mint a token from the 32-byte key at `key_file`. The issuance mode signs -/// the data-loss scope, which also authorizes a plain reverse-migration -/// rollback and is what older issuers produced. -fn mint_token(key_file: &Path, commit_hash: &str, uid: u32) -> anyhow::Result { - mint_with_key( - &read_key(key_file)?.key, - agentic_core::approval::ApprovalScope::DataLoss, - commit_hash, - uid, - ) +/// Mint a token of `scope` from the 32-byte key at `key_file`. +fn mint_token( + key_file: &Path, + scope: agentic_core::approval::ApprovalScope, + commit_hash: &str, + uid: u32, +) -> anyhow::Result { + mint_with_key(&read_key(key_file)?.key, scope, commit_hash, uid) } /// ADR-0014 operator token issuer. Prints a token to stdout. Does not @@ -300,10 +335,11 @@ fn cmd_mint_approval( commit_hash: &str, uid: Option, key_file: Option, + scope: agentic_core::approval::ApprovalScope, ) -> anyhow::Result<()> { let uid = uid.ok_or_else(|| anyhow!("--approval requires --uid "))?; let key_file = key_file.ok_or_else(|| anyhow!("--approval requires --key-file "))?; - println!("{}", mint_token(&key_file, commit_hash, uid)?); + println!("{}", mint_token(&key_file, scope, commit_hash, uid)?); Ok(()) } @@ -871,6 +907,34 @@ fn read_git_head(repo: &Path) -> anyhow::Result { mod tests { use super::*; + fn write_key_0600(path: &Path, bytes: &[u8]) { + use std::os::unix::fs::PermissionsExt; + std::fs::write(path, bytes).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + #[test] + fn a_group_or_other_accessible_key_is_refused_with_a_chmod_hint() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("approval.key"); + write_key_0600(&path, &[7u8; 32]); + for mode in [0o644, 0o640, 0o604, 0o660, 0o666] { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + let err = read_key(&path) + .err() + .unwrap_or_else(|| panic!("{mode:o} accepted")); + assert!( + format!("{err:#}").contains("chmod 600"), + "{mode:o}: {err:#}" + ); + } + for mode in [0o600, 0o400] { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + assert!(read_key(&path).is_ok(), "{mode:o}"); + } + } + /// A reader that never ends and counts what it hands out. struct Endless(std::cell::Cell); impl std::io::Read for &Endless { @@ -912,9 +976,15 @@ mod tests { fn minted_token_verifies_for_the_commit_and_uid() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("approval.key"); - std::fs::write(&path, [7u8; 32]).unwrap(); + write_key_0600(&path, &[7u8; 32]); let hash = "ab".repeat(32); - let token = mint_token(&path, &hash, 1234).unwrap(); + let token = mint_token( + &path, + agentic_core::approval::ApprovalScope::DataLoss, + &hash, + 1234, + ) + .unwrap(); let key = agentic_core::approval::ApprovalKey::from_bytes(&[7u8; 32]).unwrap(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -922,7 +992,13 @@ mod tests { .as_secs(); agentic_core::approval::verify_token(&key, &hash, 1234, &token, now).unwrap(); assert!(agentic_core::approval::verify_token(&key, &hash, 1235, &token, now).is_err()); - std::fs::write(&path, [7u8; 5]).unwrap(); - assert!(mint_token(&path, &hash, 1234).is_err()); + write_key_0600(&path, &[7u8; 5]); + assert!(mint_token( + &path, + agentic_core::approval::ApprovalScope::DataLoss, + &hash, + 1234 + ) + .is_err()); } } diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index cb31603f..f5a576a9 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -167,6 +167,13 @@ fn run_rollback(f: &Fixture, extra: &[&str]) { ); } +/// Write a key file with the mode the CLI requires (0600). +fn write_key(path: impl AsRef, bytes: &[u8]) { + use std::os::unix::fs::PermissionsExt; + std::fs::write(path.as_ref(), bytes).unwrap(); + std::fs::set_permissions(path.as_ref(), std::fs::Permissions::from_mode(0o600)).unwrap(); +} + fn euid() -> u32 { // SAFETY: geteuid has no preconditions and cannot fail. unsafe { libc::geteuid() } @@ -182,7 +189,7 @@ fn now() -> u64 { #[test] fn attaches_a_token_from_the_default_key_file() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); run_rollback(&f, &[]); let seen = f.seen.lock().unwrap(); @@ -209,7 +216,7 @@ fn attaches_a_token_from_the_default_key_file() { fn attaches_a_token_from_the_key_file_flag() { let f = fixture(); let key_path = f.repo.path().join("custom.key"); - std::fs::write(&key_path, KEY).unwrap(); + write_key(&key_path, &KEY); run_rollback(&f, &["--key-file", key_path.to_str().unwrap()]); assert!(f.seen.lock().unwrap().last().unwrap().token.is_some()); } @@ -230,7 +237,7 @@ fn sends_no_token_without_a_key() { #[test] fn explicit_token_is_not_replaced() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); run_rollback(&f, &["--approval-token", "1:deadbeef"]); let seen = f.seen.lock().unwrap(); assert_eq!(seen.len(), 1); @@ -245,7 +252,7 @@ fn explicit_token_is_not_replaced() { fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { let f = fixture(); // Wrong length: the daemon would run keyless, so the CLI must not fail. - std::fs::write(f.repo.path().join(".agentic/approval.key"), [1u8; 5]).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &[1u8; 5]); run_rollback(&f, &[]); assert_eq!(f.seen.lock().unwrap()[0].token, None); f.seen.lock().unwrap().clear(); @@ -262,7 +269,7 @@ fn unusable_default_key_sends_no_token_but_a_bad_explicit_key_fails() { #[test] fn preview_and_applied_rollback_name_the_pinned_hash_and_only_the_applied_one_is_signed() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); // No --yes: preview, then confirm. let out = agentic(&f, &["rollback", "main"], "y\n"); assert!( @@ -293,7 +300,7 @@ fn preview_and_applied_rollback_name_the_pinned_hash_and_only_the_applied_one_is #[test] fn destructive_preview_gets_its_own_token_and_the_apply_is_minted_fresh() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); let out = agentic(&f, &["rollback", "main", "--accept-data-loss"], "y\n"); assert!( out.status.success(), @@ -314,7 +321,7 @@ fn destructive_preview_gets_its_own_token_and_the_apply_is_minted_fresh() { #[test] fn declining_the_prompt_sends_no_signed_apply() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); let out = agentic(&f, &["rollback", "main"], "n\n"); assert!(!out.status.success()); let seen = f.seen.lock().unwrap(); @@ -325,7 +332,7 @@ fn declining_the_prompt_sends_no_signed_apply() { #[test] fn dry_run_flag_carries_no_auto_token() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); run_rollback(&f, &["--dry-run"]); let seen = f.seen.lock().unwrap(); assert!(seen[0].dry_run); @@ -341,7 +348,7 @@ fn refuses_to_sign_a_resolved_hash_that_is_not_64_lowercase_hex() { "ab".repeat(32) + "\n", ] { let f = fixture_resolving(bad.clone()); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); let out = rollback_cmd(&f, &[]); assert!(!out.status.success(), "{bad:?} must be refused"); assert!( @@ -356,7 +363,7 @@ fn refuses_to_sign_a_resolved_hash_that_is_not_64_lowercase_hex() { #[test] fn key_warning_goes_to_stderr_and_json_stdout_stays_parseable() { let f = fixture(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), [1u8; 5]).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &[1u8; 5]); let out = agentic(&f, &["--json", "rollback", "main", "--yes"], ""); assert!(out.status.success()); serde_json::from_slice::(&out.stdout).unwrap_or_else(|e| { @@ -375,7 +382,7 @@ fn apply_is_not_signed_when_the_preview_reported_no_approval_needed() { // reverse migration nobody saw. The daemon's gate refuses it instead. for extra in [&[][..], &["--yes"][..]] { let f = fixture_no_approval(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); let mut args = vec!["rollback", "main"]; args.extend_from_slice(extra); let out = agentic(&f, &args, "y\n"); @@ -395,11 +402,10 @@ fn apply_is_not_signed_when_the_preview_reported_no_approval_needed() { fn oversized_default_key_file_is_rejected_without_a_token() { let f = fixture(); // Far longer than a key; only the first 33 bytes may be read. - std::fs::write( + write_key( f.repo.path().join(".agentic/approval.key"), - vec![7u8; 1 << 20], - ) - .unwrap(); + &vec![7u8; 1 << 20], + ); run_rollback(&f, &[]); let seen = f.seen.lock().unwrap(); assert_eq!(seen.len(), 1, "no key, so no pinning preview: {seen:?}"); @@ -410,7 +416,7 @@ fn oversized_default_key_file_is_rejected_without_a_token() { fn accept_data_loss_apply_is_signed_even_if_the_preview_omits_approval_required() { // An older daemon's reply has no approval_required (it reads as false). let f = fixture_no_approval(); - std::fs::write(f.repo.path().join(".agentic/approval.key"), KEY).unwrap(); + write_key(f.repo.path().join(".agentic/approval.key"), &KEY); let out = agentic(&f, &["rollback", "main", "--accept-data-loss"], "y\n"); assert!( out.status.success(), @@ -449,7 +455,7 @@ fn a_fifo_at_the_default_key_path_is_skipped_not_blocked_on() { fn a_symlinked_default_key_is_skipped() { let f = fixture(); let real = f.repo.path().join("real.key"); - std::fs::write(&real, KEY).unwrap(); + write_key(&real, &KEY); std::os::unix::fs::symlink(&real, f.repo.path().join(".agentic/approval.key")).unwrap(); run_rollback(&f, &[]); assert_eq!(f.seen.lock().unwrap()[0].token, None); @@ -465,3 +471,98 @@ fn an_explicit_key_that_is_not_a_regular_file_is_an_error() { assert!(String::from_utf8_lossy(&out.stderr).contains("not a regular file")); assert!(f.seen.lock().unwrap().is_empty()); } + +/// `agentic rollback --approval --uid 1000 --key-file [extra]` +/// prints a token; returns it. +fn issue(extra: &[&str]) -> String { + let dir = tempfile::tempdir().unwrap(); + let key = dir.path().join("k"); + write_key(&key, &KEY); + let out = Command::new(env!("CARGO_BIN_EXE_agentic")) + .arg("--repo") + .arg(dir.path()) + .args(["rollback", "--approval", &target_hash(), "--uid", "1000"]) + .arg("--key-file") + .arg(&key) + .args(extra) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).unwrap().trim().to_string() +} + +#[test] +fn issuer_scope_flag_selects_the_token_scope_and_defaults_to_data_loss() { + let key = ApprovalKey::from_bytes(&KEY).unwrap(); + let h = target_hash(); + let rm = issue(&["--scope", "reverse-migration"]); + // Verifies for a plain reverse-migration rollback, not for accept_data_loss. + verify_token_any( + &key, + &[ApprovalScope::ReverseMigration], + &h, + 1000, + &rm, + now(), + ) + .unwrap(); + assert!(verify_token(&key, &h, 1000, &rm, now()).is_err()); + // No flag, or data-loss: the data-loss scope, as before. + for dl in [issue(&[]), issue(&["--scope", "data-loss"])] { + verify_token(&key, &h, 1000, &dl, now()).unwrap(); + assert!(verify_token_any( + &key, + &[ApprovalScope::ReverseMigration], + &h, + 1000, + &dl, + now() + ) + .is_err()); + } +} + +#[test] +fn a_symlink_at_the_key_path_is_never_followed() { + // O_NOFOLLOW: a symlink to a valid key is refused even when the path is + // named explicitly, so a swap after any earlier check cannot be followed. + let f = fixture(); + let real = f.repo.path().join("real.key"); + write_key(&real, &KEY); + let link = f.repo.path().join("link.key"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let out = rollback_cmd(&f, &["--key-file", link.to_str().unwrap()]); + assert!( + !out.status.success(), + "an explicit symlinked key is an error" + ); + assert!(f.seen.lock().unwrap().is_empty()); +} + +#[test] +fn a_group_readable_key_is_skipped_by_default_and_refused_when_named() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(); + let default = f.repo.path().join(".agentic/approval.key"); + write_key(&default, &KEY); + std::fs::set_permissions(&default, std::fs::Permissions::from_mode(0o644)).unwrap(); + // Default path: warning on stderr, no token, the rollback still runs. + let out = rollback_cmd(&f, &[]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(String::from_utf8_lossy(&out.stderr).contains("chmod 600")); + assert_eq!(f.seen.lock().unwrap()[0].token, None); + f.seen.lock().unwrap().clear(); + // Named with --key-file: an error, nothing sent. + let out = rollback_cmd(&f, &["--key-file", default.to_str().unwrap()]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("chmod 600")); + assert!(f.seen.lock().unwrap().is_empty()); +} diff --git a/crates/agentic-core/src/approval.rs b/crates/agentic-core/src/approval.rs index 4dba3459..d38b15ed 100644 --- a/crates/agentic-core/src/approval.rs +++ b/crates/agentic-core/src/approval.rs @@ -57,6 +57,16 @@ pub enum ApprovalScope { ReverseMigration, } +impl ApprovalScope { + /// Stable name for audit events. + pub fn as_str(self) -> &'static str { + match self { + ApprovalScope::DataLoss => "data_loss", + ApprovalScope::ReverseMigration => "reverse_migration", + } + } +} + /// Required approval-key length in bytes (256-bit, Decision 6). pub const APPROVAL_KEY_LEN: usize = 32; @@ -189,6 +199,8 @@ pub fn generate_token_scoped( pub struct VerifiedToken { pub timestamp: u64, pub tag: [u8; 32], + /// The scope whose signing input the tag verified under. + pub scope: ApprovalScope, } impl VerifiedToken { @@ -265,7 +277,11 @@ pub fn verify_token_any( mac.update(&signing_input(*scope, &commit_hash, peer_uid, timestamp)); // Constant-time comparison of the decoded tag bytes. if mac.verify_slice(&tag).is_ok() { - return Ok(VerifiedToken { timestamp, tag }); + return Ok(VerifiedToken { + timestamp, + tag, + scope: *scope, + }); } } Err(ApprovalRejection::InvalidSignature) @@ -483,4 +499,20 @@ mod tests { let dl = generate_token(&key(), &h, 1000, 5_000); assert!(verify_token_any(&key(), &both, &h, 1000, &dl, 5_000).is_ok()); } + + #[test] + fn verified_token_reports_the_scope_it_matched() { + let h = "a".repeat(64); + let both = [ApprovalScope::ReverseMigration, ApprovalScope::DataLoss]; + for scope in both { + let t = generate_token_scoped(&key(), scope, &h, 1, 100); + let v = verify_token_any(&key(), &both, &h, 1, &t, 100).unwrap(); + assert_eq!(v.scope, scope); + } + assert_eq!(ApprovalScope::DataLoss.as_str(), "data_loss"); + assert_eq!( + ApprovalScope::ReverseMigration.as_str(), + "reverse_migration" + ); + } } diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index 64aeb162..de7ee99f 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -236,11 +236,12 @@ fn load_approval_key( ); }; // O_NONBLOCK so opening a FIFO returns at once instead of waiting for a - // writer; the regular-file check below then rejects it. + // writer; the regular-file check below then rejects it. O_NOFOLLOW so a + // symlink swapped in after the default-path check is never followed. use std::os::unix::fs::OpenOptionsExt; let opened = std::fs::OpenOptions::new() .read(true) - .custom_flags(libc::O_NONBLOCK) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) .open(path); let mut file = match opened { Ok(f) => f, diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index 65bd2a39..a73b1724 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -105,12 +105,20 @@ pub enum ApprovalError { )] NoPeerUid, #[error( - "this rollback requires an approval_token (accept_data_loss=true per ADR-0014, or a \ - reverse schema migration per ADR-0019), but none was supplied. The `agentic` CLI \ - attaches one automatically when it can read the approval key; otherwise mint one \ - with `agentic rollback --approval --uid --key-file `." + "accept_data_loss=true requires an approval_token (ADR-0014), but none was supplied. \ + The `agentic` CLI attaches one automatically when it can read the approval key; \ + otherwise mint one with `agentic rollback --approval --uid \ + --key-file --scope data-loss`." )] TokenRequired, + #[error( + "this rollback runs reverse schema migrations and requires an approval_token \ + (ADR-0019), but none was supplied. The `agentic` CLI attaches one automatically \ + when it can read the approval key; otherwise mint one with `agentic rollback \ + --approval --uid --key-file --scope reverse-migration`. \ + Do not hand out a data-loss token for this: it also authorizes accept_data_loss." + )] + TokenRequiredForReverseMigration, #[error("approval token rejected: {0}")] Rejected(#[from] ApprovalRejection), } @@ -121,7 +129,9 @@ impl ApprovalError { match self { ApprovalError::KeyNotConfigured => "rejected_no_key_configured", ApprovalError::NoPeerUid => "rejected_no_peer_uid", - ApprovalError::TokenRequired => "rejected_no_token", + ApprovalError::TokenRequired | ApprovalError::TokenRequiredForReverseMigration => { + "rejected_no_token" + } ApprovalError::Rejected(r) => r.audit_decision(), } } @@ -151,6 +161,7 @@ fn audit_forced_data_loss( decision: &str, token: Option<&str>, reason: GateReason, + scope: Option, ) { let reason = reason.as_str(); let token_prefix = token.map(token_prefix_for_audit); @@ -163,6 +174,9 @@ fn audit_forced_data_loss( target_commit_hash, decision, reason, + // The scope the token verified under (ADR-0019): a data-loss + // token also covers a plain reverse-migration rollback. + scope = scope.map(ApprovalScope::as_str), ?token_prefix, ); } else { @@ -205,6 +219,7 @@ fn approval_gate( err.audit_decision(), approval_token, reason, + None, ); err }; @@ -221,7 +236,10 @@ fn approval_gate( }; // (c) Key present but no token supplied. let Some(token) = approval_token else { - return Err(reject(ApprovalError::TokenRequired)); + return Err(reject(match reason { + GateReason::AcceptDataLoss => ApprovalError::TokenRequired, + GateReason::ReverseMigration => ApprovalError::TokenRequiredForReverseMigration, + })); }; // (d) Verify. let now = now_unix_seconds(); @@ -254,7 +272,14 @@ fn approval_gate( } } // (e) Valid — audit the accepted path too. - audit_forced_data_loss(peer_uid, &commit_hash, "accepted", approval_token, reason); + audit_forced_data_loss( + peer_uid, + &commit_hash, + "accepted", + approval_token, + reason, + Some(verified.scope), + ); Ok(()) } @@ -398,10 +423,13 @@ pub async fn execute( // Phase 2: synchronous filesystem I/O — no adapter call in // flight. `accept_data_loss` is forwarded so // `check_irreversible` can honor the operator's opt-in for - // IRREVERSIBLE-marked migrations. Read-only, and ahead of the - // approval gate so a missing or IRREVERSIBLE `.down.sql` is - // refused before a single-use token is consumed and before an - // `accepted` audit event. + // IRREVERSIBLE-marked migrations. Read-only. On this path (a + // plain reverse-migration rollback) it runs ahead of the approval + // gate, so a missing or IRREVERSIBLE `.down.sql` is refused + // before a single-use token is consumed and before an `accepted` + // audit event. With accept_data_loss=true the gate already ran at + // the top of `execute`, so there the token is consumed (and the + // audit event written) before this load. let steps = migrate::load_steps( state.refs.agentic_dir(), &migration_names, diff --git a/crates/agenticd/src/wire_error.rs b/crates/agenticd/src/wire_error.rs index 9a3a2f78..9ce7c116 100644 --- a/crates/agenticd/src/wire_error.rs +++ b/crates/agenticd/src/wire_error.rs @@ -47,7 +47,7 @@ pub fn map_anyhow_to_response_error(err: anyhow::Error) -> Response { let code = match gate { A::KeyNotConfigured => "approval_key_not_configured", A::NoPeerUid => "approval_no_peer_uid", - A::TokenRequired => "approval_required", + A::TokenRequired | A::TokenRequiredForReverseMigration => "approval_required", A::Rejected(R::Malformed) => "approval_token_malformed", A::Rejected(R::Expired { .. }) => "approval_token_expired", A::Rejected(R::InvalidSignature) => "approval_token_invalid_signature", @@ -304,6 +304,10 @@ mod tests { anyhow::Error::new(ApprovalError::TokenRequired), "approval_required", ), + ( + anyhow::Error::new(ApprovalError::TokenRequiredForReverseMigration), + "approval_required", + ), ( anyhow::Error::new(ApprovalError::Rejected(ApprovalRejection::Malformed)), "approval_token_malformed", diff --git a/crates/agenticd/tests/approval_key_discovery.rs b/crates/agenticd/tests/approval_key_discovery.rs index 451374a4..24a143e4 100644 --- a/crates/agenticd/tests/approval_key_discovery.rs +++ b/crates/agenticd/tests/approval_key_discovery.rs @@ -204,3 +204,32 @@ async fn a_fifo_named_with_the_flag_does_not_block_startup_either() { "approval_key_not_configured" ); } + +#[tokio::test] +async fn a_symlink_to_a_valid_key_is_not_followed_default_or_explicit() { + // Default path: treated as no key. + let repo = tempfile::tempdir().unwrap(); + let state = state_dir(repo.path()); + let real = state.join("real.key"); + std::fs::write(&real, [5u8; 32]).unwrap(); + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); + std::os::unix::fs::symlink(&real, state.join("approval.key")).unwrap(); + assert_eq!( + rollback_error_code(repo.path()).await, + "approval_key_not_configured" + ); + + // Explicit flag: O_NOFOLLOW makes it unreadable, so fail closed. + let repo = tempfile::tempdir().unwrap(); + let state = state_dir(repo.path()); + let real = state.join("real.key"); + std::fs::write(&real, [5u8; 32]).unwrap(); + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); + let link = state.join("link.key"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let flag = std::ffi::OsString::from("--approval-key-file"); + assert_eq!( + rollback_error_code_with(repo.path(), &[flag.as_os_str(), link.as_os_str()]).await, + "approval_key_not_configured" + ); +} diff --git a/crates/agenticd/tests/reverse_migration.rs b/crates/agenticd/tests/reverse_migration.rs index c41a72be..c81dc1e5 100644 --- a/crates/agenticd/tests/reverse_migration.rs +++ b/crates/agenticd/tests/reverse_migration.rs @@ -497,9 +497,9 @@ async fn adr_0019_reverse_migration_rollback_needs_a_token_against_postgres() { assert!( err.chain().any(|e| matches!( e.downcast_ref::(), - Some(ApprovalError::TokenRequired) + Some(ApprovalError::TokenRequiredForReverseMigration) )), - "expected TokenRequired, got: {err:#}" + "expected TokenRequiredForReverseMigration, got: {err:#}" ); assert_eq!(migration_row_count(&admin, &schema).await.unwrap(), 2); assert!(table_exists(&admin, &schema, "step_b").await.unwrap()); diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 12df3a09..57438949 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -942,7 +942,7 @@ async fn reverse_migration_rollback_without_token_is_refused_before_side_effects .expect_err("a plain reverse-migration rollback needs a token"); assert!(matches!( downcast_approval(&err), - ApprovalError::TokenRequired + ApprovalError::TokenRequiredForReverseMigration )); assert_untouched(&state, &adapter, tip).await; assert!( @@ -1284,3 +1284,106 @@ async fn legacy_format_token_still_authorizes_accept_data_loss() { .expect("a legacy token keeps working for accept_data_loss"); assert!(out.executed); } + +#[tokio::test] +async fn missing_token_diagnostics_name_the_right_scope() { + // A plain reverse-migration rollback must point operators at the + // reverse-migration scope, never at a data-loss token, which a worker + // could replay with accept_data_loss. accept_data_loss points at data-loss. + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let plain = rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, None, false), + Some(1000), + ) + .await + .expect_err("no token"); + let msg = format!("{plain:#}"); + assert!(msg.contains("--scope reverse-migration"), "{msg}"); + assert!(!msg.contains("--scope data-loss"), "{msg}"); + + let destructive = rollback::execute( + Arc::clone(&state), + destructive_args(&baseline, None), + Some(1000), + ) + .await + .expect_err("no token"); + let msg = format!("{destructive:#}"); + assert!(msg.contains("--scope data-loss"), "{msg}"); + assert!(!msg.contains("--scope reverse-migration"), "{msg}"); +} + +#[derive(Clone, Default)] +struct LogBuf(Arc>>); + +impl std::io::Write for LogBuf { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogBuf { + type Writer = LogBuf; + fn make_writer(&'a self) -> LogBuf { + self.clone() + } +} + +/// The process-wide log buffer. A global subscriber, installed once, because +/// a thread-local default can lose to callsite-interest caching when other +/// tests in the binary hit the same callsites first. +fn audit_log() -> &'static LogBuf { + static LOG: std::sync::OnceLock = std::sync::OnceLock::new(); + LOG.get_or_init(|| { + let buf = LogBuf::default(); + let _ = tracing::subscriber::set_global_default( + tracing_subscriber::fmt() + .with_writer(buf.clone()) + .with_ansi(false) + .finish(), + ); + buf + }) +} + +#[tokio::test] +async fn accepted_audit_event_names_the_scope_the_token_verified_under() { + use agentic_core::approval::{generate_token_scoped, ApprovalScope}; + let buf = audit_log(); + for (scope, expect) in [ + ( + ApprovalScope::ReverseMigration, + "scope=\"reverse_migration\"", + ), + (ApprovalScope::DataLoss, "scope=\"data_loss\""), + ] { + let (state, adapter, baseline, _dir) = setup_gate_state(true).await; + contaminate(&state, &adapter).await; + let tok = generate_token_scoped(&test_key(), scope, &baseline, 1000, now_secs()); + // The audited token_prefix is the first 8 hex chars of the tag: unique + // to this scope's token, even if another test shares the commit hash. + let prefix = tok.split_once(':').unwrap().1[..8].to_string(); + rollback::execute( + Arc::clone(&state), + plain_args(&state, &baseline, Some(tok), false), + Some(1000), + ) + .await + .unwrap(); + // Other tests log into the same buffer; find this run's event by it. + let log = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap(); + let line = log + .lines() + .find(|l| l.contains("RollbackForcedDataLoss") && l.contains(&prefix)) + .unwrap_or_else(|| panic!("no audit event for {prefix} in: {log}")); + assert!(line.contains("decision=\"accepted\""), "{line}"); + assert!(line.contains(expect), "{expect}: {line}"); + assert!(line.contains("reason=\"reverse_migration\""), "{line}"); + } +} diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md index be7e0f9a..54feacea 100644 --- a/docs/adr/0019-approval-for-reverse-migration-rollback.md +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -40,7 +40,8 @@ If so, and the request is not a dry run, the request passes the same gate as an The token format, the HMAC binding to the target commit and the peer UID, the five-minute window and the single-use ledger are the ADR-0014 ones, unchanged. The gate runs before any side effect. -The down-migration files are loaded (read-only) just before it, so a missing or `IRREVERSIBLE` file is refused before a token is consumed or an `accepted` audit event is written. +For a plain reverse-migration rollback, the down-migration files are loaded (read-only) just before the gate, so a missing or `IRREVERSIBLE` file is refused before a token is consumed or an `accepted` audit event is written. +With `accept_data_loss=true` the gate runs earlier, at the start of the request, so there the token is consumed and the event written before the files are loaded. The code that builds the plan only reads: it resolves the ref, loads the target, checks the prompts tree and queries the backend for the live schema version and the pending migration names. The gate sits right after that, before the reverse migrations run, the memory restore, the prompts write-back and the forward-record. A refused request changes nothing. @@ -53,6 +54,7 @@ That includes a rollback whose target has no `schema_version`, and one whose tar Audit. The gate emits the existing `RollbackForcedDataLoss` event, with the same `decision` values. +An accepted event also carries `scope`, `data_loss` or `reverse_migration`, the scope the token verified under. The event gains a `reason` field: `accept_data_loss` for the ADR-0014 trigger and `reverse_migration` for this one. Events from before this ADR carry no `reason` and mean `accept_data_loss`. An alert on forced data loss should filter on `reason = "accept_data_loss"`, so routine operator rollbacks that run reverse migrations do not trip it. @@ -118,6 +120,7 @@ The CLI also checks who it is talking to. In a flow that may auto-sign, every request (resolving the target, the preview, the applied request) goes over a connection whose peer uid, read from the kernel, is the uid that owns the key file. If a check fails, the CLI gives up on signing: it warns on stderr and carries on without a token, and the daemon's gate refuses if one was needed. With `--accept-data-loss` the applied request is signed after a successful preview even if the reply omits `approval_required`, as an older daemon's would. +Both sides open the key file with `O_NOFOLLOW` and `O_NONBLOCK`, so a symlink swapped in after the default-path check is never followed, and a symlinked key path is refused whether it is the default or named explicitly. The CLI skips a default key path that is a symlink, FIFO or other special file, with a warning, and the daemon treats such a default path as no key, so a special file cannot block either. A key named explicitly must be a regular file (the CLI fails; the daemon warns and runs without a key, as for an unreadable file). It reads at most 33 bytes of the key file, as the daemon does. @@ -151,7 +154,11 @@ Verification: - The single-use ledger keys on the decoded tag as before. The CLI mints a `DataLoss` token for `--accept-data-loss` requests and a `ReverseMigration` token otherwise. -The `agentic rollback --approval` issuance mode keeps minting `DataLoss` tokens, which cover both. +The `agentic rollback --approval` issuance mode takes `--scope reverse-migration|data-loss`. +The default is `data-loss`, so existing callers keep getting the tokens they got before. +An operator who hands a worker a token for an ordinary rollback should use `--scope reverse-migration`, because a `data-loss` token also authorizes `accept_data_loss`. +The daemon's missing-token error says so: for a reverse-migration rollback it recommends `--scope reverse-migration`, and for `accept_data_loss` it recommends `--scope data-loss`. +Both errors keep the wire code `approval_required`. ## Consequences From d4a34c8487caeac8eb7a8cb3bd0d6c6e35e237f2 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:46:09 +0200 Subject: [PATCH 08/10] Follow symlinks for named approval keys and make the audit-scope test unique O_NOFOLLOW now applies only to the auto-discovered default key path, in the CLI and the daemon. A key named with --approval-key-file, --key-file or the issuer is an operator choice and follows symlinks, because Kubernetes and Cloud Run secret volumes expose files through them. O_NONBLOCK and the regular-file and mode checks on the opened handle stay for both. A symlink at the default path is still skipped or treated as no key. ADR-0019 says so. The audit-scope test minted tokens that another test could mint byte for byte (same commit hash, uid and second), so its search could match that test's accept_data_loss line. It now mints with a timestamp offset no other test uses and also requires reason="reverse_migration" in the line. --- crates/agentic-cli/src/main.rs | 34 ++++++++++---- crates/agentic-cli/tests/rollback_token.rs | 15 +++---- crates/agenticd/src/main.rs | 44 +++++++++++++++---- .../agenticd/tests/approval_key_discovery.rs | 7 +-- crates/agenticd/tests/rollback_in_memory.rs | 12 ++++- ...approval-for-reverse-migration-rollback.md | 4 +- 6 files changed, 85 insertions(+), 31 deletions(-) diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index b20997e5..e746d2da 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -261,15 +261,22 @@ fn read_capped(reader: impl std::io::Read) -> std::io::Result> { Ok(bytes) } -fn read_key(key_file: &Path) -> anyhow::Result { +/// Read an approval key. `nofollow` is set for the auto-discovered default +/// path, so a symlink swapped in after discovery is never followed. A path the +/// operator named (`--key-file`, the issuer) follows symlinks, because secret +/// volumes expose files through them. +fn read_key(key_file: &Path, nofollow: bool) -> anyhow::Result { use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; let ctx = || format!("reading approval key {}", key_file.display()); // O_NONBLOCK so opening a FIFO returns at once instead of waiting for a - // writer; the regular-file check below then refuses it. O_NOFOLLOW so a - // symlink swapped in after the default-path check is never followed. + // writer; the regular-file check below then refuses it. + let mut flags = libc::O_NONBLOCK; + if nofollow { + flags |= libc::O_NOFOLLOW; + } let file = std::fs::OpenOptions::new() .read(true) - .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .custom_flags(flags) .open(key_file) .with_context(ctx)?; let meta = file.metadata().with_context(ctx)?; @@ -326,7 +333,7 @@ fn mint_token( commit_hash: &str, uid: u32, ) -> anyhow::Result { - mint_with_key(&read_key(key_file)?.key, scope, commit_hash, uid) + mint_with_key(&read_key(key_file, false)?.key, scope, commit_hash, uid) } /// ADR-0014 operator token issuer. Prints a token to stdout. Does not @@ -390,7 +397,7 @@ fn load_rollback_key(repo: &Path, key_file: Option) -> anyhow::Result Ok(Some(key)), Err(e) if !explicit => { eprintln!("warning: not attaching an approval token: {e:#}"); @@ -913,6 +920,17 @@ mod tests { std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); } + #[test] + fn nofollow_applies_only_to_the_default_path() { + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real.key"); + write_key_0600(&real, &[7u8; 32]); + let link = dir.path().join("link.key"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + assert!(read_key(&link, true).is_err()); + assert!(read_key(&link, false).is_ok()); + } + #[test] fn a_group_or_other_accessible_key_is_refused_with_a_chmod_hint() { use std::os::unix::fs::PermissionsExt; @@ -921,7 +939,7 @@ mod tests { write_key_0600(&path, &[7u8; 32]); for mode in [0o644, 0o640, 0o604, 0o660, 0o666] { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); - let err = read_key(&path) + let err = read_key(&path, false) .err() .unwrap_or_else(|| panic!("{mode:o} accepted")); assert!( @@ -931,7 +949,7 @@ mod tests { } for mode in [0o600, 0o400] { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); - assert!(read_key(&path).is_ok(), "{mode:o}"); + assert!(read_key(&path, false).is_ok(), "{mode:o}"); } } diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index f5a576a9..791a0fce 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -527,20 +527,17 @@ fn issuer_scope_flag_selects_the_token_scope_and_defaults_to_data_loss() { } #[test] -fn a_symlink_at_the_key_path_is_never_followed() { - // O_NOFOLLOW: a symlink to a valid key is refused even when the path is - // named explicitly, so a swap after any earlier check cannot be followed. +fn an_explicitly_named_symlinked_key_is_followed() { + // A path the operator names follows symlinks: secret volumes are mounted + // that way. Only the auto-discovered default is opened with O_NOFOLLOW. let f = fixture(); let real = f.repo.path().join("real.key"); write_key(&real, &KEY); let link = f.repo.path().join("link.key"); std::os::unix::fs::symlink(&real, &link).unwrap(); - let out = rollback_cmd(&f, &["--key-file", link.to_str().unwrap()]); - assert!( - !out.status.success(), - "an explicit symlinked key is an error" - ); - assert!(f.seen.lock().unwrap().is_empty()); + run_rollback(&f, &["--key-file", link.to_str().unwrap()]); + let seen = f.seen.lock().unwrap(); + assert!(seen.last().unwrap().token.is_some(), "{seen:?}"); } #[test] diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index de7ee99f..b890243f 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -221,8 +221,14 @@ fn approval_key_path( /// fail-closed whatever its mode. The mode comes from the opened handle, not /// a separate path stat, so the file checked is the file read. It only /// excludes other uids: a process sharing the daemon's uid can read a 0600 key. +/// +/// `nofollow` is set for the auto-discovered default path, so a symlink +/// swapped in after the discovery check is never followed. A path named with +/// `--approval-key-file` is an operator choice and follows symlinks, because +/// Kubernetes and Cloud Run secret volumes expose files through them. fn load_approval_key( path: Option<&std::path::Path>, + nofollow: bool, ) -> anyhow::Result> { let Some(path) = path else { return Ok(None); @@ -236,12 +242,15 @@ fn load_approval_key( ); }; // O_NONBLOCK so opening a FIFO returns at once instead of waiting for a - // writer; the regular-file check below then rejects it. O_NOFOLLOW so a - // symlink swapped in after the default-path check is never followed. + // writer; the regular-file check below then rejects it. use std::os::unix::fs::OpenOptionsExt; + let mut flags = libc::O_NONBLOCK; + if nofollow { + flags |= libc::O_NOFOLLOW; + } let opened = std::fs::OpenOptions::new() .read(true) - .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .custom_flags(flags) .open(path); let mut file = match opened { Ok(f) => f, @@ -505,6 +514,7 @@ async fn main() -> anyhow::Result<()> { // the socket, so a malformed key aborts startup before accepting work. let approval_key = load_approval_key( approval_key_path(args.approval_key_file.as_deref(), &agentic_dir).as_deref(), + args.approval_key_file.is_none(), )?; let peer_auth = Arc::new(peer_auth); @@ -705,6 +715,22 @@ mod tests { ); } + // The default path is opened with O_NOFOLLOW; a named path follows + // symlinks (secret volumes). + #[cfg(unix)] + #[test] + fn nofollow_applies_only_to_the_default_path() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real.key"); + std::fs::write(&real, [7u8; 32]).unwrap(); + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); + let link = dir.path().join("link.key"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + assert!(load_approval_key(Some(&link), true).unwrap().is_none()); + assert!(load_approval_key(Some(&link), false).unwrap().is_some()); + } + // ADR-0019 Decision 3: only a regular file counts as the default key. A // FIFO would block the open, a symlink is not followed. #[cfg(unix)] @@ -733,7 +759,7 @@ mod tests { std::fs::write(&path, [7u8; 32]).unwrap(); for mode in [0o644, 0o640, 0o604, 0o660, 0o666] { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); - let err = load_approval_key(Some(&path)) + let err = load_approval_key(Some(&path), false) .expect_err(&format!("mode {mode:o} must abort startup")); let msg = err.to_string(); assert!(msg.contains("chmod 600"), "{msg}"); @@ -741,17 +767,19 @@ mod tests { } for mode in [0o600, 0o400] { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); - assert!(load_approval_key(Some(&path)).unwrap().is_some()); + assert!(load_approval_key(Some(&path), false).unwrap().is_some()); } // Empty file, even with a loose mode, stays fail-closed (Decision 4). let empty = dir.path().join("empty.key"); std::fs::write(&empty, []).unwrap(); std::fs::set_permissions(&empty, std::fs::Permissions::from_mode(0o644)).unwrap(); - assert!(load_approval_key(Some(&empty)).unwrap().is_none()); + assert!(load_approval_key(Some(&empty), false).unwrap().is_none()); // A path that opens but fails to read (a directory) too. - assert!(load_approval_key(Some(dir.path())).unwrap().is_none()); + assert!(load_approval_key(Some(dir.path()), false) + .unwrap() + .is_none()); // Unreadable/missing stays fail-closed, not an abort. - assert!(load_approval_key(Some(&dir.path().join("missing"))) + assert!(load_approval_key(Some(&dir.path().join("missing")), false) .unwrap() .is_none()); } diff --git a/crates/agenticd/tests/approval_key_discovery.rs b/crates/agenticd/tests/approval_key_discovery.rs index 24a143e4..83845181 100644 --- a/crates/agenticd/tests/approval_key_discovery.rs +++ b/crates/agenticd/tests/approval_key_discovery.rs @@ -206,7 +206,7 @@ async fn a_fifo_named_with_the_flag_does_not_block_startup_either() { } #[tokio::test] -async fn a_symlink_to_a_valid_key_is_not_followed_default_or_explicit() { +async fn a_symlink_is_refused_as_the_default_key_but_followed_when_named() { // Default path: treated as no key. let repo = tempfile::tempdir().unwrap(); let state = state_dir(repo.path()); @@ -219,7 +219,8 @@ async fn a_symlink_to_a_valid_key_is_not_followed_default_or_explicit() { "approval_key_not_configured" ); - // Explicit flag: O_NOFOLLOW makes it unreadable, so fail closed. + // Explicit flag: an operator choice, so the symlink is followed (secret + // volumes are mounted that way) and the key loads. let repo = tempfile::tempdir().unwrap(); let state = state_dir(repo.path()); let real = state.join("real.key"); @@ -230,6 +231,6 @@ async fn a_symlink_to_a_valid_key_is_not_followed_default_or_explicit() { let flag = std::ffi::OsString::from("--approval-key-file"); assert_eq!( rollback_error_code_with(repo.path(), &[flag.as_os_str(), link.as_os_str()]).await, - "approval_key_not_configured" + "approval_required" ); } diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 57438949..a86b7e02 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -1365,7 +1365,11 @@ async fn accepted_audit_event_names_the_scope_the_token_verified_under() { ] { let (state, adapter, baseline, _dir) = setup_gate_state(true).await; contaminate(&state, &adapter).await; - let tok = generate_token_scoped(&test_key(), scope, &baseline, 1000, now_secs()); + // A timestamp no other test uses (they mint at now_secs()), still + // inside the TTL: tokens are deterministic in (key, scope, commit, + // uid, timestamp), so another test sharing the baseline hash and the + // second would otherwise mint a byte-identical token. + let tok = generate_token_scoped(&test_key(), scope, &baseline, 1000, now_secs() - 37); // The audited token_prefix is the first 8 hex chars of the tag: unique // to this scope's token, even if another test shares the commit hash. let prefix = tok.split_once(':').unwrap().1[..8].to_string(); @@ -1380,7 +1384,11 @@ async fn accepted_audit_event_names_the_scope_the_token_verified_under() { let log = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap(); let line = log .lines() - .find(|l| l.contains("RollbackForcedDataLoss") && l.contains(&prefix)) + .find(|l| { + l.contains("RollbackForcedDataLoss") + && l.contains(&prefix) + && l.contains("reason=\"reverse_migration\"") + }) .unwrap_or_else(|| panic!("no audit event for {prefix} in: {log}")); assert!(line.contains("decision=\"accepted\""), "{line}"); assert!(line.contains(expect), "{expect}: {line}"); diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md index 54feacea..a87fde1a 100644 --- a/docs/adr/0019-approval-for-reverse-migration-rollback.md +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -120,7 +120,9 @@ The CLI also checks who it is talking to. In a flow that may auto-sign, every request (resolving the target, the preview, the applied request) goes over a connection whose peer uid, read from the kernel, is the uid that owns the key file. If a check fails, the CLI gives up on signing: it warns on stderr and carries on without a token, and the daemon's gate refuses if one was needed. With `--accept-data-loss` the applied request is signed after a successful preview even if the reply omits `approval_required`, as an older daemon's would. -Both sides open the key file with `O_NOFOLLOW` and `O_NONBLOCK`, so a symlink swapped in after the default-path check is never followed, and a symlinked key path is refused whether it is the default or named explicitly. +Both sides open the key file with `O_NONBLOCK`, and check that the opened handle is a regular file. +The auto-discovered default path is also opened with `O_NOFOLLOW`, so a symlink swapped in after the discovery check is never followed, and a symlink at the default path is skipped (CLI, with a warning) or treated as no key (daemon). +A key named explicitly (`--approval-key-file`, `--key-file`, the issuer) is an operator choice and follows symlinks, because Kubernetes and Cloud Run secret volumes expose files through them. The CLI skips a default key path that is a symlink, FIFO or other special file, with a warning, and the daemon treats such a default path as no key, so a special file cannot block either. A key named explicitly must be a regular file (the CLI fails; the daemon warns and runs without a key, as for an unreadable file). It reads at most 33 bytes of the key file, as the daemon does. From fe75b298583e946e0bd6d04a8bfcbdb79a9c815f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:49:12 +0200 Subject: [PATCH 09/10] Require --approval when --scope is given Without issuance mode the scope flag was silently ignored. Make clap reject it and apply the data-loss default inside issuance only. --- crates/agentic-cli/src/main.rs | 5 +++-- crates/agentic-cli/tests/rollback_token.rs | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index e746d2da..3bc2edc4 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -174,8 +174,8 @@ enum Command { /// authorizes only a rollback that runs reverse migrations; /// `data-loss` (the default, as before) also authorizes /// `--accept-data-loss`. Hand a worker the narrowest scope. - #[arg(long, value_enum, default_value_t = IssueScope::DataLoss)] - scope: IssueScope, + #[arg(long, value_enum, requires = "approval")] + scope: Option, /// Path to the 32-byte approval key. Used by the issuance mode and /// to attach a token to a rollback automatically (ADR-0019). #[arg(long)] @@ -221,6 +221,7 @@ async fn main() -> anyhow::Result<()> { } => { if let Some(commit_hash) = approval { // Issuance mode: mint a token, no daemon contact. + let scope = scope.unwrap_or(IssueScope::DataLoss); return cmd_mint_approval(&commit_hash, uid, key_file, scope.into()); } let target = target diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index 791a0fce..3f7364ca 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -563,3 +563,14 @@ fn a_group_readable_key_is_skipped_by_default_and_refused_when_named() { assert!(String::from_utf8_lossy(&out.stderr).contains("chmod 600")); assert!(f.seen.lock().unwrap().is_empty()); } + +#[test] +fn scope_without_approval_is_rejected() { + let out = std::process::Command::new(env!("CARGO_BIN_EXE_agentic")) + .args(["rollback", "main", "--scope", "reverse-migration"]) + .output() + .expect("run agentic"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("--approval"), "got: {stderr}"); +} From 978d6f009d70c8eacd49d01804303bafc1e159dc Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:58:31 +0200 Subject: [PATCH 10/10] Default offline approval tokens to the reverse-migration scope A data-loss token also authorizes accept_data_loss, so it should be asked for explicitly. An accept_data_loss request with the narrower token fails with an error that names --scope data-loss. --- crates/agentic-cli/src/main.rs | 8 ++-- crates/agentic-cli/tests/rollback_token.rs | 41 ++++++++++--------- ...0014-destructive-rollback-approval-gate.md | 4 +- ...approval-for-reverse-migration-rollback.md | 4 +- 4 files changed, 30 insertions(+), 27 deletions(-) diff --git a/crates/agentic-cli/src/main.rs b/crates/agentic-cli/src/main.rs index 3bc2edc4..2969b69d 100644 --- a/crates/agentic-cli/src/main.rs +++ b/crates/agentic-cli/src/main.rs @@ -171,9 +171,9 @@ enum Command { #[arg(long)] uid: Option, /// Scope of the minted token (issuance mode). `reverse-migration` - /// authorizes only a rollback that runs reverse migrations; - /// `data-loss` (the default, as before) also authorizes - /// `--accept-data-loss`. Hand a worker the narrowest scope. + /// (the default) authorizes only a rollback that runs reverse + /// migrations; `data-loss` also authorizes `--accept-data-loss` and + /// must be asked for explicitly. #[arg(long, value_enum, requires = "approval")] scope: Option, /// Path to the 32-byte approval key. Used by the issuance mode and @@ -221,7 +221,7 @@ async fn main() -> anyhow::Result<()> { } => { if let Some(commit_hash) = approval { // Issuance mode: mint a token, no daemon contact. - let scope = scope.unwrap_or(IssueScope::DataLoss); + let scope = scope.unwrap_or(IssueScope::ReverseMigration); return cmd_mint_approval(&commit_hash, uid, key_file, scope.into()); } let target = target diff --git a/crates/agentic-cli/tests/rollback_token.rs b/crates/agentic-cli/tests/rollback_token.rs index 3f7364ca..badf0623 100644 --- a/crates/agentic-cli/tests/rollback_token.rs +++ b/crates/agentic-cli/tests/rollback_token.rs @@ -496,34 +496,35 @@ fn issue(extra: &[&str]) -> String { } #[test] -fn issuer_scope_flag_selects_the_token_scope_and_defaults_to_data_loss() { +fn issuer_scope_flag_selects_the_token_scope_and_defaults_to_reverse_migration() { let key = ApprovalKey::from_bytes(&KEY).unwrap(); let h = target_hash(); - let rm = issue(&["--scope", "reverse-migration"]); - // Verifies for a plain reverse-migration rollback, not for accept_data_loss. - verify_token_any( - &key, - &[ApprovalScope::ReverseMigration], - &h, - 1000, - &rm, - now(), - ) - .unwrap(); - assert!(verify_token(&key, &h, 1000, &rm, now()).is_err()); - // No flag, or data-loss: the data-loss scope, as before. - for dl in [issue(&[]), issue(&["--scope", "data-loss"])] { - verify_token(&key, &h, 1000, &dl, now()).unwrap(); - assert!(verify_token_any( + // No flag, or reverse-migration: verifies for a plain reverse-migration + // rollback, not for accept_data_loss. + for rm in [issue(&[]), issue(&["--scope", "reverse-migration"])] { + verify_token_any( &key, &[ApprovalScope::ReverseMigration], &h, 1000, - &dl, - now() + &rm, + now(), ) - .is_err()); + .unwrap(); + assert!(verify_token(&key, &h, 1000, &rm, now()).is_err()); } + // data-loss only when asked for. + let dl = issue(&["--scope", "data-loss"]); + verify_token(&key, &h, 1000, &dl, now()).unwrap(); + assert!(verify_token_any( + &key, + &[ApprovalScope::ReverseMigration], + &h, + 1000, + &dl, + now() + ) + .is_err()); } #[test] diff --git a/docs/adr/0014-destructive-rollback-approval-gate.md b/docs/adr/0014-destructive-rollback-approval-gate.md index e7615b4c..5185c680 100644 --- a/docs/adr/0014-destructive-rollback-approval-gate.md +++ b/docs/adr/0014-destructive-rollback-approval-gate.md @@ -149,9 +149,11 @@ v1.1 may introduce KMS-backed signing where the operator holds a KMS key referen The operator's CLI for issuing tokens is a separate concern, handled by the `agentic` command: ``` -agentic rollback --approval --uid --key-file +agentic rollback --approval --uid --key-file --scope data-loss ``` +(`--scope data-loss` since ADR-0019; the default scope only authorizes a rollback that runs reverse migrations.) + This prints a token to stdout that the operator hands to the worker (or pastes into a CI variable, or whatever the deployment shape requires). The token-issuing path lives in `agentic-cli` and does not require the daemon to be running. ## Consequences diff --git a/docs/adr/0019-approval-for-reverse-migration-rollback.md b/docs/adr/0019-approval-for-reverse-migration-rollback.md index a87fde1a..897f09d6 100644 --- a/docs/adr/0019-approval-for-reverse-migration-rollback.md +++ b/docs/adr/0019-approval-for-reverse-migration-rollback.md @@ -157,8 +157,8 @@ Verification: The CLI mints a `DataLoss` token for `--accept-data-loss` requests and a `ReverseMigration` token otherwise. The `agentic rollback --approval` issuance mode takes `--scope reverse-migration|data-loss`. -The default is `data-loss`, so existing callers keep getting the tokens they got before. -An operator who hands a worker a token for an ordinary rollback should use `--scope reverse-migration`, because a `data-loss` token also authorizes `accept_data_loss`. +The default is `reverse-migration`, the narrower scope, because a `data-loss` token also authorizes `accept_data_loss`. +An operator who needs a token for `--accept-data-loss` passes `--scope data-loss` explicitly. Scripts that relied on the old default now get a narrower token, and an `accept_data_loss` request with it fails with an error that names `--scope data-loss`. The daemon's missing-token error says so: for a reverse-migration rollback it recommends `--scope reverse-migration`, and for `accept_data_loss` it recommends `--scope data-loss`. Both errors keep the wire code `approval_required`.