Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/62f09cde21a62f58 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#203 (code only) closed derived `62f09cde21a62f58` #203 Imported from GitHub aien-dev/aien-sovereign-core-mv#203 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `0bcd558ed9adc3aafcc59526fba6417a86fe804b` · Head `bdcb2d4fb631df7777b2ce9fbda41088a2abcd7e` greptile-apps[bot] commented on `crates/aien-mcp/src/broker.rs` line 269 on 2026-10-04 21:37 UTC P1 security Restricted calls run unrestricted When an authority returns `AllowRestricted`, this branch discards the restrictions and mints the effect. Execution sends the original arguments to the provider, so a call that violates the authority’s conditions can still run. Enforce the restrictions before dispatch, or reject conditions the broker cannot enforce. This must be fixed before merging. How this was verified: A call restricted to an approved recipient reached the provider with an unapproved recipient and returned a receipt.
Artifacts
Rust integration probe source for allowed and restricted calls - This source was copied into the isolated worktree and executed with both authority decisions; it captures the provider's actual arguments. Provider call with unrestricted Allow decision - The recorded command ran the probe with `CASE=allow` and exited 0, showing one call carrying the original unapproved recipient. Provider call with recipient restriction - The recorded command ran the same probe with `CASE=restricted` and exited 0, showing the same unapproved recipient reached the provider despite the restriction. View artifacts
T-Rex Ran code and verified through T-Rex
Prompt To Fix With AI ``` This is a comment left during a code review. Path: crates/aien-mcp/src/broker.rs Line: 269 Comment: **Restricted calls run unrestricted** When an authority returns `AllowRestricted`, this branch discards the restrictions and mints the effect. Execution sends the original arguments to the provider, so a call that violates the authority’s conditions can still run. Enforce the restrictions before dispatch, or reject conditions the broker cannot enforce. This must be fixed before merging. > **How this was verified:** A call restricted to an approved recipient reached the provider with an unapproved recipient and returned a receipt. --- For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. ```
Fix in Claude Code greptile-apps[bot] commented on `crates/aien-mcp/src/broker.rs` line 255 on 2026-10-04 21:37 UTC P1 security Authorization loses session binding The lane releases the session lock after reading the descriptor and catalog digest. If the provider is re-admitted with a different wire but the same catalog before execution, the digest check passes and the authorized call runs on a session the authority did not examine. Bind the effect to a session generation that changes on every re-admission. This must be fixed before merging. How this was verified: Re-admission during authorization left the catalog unchanged, but the subsequent call reached the replacement wire.
Artifacts
Rust test for replacing a provider wire during authorization - This authored integration test stages an intent, optionally re-admits the provider inside the authority callback, and asserts which wire receives execution. Control run without provider re-admission - Running the test with `SWAP_WIRE=0` showed one old-wire call and zero new-wire calls, establishing the control. Run with provider re-admission during authorization - Running the same test with `SWAP_WIRE=1` showed zero old-wire calls and one new-wire call while the catalog and epoch remained unchanged, confirming the finding. Public-API Rust test for an unknown tool and custom allow authority - This authored test submits an unknown tool with the current catalog digest and checks authorization, execution, and provider calls. Script that runs the current and temporary guarded broker - This authored script runs the same test against repository source and a temporary copy with a descriptor guard, leaving tracked files unchanged. Current broker test log showing an effect minted for an unknown tool - The test called the custom authority with no descriptor, minted an effect, and received UnknownTool on execution; the provider was never called. Temporary guarded broker test log showing denial before authority - The same test ran against a temporary broker copy with a missing-descriptor guard and received Denied without calling the authority or provider. View artifacts
T-Rex Ran code and verified through T-Rex
Prompt To Fix With AI ``` This is a comment left during a code review. Path: crates/aien-mcp/src/broker.rs Line: 245-255 Comment: **Authorization loses session binding** The lane releases the session lock after reading the descriptor and catalog digest. If the provider is re-admitted with a different wire but the same catalog before execution, the digest check passes and the authorized call runs on a session the authority did not examine. Bind the effect to a session generation that changes on every re-admission. This must be fixed before merging. > **How this was verified:** Re-admission during authorization left the catalog unchanged, but the subsequent call reached the replacement wire. --- For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. ```
Fix in Claude Code greptile-apps[bot] commented on `crates/aien-mcp/src/broker.rs` line 252 on 2026-10-04 21:37 UTC P2 Unknown tools receive authorization If a host authority returns `Allow` without checking the optional descriptor, `authorize` mints an effect for a tool absent from the live catalog. Execution later returns `UnknownTool`, so callers authorizing separately receive a misleading success instead of the documented unknown-tool denial. Reject a missing descriptor before accepting the decision. This concern does not block merging because execution still rejects the call.
Artifacts
Public-API Rust test for an unknown tool and custom allow authority - This authored test submits an unknown tool with the current catalog digest and checks authorization, execution, and provider calls. Script that runs the current and temporary guarded broker - This authored script runs the same test against repository source and a temporary copy with a descriptor guard, leaving tracked files unchanged. Current broker test log showing an effect minted for an unknown tool - The test called the custom authority with no descriptor, minted an effect, and received UnknownTool on execution; the provider was never called. Temporary guarded broker test log showing denial before authority - The same test ran against a temporary broker copy with a missing-descriptor guard and received Denied without calling the authority or provider. View artifacts
T-Rex Ran code and verified through T-Rex
Prompt To Fix With AI ``` This is a comment left during a code review. Path: crates/aien-mcp/src/broker.rs Line: 252 Comment: **Unknown tools receive authorization** If a host authority returns `Allow` without checking the optional descriptor, `authorize` mints an effect for a tool absent from the live catalog. Execution later returns `UnknownTool`, so callers authorizing separately receive a misleading success instead of the documented unknown-tool denial. Reject a missing descriptor before accepting the decision. This concern does not block merging because execution still rejects the call. --- For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. ```
Fix in Claude Code greptile-apps[bot] commented on `crates/aien-mcp/src/authority.rs` line 114 on 2026-10-04 21:37 UTC P2 Policy rationale has broken references This table cites ADR 0005 and ADR 0007 for the irreversible-effects policy, but neither exists under `docs/adr/`. Readers cannot follow the cited rationale. Cite an existing decision or explain it here. The broken references are a non-blocking documentation concern.
Artifacts
Authored ADR citation checking script - The uploaded script compares authority.rs citations with ADR filenames at a specified Git revision, providing the reproducible check. Base revision ADR citation check - Running the check on origin/main showed that authority.rs was absent there, establishing the before condition. PR revision ADR citation check - Running the same check on HEAD found both ADR 0005 and ADR 0007 missing under docs/adr for the citation at line 114, confirming the finding. View artifacts
T-Rex Ran code and verified through T-Rex
Prompt To Fix With AI ``` This is a comment left during a code review. Path: crates/aien-mcp/src/authority.rs Line: 114 Comment: **Policy rationale has broken references** This table cites ADR 0005 and ADR 0007 for the irreversible-effects policy, but neither exists under `docs/adr/`. Readers cannot follow the cited rationale. Cite an existing decision or explain it here. The broken references are a non-blocking documentation concern. --- For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. ```
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! Fix in Claude Code greptile-apps[bot] reviewed (COMMENTED) on 2026-10-04 21:37 UTC greptile-apps[bot] wrote on 2026-10-04 21:37 UTC

RetriggerConfidence Score: 1/5

[Critical risk] Adds the production path to authorize and execute effects. Not safe to merge until restrictions are enforced and authorization is bound to the provider session that receives the call.

Fix All in Claude CodeFindings

- P1 Security Restricted calls run unrestricted ▶ - P1 Security Authorization loses session binding ▶ - P2 Unknown tools receive authorization ▶ - P2 Policy rationale has broken references ▶
Fix with agent prompt ``` ### Issue 1 crates/aien-mcp/src/broker.rs:269 When an authority returns `AllowRestricted`, this branch discards the restrictions and mints the effect. Execution sends the original arguments to the provider, so a call that violates the authority’s conditions can still run. Enforce the restrictions before dispatch, or reject conditions the broker cannot enforce. This must be fixed before merging. > **How this was verified:** A call restricted to an approved recipient reached the provider with an unapproved recipient and returned a receipt. ### Issue 2 crates/aien-mcp/src/broker.rs:245-255 The lane releases the session lock after reading the descriptor and catalog digest. If the provider is re-admitted with a different wire but the same catalog before execution, the digest check passes and the authorized call runs on a session the authority did not examine. Bind the effect to a session generation that changes on every re-admission. This must be fixed before merging. > **How this was verified:** Re-admission during authorization left the catalog unchanged, but the subsequent call reached the replacement wire. ### Issue 3 crates/aien-mcp/src/broker.rs:252 If a host authority returns `Allow` without checking the optional descriptor, `authorize` mints an effect for a tool absent from the live catalog. Execution later returns `UnknownTool`, so callers authorizing separately receive a misleading success instead of the documented unknown-tool denial. Reject a missing descriptor before accepting the decision. This concern does not block merging because execution still rejects the call. ### Issue 4 crates/aien-mcp/src/authority.rs:114 This table cites ADR 0005 and ADR 0007 for the irreversible-effects policy, but neither exists under `docs/adr/`. Readers cannot follow the cited rationale. Cite an existing decision or explain it here. The broken references are a non-blocking documentation concern. Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! --- For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. ```
Summary Adds a host-supplied authority seam for MCP effects, with authorization tests and documentation. User story: A host stages an effect and asks an authority whether it may run. The call should satisfy the authority’s conditions and reach the provider session against which it was authorized. Changes: Adds effect decisions and pending, denied, and contained outcomes; adds tests and documents the authority seam. Restricted calls can run without satisfying their conditions, and authorization can be applied to a replacement provider session. Both failures must be fixed before merging. Unknown-tool authorization and broken policy references are non-blocking concerns.
Reviews (1) · Last reviewed commit: "test(aien-mcp): negative controls for th..." ### Apply it ``` git checkout -b patch-62f09cde21a62f58 0bcd558ed9adc3aafcc59526fba6417a86fe804b curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/62f09cde21a62f58.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 203 bdcb2d4fb631df7777b2ce9fbda41088a2abcd7e ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":203,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/203","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:17Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` 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. ```