From 5fa1df4398e5ce78113fa7772071ab9abb83352a Mon Sep 17 00:00:00 2001 From: "cycle-five-nyx[bot]" <156843045+cycle-five-nyx[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:07:57 -0500 Subject: [PATCH 1/3] fix(grants): request_grant returns a matching live grant (#418) kharon_request_grant / POST /v1/grants opened a new pending request, and a fresh owner prompt, even when a live grant already covered the same agent, item, observed origin and action. After the live origin is observed, a matching grant with uses left is now returned as state granted with its grant_id: no request is created and no notification is sent. The call is audited as grant_request with result existing_grant. A spent, expired, or mismatched grant still opens a new request. Closes #418 --- crates/kharond/src/api/core.rs | 66 +++- crates/kharond/src/api/grant.rs | 29 +- crates/kharond/src/api/http.rs | 2 +- crates/kharond/src/api/mcp.rs | 9 +- crates/kharond/tests/req_apr_grants.rs | 329 ++++++++++++++++++- crates/kharond/tests/req_goal_001_surface.rs | 4 + docs/api/mcp-tools.json | 2 +- docs/api/openapi.json | 11 +- 8 files changed, 433 insertions(+), 19 deletions(-) diff --git a/crates/kharond/src/api/core.rs b/crates/kharond/src/api/core.rs index ed8ee03..07fa42b 100644 --- a/crates/kharond/src/api/core.rs +++ b/crates/kharond/src/api/core.rs @@ -1896,9 +1896,14 @@ impl Broker { /// `locked`); an unknown item is `not_found` and a target the /// broker cannot observe is `target_not_owned` — both as /// [`GrantRequestBody`] states with no request created, mirroring - /// how fills report refusals in-band. A created request is - /// audited before the reply (REQ-AUD-003). Bounded by the fill - /// deadline from `received`, like fills and context calls. + /// how fills report refusals in-band. After the live origin is + /// observed, a matching live grant for the same agent, item, + /// origin and action, with uses left, is returned as `granted` + /// with its `grant_id`: no request is created and no notification + /// is sent, audited as `grant_request` with result + /// `existing_grant` (#418). A created request is audited before + /// the reply (REQ-AUD-003). Bounded by the fill deadline from + /// `received`, like fills and context calls. pub async fn request_grant( &self, agent: &AgentId, @@ -1984,6 +1989,61 @@ impl Broker { "target_not_owned", ))); }; + // #418: a live grant that already covers this (agent, item, + // observed origin, action) with uses left is returned as-is. + // Claim mismatches still go through create_request so + // REQ-APR-007's origin_mismatch refusal is unchanged. + let claim_ok = super::grant::serialized_origin(&args.expected_origin) + == super::grant::serialized_origin(&observed); + if claim_ok { + let now = self.grant_now(); + let existing = { + let (collections, revision) = { + let mut lock = self.lock.lock().unwrap_or_else(|p| p.into_inner()); + match lock.require_unlocked() { + Ok(session) => match session.vault().get(&args.item_id) { + Ok(item) => ( + item.collection_ids().to_vec(), + item.revision().map(str::to_owned), + ), + Err(_) => { + drop(lock); + self.append(base("not_found"))?; + return Ok(Outcome::GrantRequest(GrantRequestBody::refused( + "not_found", + ))); + } + }, + Err(_) => { + drop(lock); + self.append(base("locked"))?; + return Err(ApiError::LOCKED); + } + } + }; + self.grants + .lock() + .unwrap_or_else(|p| p.into_inner()) + .matching_grant( + agent.as_str(), + &args.item_id, + &collections, + &observed, + args.action, + now, + ) + .filter(|g| g.revision_matches(revision.as_deref())) + .cloned() + }; + if let Some(grant) = existing { + self.append( + base("existing_grant") + .origin(observed) + .grant_id(grant.id.clone()), + )?; + return Ok(Outcome::GrantRequest(GrantRequestBody::existing(&grant))); + } + } let (greq, created) = self .grants .lock() diff --git a/crates/kharond/src/api/grant.rs b/crates/kharond/src/api/grant.rs index 1d772f2..b4e1a11 100644 --- a/crates/kharond/src/api/grant.rs +++ b/crates/kharond/src/api/grant.rs @@ -699,6 +699,10 @@ impl GrantStore { /// which is never deduped into a pending one and never prompts. /// The `bool` is `true` when this call created the request (the /// broker audits creation exactly once). + /// + /// Live grants are not consulted here. The explicit + /// `kharon_request_grant` / `POST /v1/grants` path returns a + /// matching live grant before calling this (#418). pub fn create_request( &mut self, agent_id: &str, @@ -1007,13 +1011,15 @@ pub fn parse_grant(json: &[u8]) -> Result { /// SPEC §4: the `kharon_request_grant` / `POST /v1/grants` body, /// `{grant_request_id, state}`. `grant_request_id` is null when no -/// request was created (`not_found`, `target_not_owned`). +/// request was created (`not_found`, `target_not_owned`, or when a +/// matching live grant is returned as `granted`, #418). #[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] pub struct GrantRequestBody { /// The created (or already pending) request, if any. pub grant_request_id: Option, - /// `pending`, `origin_mismatch`, `not_found` or - /// `target_not_owned`. + /// `pending`, `origin_mismatch`, `not_found`, + /// `target_not_owned`, `timeout`, or `granted` when a matching + /// live grant was returned instead of a new request (#418). pub state: &'static str, /// A fixed refusal detail code, when the state has one — the /// same code the fill path reports for the same refusal @@ -1021,6 +1027,10 @@ pub struct GrantRequestBody { /// scheme pre-refusal, #180 item 3). #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option<&'static str>, + /// The matching live grant returned for a reuse (#418). Absent + /// on a request or a refusal. + #[serde(skip_serializing_if = "Option::is_none")] + pub grant_id: Option, } impl GrantRequestBody { @@ -1030,6 +1040,17 @@ impl GrantRequestBody { grant_request_id: Some(req.id.clone()), state: req.state.as_str(), detail: None, + grant_id: None, + } + } + + /// The body for a matching live grant: no new request (#418). + pub fn existing(grant: &Grant) -> Self { + Self { + grant_request_id: None, + state: "granted", + detail: None, + grant_id: Some(grant.id.clone()), } } @@ -1039,6 +1060,7 @@ impl GrantRequestBody { grant_request_id: None, state, detail: None, + grant_id: None, } } @@ -1049,6 +1071,7 @@ impl GrantRequestBody { grant_request_id: None, state, detail: Some(detail), + grant_id: None, } } } diff --git a/crates/kharond/src/api/http.rs b/crates/kharond/src/api/http.rs index 0db61d0..6915570 100644 --- a/crates/kharond/src/api/http.rs +++ b/crates/kharond/src/api/http.rs @@ -15,7 +15,7 @@ //! | `POST /v1/fill_totp` | bearer | `FillTotpRequest` → `FillResult` | //! | `POST /v1/open` | bearer | `{item_id}` → `{target_id, origin}` (REQ-API-012) | //! | `POST /v1/context` | bearer | empty or `{}` → `ContextResult` (the agent's `browserContextId`, #65) | -//! | `POST /v1/grants` | bearer | `GrantRequest` → `GrantRequestBody` (`{grant_request_id, state}`, #20) | +//! | `POST /v1/grants` | bearer | `GrantRequest` → `GrantRequestBody` (`{grant_request_id, state, grant_id?}`, #20 / #418) | //! | `GET /v1/openapi.json` | none | the OpenAPI document | //! | `POST /mcp` | bearer | MCP over Streamable HTTP ([`super::mcp`]) | //! diff --git a/crates/kharond/src/api/mcp.rs b/crates/kharond/src/api/mcp.rs index c5d2983..8fb06b8 100644 --- a/crates/kharond/src/api/mcp.rs +++ b/crates/kharond/src/api/mcp.rs @@ -355,7 +355,10 @@ impl Tool { "Ask the owner for a grant to fill one item (action fill, or totp) in the \ tab cdp_target_id in your own browser context. The broker reads the tab's \ live origin itself: if it differs from expected_origin the request is \ - origin_mismatch and no prompt is shown. Otherwise the request is pending \ + origin_mismatch and no prompt is shown. If a live grant already covers \ + the same item, origin and action and still has uses left, the call \ + returns that grant (state granted, with its grant_id), creates no \ + request and sends no notification. Otherwise the request is pending \ until the owner approves or it times out after 120 s (denied). Calling \ again while one is pending returns the same request. A fill without a \ matching grant creates the same request implicitly. Requires unlock. \ @@ -411,7 +414,9 @@ impl Tool { "readOnlyHint": reads, "destructiveHint": false, // `kharon_request_grant` is idempotent too: the broker - // dedupes a pending request per (agent, item, action). + // dedupes a pending request per (agent, item, action), + // and returns a matching live grant instead of prompting + // again (#418). "idempotentHint": reads || matches!(self, Self::Context | Self::RequestGrant), "openWorldHint": !reads, }) diff --git a/crates/kharond/tests/req_apr_grants.rs b/crates/kharond/tests/req_apr_grants.rs index 1a7d565..1e95bf7 100644 --- a/crates/kharond/tests/req_apr_grants.rs +++ b/crates/kharond/tests/req_apr_grants.rs @@ -25,25 +25,34 @@ //! again after unlock. (The AC's home issue is #23; the test //! lands here per the PR #109 review.) //! -//! The transports carry the same bodies: the last test runs +//! The transports carry the same bodies: one test runs //! `kharon_request_grant` over HTTP and MCP against one broker and //! gets the identical `{grant_request_id, state}` — including the //! same id, because a pending request is deduped. +//! +//! - **#418**: `kharon_request_grant` returns a matching live grant +//! (`state` `granted`, with its `grant_id`) instead of prompting +//! again; a spent, expired, or mismatched grant still opens a new +//! request. mod api_support; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use api_support::{ - CHEAP_FLOOR, FakeAnswer, FakeFill, Harness, ITEM_A, RecordingAudit, TestSession, cheap_argon, - mcp_call, post_json, serve_http, + CHEAP_FLOOR, FakeAnswer, FakeFill, Harness, ITEM_A, ITEM_B, RecordingAudit, TestSession, + cheap_argon, fixture_collection_id, mcp_call, post_json, serve_http, +}; +use kharond::api::grant::{ + ApprovalPrompt, Channel, GrantAction, GrantError, GrantScope, GrantTerms, RequestState, }; -use kharond::api::grant::{Channel, GrantAction, GrantError, GrantTerms, RequestState}; +use kharond::api::notify::ApprovalNotifier; use kharond::api::token::{TokenStore, generate_with}; use kharond::api::{Broker, GrantRequestArgs, Outcome, VaultView, parse_fill, parse_grant}; use kharond::audit::Entry; +use kharond::config::GrantKind; use kharond::lock::{Clock, LockController, LockPolicy, LockReason, ManualClock, StaticHardening}; use kharond::origin::OriginConfig; use kharond::sync::{SecretField, SyncError, Vault}; @@ -95,9 +104,23 @@ impl Rig { Self::with_origin_cfg(live_url, OriginConfig::default()) } + /// [`Self::new`] with an approval notifier, so tests can assert + /// that a reuse does not prompt (#418). + fn with_notifier(live_url: &'static str, notifier: Arc) -> Self { + Self::build(live_url, OriginConfig::default(), Some(notifier)) + } + /// [`Self::new`] with a non-default origin config (#180's /// `allow_http` cases). fn with_origin_cfg(live_url: &'static str, origin_cfg: OriginConfig) -> Self { + Self::build(live_url, origin_cfg, None) + } + + fn build( + live_url: &'static str, + origin_cfg: OriginConfig, + notifier: Option>, + ) -> Self { let (alpha, ha) = generate_with(&cheap_argon(), "alpha"); let (_beta, hb) = generate_with(&cheap_argon(), "beta"); let tokens = TokenStore::with_floor( @@ -122,9 +145,12 @@ impl Rig { let audit = RecordingAudit::default(); let fake = FakeFill::new(FakeAnswer::Filled).with_live_url(live_url); let grant_clock: Arc = clock.clone(); - let broker = Broker::new(tokens, lock, Box::new(audit.clone()), origin_cfg) + let mut broker = Broker::new(tokens, lock, Box::new(audit.clone()), origin_cfg) .with_grant_clock(grant_clock) .with_fill_backend(Box::new(fake.clone())); + if let Some(notifier) = notifier { + broker = broker.with_approval_notifier(notifier); + } Self { broker: Arc::new(broker), clock, @@ -184,6 +210,42 @@ impl Rig { fn audit_entries(&self) -> Vec { self.audit.entries.lock().unwrap().clone() } + + async fn request_grant( + &self, + item_id: &str, + origin: &str, + action: &str, + ) -> kharond::api::grant::GrantRequestBody { + let args = parse_grant( + json!({ + "item_id": item_id, + "target": {"cdp_target_id": "tab-1", "expected_origin": origin}, + "action": action, + }) + .to_string() + .as_bytes(), + ) + .unwrap(); + match self + .broker + .request_grant(&self.agent(), args, Instant::now()) + .await + .unwrap() + { + Outcome::GrantRequest(body) => body, + other => panic!("expected a grant request outcome, got {other:?}"), + } + } + + fn pending_count(&self) -> usize { + self.broker + .grant_store() + .lock() + .unwrap() + .pending_requests() + .len() + } } #[tokio::test] @@ -806,6 +868,261 @@ async fn req_apr_request_grant_transports_agree() { assert!(tools.iter().any(|t| t["name"] == "kharon_request_grant")); } +// ------------------------------------------------- #418: reuse a live grant + +#[derive(Default)] +struct RecordingNotifier { + calls: Mutex>, +} + +impl ApprovalNotifier for RecordingNotifier { + fn notify_grant_request(&self, prompt: &ApprovalPrompt, _approve: &str, _deny: &str) { + self.calls.lock().unwrap().push(prompt.clone()); + } +} + +/// A 1-hour per-origin grant for `item` at `origin` (SPEC §5 default). +fn per_origin_terms(item: &str) -> GrantTerms { + GrantTerms { + scope: GrantScope::Item(item.to_owned()), + kind: GrantKind::PerOrigin, + ttl: None, + max_uses: None, + } +} + +fn approve(rig: &Rig, request_id: &str, terms: GrantTerms) -> String { + rig.broker + .approve_grant_request(request_id, &terms, Channel::Cli) + .unwrap() + .id +} + +fn last_grant_request_entry(rig: &Rig) -> Entry { + rig.audit_entries() + .into_iter() + .rev() + .find(|e| e.event == kharond::audit::Event::GrantRequest) + .expect("a grant_request entry") +} + +/// #418: approve a 1 h grant, then `request_grant` again for the same +/// (agent, item, origin, action): no new request, no notification, +/// the reply carries the existing grant id, and the audit is +/// `existing_grant`. +#[tokio::test] +async fn req_apr_418_live_grant_is_returned_without_a_new_request() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let first = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + assert_eq!(first.state, "pending"); + assert_eq!(notifier.calls.lock().unwrap().len(), 1); + let grant_id = approve( + &rig, + first.grant_request_id.as_deref().unwrap(), + per_origin_terms(ITEM_A), + ); + + let again = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + assert_eq!(again.state, "granted", "{again:?}"); + assert_eq!(again.grant_id.as_deref(), Some(grant_id.as_str())); + assert!(again.grant_request_id.is_none(), "{again:?}"); + assert_eq!(rig.pending_count(), 0); + assert_eq!( + notifier.calls.lock().unwrap().len(), + 1, + "reusing a live grant must not notify" + ); + let entry = last_grant_request_entry(&rig); + assert_eq!(entry.result.as_deref(), Some("existing_grant")); + assert_eq!(entry.grant_id.as_deref(), Some(grant_id.as_str())); + assert_eq!(entry.origin.as_deref(), Some("https://login.example.com")); + assert_eq!(entry.item_id.as_deref(), Some(ITEM_A)); + assert!(entry.request_id.is_none(), "{entry:?}"); +} + +/// #418: a once-grant already spent still yields a new request. +#[tokio::test] +async fn req_apr_418_spent_once_grant_opens_a_new_request() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let first = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + approve( + &rig, + first.grant_request_id.as_deref().unwrap(), + GrantTerms::once_item(ITEM_A), + ); + let filled = rig.fill_password().await; + assert_eq!(filled["status"], "filled", "{filled}"); + assert_eq!(notifier.calls.lock().unwrap().len(), 1); + + let again = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + assert_eq!(again.state, "pending", "{again:?}"); + assert!( + again + .grant_request_id + .as_deref() + .is_some_and(|id| id != first.grant_request_id.as_deref().unwrap()), + "{again:?}" + ); + assert!(again.grant_id.is_none()); + assert_eq!(rig.pending_count(), 1); + assert_eq!(notifier.calls.lock().unwrap().len(), 2); + assert_eq!( + last_grant_request_entry(&rig).result.as_deref(), + Some("pending") + ); +} + +/// #418: an expired grant still yields a new request. +#[tokio::test] +async fn req_apr_418_expired_grant_opens_a_new_request() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let first = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + approve( + &rig, + first.grant_request_id.as_deref().unwrap(), + GrantTerms { + ttl: Some(Duration::from_secs(60)), + ..per_origin_terms(ITEM_A) + }, + ); + // Past the grant TTL, but inside the lock idle window, so the + // second request is refused for expiry rather than lock. + rig.clock.advance(Duration::from_secs(61)); + let again = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + assert_eq!(again.state, "pending", "{again:?}"); + assert!(again.grant_request_id.is_some()); + assert!(again.grant_id.is_none()); + assert_eq!(rig.pending_count(), 1); + assert_eq!(notifier.calls.lock().unwrap().len(), 2); +} + +/// #418: a grant for a different item does not cover this request. +#[tokio::test] +async fn req_apr_418_mismatched_item_opens_a_new_request() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let first = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + approve( + &rig, + first.grant_request_id.as_deref().unwrap(), + per_origin_terms(ITEM_A), + ); + let again = rig + .request_grant(ITEM_B, "https://login.example.com", "fill") + .await; + assert_eq!(again.state, "pending", "{again:?}"); + assert_eq!(rig.pending_count(), 1); + assert_eq!(notifier.calls.lock().unwrap().len(), 2); +} + +/// #418: a fill grant does not cover a totp request for the same item. +#[tokio::test] +async fn req_apr_418_mismatched_action_opens_a_new_request() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let first = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + approve( + &rig, + first.grant_request_id.as_deref().unwrap(), + per_origin_terms(ITEM_A), + ); + let again = rig + .request_grant(ITEM_A, "https://login.example.com", "totp") + .await; + assert_eq!(again.state, "pending", "{again:?}"); + assert_eq!(rig.pending_count(), 1); + assert_eq!(notifier.calls.lock().unwrap().len(), 2); +} + +/// #418: a grant at a different origin does not cover this request. +/// The claim agrees with the observed origin so this is a new pending +/// request, not an `origin_mismatch` refusal. +#[tokio::test] +async fn req_apr_418_mismatched_origin_opens_a_new_request() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://app.example.com/login", notifier.clone()); + { + let mut store = rig.broker.grant_store().lock().unwrap(); + store + .issue( + "alpha", + ITEM_A, + GrantAction::Fill, + "https://login.example.com", + &per_origin_terms(ITEM_A), + Channel::Cli, + None, + rig.clock.now(), + ) + .unwrap(); + } + let again = rig + .request_grant(ITEM_A, "https://app.example.com", "fill") + .await; + assert_eq!(again.state, "pending", "{again:?}"); + assert_eq!(rig.pending_count(), 1); + assert_eq!(notifier.calls.lock().unwrap().len(), 1); +} + +/// A collection-scoped live grant covers a member item the same way +/// `resolve_fill` would, so `request_grant` reuses it. +#[tokio::test] +async fn req_apr_418_collection_scoped_grant_is_reused_for_a_member() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let grant_id = { + let mut store = rig.broker.grant_store().lock().unwrap(); + store + .issue( + "alpha", + ITEM_A, + GrantAction::Fill, + "https://login.example.com", + &GrantTerms { + scope: GrantScope::Collection(fixture_collection_id()), + kind: GrantKind::PerOrigin, + ttl: None, + max_uses: None, + }, + Channel::Cli, + None, + rig.clock.now(), + ) + .unwrap() + .id + }; + let again = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + assert_eq!(again.state, "granted", "{again:?}"); + assert_eq!(again.grant_id.as_deref(), Some(grant_id.as_str())); + assert_eq!(rig.pending_count(), 0); + assert!(notifier.calls.lock().unwrap().is_empty()); + assert_eq!( + last_grant_request_entry(&rig).result.as_deref(), + Some("existing_grant") + ); +} + // ------------------------------------------------- #240: presented grant /// A password fill on the fixture origin that presents `grant_id`. diff --git a/crates/kharond/tests/req_goal_001_surface.rs b/crates/kharond/tests/req_goal_001_surface.rs index 816ec2b..3d1f5f5 100644 --- a/crates/kharond/tests/req_goal_001_surface.rs +++ b/crates/kharond/tests/req_goal_001_surface.rs @@ -98,6 +98,10 @@ const REVIEWED_STRINGS: &[(&str, &str)] = &[ ), ("GrantRequestBody.state", "fixed request-state literal"), ("GrantRequestBody.detail", "fixed detail-code literal"), + ( + "GrantRequestBody.grant_id", + "broker-assigned grant id returned on reuse (#418)", + ), ("ContextResult.status", "fixed literal"), ( "ContextResult.browser_context_id", diff --git a/docs/api/mcp-tools.json b/docs/api/mcp-tools.json index f184f9f..a898194 100644 --- a/docs/api/mcp-tools.json +++ b/docs/api/mcp-tools.json @@ -399,7 +399,7 @@ "openWorldHint": true, "readOnlyHint": false }, - "description": "Ask the owner for a grant to fill one item (action fill, or totp) in the tab cdp_target_id in your own browser context. The broker reads the tab's live origin itself: if it differs from expected_origin the request is origin_mismatch and no prompt is shown. Otherwise the request is pending until the owner approves or it times out after 120 s (denied). Calling again while one is pending returns the same request. A fill without a matching grant creates the same request implicitly. Requires unlock. Audited. Same body as POST /v1/grants.", + "description": "Ask the owner for a grant to fill one item (action fill, or totp) in the tab cdp_target_id in your own browser context. The broker reads the tab's live origin itself: if it differs from expected_origin the request is origin_mismatch and no prompt is shown. If a live grant already covers the same item, origin and action and still has uses left, the call returns that grant (state granted, with its grant_id), creates no request and sends no notification. Otherwise the request is pending until the owner approves or it times out after 120 s (denied). Calling again while one is pending returns the same request. A fill without a matching grant creates the same request implicitly. Requires unlock. Audited. Same body as POST /v1/grants.", "inputSchema": { "$defs": { "GrantAction": { diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 6a707a7..57b5d11 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -293,7 +293,7 @@ "/v1/grants": { "post": { "operationId": "kharon_request_grant", - "summary": "Request a grant for one item and action (SPEC §5; REQ-APR-001/002/003/007, issue #20): the broker reads the target tab's live origin itself, and a claim that disagrees is origin_mismatch with no prompt shown. Otherwise the request is pending until the owner approves or it times out after 120 s (denied). Calling again while one is pending returns the same request. A fill without a matching grant creates the same request implicitly. Requires unlock. Audited before the reply (REQ-AUD-003).", + "summary": "Request a grant for one item and action (SPEC §5; REQ-APR-001/002/003/007, issue #20 / #418): the broker reads the target tab's live origin itself, and a claim that disagrees is origin_mismatch with no prompt shown. If a live grant already covers the same item, origin and action and still has uses left, the call returns that grant (state granted, with its grant_id), creates no request and sends no notification. Otherwise the request is pending until the owner approves or it times out after 120 s (denied). Calling again while one is pending returns the same request. A fill without a matching grant creates the same request implicitly. Requires unlock. Audited before the reply (REQ-AUD-003).", "requestBody": { "required": true, "content": { @@ -921,7 +921,7 @@ "grant_request_id", "state" ], - "description": "SPEC §4 {grant_request_id, state}. grant_request_id is null when no request was created (not_found, target_not_owned, timeout).", + "description": "SPEC §4 {grant_request_id, state}. grant_request_id is null when no request was created (not_found, target_not_owned, timeout, or granted when a matching live grant is returned, #418).", "properties": { "detail": { "type": "string", @@ -930,6 +930,10 @@ "insecure_context" ] }, + "grant_id": { + "type": "string", + "description": "Broker-assigned grant id (g_…) returned when state is granted (#418)." + }, "grant_request_id": { "type": [ "string", @@ -944,7 +948,8 @@ "origin_mismatch", "not_found", "target_not_owned", - "timeout" + "timeout", + "granted" ] } } From 8b29c05bbccd99fb6e3dbe0454d7586f75e5b0d6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 14:38:01 +0000 Subject: [PATCH 2/3] fix(grants): reuse the live grant a fill would admit (#418) request_grant applied the revision pin only to the first dimension match, so a stale pin ahead of a current one hid the grant resolve_fill would use. Search once with both predicates via GrantStore::admitting_grant, shared with resolve_fill and the fill backing check. The lookup does not spend a use. Co-authored-by: Cycle Five --- crates/kharond/src/api/core.rs | 70 ++++++++------ crates/kharond/src/api/grant.rs | 125 ++++++++++++++++++++++++- crates/kharond/tests/req_apr_grants.rs | 91 +++++++++++++++++- 3 files changed, 255 insertions(+), 31 deletions(-) diff --git a/crates/kharond/src/api/core.rs b/crates/kharond/src/api/core.rs index 07fa42b..2f1b3dd 100644 --- a/crates/kharond/src/api/core.rs +++ b/crates/kharond/src/api/core.rs @@ -1898,10 +1898,12 @@ impl Broker { /// [`GrantRequestBody`] states with no request created, mirroring /// how fills report refusals in-band. After the live origin is /// observed, a matching live grant for the same agent, item, - /// origin and action, with uses left, is returned as `granted` - /// with its `grant_id`: no request is created and no notification - /// is sent, audited as `grant_request` with result - /// `existing_grant` (#418). A created request is audited before + /// origin and action, with uses left and a revision pin the item + /// admits (REQ-REV-004), is returned as `granted` with its + /// `grant_id`: no request is created and no notification is sent, + /// audited as `grant_request` with result `existing_grant` (#418). + /// The search is the one a fill admits with, so an older pin does + /// not hide a later grant. A created request is audited before /// the reply (REQ-AUD-003). Bounded by the fill deadline from /// `received`, like fills and context calls. pub async fn request_grant( @@ -1990,7 +1992,11 @@ impl Broker { ))); }; // #418: a live grant that already covers this (agent, item, - // observed origin, action) with uses left is returned as-is. + // observed origin, action) with uses left, and whose revision + // pin admits the item, is returned as-is. The search applies + // both predicates together, the same way `resolve_fill` does: + // a stale pin earlier in the store must not hide a later grant + // that pins the current revision, and the lookup spends no use. // Claim mismatches still go through create_request so // REQ-APR-007's origin_mismatch refusal is unchanged. let claim_ok = super::grant::serialized_origin(&args.expected_origin) @@ -2024,15 +2030,15 @@ impl Broker { self.grants .lock() .unwrap_or_else(|p| p.into_inner()) - .matching_grant( + .admitting_grant( agent.as_str(), &args.item_id, &collections, &observed, args.action, now, + revision.as_deref(), ) - .filter(|g| g.revision_matches(revision.as_deref())) .cloned() }; if let Some(grant) = existing { @@ -3205,22 +3211,30 @@ impl Broker { FillOperation::FillTotp => GrantAction::Totp, }; let admits = |g: &Grant| { - g.matches( + g.admits( agent.as_str(), &req.item_id, &collections, &req.expected_origin, action, now, - ) && g.revision_matches(revision.as_deref()) + revision.as_deref(), + ) }; let store = self.grants.lock().unwrap_or_else(|p| p.into_inner()); let chosen = match &req.grant_id { Some(gid) => store.grant(gid).filter(|g| admits(g)).cloned(), None => store - .grants_for(agent.as_str(), now) - .into_iter() - .find(|g| admits(g)), + .admitting_grant( + agent.as_str(), + &req.item_id, + &collections, + &req.expected_origin, + action, + now, + revision.as_deref(), + ) + .cloned(), }; match chosen { Some(g) if g.kind == crate::config::GrantKind::Once => FillBacking::OnceGrant, @@ -3306,14 +3320,15 @@ impl Broker { Some(gid) => { let rev = item.revision(); let ok = store.grant(gid).is_some_and(|g| { - g.matches( + g.admits( agent.as_str(), &req.item_id, item.collection_ids(), &req.expected_origin, action, now, - ) && g.revision_matches(rev) + rev, + ) }) && store.consume(gid, now); if !ok { return refuse(FillStatus::GrantDenied); @@ -3324,19 +3339,16 @@ impl Broker { None => { let rev = item.revision(); let found = store - .grants_for(agent.as_str(), now) - .into_iter() - .find(|g| { - g.matches( - agent.as_str(), - &req.item_id, - item.collection_ids(), - &req.expected_origin, - action, - now, - ) && g.revision_matches(rev) - }) - .map(|g| g.id); + .admitting_grant( + agent.as_str(), + &req.item_id, + item.collection_ids(), + &req.expected_origin, + action, + now, + rev, + ) + .map(|g| g.id.clone()); match found { Some(gid) => { let consumed = store.consume(&gid, now); @@ -3347,7 +3359,9 @@ impl Broker { None => { // A live grant that fails only on revision // is denied (re-approval), not a fresh - // request (REQ-REV-004). + // request (REQ-REV-004). `admitting_grant` + // already found nothing, so the first + // dimension match, if any, fails the pin. let revision_miss = store .matching_grant( agent.as_str(), diff --git a/crates/kharond/src/api/grant.rs b/crates/kharond/src/api/grant.rs index b4e1a11..b91c308 100644 --- a/crates/kharond/src/api/grant.rs +++ b/crates/kharond/src/api/grant.rs @@ -302,6 +302,24 @@ impl Grant { } } + /// What a fill admits and what `request_grant` reuses: every + /// REQ-APR-002 dimension ([`Self::matches`]) and the REQ-REV-004 + /// revision pin ([`Self::revision_matches`]). Does not consume a use. + #[allow(clippy::too_many_arguments)] + pub fn admits( + &self, + agent_id: &str, + item_id: &str, + item_collections: &[String], + origin: &str, + action: GrantAction, + now: Duration, + item_revision: Option<&str>, + ) -> bool { + self.matches(agent_id, item_id, item_collections, origin, action, now) + && self.revision_matches(item_revision) + } + /// The status view (SPEC §4 `Grant`). pub fn view(&self, now: Duration) -> GrantView { let (item_id, collection_id) = match &self.scope { @@ -543,8 +561,15 @@ impl GrantStore { self.allow_standing = allow; } - /// The live grant matching every dimension of a fill - /// (REQ-APR-002), if one exists. + /// The first live grant matching every REQ-APR-002 dimension, if + /// one exists. Ignores the revision pin. A caller that admits a + /// fill or reuses a grant wants [`Self::admitting_grant`], which + /// applies the pin in the same search: stopping here and filtering + /// the one hit drops a later grant that pins the current revision + /// when an older pin sits ahead of it (#418). This method is the + /// "matches, but maybe the wrong revision" probe the fill path + /// uses after [`Self::admitting_grant`] has already failed + /// (REQ-REV-004 re-approval versus no grant at all). pub fn matching_grant( &self, agent_id: &str, @@ -559,6 +584,35 @@ impl GrantStore { .find(|g| g.matches(agent_id, item_id, item_collections, origin, action, now)) } + /// The first grant [`Grant::admits`] would let through, in store + /// order. A stale revision pin earlier in the store does not hide + /// a later grant that pins the current revision. Does not consume + /// a use. `resolve_fill` and `request_grant` both use this, so a + /// reuse is exactly the grant a fill would admit (#418). + #[allow(clippy::too_many_arguments)] + pub fn admitting_grant( + &self, + agent_id: &str, + item_id: &str, + item_collections: &[String], + origin: &str, + action: GrantAction, + now: Duration, + item_revision: Option<&str>, + ) -> Option<&Grant> { + self.grants.iter().find(|g| { + g.admits( + agent_id, + item_id, + item_collections, + origin, + action, + now, + item_revision, + ) + }) + } + /// A grant by id. pub fn grant(&self, grant_id: &str) -> Option<&Grant> { self.grants.iter().find(|g| g.id == grant_id) @@ -1248,6 +1302,73 @@ mod tests { ); } + #[test] + fn admitting_grant_skips_a_stale_revision_ahead_of_a_current_one() { + let mut s = store(); + let terms = GrantTerms { + scope: GrantScope::Item("item-1".into()), + kind: GrantKind::PerOrigin, + ttl: None, + max_uses: None, + }; + let stale = s + .issue( + "alpha", + "item-1", + GrantAction::Fill, + "https://login.example.com", + &terms, + Channel::Cli, + None, + NOW, + ) + .unwrap(); + s.pin_revision(&stale.id, Some("2026-11-01T00:00:00Z".into())); + let current = s + .issue( + "alpha", + "item-1", + GrantAction::Fill, + "https://login.example.com", + &terms, + Channel::Cli, + None, + NOW, + ) + .unwrap(); + s.pin_revision(¤t.id, Some("2026-11-05T00:00:00Z".into())); + let current_rev = Some("2026-11-05T00:00:00Z"); + assert_eq!( + s.admitting_grant( + "alpha", + "item-1", + &[], + "https://login.example.com", + GrantAction::Fill, + NOW, + current_rev, + ) + .map(|g| g.id.as_str()), + Some(current.id.as_str()) + ); + // The dimension-only probe still stops on the stale pin. A + // caller that filters that one hit would miss `current`. + assert_eq!( + s.matching_grant( + "alpha", + "item-1", + &[], + "https://login.example.com", + GrantAction::Fill, + NOW, + ) + .map(|g| g.id.as_str()), + Some(stale.id.as_str()) + ); + assert_eq!(s.grant(&stale.id).unwrap().uses, 0); + assert_eq!(s.grant(¤t.id).unwrap().uses, 0); + } + #[test] fn req_apr_008_refund_gives_back_one_spent_use() { let mut s = store(); diff --git a/crates/kharond/tests/req_apr_grants.rs b/crates/kharond/tests/req_apr_grants.rs index 1e95bf7..1052e91 100644 --- a/crates/kharond/tests/req_apr_grants.rs +++ b/crates/kharond/tests/req_apr_grants.rs @@ -33,7 +33,8 @@ //! - **#418**: `kharon_request_grant` returns a matching live grant //! (`state` `granted`, with its `grant_id`) instead of prompting //! again; a spent, expired, or mismatched grant still opens a new -//! request. +//! request. A stale revision pin earlier in the store does not hide +//! a later grant that pins the current revision. mod api_support; @@ -1123,6 +1124,94 @@ async fn req_apr_418_collection_scoped_grant_is_reused_for_a_member() { ); } +/// The fixture item's current `revisionDate`, if it has one. +fn item_a_revision(rig: &Rig) -> Option { + let mut lock = rig.broker.lock_controller().lock().unwrap(); + lock.require_unlocked() + .expect("fixture session is unlocked") + .vault() + .get(ITEM_A) + .expect("item A") + .revision() + .map(str::to_owned) +} + +/// Issue a live per-origin fill grant for alpha on ITEM_A and pin +/// `revision`. Store order is issuance order. +fn issue_pinned(rig: &Rig, revision: Option) -> String { + let mut store = rig.broker.grant_store().lock().unwrap(); + let id = store + .issue( + "alpha", + ITEM_A, + GrantAction::Fill, + "https://login.example.com", + &per_origin_terms(ITEM_A), + Channel::Cli, + None, + rig.clock.now(), + ) + .unwrap() + .id; + store.pin_revision(&id, revision); + id +} + +/// #418 review: a live grant pinned to a previous revision is ordered +/// ahead of a live grant pinned to the current revision (the usual +/// REQ-REV-004 path after an item edit, before the stale pin is +/// dropped). `request_grant` must return the second grant — the one +/// `resolve_fill` would admit — as `granted`, with an `existing_grant` +/// audit and no new pending request. The lookup must not spend a use. +#[tokio::test] +async fn req_apr_418_stale_revision_ahead_of_current_returns_the_current_grant() { + let notifier = Arc::new(RecordingNotifier::default()); + let rig = Rig::with_notifier("https://login.example.com/signin", notifier.clone()); + let current = item_a_revision(&rig); + let stale_pin = "1999-01-01T00:00:00.000000Z".to_owned(); + assert_ne!( + current.as_deref(), + Some(stale_pin.as_str()), + "the stale pin must not be the item's current revision" + ); + + let stale_id = issue_pinned(&rig, Some(stale_pin)); + let current_id = issue_pinned(&rig, current.clone()); + { + let store = rig.broker.grant_store().lock().unwrap(); + let live = store.grants_for("alpha", rig.clock.now()); + assert_eq!(live.len(), 2, "both grants are live"); + assert_eq!(live[0].id, stale_id, "the stale pin is first"); + assert_eq!(live[1].id, current_id); + assert!(!live[0].revision_matches(current.as_deref())); + assert!(live[1].revision_matches(current.as_deref())); + assert_eq!(live[0].uses, 0); + assert_eq!(live[1].uses, 0); + } + + let again = rig + .request_grant(ITEM_A, "https://login.example.com", "fill") + .await; + assert_eq!(again.state, "granted", "{again:?}"); + assert_eq!(again.grant_id.as_deref(), Some(current_id.as_str())); + assert!(again.grant_request_id.is_none(), "{again:?}"); + assert_eq!(rig.pending_count(), 0); + assert!( + notifier.calls.lock().unwrap().is_empty(), + "reusing a live grant must not notify" + ); + let entry = last_grant_request_entry(&rig); + assert_eq!(entry.result.as_deref(), Some("existing_grant")); + assert_eq!(entry.grant_id.as_deref(), Some(current_id.as_str())); + assert_eq!(entry.origin.as_deref(), Some("https://login.example.com")); + assert!(entry.request_id.is_none(), "{entry:?}"); + { + let store = rig.broker.grant_store().lock().unwrap(); + assert_eq!(store.grant(&stale_id).unwrap().uses, 0); + assert_eq!(store.grant(¤t_id).unwrap().uses, 0); + } +} + // ------------------------------------------------- #240: presented grant /// A password fill on the fixture origin that presents `grant_id`. From e4dc40aeef0c4bdb72a32b89efa0f0ec3dd6dadc Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 30 Nov 2026 14:38:01 +0000 Subject: [PATCH 3/3] docs: a granted response means fill now with this grant_id A granted kharon_request_grant body is not RequestState's approved: no request exists, and the agent should fill with the returned grant_id. Co-authored-by: Cycle Five --- docs/first-run.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/first-run.md b/docs/first-run.md index 60ad010..4a7bf15 100644 --- a/docs/first-run.md +++ b/docs/first-run.md @@ -445,10 +445,10 @@ typed, never the values. (`kharon_request_grant`), and waits. **The agent asks once.** The request stays pending for 120 seconds. It must not call `kharon_request_grant` again to see whether it was - approved: that never reports approval, and once the owner has - approved, the next call opens a new request and a new prompt. - Watch `kharon_status` instead: an approved grant shows up in its - `grants` list. + approved: that never reports approval. Watch `kharon_status` instead: + an approved grant shows up in its `grants` list. A `granted` response + means fill now with this `grant_id` (it is distinct from + RequestState's `approved`; no request exists). 3. Approve the request: in the owner UI, or from the ntfy notification. The owner chooses the kind. **Approve once** is a single use that lasts 120 seconds. **Approve for 1 h** is reusable