From 4474603dfa81c80d9484dfd8502a483a4557b1d3 Mon Sep 17 00:00:00 2001 From: aien Date: Sun, 4 Oct 2026 17:24:32 -0500 Subject: [PATCH] feat(aien-mcp): single-use approval consumption on the authority seam ApprovalDesk issues an ApprovalGrant bound to intent digest, idempotency key, world and J-node. EffectLane::authorize_approved spends it at mint time; a second use, wrong effect, or expired grant is refused with a typed ApprovalError. Replay of a completed request returns the ledger receipt. Co-Authored-By: Claude Sonnet 5.5 --- .crumb | 10 +- crates/aien-mcp/src/approval.rs | 108 ++++++++++++ crates/aien-mcp/src/authority.rs | 7 +- crates/aien-mcp/src/broker.rs | 129 +++++++++++++- crates/aien-mcp/src/lib.rs | 2 + crates/aien-mcp/src/session.rs | 7 +- crates/aien-mcp/tests/approval.rs | 281 ++++++++++++++++++++++++++++++ 7 files changed, 528 insertions(+), 16 deletions(-) create mode 100644 crates/aien-mcp/src/approval.rs create mode 100644 crates/aien-mcp/tests/approval.rs diff --git a/.crumb b/.crumb index 0c24acf6..091aca72 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:dfcfd805db0c30c667bc5682364bd3acb3383d494967dcae39f2420739723d7d", - "compiled_at": "2026-10-04T20:38:05Z", + "compiled_at": "2026-10-04T22:24:32Z", "compiler": "crumb-compile/1", - "digest": "sha256:6d499cbb26f7041353de10fd948cdbfa3013d648c58da39dc6395cc409b898a9", + "digest": "sha256:ccab54027d46c9733e848bd4fad0fb4c072c942a2177128415f989770ff742c5", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 677, - "generated_at_commit": "8c60f97ed5d702df3bd1966a8d0691e0b9c113c9", - "source_tree": "sha256:6edde9bdd6a59719ac31631c16a3520139a9b6cc61ac8f9e122a16b26a9610c0" + "files": 680, + "generated_at_commit": "2a968bfc2770c012b4d53cfb1669f97594d2ff31", + "source_tree": "sha256:ac6c6dfb3cb4d1e232093b035d8caa741ae9e5844d1c418a2b18aa4f13eebf6c" } }, "history": [], diff --git a/crates/aien-mcp/src/approval.rs b/crates/aien-mcp/src/approval.rs new file mode 100644 index 00000000..ab8d2330 --- /dev/null +++ b/crates/aien-mcp/src/approval.rs @@ -0,0 +1,108 @@ +//! Single-use approvals for the host-owned authority seam. +//! +//! When an [`crate::EffectAuthority`] answers `RequireApproval`, a host approver (a human or an +//! approval service, holding an [`ApprovalDesk`]) may issue one [`ApprovalGrant`]. The grant is +//! bound to one effect identity: the intent digest (tool, arguments, catalog), the idempotency +//! key, the world and the winning J-node. [`crate::EffectLane::authorize_approved`] spends the +//! grant when it mints the `AuthorizedEffect`. A second mint with the same grant is refused. +//! +//! Replay of a finished request does not need a second approval: the existing effect ledger +//! (keyed by the idempotency key) already returns the original receipt, and +//! [`crate::EffectLane::authorize_and_execute_approved`] consults it for a spent grant that is +//! bound to the same effect. +//! +//! Expiry uses a host-supplied `now` and `expires_at` in the same unit. The crate reads no clock. + +use aien_capability::{Digest32, EffectId, JNodeId, WorldId}; + +use crate::authority::{intent_digest, EffectScope}; +use crate::broker::McpBroker; +use crate::EffectIntent; + +/// Why an approval could not be spent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ApprovalError { + /// The grant was not issued by this broker's desk. + Unknown, + /// The grant is bound to a different effect than the one presented. Nothing is spent. + Mismatch, + /// The grant was already spent by an earlier mint. + Consumed, + /// `now` is at or past `expires_at`. Nothing is spent. + Expired, +} + +/// Proof that a host approver approved exactly one effect. Fields are private and only an +/// [`ApprovalDesk`] can create one. Cloning does not duplicate it: spending is tracked by the +/// broker, not by the value. +#[derive(Clone, Debug)] +pub struct ApprovalGrant { + id: Digest32, +} + +#[derive(Debug)] +pub(crate) struct ApprovalRecord { + pub(crate) intent_digest: Digest32, + pub(crate) idempotency_key: EffectId, + pub(crate) world_id: WorldId, + pub(crate) winning_jnode: JNodeId, + pub(crate) expires_at: u64, + pub(crate) consumed: bool, +} + +impl ApprovalRecord { + pub(crate) fn binds(&self, intent: &EffectIntent, scope: &EffectScope) -> bool { + self.intent_digest == intent_digest(intent) + && self.idempotency_key == scope.idempotency_key + && self.world_id == scope.world_id + && self.winning_jnode == scope.winning_jnode + } +} + +impl ApprovalGrant { + pub(crate) fn id(&self) -> Digest32 { + self.id + } +} + +/// The approver's handle. Held by the host's approval service, not by J-Space or the effect +/// lane's callers. Limit: any code holding a `McpBroker` or `SessionManager` can obtain one, so +/// the separation is by handle discipline, not by type. +#[derive(Clone)] +pub struct ApprovalDesk { + broker: McpBroker, +} + +impl ApprovalDesk { + pub fn new(broker: McpBroker) -> Self { + Self { broker } + } + + /// Issue one grant for exactly this intent and scope, valid while `now < expires_at`. + pub fn issue( + &self, + intent: &EffectIntent, + scope: EffectScope, + expires_at: u64, + ) -> ApprovalGrant { + let mut inner = self.broker.lock(); + inner.next_approval = inner.next_approval.saturating_add(1); + let digest = intent_digest(intent); + let mut bytes = inner.next_approval.to_le_bytes().to_vec(); + bytes.extend_from_slice(&digest.0); + bytes.extend_from_slice(&scope.idempotency_key.0); + let id = Digest32::of(&bytes); + inner.approvals.insert( + id, + ApprovalRecord { + intent_digest: digest, + idempotency_key: scope.idempotency_key, + world_id: scope.world_id, + winning_jnode: scope.winning_jnode, + expires_at, + consumed: false, + }, + ); + ApprovalGrant { id } + } +} diff --git a/crates/aien-mcp/src/authority.rs b/crates/aien-mcp/src/authority.rs index a1868578..004779b7 100644 --- a/crates/aien-mcp/src/authority.rs +++ b/crates/aien-mcp/src/authority.rs @@ -17,6 +17,7 @@ use aien_capability::{Digest32, EffectId, JNodeId, ToolDescriptor, ToolEffects, WorldId}; +use crate::approval::ApprovalError; use crate::{EffectIntent, Error}; /// Verdict of an [`EffectAuthority`]. Same five variants as aegis-runtime `DoctrineDecision`. @@ -25,7 +26,7 @@ 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. + /// A human or approval authority must decide. Nothing runs and nothing is consumed until an approval is spent. RequireApproval(String), Deny(String), Contain(String), @@ -83,11 +84,13 @@ pub trait EffectAuthority { #[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. + /// Issue one with [`crate::ApprovalDesk`] and spend it with [`crate::EffectLane::authorize_approved`]. Pending { intent_digest: Digest32, reason: String, }, + /// Approval was presented but could not be spent. See [`ApprovalError`]. + Approval(ApprovalError), Denied(String), Contained(String), /// Authorization succeeded but the effect lane failed (stale catalog, provider error, ...). diff --git a/crates/aien-mcp/src/broker.rs b/crates/aien-mcp/src/broker.rs index db0e3aa4..e55baa89 100644 --- a/crates/aien-mcp/src/broker.rs +++ b/crates/aien-mcp/src/broker.rs @@ -7,6 +7,7 @@ use aien_capability::{ }; use serde_json::Value; +use crate::approval::{ApprovalError, ApprovalGrant, ApprovalRecord}; use crate::authority::{ intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, EffectScope, @@ -33,9 +34,11 @@ enum LedgerEntry { Uncertain, } -struct Inner { +pub(crate) struct Inner { sessions: HashMap, ledger: HashMap, + pub(crate) approvals: HashMap, + pub(crate) next_approval: u64, } /// Owns admitted MCP sessions and the idempotency ledger. @@ -50,6 +53,8 @@ impl McpBroker { inner: Arc::new(Mutex::new(Inner { sessions: HashMap::new(), ledger: HashMap::new(), + approvals: HashMap::new(), + next_approval: 0, })), } } @@ -90,7 +95,7 @@ impl McpBroker { Ok(()) } - fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + pub(crate) fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { self.inner .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) @@ -234,13 +239,40 @@ impl EffectLane { /// /// 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. + /// `RequireApproval` returns `Pending` with the intent digest; no approval is consumed here + /// (see [`Self::authorize_approved`]). `Deny` and `Contain` return errors. pub fn authorize( &self, intent: EffectIntent, scope: EffectScope, authority: &dyn EffectAuthority, + ) -> Result, AuthorityOutcome> { + self.authorize_inner(intent, scope, authority, None) + } + + /// Like [`Self::authorize`], but a `RequireApproval` verdict is satisfied by spending `grant`. + /// + /// The grant must have been issued by an [`crate::ApprovalDesk`] for exactly this intent and + /// scope, must be unspent and unexpired (`now < expires_at`). A refused grant is not spent + /// unless it was already spent. `Deny` and `Contain` stay refused whatever the grant says, + /// and an `Allow` verdict never touches the grant. + pub fn authorize_approved( + &self, + intent: EffectIntent, + scope: EffectScope, + authority: &dyn EffectAuthority, + grant: &ApprovalGrant, + now: u64, + ) -> Result, AuthorityOutcome> { + self.authorize_inner(intent, scope, authority, Some((grant, now))) + } + + fn authorize_inner( + &self, + intent: EffectIntent, + scope: EffectScope, + authority: &dyn EffectAuthority, + approval: Option<(&ApprovalGrant, u64)>, ) -> Result, AuthorityOutcome> { let (descriptor, live) = { let inner = self.broker.lock(); @@ -274,10 +306,24 @@ impl EffectLane { live, scope.idempotency_key, )), - AuthorityDecision::RequireApproval(reason) => Err(AuthorityOutcome::Pending { - intent_digest: intent_digest(&intent), - reason, - }), + AuthorityDecision::RequireApproval(reason) => { + let Some((grant, now)) = approval else { + return Err(AuthorityOutcome::Pending { + intent_digest: intent_digest(&intent), + reason, + }); + }; + self.spend(grant, &intent, &scope, now) + .map_err(AuthorityOutcome::Approval)?; + Ok(mint( + intent, + scope.world_id, + scope.winning_jnode, + policy_digest, + live, + scope.idempotency_key, + )) + } AuthorityDecision::Deny(reason) => Err(AuthorityOutcome::Denied(reason)), AuthorityDecision::Contain(reason) => Err(AuthorityOutcome::Contained(reason)), } @@ -296,6 +342,73 @@ impl EffectLane { .map_err(AuthorityOutcome::Execution) } + /// `authorize_approved`, then `execute_effect`. + /// + /// If `grant` is already spent for this same effect (same intent, key, world, J-node), the + /// request is a replay: the ledger's existing outcome is returned and nothing is minted. + /// Any other use of a spent grant is refused with `ApprovalError::Consumed`. + pub async fn authorize_and_execute_approved( + &self, + intent: EffectIntent, + scope: EffectScope, + authority: &dyn EffectAuthority, + grant: &ApprovalGrant, + now: u64, + ) -> Result { + if let Some(existing) = self.replay_of(grant, &intent, &scope) { + return existing.map_err(AuthorityOutcome::Execution); + } + let effect = self.authorize_approved(intent, scope, authority, grant, now)?; + self.execute_effect(effect) + .await + .map_err(AuthorityOutcome::Execution) + } + + /// Ledger outcome for a spent grant presented again for the effect it was spent on. + fn replay_of( + &self, + grant: &ApprovalGrant, + intent: &EffectIntent, + scope: &EffectScope, + ) -> Option> { + let inner = self.broker.lock(); + let record = inner.approvals.get(&grant.id())?; + if !record.consumed || !record.binds(intent, scope) { + return None; + } + match inner.ledger.get(&scope.idempotency_key)? { + LedgerEntry::Completed(receipt) => Some(Ok(receipt.clone())), + LedgerEntry::Uncertain => Some(Err(Error::ReconciliationRequired)), + LedgerEntry::InFlight => Some(Err(Error::EffectInFlight)), + } + } + + /// Check and spend `grant` atomically under the broker lock. + fn spend( + &self, + grant: &ApprovalGrant, + intent: &EffectIntent, + scope: &EffectScope, + now: u64, + ) -> Result<(), ApprovalError> { + let mut inner = self.broker.lock(); + let record = inner + .approvals + .get_mut(&grant.id()) + .ok_or(ApprovalError::Unknown)?; + if !record.binds(intent, scope) { + return Err(ApprovalError::Mismatch); + } + if record.consumed { + return Err(ApprovalError::Consumed); + } + if now >= record.expires_at { + return Err(ApprovalError::Expired); + } + record.consumed = true; + Ok(()) + } + pub async fn execute_effect( &self, effect: AuthorizedEffect, diff --git a/crates/aien-mcp/src/lib.rs b/crates/aien-mcp/src/lib.rs index 1a03a777..dd2d890a 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 approval; mod authority; mod broker; mod effect; @@ -23,6 +24,7 @@ mod transport_tests; #[cfg(test)] pub(crate) use effect::authorize_for_test; +pub use approval::{ApprovalDesk, ApprovalError, ApprovalGrant}; pub use authority::{ intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority, EffectClassAuthority, EffectScope, diff --git a/crates/aien-mcp/src/session.rs b/crates/aien-mcp/src/session.rs index 481d054d..3c0b7ede 100644 --- a/crates/aien-mcp/src/session.rs +++ b/crates/aien-mcp/src/session.rs @@ -8,7 +8,7 @@ use rmcp::service::RoleClient; use rmcp::transport::IntoTransport; use crate::transport::RmcpClientWire; -use crate::{EffectLane, Error, McpBroker, McpWire, SpeculativeLane}; +use crate::{ApprovalDesk, EffectLane, Error, McpBroker, McpWire, SpeculativeLane}; /// Admits MCP providers and hands out the two lanes. /// @@ -34,6 +34,11 @@ impl SessionManager { EffectLane::new(self.broker.clone()) } + /// The approver's handle. Keep it away from callers of the effect lane. + pub fn approval_desk(&self) -> ApprovalDesk { + ApprovalDesk::new(self.broker.clone()) + } + /// Enroll a provider that is already on an [`McpWire`]. pub async fn enroll(&self, provider: ProviderId, wire: Arc) -> Result<(), Error> { self.broker.admit(provider, wire).await diff --git a/crates/aien-mcp/tests/approval.rs b/crates/aien-mcp/tests/approval.rs new file mode 100644 index 00000000..c7bad812 --- /dev/null +++ b/crates/aien-mcp/tests/approval.rs @@ -0,0 +1,281 @@ +//! Single-use approval consumption, through the public API only. +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::{ + ApprovalDesk, ApprovalError, AuthorityContext, AuthorityDecision, AuthorityOutcome, + CallOutcome, EffectAuthority, EffectClassAuthority, EffectIntent, EffectLane, EffectScope, + McpBroker, SpeculativeLane, +}; +use serde_json::json; + +struct Fixed(AuthorityDecision); +impl EffectAuthority for Fixed { + fn authorize(&self, _: &EffectIntent, _: &AuthorityContext) -> AuthorityDecision { + self.0.clone() + } +} + +struct H { + broker: McpBroker, + lane: EffectLane, + desk: ApprovalDesk, + 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() -> H { + let calls = Arc::new(AtomicUsize::new(0)); + let c = calls.clone(); + let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, 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(); + let live = 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.clone()), + desk: ApprovalDesk::new(broker.clone()), + broker, + calls, + intent, + } +} + +fn approval(e: AuthorityOutcome) -> ApprovalError { + match e { + AuthorityOutcome::Approval(a) => a, + other => panic!("expected Approval, got {other:?}"), + } +} + +#[tokio::test] +async fn first_use_mints_and_runs_once() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("a"), 100); + let r = h + .lane + .authorize_and_execute_approved(h.intent.clone(), scope("a"), &EffectClassAuthority, &g, 1) + .await + .unwrap(); + assert_eq!(r.output, json!({"done": true})); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn second_mint_with_the_same_grant_is_refused() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("b"), 100); + let a = EffectClassAuthority; + assert!(h + .lane + .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1) + .is_ok()); + let err = h + .lane + .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1) + .unwrap_err(); + assert_eq!(approval(err), ApprovalError::Consumed); + // A cloned grant is the same grant. + let err = h + .lane + .authorize_approved(h.intent.clone(), scope("b"), &a, &g.clone(), 1) + .unwrap_err(); + assert_eq!(approval(err), ApprovalError::Consumed); +} + +#[tokio::test] +async fn replay_after_completion_returns_the_existing_receipt() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("r"), 100); + let a = EffectClassAuthority; + let first = h + .lane + .authorize_and_execute_approved(h.intent.clone(), scope("r"), &a, &g, 1) + .await + .unwrap(); + // Even after the grant has expired, the same logical request gets the same outcome. + let again = h + .lane + .authorize_and_execute_approved(h.intent.clone(), scope("r"), &a, &g, 10_000) + .await + .unwrap(); + assert_eq!(first, again); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn spent_grant_cannot_run_a_different_request_under_the_same_key() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("k"), 100); + let a = EffectClassAuthority; + h.lane + .authorize_and_execute_approved(h.intent.clone(), scope("k"), &a, &g, 1) + .await + .unwrap(); + let mut other = h.intent.clone(); + other.arguments = json!({"a": 2}); + let err = h + .lane + .authorize_and_execute_approved(other, scope("k"), &a, &g, 1) + .await + .unwrap_err(); + assert_eq!(approval(err), ApprovalError::Mismatch); + assert_eq!(h.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn grant_for_a_different_effect_is_refused_and_not_spent() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("x"), 100); + let a = EffectClassAuthority; + let mut other = h.intent.clone(); + other.arguments = json!({"a": 2}); + let e = h + .lane + .authorize_approved(other, scope("x"), &a, &g, 1) + .unwrap_err(); + assert_eq!(approval(e), ApprovalError::Mismatch); + let e = h + .lane + .authorize_approved(h.intent.clone(), scope("y"), &a, &g, 1) + .unwrap_err(); + assert_eq!(approval(e), ApprovalError::Mismatch); + let mut w = scope("x"); + w.world_id = WorldId(2); + let e = h + .lane + .authorize_approved(h.intent.clone(), w, &a, &g, 1) + .unwrap_err(); + assert_eq!(approval(e), ApprovalError::Mismatch); + // The mismatches burned nothing: the right request still works. + assert!(h + .lane + .authorize_approved(h.intent.clone(), scope("x"), &a, &g, 1) + .is_ok()); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn expired_grant_is_refused_and_not_spent() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("e"), 50); + let a = EffectClassAuthority; + let e = h + .lane + .authorize_approved(h.intent.clone(), scope("e"), &a, &g, 50) + .unwrap_err(); + assert_eq!(approval(e), ApprovalError::Expired); + assert!(h + .lane + .authorize_approved(h.intent.clone(), scope("e"), &a, &g, 49) + .is_ok()); +} + +#[tokio::test] +async fn catalog_change_makes_the_grant_stale() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("c"), 100); + let provider = h.intent.provider.clone(); + let changed = vec![ + ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t")), + ToolDescriptor::new("u", ToolEffects::PURE, Digest32::of(b"u")), + ]; + h.broker.replace_catalog(&provider, changed).await.unwrap(); + let e = h + .lane + .authorize_approved(h.intent.clone(), scope("c"), &EffectClassAuthority, &g, 1) + .unwrap_err(); + assert!(matches!(e, AuthorityOutcome::Denied(_))); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn deny_and_contain_stay_refused_and_keep_the_grant() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("d"), 100); + let deny = Fixed(AuthorityDecision::Deny("no".into())); + let e = h + .lane + .authorize_and_execute_approved(h.intent.clone(), scope("d"), &deny, &g, 1) + .await + .unwrap_err(); + assert_eq!(e, AuthorityOutcome::Denied("no".into())); + let contain = Fixed(AuthorityDecision::Contain("box".into())); + let e = h + .lane + .authorize_approved(h.intent.clone(), scope("d"), &contain, &g, 1) + .unwrap_err(); + assert_eq!(e, AuthorityOutcome::Contained("box".into())); + assert_eq!(h.calls.load(Ordering::SeqCst), 0); + // Grant untouched by the refusals. + assert!(h + .lane + .authorize_approved(h.intent.clone(), scope("d"), &EffectClassAuthority, &g, 1) + .is_ok()); +} + +#[tokio::test] +async fn allow_does_not_spend_the_grant() { + let h = harness().await; + let g = h.desk.issue(&h.intent, scope("l"), 100); + let allow = Fixed(AuthorityDecision::Allow); + assert!(h + .lane + .authorize_approved(h.intent.clone(), scope("l"), &allow, &g, 1) + .is_ok()); + assert!(h + .lane + .authorize_approved(h.intent.clone(), scope("l"), &EffectClassAuthority, &g, 1) + .is_ok()); +} + +#[tokio::test] +async fn grant_from_another_broker_is_unknown() { + let h = harness().await; + let other = harness().await; + let g = other.desk.issue(&other.intent, scope("z"), 100); + let e = h + .lane + .authorize_approved(h.intent.clone(), scope("z"), &EffectClassAuthority, &g, 1) + .unwrap_err(); + assert_eq!(approval(e), ApprovalError::Unknown); +} + +#[tokio::test] +async fn unapproved_request_is_still_pending() { + let h = harness().await; + let e = h + .lane + .authorize(h.intent.clone(), scope("n"), &EffectClassAuthority) + .unwrap_err(); + assert!(matches!(e, AuthorityOutcome::Pending { .. })); +}