Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 59 additions & 8 deletions crates/agentic-core/src/approval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -97,6 +99,7 @@ impl ApprovalRejection {
ApprovalRejection::Malformed => "rejected_malformed",
ApprovalRejection::Expired { .. } => "rejected_expired",
ApprovalRejection::InvalidSignature => "rejected_invalid_signature",
ApprovalRejection::Replayed => "rejected_replayed",
}
}
}
Expand Down Expand Up @@ -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
Expand All @@ -142,15 +164,16 @@ pub fn verify_token(
peer_uid: u32,
token: &str,
now: u64,
) -> Result<(), ApprovalRejection> {
) -> Result<VerifiedToken, ApprovalRejection> {
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
Expand All @@ -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)]
Expand Down Expand Up @@ -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:?}"
);
}
}
}
94 changes: 85 additions & 9 deletions crates/agenticd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<agentic_core::approval::ApprovalKey>> {
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",
Expand All @@ -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",
Expand Down Expand Up @@ -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() {
Expand Down
29 changes: 27 additions & 2 deletions crates/agenticd/src/rollback/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>,
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 {
Expand All @@ -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);
Expand Down Expand Up @@ -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)?;
}
Expand Down
7 changes: 7 additions & 0 deletions crates/agenticd/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<agentic_core::approval::ApprovalKey>,
/// 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<std::collections::HashMap<[u8; 32], u64>>,
/// Static limits in force (issue #118). Set at startup via
/// [`DaemonState::with_limits`]; defaults are spec values.
pub limits: crate::limits::LimitsConfig,
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions crates/agenticd/src/wire_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions crates/agenticd/tests/commit_with_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading