From 576950cd81aa6e99c7187c7ceab41d61c9852b47 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 05:06:16 -0600 Subject: [PATCH] id-caps: reconcile the two #7916 policy points into mcp_policy (#13202) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spike step 4 landed twice: mcp_policy (PR #13192, bridge-integrated PolicySession) and agent_policy (PR #13182, standalone PolicyPoint). Keep mcp_policy as the one policy point — it is the shape spike step 5 drives through the bridge — and port the standalone point's remaining pieces into it: - per-tool rate limits (design 6.3): RoleGrant.rate_limits, a sliding admitted-call window per tool, RefusedRateLimit audit outcome and RefusalKind::RateLimited; act() now takes the host time that drives the windows - the structured park event: PolicyRefusal.park_event is now a serializable ParkEvent (kind/reason/message/agent/world/at/spend/ budget) instead of the bare message string - owner summary refusals broken down by stable refusal code (AuditOutcome::refusal_code) Delete agent_policy.rs and its acceptance test file; the ported behaviors are covered by new mcp_policy unit tests (rate-limit window slide, park-event fields, summary breakdown). Deliberately not ported: delegation expiry (the #13202 union does not list it and RoleGrant carries no expiry) and the join-granted opening event (the bridge session's world.join call is the audited join here). --- pkgs/id/crates/id-caps/src/agent_policy.rs | 915 ------------------ pkgs/id/crates/id-caps/src/lib.rs | 1 - pkgs/id/crates/id-caps/src/mcp_policy.rs | 288 +++++- .../id-caps/tests/agent_policy_point.rs | 421 -------- 4 files changed, 262 insertions(+), 1363 deletions(-) delete mode 100644 pkgs/id/crates/id-caps/src/agent_policy.rs delete mode 100644 pkgs/id/crates/id-caps/tests/agent_policy_point.rs diff --git a/pkgs/id/crates/id-caps/src/agent_policy.rs b/pkgs/id/crates/id-caps/src/agent_policy.rs deleted file mode 100644 index fc9c8e55e7..0000000000 --- a/pkgs/id/crates/id-caps/src/agent_policy.rs +++ /dev/null @@ -1,915 +0,0 @@ -//! The host-side policy point for agent frames (spike 4/5 for #6300, -//! issue #7916). -//! -//! Oracle: `doc/2026-11-09_design_id6300_agents_in_worlds_v1.md` §6 -//! (guardrails: capability ceiling, quota, behavioural limits), §7 -//! (audit log) and §9.3 (the spike's quota is a local, per-session -//! budget in the event shape F12.10 will consume — it does not wait -//! for #1067 to land). -//! -//! The policy point sits in the world host, outside the agent's -//! execution environment (§3): every frame the agent causes is checked -//! against (1) the capability ceiling set at role grant, (2) the -//! per-session quota ledger — charged *before* execution — and only -//! then executed and (3) written to the audit log, refusals included. -//! Refusals are the highest-signal events and are never sampled away -//! (§7). The agent is the audit subject, never its editor: this module -//! exposes no operation that mutates the log or the ledger from the -//! agent side, and the log is hash-chained and host-signed so a -//! hosted operator cannot quietly edit an agent's history either. - -use std::collections::{BTreeMap, BTreeSet, VecDeque}; - -use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey}; -use serde::Serialize; -use sha2::{Digest as _, Sha256}; - -use crate::agent_delegation::{AgentId, JoinGrant}; -use crate::world_scopes::WorldScopes; - -/// Ceiling key for the presence tools (`world.join`, `world.leave`, -/// `presence.set`), per the §4.4 tool table. -pub const CEILING_PRESENCE: &str = "presence"; -/// Ceiling key for the screen tools (`screen.read`, -/// `screen.subscribe`, `object.inspect`), per §4.4. -pub const CEILING_SCREEN_READ: &str = "screen.read"; -/// Ceiling key for `chat.post`, per §4.4. -pub const CEILING_CHAT_POST: &str = "chat.post"; -/// Base ceiling key for the one bounded program interaction (§4.6); -/// the full key is `program.invoke:`. -pub const CEILING_PROGRAM_INVOKE: &str = "program.invoke"; - -/// One agent action presented to the policy point: a single frame the -/// agent causes, described in the terms the ceiling and quota check. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct AgentAction { - /// MCP tool name, e.g. `chat.post` (the §4.4 surface). - pub tool: String, - /// Ceiling key from the pinned tool definition (§4.4): - /// `presence`, `screen.read`, `chat.post`, or - /// `program.invoke:`. - pub ceiling_key: String, - /// Object/entity reference the action acts on, when it acts on - /// one. Recorded in the audit event (§7). - pub object: Option, - /// Class of the object acted on, when known (§6.1 names object - /// classes as part of the ceiling). - pub object_class: Option, - /// Screen revision the action was decided against (§4.3 - /// stale-decision token), when the frame carries one. - pub decided_revision: Option, -} - -impl AgentAction { - /// An action for `tool` under `ceiling_key`, acting on no object - /// and carrying no stale-decision token. - #[must_use] - pub fn new(tool: impl Into, ceiling_key: impl Into) -> Self { - Self { - tool: tool.into(), - ceiling_key: ceiling_key.into(), - object: None, - object_class: None, - decided_revision: None, - } - } - - /// This action acting on `object` of class `object_class`. - #[must_use] - pub fn with_object( - mut self, - object: impl Into, - object_class: impl Into, - ) -> Self { - self.object = Some(object.into()); - self.object_class = Some(object_class.into()); - self - } - - /// This action carrying the §4.3 stale-decision token: it was - /// decided against screen revision `revision`. - #[must_use] - pub const fn with_decided_revision(mut self, revision: u64) -> Self { - self.decided_revision = Some(revision); - self - } - - /// Whether this action invokes a program (§4.6), and so charges - /// the program-invocation quota axis. - #[must_use] - pub fn is_program_invoke(&self) -> bool { - self.ceiling_key == CEILING_PROGRAM_INVOKE - || self.ceiling_key.starts_with("program.invoke:") - } -} - -/// The capability ceiling (§6.1). -/// -/// Set at role grant, enforced at the policy point on every frame, -/// never by the model. The ceiling names tools, worlds, object -/// classes, and the program-invoke allowlist. It can only be changed -/// owner-side, out-of-band — nothing in this module widens one. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Ceiling { - /// Base ceiling keys the agent may use at all (§4.4): - /// `presence`, `screen.read`, `chat.post`, `program.invoke`. - tools: BTreeSet, - /// Worlds the ceiling applies to. - worlds: BTreeSet, - /// Object classes the agent may act on. An action naming a class - /// outside this set is refused; an empty set refuses every - /// class-named action (deny by default). - object_classes: BTreeSet, - /// Program ids the agent may invoke (§4.6). A `program.invoke` - /// action for a program outside this list is refused even when - /// the base `program.invoke` key is in `tools`. - programs: BTreeSet, -} - -impl Ceiling { - /// A ceiling naming exactly the given tools, worlds, object - /// classes, and program allowlist. - #[must_use] - pub fn new( - tools: Vec, - worlds: Vec, - object_classes: Vec, - programs: Vec, - ) -> Self { - Self { - tools: tools.into_iter().collect(), - worlds: worlds.into_iter().collect(), - object_classes: object_classes.into_iter().collect(), - programs: programs.into_iter().collect(), - } - } - - /// The ceiling a join grant carries (§5.2, §6.1): the tool keys - /// derived from the grant's scopes, in the grant's one world, - /// with no object classes and an empty program allowlist — the - /// owner widens those two out-of-band, never the agent. - /// - /// Scope mapping (§4.4 against [`WorldScopes`]): `JOIN` carries - /// `presence`; chat-reading scopes carry `screen.read`; `CHAT` - /// carries `chat.post`; `INPUT` carries the base `program.invoke` - /// key (each invocation still needs its program on the allowlist). - #[must_use] - pub fn from_grant(grant: &JoinGrant) -> Self { - let mut tools = BTreeSet::new(); - if grant.scopes.contains(WorldScopes::JOIN) { - tools.insert(CEILING_PRESENCE.to_owned()); - } - if grant.scopes.reads_chat() { - tools.insert(CEILING_SCREEN_READ.to_owned()); - } - if grant.scopes.contains(WorldScopes::CHAT) { - tools.insert(CEILING_CHAT_POST.to_owned()); - } - if grant.scopes.contains(WorldScopes::INPUT) { - tools.insert(CEILING_PROGRAM_INVOKE.to_owned()); - } - Self { - tools, - worlds: BTreeSet::from([grant.world.clone()]), - object_classes: BTreeSet::new(), - programs: BTreeSet::new(), - } - } - - /// This ceiling with the object classes the owner allows, - /// replacing any previously set (an owner-side, out-of-band act). - #[must_use] - pub fn with_object_classes(mut self, object_classes: Vec) -> Self { - self.object_classes = object_classes.into_iter().collect(); - self - } - - /// This ceiling with the program allowlist the owner allows, - /// replacing any previously set (an owner-side, out-of-band act). - #[must_use] - pub fn with_programs(mut self, programs: Vec) -> Self { - self.programs = programs.into_iter().collect(); - self - } - - /// Base ceiling keys in force. - #[must_use] - pub const fn tools(&self) -> &BTreeSet { - &self.tools - } - - /// Worlds in force. - #[must_use] - pub const fn worlds(&self) -> &BTreeSet { - &self.worlds - } - - /// Object classes in force. - #[must_use] - pub const fn object_classes(&self) -> &BTreeSet { - &self.object_classes - } - - /// Program allowlist in force. - #[must_use] - pub const fn programs(&self) -> &BTreeSet { - &self.programs - } - - /// The ceiling stage of the policy point (§6.1): anything outside - /// the ceiling is refused (and audited by the caller). - /// - /// # Errors - /// - /// Returns the specific [`PolicyRefusal`] for the first failed - /// check: program allowlist, tool key, then object class. - pub fn check(&self, action: &AgentAction) -> Result<(), PolicyRefusal> { - if let Some(program) = action.ceiling_key.strip_prefix("program.invoke:") { - if !self.tools.contains(CEILING_PROGRAM_INVOKE) || !self.programs.contains(program) { - return Err(PolicyRefusal::CeilingProgram); - } - } else if !self.tools.contains(&action.ceiling_key) { - return Err(PolicyRefusal::CeilingTool); - } - if let Some(class) = &action.object_class - && !self.object_classes.contains(class) - { - return Err(PolicyRefusal::CeilingObjectClass); - } - Ok(()) - } -} - -/// Quota amounts over the §6.2 axes: frames requested, tool calls, -/// program invocations. One shape serves as the session budget, the -/// running spend, and the per-event charge recorded in the audit log -/// (§7). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] -pub struct Quota { - /// Frames requested. - pub frames: u64, - /// Tool calls made. - pub tool_calls: u64, - /// Program invocations made. - pub program_invocations: u64, -} - -impl Quota { - /// No charge on any axis. - pub const ZERO: Self = Self { - frames: 0, - tool_calls: 0, - program_invocations: 0, - }; - - /// The charge for one admitted action: one frame and one tool - /// call, plus one program invocation for a §4.6 program action. - #[must_use] - pub fn charge_for(action: &AgentAction) -> Self { - Self { - frames: 1, - tool_calls: 1, - program_invocations: u64::from(action.is_program_invoke()), - } - } - - /// This amount plus `other`, saturating per axis. - #[must_use] - pub const fn plus(self, other: Self) -> Self { - Self { - frames: self.frames.saturating_add(other.frames), - tool_calls: self.tool_calls.saturating_add(other.tool_calls), - program_invocations: self - .program_invocations - .saturating_add(other.program_invocations), - } - } - - /// Whether this amount stays within `budget` on every axis. - #[must_use] - pub const fn within(self, budget: Self) -> bool { - self.frames <= budget.frames - && self.tool_calls <= budget.tool_calls - && self.program_invocations <= budget.program_invocations - } -} - -/// A per-tool rate limit (§6.3). -/// -/// At most `max_calls` admitted calls to `tool` within any -/// `window_secs` window. Rate limits apply in addition to quota; -/// `chat.post` is the spam-prone surface and its limit is part of -/// the role. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct RateLimit { - /// Tool the limit applies to, e.g. `chat.post`. - pub tool: String, - /// Admitted calls allowed inside the window. - pub max_calls: u64, - /// Window length, seconds. - pub window_secs: u64, -} - -/// Why the policy point refused an action. Each variant maps to a -/// stable machine-readable [`PolicyRefusal::code`], journaled in the -/// audit event's outcome as `refused:`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PolicyRefusal { - /// The session is parked (§6.2): quota exhaustion ended it, and - /// every later action is refused until the owner intervenes. - SessionParked, - /// The delegation behind the session has expired (§5.3). - DelegationExpired, - /// The ceiling does not cover the session's world (§6.1). - CeilingWorld, - /// The action's ceiling key is not in the ceiling (§6.1). - CeilingTool, - /// The action names an object class outside the ceiling (§6.1). - CeilingObjectClass, - /// The action invokes a program outside the allowlist (§4.6, - /// §6.1). - CeilingProgram, - /// The action was decided against a screen revision that is no - /// longer current (§4.3): the agent may not act on unseen state. - StaleInput, - /// The action exceeds the tool's per-role rate limit (§6.3). - RateLimited, - /// The action's charge would exceed the session budget (§6.2). - /// This refusal parks the session. - QuotaExhausted, -} - -impl PolicyRefusal { - /// Stable machine-readable refusal code, as journaled in §7 - /// events. - #[must_use] - pub const fn code(&self) -> &'static str { - match self { - Self::SessionParked => "session_parked", - Self::DelegationExpired => "delegation_expired", - Self::CeilingWorld => "ceiling_world", - Self::CeilingTool => "ceiling_tool", - Self::CeilingObjectClass => "ceiling_object_class", - Self::CeilingProgram => "ceiling_program", - Self::StaleInput => "stale_input", - Self::RateLimited => "rate_limited", - Self::QuotaExhausted => "quota_exhausted", - } - } -} - -/// One §7 audit event for an agent action. -/// -/// Agent key, owner, world, tool, object, capability proof -/// reference, quota charged, outcome. Refusals and stale-input -/// rejections are events exactly like executions — one event per -/// action, never sampled away. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PolicyAuditEvent { - /// Agent key (hex). - pub agent: String, - /// Owner key the authority derives from (hex). - pub owner: String, - /// World the session is in. - pub world: String, - /// Tool surface, e.g. `chat.post`; the join event uses - /// `world.join`. - pub tool: String, - /// Object acted on, when the action names one. - pub object: Option, - /// §7 capability proof reference of the session's delegation. - pub proof_ref: Option, - /// Quota charged by this action (zero for a refusal: the charge - /// is refused atomically, never partially applied). - pub quota_charged: Quota, - /// `granted` (the join), `executed`, or `refused:`. - pub outcome: String, - /// Host time of the event, unix seconds. - pub at: u64, -} - -impl PolicyAuditEvent { - /// Canonical bytes for the hash chain: length-prefixed fields in - /// a fixed order under a domain tag. - #[must_use] - pub fn canonical_bytes(&self) -> Vec { - let mut out = Vec::new(); - push_field(&mut out, b"agent-audit/v1"); - push_field(&mut out, self.agent.as_bytes()); - push_field(&mut out, self.owner.as_bytes()); - push_field(&mut out, self.world.as_bytes()); - push_field(&mut out, self.tool.as_bytes()); - push_field(&mut out, &option_field(self.object.as_deref())); - push_field(&mut out, &option_field(self.proof_ref.as_deref())); - push_field(&mut out, &self.quota_charged.frames.to_be_bytes()); - push_field(&mut out, &self.quota_charged.tool_calls.to_be_bytes()); - push_field( - &mut out, - &self.quota_charged.program_invocations.to_be_bytes(), - ); - push_field(&mut out, self.outcome.as_bytes()); - push_field(&mut out, &self.at.to_be_bytes()); - out - } -} - -/// One audit event sealed into the hash chain (§7). -/// -/// Its sequence number, the previous event's hash, its own hash over -/// the canonical event bytes, and the host's signature over that -/// hash — so neither the agent nor a hosted operator can quietly -/// edit history. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ChainedAuditEvent { - /// Position in the chain, from 0 (the join event). - pub seq: u64, - /// Hash of the previous event; all-zero for the first. - pub prev_hash: [u8; 32], - /// The event itself. - pub event: PolicyAuditEvent, - /// `Sha256(prev_hash || seq || canonical event bytes)`. - pub hash: [u8; 32], - /// Host Ed25519 signature over `hash`. - pub signature: [u8; 64], -} - -/// Why an audit chain failed verification. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum AuditChainError { - /// An event's sequence number is not its position in the chain. - SequenceGap, - /// An event's `prev_hash` does not match its predecessor's hash. - PrevHashMismatch, - /// An event's recorded hash does not match its contents. - HashMismatch, - /// An event's host signature does not verify. - BadSignature, -} - -/// The session audit log (§7): append-only, hash-chained, -/// host-signed. Appending happens only inside the policy point; the -/// public surface is reading and verifying. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct AuditLog { - events: Vec, -} - -impl AuditLog { - /// An empty log. - #[must_use] - pub const fn new() -> Self { - Self { events: Vec::new() } - } - - /// Every event in order, join first. One event exists per action - /// the policy point has seen — refusals included, never sampled. - #[must_use] - pub fn events(&self) -> &[ChainedAuditEvent] { - &self.events - } - - /// Number of events recorded. - #[must_use] - pub const fn len(&self) -> usize { - self.events.len() - } - - /// Whether no event has been recorded yet. - #[must_use] - pub const fn is_empty(&self) -> bool { - self.events.is_empty() - } - - /// Verify this log's chain end-to-end against the host key. - /// - /// # Errors - /// - /// Returns the first [`AuditChainError`] found. - pub fn verify(&self, host: &VerifyingKey) -> Result<(), AuditChainError> { - Self::verify_events(&self.events, host) - } - - /// Verify an exported chain end-to-end: sequence, hash links, - /// event hashes, and host signatures are all re-derived from the - /// events themselves, so any edit to any event is detected. - /// - /// # Errors - /// - /// Returns the first [`AuditChainError`] found. - pub fn verify_events( - events: &[ChainedAuditEvent], - host: &VerifyingKey, - ) -> Result<(), AuditChainError> { - let mut prev_hash = [0u8; 32]; - for (index, chained) in events.iter().enumerate() { - if chained.seq != index as u64 { - return Err(AuditChainError::SequenceGap); - } - if chained.prev_hash != prev_hash { - return Err(AuditChainError::PrevHashMismatch); - } - if chain_hash(&chained.prev_hash, chained.seq, &chained.event) != chained.hash { - return Err(AuditChainError::HashMismatch); - } - host.verify(&chained.hash, &Signature::from_bytes(&chained.signature)) - .map_err(|_err| AuditChainError::BadSignature)?; - prev_hash = chained.hash; - } - Ok(()) - } - - /// Append one event, sealing it into the chain under the host - /// key. Policy-point internal: there is deliberately no public - /// append, because the agent must never write its own history. - fn append(&mut self, host_key: &SigningKey, event: PolicyAuditEvent) -> ChainedAuditEvent { - let seq = self.events.len() as u64; - let prev_hash = self.events.last().map_or([0u8; 32], |last| last.hash); - let hash = chain_hash(&prev_hash, seq, &event); - let signature = host_key.sign(&hash).to_bytes(); - let chained = ChainedAuditEvent { - seq, - prev_hash, - event, - hash, - signature, - }; - self.events.push(chained.clone()); - chained - } -} - -/// The park world event (§6.2). -/// -/// Emitted when quota exhaustion parks the agent: "agent parked, -/// quota exhausted" is a first-class world event the owner sees, -/// never a silent failure. The shape is the §9.3 local budget event -/// F12.10 will consume. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct ParkEvent { - /// Event kind: always `agent_parked`. - pub kind: String, - /// Machine-readable reason: always `quota_exhausted`. - pub reason: String, - /// Owner-facing message: `agent parked, quota exhausted`. - pub message: String, - /// Agent key (hex). - pub agent: String, - /// World the session is in. - pub world: String, - /// Host time of the park, unix seconds. - pub at: u64, - /// Quota spent when the park happened. - pub quota_spent: Quota, - /// The session budget that was exhausted. - pub quota_budget: Quota, -} - -/// The owner-readable periodic summary (§7): the raw log is for -/// machines; this is the review surface an owner actually reads — -/// actions, spend, and refusals for one session. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct OwnerSummary { - /// Agent key (hex). - pub agent: String, - /// Owner key (hex). - pub owner: String, - /// World the session is in. - pub world: String, - /// Actions executed. - pub executed: u64, - /// Actions refused. - pub refused: u64, - /// Refusals by stable refusal code. - pub refusals: BTreeMap, - /// Total quota charged across the session. - pub quota_spent: Quota, - /// The session budget. - pub quota_budget: Quota, - /// Whether the session is parked (§6.2). - pub parked: bool, -} - -impl OwnerSummary { - /// Render the summary as one owner-facing sentence set, in the - /// §7 shape ("your archivist agent edited 14 objects, spent X, - /// was refused twice"). - #[must_use] - pub fn render(&self) -> String { - let refusal_detail = if self.refusals.is_empty() { - "no refusals".to_owned() - } else { - let parts: Vec = self - .refusals - .iter() - .map(|(code, count)| format!("{code} x{count}")) - .collect(); - format!("refusals: {}", parts.join(", ")) - }; - let parked = if self.parked { - " The agent is parked: quota exhausted." - } else { - "" - }; - format!( - "your agent {} in world {}: {} actions executed, {} refused ({}); spent {} frames, {} tool calls, {} program invocations of a budget of {} / {} / {}.{}", - self.agent, - self.world, - self.executed, - self.refused, - refusal_detail, - self.quota_spent.frames, - self.quota_spent.tool_calls, - self.quota_spent.program_invocations, - self.quota_budget.frames, - self.quota_budget.tool_calls, - self.quota_budget.program_invocations, - parked, - ) - } -} - -/// The result of presenting one action to the policy point. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Admission { - /// `Ok(charge)` when the action is admitted — the charge has - /// already been applied to the ledger, before execution — or the - /// refusal that stopped it. Execution happens only on `Ok`. - pub decision: Result, - /// The audit event recorded for this action, either way (§7). - pub event: ChainedAuditEvent, - /// The park world event, present exactly when this action's - /// refusal parked the session (§6.2). - pub park_event: Option, -} - -/// The policy point for one agent session (§3, §6, §7). -/// -/// Owns the ceiling, the quota ledger, the rate-limit windows, and -/// the audit log for a session opened by a verified join. Every -/// action goes through [`PolicyPoint::admit`], in the design's -/// order — ceiling, quota, audit — and no other path executes an -/// agent action. -#[derive(Debug)] -pub struct PolicyPoint { - agent: String, - owner: String, - world: String, - proof_ref: String, - expires_at: u64, - ceiling: Ceiling, - budget: Quota, - spent: Quota, - rate_limits: Vec, - admitted_at: BTreeMap>, - parked: bool, - log: AuditLog, -} - -impl PolicyPoint { - /// Open the policy point for a session whose join was verified - /// (spike step 3, [`crate::agent_delegation::verify_join`]). The - /// join itself is audit event #1 of the session (§4.1), recorded - /// here under the host key. - /// - /// # Errors - /// - /// Returns [`PolicyRefusal::CeilingWorld`] if the ceiling does - /// not cover the grant's world: a session never opens under a - /// ceiling that does not name its world. - pub fn open( - grant: &JoinGrant, - ceiling: Ceiling, - budget: Quota, - rate_limits: Vec, - host_key: &SigningKey, - now: u64, - ) -> Result { - if !ceiling.worlds().contains(&grant.world) { - return Err(PolicyRefusal::CeilingWorld); - } - let mut point = Self { - agent: grant.agent.to_hex(), - owner: AgentId(grant.owner).to_hex(), - world: grant.world.clone(), - proof_ref: grant.proof_ref.clone(), - expires_at: grant.expires_at, - ceiling, - budget, - spent: Quota::ZERO, - rate_limits, - admitted_at: BTreeMap::new(), - parked: false, - log: AuditLog::new(), - }; - point.log.append( - host_key, - PolicyAuditEvent { - agent: point.agent.clone(), - owner: point.owner.clone(), - world: point.world.clone(), - tool: "world.join".to_owned(), - object: None, - proof_ref: Some(point.proof_ref.clone()), - quota_charged: Quota::ZERO, - outcome: "granted".to_owned(), - at: now, - }, - ); - Ok(point) - } - - /// Present one agent action, in the §3 order: parked and expiry - /// checks, the ceiling (§6.1), the stale-decision rule (§4.3), - /// per-tool rate limits (§6.3), then the quota charge (§6.2) — - /// applied before execution, refused atomically when it would - /// exceed the budget, parking the session on exhaustion. Exactly - /// one audit event is appended per action, whatever the outcome - /// (§7). - pub fn admit( - &mut self, - host_key: &SigningKey, - action: &AgentAction, - current_revision: u64, - now: u64, - ) -> Admission { - let mut park_event = None; - let refusal = if self.parked { - Some(PolicyRefusal::SessionParked) - } else if now >= self.expires_at { - Some(PolicyRefusal::DelegationExpired) - } else if let Err(refusal) = self.ceiling.check(action) { - Some(refusal) - } else if action - .decided_revision - .is_some_and(|decided| decided != current_revision) - { - Some(PolicyRefusal::StaleInput) - } else if self.rate_limited(action, now) { - Some(PolicyRefusal::RateLimited) - } else { - None - }; - let (decision, charged) = if let Some(refusal) = refusal { - (Err(refusal), Quota::ZERO) - } else { - let charge = Quota::charge_for(action); - let prospective = self.spent.plus(charge); - if prospective.within(self.budget) { - self.spent = prospective; - self.admitted_at - .entry(action.tool.clone()) - .or_default() - .push_back(now); - (Ok(charge), charge) - } else { - self.parked = true; - park_event = Some(ParkEvent { - kind: "agent_parked".to_owned(), - reason: PolicyRefusal::QuotaExhausted.code().to_owned(), - message: "agent parked, quota exhausted".to_owned(), - agent: self.agent.clone(), - world: self.world.clone(), - at: now, - quota_spent: self.spent, - quota_budget: self.budget, - }); - (Err(PolicyRefusal::QuotaExhausted), Quota::ZERO) - } - }; - let outcome = match &decision { - Ok(_) => "executed".to_owned(), - Err(refusal) => { - let code = refusal.code(); - format!("refused:{code}") - } - }; - let event = self.log.append( - host_key, - PolicyAuditEvent { - agent: self.agent.clone(), - owner: self.owner.clone(), - world: self.world.clone(), - tool: action.tool.clone(), - object: action.object.clone(), - proof_ref: Some(self.proof_ref.clone()), - quota_charged: charged, - outcome, - at: now, - }, - ); - Admission { - decision, - event, - park_event, - } - } - - /// Whether this action's tool is at its §6.3 rate limit at - /// `now`, counting admitted calls inside the trailing window. - fn rate_limited(&mut self, action: &AgentAction, now: u64) -> bool { - let Some(limit) = self - .rate_limits - .iter() - .find(|limit| limit.tool == action.tool) - .cloned() - else { - return false; - }; - let window = self.admitted_at.entry(action.tool.clone()).or_default(); - while window - .front() - .is_some_and(|at| now.saturating_sub(*at) >= limit.window_secs) - { - window.pop_front(); - } - window.len() as u64 >= limit.max_calls - } - - /// Whether quota exhaustion has parked this session (§6.2). - #[must_use] - pub const fn is_parked(&self) -> bool { - self.parked - } - - /// Quota charged so far this session. - #[must_use] - pub const fn spent(&self) -> Quota { - self.spent - } - - /// The session budget. - #[must_use] - pub const fn budget(&self) -> Quota { - self.budget - } - - /// The ceiling in force. - #[must_use] - pub const fn ceiling(&self) -> &Ceiling { - &self.ceiling - } - - /// The session audit log (§7): read and verify, never edit. - #[must_use] - pub const fn log(&self) -> &AuditLog { - &self.log - } - - /// The owner summary for this session (§7), derived from the - /// audit log plus the live ledger. - #[must_use] - pub fn summary(&self) -> OwnerSummary { - let mut executed = 0u64; - let mut refused = 0u64; - let mut refusals: BTreeMap = BTreeMap::new(); - for chained in self.log.events() { - if chained.event.outcome == "executed" { - executed += 1; - } else if let Some(code) = chained.event.outcome.strip_prefix("refused:") { - refused += 1; - *refusals.entry(code.to_owned()).or_default() += 1; - } - } - OwnerSummary { - agent: self.agent.clone(), - owner: self.owner.clone(), - world: self.world.clone(), - executed, - refused, - refusals, - quota_spent: self.spent, - quota_budget: self.budget, - parked: self.parked, - } - } -} - -/// The chain hash of one event: `Sha256(prev_hash || seq || -/// canonical event bytes)`. -fn chain_hash(prev_hash: &[u8; 32], seq: u64, event: &PolicyAuditEvent) -> [u8; 32] { - let mut hasher = Sha256::new(); - hasher.update(prev_hash); - hasher.update(seq.to_be_bytes()); - hasher.update(event.canonical_bytes()); - hasher.finalize().into() -} - -/// Length-prefixed field encoding for canonical bytes (the same -/// shape `agent_delegation` signs). -fn push_field(out: &mut Vec, field: &[u8]) { - out.extend_from_slice(&(field.len() as u64).to_be_bytes()); - out.extend_from_slice(field); -} - -/// An optional string as canonical field bytes: a presence byte -/// followed by the value, so `None` and `Some("")` never collide. -fn option_field(value: Option<&str>) -> Vec { - match value { - None => vec![0], - Some(text) => { - let mut out = vec![1]; - out.extend_from_slice(text.as_bytes()); - out - } - } -} diff --git a/pkgs/id/crates/id-caps/src/lib.rs b/pkgs/id/crates/id-caps/src/lib.rs index 5f427e4e47..98746af08b 100644 --- a/pkgs/id/crates/id-caps/src/lib.rs +++ b/pkgs/id/crates/id-caps/src/lib.rs @@ -11,7 +11,6 @@ //! the dependency points one way — `id-core` never names this crate. pub mod agent_delegation; -pub mod agent_policy; pub mod cap_baseline; pub mod cap_class; pub mod cap_diff; diff --git a/pkgs/id/crates/id-caps/src/mcp_policy.rs b/pkgs/id/crates/id-caps/src/mcp_policy.rs index 4d625ff3ef..b1d3316fcb 100644 --- a/pkgs/id/crates/id-caps/src/mcp_policy.rs +++ b/pkgs/id/crates/id-caps/src/mcp_policy.rs @@ -31,6 +31,17 @@ //! `screen_revision` token does not name the latest observed revision //! is refused as stale input and audited. //! +//! Per-tool rate limits (section 6.3) are enforced here too: a role +//! may cap admitted calls to a tool inside a sliding window — +//! `chat.post` is the spam-prone surface the design names — and a +//! call past the cap is refused and audited, charged nothing. +//! +//! This module is the one surviving policy point for the spike. +//! Spike step 4 landed twice (#7916); #13202 reconciled the two +//! implementations into this one, porting the standalone policy +//! point's per-tool rate limits, structured park event, and +//! refusal-code summary breakdown here before deleting it. +//! //! `world.leave` is the exit, not an in-world action: it is never //! refused by the ceiling or the quota (an agent must always be able //! to leave, even parked or out of budget), it is charged nothing, and @@ -41,7 +52,7 @@ //! the bridge grows the tool, an admitted invoke ends as an audited //! bridge refusal (`UnknownTool`), charged like any admitted attempt. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey}; use serde::{Deserialize, Serialize}; @@ -53,6 +64,47 @@ use crate::mcp_bridge::{BridgeError, BridgeSession, ToolAction, ToolDefinition}; /// (design section 6.2, findings Q3b: visible, never silent). pub const QUOTA_PARK_EVENT: &str = "agent parked, quota exhausted"; +/// A per-tool rate limit (design section 6.3), part of the role. +/// +/// At most `max_calls` admitted calls to `tool` within any +/// `window_secs` sliding window. Rate limits apply in addition to +/// quota; `chat.post` is the spam-prone surface the design names. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct RateLimit { + /// Tool the limit applies to, e.g. `chat.post`. + pub tool: String, + /// Admitted calls allowed inside the window. + pub max_calls: u64, + /// Window length, seconds. + pub window_secs: u64, +} + +/// The park world event (design section 6.2). +/// +/// Emitted when quota exhaustion parks an agent. "Agent parked, +/// quota exhausted" is a first-class world event the owner sees, +/// never a silent failure; the shape is the section 9.3 +/// local-budget event F12.10 will consume. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct ParkEvent { + /// Event kind: always `agent_parked`. + pub kind: String, + /// Machine-readable reason: always `quota_exhausted`. + pub reason: String, + /// Owner-facing message: [`QUOTA_PARK_EVENT`]. + pub message: String, + /// The parked agent's public key. + pub agent_key: [u8; 32], + /// The world the session is connected to. + pub world: String, + /// Host time of the park, unix seconds. + pub at: u64, + /// Quota spent when the park happened. + pub quota_spent: Quota, + /// The session budget that was exhausted. + pub quota_budget: Quota, +} + /// The capability ceiling set at role grant (design section 6.1). /// /// The ceiling names the tools, worlds, and object classes the @@ -155,6 +207,9 @@ pub struct RoleGrant { pub ceiling: CapabilityCeiling, /// The per-session quota budget for this session. pub quota: Quota, + /// Per-tool rate limits for this session (design section 6.3), + /// part of the role: empty when the role caps no tool. + pub rate_limits: Vec, } /// The outcome of one agent action, as recorded in the audit log @@ -185,6 +240,16 @@ pub enum AuditOutcome { /// The latest revision the host has observed. current: u64, }, + /// The action exceeded the role's per-tool rate limit (design + /// section 6.3). Never executed, charged nothing. + RefusedRateLimit { + /// The tool whose limit was hit. + tool: String, + /// Admitted calls allowed inside the window. + limit: u64, + /// Window length, seconds. + window_secs: u64, + }, /// The policy point admitted the action and the bridge refused /// it (unknown tool, invalid arguments, no frame mapping, ...). /// The charge stands: the attempt consumed the host's work. @@ -194,6 +259,24 @@ pub enum AuditOutcome { }, } +impl AuditOutcome { + /// The stable machine-readable refusal code for this outcome, + /// or `None` for an executed action. The owner summary's + /// refusal breakdown is keyed by these codes. + #[must_use] + pub const fn refusal_code(&self) -> Option<&'static str> { + match self { + Self::Executed => None, + Self::RefusedCeiling { .. } => Some("ceiling"), + Self::RefusedQuota { .. } => Some("quota"), + Self::RefusedParked => Some("parked"), + Self::RefusedStaleInput { .. } => Some("stale_input"), + Self::RefusedRateLimit { .. } => Some("rate_limited"), + Self::RefusedBridge { .. } => Some("bridge"), + } + } +} + /// One signed, hash-chained audit event (design section 7). #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct AuditEvent { @@ -448,6 +531,9 @@ pub struct OwnerSummary { /// Actions refused, for any reason. Refusals are the /// highest-signal events and are never sampled away. pub refusals: u64, + /// Refusals broken down by stable refusal code + /// ([`AuditOutcome::refusal_code`]). + pub refusals_by_code: BTreeMap, /// Total quota spent across the session. pub spend: Quota, /// Whether the agent is currently parked. @@ -490,6 +576,8 @@ pub enum RefusalKind { Parked, /// The stale-decision token did not name the current revision. StaleInput, + /// The action exceeded the role's per-tool rate limit. + RateLimited, /// Admitted by the policy point, refused by the bridge. Bridge, } @@ -502,8 +590,8 @@ pub struct PolicyRefusal { /// Human-readable detail for the caller and the audit record. pub detail: String, /// The world event the driver must surface, when this refusal - /// parked the agent ([`QUOTA_PARK_EVENT`]); `None` otherwise. - pub park_event: Option, + /// parked the agent; `None` otherwise. + pub park_event: Option, } /// What the bridge driver must do with one policy-checked tool call. @@ -527,6 +615,7 @@ pub struct PolicySession { spend: Quota, parked: bool, object_classes: BTreeMap, + admitted_at: BTreeMap>, } impl PolicySession { @@ -542,6 +631,7 @@ impl PolicySession { spend: Quota::zero(), parked: false, object_classes: BTreeMap::new(), + admitted_at: BTreeMap::new(), } } @@ -595,11 +685,15 @@ impl PolicySession { pub fn owner_summary(&self) -> OwnerSummary { let mut executed = 0u64; let mut refusals = 0u64; + let mut refusals_by_code: BTreeMap = BTreeMap::new(); for event in self.audit.events() { match event.outcome { AuditOutcome::Executed => executed += 1, _ => refusals += 1, } + if let Some(code) = event.outcome.refusal_code() { + *refusals_by_code.entry(code.to_owned()).or_default() += 1; + } } OwnerSummary { agent_label: self.grant.agent_label.clone(), @@ -608,6 +702,7 @@ impl PolicySession { actions: self.audit.events().len() as u64, executed, refusals, + refusals_by_code, spend: self.spend, parked: self.parked, } @@ -653,9 +748,11 @@ impl PolicySession { } /// Run one agent tool call through the policy point, in the - /// design's order: ceiling, quota, execution — with exactly one - /// audit event whatever the verdict. - pub fn act(&mut self, name: &str, arguments: &serde_json::Value) -> PolicyOutcome { + /// design's order: ceiling, stale-decision, rate limit, quota, + /// execution — with exactly one audit event whatever the + /// verdict. `now` is the host time, unix seconds; it drives the + /// rate-limit windows and stamps the park event. + pub fn act(&mut self, name: &str, arguments: &serde_json::Value, now: u64) -> PolicyOutcome { let object = audit_object(name, arguments); // The exit is never refused: not by the ceiling, not by the // quota, not by parking. It is charged nothing and audited. @@ -713,6 +810,27 @@ impl PolicySession { park_event: None, }); } + if let Some(limit) = self.rate_limit_hit(name, now) { + self.audit.append( + &self.grant, + name, + object, + Quota::zero(), + AuditOutcome::RefusedRateLimit { + tool: name.to_owned(), + limit: limit.max_calls, + window_secs: limit.window_secs, + }, + ); + return PolicyOutcome::Refused(PolicyRefusal { + kind: RefusalKind::RateLimited, + detail: format!( + "rate limit for {name}: {} admitted calls per {}s window", + limit.max_calls, limit.window_secs + ), + park_event: None, + }); + } let charge = charge_for(name); if let Some(axis) = Quota::exceeded_axis(self.grant.quota, self.spend, charge) { self.parked = true; @@ -728,13 +846,47 @@ impl PolicySession { return PolicyOutcome::Refused(PolicyRefusal { kind: RefusalKind::Quota, detail: format!("quota exhausted on the {axis} axis"), - park_event: Some(QUOTA_PARK_EVENT.to_owned()), + park_event: Some(ParkEvent { + kind: "agent_parked".to_owned(), + reason: "quota_exhausted".to_owned(), + message: QUOTA_PARK_EVENT.to_owned(), + agent_key: self.grant.agent_key, + world: self.grant.world.clone(), + at: now, + quota_spent: self.spend, + quota_budget: self.grant.quota, + }), }); } self.spend.add(charge); + self.admitted_at + .entry(name.to_owned()) + .or_default() + .push_back(now); self.execute(name, arguments, object, charge) } + /// The rate limit this call hits at `now`, if any (design + /// section 6.3): the role's limit for the tool, once the + /// admitted calls inside the trailing window reach its cap. + /// Expired admissions slide out of the window as a side effect. + fn rate_limit_hit(&mut self, name: &str, now: u64) -> Option { + let limit = self + .grant + .rate_limits + .iter() + .find(|limit| limit.tool == name)? + .clone(); + let window = self.admitted_at.entry(name.to_owned()).or_default(); + while window + .front() + .is_some_and(|at| now.saturating_sub(*at) >= limit.window_secs) + { + window.pop_front(); + } + (window.len() as u64 >= limit.max_calls).then_some(limit) + } + /// The ceiling check (step 1). Returns the refusal detail when /// the action is outside the ceiling. fn ceiling_refusal(&self, name: &str, arguments: &serde_json::Value) -> Option { @@ -854,6 +1006,8 @@ mod tests { SigningKey::from_bytes(&[7; 32]) } + const TEST_NOW: u64 = 1_700_000_000; + fn grant() -> RoleGrant { let mut tools: BTreeSet = v1_tool_definitions() .iter() @@ -877,6 +1031,7 @@ mod tests { tool_calls: 32, program_invocations: 1, }, + rate_limits: Vec::new(), } } @@ -890,7 +1045,7 @@ mod tests { fn joined(grant: RoleGrant) -> PolicySession { let mut session = session(grant); - let outcome = session.act("world.join", &json!({ "capability": "cap-1" })); + let outcome = session.act("world.join", &json!({ "capability": "cap-1" }), TEST_NOW); assert!( matches!(outcome, PolicyOutcome::Executed(ToolAction::SendFrame(_))), "{outcome:?}" @@ -910,7 +1065,7 @@ mod tests { let mut scoped_grant = grant(); scoped_grant.ceiling.tools.remove("chat.post"); let mut scoped_session = joined(scoped_grant); - let outcome = scoped_session.act("chat.post", &json!({ "text": "hello" })); + let outcome = scoped_session.act("chat.post", &json!({ "text": "hello" }), TEST_NOW); assert!(matches!( outcome, PolicyOutcome::Refused(PolicyRefusal { @@ -933,7 +1088,8 @@ mod tests { let mut elsewhere_grant = grant(); elsewhere_grant.world = "elsewhere".to_owned(); let mut elsewhere_session = session(elsewhere_grant); - let outcome = elsewhere_session.act("world.join", &json!({ "capability": "cap-1" })); + let outcome = + elsewhere_session.act("world.join", &json!({ "capability": "cap-1" }), TEST_NOW); assert!(matches!( outcome, PolicyOutcome::Refused(PolicyRefusal { @@ -949,12 +1105,18 @@ mod tests { let mut grant = grant(); grant.quota.frames = 1; // the join spends the only frame let mut session = joined(grant); - let outcome = session.act("chat.post", &json!({ "text": "hello" })); + let outcome = session.act("chat.post", &json!({ "text": "hello" }), TEST_NOW); let PolicyOutcome::Refused(refusal) = outcome else { panic!("quota refusal expected, got {outcome:?}"); }; assert_eq!(refusal.kind, RefusalKind::Quota); - assert_eq!(refusal.park_event.as_deref(), Some(QUOTA_PARK_EVENT)); + let park = refusal.park_event.as_ref().expect("park event present"); + assert_eq!(park.kind, "agent_parked"); + assert_eq!(park.reason, "quota_exhausted"); + assert_eq!(park.message, QUOTA_PARK_EVENT); + assert_eq!(park.world, "tic-tac-toe"); + assert_eq!(park.quota_budget.frames, 1); + assert_eq!(park.quota_spent.frames, 1); assert!(session.is_parked()); assert!(matches!( last_outcome(&session), @@ -962,7 +1124,7 @@ mod tests { )); // Parked actions are refused without a charge... let spend_before = session.spend(); - let outcome = session.act("screen.read", &json!({})); + let outcome = session.act("screen.read", &json!({}), TEST_NOW); assert!(matches!( outcome, PolicyOutcome::Refused(PolicyRefusal { @@ -973,7 +1135,7 @@ mod tests { assert_eq!(session.spend(), spend_before); // ...but the agent can always leave. assert_eq!( - session.act("world.leave", &json!({})), + session.act("world.leave", &json!({}), TEST_NOW), PolicyOutcome::Executed(ToolAction::Close) ); let summary = session.owner_summary(); @@ -987,9 +1149,10 @@ mod tests { session.act( "screen.subscribe", &json!({ "event_classes": ["chat_posted"] }), + TEST_NOW, ); - session.act("chat.post", &json!({ "text": "hello" })); - session.act("host.exec", &json!({})); // ceiling refusal + session.act("chat.post", &json!({ "text": "hello" }), TEST_NOW); + session.act("host.exec", &json!({}), TEST_NOW); // ceiling refusal session.verify_audit().unwrap(); let key = session.host_verifying_key(); @@ -1018,7 +1181,7 @@ mod tests { #[test] fn audit_events_round_trip_through_serde_and_still_verify() { let mut session = joined(grant()); - session.act("chat.post", &json!({ "text": "hello" })); + session.act("chat.post", &json!({ "text": "hello" }), TEST_NOW); let bytes = serde_json::to_vec(session.audit_events()).unwrap(); let restored: Vec = serde_json::from_slice(&bytes).unwrap(); assert_eq!(restored, session.audit_events()); @@ -1031,10 +1194,11 @@ mod tests { session.act( "screen.subscribe", &json!({ "event_classes": ["chat_posted"] }), + TEST_NOW, ); // 1 frame + 1 tool call - session.act("screen.read", &json!({})); // 1 tool call - session.act("chat.post", &json!({ "text": "hi" })); // 1 frame + 1 tool call - session.act("host.exec", &json!({})); // ceiling refusal, no charge + session.act("screen.read", &json!({}), TEST_NOW); // 1 tool call + session.act("chat.post", &json!({ "text": "hi" }), TEST_NOW); // 1 frame + 1 tool call + session.act("host.exec", &json!({}), TEST_NOW); // ceiling refusal, no charge let summary = session.owner_summary(); assert_eq!(summary.actions, 5); assert_eq!(summary.executed, 4); @@ -1066,6 +1230,7 @@ mod tests { let outcome = session.act( "chat.post", &json!({ "text": "move", "screen_revision": 2 }), + TEST_NOW, ); assert!(matches!( outcome, @@ -1085,6 +1250,7 @@ mod tests { let outcome = session.act( "chat.post", &json!({ "text": "move", "screen_revision": 3 }), + TEST_NOW, ); assert!(matches!( outcome, @@ -1106,12 +1272,20 @@ mod tests { })); // An observed class inside the ceiling: admitted. assert!(matches!( - session.act("object.inspect", &json!({ "entity_ref": "cell-4" })), + session.act( + "object.inspect", + &json!({ "entity_ref": "cell-4" }), + TEST_NOW + ), PolicyOutcome::Executed(ToolAction::Local(_)) )); // An observed class outside the ceiling: refused. assert!(matches!( - session.act("object.inspect", &json!({ "entity_ref": "safe-1" })), + session.act( + "object.inspect", + &json!({ "entity_ref": "safe-1" }), + TEST_NOW + ), PolicyOutcome::Refused(PolicyRefusal { kind: RefusalKind::Ceiling, .. @@ -1119,7 +1293,11 @@ mod tests { )); // A class:id reference carries its class without a frame. assert!(matches!( - session.act("object.inspect", &json!({ "entity_ref": "vault:9" })), + session.act( + "object.inspect", + &json!({ "entity_ref": "vault:9" }), + TEST_NOW + ), PolicyOutcome::Refused(PolicyRefusal { kind: RefusalKind::Ceiling, .. @@ -1132,7 +1310,7 @@ mod tests { let mut session = joined(grant()); // Outside the allowlist: ceiling refusal, no program charge. assert!(matches!( - session.act("program.invoke", &json!({ "program": "wipe" })), + session.act("program.invoke", &json!({ "program": "wipe" }), TEST_NOW), PolicyOutcome::Refused(PolicyRefusal { kind: RefusalKind::Ceiling, .. @@ -1143,7 +1321,11 @@ mod tests { // has no such tool yet (spike step 5), so the attempt ends // as an audited bridge refusal with the charge standing. assert!(matches!( - session.act("program.invoke", &json!({ "program": "scorekeeper" })), + session.act( + "program.invoke", + &json!({ "program": "scorekeeper" }), + TEST_NOW + ), PolicyOutcome::Refused(PolicyRefusal { kind: RefusalKind::Bridge, .. @@ -1163,7 +1345,7 @@ mod tests { #[test] fn the_agent_cannot_mutate_the_log_or_its_quota() { let mut session = joined(grant()); - session.act("chat.post", &json!({ "text": "hello" })); + session.act("chat.post", &json!({ "text": "hello" }), TEST_NOW); // The spend comes out by value: scribbling on the copy does // not reach the session's ledger. let mut copy = session.spend(); @@ -1176,4 +1358,58 @@ mod tests { assert_eq!(session.audit_events().len(), 2); session.verify_audit().unwrap(); } + + #[test] + fn rate_limit_refuses_beyond_the_role_limit_and_the_window_slides() { + let mut grant = grant(); + grant.rate_limits = vec![RateLimit { + tool: "chat.post".to_owned(), + max_calls: 2, + window_secs: 60, + }]; + let mut session = joined(grant); + // Two admitted posts inside the window. (The join is a + // different tool and never counts against this limit.) + assert!(matches!( + session.act("chat.post", &json!({ "text": "one" }), TEST_NOW), + PolicyOutcome::Executed(_) + )); + assert!(matches!( + session.act("chat.post", &json!({ "text": "two" }), TEST_NOW + 1), + PolicyOutcome::Executed(_) + )); + // The third is refused by the rate limit, audited, and + // charged nothing. + let spend_before = session.spend(); + let outcome = session.act("chat.post", &json!({ "text": "three" }), TEST_NOW + 2); + assert!(matches!( + outcome, + PolicyOutcome::Refused(PolicyRefusal { + kind: RefusalKind::RateLimited, + .. + }) + )); + assert!(matches!( + last_outcome(&session), + AuditOutcome::RefusedRateLimit { .. } + )); + assert_eq!(session.spend(), spend_before); + // Once the window slides past the admitted calls, the tool + // admits again. + assert!(matches!( + session.act("chat.post", &json!({ "text": "later" }), TEST_NOW + 62), + PolicyOutcome::Executed(_) + )); + } + + #[test] + fn owner_summary_breaks_refusals_down_by_code() { + let mut session = joined(grant()); + session.act("host.exec", &json!({}), TEST_NOW); // ceiling refusal + session.act("host.exec", &json!({}), TEST_NOW); // ceiling refusal again + let summary = session.owner_summary(); + assert_eq!(summary.refusals, 2); + assert_eq!(summary.refusals_by_code.get("ceiling"), Some(&2)); + assert_eq!(summary.refusals_by_code.len(), 1); + } } diff --git a/pkgs/id/crates/id-caps/tests/agent_policy_point.rs b/pkgs/id/crates/id-caps/tests/agent_policy_point.rs deleted file mode 100644 index 84839791ed..0000000000 --- a/pkgs/id/crates/id-caps/tests/agent_policy_point.rs +++ /dev/null @@ -1,421 +0,0 @@ -//! Acceptance oracle for #7916 (spike 4/5 for #6300): the host-side -//! policy point — capability ceiling, per-session quota with visible -//! parking, and the signed/hash-chained audit log (design §6, §7, -//! §9.3). - -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use ed25519_dalek::SigningKey; -use id_caps::agent_delegation::{ - AgentId, DEFAULT_LIFETIME_SECS, Delegation, Role, RoleBinding, verify_join, -}; -use id_caps::agent_policy::{ - AgentAction, AuditChainError, AuditLog, Ceiling, ParkEvent, PolicyPoint, PolicyRefusal, Quota, - RateLimit, -}; -use id_caps::world_scopes::WorldScopes; - -const NOW: u64 = 1_700_000_000; - -fn key(seed: u8) -> SigningKey { - SigningKey::from_bytes(&[seed; 32]) -} - -/// A session fixture: owner 7, agent 9, host 3; role "archivist" in -/// world "atlas" with the GUEST ceiling; the delegation carries -/// exactly `scopes`. -struct Fixture { - host: SigningKey, - point: PolicyPoint, -} - -fn fixture(scopes: WorldScopes, budget: Quota, rate_limits: Vec) -> Fixture { - fixture_with_ceiling(scopes, budget, rate_limits, None) -} - -fn fixture_with_ceiling( - scopes: WorldScopes, - budget: Quota, - rate_limits: Vec, - widen: Option Ceiling>, -) -> Fixture { - let owner = key(7); - let agent = key(9); - let host = key(3); - let role = Role::new( - "archivist", - WorldScopes::GUEST, - vec!["atlas".to_owned()], - DEFAULT_LIFETIME_SECS, - ) - .expect("role within lifetime bounds"); - let binding = RoleBinding::bind( - &owner, - "atlas", - &role, - AgentId::from_verifying_key(&agent.verifying_key()), - ) - .expect("role applies to world"); - let delegation = Delegation::issue(&owner, &binding, scopes, NOW, DEFAULT_LIFETIME_SECS) - .expect("attenuated issue"); - let grant = verify_join(&binding, Some(&delegation), "atlas", NOW).expect("valid chain"); - let mut ceiling = Ceiling::from_grant(&grant); - if let Some(widen) = widen { - ceiling = widen(ceiling); - } - let point = PolicyPoint::open(&grant, ceiling, budget, rate_limits, &host, NOW) - .expect("ceiling covers the grant world"); - Fixture { host, point } -} - -const fn big_budget() -> Quota { - Quota { - frames: 100, - tool_calls: 100, - program_invocations: 10, - } -} - -/// Oracle §6.1 + §7: an out-of-ceiling action is refused, audited, -/// and never executed. The delegation carries no CHAT, so `chat.post` -/// is outside the ceiling the grant set at role grant. -#[test] -fn out_of_ceiling_action_is_refused_audited_and_never_executed() { - let mut fx = fixture(WorldScopes::JOIN, big_budget(), Vec::new()); - let mut executed = 0u32; - let admission = fx.point.admit( - &fx.host, - &AgentAction::new("chat.post", "chat.post"), - 0, - NOW + 1, - ); - if admission.decision.is_ok() { - executed += 1; - } - assert_eq!(admission.decision, Err(PolicyRefusal::CeilingTool)); - assert_eq!(executed, 0, "a refused action must never execute"); - assert_eq!(admission.event.event.tool, "chat.post"); - assert_eq!(admission.event.event.outcome, "refused:ceiling_tool"); - assert_eq!(admission.event.event.quota_charged, Quota::ZERO); - assert_eq!(fx.point.spent(), Quota::ZERO); -} - -/// Oracle §7: refusals are never sampled away — a mixed run of -/// actions leaves exactly one audit event per action, plus the join. -#[test] -fn refusals_are_never_sampled_away() { - let mut fx = fixture( - WorldScopes::JOIN.union(WorldScopes::CHAT), - big_budget(), - Vec::new(), - ); - let actions = [ - AgentAction::new("screen.read", "screen.read"), - AgentAction::new("chat.post", "chat.post"), - AgentAction::new("program.invoke", "program.invoke:delete-all"), - AgentAction::new("screen.read", "screen.read").with_decided_revision(41), - AgentAction::new("chat.post", "chat.post"), - AgentAction::new("audit.mutate", "audit.mutate"), - ]; - let mut refusals = 0u64; - for (index, action) in actions.iter().enumerate() { - let admission = fx.point.admit(&fx.host, action, 42, NOW + 1 + index as u64); - if admission.decision.is_err() { - refusals += 1; - } - } - assert_eq!(refusals, 3); - assert_eq!(fx.point.log().len(), actions.len() + 1); - let refused_events = fx - .point - .log() - .events() - .iter() - .filter(|chained| chained.event.outcome.starts_with("refused:")) - .count(); - assert_eq!(refused_events, 3); - fx.point - .log() - .verify(&fx.host.verifying_key()) - .expect("chain verifies"); -} - -/// Oracle §6.2: quota exhaustion parks the agent visibly — the park -/// is a first-class world event, and a parked session refuses -/// everything after it. -#[test] -fn quota_exhaustion_parks_the_agent_visibly() { - let budget = Quota { - frames: 2, - tool_calls: 2, - program_invocations: 0, - }; - let mut fx = fixture(WorldScopes::GUEST, budget, Vec::new()); - let read = AgentAction::new("screen.read", "screen.read"); - assert!(fx.point.admit(&fx.host, &read, 0, NOW + 1).decision.is_ok()); - assert!(fx.point.admit(&fx.host, &read, 0, NOW + 2).decision.is_ok()); - - let third = fx.point.admit(&fx.host, &read, 0, NOW + 3); - assert_eq!(third.decision, Err(PolicyRefusal::QuotaExhausted)); - let park: ParkEvent = third.park_event.expect("exhaustion emits the park event"); - assert_eq!(park.kind, "agent_parked"); - assert_eq!(park.reason, "quota_exhausted"); - assert_eq!(park.message, "agent parked, quota exhausted"); - assert_eq!(park.quota_spent.frames, 2); - assert!(fx.point.is_parked()); - - let fourth = fx.point.admit(&fx.host, &read, 0, NOW + 4); - assert_eq!(fourth.decision, Err(PolicyRefusal::SessionParked)); - assert_eq!(fourth.park_event, None, "the park event fires once"); -} - -/// Oracle §6.2 + §7: the charge lands before execution and a refusal -/// charges nothing — the ledger only ever moves on admission. -#[test] -fn quota_is_charged_before_execution_and_a_refusal_charges_nothing() { - let mut fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - let chat = AgentAction::new("chat.post", "chat.post"); - let admission = fx.point.admit(&fx.host, &chat, 0, NOW + 1); - assert_eq!( - admission.decision.expect("within ceiling and budget"), - Quota { - frames: 1, - tool_calls: 1, - program_invocations: 0, - } - ); - assert_eq!(fx.point.spent().tool_calls, 1); - - let refused = fx.point.admit( - &fx.host, - &AgentAction::new("program.invoke", "program.invoke:unlisted"), - 0, - NOW + 2, - ); - assert_eq!(refused.decision, Err(PolicyRefusal::CeilingProgram)); - assert_eq!(fx.point.spent().tool_calls, 1, "a refusal charges nothing"); -} - -/// Oracle §7: the audit chain verifies end-to-end for a spike -/// session, and any edit to any event — content, hash, or signature — -/// is detected. The agent cannot mutate the log: the only writer is -/// the policy point, and tampering with an exported copy fails -/// verification rather than rewriting history. -#[test] -fn audit_chain_verifies_end_to_end_and_detects_tampering() { - let mut fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - for index in 0..5u64 { - fx.point.admit( - &fx.host, - &AgentAction::new("screen.read", "screen.read"), - 0, - NOW + 1 + index, - ); - } - let host_key = fx.host.verifying_key(); - fx.point.log().verify(&host_key).expect("chain verifies"); - - let mut tampered = fx.point.log().events().to_vec(); - tampered[2].event.outcome = "refused:ceiling_tool".to_owned(); - assert_eq!( - AuditLog::verify_events(&tampered, &host_key), - Err(AuditChainError::HashMismatch) - ); - - let mut rehashed = fx.point.log().events().to_vec(); - rehashed[1].signature = [0u8; 64]; - assert_eq!( - AuditLog::verify_events(&rehashed, &host_key), - Err(AuditChainError::BadSignature) - ); - - // The non-tools of §4.5 stay non-tools at the policy point: - // audit mutation and quota adjustment are refused and audited. - let mutation = fx.point.admit( - &fx.host, - &AgentAction::new("audit.mutate", "audit.mutate"), - 0, - NOW + 10, - ); - assert_eq!(mutation.decision, Err(PolicyRefusal::CeilingTool)); - assert_eq!(fx.point.log().len(), 7); - fx.point - .log() - .verify(&host_key) - .expect("chain still verifies"); -} - -/// Oracle §4.3 + §7: an action decided against a stale screen -/// revision is rejected and audited like a refusal; the same action -/// at the current revision executes. -#[test] -fn stale_input_is_rejected_and_audited() { - let mut fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - let action = AgentAction::new("chat.post", "chat.post").with_decided_revision(7); - let stale = fx.point.admit(&fx.host, &action, 8, NOW + 1); - assert_eq!(stale.decision, Err(PolicyRefusal::StaleInput)); - assert_eq!(stale.event.event.outcome, "refused:stale_input"); - let fresh = fx.point.admit(&fx.host, &action, 7, NOW + 2); - assert!(fresh.decision.is_ok()); -} - -/// Oracle §7: the owner summary shows actions, spend, and refusals -/// for the session, in structured form and rendered. -#[test] -fn owner_summary_shows_actions_spend_and_refusals() { - let mut fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - fx.point.admit( - &fx.host, - &AgentAction::new("screen.read", "screen.read"), - 0, - NOW + 1, - ); - fx.point.admit( - &fx.host, - &AgentAction::new("chat.post", "chat.post"), - 0, - NOW + 2, - ); - fx.point.admit( - &fx.host, - &AgentAction::new("program.invoke", "program.invoke:unlisted"), - 0, - NOW + 3, - ); - let summary = fx.point.summary(); - assert_eq!(summary.executed, 2); - assert_eq!(summary.refused, 1); - assert_eq!(summary.refusals.get("ceiling_program"), Some(&1)); - assert_eq!(summary.quota_spent.tool_calls, 2); - assert!(!summary.parked); - let rendered = summary.render(); - assert!(rendered.contains("2 actions executed, 1 refused")); - assert!(rendered.contains("ceiling_program x1")); -} - -/// Oracle §4.6 + §6.1 + §6.2: program invocation needs both the -/// base key in the ceiling and the program on the owner's allowlist, -/// and it charges the program axis of the quota. -#[test] -fn program_invoke_needs_the_allowlist_and_charges_the_program_axis() { - let mut fx = fixture_with_ceiling( - WorldScopes::GUEST, - big_budget(), - Vec::new(), - Some(|ceiling| ceiling.with_programs(vec!["lamp.toggle".to_owned()])), - ); - let allowed = fx.point.admit( - &fx.host, - &AgentAction::new("program.invoke", "program.invoke:lamp.toggle"), - 0, - NOW + 1, - ); - let charge = allowed.decision.expect("allowlisted program admitted"); - assert_eq!(charge.program_invocations, 1); - assert_eq!(fx.point.spent().program_invocations, 1); - - let unlisted = fx.point.admit( - &fx.host, - &AgentAction::new("program.invoke", "program.invoke:door.unlock"), - 0, - NOW + 2, - ); - assert_eq!(unlisted.decision, Err(PolicyRefusal::CeilingProgram)); -} - -/// Oracle §6.1: object classes are part of the ceiling — an action -/// on a class the owner has not allowed is refused even when its -/// tool is in the ceiling. -#[test] -fn object_classes_are_part_of_the_ceiling() { - let mut fx = fixture_with_ceiling( - WorldScopes::GUEST, - big_budget(), - Vec::new(), - Some(|ceiling| ceiling.with_object_classes(vec!["note".to_owned()])), - ); - let note = AgentAction::new("object.inspect", "screen.read").with_object("obj-1", "note"); - assert!(fx.point.admit(&fx.host, ¬e, 0, NOW + 1).decision.is_ok()); - let secret = - AgentAction::new("object.inspect", "screen.read").with_object("obj-2", "credential"); - let refused = fx.point.admit(&fx.host, &secret, 0, NOW + 2); - assert_eq!(refused.decision, Err(PolicyRefusal::CeilingObjectClass)); -} - -/// Oracle §6.3: the per-tool rate limit refuses beyond the role's -/// limit inside the window, and the window slides. -#[test] -fn chat_post_rate_limit_refuses_beyond_the_role_limit() { - let limits = vec![RateLimit { - tool: "chat.post".to_owned(), - max_calls: 2, - window_secs: 60, - }]; - let mut fx = fixture(WorldScopes::GUEST, big_budget(), limits); - let chat = AgentAction::new("chat.post", "chat.post"); - assert!(fx.point.admit(&fx.host, &chat, 0, NOW + 1).decision.is_ok()); - assert!(fx.point.admit(&fx.host, &chat, 0, NOW + 2).decision.is_ok()); - let third = fx.point.admit(&fx.host, &chat, 0, NOW + 3); - assert_eq!(third.decision, Err(PolicyRefusal::RateLimited)); - let later = fx.point.admit(&fx.host, &chat, 0, NOW + 62); - assert!(later.decision.is_ok(), "the window slides open again"); -} - -/// Oracle §5.3: once the delegation behind the session expires, -/// actions are refused (and audited) until the owner's client -/// renews. -#[test] -fn expired_delegation_refuses_actions() { - let mut fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - let admission = fx.point.admit( - &fx.host, - &AgentAction::new("screen.read", "screen.read"), - 0, - NOW + DEFAULT_LIFETIME_SECS, - ); - assert_eq!(admission.decision, Err(PolicyRefusal::DelegationExpired)); - assert_eq!(admission.event.event.outcome, "refused:delegation_expired"); -} - -/// Oracle §4.1 + §7: the join is audit event #1 of the session. -#[test] -fn the_join_is_the_first_audit_event() { - let fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - let events = fx.point.log().events(); - assert_eq!(events.len(), 1); - assert_eq!(events[0].seq, 0); - assert_eq!(events[0].event.tool, "world.join"); - assert_eq!(events[0].event.outcome, "granted"); - assert!(events[0].event.proof_ref.is_some()); -} - -/// Oracle §6/§7 property: for any sequence of actions, the log -/// holds exactly one event per action plus the join, and the chain -/// verifies — refusals are never sampled away, whatever the mix. -#[test] -fn any_action_sequence_leaves_a_complete_verifiable_log() { - let mut fx = fixture(WorldScopes::GUEST, big_budget(), Vec::new()); - let tools = [ - ("screen.read", "screen.read"), - ("chat.post", "chat.post"), - ("world.leave", "presence"), - ("program.invoke", "program.invoke:nope"), - ("host.exec", "host.exec"), - ]; - let mut state = 0x2436_2017u32; - let mut next = move || { - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (state >> 16) as usize - }; - for step in 0..40u64 { - let (tool, ceiling_key) = tools[next() % tools.len()]; - let decided = u64::from(next() % 3 == 0); - let action = AgentAction::new(tool, ceiling_key).with_decided_revision(decided); - fx.point.admit(&fx.host, &action, 1, NOW + 1 + step); - } - assert_eq!(fx.point.log().len(), 41); - fx.point - .log() - .verify(&fx.host.verifying_key()) - .expect("chain verifies after a mixed sequence"); -}