Skip to main content

rusty_agent_runtime/
broker.rs

1//! The credential/connection broker contracts (R0.11 Extension Plane,
2//! wave 3): the connection entity, the sealed-storage shape, the handle
3//! lifecycle, and the seams that keep credential bytes out of tool code.
4//!
5//! The design doc is `docs/extension-plane-design.md` ("The
6//! credential/connection broker"). Its governing claim: **no tool ever
7//! holds a raw credential — credentials live in one broker, and tools
8//! receive short-lived, opaque capability handles, non-serializable and
9//! scope-checked at use.** This module is the pure-contract half both
10//! sides agree on (the `capsule.rs` / `registry.rs` posture); the store
11//! backends, the envelope cryptography, the master key, and the HTTP
12//! surface live in `rusty-agent-server`.
13//!
14//! - [`ConnectionRecord`] — the one entity: stable id, provider kind, the
15//!   per-user subject (absent for service-level connections), the consent
16//!   scope set (the ceiling everything downstream may only narrow — the
17//!   `CapsuleOverlay` stance applied to credentials), status, and health.
18//! - [`TokenMaterial`] — the plaintext secret. It exists in this contract
19//!   for exactly one reason: to be *sealed*. The store persists
20//!   [`StoredConnection`] — the record plus a [`SealedCredential`] —
21//!   and plaintext enters the store abstraction on neither backend, ever
22//!   (the design's named deviation: ciphertext may enter the abstraction
23//!   because connections are numerous, refreshed, and queried by id; the
24//!   R0.9 principle survives — a store leak must not leak credentials,
25//!   and ciphertext without the host-local master key is not a
26//!   credential).
27//! - [`CredentialHandle`] — what a tool receives: an opaque token bound
28//!   to the connection, a *narrowed* scope set, the tenant, the run, and
29//!   a short TTL. Redacted in `Debug`, no `Serialize` impl, carrying no
30//!   bytes — the R0.9 capsule secret handle generalized from guest
31//!   linear memory to all tool code. Validity (expiry, scope binding) is
32//!   self-contained in the signed claims; only the connection liveness
33//!   check hits the store at resolution, which is what makes revocation
34//!   effective at the *next* tool call rather than the next deploy.
35//! - [`BrokerDenial`] — the typed refusal: revoked connection (naming the
36//!   revoked grant), expired handle, scope beyond the narrowed set,
37//!   `needs_reauth`, unknown handle or connection, and
38//!   broker-unavailable. Every failure mode fails closed, and every
39//!   denial is attributable to a declaration — never a stack trace, and
40//!   never the bytes.
41//! - [`CredentialBroker`] — the seam the server implements (the
42//!   `NetworkConnector` boundary, drawn for the same reason: core owns
43//!   the journaled *shape*; the deployment owns key custody and
44//!   persistence). [`CredentialMediator`] + [`MediatedTool`] are the
45//!   `ToolExecutor` integration: a credential-requiring tool wrapped at
46//!   registration is issued a handle at first use and re-issued as the
47//!   TTL turns over; the tool presents the handle to the host-side
48//!   connector, and resolution returns the credential bytes to the
49//!   *connector* — they never enter tool code. Behind `wasm`,
50//!   `BrokeredCapsuleHost` is the capsule half: a manifest's `Secret`
51//!   grants are brokered into issued handle tokens the guest receives in
52//!   its input, the R0.9 "the guest receives opaque tokens" precedent
53//!   extended from names to broker-issued handles.
54//! - [`OAuthProvider`] — the token-endpoint seam (wave 4): the
55//!   authorization-code exchange and the refresh the broker's lifecycle
56//!   drives (at resolution and from the server's sweeper), with
57//!   [`TokenGrant`] / [`OAuthFailure`] as the outcome vocabulary —
58//!   permanent failures flip the connection to `needs_reauth`, journaled
59//!   as [`ConnectionReauthRequired`]. [`ScriptedOAuthProvider`] is the
60//!   lifecycle's stand-in for a live endpoint, so no test needs one.
61//!
62//! Golden-file tests under `tests/golden/` pin every wire shape in this
63//! module; any accidental contract drift fails CI.
64
65use std::collections::{BTreeSet, HashMap};
66use std::sync::{Arc, Mutex};
67
68use async_trait::async_trait;
69use chrono::{DateTime, Utc};
70use serde::{Deserialize, Serialize};
71use serde_json::Value;
72
73use crate::durable::ErrorClass;
74use crate::error::{Result, RustyError};
75use crate::record::Effect;
76use crate::tool::Tool;
77
78fn invalid(message: impl Into<String>) -> RustyError {
79    // Contract validation at a state boundary; the invalid-update class
80    // covers it rather than growing the error taxonomy for one module
81    // (the capsule/memory convention).
82    RustyError::InvalidUpdate(message.into())
83}
84
85/// Lowercase hex encoding (the `record::sha256_hex` output discipline),
86/// kept dependency-free so the token codec and the sealed envelope share
87/// one byte-to-text rule without pulling a hex dependency into core.
88/// Public because the sealed envelope's hex fields are the storage
89/// contract — the server's key-custody layer writes and reads them.
90pub fn hex_encode(bytes: &[u8]) -> String {
91    let mut out = String::with_capacity(bytes.len() * 2);
92    for byte in bytes {
93        use std::fmt::Write as _;
94        let _ = write!(out, "{byte:02x}");
95    }
96    out
97}
98
99/// The inverse of [`hex_encode`]; `None` on odd length or non-hex input.
100pub fn hex_decode(hex: &str) -> Option<Vec<u8>> {
101    if hex.len() % 2 != 0 {
102        return None;
103    }
104    (0..hex.len())
105        .step_by(2)
106        .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok())
107        .collect()
108}
109
110// --------------------------------------------------------------------- //
111// The connection model
112// --------------------------------------------------------------------- //
113
114/// The provider kind of a [`ConnectionRecord`]. Closed enum, additive
115/// evolution — a fifth kind lands as a new variant, never a rewrite of
116/// pinned shapes (the `CandidateKind` rule).
117#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
118#[serde(rename_all = "snake_case")]
119pub enum ConnectionProvider {
120    /// An OAuth 2.0 authorization-code grant: a human consented at the
121    /// provider, and the broker recorded what was granted.
122    Oauth2AuthorizationCode,
123    /// An OAuth 2.0 client-credentials grant (service-to-service).
124    Oauth2ClientCredentials,
125    /// A static API key presented as a bearer or header credential.
126    ApiKey,
127    /// HTTP basic authentication (username:password material).
128    Basic,
129}
130
131/// The lifecycle status of a [`ConnectionRecord`]. Closed enum, additive
132/// evolution.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub enum ConnectionStatus {
136    /// Resolutions may proceed.
137    Active,
138    /// The refresh path failed terminally (an expired refresh token, a
139    /// provider `invalid_grant`): calls fail closed with a typed re-auth
140    /// signal until a new consent act is recorded — never silent retries
141    /// with stale material, because a stale credential retried looks
142    /// exactly like an attack retried.
143    NeedsReauth,
144    /// Revoked. Outstanding handles fail at their next use with a typed,
145    /// journaled denial naming the revoked grant.
146    Revoked,
147}
148
149/// One classified failure on the connection's health record: the last
150/// refresh or resolution-time provider failure, classified under the
151/// R0.6 [`ErrorClass`] taxonomy so the retry policy plane reads it
152/// unchanged.
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
154pub struct ClassifiedFailure {
155    /// The retry-taxonomy class of the failure.
156    pub class: ErrorClass,
157
158    /// Human-facing context (the provider's error, never credential
159    /// material).
160    pub detail: String,
161
162    /// When the failure was observed.
163    pub at: DateTime<Utc>,
164}
165
166/// The health half of a [`ConnectionRecord`]: refresh bookkeeping and
167/// failure classification, metadata by construction — nothing here can
168/// carry credential bytes.
169#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
170pub struct ConnectionHealth {
171    /// When the token material was last refreshed (a recorded consent act
172    /// counts — it replaces the material).
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub last_refresh_at: Option<DateTime<Utc>>,
175
176    /// The most recent classified failure, when one was observed.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub last_failure: Option<ClassifiedFailure>,
179
180    /// Consecutive failures since the last success. Reset by any
181    /// successful refresh or consent.
182    #[serde(default)]
183    pub consecutive_failures: u32,
184}
185
186/// The connection: a named, tenant-scoped record binding a provider
187/// account (and optionally a user subject) to its consent scope set and
188/// lifecycle state. The credential bytes are *not* here — they live in
189/// the [`SealedCredential`] half of [`StoredConnection`], so the record
190/// is safe to journal, list, and serve whole.
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
192pub struct ConnectionRecord {
193    /// The stable id, minted at registration (`conn-{32 hex}`). Stable
194    /// across rotation beneath it: credential rotation changes nothing a
195    /// run pinned, because the pin names this governed relationship, not
196    /// the secret of the moment.
197    pub connection_id: String,
198
199    /// The provider kind.
200    pub provider: ConnectionProvider,
201
202    /// The per-user binding — a user id within the tenant. Absent for
203    /// service-level (shared) connections.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub subject: Option<String>,
206
207    /// The consent scope set, in provider semantics (`repo`,
208    /// `https://…/auth/drive.readonly`): recorded when the human (or the
209    /// service enrollment) consents. This is the ceiling — handle
210    /// issuance may only narrow against it, and there is no code path
211    /// that widens a handle past it.
212    pub scopes: BTreeSet<String>,
213
214    /// The lifecycle status.
215    pub status: ConnectionStatus,
216
217    /// Refresh and failure bookkeeping.
218    #[serde(default)]
219    pub health: ConnectionHealth,
220
221    /// When the connection was registered.
222    pub created_at: DateTime<Utc>,
223
224    /// When the record last changed (consent, refresh, revocation).
225    pub updated_at: DateTime<Utc>,
226}
227
228/// The connection id prefix; the id is the prefix plus 32 lowercase hex
229/// chars (one `uuid` v4 draw of OS entropy, the receipt-key generation
230/// precedent).
231pub const CONNECTION_ID_PREFIX: &str = "conn-";
232
233/// The handle id prefix, same shape.
234pub const HANDLE_ID_PREFIX: &str = "hdl-";
235
236/// Mint a connection id. Ids are minted, never caller-chosen: the caller
237/// naming a connection would make id collisions a confused-deputy vector
238/// across tenants.
239pub fn new_connection_id() -> String {
240    format!("{}{}", CONNECTION_ID_PREFIX, uuid::Uuid::new_v4().simple())
241}
242
243/// Mint a handle id.
244pub fn new_handle_id() -> String {
245    format!("{}{}", HANDLE_ID_PREFIX, uuid::Uuid::new_v4().simple())
246}
247
248/// `true` when `id` is `{prefix}` plus 32 lowercase hex chars.
249fn minted_id_ok(prefix: &str, id: &str) -> bool {
250    let Some(hex) = id.strip_prefix(prefix) else {
251        return false;
252    };
253    hex.len() == 32
254        && hex
255            .chars()
256            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
257}
258
259/// Free-text field validation shared by subjects and scopes: non-empty,
260/// bounded, no control characters, and no `/` (the tenant separator —
261/// the registry's artifact-name rule, applied here for the same reason).
262fn validate_free_text(what: &str, value: &str, max: usize) -> Result<()> {
263    let ok = !value.is_empty()
264        && value.len() <= max
265        && !value.contains('/')
266        && value.chars().all(|c| !c.is_control());
267    if !ok {
268        return Err(invalid(format!(
269            "invalid {what} `{value}` (non-empty, at most {max} chars, no `/` or control characters)"
270        )));
271    }
272    Ok(())
273}
274
275impl ConnectionRecord {
276    /// Contract validation, run at every write boundary (registration,
277    /// consent, load). What passes here is a record the broker can serve
278    /// without further interpretation.
279    pub fn validate(&self) -> Result<()> {
280        if !minted_id_ok(CONNECTION_ID_PREFIX, &self.connection_id) {
281            return Err(invalid(format!(
282                "connection id `{}` is not a minted id (`{CONNECTION_ID_PREFIX}` + 32 lowercase hex)",
283                self.connection_id
284            )));
285        }
286        validate_connection_fields(self.subject.as_deref(), &self.scopes)
287    }
288
289    /// `true` when resolutions may proceed against this record.
290    pub fn is_active(&self) -> bool {
291        self.status == ConnectionStatus::Active
292    }
293}
294
295/// The scopes of `requested` that `ceiling` does not cover, sorted. The
296/// narrowing check reduced to one pure function — a reviewer verifying
297/// "issuance can only narrow against consent" reads this and the two
298/// call sites (issuance, resolution) and nothing else. An empty
299/// `requested` asks for nothing and is always covered.
300pub fn scopes_missing(ceiling: &BTreeSet<String>, requested: &BTreeSet<String>) -> Vec<String> {
301    requested.difference(ceiling).cloned().collect()
302}
303
304/// The caller-supplied-field half of [`ConnectionRecord::validate`]:
305/// subject and scope free-text, without a record. HTTP boundaries run
306/// this to answer `422` for bad input before the broker mints anything;
307/// the record-level validation at the write boundary stays the backstop.
308pub fn validate_connection_fields(subject: Option<&str>, scopes: &BTreeSet<String>) -> Result<()> {
309    if let Some(subject) = subject {
310        validate_free_text("connection subject", subject, 256)?;
311    }
312    for scope in scopes {
313        validate_free_text("connection scope", scope, 512)?;
314    }
315    Ok(())
316}
317
318// --------------------------------------------------------------------- //
319// Token material and the sealed envelope
320// --------------------------------------------------------------------- //
321
322/// The plaintext credential. This type exists to be **sealed**: it is
323/// the input to the server's envelope encryption and the output of
324/// handle resolution, and it must never appear in a store row, a
325/// journal, a manifest, or a log line. `Debug` is redacted by hand
326/// (the receipt signing key's posture); there is intentionally no
327/// `Display`.
328///
329/// `Serialize`/`Deserialize` exist because sealing serializes — the
330/// encrypted form is what the store holds. Any code serializing a
331/// `TokenMaterial` for another purpose is the bug this type's docs warn
332/// against.
333#[derive(Clone, PartialEq, Serialize, Deserialize)]
334pub struct TokenMaterial {
335    /// The access token presented to the provider.
336    pub access_token: String,
337
338    /// The refresh token, where the provider issues one.
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub refresh_token: Option<String>,
341
342    /// The access token's expiry, when the provider declares one.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub expires_at: Option<DateTime<Utc>>,
345
346    /// The client credential of an `oauth2_client_credentials` connection
347    /// (R0.11 wave 4): the long-lived secret the provider exchanges for
348    /// access tokens on every refresh. Sealed like everything else in
349    /// this struct; redacted in `Debug`; absent for every other flow.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub client_secret: Option<String>,
352}
353
354impl std::fmt::Debug for TokenMaterial {
355    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356        f.debug_struct("TokenMaterial")
357            .field("access_token", &"[redacted]")
358            .field(
359                "refresh_token",
360                &self.refresh_token.as_ref().map(|_| "[redacted]"),
361            )
362            .field("expires_at", &self.expires_at)
363            .field(
364                "client_secret",
365                &self.client_secret.as_ref().map(|_| "[redacted]"),
366            )
367            .finish()
368    }
369}
370
371/// The sealed-envelope format version. Version 1 is XChaCha20-Poly1305
372/// with the connection id as associated data; a future algorithm or
373/// key-source change lands as a new version, and old envelopes keep
374/// opening (the additive-evolution rule applied to cryptography).
375pub const SEALED_FORMAT_VERSION: u32 = 1;
376
377/// The sealed form of a connection's token material: everything the
378/// store persists about the secret. Envelope encryption — the material
379/// is encrypted under a per-connection data key (random, minted at
380/// registration), and the data key is wrapped by the deployment master
381/// key — so the store holds ciphertext and the wrapped key only, on
382/// both backends. All binary fields are lowercase hex.
383///
384/// The `key_id` names the master key that wrapped the data key, so
385/// master-key rotation (the design's open question 3: lazy re-wrap,
386/// KMS/HSM as the R1.0 plug point) lands additively — the cryptography
387/// is key-source-agnostic from the start.
388#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
389pub struct SealedCredential {
390    /// The envelope format version ([`SEALED_FORMAT_VERSION`]).
391    pub format_version: u32,
392
393    /// The id of the master key that wrapped the data key.
394    pub key_id: String,
395
396    /// The data key, wrapped by the master key (hex).
397    pub wrapped_data_key: String,
398
399    /// The nonce the data key was wrapped under (hex).
400    pub wrap_nonce: String,
401
402    /// The nonce the token material was sealed under (hex). Fresh per
403    /// seal: a consent act re-sealing the same connection reuses the
404    /// data key but never a nonce.
405    pub nonce: String,
406
407    /// The sealed token material (hex).
408    pub ciphertext: String,
409
410    /// When this envelope was sealed.
411    pub sealed_at: DateTime<Utc>,
412}
413
414/// What both store backends hold for one connection: the servable
415/// record plus the sealed credential. Plaintext on neither backend,
416/// ever — a Postgres dump of this row contains no credential.
417#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
418pub struct StoredConnection {
419    /// The connection record (metadata; safe to serve and journal).
420    pub record: ConnectionRecord,
421
422    /// The sealed token material.
423    pub credential: SealedCredential,
424}
425
426// --------------------------------------------------------------------- //
427// Handles
428// --------------------------------------------------------------------- //
429
430/// The signed claims a [`CredentialHandle`] carries. Validity is
431/// self-contained: expiry and the scope binding read from here, and only
432/// the connection liveness check hits the store at resolution (the
433/// design's open question 5 leaning — "fails closed at the next tool
434/// call" forbids caching revocation decisions). Journaled on issuance;
435/// safe to journal throughout — claims name the connection and the
436/// narrowed grant, never the bytes.
437#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
438pub struct HandleClaims {
439    /// The handle id (`hdl-{32 hex}`).
440    pub handle_id: String,
441
442    /// The connection this handle resolves against.
443    pub connection_id: String,
444
445    /// The tenant the handle was issued to. Bound in the claims (and
446    /// covered by the signature) so a handle presented outside its
447    /// tenant is a forgery, not a cross-tenant read.
448    pub tenant: String,
449
450    /// The run the handle was issued for, when the issuance was
451    /// run-bound. The run's evidence pins — through the issuance event —
452    /// the connection id and the consent scope set it resolved; rotation
453    /// beneath the stable connection id changes nothing pinned.
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub run_id: Option<String>,
456
457    /// The narrowed scope set: always a subset of the connection's
458    /// consent set at issuance (the whole set when the request asked for
459    /// no narrowing). Resolution may check any subset of *this* set —
460    /// the second, per-operation narrowing.
461    pub scopes: BTreeSet<String>,
462
463    /// When the handle was issued.
464    pub issued_at: DateTime<Utc>,
465
466    /// When the handle stops resolving. Handles live for minutes and are
467    /// never pinned anywhere.
468    pub expires_at: DateTime<Utc>,
469}
470
471impl HandleClaims {
472    /// `true` at or past the expiry instant.
473    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
474        now >= self.expires_at
475    }
476}
477
478/// The wire prefix of a handle token (`v1.{hex claims}.{hex signature}`).
479pub const HANDLE_TOKEN_PREFIX: &str = "v1";
480
481/// An opaque capability handle: what a tool receives and presents at
482/// use. Carrying no bytes — only the signed claims and their signature —
483/// redacted in `Debug`, and with no `Serialize`/`Deserialize` impl: the
484/// wire form is [`CredentialHandle::token`], minted by a broker and
485/// verified by one, never a serde shape tool code can construct (the
486/// R0.9 non-serializability posture).
487#[derive(Clone, PartialEq)]
488pub struct CredentialHandle {
489    claims: HandleClaims,
490    signature: String,
491}
492
493impl std::fmt::Debug for CredentialHandle {
494    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495        f.debug_struct("CredentialHandle")
496            .field("claims", &self.claims)
497            .field("signature", &"[redacted]")
498            .finish()
499    }
500}
501
502impl CredentialHandle {
503    /// Assemble a handle from its signed parts. Only a broker mints
504    /// handles — the signature is an HMAC under key material the broker
505    /// holds — so this constructor existing does not make handles
506    /// forgeable; it makes them *passable* (across the tool boundary,
507    /// into a capsule's input) without a serde impl.
508    pub fn from_parts(claims: HandleClaims, signature: String) -> Self {
509        Self { claims, signature }
510    }
511
512    /// The signed claims.
513    pub fn claims(&self) -> &HandleClaims {
514        &self.claims
515    }
516
517    /// The signature (hex), for verification at resolution.
518    pub fn signature(&self) -> &str {
519        &self.signature
520    }
521
522    /// The opaque wire token: `v1.{hex(json claims)}.{hex signature}`.
523    /// Opaque to tools — they store and present it, and nothing in it
524    /// helps them reach the credential: the bytes are not here, and a
525    /// modified token fails the signature check at resolution.
526    pub fn token(&self) -> String {
527        let claims = serde_json::to_vec(&self.claims).unwrap_or_default();
528        format!(
529            "{}.{}.{}",
530            HANDLE_TOKEN_PREFIX,
531            hex_encode(&claims),
532            self.signature
533        )
534    }
535
536    /// Parse a wire token back into its unsigned parts. This is *not*
537    /// verification: the broker recomputes the signature over the parsed
538    /// claims before anything else happens. A malformed token is an
539    /// [`BrokerDenialReason::UnknownHandle`] — parse failure and forgery
540    /// are the same refusal.
541    // result_large_err: shrinking the denial would buy nothing here —
542    // the Ok half (claims plus signature) is the larger variant, so the
543    // Result is already sized by the success payload.
544    #[allow(clippy::result_large_err)]
545    pub fn parse_token(token: &str) -> std::result::Result<(HandleClaims, String), BrokerDenial> {
546        let unknown = |detail: &str| BrokerDenial::unknown_handle(detail.to_owned());
547        let mut parts = token.splitn(3, '.');
548        if parts.next() != Some(HANDLE_TOKEN_PREFIX) {
549            return Err(unknown("not a broker handle token"));
550        }
551        let claims_hex = parts.next().unwrap_or_default();
552        let signature = parts.next().unwrap_or_default().to_owned();
553        let claims_bytes =
554            hex_decode(claims_hex).ok_or_else(|| unknown("the claims half is not valid hex"))?;
555        let claims: HandleClaims = serde_json::from_slice(&claims_bytes)
556            .map_err(|_| unknown("the claims half is not a handle claims document"))?;
557        if !minted_id_ok(HANDLE_ID_PREFIX, &claims.handle_id)
558            || !minted_id_ok(CONNECTION_ID_PREFIX, &claims.connection_id)
559            || claims.tenant.is_empty()
560            || claims.expires_at <= claims.issued_at
561        {
562            return Err(unknown("the claims fail handle grammar"));
563        }
564        Ok((claims, signature))
565    }
566}
567
568// --------------------------------------------------------------------- //
569// Denials
570// --------------------------------------------------------------------- //
571
572/// Why a handle issuance or resolution was refused. Closed enum,
573/// additive evolution; serialized with internal tagging so the reason is
574/// part of the journaled evidence (the `CapabilityGrant` rule).
575///
576/// Every variant is a fail-closed answer: a scope check that cannot be
577/// performed is a check that fails ([`BrokerDenialReason::BrokerUnavailable`]),
578/// and there is no degraded mode that skips it.
579#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
580#[serde(tag = "reason", rename_all = "snake_case")]
581pub enum BrokerDenialReason {
582    /// The presented token is not a handle this broker minted — malformed,
583    /// or the signature did not verify. Parse failure and forgery are
584    /// deliberately the same refusal: a broker that distinguishes them
585    /// tells a prober which half to fix.
586    UnknownHandle,
587
588    /// The handle's TTL ran out. Handles are short-lived; the tool
589    /// re-issues at its next use.
590    HandleExpired {
591        /// When the handle expired.
592        expires_at: DateTime<Utc>,
593    },
594
595    /// The request named scopes outside the bound set — the consent set
596    /// at issuance (beyond what the human granted), the handle's narrowed
597    /// set at resolution (scope escalation refused).
598    ScopeNotGranted {
599        /// The scopes that were not granted, sorted.
600        missing: Vec<String>,
601    },
602
603    /// The connection was revoked; outstanding handles fail at their
604    /// next use. The grant travels in the denial — the release proof's
605    /// "naming the connection and the revoked grant".
606    ConnectionRevoked {
607        /// The revoked consent scope set.
608        grant: Vec<String>,
609    },
610
611    /// The refresh path failed terminally; a human must re-consent. A
612    /// typed re-auth signal, never a silent retry with stale material.
613    ConnectionNeedsReauth,
614
615    /// No connection by that id in this tenant (unknown and cross-tenant
616    /// are indistinguishable — 404, never 403).
617    UnknownConnection,
618
619    /// The broker could not perform the check (the store read failed,
620    /// the evidence could not be journaled). Fail closed: the call is
621    /// denied because the check did not happen.
622    BrokerUnavailable,
623}
624
625/// A typed, journaled refusal. Attributable — it names the connection,
626/// the handle, and the grant (or missing scope) that decided it — and it
627/// can never carry credential bytes: no field of this type is
628/// credential-shaped, by construction (the `MemoryForgetTombstone`
629/// discipline: the receipt of an erasure cannot leak what was erased).
630#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
631pub struct BrokerDenial {
632    /// The connection the denial concerns, when known (absent for an
633    /// unparseable handle).
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub connection_id: Option<String>,
636
637    /// The handle the denial concerns, when known.
638    #[serde(default, skip_serializing_if = "Option::is_none")]
639    pub handle_id: Option<String>,
640
641    /// The tenant the denial concerns, when known. Carried because the
642    /// broker's evidence chain is deployment-wide and the tenant is what
643    /// makes a denial attributable across it.
644    #[serde(default, skip_serializing_if = "Option::is_none")]
645    pub tenant: Option<String>,
646
647    /// Why the call was refused. Flattened, so the internally-tagged
648    /// reason sits at the denial's top level — `{"reason":
649    /// "connection_revoked", "grant": […], …}` — one flat evidence
650    /// object, never a `reason.reason` nesting.
651    #[serde(flatten)]
652    pub reason: BrokerDenialReason,
653
654    /// Human-facing context: what was attempted, against which grant.
655    pub detail: String,
656}
657
658impl BrokerDenial {
659    /// An unparseable or badly signed token.
660    pub fn unknown_handle(detail: String) -> Self {
661        Self {
662            connection_id: None,
663            handle_id: None,
664            tenant: None,
665            reason: BrokerDenialReason::UnknownHandle,
666            detail,
667        }
668    }
669
670    /// A valid handle past its TTL.
671    pub fn handle_expired(claims: &HandleClaims) -> Self {
672        Self {
673            connection_id: Some(claims.connection_id.clone()),
674            handle_id: Some(claims.handle_id.clone()),
675            tenant: Some(claims.tenant.clone()),
676            reason: BrokerDenialReason::HandleExpired {
677                expires_at: claims.expires_at,
678            },
679            detail: format!(
680                "handle `{}` expired at {} — handles are short-lived; re-issue at the next use",
681                claims.handle_id, claims.expires_at
682            ),
683        }
684    }
685
686    /// A request beyond the bound scope set (issuance against consent,
687    /// or resolution against the handle's narrowed set). The missing
688    /// scopes join the detail: a denial must name what was refused.
689    pub fn scope_not_granted(
690        claims_or_connection: Option<(&str, Option<&str>, &str)>,
691        missing: Vec<String>,
692        detail: String,
693    ) -> Self {
694        let (connection_id, handle_id, tenant) = match claims_or_connection {
695            Some((connection, handle, tenant)) => (
696                Some(connection.to_owned()),
697                handle.map(str::to_owned),
698                Some(tenant.to_owned()),
699            ),
700            None => (None, None, None),
701        };
702        Self {
703            connection_id,
704            handle_id,
705            tenant,
706            detail: format!("{detail} — missing scopes: {}", missing.join(", ")),
707            reason: BrokerDenialReason::ScopeNotGranted { missing },
708        }
709    }
710
711    /// A use against a revoked connection, naming the revoked grant.
712    pub fn connection_revoked(record: &ConnectionRecord, tenant: &str, handle_id: &str) -> Self {
713        Self {
714            connection_id: Some(record.connection_id.clone()),
715            handle_id: Some(handle_id.to_owned()),
716            tenant: Some(tenant.to_owned()),
717            reason: BrokerDenialReason::ConnectionRevoked {
718                grant: record.scopes.iter().cloned().collect(),
719            },
720            detail: format!(
721                "connection `{}` is revoked — the grant {} no longer holds; the next use fails \
722                 closed, not the next deploy",
723                record.connection_id,
724                serde_json::to_string(&record.scopes).unwrap_or_default(),
725            ),
726        }
727    }
728
729    /// A use against a connection whose refresh path failed terminally.
730    pub fn connection_needs_reauth(
731        record: &ConnectionRecord,
732        tenant: &str,
733        handle_id: &str,
734    ) -> Self {
735        Self {
736            connection_id: Some(record.connection_id.clone()),
737            handle_id: Some(handle_id.to_owned()),
738            tenant: Some(tenant.to_owned()),
739            reason: BrokerDenialReason::ConnectionNeedsReauth,
740            detail: format!(
741                "connection `{}` needs re-authentication — a human must record a new consent act",
742                record.connection_id
743            ),
744        }
745    }
746
747    /// A handle naming a connection the tenant does not hold.
748    pub fn unknown_connection(claims: &HandleClaims) -> Self {
749        Self {
750            connection_id: Some(claims.connection_id.clone()),
751            handle_id: Some(claims.handle_id.clone()),
752            tenant: Some(claims.tenant.clone()),
753            reason: BrokerDenialReason::UnknownConnection,
754            detail: format!(
755                "connection `{}` is unknown to tenant `{}`",
756                claims.connection_id, claims.tenant
757            ),
758        }
759    }
760
761    /// The check itself could not be performed — fail closed.
762    pub fn unavailable(detail: String) -> Self {
763        Self {
764            connection_id: None,
765            handle_id: None,
766            tenant: None,
767            reason: BrokerDenialReason::BrokerUnavailable,
768            detail,
769        }
770    }
771}
772
773impl std::fmt::Display for BrokerDenial {
774    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
775        let tag = match &self.reason {
776            BrokerDenialReason::UnknownHandle => "unknown_handle",
777            BrokerDenialReason::HandleExpired { .. } => "handle_expired",
778            BrokerDenialReason::ScopeNotGranted { .. } => "scope_not_granted",
779            BrokerDenialReason::ConnectionRevoked { .. } => "connection_revoked",
780            BrokerDenialReason::ConnectionNeedsReauth => "connection_needs_reauth",
781            BrokerDenialReason::UnknownConnection => "unknown_connection",
782            BrokerDenialReason::BrokerUnavailable => "broker_unavailable",
783        };
784        write!(f, "{tag}: {}", self.detail)
785    }
786}
787
788impl std::error::Error for BrokerDenial {}
789
790// --------------------------------------------------------------------- //
791// Journaled payloads
792// --------------------------------------------------------------------- //
793
794/// The journaled consent act (output of
795/// [`RunEventKind::ConnectionConsented`](crate::record::RunEventKind::ConnectionConsented)):
796/// the human's grant at the provider, recorded. Scope widening is *only*
797/// ever this — a new consent act, journaled; there is no API path that
798/// widens a connection's consented set silently.
799#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
800pub struct ConnectionConsent {
801    /// The connection the consent governs.
802    pub connection_id: String,
803
804    /// The subject the consent binds, when per-user.
805    #[serde(default, skip_serializing_if = "Option::is_none")]
806    pub subject: Option<String>,
807
808    /// The consent scope set as recorded — the new ceiling.
809    pub scopes: BTreeSet<String>,
810
811    /// When the consent was recorded.
812    pub recorded_at: DateTime<Utc>,
813}
814
815/// The journaled token-material update (output of
816/// [`RunEventKind::ConnectionRefreshed`](crate::record::RunEventKind::ConnectionRefreshed)):
817/// new material beneath the same consent set — a recorded credential
818/// rotation. Names the connection and the new expiry; never the bytes.
819#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
820pub struct ConnectionRefresh {
821    /// The connection whose material rotated.
822    pub connection_id: String,
823
824    /// When the new material was sealed.
825    pub refreshed_at: DateTime<Utc>,
826
827    /// The new access token's expiry, when the provider declares one.
828    #[serde(default, skip_serializing_if = "Option::is_none")]
829    pub expires_at: Option<DateTime<Utc>>,
830}
831
832/// The journaled revocation (output of
833/// [`RunEventKind::ConnectionRevoked`](crate::record::RunEventKind::ConnectionRevoked)).
834/// The status flip and this event commit together; outstanding handles
835/// fail at their next use.
836#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
837pub struct ConnectionRevocation {
838    /// The revoked connection.
839    pub connection_id: String,
840
841    /// The consent scope set that stopped holding — the revoked grant.
842    pub grant: BTreeSet<String>,
843
844    /// When the revocation was recorded.
845    pub revoked_at: DateTime<Utc>,
846
847    /// The operator's reason, when given.
848    #[serde(default, skip_serializing_if = "Option::is_none")]
849    pub reason: Option<String>,
850}
851
852/// The journaled re-auth transition (output of
853/// [`RunEventKind::ConnectionNeedsReauth`](crate::record::RunEventKind::ConnectionNeedsReauth)):
854/// the refresh path failed terminally and the connection's status flipped
855/// to `needs_reauth`. Names the classified failure that decided the flip
856/// and the consent set that stopped being servable — attributable, like
857/// every broker event, and metadata by construction: the provider's error
858/// detail is human-facing context, never credential material.
859#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
860pub struct ConnectionReauthRequired {
861    /// The connection that needs a new consent act.
862    pub connection_id: String,
863
864    /// The terminal failure: the provider's refusal classified under the
865    /// R0.6 [`ErrorClass`] taxonomy.
866    pub failure: ClassifiedFailure,
867
868    /// The consent scope set that stopped being servable.
869    pub grant: BTreeSet<String>,
870
871    /// When the flip was recorded.
872    pub recorded_at: DateTime<Utc>,
873}
874
875/// The journaled handle issuance (output of
876/// [`RunEventKind::CredentialHandleIssued`](crate::record::RunEventKind::CredentialHandleIssued)):
877/// the full claims, so the run's evidence pins the connection id and the
878/// consent scope set it resolved — credential rotation beneath the
879/// stable connection id changes nothing pinned.
880#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
881pub struct HandleIssuance {
882    /// The issued claims.
883    pub claims: HandleClaims,
884}
885
886/// The journaled resolution (output of
887/// [`RunEventKind::CredentialUse`](crate::record::RunEventKind::CredentialUse)):
888/// metadata — handle, connection, the scopes checked — never bytes (the
889/// `CapsuleUse` precedent).
890#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
891pub struct CredentialUse {
892    /// The handle that resolved.
893    pub handle_id: String,
894
895    /// The connection the credential came from.
896    pub connection_id: String,
897
898    /// The tenant the resolution served.
899    pub tenant: String,
900
901    /// The run the handle was bound to, when it was.
902    #[serde(default, skip_serializing_if = "Option::is_none")]
903    pub run_id: Option<String>,
904
905    /// The scopes this call required and the handle covered.
906    pub scopes_checked: BTreeSet<String>,
907
908    /// When the resolution happened.
909    pub used_at: DateTime<Utc>,
910}
911
912// --------------------------------------------------------------------- //
913// The OAuth lifecycle (R0.11 Extension Plane, wave 4)
914// --------------------------------------------------------------------- //
915
916/// A successful grant from a provider: token exchange (the back half of
917/// the human's consent act) or a refresh. Like [`TokenMaterial`], this
918/// type carries credential bytes and follows the same posture — redacted
919/// in `Debug`, no `Serialize` impl, because a grant is never evidence:
920/// the journaled `connection_refreshed` event is. The broker converts it
921/// into [`TokenMaterial`] and seals it; nothing else ever holds it.
922#[derive(Clone, PartialEq)]
923pub struct TokenGrant {
924    /// The freshly minted access token.
925    pub access_token: String,
926
927    /// The refresh token, where the provider rotates or issues one. When
928    /// absent on a refresh, the connection's existing refresh token
929    /// stands (providers that do not rotate refresh tokens).
930    pub refresh_token: Option<String>,
931
932    /// The new access token's expiry, when the provider declares one.
933    pub expires_at: Option<DateTime<Utc>>,
934}
935
936impl std::fmt::Debug for TokenGrant {
937    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
938        f.debug_struct("TokenGrant")
939            .field("access_token", &"[redacted]")
940            .field(
941                "refresh_token",
942                &self.refresh_token.as_ref().map(|_| "[redacted]"),
943            )
944            .field("expires_at", &self.expires_at)
945            .finish()
946    }
947}
948
949/// The provider's typed refusal. Classified under the R0.6 [`ErrorClass`]
950/// taxonomy so the retry policy plane reads it unchanged; `permanent`
951/// marks the terminal refusals — `invalid_grant`, an expired refresh
952/// token — that flip the connection to `needs_reauth` rather than retry:
953/// a stale credential retried looks exactly like an attack retried. The
954/// `detail` is human-facing context (the provider's error), never
955/// credential material.
956#[derive(Debug, Clone, PartialEq)]
957pub struct OAuthFailure {
958    /// The retry-taxonomy class of the failure.
959    pub class: ErrorClass,
960
961    /// `true` for terminal refusals (`invalid_grant` and kin): the
962    /// connection flips to `needs_reauth` and calls fail closed until a
963    /// human records a new consent act.
964    pub permanent: bool,
965
966    /// Human-facing context, never credential material.
967    pub detail: String,
968}
969
970impl OAuthFailure {
971    /// A terminal refusal (`permanent: true`, classed `InvalidInput` — the
972    /// taxonomy's "the same bytes will fail the same way on every attempt"
973    /// bucket, which a stale grant is exactly).
974    pub fn permanent(detail: impl Into<String>) -> Self {
975        Self {
976            class: ErrorClass::InvalidInput,
977            permanent: true,
978            detail: detail.into(),
979        }
980    }
981
982    /// A retryable failure (`permanent: false`) under `class`.
983    pub fn transient(class: ErrorClass, detail: impl Into<String>) -> Self {
984        Self {
985            class,
986            permanent: false,
987            detail: detail.into(),
988        }
989    }
990}
991
992impl std::fmt::Display for OAuthFailure {
993    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
994        let kind = if self.permanent {
995            "permanent"
996        } else {
997            "transient"
998        };
999        write!(
1000            f,
1001            "{kind} OAuth failure ({:?}): {}",
1002            self.class, self.detail
1003        )
1004    }
1005}
1006
1007impl std::error::Error for OAuthFailure {}
1008
1009impl ConnectionProvider {
1010    /// `true` for the OAuth 2.0 flows — the kinds whose token material the
1011    /// refresh lifecycle (at-resolution and the sweeper) rotates. Static
1012    /// kinds (`api_key`, `basic`) have no refresh path: their material
1013    /// changes only by a recorded consent act.
1014    pub fn is_oauth(self) -> bool {
1015        matches!(
1016            self,
1017            ConnectionProvider::Oauth2AuthorizationCode
1018                | ConnectionProvider::Oauth2ClientCredentials
1019        )
1020    }
1021}
1022
1023/// The OAuth provider seam: where a deployment plugs the token endpoint.
1024/// Core owns the lifecycle — when an exchange or refresh happens, what
1025/// the outcomes mean — and the server owns custody; the provider owns
1026/// exactly one thing: speaking the provider's wire protocol. Drawn as a
1027/// trait (the [`CredentialBroker`] / `NetworkConnector` boundary) so the
1028/// lifecycle is testable against a scripted provider with no live
1029/// external dependency, and so a deployment's HTTP implementation is one
1030/// small adapter rather than a fork of the broker.
1031///
1032/// Implementations MUST NOT log or persist anything they are handed or
1033/// return: the arguments and the grant are credential bytes.
1034#[async_trait]
1035pub trait OAuthProvider: std::fmt::Debug + Send + Sync {
1036    /// Exchange an authorization code for the initial grant — the back
1037    /// half of the human's consent act at the provider. The `scopes` are
1038    /// the consent set being recorded; providers that echo the granted
1039    /// scope set in the exchange response answer for the same set.
1040    async fn exchange_code(
1041        &self,
1042        code: &str,
1043        scopes: &BTreeSet<String>,
1044    ) -> std::result::Result<TokenGrant, OAuthFailure>;
1045
1046    /// Refresh the connection's access token. The two OAuth flows differ
1047    /// in what they present, and the provider sees the sealed material so
1048    /// it can serve both: authorization-code connections present
1049    /// `material.refresh_token`; client-credentials connections re-present
1050    /// `material.client_secret`. The connection record rides along for the
1051    /// provider kind, the subject, and the consented scope set.
1052    async fn refresh(
1053        &self,
1054        connection: &ConnectionRecord,
1055        material: &TokenMaterial,
1056    ) -> std::result::Result<TokenGrant, OAuthFailure>;
1057}
1058
1059/// One scripted outcome of a [`ScriptedOAuthProvider`] call.
1060#[derive(Debug, Clone)]
1061enum ScriptedOutcome {
1062    /// Mint the next rotating token (`{prefix}-{n}`, counter monotonic).
1063    Rotate,
1064    /// Answer with this grant verbatim.
1065    Grant(TokenGrant),
1066    /// Answer with this failure verbatim.
1067    Fail(OAuthFailure),
1068}
1069
1070/// A scripted OAuth provider for tests and embedder smoke checks — the
1071/// lifecycle's stand-in for a live token endpoint, so no test needs a
1072/// network. Authorization codes map to scripted outcomes (an unknown code
1073/// is the provider's `invalid_grant`, permanent); refreshes pop a
1074/// scripted queue and default to rotation: each call mints the next
1075/// access token beneath the same refresh token, which is exactly the
1076/// provider behavior the broker's rotation-beneath-a-stable-id contract
1077/// is built on.
1078#[derive(Debug)]
1079pub struct ScriptedOAuthProvider {
1080    codes: Mutex<std::collections::HashMap<String, ScriptedOutcome>>,
1081    refresh_script: Mutex<std::collections::VecDeque<ScriptedOutcome>>,
1082    counter: std::sync::atomic::AtomicU64,
1083    token_prefix: String,
1084    grant_ttl: chrono::Duration,
1085    exchanges: Mutex<Vec<String>>,
1086    refreshes: Mutex<u64>,
1087}
1088
1089impl Default for ScriptedOAuthProvider {
1090    fn default() -> Self {
1091        Self::new()
1092    }
1093}
1094
1095impl ScriptedOAuthProvider {
1096    /// A provider whose tokens read `scripted-token-{n}` and live one
1097    /// hour per grant.
1098    pub fn new() -> Self {
1099        Self {
1100            codes: Mutex::new(std::collections::HashMap::new()),
1101            refresh_script: Mutex::new(std::collections::VecDeque::new()),
1102            counter: std::sync::atomic::AtomicU64::new(0),
1103            token_prefix: "scripted-token".to_owned(),
1104            grant_ttl: chrono::Duration::hours(1),
1105            exchanges: Mutex::new(Vec::new()),
1106            refreshes: Mutex::new(0),
1107        }
1108    }
1109
1110    /// Builder-style: the minted token prefix (a distinctive marker, so a
1111    /// leak scan is a scan for it).
1112    pub fn with_token_prefix(mut self, prefix: impl Into<String>) -> Self {
1113        self.token_prefix = prefix.into();
1114        self
1115    }
1116
1117    /// Builder-style: the lifetime stamped on minted grants.
1118    pub fn with_grant_ttl(mut self, ttl: chrono::Duration) -> Self {
1119        self.grant_ttl = ttl;
1120        self
1121    }
1122
1123    /// Script `code` to exchange for `grant`.
1124    pub fn with_code(self, code: impl Into<String>, grant: TokenGrant) -> Self {
1125        self.codes
1126            .lock()
1127            .expect("scripted provider lock")
1128            .insert(code.into(), ScriptedOutcome::Grant(grant));
1129        self
1130    }
1131
1132    /// Script `code` to fail its exchange with `failure`.
1133    pub fn with_code_failure(self, code: impl Into<String>, failure: OAuthFailure) -> Self {
1134        self.codes
1135            .lock()
1136            .expect("scripted provider lock")
1137            .insert(code.into(), ScriptedOutcome::Fail(failure));
1138        self
1139    }
1140
1141    /// Queue a scripted refresh failure (consumed in call order; the
1142    /// queue empty is steady-state rotation — a transient failure that
1143    /// heals is one entry, a terminal one is the last).
1144    pub fn then_refresh_failure(self, failure: OAuthFailure) -> Self {
1145        self.refresh_script
1146            .lock()
1147            .expect("scripted provider lock")
1148            .push_back(ScriptedOutcome::Fail(failure));
1149        self
1150    }
1151
1152    /// Queue a scripted refresh grant.
1153    pub fn then_refresh_grant(self, grant: TokenGrant) -> Self {
1154        self.refresh_script
1155            .lock()
1156            .expect("scripted provider lock")
1157            .push_back(ScriptedOutcome::Grant(grant));
1158        self
1159    }
1160
1161    /// `(exchanges, refreshes)` observed so far — the assertions a
1162    /// lifecycle test makes ("the rotation happened exactly once").
1163    pub fn call_counts(&self) -> (usize, u64) {
1164        (
1165            self.exchanges.lock().expect("scripted provider lock").len(),
1166            *self.refreshes.lock().expect("scripted provider lock"),
1167        )
1168    }
1169
1170    fn mint(&self, refresh_token: Option<String>) -> TokenGrant {
1171        let n = self
1172            .counter
1173            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1174        TokenGrant {
1175            access_token: format!("{}-{n}", self.token_prefix),
1176            refresh_token,
1177            expires_at: Some(Utc::now() + self.grant_ttl),
1178        }
1179    }
1180
1181    fn resolve(
1182        &self,
1183        outcome: ScriptedOutcome,
1184        material: Option<&TokenMaterial>,
1185    ) -> std::result::Result<TokenGrant, OAuthFailure> {
1186        match outcome {
1187            // A rotation keeps the presented refresh token when the
1188            // material carries one (providers that do not rotate refresh
1189            // tokens); client-credentials material carries none, and the
1190            // minted grant carries none either.
1191            ScriptedOutcome::Rotate => {
1192                Ok(self.mint(material.and_then(|m| m.refresh_token.clone())))
1193            }
1194            ScriptedOutcome::Grant(grant) => Ok(grant),
1195            ScriptedOutcome::Fail(failure) => Err(failure),
1196        }
1197    }
1198}
1199
1200#[async_trait]
1201impl OAuthProvider for ScriptedOAuthProvider {
1202    async fn exchange_code(
1203        &self,
1204        code: &str,
1205        scopes: &BTreeSet<String>,
1206    ) -> std::result::Result<TokenGrant, OAuthFailure> {
1207        let _ = scopes;
1208        self.exchanges
1209            .lock()
1210            .expect("scripted provider lock")
1211            .push(code.to_owned());
1212        let outcome = self
1213            .codes
1214            .lock()
1215            .expect("scripted provider lock")
1216            .get(code)
1217            .cloned();
1218        match outcome {
1219            Some(outcome) => self.resolve(outcome, None),
1220            // An unknown code is the provider's refusal, not a scripting
1221            // gap: real providers answer `invalid_grant` here, and the
1222            // broker's permanent-failure path is what a test drives.
1223            None => Err(OAuthFailure::permanent(format!(
1224                "invalid_grant: unknown authorization code `{code}`"
1225            ))),
1226        }
1227    }
1228
1229    async fn refresh(
1230        &self,
1231        connection: &ConnectionRecord,
1232        material: &TokenMaterial,
1233    ) -> std::result::Result<TokenGrant, OAuthFailure> {
1234        let _ = connection;
1235        *self.refreshes.lock().expect("scripted provider lock") += 1;
1236        let outcome = self
1237            .refresh_script
1238            .lock()
1239            .expect("scripted provider lock")
1240            .pop_front();
1241        self.resolve(outcome.unwrap_or(ScriptedOutcome::Rotate), Some(material))
1242    }
1243}
1244
1245// --------------------------------------------------------------------- //
1246// The broker seam
1247// --------------------------------------------------------------------- //
1248
1249/// What a tool (or capsule, or MCP/A2A client call) declares it needs:
1250/// the connection to draw on and the scopes *this call* requires. The
1251/// declaration is the unit of narrowing — issuance checks it against the
1252/// consent ceiling, resolution checks it against the handle's narrowed
1253/// set, and a tool asking beyond either is denied with the missing
1254/// scopes named.
1255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1256pub struct CredentialRequirement {
1257    /// The connection to draw on.
1258    pub connection_id: String,
1259
1260    /// The scopes this call requires, in provider semantics. An empty
1261    /// set asks for no narrowing: issuance binds the handle to the
1262    /// connection's whole consent set (the capsule `Secret` grant's
1263    /// posture — the grant names the connection wholesale).
1264    pub scopes: BTreeSet<String>,
1265}
1266
1267/// One handle issuance request against a [`CredentialBroker`].
1268#[derive(Debug, Clone, PartialEq, Eq)]
1269pub struct IssueRequest {
1270    /// The tenant the handle is issued to.
1271    pub tenant: String,
1272
1273    /// The run to bind the handle to, when the issuance is run-bound.
1274    pub run_id: Option<String>,
1275
1276    /// The declared need.
1277    pub requirement: CredentialRequirement,
1278}
1279
1280/// What resolution hands to the **connector** — the host's HTTP/tool-call
1281/// boundary — and never to tool code: the decrypted credential plus the
1282/// metadata of the resolution it came from. Redacted in `Debug`; no
1283/// `Serialize` impl, because nothing about a resolved credential is
1284/// evidence — the [`CredentialUse`] event is.
1285#[derive(Clone)]
1286pub struct ResolvedCredential {
1287    /// The connection the credential came from.
1288    pub connection_id: String,
1289
1290    /// The handle that resolved.
1291    pub handle_id: String,
1292
1293    /// The handle's narrowed scope set (the ceiling this resolution was
1294    /// checked against).
1295    pub scopes: BTreeSet<String>,
1296
1297    /// The decrypted token material. The connector injects it into the
1298    /// outbound request; tool code never sees this struct.
1299    pub material: TokenMaterial,
1300}
1301
1302impl std::fmt::Debug for ResolvedCredential {
1303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1304        f.debug_struct("ResolvedCredential")
1305            .field("connection_id", &self.connection_id)
1306            .field("handle_id", &self.handle_id)
1307            .field("scopes", &self.scopes)
1308            .field("material", &"[redacted]")
1309            .finish()
1310    }
1311}
1312
1313/// The broker seam: where a deployment plugs credential custody. Core
1314/// owns the contracts and the journaled shapes; the server owns key
1315/// custody, envelope encryption, and persistence — the `NetworkConnector`
1316/// boundary, drawn for the same reason.
1317///
1318/// Implementations MUST journal: every issuance, every resolution, and
1319/// every denial, typed and naming the connection and grant — never the
1320/// bytes. A use that cannot journal must fail closed
1321/// ([`BrokerDenialReason::BrokerUnavailable`]): evidence is not
1322/// optional on this surface.
1323#[async_trait]
1324pub trait CredentialBroker: std::fmt::Debug + Send + Sync {
1325    /// Issue a short-lived handle for one declared need. Issuance checks
1326    /// the connection's live state (active, not revoked or
1327    /// `needs_reauth`) and the consent ceiling (the requested scopes
1328    /// must be covered — a tool requesting beyond the consented set is
1329    /// denied *here*, not at the provider).
1330    async fn issue(
1331        &self,
1332        request: &IssueRequest,
1333    ) -> std::result::Result<CredentialHandle, BrokerDenial>;
1334
1335    /// Resolve a handle for one operation: verify the signature, check
1336    /// expiry and scope coverage from the self-contained claims, then
1337    /// read the connection's *live* state (revocation takes effect at
1338    /// the next call, never the next deploy), and return the credential
1339    /// to the connector. Denials are typed and journaled.
1340    async fn resolve(
1341        &self,
1342        token: &str,
1343        scopes: &BTreeSet<String>,
1344    ) -> std::result::Result<ResolvedCredential, BrokerDenial>;
1345}
1346
1347// --------------------------------------------------------------------- //
1348// ToolExecutor integration
1349// --------------------------------------------------------------------- //
1350
1351/// A tool that draws on a broker connection: a [`Tool`] plus the two
1352/// things the broker needs — the per-call declaration of what it
1353/// requires, and an entry point that receives the issued handle. The
1354/// handle is all `call_authenticated` gets: the tool presents it to the
1355/// host-side connector, and the connector (holding a
1356/// [`CredentialBroker`]) resolves it into the credential it injects —
1357/// the bytes never enter tool code.
1358#[async_trait]
1359pub trait CredentialTool: Tool {
1360    /// The connection and scopes this concrete call requires. Per-call
1361    /// because the operation decides the scope — a `search.read` call and
1362    /// a `drive.write` call through the same tool must not share a
1363    /// ceiling.
1364    fn credential_requirement(&self, args: &Value) -> CredentialRequirement;
1365
1366    /// Execute with the issued handle. The handle is opaque: present it
1367    /// to the connector; there is nothing here to exfiltrate.
1368    async fn call_authenticated(&self, args: Value, handle: &CredentialHandle) -> Result<Value>;
1369}
1370
1371/// The mediator's handle cache: `(run, connection, scopes)` → a live
1372/// handle and the instant to re-issue at (three quarters through the
1373/// TTL, so a handle never expires mid-call the way a boundary-checked
1374/// one could).
1375type HandleCache =
1376    HashMap<(Option<String>, String, BTreeSet<String>), (CredentialHandle, DateTime<Utc>)>;
1377
1378/// The run-scoped issuance half of the `ToolExecutor` integration: one
1379/// broker, one tenant, an optional run binding, and a small cache of
1380/// live handles so a tool "receives a handle at first use" and reuses it
1381/// through its TTL rather than minting one per call. The cache only
1382/// defers *issuance* — every resolution still reads live connection
1383/// state, so caching a handle cannot cache a revocation.
1384#[derive(Clone)]
1385pub struct CredentialMediator {
1386    broker: Arc<dyn CredentialBroker>,
1387    tenant: String,
1388    run_id: Option<String>,
1389    handles: Arc<Mutex<HandleCache>>,
1390}
1391
1392impl std::fmt::Debug for CredentialMediator {
1393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1394        f.debug_struct("CredentialMediator")
1395            .field("tenant", &self.tenant)
1396            .field("run_id", &self.run_id)
1397            .finish()
1398    }
1399}
1400
1401impl CredentialMediator {
1402    /// A mediator over `broker` issuing for `tenant`, unbound to a run.
1403    pub fn new(broker: Arc<dyn CredentialBroker>, tenant: impl Into<String>) -> Self {
1404        Self {
1405            broker,
1406            tenant: tenant.into(),
1407            run_id: None,
1408            handles: Arc::new(Mutex::new(HashMap::new())),
1409        }
1410    }
1411
1412    /// The same mediator bound to a run. The cache is shared (keyed on
1413    /// the run binding), so rebinding never strands a live handle.
1414    pub fn for_run(&self, run_id: Option<String>) -> Self {
1415        Self {
1416            broker: Arc::clone(&self.broker),
1417            tenant: self.tenant.clone(),
1418            run_id,
1419            handles: Arc::clone(&self.handles),
1420        }
1421    }
1422
1423    /// The run this mediator binds handles to, when bound.
1424    pub fn run_id(&self) -> Option<&str> {
1425        self.run_id.as_deref()
1426    }
1427
1428    /// The underlying broker (the connector's resolution path).
1429    pub fn broker(&self) -> &Arc<dyn CredentialBroker> {
1430        &self.broker
1431    }
1432
1433    /// Issue (or serve from the live cache) a handle for one declared
1434    /// need. Denials propagate typed — the caller fails the tool call
1435    /// closed.
1436    pub async fn issue(
1437        &self,
1438        requirement: &CredentialRequirement,
1439    ) -> std::result::Result<CredentialHandle, BrokerDenial> {
1440        let key = (
1441            self.run_id.clone(),
1442            requirement.connection_id.clone(),
1443            requirement.scopes.clone(),
1444        );
1445        if let Some((handle, renew_after)) = self
1446            .handles
1447            .lock()
1448            .ok()
1449            .and_then(|cache| cache.get(&key).cloned())
1450        {
1451            if Utc::now() < renew_after {
1452                return Ok(handle);
1453            }
1454        }
1455        let handle = self
1456            .broker
1457            .issue(&IssueRequest {
1458                tenant: self.tenant.clone(),
1459                run_id: self.run_id.clone(),
1460                requirement: requirement.clone(),
1461            })
1462            .await?;
1463        let claims = handle.claims();
1464        // Re-issue at three quarters of the TTL: the cached handle is
1465        // always comfortably live when served, and the re-issue path is
1466        // exercised routinely rather than only at the boundary.
1467        let ttl = claims.expires_at - claims.issued_at;
1468        let renew_after = claims.issued_at + ttl * 3 / 4;
1469        if let Ok(mut cache) = self.handles.lock() {
1470            cache.insert(key, (handle.clone(), renew_after));
1471        }
1472        Ok(handle)
1473    }
1474
1475    /// Wrap one credential-requiring tool so ordinary `ToolExecutor`
1476    /// dispatch mediates it: the executor needs no changes — issuance
1477    /// happens inside the tool's own `call`, scope-checked at the
1478    /// broker, with the effect boundary transparently delegated.
1479    pub fn mediate(&self, tool: Arc<dyn CredentialTool>) -> MediatedTool {
1480        MediatedTool {
1481            inner: tool,
1482            mediator: self.clone(),
1483        }
1484    }
1485}
1486
1487/// The [`Tool`] wrapper [`CredentialMediator::mediate`] produces. Every
1488/// reflective method delegates to the inner tool — a wrapper must remain
1489/// transparent to the effect boundary (`Tool::effect_request`'s own
1490/// rule) — and `call` inserts exactly one step: issue, then hand the
1491/// inner tool the handle.
1492pub struct MediatedTool {
1493    inner: Arc<dyn CredentialTool>,
1494    mediator: CredentialMediator,
1495}
1496
1497impl std::fmt::Debug for MediatedTool {
1498    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1499        f.debug_struct("MediatedTool")
1500            .field("tool", &self.inner.name())
1501            .finish()
1502    }
1503}
1504
1505#[async_trait]
1506impl Tool for MediatedTool {
1507    fn name(&self) -> &str {
1508        self.inner.name()
1509    }
1510
1511    fn description(&self) -> &str {
1512        self.inner.description()
1513    }
1514
1515    fn parameters_schema(&self) -> Value {
1516        self.inner.parameters_schema()
1517    }
1518
1519    fn effect(&self) -> Effect {
1520        self.inner.effect()
1521    }
1522
1523    fn effect_kind(&self) -> &str {
1524        self.inner.effect_kind()
1525    }
1526
1527    fn idempotency_key(&self, args: &Value) -> Option<String> {
1528        self.inner.idempotency_key(args)
1529    }
1530
1531    fn effect_request(&self, call: &crate::llm::ToolCall) -> crate::effects::EffectRequest {
1532        self.inner.effect_request(call)
1533    }
1534
1535    async fn call(&self, args: Value) -> Result<Value> {
1536        let requirement = self.inner.credential_requirement(&args);
1537        let handle =
1538            self.mediator.issue(&requirement).await.map_err(|denial| {
1539                RustyError::Tool(format!("credential issuance denied: {denial}"))
1540            })?;
1541        self.inner.call_authenticated(args, &handle).await
1542    }
1543}
1544
1545// --------------------------------------------------------------------- //
1546// Capsule-host integration (feature `wasm`)
1547// --------------------------------------------------------------------- //
1548
1549/// The capsule half of the broker (R0.9 secret-handle precedent,
1550/// extended): a [`CapsuleHost`](crate::capsule_host::CapsuleHost)
1551/// wrapper that brokers the manifest's `Secret` grants into issued
1552/// handle tokens before the guest runs.
1553///
1554/// The v1 world has no secret import, so the tokens travel the one
1555/// channel a guest already has: its input. Each granted name — now a
1556/// broker connection id — is issued a handle (run-bound when the
1557/// invocation journals into a run) and injected under the reserved
1558/// `secrets` key. The guest receives opaque tokens and nothing else; a
1559/// later world version's credential import resolves them through the
1560/// same broker the host wired here. Two fail-closed edges, by
1561/// construction: an issuance denial refuses the invocation before guest
1562/// code runs (the broker journals it), and an input that already
1563/// carries a `secrets` key is refused — a guest smuggling its own
1564/// "tokens" is indistinguishable from one the host issued, so the
1565/// collision is an admission error, never an overwrite.
1566#[cfg(feature = "wasm")]
1567#[derive(Clone)]
1568pub struct BrokeredCapsuleHost {
1569    host: crate::capsule_host::CapsuleHost,
1570    mediator: CredentialMediator,
1571}
1572
1573#[cfg(feature = "wasm")]
1574impl std::fmt::Debug for BrokeredCapsuleHost {
1575    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1576        f.debug_struct("BrokeredCapsuleHost")
1577            .field("host", &self.host)
1578            .field("mediator", &self.mediator)
1579            .finish()
1580    }
1581}
1582
1583#[cfg(feature = "wasm")]
1584impl BrokeredCapsuleHost {
1585    /// Wrap `host` with credential mediation.
1586    pub fn new(host: crate::capsule_host::CapsuleHost, mediator: CredentialMediator) -> Self {
1587        Self { host, mediator }
1588    }
1589
1590    /// The underlying host.
1591    pub fn host(&self) -> &crate::capsule_host::CapsuleHost {
1592        &self.host
1593    }
1594
1595    /// Invoke with brokered secrets: issue one handle per granted
1596    /// connection, inject the tokens into the guest's input, then run
1597    /// the host's ordinary invocation — whose journaled `WasmCall` input
1598    /// is itself the evidence that the guest received tokens, and whose
1599    /// capability enforcement is untouched.
1600    pub async fn invoke(
1601        &self,
1602        invocation: crate::capsule_host::CapsuleInvocation,
1603    ) -> Result<crate::capsule_host::CapsuleOutcome> {
1604        use crate::capsule::CapabilityGrant;
1605        use std::collections::BTreeMap;
1606        let connections: Vec<String> = self
1607            .host
1608            .manifest()
1609            .capabilities
1610            .iter()
1611            .flat_map(|grant| match grant {
1612                CapabilityGrant::Secret { handles } => handles.as_slice(),
1613                _ => &[],
1614            })
1615            .cloned()
1616            .collect();
1617        if connections.is_empty() {
1618            return self.host.invoke(invocation).await;
1619        }
1620        // The smuggling guard runs before any issuance: an input that
1621        // already carries `secrets` is refused with nothing minted.
1622        let mut input = invocation.input.clone();
1623        match &input {
1624            Value::Object(map) => {
1625                if map.contains_key("secrets") {
1626                    return Err(RustyError::Node(
1627                        "capsule input already carries a `secrets` key — the host issues those \
1628                         tokens; a guest supplying its own is refused at admission"
1629                            .to_owned(),
1630                    ));
1631                }
1632            }
1633            _ => {
1634                return Err(RustyError::Node(
1635                    "capsule input must be a JSON object when the manifest grants secrets — \
1636                     the host injects handle tokens under the reserved `secrets` key"
1637                        .to_owned(),
1638                ));
1639            }
1640        }
1641        // The invocation's run is the binding of choice; an embedder's
1642        // mediator run binding is the fallback, never an invented one.
1643        let run_id = invocation
1644            .journal
1645            .as_ref()
1646            .map(|journal| journal.run_id().to_owned())
1647            .or_else(|| self.mediator.run_id().map(str::to_owned));
1648        let mediator = self.mediator.for_run(run_id);
1649        let mut tokens = BTreeMap::new();
1650        for connection_id in connections {
1651            let requirement = CredentialRequirement {
1652                connection_id: connection_id.clone(),
1653                // The `Secret` grant names the connection wholesale —
1654                // no narrowing exists in the grant model, so the handle
1655                // binds the whole consent set.
1656                scopes: BTreeSet::new(),
1657            };
1658            let handle = mediator.issue(&requirement).await.map_err(|denial| {
1659                RustyError::Node(format!(
1660                    "capsule secret grant `{connection_id}` failed at the broker: {denial}"
1661                ))
1662            })?;
1663            tokens.insert(connection_id, handle.token());
1664        }
1665        if let Value::Object(map) = &mut input {
1666            let value = serde_json::to_value(&tokens).map_err(RustyError::Serialization)?;
1667            map.insert("secrets".to_owned(), value);
1668        }
1669        self.host
1670            .invoke(crate::capsule_host::CapsuleInvocation {
1671                input,
1672                journal: invocation.journal,
1673                parent: invocation.parent,
1674                budget: invocation.budget,
1675            })
1676            .await
1677    }
1678}
1679
1680#[cfg(test)]
1681mod tests {
1682    use super::*;
1683
1684    fn ts(millis: i64) -> DateTime<Utc> {
1685        DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
1686    }
1687
1688    fn record() -> ConnectionRecord {
1689        ConnectionRecord {
1690            connection_id: format!("{}{}", CONNECTION_ID_PREFIX, "a".repeat(32)),
1691            provider: ConnectionProvider::Oauth2AuthorizationCode,
1692            subject: Some("user-7".into()),
1693            scopes: BTreeSet::from(["drive.readonly".to_owned(), "drive.write".to_owned()]),
1694            status: ConnectionStatus::Active,
1695            health: ConnectionHealth::default(),
1696            created_at: ts(1_800_000_000_000),
1697            updated_at: ts(1_800_000_000_000),
1698        }
1699    }
1700
1701    fn claims() -> HandleClaims {
1702        HandleClaims {
1703            handle_id: format!("{}{}", HANDLE_ID_PREFIX, "b".repeat(32)),
1704            connection_id: format!("{}{}", CONNECTION_ID_PREFIX, "a".repeat(32)),
1705            tenant: "acme".into(),
1706            run_id: Some("run-1".into()),
1707            scopes: BTreeSet::from(["drive.readonly".to_owned()]),
1708            issued_at: ts(1_800_000_000_000),
1709            expires_at: ts(1_800_000_300_000),
1710        }
1711    }
1712
1713    #[test]
1714    fn minted_ids_fit_their_grammar() {
1715        let connection = new_connection_id();
1716        let handle = new_handle_id();
1717        assert!(minted_id_ok(CONNECTION_ID_PREFIX, &connection));
1718        assert!(minted_id_ok(HANDLE_ID_PREFIX, &handle));
1719        assert!(record().validate().is_ok());
1720        // Hand-shaped ids fail: the grammar is the mint's, not the
1721        // caller's.
1722        let mut bad = record();
1723        bad.connection_id = "conn-XYZ".into();
1724        assert!(bad.validate().is_err());
1725        // The tenant separator is refused in subjects and scopes.
1726        let mut bad = record();
1727        bad.subject = Some("acme/user".into());
1728        assert!(bad.validate().is_err());
1729        let mut bad = record();
1730        bad.scopes.insert("a/b".into());
1731        assert!(bad.validate().is_err());
1732    }
1733
1734    #[test]
1735    fn scope_narrowing_names_exactly_the_missing() {
1736        let ceiling = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
1737        assert!(scopes_missing(&ceiling, &BTreeSet::new()).is_empty());
1738        assert!(scopes_missing(&ceiling, &BTreeSet::from(["a".to_owned()])).is_empty());
1739        assert_eq!(
1740            scopes_missing(&ceiling, &BTreeSet::from(["a".to_owned(), "c".to_owned()])),
1741            vec!["c".to_owned()]
1742        );
1743    }
1744
1745    #[test]
1746    fn token_material_debug_never_shows_bytes() {
1747        let material = TokenMaterial {
1748            access_token: "sk-live-MARKER".into(),
1749            refresh_token: Some("rt-MARKER".into()),
1750            expires_at: Some(ts(1_800_000_300_000)),
1751            client_secret: Some("cs-MARKER".into()),
1752        };
1753        let rendered = format!("{material:?}");
1754        assert!(!rendered.contains("sk-live-MARKER"), "got: {rendered}");
1755        assert!(!rendered.contains("rt-MARKER"), "got: {rendered}");
1756        assert!(!rendered.contains("cs-MARKER"), "got: {rendered}");
1757        assert!(rendered.contains("[redacted]"));
1758        // The sealed form is the store contract: `client_secret` rides
1759        // the same skip-when-absent rule, so pre-wave-4 envelopes are
1760        // byte-stable.
1761        let without = TokenMaterial {
1762            client_secret: None,
1763            ..material.clone()
1764        };
1765        let value = serde_json::to_value(&without).unwrap();
1766        assert!(value.get("client_secret").is_none(), "got: {value}");
1767        let with = serde_json::to_value(&material).unwrap();
1768        assert_eq!(with["client_secret"], serde_json::json!("cs-MARKER"));
1769    }
1770
1771    #[tokio::test]
1772    async fn scripted_provider_exchanges_rotates_and_fails_as_scripted() {
1773        let scopes = BTreeSet::from(["drive.readonly".to_owned()]);
1774        let provider = ScriptedOAuthProvider::new()
1775            .with_token_prefix("proof-token")
1776            .with_code(
1777                "code-1",
1778                TokenGrant {
1779                    access_token: "exchanged-1".into(),
1780                    refresh_token: Some("rt-1".into()),
1781                    expires_at: Some(ts(1_800_003_600_000)),
1782                },
1783            )
1784            .then_refresh_failure(OAuthFailure::transient(
1785                ErrorClass::Transient,
1786                "provider 503",
1787            ))
1788            .then_refresh_failure(OAuthFailure::permanent("invalid_grant"));
1789
1790        // The scripted exchange answers the grant verbatim; an unknown
1791        // code is the provider's permanent `invalid_grant`.
1792        let grant = provider.exchange_code("code-1", &scopes).await.unwrap();
1793        assert_eq!(grant.access_token, "exchanged-1");
1794        let err = provider
1795            .exchange_code("code-unknown", &scopes)
1796            .await
1797            .unwrap_err();
1798        assert!(err.permanent, "got: {err}");
1799
1800        // Refreshes pop the script (transient, then permanent), then fall
1801        // back to rotation: a new access token beneath the same refresh
1802        // token — the provider behavior the stable-id contract is built on.
1803        let record = record();
1804        let material = TokenMaterial {
1805            access_token: "old".into(),
1806            refresh_token: Some("rt-1".into()),
1807            expires_at: None,
1808            client_secret: None,
1809        };
1810        let err = provider.refresh(&record, &material).await.unwrap_err();
1811        assert!(!err.permanent, "got: {err}");
1812        let err = provider.refresh(&record, &material).await.unwrap_err();
1813        assert!(err.permanent, "got: {err}");
1814        let rotated = provider.refresh(&record, &material).await.unwrap();
1815        assert_eq!(rotated.access_token, "proof-token-0");
1816        assert_eq!(rotated.refresh_token.as_deref(), Some("rt-1"));
1817        let rotated = provider.refresh(&record, &material).await.unwrap();
1818        assert_eq!(rotated.access_token, "proof-token-1");
1819        assert_eq!(provider.call_counts(), (2, 4));
1820
1821        // The grant's Debug shows the expiry — never the bytes.
1822        let rendered = format!("{rotated:?}");
1823        assert!(!rendered.contains("proof-token-1"), "got: {rendered}");
1824        assert!(rendered.contains("[redacted]"));
1825    }
1826
1827    #[test]
1828    fn handle_token_round_trips_and_refuses_forged_shapes() {
1829        let handle = CredentialHandle::from_parts(claims(), "cd".repeat(32));
1830        let token = handle.token();
1831        let (parsed, signature) = CredentialHandle::parse_token(&token).unwrap();
1832        assert_eq!(parsed, claims());
1833        assert_eq!(signature, "cd".repeat(32));
1834        // Malformed tokens are the same refusal as forgeries.
1835        for bad in [
1836            "",
1837            "v2.whatever.sig",
1838            "v1.zzzz.sig",
1839            "v1.aGV4.sig",
1840            &token.replace("v1.", "v0."),
1841        ] {
1842            let err = CredentialHandle::parse_token(bad).unwrap_err();
1843            assert!(
1844                matches!(err.reason, BrokerDenialReason::UnknownHandle),
1845                "{bad:?} -> {err:?}"
1846            );
1847        }
1848        // Claims failing the handle grammar (expiry not after issuance)
1849        // are refused at parse, before any signature check.
1850        let mut bad_claims = claims();
1851        bad_claims.expires_at = bad_claims.issued_at;
1852        let bad = CredentialHandle::from_parts(bad_claims, "cd".repeat(32)).token();
1853        assert!(CredentialHandle::parse_token(&bad).is_err());
1854        // The handle's Debug shows claims (metadata) but never the
1855        // signature.
1856        let rendered = format!("{handle:?}");
1857        assert!(rendered.contains("handle_id"));
1858        assert!(!rendered.contains(&"cd".repeat(32)), "got: {rendered}");
1859    }
1860
1861    #[test]
1862    fn expiry_is_at_the_instant() {
1863        let claims = claims();
1864        assert!(!claims.is_expired(ts(1_800_000_299_999)));
1865        assert!(claims.is_expired(ts(1_800_000_300_000)));
1866    }
1867
1868    #[test]
1869    fn denial_payloads_are_attributable_and_byte_free() {
1870        let denial = BrokerDenial::connection_revoked(&record(), "acme", "hdl-x");
1871        match &denial.reason {
1872            BrokerDenialReason::ConnectionRevoked { grant } => {
1873                assert_eq!(
1874                    grant,
1875                    &vec!["drive.readonly".to_owned(), "drive.write".to_owned()]
1876                )
1877            }
1878            other => panic!("expected revoked, got {other:?}"),
1879        }
1880        let value = serde_json::to_value(&denial).unwrap();
1881        assert_eq!(value["reason"], serde_json::json!("connection_revoked"));
1882        assert_eq!(
1883            value["grant"],
1884            serde_json::json!(["drive.readonly", "drive.write"]),
1885            "the internally-tagged reason flattens the revoked grant beside it"
1886        );
1887        assert_eq!(value["tenant"], serde_json::json!("acme"));
1888    }
1889}