diff --git a/crates/agentic-core/src/approval.rs b/crates/agentic-core/src/approval.rs index 88e8ef39..8b8a070b 100644 --- a/crates/agentic-core/src/approval.rs +++ b/crates/agentic-core/src/approval.rs @@ -27,8 +27,8 @@ use zeroize::{Zeroize, ZeroizeOnDrop}; /// Symmetric-token time-to-live, in seconds (Decision 3). The window is /// symmetric — a token is rejected if `|now - timestamp|` exceeds it — so /// a slightly fast/slow daemon clock can't accept arbitrarily-future -/// tokens. It is the *only* replay defense; there is no persistent -/// anti-replay store. +/// tokens. It bounds how long a token is accepted; the daemon adds a +/// per-process single-use set on top (see `VerifiedToken`). pub const APPROVAL_TOKEN_TTL_SECONDS: u64 = 300; /// HMAC domain-separation string. A future signed-message format using @@ -88,6 +88,8 @@ pub enum ApprovalRejection { Expired { ttl: u64 }, #[error("approval token signature does not verify")] InvalidSignature, + #[error("approval token was already used for a destructive rollback")] + Replayed, } impl ApprovalRejection { @@ -97,6 +99,7 @@ impl ApprovalRejection { ApprovalRejection::Malformed => "rejected_malformed", ApprovalRejection::Expired { .. } => "rejected_expired", ApprovalRejection::InvalidSignature => "rejected_invalid_signature", + ApprovalRejection::Replayed => "rejected_replayed", } } } @@ -129,6 +132,25 @@ pub fn generate_token(key: &ApprovalKey, commit_hash: &str, peer_uid: u32, now: format!("{now}:{}", hex::encode(mac)) } +/// A token that passed `verify_token`. `tag` is the decoded 32-byte HMAC, +/// the canonical identity of the token: the wire string is not canonical +/// (hex decoding is case-insensitive and the timestamp parse accepts a +/// leading `+` and leading zeros), so replay tracking must key on `tag`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VerifiedToken { + pub timestamp: u64, + pub tag: [u8; 32], +} + +impl VerifiedToken { + /// Unix second after which the token fails the time window for every + /// possible `now`. Symmetric window, so a future-dated token verifies + /// until `timestamp + TTL`, not `issue time + TTL`. + pub fn expires_at(&self) -> u64 { + self.timestamp.saturating_add(APPROVAL_TOKEN_TTL_SECONDS) + } +} + /// 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 @@ -142,15 +164,16 @@ pub fn verify_token( peer_uid: u32, token: &str, now: u64, -) -> Result<(), ApprovalRejection> { +) -> Result { let (ts_str, hex_tag) = token.split_once(':').ok_or(ApprovalRejection::Malformed)?; let timestamp: u64 = ts_str.parse().map_err(|_| ApprovalRejection::Malformed)?; let provided_tag = hex::decode(hex_tag).map_err(|_| ApprovalRejection::Malformed)?; // An HMAC-SHA256 tag is exactly 32 bytes; anything else (empty, short, // long) is structurally malformed, not a mis-signed token. - if provided_tag.len() != 32 { - return Err(ApprovalRejection::Malformed); - } + let tag: [u8; 32] = provided_tag + .as_slice() + .try_into() + .map_err(|_| ApprovalRejection::Malformed)?; // Time-bound check before the cryptographic one. Symmetric window so a // skewed-future token is also rejected. Saturating so neither side @@ -168,8 +191,9 @@ pub fn verify_token( 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(&provided_tag) - .map_err(|_| ApprovalRejection::InvalidSignature) + mac.verify_slice(&tag) + .map_err(|_| ApprovalRejection::InvalidSignature)?; + Ok(VerifiedToken { timestamp, tag }) } #[cfg(test)] @@ -312,5 +336,32 @@ mod tests { ApprovalRejection::InvalidSignature.audit_decision(), "rejected_invalid_signature" ); + assert_eq!( + ApprovalRejection::Replayed.audit_decision(), + "rejected_replayed" + ); + } + + #[test] + fn verified_token_exposes_canonical_tag_across_wire_variants() { + let hash = "a".repeat(64); + let tok = generate_token(&key(), &hash, 1, 100); + let (ts, hex_tag) = tok.split_once(':').unwrap(); + let canonical = verify_token(&key(), &hash, 1, &tok, 100).unwrap(); + assert_eq!(canonical.timestamp, 100); + assert_eq!(canonical.expires_at(), 100 + APPROVAL_TOKEN_TTL_SECONDS); + // Uppercase hex, `+`-prefixed and zero-padded timestamps all verify + // to the same tag. + for variant in [ + format!("{ts}:{}", hex_tag.to_ascii_uppercase()), + format!("+{ts}:{hex_tag}"), + format!("000{ts}:{hex_tag}"), + ] { + assert_eq!( + verify_token(&key(), &hash, 1, &variant, 100), + Ok(canonical.clone()), + "variant {variant:?}" + ); + } } } diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index 9ed0e61b..e50d7e8a 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -172,24 +172,44 @@ struct Args { /// destructive rollback rejected, daemon runs — Decision 4). /// * file readable and non-empty but not exactly 32 bytes → abort startup /// (clear operator misconfiguration — Decision 6). +/// * unix: a file that otherwise loads as a key but is accessible by group or +/// other (`mode & 0o077 != 0`) → abort startup. A key others can read lets +/// them mint tokens, so this is an operator misconfiguration. The check runs +/// after the read and empty checks, so an unreadable or empty file stays +/// 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. fn load_approval_key( path: Option<&std::path::Path>, ) -> anyhow::Result> { let Some(path) = path else { return Ok(None); }; - let bytes = match std::fs::read(path) { - Ok(b) => b, + let unreadable = |e: std::io::Error| { + tracing::warn!( + target: "agenticd::approval", + path = %path.display(), + error = %e, + "approval key file unreadable; destructive rollback disabled (fail-closed)" + ); + }; + let mut file = match std::fs::File::open(path) { + Ok(f) => f, Err(e) => { - tracing::warn!( - target: "agenticd::approval", - path = %path.display(), - error = %e, - "approval key file unreadable; destructive rollback disabled (fail-closed)" - ); + unreadable(e); 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. + let limit = (agentic_core::approval::APPROVAL_KEY_LEN + 1) as u64; + if let Err(e) = + std::io::Read::read_to_end(&mut std::io::Read::take(&mut file, limit), &mut bytes) + { + unreadable(e); + return Ok(None); + } if bytes.is_empty() { tracing::warn!( target: "agenticd::approval", @@ -198,6 +218,30 @@ fn load_approval_key( ); return Ok(None); } + // Mode check comes last so it only applies to a file that would + // otherwise load as a key: unreadable and empty files stay fail-closed + // (Decision 4) whatever their mode. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + match file.metadata() { + Ok(m) => { + let mode = m.permissions().mode() & 0o777; + if mode & 0o077 != 0 { + return Err(anyhow!( + "approval key file {} has mode {mode:03o}; it must not be accessible \ + by group or other. Run `chmod 600 {}`; refusing to start", + path.display(), + path.display() + )); + } + } + Err(e) => { + unreadable(e); + return Ok(None); + } + } + } let key = agentic_core::approval::ApprovalKey::from_bytes(&bytes).with_context(|| { format!( "approval key file {} is malformed; refusing to start", @@ -515,7 +559,39 @@ async fn main() -> anyhow::Result<()> { #[cfg(test)] mod tests { - use super::validate_exempt_prefixes; + use super::{load_approval_key, validate_exempt_prefixes}; + + #[cfg(unix)] + #[test] + fn approval_key_file_mode_is_enforced() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("approval.key"); + 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)) + .expect_err(&format!("mode {mode:o} must abort startup")); + let msg = err.to_string(); + assert!(msg.contains("chmod 600"), "{msg}"); + assert!(msg.contains(&path.display().to_string()), "{msg}"); + } + 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()); + } + // 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()); + // A path that opens but fails to read (a directory) too. + assert!(load_approval_key(Some(dir.path())).unwrap().is_none()); + // Unreadable/missing stays fail-closed, not an abort. + assert!(load_approval_key(Some(&dir.path().join("missing"))) + .unwrap() + .is_none()); + } #[test] fn accepts_single_trailing_slash_prefix() { diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index e6bfe8dc..b4a333c7 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -156,11 +156,18 @@ fn audit_forced_data_loss( /// 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. +/// +/// 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 +/// `Replayed`. Dry runs verify but do not consume. The ledger is per +/// process, so a daemon restart or a second instance accepts the token +/// again until its time window closes. fn approval_gate( state: &DaemonState, target_hash: &Hash, peer_uid: Option, approval_token: Option<&str>, + dry_run: bool, ) -> Result<(), ApprovalError> { let commit_hash = target_hash.to_hex(); // lowercase 64-hex (Decision 2) let reject = |err: ApprovalError| -> ApprovalError { @@ -183,8 +190,25 @@ fn approval_gate( return Err(reject(ApprovalError::TokenRequired)); }; // (d) Verify. - if let Err(rej) = verify_token(key, &commit_hash, uid, token, now_unix_seconds()) { - return Err(reject(ApprovalError::Rejected(rej))); + let now = now_unix_seconds(); + let verified = match verify_token(key, &commit_hash, uid, token, now) { + Ok(v) => v, + Err(rej) => return Err(reject(ApprovalError::Rejected(rej))), + }; + if !dry_run { + // Check-and-insert, plus pruning, under one lock acquisition so two + // concurrent requests can't both consume the same tag. A poisoned + // lock still holds a consistent map (no panic-prone code runs while + // it is held), so recover it rather than failing the gate open. + let mut used = state + .used_approval_tokens + .lock() + .unwrap_or_else(|e| e.into_inner()); + used.retain(|_, expiry| *expiry >= now); + if used.insert(verified.tag, verified.expires_at()).is_some() { + drop(used); + return Err(reject(ApprovalError::Rejected(ApprovalRejection::Replayed))); + } } // (e) Valid — audit the accepted path too. audit_forced_data_loss(peer_uid, &commit_hash, "accepted", approval_token); @@ -224,6 +248,7 @@ pub async fn execute( &target_hash, peer_uid, args.approval_token.as_deref(), + args.dry_run, ) .map_err(anyhow::Error::new)?; } diff --git a/crates/agenticd/src/server.rs b/crates/agenticd/src/server.rs index f25d2bb8..79b7b38e 100644 --- a/crates/agenticd/src/server.rs +++ b/crates/agenticd/src/server.rs @@ -72,6 +72,12 @@ pub struct DaemonState { /// (Decision 4). Set at startup from `--approval-key-file` via /// [`DaemonState::with_approval_key`]. pub approval_key: Option, + /// Single-use ledger for approval tokens (ADR-0014 amendment): decoded + /// HMAC tag -> expiry (`token_timestamp + TTL`, unix seconds). A token + /// authorizes at most one non-dry-run destructive rollback per daemon + /// process; this is in-memory only, so a restart or a second daemon + /// instance accepts the token again until it expires. + pub used_approval_tokens: std::sync::Mutex>, /// Static limits in force (issue #118). Set at startup via /// [`DaemonState::with_limits`]; defaults are spec values. pub limits: crate::limits::LimitsConfig, @@ -154,6 +160,7 @@ impl DaemonState { http, peer_auth, approval_key: None, + used_approval_tokens: Default::default(), limits: crate::limits::LimitsConfig::default(), rate: crate::limits::RateLimiter::new( crate::limits::LimitsConfig::default().rate_per_uid, diff --git a/crates/agenticd/src/wire_error.rs b/crates/agenticd/src/wire_error.rs index 67184eff..eec7c166 100644 --- a/crates/agenticd/src/wire_error.rs +++ b/crates/agenticd/src/wire_error.rs @@ -51,6 +51,7 @@ pub fn map_anyhow_to_response_error(err: anyhow::Error) -> Response { A::Rejected(R::Malformed) => "approval_token_malformed", A::Rejected(R::Expired { .. }) => "approval_token_expired", A::Rejected(R::InvalidSignature) => "approval_token_invalid_signature", + A::Rejected(R::Replayed) => "approval_token_replayed", }; return Response::validation(code, message); } @@ -311,6 +312,10 @@ mod tests { anyhow::Error::new(ApprovalError::Rejected(ApprovalRejection::InvalidSignature)), "approval_token_invalid_signature", ), + ( + anyhow::Error::new(ApprovalError::Rejected(ApprovalRejection::Replayed)), + "approval_token_replayed", + ), ]; for (err, expected_code) in cases { // Wrap in a context layer the way the real call site does. diff --git a/crates/agenticd/tests/commit_with_memory.rs b/crates/agenticd/tests/commit_with_memory.rs index 977747a8..bc9dc66c 100644 --- a/crates/agenticd/tests/commit_with_memory.rs +++ b/crates/agenticd/tests/commit_with_memory.rs @@ -122,6 +122,7 @@ async fn commit_with_memory_persists_manifest_via_put_raw() { .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, diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index e6cd97c0..81889c68 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -74,6 +74,7 @@ async fn rollback_reverses_schema_and_restores_memory_in_memory_backend() { .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, @@ -209,6 +210,7 @@ async fn setup_gate_state( .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, @@ -448,6 +450,142 @@ async fn gate_accepts_valid_token_and_rollback_proceeds() { ); } +fn is_replayed(err: &anyhow::Error) -> bool { + matches!( + downcast_approval(err), + ApprovalError::Rejected(agentic_core::approval::ApprovalRejection::Replayed) + ) +} + +/// Non-dry-run destructive args whose `repo` is the real daemon repo, for +/// tests where the rollback must actually execute. +fn real_args(state: &DaemonState, target: &str, token: Option) -> RollbackArgs { + RollbackArgs { + repo: state.repo_root.clone(), + ..destructive_args(target, token) + } +} + +fn dry_run_args(state: &DaemonState, target: &str, token: String) -> RollbackArgs { + RollbackArgs { + target: target.to_string(), + dry_run: true, + accept_data_loss: true, + approval_token: Some(token), + repo: state.repo_root.clone(), + } +} + +#[tokio::test] +async fn gate_token_is_single_use_for_destructive_rollback() { + let (state, _adapter, baseline, _dir) = setup_gate_state(true).await; + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + let first = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok.clone())), + Some(1000), + ) + .await + .expect("first use of a valid token succeeds"); + assert!(first.executed); + + let tip = state.refs.read_branch("main").unwrap(); + let err = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok)), + Some(1000), + ) + .await + .expect_err("second use of the same token must be rejected"); + assert!(is_replayed(&err), "got: {err:#}"); + assert_no_side_effects(&state, tip).await; +} + +#[tokio::test] +async fn gate_dry_run_verifies_but_does_not_consume_token() { + let (state, _adapter, baseline, _dir) = setup_gate_state(true).await; + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + // Several dry runs first: none consume. + for _ in 0..2 { + let out = rollback::execute( + Arc::clone(&state), + dry_run_args(&state, &baseline, tok.clone()), + Some(1000), + ) + .await + .expect("dry run with a valid token succeeds"); + assert!(!out.executed); + } + let out = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok.clone())), + Some(1000), + ) + .await + .expect("real run after dry runs still succeeds once"); + assert!(out.executed); + let err = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok)), + Some(1000), + ) + .await + .expect_err("second real run is a replay"); + assert!(is_replayed(&err), "got: {err:#}"); +} + +#[tokio::test] +async fn gate_replay_detected_across_token_encodings() { + let (state, _adapter, baseline, _dir) = setup_gate_state(true).await; + let ts = now_secs(); + let tok = generate_token(&test_key(), &baseline, 1000, ts); + let hex_tag = tok.split_once(':').unwrap().1.to_string(); + rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok)), + Some(1000), + ) + .await + .expect("canonical token succeeds once"); + + // Same tag, different wire spelling: still the same token. + for variant in [ + format!("{ts}:{}", hex_tag.to_ascii_uppercase()), + format!("+{ts}:{hex_tag}"), + format!("000{ts}:{hex_tag}"), + ] { + let err = rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(variant.clone())), + Some(1000), + ) + .await + .expect_err("re-encoded token must still be a replay"); + assert!(is_replayed(&err), "variant {variant:?}: {err:#}"); + } +} + +#[tokio::test] +async fn gate_prunes_expired_ledger_entries() { + let (state, _adapter, baseline, _dir) = setup_gate_state(true).await; + state + .used_approval_tokens + .lock() + .unwrap() + .insert([9u8; 32], now_secs() - 1); + let tok = generate_token(&test_key(), &baseline, 1000, now_secs()); + rollback::execute( + Arc::clone(&state), + real_args(&state, &baseline, Some(tok)), + Some(1000), + ) + .await + .expect("valid token succeeds"); + let used = state.used_approval_tokens.lock().unwrap(); + assert_eq!(used.len(), 1, "stale entry pruned, new entry recorded"); + assert!(!used.contains_key(&[9u8; 32])); +} + // ADR-0017: rollback forward-records by re-staging the target commit's // prompt blobs. A baseline containing a high-entropy checkpoint blob // under an exempt prefix must therefore roll back cleanly — without the @@ -477,6 +615,7 @@ async fn rollback_restages_exempt_checkpoint_blob() { .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, diff --git a/docs/adr/0014-destructive-rollback-approval-gate.md b/docs/adr/0014-destructive-rollback-approval-gate.md index 58a22ed0..db2fb697 100644 --- a/docs/adr/0014-destructive-rollback-approval-gate.md +++ b/docs/adr/0014-destructive-rollback-approval-gate.md @@ -22,7 +22,7 @@ The threat model recommends an out-of-band approval mechanism. This ADR specifie The constraints: - **No long-lived secrets in the worker.** The worker is the adversarial party for TM-002. Any approval credential that lives in the worker's process state, env, or filesystem is bypassable by definition. -- **No persistent server-side approval store.** The daemon already has `commit_lock` as its serialization primitive; adding a separate approval-state table or in-memory store complicates the failure model. Approval should be self-contained per request. +- **No persistent server-side approval store.** The daemon already has `commit_lock` as its serialization primitive; adding a persistent approval-state table complicates the failure model. Approval should be self-contained per request. (Amended 2026-11-20: a small in-memory, per-process single-use ledger is kept; see the amendment at the end.) - **Fail-closed default.** A daemon without an approval mechanism configured must reject `accept_data_loss=true` outright — not allow it for ergonomics, not silently ignore the flag, not log a warning and proceed. - **Compatible with the ADR-0004 sidecar shape.** The approval must be issuable by an out-of-band actor (the operator, a side-channel signer, a future KMS) and verifiable by the daemon without contacting that actor at verification time. - **Backwards-compatible wire schema.** Same constraint as ADR-0012: `Request::Rollback` extends, does not break. @@ -32,8 +32,8 @@ The constraints: | # | Decision | One-line rationale | |---|---|---| | 1 | **`Request::Rollback` grows `approval_token: Option`.** When `accept_data_loss == true`, the request is rejected unless `approval_token` is present AND verifies. | Additive wire change; the gate lives on the request itself so the daemon can decide at handler time without consulting external state. | -| 2 | **Approval tokens are HMAC-SHA256 over `(commit_hash, requesting_peer_uid, timestamp)` with a key held by an out-of-band approver.** The daemon verifies; it does not generate. | Self-contained, stateless verification. Operator holds the key; worker cannot forge. The signed payload is the minimum needed to scope the approval to one specific destructive operation. | -| 3 | **Tokens are short-lived (≤ 5 minutes from `timestamp` to verification).** No replay store needed — the window is the only replay defense. | Stateless replay prevention. The 5-minute window matches the operator's coordination loop (run rollback, see audit event, move on) and is short enough that a leaked token's blast radius is bounded. | +| 2 | **Approval tokens are HMAC-SHA256 over `(commit_hash, requesting_peer_uid, timestamp)` with a key held by an out-of-band approver.** The daemon verifies; it does not generate. | Self-contained verification that needs no contact with the approver. Operator holds the key; worker cannot forge. The signed payload is the minimum needed to scope the approval to one specific destructive operation. | +| 3 | **Tokens are short-lived (≤ 5 minutes from `timestamp` to verification).** The window bounds replay; the amendment at the end adds a per-process single-use ledger on top. | Time-bound replay prevention. The 5-minute window matches the operator's coordination loop (run rollback, see audit event, move on) and is short enough that a leaked token's blast radius is bounded. | | 4 | **Without an approval-key file configured (`--approval-key-file `), `accept_data_loss = true` is always rejected. Fail-closed.** | The escape hatch from ADR-0012 (`--insecure-allow-any-uid`) is per-deployment ergonomic; there is no equivalent for TM-002. Destructive operations require explicit operator configuration, full stop. | | 5 | **Every `accept_data_loss = true` attempt emits a structured `RollbackForcedDataLoss` audit event regardless of outcome.** Includes `peer_uid`, `target_commit_hash`, decision (`accepted` / `rejected_no_token` / `rejected_expired` / `rejected_invalid_signature`), and a redacted token prefix for forensics. | The audit primitive a sidecar operator monitors and an after-the-fact forensics consumer reads. Rejection paths emit too so an attacker cannot probe for the gate's existence silently. | | 6 | **HMAC key distribution is operator-managed in v1.0.** The daemon reads it from `--approval-key-file ` at startup; rotation is operator-driven (restart the daemon with a new key file). | KMS-backed signing is the v1.1 conversation. The v1.0 shape needs to ship before 2026-05-26 and a file-on-disk key is the simplest contract that closes TM-002. | @@ -89,7 +89,7 @@ At verification time the daemon computes `abs(now_unix - token_timestamp)`. If t The window is symmetric (covers both stale tokens and clock-skewed-future tokens) so a daemon with a slightly slow clock does not accept arbitrarily-future tokens. -No persistent anti-replay store is needed. Within the 5-minute window a token can be replayed — but only against its bound `(commit_hash, peer_uid)` tuple, and operators in production should treat the window as the "if you sign it, run it immediately" contract. A token that's been used once and leaked still has a bounded blast radius (the same commit + the same UID, within 5 minutes). +No persistent anti-replay store is needed. As originally accepted, a token could be replayed within the 5-minute window against its bound `(commit_hash, peer_uid)` tuple. The 2026-11-20 amendment at the end of this ADR supersedes that: a token now authorizes at most one non-dry-run destructive rollback per daemon process, tracked in an in-memory ledger. The ledger does not survive a restart and is not shared between instances, so a restarted or second daemon accepts the token again until the window closes. Operators should still treat the window as the "if you sign it, run it immediately" contract. The 5-minute window is a constant in v1.0: `const APPROVAL_TOKEN_TTL_SECONDS: u64 = 300;` in `agentic-core/src/approval.rs`. If real operator coordination loops force a wider window, that's a v1.1 conversation. @@ -121,7 +121,8 @@ struct RollbackForcedDataLoss { peer_uid: u32, // From the connection's SO_PEERCRED target_commit_hash: String, decision: &'static str, // accepted, rejected_no_token, rejected_no_key_configured, - // rejected_expired, rejected_invalid_signature, rejected_malformed + // rejected_expired, rejected_invalid_signature, rejected_malformed, + // rejected_replayed (amendment 2026-11-20) token_prefix: Option, // First 8 chars of the token, redacted hex for forensics // None when no token was supplied audit_event_version: u32, // 1, for forward compat @@ -138,7 +139,7 @@ The `token_prefix` (first 8 hex chars of the supplied token) is included in reje ### Decision 6 — Operator-managed key in v1.0; KMS in v1.1 -The key is read once at daemon startup from `--approval-key-file `. The file contains exactly 32 bytes (256 bits) — any deviation aborts daemon startup. The file is read with `tokio::fs::read` (not memory-mapped) so the bytes can be zeroized in `Drop` on shutdown. +The key is read once at daemon startup from `--approval-key-file `. The file contains exactly 32 bytes (256 bits). A non-empty file of any other length aborts daemon startup; a missing, unreadable or empty file disables destructive rollback instead (Decision 4). The file is read once at startup with `std::fs` (not memory-mapped) into an `ApprovalKey`, which is zeroized on drop; the temporary read buffer is not zeroized. Rotation is operator-driven: stop the daemon, write a new key file, restart. There is no in-process rotation in v1.0 — the operational complexity isn't worth the small reduction in key-lifetime risk for a sidecar that restarts on every Cloud Run instance boot anyway. @@ -158,7 +159,7 @@ This prints a token to stdout that the operator hands to the worker (or pastes i - TM-002 closes. The worker cannot forge an approval token because it does not hold the key. An operator who has access to the key must explicitly sign each destructive operation, bounded to that specific commit + that specific peer UID within a 5-minute window. - The audit event gives operators a continuous detection primitive. A spike in `RollbackForcedDataLoss { decision: "rejected_*" }` events is the signal that something is probing the gate or that a worker is misconfigured. -- Stateless verification keeps the daemon's failure model simple. No new persistence layer, no new lock ordering, no new race conditions. +- Verification needs no contact with the approver and no persistence layer. The only daemon state is the in-memory single-use ledger from the amendment, guarded by one mutex that is never held across other locks or I/O. - The contract is durable: the HMAC-domain prefix lets us add other signed-message formats on the same key in the future without ambiguity. - The ADR composes cleanly with ADR-0012. The `peer_uid` from the connection feeds the signed payload directly; the two ADRs together produce "who is connecting" + "what operations they are authorized for", which is the v1.0 authorization model. @@ -176,3 +177,13 @@ This prints a token to stdout that the operator hands to the worker (or pastes i - The HMAC-domain string `"git.agentic/rollback-approval/v1"` is versioned. A future signed-message format using the same key MUST use a different domain string. Drift here is silent and dangerous; the convention belongs in CONTRIBUTING.md or a domain-strings registry doc when the second signed format appears. See also: [`docs/superpowers/specs/2026-05-21-pre-public-hardening-sprint-design.md`](../superpowers/specs/2026-05-21-pre-public-hardening-sprint-design.md) §"ADR-0014" (the sprint design that frames this ADR), `git.agentic-threat-model.md` TM-002 (the row this ADR closes), [ADR-0012](./0012-socket-peer-authentication.md) (the peer-UID source feeding the signed payload). + +## Amendment (2026-11-20): key-file mode check and single-use tokens + +Status is unchanged. Two hardening changes refine Decisions 3, 4 and 5. + +**Key-file mode check (refines Decision 4).** On unix, `agenticd` reads the mode from the opened key-file handle (`fstat`, not a separate path stat). If any group or other bit is set (`mode & 0o077 != 0`), startup aborts with an error naming the path and telling the operator to `chmod 600` it. This is a misconfiguration abort, like a wrong-length key, and is distinct from Decision 4's fail-closed case: a missing, unreadable or empty key file still lets the daemon run with destructive rollback disabled. Anyone who can read the key can mint tokens, so a key readable beyond its owner is not accepted. The check runs after the read and empty checks, so an unreadable or empty file is still fail-closed whatever its mode. The check only stops readers running under other uids: a process sharing the daemon's uid (such as a sibling worker in the sidecar shape, see the threat model's attacker capabilities) can still read a 0600 key. Non-unix platforms are unchanged. Operators creating the demo key file should `chmod 600` it. + +**Single-use tokens (refines Decision 3).** A token now authorizes at most one non-dry-run destructive rollback. The daemon keeps an in-memory ledger keyed by the decoded 32-byte HMAC tag, not the token string, because hex decoding is case-insensitive and the timestamp parse accepts a leading `+` and leading zeros, so one token has many spellings. Each entry expires at `token_timestamp + 300s`: the validity window is symmetric, so a future-dated token verifies until its timestamp plus the TTL. The check, insert and pruning of expired entries happen under one lock. A second use is rejected with audit decision `rejected_replayed`, wire code `approval_token_replayed`. Dry runs verify the token but do not consume it, so an operator can preview and then execute with the same token. + +Limits: the ledger is per process. A daemon restart, or a second daemon instance sharing the same key, accepts the token again until its time window closes. A token is also consumed when the gate passes even if the rollback then fails later, so the operator signs a fresh one for the retry.