diff --git a/crates/aien-mcp/src/authority.rs b/crates/aien-mcp/src/authority.rs new file mode 100644 index 00000000..a1868578 --- /dev/null +++ b/crates/aien-mcp/src/authority.rs @@ -0,0 +1,154 @@ +//! Host-owned authority seam: the only production path to an [`AuthorizedEffect`]. +//! +//! An [`EffectIntent`] carries no authority. It becomes an `AuthorizedEffect` only when +//! [`crate::EffectLane::authorize`] (or `authorize_and_execute`) asks an [`EffectAuthority`] and +//! the answer is `Allow` or `AllowRestricted`. The mint is crate-private, so a caller cannot +//! build the value, and the lane, not the caller, supplies the live tool descriptor the +//! authority decides from. +//! +//! [`AuthorityDecision`] mirrors aegis-runtime `DoctrineDecision` one-to-one +//! (`Allow, AllowRestricted, RequireApproval, Deny, Contain`). It is not a new policy language. +//! aien-mcp cannot depend on aegis-runtime, so the shape is repeated here. Consolidating +//! `SafetyEngine`, `ProbePolicyGuard` and `DoctrineDecision` is a separate AIEN milestone. +//! +//! [`EffectClassAuthority`] is the one production implementation. It decides only from the +//! `aien_capability::ToolEffects` bits the catalog already declares (ADR 0005, ADR 0007: +//! irreversible effects are intents only). + +use aien_capability::{Digest32, EffectId, JNodeId, ToolDescriptor, ToolEffects, WorldId}; + +use crate::{EffectIntent, Error}; + +/// Verdict of an [`EffectAuthority`]. Same five variants as aegis-runtime `DoctrineDecision`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AuthorityDecision { + Allow, + /// Allowed under the listed restrictions (recorded in the policy digest). + AllowRestricted(Vec), + /// A human or approval authority must decide. Nothing runs and nothing is consumed. + RequireApproval(String), + Deny(String), + Contain(String), +} + +/// World facts the committer supplies. Identifiers only: they carry no authority. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EffectScope { + pub world_id: WorldId, + pub winning_jnode: JNodeId, + pub idempotency_key: EffectId, +} + +/// What an authority sees. Built by the lane from the live session, never by the caller. +#[derive(Clone, Debug)] +pub struct AuthorityContext { + scope: EffectScope, + descriptor: Option, + live_catalog_digest: Digest32, +} + +impl AuthorityContext { + pub(crate) fn new( + scope: EffectScope, + descriptor: Option, + live_catalog_digest: Digest32, + ) -> Self { + Self { + scope, + descriptor, + live_catalog_digest, + } + } + + pub fn scope(&self) -> EffectScope { + self.scope + } + + /// The descriptor in the live catalog for the intent's tool, or `None` if unknown. + pub fn descriptor(&self) -> Option<&ToolDescriptor> { + self.descriptor.as_ref() + } + + pub fn live_catalog_digest(&self) -> Digest32 { + self.live_catalog_digest + } +} + +/// Decides whether an intent may become an `AuthorizedEffect`. +pub trait EffectAuthority { + fn authorize(&self, intent: &EffectIntent, ctx: &AuthorityContext) -> AuthorityDecision; +} + +/// Why no `AuthorizedEffect` was produced (or why execution failed afterwards). +#[derive(Debug, PartialEq, Eq)] +pub enum AuthorityOutcome { + /// Approval is required. Nothing executed. `intent_digest` names the intent to approve. + /// No approval record is created or consumed by aien-mcp. + Pending { + intent_digest: Digest32, + reason: String, + }, + Denied(String), + Contained(String), + /// Authorization succeeded but the effect lane failed (stale catalog, provider error, ...). + Execution(Error), +} + +/// Digest that names one intent: tool, arguments and the catalog it was staged against. +pub fn intent_digest(intent: &EffectIntent) -> Digest32 { + let mut bytes = Vec::new(); + bytes.extend_from_slice(intent.provider.as_str().as_bytes()); + bytes.push(0); + bytes.extend_from_slice(intent.tool_name.as_bytes()); + bytes.push(0); + bytes.extend_from_slice(intent.arguments.to_string().as_bytes()); + bytes.push(0); + bytes.extend_from_slice(&intent.capability_digest.0); + Digest32::of(&bytes) +} + +/// AIEN's production authority. Decides from the declared `ToolEffects` of the live descriptor. +/// +/// | effects | decision | +/// |---|---| +/// | `EXTERNAL_IRREVERSIBLE` | `Deny` (irreversible effects stay intents, ADR 0005/0007) | +/// | `EXTERNAL_WRITE`, `WORLD_MUTATION`, `SECRET_BEARING`, `SPAWN_PROCESS` | `RequireApproval` | +/// | `PURE`, `READ_FILESYSTEM`, `READ_NETWORK`, `LOCAL_EPHEMERAL` | `Allow` | +/// | unknown tool, unknown effect bits | `Deny` | +#[derive(Clone, Copy, Debug, Default)] +pub struct EffectClassAuthority; + +const KNOWN_BITS: u32 = 0xFF; + +impl EffectAuthority for EffectClassAuthority { + fn authorize(&self, intent: &EffectIntent, ctx: &AuthorityContext) -> AuthorityDecision { + let Some(desc) = ctx.descriptor() else { + return AuthorityDecision::Deny(format!( + "tool `{}` is not in the live catalog", + intent.tool_name + )); + }; + let e = desc.effects(); + if e.bits() & !KNOWN_BITS != 0 { + return AuthorityDecision::Deny("tool declares unknown effect bits".into()); + } + if e.intersects(ToolEffects::EXTERNAL_IRREVERSIBLE) { + return AuthorityDecision::Deny( + "irreversible external effects are intents only".into(), + ); + } + if e.intersects( + ToolEffects::EXTERNAL_WRITE + | ToolEffects::WORLD_MUTATION + | ToolEffects::SECRET_BEARING + | ToolEffects::SPAWN_PROCESS, + ) { + return AuthorityDecision::RequireApproval(format!( + "tool `{}` needs approval (effect bits {:#x})", + intent.tool_name, + e.bits() + )); + } + AuthorityDecision::Allow + } +} diff --git a/crates/aien-mcp/src/broker.rs b/crates/aien-mcp/src/broker.rs index d62dba4e..db0e3aa4 100644 --- a/crates/aien-mcp/src/broker.rs +++ b/crates/aien-mcp/src/broker.rs @@ -7,6 +7,11 @@ use aien_capability::{ }; use serde_json::Value; +use crate::authority::{ + intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, + EffectScope, +}; +use crate::effect::mint; use crate::{ AuthorizedEffect, CallOutcome, CapabilitySnapshot, EffectIntent, EffectReceipt, Error, McpWire, ToolResult, @@ -224,6 +229,73 @@ impl EffectLane { Self { broker } } + /// Ask `authority` whether `intent` may run, and mint an `AuthorizedEffect` only on + /// `Allow` or `AllowRestricted`. This is the only production path to an `AuthorizedEffect`. + /// + /// The lane, not the caller, reads the live descriptor for the authority. A stale intent + /// (digest differs from the live catalog) is denied before the authority is asked. + /// `RequireApproval` returns `Pending` with the intent digest; no approval is created or + /// consumed here. `Deny` and `Contain` return errors. + pub fn authorize( + &self, + intent: EffectIntent, + scope: EffectScope, + authority: &dyn EffectAuthority, + ) -> Result, AuthorityOutcome> { + let (descriptor, live) = { + let inner = self.broker.lock(); + let session = inner + .sessions + .get(intent.provider.as_str()) + .ok_or_else(|| AuthorityOutcome::Denied("provider is not admitted".into()))?; + ( + find_tool(session, &intent.tool_name).cloned(), + session.catalog_digest, + ) + }; + if intent.capability_digest != live { + return Err(AuthorityOutcome::Denied( + "intent was staged against a stale catalog".into(), + )); + } + let ctx = AuthorityContext::new(scope, descriptor, live); + let decision = authority.authorize(&intent, &ctx); + let policy_digest = { + let mut bytes = format!("{decision:?}|{}|", intent.tool_name).into_bytes(); + bytes.extend_from_slice(&live.0); + Digest32::of(&bytes) + }; + match decision { + AuthorityDecision::Allow | AuthorityDecision::AllowRestricted(_) => Ok(mint( + intent, + scope.world_id, + scope.winning_jnode, + policy_digest, + live, + scope.idempotency_key, + )), + AuthorityDecision::RequireApproval(reason) => Err(AuthorityOutcome::Pending { + intent_digest: intent_digest(&intent), + reason, + }), + AuthorityDecision::Deny(reason) => Err(AuthorityOutcome::Denied(reason)), + AuthorityDecision::Contain(reason) => Err(AuthorityOutcome::Contained(reason)), + } + } + + /// `authorize`, then `execute_effect`. Nothing reaches the provider unless authorized. + pub async fn authorize_and_execute( + &self, + intent: EffectIntent, + scope: EffectScope, + authority: &dyn EffectAuthority, + ) -> Result { + let effect = self.authorize(intent, scope, authority)?; + self.execute_effect(effect) + .await + .map_err(AuthorityOutcome::Execution) + } + pub async fn execute_effect( &self, effect: AuthorizedEffect, diff --git a/crates/aien-mcp/src/effect.rs b/crates/aien-mcp/src/effect.rs index 93f0f1a0..49f1d7dc 100644 --- a/crates/aien-mcp/src/effect.rs +++ b/crates/aien-mcp/src/effect.rs @@ -32,10 +32,31 @@ pub struct EffectReceipt { /// An effect the policy boundary has allowed. /// -/// This commit has no production constructor. The next policy change is the -/// only path that may mint one: an `EffectIntent` enters AEGIS, and an -/// `AuthorizedEffect` comes out. Fields stay private so another crate cannot -/// build the value with a struct literal. +/// The only production mint is crate-private and reachable solely through +/// [`crate::EffectLane::authorize`], which asks an [`crate::EffectAuthority`]. Fields stay +/// private, so another crate cannot build the value with a struct literal: +/// +/// ```compile_fail +/// use aien_capability::{Digest32, EffectId, JNodeId, WorldId}; +/// use aien_mcp::AuthorizedEffect; +/// let _ = AuthorizedEffect { +/// intent: (), +/// world_id: WorldId(1), +/// winning_jnode: JNodeId(1), +/// policy_digest: Digest32::of(b"x"), +/// capability_digest: Digest32::of(b"x"), +/// idempotency_key: EffectId::from_label("x"), +/// }; +/// ``` +/// +/// A bare intent cannot be executed: +/// +/// ```compile_fail +/// use aien_mcp::{EffectIntent, EffectLane, McpBroker}; +/// async fn f(lane: EffectLane, intent: EffectIntent) { +/// let _ = lane.execute_effect(intent).await; +/// } +/// ``` #[derive(Clone, Debug)] pub struct AuthorizedEffect { intent: T, @@ -91,3 +112,23 @@ pub(crate) fn authorize_for_test( idempotency_key, } } + +/// Production mint. Crate-private: reached only from `EffectLane::authorize` after an +/// `EffectAuthority` returned `Allow` or `AllowRestricted`. +pub(crate) fn mint( + intent: T, + world_id: WorldId, + winning_jnode: JNodeId, + policy_digest: Digest32, + capability_digest: Digest32, + idempotency_key: EffectId, +) -> AuthorizedEffect { + AuthorizedEffect { + intent, + world_id, + winning_jnode, + policy_digest, + capability_digest, + idempotency_key, + } +} diff --git a/crates/aien-mcp/src/lib.rs b/crates/aien-mcp/src/lib.rs index b4307060..1a03a777 100644 --- a/crates/aien-mcp/src/lib.rs +++ b/crates/aien-mcp/src/lib.rs @@ -4,6 +4,7 @@ //! and may invoke only speculation-safe tools. An irreversible `tools/call` //! runs only when the Effect Broker presents an [`AuthorizedEffect`]. +mod authority; mod broker; mod effect; mod error; @@ -22,6 +23,10 @@ mod transport_tests; #[cfg(test)] pub(crate) use effect::authorize_for_test; +pub use authority::{ + intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, + EffectClassAuthority, EffectScope, +}; pub use broker::{EffectLane, McpBroker, SpeculativeLane, SpeculativeToolCall}; pub use effect::{AuthorizedEffect, EffectIntent, EffectReceipt, ToolResult}; pub use error::Error; diff --git a/crates/aien-mcp/tests/authority.rs b/crates/aien-mcp/tests/authority.rs new file mode 100644 index 00000000..4e309854 --- /dev/null +++ b/crates/aien-mcp/tests/authority.rs @@ -0,0 +1,185 @@ +//! Negative controls for the host-owned authority seam. This file is outside the crate, so it +//! can touch only the public API: no `AuthorizedEffect` can be built here except through +//! `EffectLane::authorize`. +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use aien_capability::{ + Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId, +}; +use aien_mcp::memory::MemoryWire; +use aien_mcp::{ + AuthorityContext, AuthorityDecision, AuthorityOutcome, CallOutcome, EffectAuthority, + EffectClassAuthority, EffectIntent, EffectLane, EffectScope, McpBroker, +}; +use serde_json::json; + +struct Fixed(AuthorityDecision); +impl EffectAuthority for Fixed { + fn authorize(&self, _: &EffectIntent, _: &AuthorityContext) -> AuthorityDecision { + self.0.clone() + } +} + +struct H { + lane: EffectLane, + calls: Arc, + intent: EffectIntent, +} + +fn scope(label: &str) -> EffectScope { + EffectScope { + world_id: WorldId(1), + winning_jnode: JNodeId(1), + idempotency_key: EffectId::from_label(label), + } +} + +async fn harness(effects: ToolEffects) -> H { + let calls = Arc::new(AtomicUsize::new(0)); + let c = calls.clone(); + let tool = ToolDescriptor::new("t", effects, Digest32::of(b"t")); + let wire = MemoryWire::new(vec![tool], move |_, _| { + c.fetch_add(1, Ordering::SeqCst); + CallOutcome::Finished(json!({"done": true})) + }); + let broker = McpBroker::new(); + let provider = ProviderId::new("p"); + broker + .admit(provider.clone(), Arc::new(wire)) + .await + .unwrap(); + // An intent is plain data (public fields). Possessing one grants nothing. + let live = aien_mcp::SpeculativeLane::new(broker.clone()) + .discovery_snapshot(&provider) + .await + .unwrap() + .catalog_digest; + let intent = EffectIntent { + provider, + tool_name: "t".into(), + arguments: json!({"a": 1}), + capability_digest: live, + }; + H { + lane: EffectLane::new(broker), + calls, + intent, + } +} + +#[tokio::test] +async fn deny_mints_nothing_and_never_executes() { + let h = harness(ToolEffects::PURE).await; + let a = Fixed(AuthorityDecision::Deny("no".into())); + assert!(h.lane.authorize(h.intent.clone(), scope("d"), &a).is_err()); + let r = h.lane.authorize_and_execute(h.intent, scope("d"), &a).await; + assert_eq!(r.unwrap_err(), AuthorityOutcome::Denied("no".into())); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn contain_mints_nothing_and_never_executes() { + let h = harness(ToolEffects::PURE).await; + let a = Fixed(AuthorityDecision::Contain("box".into())); + let r = h.lane.authorize_and_execute(h.intent, scope("c"), &a).await; + assert_eq!(r.unwrap_err(), AuthorityOutcome::Contained("box".into())); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn require_approval_is_pending_and_never_executes() { + let h = harness(ToolEffects::WORLD_MUTATION).await; + let want = aien_mcp::intent_digest(&h.intent); + let r = h + .lane + .authorize_and_execute(h.intent, scope("p"), &EffectClassAuthority) + .await; + match r.unwrap_err() { + AuthorityOutcome::Pending { intent_digest, .. } => assert_eq!(intent_digest, want), + other => panic!("expected Pending, got {other:?}"), + } + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn allow_executes_and_returns_receipt() { + let h = harness(ToolEffects::LOCAL_EPHEMERAL).await; + let r = h + .lane + .authorize_and_execute(h.intent, scope("a"), &EffectClassAuthority) + .await + .unwrap(); + assert_eq!(r.output, json!({"done": true})); + assert_eq!(r.tool_name, "t"); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn allow_restricted_mints() { + let h = harness(ToolEffects::PURE).await; + let a = Fixed(AuthorityDecision::AllowRestricted(vec!["x".into()])); + assert!(h + .lane + .authorize_and_execute(h.intent, scope("r"), &a) + .await + .is_ok()); +} + +#[tokio::test] +async fn unknown_descriptor_is_denied() { + let h = harness(ToolEffects::PURE).await; + let mut intent = h.intent.clone(); + intent.tool_name = "ghost".into(); + let r = h + .lane + .authorize_and_execute(intent, scope("u"), &EffectClassAuthority) + .await; + assert!(matches!(r.unwrap_err(), AuthorityOutcome::Denied(_))); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn stale_intent_is_denied_before_the_authority_is_asked() { + let h = harness(ToolEffects::PURE).await; + let mut intent = h.intent.clone(); + intent.capability_digest = Digest32::of(b"old"); + let a = Fixed(AuthorityDecision::Allow); + let r = h.lane.authorize_and_execute(intent, scope("s"), &a).await; + assert!(matches!(r.unwrap_err(), AuthorityOutcome::Denied(_))); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn effect_class_table() { + use AuthorityDecision as D; + let cases = [ + (ToolEffects::PURE, "allow"), + (ToolEffects::READ_FILESYSTEM, "allow"), + (ToolEffects::READ_NETWORK, "allow"), + (ToolEffects::LOCAL_EPHEMERAL, "allow"), + (ToolEffects::EXTERNAL_WRITE, "approval"), + (ToolEffects::WORLD_MUTATION, "approval"), + (ToolEffects::SECRET_BEARING, "approval"), + (ToolEffects::SPAWN_PROCESS, "approval"), + (ToolEffects::EXTERNAL_IRREVERSIBLE, "deny"), + ( + ToolEffects::EXTERNAL_IRREVERSIBLE | ToolEffects::READ_FILESYSTEM, + "deny", + ), + ]; + for (effects, want) in cases { + let h = harness(effects).await; + let r = h + .lane + .authorize(h.intent.clone(), scope("t"), &EffectClassAuthority); + let got = match &r { + Ok(_) => "allow", + Err(AuthorityOutcome::Pending { .. }) => "approval", + Err(AuthorityOutcome::Denied(_)) => "deny", + Err(_) => "other", + }; + assert_eq!(got, want, "{effects:?}"); + } + let _ = D::Allow; +} diff --git a/docs/adr/0002-aien-mcp-effect-authority.md b/docs/adr/0002-aien-mcp-effect-authority.md new file mode 100644 index 00000000..ec9fedbf --- /dev/null +++ b/docs/adr/0002-aien-mcp-effect-authority.md @@ -0,0 +1,27 @@ +# ADR 0002: aien-mcp mints AuthorizedEffect only through a host-supplied EffectAuthority + +Status: Proposed (2026-10-04) + +`AuthorizedEffect` had no production constructor. This change adds one, and only one: +`EffectLane::authorize` (and `authorize_and_execute`) in `crates/aien-mcp`. The lane builds an +`AuthorityContext` from the live session (descriptor, catalog digest), asks an `EffectAuthority`, +and mints through a crate-private function on `Allow` or `AllowRestricted`. +`RequireApproval` returns `Pending` carrying the intent digest. `Deny` and `Contain` return +errors. A stale or unknown tool is denied before the authority is asked or by the authority. +Nothing is persisted: aien-mcp does not wire the aegis-runtime `Approval` types, so no approval is +created or consumed here. + +`AuthorityDecision` mirrors aegis-runtime `DoctrineDecision` one-to-one. aien-mcp cannot depend on +aegis-runtime, so the shape is repeated, not extended. Consolidating `SafetyEngine`, +`ProbePolicyGuard` and `DoctrineDecision` into one authority is a separate AIEN milestone; this +change adds no new policy language. + +`EffectClassAuthority` decides only from the `ToolEffects` bits the catalog already declares: +`EXTERNAL_IRREVERSIBLE` Deny; `EXTERNAL_WRITE`, `WORLD_MUTATION`, `SECRET_BEARING`, +`SPAWN_PROCESS` RequireApproval; `PURE`, `READ_FILESYSTEM`, `READ_NETWORK`, `LOCAL_EPHEMERAL` +Allow; unknown tool or unknown bits Deny. + +Known limit: `EffectAuthority` is a public trait, so whoever holds an `EffectLane` and can write +an implementation can supply an allow-all authority. The seam keeps the intent from being +self-authorizing; it does not by itself stop a host that chooses a permissive authority. Binding +the authority to the AIENOS capability root (ADR 0016) is future work.