Skip to main content

cortexkit_claustrum_client/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Claustrum credential consumer for subc-supervised modules.
4//!
5//! Disable default features to reuse the decoders and watch tracker
6//! without the socket transport or SDK dependency.
7//!
8//! ```
9//! use cortexkit_claustrum_client::{decode_credential_reply, WatchAction, WatchNotice, WatchTracker};
10//!
11//! let credential = decode_credential_reply(serde_json::json!({
12//!     "result": {"payload": [101, 120, 97, 109, 112, 108, 101], "record_version": 1}
13//! })).unwrap();
14//! assert_eq!(credential.expose(), b"example");
15//! let notice = WatchNotice::decode(
16//!     br#"{"kind":"changed","epoch":"launch","seq":1,"view":"v1","keys":"k1"}"#,
17//! ).unwrap();
18//! let mut tracker = WatchTracker::default();
19//! assert_eq!(tracker.notice(&notice), WatchAction::Reread { inventory: true, keys: true });
20//! ```
21
22use std::collections::BTreeMap;
23#[cfg(all(test, feature = "transport"))]
24use std::collections::VecDeque;
25use std::future::Future;
26#[cfg(any(feature = "transport", test))]
27use std::path::Path;
28#[cfg(feature = "transport")]
29use std::path::PathBuf;
30use std::pin::Pin;
31#[cfg(feature = "transport")]
32use std::sync::Arc;
33#[cfg(all(test, feature = "transport"))]
34use std::sync::Mutex;
35#[cfg(feature = "transport")]
36use std::time::Duration;
37
38use base64::Engine;
39#[cfg(any(feature = "transport", test))]
40use serde_json::json;
41use serde_json::Value;
42use sha2::{Digest, Sha256};
43use subc_protocol::{ErrorBody, Flags};
44#[cfg(feature = "transport")]
45use subc_protocol::{Frame, FrameType, Priority};
46#[cfg(feature = "transport")]
47use subc_transport::{authenticate_client, connection_file, read_frame, write_frame};
48#[cfg(feature = "transport")]
49use tokio::net::TcpStream;
50#[cfg(feature = "transport")]
51use tokio::sync::Mutex as AsyncMutex;
52#[cfg(feature = "transport")]
53use tokio::time::Instant;
54
55#[cfg(feature = "consumer")]
56mod consumer;
57mod fleet_epoch;
58mod module_secret;
59mod policy;
60#[cfg(any(feature = "transport", test))]
61mod sensitive_wire;
62#[cfg(feature = "transport")]
63mod transport;
64mod watch;
65pub use fleet_epoch::{
66    decode_fleet_epoch_open_batch_reply, decode_fleet_epoch_open_reply,
67    decode_fleet_epoch_seal_batch_reply, decode_fleet_epoch_seal_reply, FleetEpochOpenRequest,
68    FleetEpochOpenResult, FleetEpochSeal, FleetEpochSealRequest,
69};
70pub use module_secret::{
71    ModuleSecret, ModuleSecretError, ModuleSecretState, ModuleSecretSummary, ModuleSecretWritten,
72    Secret,
73};
74pub use policy::{
75    decode_policy_active_reply, decode_policy_token_reply, ActivePolicy, PolicyToken,
76    PolicyTokenRequest,
77};
78#[cfg(feature = "transport")]
79pub use watch::{PolicyWatch, ScopedWatch};
80pub use watch::{
81    PolicyWatchNotice, ScopedWatchKind, ScopedWatchNotice, ScopedWatchOutcome, WatchAction,
82    WatchNotice, WatchTracker,
83};
84
85#[cfg(feature = "transport")]
86const CREDENTIAL_MODULE_ID: &str = "claustrum";
87#[cfg(any(feature = "transport", test))]
88const CREDENTIAL_GET_OP: &str = "credential.get";
89#[cfg(any(feature = "transport", test))]
90const CREDENTIAL_GET_SCOPED_OP: &str = "credential.get_scoped";
91#[cfg(any(feature = "transport", test))]
92const CREDENTIAL_REPORT_AUTH_FAILURE_OP: &str = "credential.report_auth_failure";
93#[cfg(feature = "transport")]
94const CREDENTIAL_REPORT_CONDITION_OP: &str = "credential.report_condition";
95#[cfg(feature = "transport")]
96const CREDENTIAL_CLEAR_CONDITION_OP: &str = "credential.clear_condition";
97#[cfg(any(feature = "transport", test))]
98const CREDENTIAL_STATUS_OP: &str = "credential.status";
99#[cfg(any(feature = "transport", test))]
100const CREDENTIAL_SIGN_OP: &str = "credential.sign";
101#[cfg(any(feature = "transport", test))]
102const CREDENTIAL_PUBLIC_KEY_OP: &str = "credential.public_key";
103#[cfg(any(feature = "transport", test))]
104const CREDENTIAL_SEAL_OP: &str = "credential.seal";
105#[cfg(any(feature = "transport", test))]
106const CREDENTIAL_LIST_SCOPED_OP: &str = "credential.list_scoped";
107#[cfg(feature = "transport")]
108const CREDENTIAL_READ_TIMEOUT: Duration = Duration::from_secs(3);
109#[cfg(feature = "transport")]
110const CREDENTIAL_CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
111/// A peer daemon restart can leave this daemon holding an outdated routing
112/// generation. The peer silently discards requests from that generation instead
113/// of returning an error, so the request looks the same as a dead peer; this
114/// deadline detects both cases and lets this daemon recover without restarting.
115#[cfg(feature = "transport")]
116const CREDENTIAL_CALL_DEADLINE: Duration = Duration::from_secs(10);
117#[cfg(feature = "transport")]
118const DEFAULT_TRANSIENT_RETRIES: usize = 2;
119
120const MAX_SCOPED_CONDITION_SINCE_MS: u64 = (1 << 53) - 1;
121
122pub type CredentialResolverFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum CredentialErrorClass {
126    AuthRequired,
127    CredentialAbsent,
128    Unauthorized,
129    Permanent,
130    Transient,
131    ContextOverflow,
132    InvalidResponse,
133    Transport,
134    Unavailable,
135    Unclassified,
136}
137
138impl CredentialErrorClass {
139    pub fn classifier_code(self) -> &'static str {
140        match self {
141            Self::AuthRequired => "credential_auth_required",
142            Self::CredentialAbsent => "credential_absent",
143            Self::Unauthorized => "unauthorized",
144            Self::Permanent => "credential_permanent",
145            Self::Transient => "credential_transient",
146            Self::ContextOverflow => "credential_context_overflow",
147            Self::InvalidResponse => "credential_invalid_response",
148            Self::Transport => "credential_transport",
149            Self::Unavailable => "credential_resolver_unavailable",
150            Self::Unclassified => "credential_unclassified",
151        }
152    }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct CredentialResolverError {
157    pub class: CredentialErrorClass,
158    code: String,
159    safe_message: String,
160    established_route_dead: bool,
161}
162
163impl CredentialResolverError {
164    pub fn new(class: CredentialErrorClass, safe_message: impl Into<String>) -> Self {
165        let code = class.classifier_code();
166        Self {
167            class,
168            code: code.to_owned(),
169            safe_message: safe_message.into(),
170            established_route_dead: false,
171        }
172    }
173
174    pub fn unavailable() -> Self {
175        Self::new(
176            CredentialErrorClass::Unavailable,
177            "campaign credential resolver is unavailable",
178        )
179    }
180
181    pub fn transport(message: impl Into<String>) -> Self {
182        Self::new(CredentialErrorClass::Transport, message)
183    }
184
185    fn unclassified(code: impl Into<String>, message: impl Into<String>) -> Self {
186        Self {
187            class: CredentialErrorClass::Unclassified,
188            code: code.into(),
189            safe_message: message.into(),
190            established_route_dead: false,
191        }
192    }
193
194    pub fn code(&self) -> &str {
195        &self.code
196    }
197
198    pub fn retryable(&self) -> bool {
199        matches!(
200            self.class,
201            CredentialErrorClass::Transient | CredentialErrorClass::Transport
202        )
203    }
204
205    pub fn is_transport(&self) -> bool {
206        matches!(
207            self.class,
208            CredentialErrorClass::Transport | CredentialErrorClass::Unavailable
209        )
210    }
211}
212
213impl std::fmt::Display for CredentialResolverError {
214    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        write!(formatter, "{}: {}", self.code(), self.safe_message)
216    }
217}
218
219impl std::error::Error for CredentialResolverError {}
220
221pub struct ResolvedCredential {
222    payload: Vec<u8>,
223    pub record_version: String,
224    pub expires_at_ms: Option<i64>,
225    /// Provider account identifier returned by the vault, when known.
226    pub account_id: Option<String>,
227    /// Provider account email returned by the vault, when captured.
228    pub email: Option<String>,
229    /// Provider organization name returned by the vault, when captured (OAuth logins
230    /// that report one; static API keys carry none).
231    pub org_name: Option<String>,
232    /// Read-time provider metadata, absent on older vaults and non-provider records.
233    pub auth: Option<AuthDescriptor>,
234    pub hosts: Option<Vec<String>>,
235    pub invalid_key: Option<InvalidKeyEvidence>,
236    /// API root for a gateway credential; absent for ordinary provider keys.
237    pub base_url: Option<String>,
238    /// Fixed non-secret request headers, including an empty map on gateways without any.
239    pub headers: Option<BTreeMap<String, String>>,
240}
241
242/// How a provider accepts a key in a request header.
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct AuthDescriptor {
245    pub header: String,
246    pub scheme: AuthScheme,
247}
248
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub enum AuthScheme {
251    Bearer,
252    Raw,
253}
254
255/// An observation of a rejected key, not a rule evaluated by the vault.
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct InvalidKeyEvidence {
258    pub status: u16,
259    pub error_code: Option<String>,
260    pub error_code_field: Option<String>,
261}
262
263/// Plaintext readiness metadata for a scoped credential. This never contains or
264/// mints credential material, so callers can poll repair progress safely.
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct CredentialStatus {
267    pub ready: bool,
268    pub record_version: Option<String>,
269    pub stale_pending: bool,
270    pub last_error_code: Option<String>,
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct CredentialSignature {
275    pub signature_hex: String,
276    pub key_id: String,
277}
278
279/// The kind of key a `credential.public_key` reply carries.
280///
281/// One vault operation serves the public half of both vault-held key kinds, so the
282/// algorithm is a closed type rather than a string: a caller that expects a signing
283/// verifier must match `Ed25519` and cannot mistake an X25519 encryption key for one.
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
285pub enum PublicKeyAlgorithm {
286    /// An Ed25519 signing key's public half, which verifies `credential.sign` output.
287    Ed25519,
288    /// An X25519 KEM key's public half, which HPKE senders and recipients use with
289    /// `credential.seal` and `credential.open`.
290    X25519,
291}
292
293impl PublicKeyAlgorithm {
294    /// The `algorithm` string the vault sends for this kind.
295    pub fn as_str(self) -> &'static str {
296        match self {
297            Self::Ed25519 => "ed25519",
298            Self::X25519 => "x25519",
299        }
300    }
301}
302
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct CredentialPublicKey {
305    pub public_key_hex: String,
306    pub key_id: String,
307    pub algorithm: PublicKeyAlgorithm,
308}
309
310/// One `credential.seal` request: seal `plaintext` to `recipient_public_key` in RFC 9180
311/// Auth mode, with the vault-held KEM key `credential_id` as the sender. The caller's
312/// route principal must hold an exact `seal` grant for that key.
313///
314/// No `Debug`: the plaintext is the message being protected.
315#[derive(Clone, Copy)]
316pub struct SealRequest<'a> {
317    pub credential_id: &'a str,
318    /// The recipient's X25519 public key.
319    pub recipient_public_key: &'a [u8; 32],
320    /// HPKE `info`, at most 1 KiB.
321    pub info: &'a [u8],
322    /// Associated data, at most 1 KiB.
323    pub aad: &'a [u8],
324    /// At most 64 KiB.
325    pub plaintext: &'a [u8],
326}
327
328/// A `credential.seal` result. The recipient opens `ciphertext` with `enc`, the same
329/// `info` and `aad`, and the public half of the key `key_id` names.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct CredentialSeal {
332    /// The 32-byte encapsulated ephemeral key.
333    pub enc: Vec<u8>,
334    /// ChaCha20-Poly1305 output: the plaintext's length plus a 16-byte tag.
335    pub ciphertext: Vec<u8>,
336    /// The sealing key's id, as `credential.public_key` reports it.
337    pub key_id: String,
338}
339
340/// The metadata `credential.list_scoped` returns for the caller's own grants.
341/// It carries identity and protocol only, never secret material.
342#[derive(Debug, Clone, Default, PartialEq, Eq)]
343pub struct ScopedCredentialListing {
344    pub credentials: Vec<ListedCredential>,
345    /// Row-local decode failures; usable rows in the same reply remain available.
346    pub undecodable_credentials: Vec<String>,
347    pub grant_tuples: Vec<ListedGrant>,
348    /// Tuple-local decode failures; malformed tuples never become usable grants.
349    pub undecodable_grants: Vec<String>,
350    /// Digest over the listed rows and grants. It moves when grants or listed
351    /// metadata (including conditions) change, but not when a token is refreshed.
352    pub view: String,
353}
354
355/// One vault row as `credential.list_scoped` describes it. The vault fills in
356/// `account_id`, `refresh_adapter`, the plan tier and the condition only for rows
357/// the caller may list or read. Learned `org_id` has the same visibility.
358#[derive(Debug, Clone, Default, PartialEq, Eq)]
359pub struct ListedCredential {
360    /// Catalog service key, distinct from routing provider ids.
361    pub provider: Option<String>,
362    /// Read-time join key for Fusiform's provider card, not a stored routing id.
363    pub fusiform_provider_id: Option<String>,
364    pub hosts: Option<Vec<String>>,
365    pub incarnation: Option<String>,
366    pub plan_tier_observed_at_ms: Option<i64>,
367    /// Operator-supplied effective start; fall back to the observation time if absent.
368    pub plan_tier_since_ms: Option<u64>,
369    /// The vault credential ID, returned verbatim (for example `oauth:anthropic:yiyi`).
370    pub id: String,
371    pub categories: Vec<String>,
372    pub credential_type: String,
373    /// Model vendors, not Fusiform provider IDs. Never use these for reachability.
374    pub serves: Vec<String>,
375    /// Stored routing ids, defaulted from the catalog at creation or operator-assigned.
376    /// Missing on older vaults; empty when the credential is unmapped.
377    pub provider_ids: Vec<String>,
378    pub auth_method: Option<String>,
379    pub refresh_adapter: Option<String>,
380    pub state: String,
381    pub record_version: u64,
382    pub operations: Vec<String>,
383    pub account_id: Option<String>,
384    pub email: Option<String>,
385    pub org_name: Option<String>,
386    /// Provider organization of this API key; independent of `account_id`.
387    pub org_id: Option<String>,
388    /// The subscription plan to price this account by (for example `max_20x` or
389    /// `pro_200`). `None` means unknown: an API key, a provider that reports no plan,
390    /// or a vault older than plan tiers.
391    pub plan_tier: Option<String>,
392    /// Where `plan_tier` came from: `operator` (set with `ck auth set-plan`, which wins)
393    /// or `detected` (read from the provider). Present only alongside `plan_tier`.
394    pub plan_tier_source: Option<String>,
395    pub condition: Option<ListedCredentialCondition>,
396    pub github_app: Option<ListedGitHubApp>,
397}
398
399/// GitHub App identity recorded by the vault for a listed credential.
400#[derive(Debug, Clone, PartialEq, Eq)]
401pub struct ListedGitHubApp {
402    /// Decimal App ID kept as a string so it can be used without precision loss.
403    pub app_id: String,
404    pub slug: String,
405    /// Present with `created_at_ms` and `agent` only for a vault-created App.
406    pub created_by: Option<String>,
407    pub created_at_ms: Option<u64>,
408    pub agent: Option<String>,
409}
410
411/// A login condition visible in a scoped listing, without the action link or reporter.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub struct ListedCredentialCondition {
414    /// Open-ended reason code; newer vaults can report reasons this client does not know.
415    pub reason: String,
416    /// When this reason was first set, as Unix epoch milliseconds.
417    pub since_ms: u64,
418}
419
420/// One grant the caller holds: which selector it names and which operation it allows.
421#[derive(Debug, Clone, PartialEq, Eq)]
422pub struct ListedGrant {
423    pub selector_kind: String,
424    pub selector: String,
425    pub operation: String,
426}
427
428impl ResolvedCredential {
429    pub fn new(payload: Vec<u8>, record_version: String, expires_at_ms: Option<i64>) -> Self {
430        Self::new_with_identity(payload, record_version, expires_at_ms, None, None, None)
431    }
432
433    fn new_with_identity(
434        payload: Vec<u8>,
435        record_version: String,
436        expires_at_ms: Option<i64>,
437        account_id: Option<String>,
438        email: Option<String>,
439        org_name: Option<String>,
440    ) -> Self {
441        Self {
442            payload,
443            record_version,
444            expires_at_ms,
445            account_id,
446            email,
447            org_name,
448            auth: None,
449            hosts: None,
450            invalid_key: None,
451            base_url: None,
452            headers: None,
453        }
454    }
455
456    pub fn expose(&self) -> &[u8] {
457        &self.payload
458    }
459}
460
461impl std::fmt::Debug for ResolvedCredential {
462    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
463        formatter
464            .debug_struct("ResolvedCredential")
465            .field("payload", &"[REDACTED]")
466            .field("record_version", &self.record_version)
467            .field("expires_at_ms", &self.expires_at_ms)
468            .field("account_id", &self.account_id)
469            .field("email", &self.email)
470            .field("org_name", &self.org_name)
471            .field("auth", &self.auth)
472            .field("hosts", &self.hosts)
473            .field("invalid_key", &self.invalid_key)
474            .field("base_url", &self.base_url)
475            // Gateway header values are meant to be non-secret, but an operator can still
476            // paste a token into one, so a log line made from this shows names only.
477            .field(
478                "headers",
479                &self
480                    .headers
481                    .as_ref()
482                    .map(|headers| headers.keys().collect::<Vec<_>>()),
483            )
484            .finish()
485    }
486}
487
488impl Drop for ResolvedCredential {
489    fn drop(&mut self) {
490        self.payload.fill(0);
491    }
492}
493
494pub trait CredentialResolver: Send + Sync {
495    /// `raw_handle` is the capability stored only in module configuration. Callers
496    /// must use the config's public credential name in reports and diagnostics.
497    fn resolve<'a>(
498        &'a self,
499        raw_handle: &'a str,
500        min_ttl_ms: Option<u64>,
501        force_refresh: bool,
502    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>>;
503
504    /// Reads a credential by its vault ID under the route's reserved principal.
505    /// Unlike `resolve`, this never accepts a raw capability handle.
506    fn get_scoped<'a>(
507        &'a self,
508        credential_id: &'a str,
509    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>>;
510
511    /// Reads a scoped credential only when the served token has at least this much
512    /// remaining lifetime. Implementations that cannot enforce the bound fail closed.
513    fn get_scoped_with_min_ttl<'a>(
514        &'a self,
515        _credential_id: &'a str,
516        _min_ttl_ms: u64,
517    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
518        Box::pin(async { Err(CredentialResolverError::unavailable()) })
519    }
520
521    /// Reports a provider auth failure for the credential ID and served version.
522    /// The vault accepts only provider status 401 or 403; any other status is
523    /// rejected locally before a request is sent.
524    /// `accepted` means the vault accepted the report, not that it changed state: a
525    /// stale `record_version` is accepted and ignored. Read again after reporting; if
526    /// the version has not moved, stop rather than retrying in a loop. For a static
527    /// API key, a 401 means the key is dead.
528    fn report_auth_failure<'a>(
529        &'a self,
530        _credential_id: &'a str,
531        _record_version: u64,
532        _provider_status: u16,
533    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
534        Box::pin(async { Err(CredentialResolverError::unavailable()) })
535    }
536
537    /// Reports a lasting provider condition on the credential and served version.
538    /// The vault decides whether to admit the reason, status and link. `true` means
539    /// it accepted the report, not necessarily that it changed the condition.
540    /// The client does not retry: a lost reply does not tell us whether the vault committed.
541    fn report_condition<'a>(
542        &'a self,
543        _credential_id: &'a str,
544        _record_version: u64,
545        _reason: &'a str,
546        _provider_status: u16,
547        _action_url: Option<&'a str>,
548        _enrollment_token: Option<&'a str>,
549    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
550        Box::pin(async { Err(CredentialResolverError::unavailable()) })
551    }
552
553    /// Reports that the served version worked. `true` means the vault removed a
554    /// condition; `false` means there was none to clear or the version did not match.
555    /// The client does not retry: a replay could erase a condition reported after the clear.
556    fn clear_condition<'a>(
557        &'a self,
558        _credential_id: &'a str,
559        _record_version: u64,
560        _enrollment_token: Option<&'a str>,
561    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
562        Box::pin(async { Err(CredentialResolverError::unavailable()) })
563    }
564
565    /// Returns status for a vault ID under the reserved principal without minting.
566    fn status_scoped<'a>(
567        &'a self,
568        _credential_id: &'a str,
569    ) -> CredentialResolverFuture<'a, Result<CredentialStatus, CredentialResolverError>> {
570        Box::pin(async { Err(CredentialResolverError::unavailable()) })
571    }
572
573    fn sign<'a>(
574        &'a self,
575        _credential_id: &'a str,
576        _payload: &'a [u8],
577    ) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
578        Box::pin(async { Err(CredentialResolverError::unavailable()) })
579    }
580
581    fn public_key<'a>(
582        &'a self,
583        _credential_id: &'a str,
584    ) -> CredentialResolverFuture<'a, Result<CredentialPublicKey, CredentialResolverError>> {
585        Box::pin(async { Err(CredentialResolverError::unavailable()) })
586    }
587
588    /// Seals one message under a vault-held KEM key (`credential.seal`). Makes exactly
589    /// one attempt, even on a retryable error: every seal is a fresh ciphertext with its
590    /// own audit row, so retrying is the caller's decision (its own backoff, its own
591    /// record of what was sent), never something the client does silently.
592    fn seal<'a>(
593        &'a self,
594        _request: SealRequest<'a>,
595    ) -> CredentialResolverFuture<'a, Result<CredentialSeal, CredentialResolverError>> {
596        Box::pin(async { Err(CredentialResolverError::unavailable()) })
597    }
598
599    /// Opens a dedicated scoped watch. The caller owns reconnection and re-reading.
600    #[cfg(feature = "transport")]
601    fn watch_scoped<'a>(
602        &'a self,
603        _enrollment_token: Option<&'a str>,
604    ) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
605        Box::pin(async { Err(CredentialResolverError::unavailable()) })
606    }
607
608    /// Lists the vault rows covered by this principal's own grants, metadata only.
609    fn list_scoped(
610        &self,
611    ) -> CredentialResolverFuture<'_, Result<ScopedCredentialListing, CredentialResolverError>>
612    {
613        Box::pin(async { Err(CredentialResolverError::unavailable()) })
614    }
615}
616
617/// Fail-closed resolver used when no live claustrum route is available.
618#[derive(Debug, Default)]
619pub struct UnavailableCredentialResolver;
620
621impl CredentialResolver for UnavailableCredentialResolver {
622    fn resolve<'a>(
623        &'a self,
624        _raw_handle: &'a str,
625        _min_ttl_ms: Option<u64>,
626        _force_refresh: bool,
627    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
628        Box::pin(async { Err(CredentialResolverError::unavailable()) })
629    }
630
631    fn get_scoped<'a>(
632        &'a self,
633        _credential_id: &'a str,
634    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
635        Box::pin(async { Err(CredentialResolverError::unavailable()) })
636    }
637}
638
639#[doc(hidden)]
640pub trait CredentialGetTarget: Send + Sync {
641    fn credential_get<'a>(
642        &'a self,
643        raw_handle: &'a str,
644        min_ttl_ms: Option<u64>,
645        force_refresh: bool,
646    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
647
648    fn credential_get_scoped<'a>(
649        &'a self,
650        _credential_id: &'a str,
651    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
652        Box::pin(async {
653            Err(CredentialResolverError::new(
654                CredentialErrorClass::Permanent,
655                "credential scoped reads are unavailable",
656            ))
657        })
658    }
659
660    fn credential_get_scoped_with_min_ttl<'a>(
661        &'a self,
662        _credential_id: &'a str,
663        _min_ttl_ms: u64,
664    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
665        Box::pin(async {
666            Err(CredentialResolverError::new(
667                CredentialErrorClass::Unavailable,
668                "credential scoped reads with a minimum TTL are unavailable",
669            ))
670        })
671    }
672
673    fn credential_report_auth_failure<'a>(
674        &'a self,
675        _credential_id: &'a str,
676        _record_version: u64,
677        _provider_status: u16,
678    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
679        Box::pin(async {
680            Err(CredentialResolverError::new(
681                CredentialErrorClass::Unavailable,
682                "credential auth-failure reports are unavailable",
683            ))
684        })
685    }
686
687    fn credential_report_condition<'a>(
688        &'a self,
689        _credential_id: &'a str,
690        _record_version: u64,
691        _reason: &'a str,
692        _provider_status: u16,
693        _action_url: Option<&'a str>,
694        _enrollment_token: Option<&'a str>,
695    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
696        Box::pin(async { Err(CredentialResolverError::unavailable()) })
697    }
698
699    fn credential_clear_condition<'a>(
700        &'a self,
701        _credential_id: &'a str,
702        _record_version: u64,
703        _enrollment_token: Option<&'a str>,
704    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
705        Box::pin(async { Err(CredentialResolverError::unavailable()) })
706    }
707
708    fn credential_status<'a>(
709        &'a self,
710        _credential_id: &'a str,
711    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
712        Box::pin(async {
713            Err(CredentialResolverError::new(
714                CredentialErrorClass::Permanent,
715                "credential status reads are unavailable",
716            ))
717        })
718    }
719
720    fn credential_sign<'a>(
721        &'a self,
722        _credential_id: &'a str,
723        _payload: &'a [u8],
724    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
725        Box::pin(async {
726            Err(CredentialResolverError::new(
727                CredentialErrorClass::Permanent,
728                "credential signing is unavailable",
729            ))
730        })
731    }
732
733    fn credential_public_key<'a>(
734        &'a self,
735        _credential_id: &'a str,
736    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
737        Box::pin(async {
738            Err(CredentialResolverError::new(
739                CredentialErrorClass::Permanent,
740                "credential public-key reads are unavailable",
741            ))
742        })
743    }
744
745    fn credential_seal<'a>(
746        &'a self,
747        _request: SealRequest<'a>,
748    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
749        Box::pin(async {
750            Err(CredentialResolverError::new(
751                CredentialErrorClass::Permanent,
752                "credential sealing is unavailable",
753            ))
754        })
755    }
756
757    #[cfg(feature = "transport")]
758    fn credential_watch_scoped<'a>(
759        &'a self,
760        _enrollment_token: Option<&'a str>,
761    ) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
762        Box::pin(async { Err(CredentialResolverError::unavailable()) })
763    }
764
765    fn credential_list_scoped(
766        &self,
767    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
768        Box::pin(async {
769            Err(CredentialResolverError::new(
770                CredentialErrorClass::Permanent,
771                "credential listing is unavailable",
772            ))
773        })
774    }
775}
776
777/// Live claustrum-backed resolver. It lazily opens one soft outbound route and
778/// retries transient or transport errors for credential operations;
779/// scoped reads return the first error because each consumer owns its one-shot
780/// redial bound. Auth and permanent failures always return immediately.
781/// Login condition reports and clears are never retried.
782/// Module-secret methods are single-shot and use an additional route on the
783/// caller's SDK consumer without changing the ordinary credential route.
784#[cfg(feature = "transport")]
785pub struct ClaustrumCredentialResolver {
786    target: Arc<dyn CredentialGetTarget>,
787    live_target: Option<Arc<LiveCredentialGetTarget>>,
788    module_secret_target: Option<Arc<LiveCredentialGetTarget>>,
789    transient_retries: usize,
790}
791
792#[cfg(feature = "transport")]
793impl std::fmt::Debug for ClaustrumCredentialResolver {
794    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
795        formatter
796            .debug_struct("ClaustrumCredentialResolver")
797            .field("target", &CREDENTIAL_MODULE_ID)
798            .field("transient_retries", &self.transient_retries)
799            .finish()
800    }
801}
802
803#[cfg(feature = "transport")]
804impl ClaustrumCredentialResolver {
805    /// Creates a lazy resolver for a supervised consumer. Bind identity carries
806    /// harness/session labels only; a route's project comes from its session scope.
807    /// Claim-bound modules must use `with_consumer` instead (feature `consumer`).
808    pub fn new(connection_file_path: PathBuf, consumer_module_id: impl Into<String>) -> Self {
809        let target = Arc::new(LiveCredentialGetTarget::new(
810            Arc::new(LiveCredentialConnector {
811                connection_file_path,
812                consumer_module_id: consumer_module_id.into(),
813            }),
814            CREDENTIAL_CALL_DEADLINE,
815        ));
816        Self {
817            target: target.clone(),
818            live_target: Some(target.clone()),
819            module_secret_target: Some(target),
820            transient_retries: DEFAULT_TRANSIENT_RETRIES,
821        }
822    }
823
824    /// Creates a resolver with an explicit supervised consumer module ID.
825    /// Claim-bound modules must use `with_consumer` instead (feature `consumer`).
826    #[doc(hidden)]
827    pub fn with_live_consumer_identity(
828        connection_file_path: PathBuf,
829        consumer_module_id: String,
830    ) -> Self {
831        Self::new(connection_file_path, consumer_module_id)
832    }
833
834    /// Uses the caller's SDK connection, including its module claim binding.
835    /// Legacy module-ID/launch-nonce identity overrides would conflict with a
836    /// claim-bound connection, so this resolver leaves identity binding to the SDK.
837    /// The consumer is shared because `SubcConsumer` is not `Clone`; dropping
838    /// the resolver never closes the caller's connection or unrelated routes.
839    #[cfg(feature = "consumer")]
840    pub fn with_consumer(consumer: Arc<subc_client_rs::SubcConsumer>) -> Self {
841        let target = Arc::new(LiveCredentialGetTarget::new(
842            Arc::new(consumer::ConsumerConnector(consumer.clone())),
843            CREDENTIAL_CALL_DEADLINE,
844        ));
845        Self {
846            module_secret_target: Some(Arc::new(LiveCredentialGetTarget::new(
847                Arc::new(consumer::ModuleSecretConnector(consumer)),
848                CREDENTIAL_CALL_DEADLINE,
849            ))),
850            target: target.clone(),
851            live_target: Some(target),
852            transient_retries: DEFAULT_TRANSIENT_RETRIES,
853        }
854    }
855
856    #[doc(hidden)]
857    async fn retry_call<T, F: Future<Output = Result<T, CredentialResolverError>>>(
858        &self,
859        should_retry: impl Fn(&CredentialResolverError) -> bool,
860        mut attempt: impl FnMut() -> F,
861    ) -> Result<T, CredentialResolverError> {
862        let mut retried_dead_route = false;
863        for _ in 0..self.transient_retries {
864            match attempt().await {
865                Err(error) if should_retry(&error) => {
866                    if error.established_route_dead {
867                        if retried_dead_route {
868                            return Err(error);
869                        }
870                        retried_dead_route = true;
871                    }
872                    tokio::time::sleep(Duration::from_millis(100)).await;
873                }
874                result => return result,
875            }
876        }
877        attempt().await
878    }
879
880    pub fn with_target(target: Arc<dyn CredentialGetTarget>, transient_retries: usize) -> Self {
881        Self {
882            target,
883            live_target: None,
884            module_secret_target: None,
885            transient_retries,
886        }
887    }
888}
889
890#[cfg(feature = "transport")]
891impl CredentialResolver for ClaustrumCredentialResolver {
892    fn watch_scoped<'a>(
893        &'a self,
894        enrollment_token: Option<&'a str>,
895    ) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
896        self.target.credential_watch_scoped(enrollment_token)
897    }
898
899    fn resolve<'a>(
900        &'a self,
901        raw_handle: &'a str,
902        min_ttl_ms: Option<u64>,
903        force_refresh: bool,
904    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
905        Box::pin(self.retry_call(
906            |error| error.class == CredentialErrorClass::Transport,
907            move || async move {
908                self.target
909                    .credential_get(raw_handle, min_ttl_ms, force_refresh)
910                    .await
911                    .and_then(decode_credential_reply)
912            },
913        ))
914    }
915
916    fn get_scoped<'a>(
917        &'a self,
918        credential_id: &'a str,
919    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
920        Box::pin(async move {
921            self.target
922                .credential_get_scoped(credential_id)
923                .await
924                .and_then(decode_credential_reply)
925        })
926    }
927
928    fn get_scoped_with_min_ttl<'a>(
929        &'a self,
930        credential_id: &'a str,
931        min_ttl_ms: u64,
932    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
933        Box::pin(async move {
934            self.target
935                .credential_get_scoped_with_min_ttl(credential_id, min_ttl_ms)
936                .await
937                .and_then(decode_credential_reply)
938        })
939    }
940
941    fn report_auth_failure<'a>(
942        &'a self,
943        credential_id: &'a str,
944        record_version: u64,
945        provider_status: u16,
946    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
947        Box::pin(async move {
948            if !matches!(provider_status, 401 | 403) {
949                return Err(CredentialResolverError::new(
950                    CredentialErrorClass::Permanent,
951                    "provider status must be 401 or 403",
952                ));
953            }
954            self.target
955                .credential_report_auth_failure(credential_id, record_version, provider_status)
956                .await
957                .and_then(decode_report_auth_failure_reply)
958        })
959    }
960
961    fn report_condition<'a>(
962        &'a self,
963        credential_id: &'a str,
964        record_version: u64,
965        reason: &'a str,
966        provider_status: u16,
967        action_url: Option<&'a str>,
968        enrollment_token: Option<&'a str>,
969    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
970        Box::pin(async move {
971            self.target
972                .credential_report_condition(
973                    credential_id,
974                    record_version,
975                    reason,
976                    provider_status,
977                    action_url,
978                    enrollment_token,
979                )
980                .await
981                .and_then(decode_report_condition_reply)
982        })
983    }
984
985    fn clear_condition<'a>(
986        &'a self,
987        credential_id: &'a str,
988        record_version: u64,
989        enrollment_token: Option<&'a str>,
990    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
991        Box::pin(async move {
992            self.target
993                .credential_clear_condition(credential_id, record_version, enrollment_token)
994                .await
995                .and_then(decode_clear_condition_reply)
996        })
997    }
998
999    fn status_scoped<'a>(
1000        &'a self,
1001        credential_id: &'a str,
1002    ) -> CredentialResolverFuture<'a, Result<CredentialStatus, CredentialResolverError>> {
1003        Box::pin(async move {
1004            self.target
1005                .credential_status(credential_id)
1006                .await
1007                .and_then(decode_credential_status_reply)
1008        })
1009    }
1010
1011    fn sign<'a>(
1012        &'a self,
1013        credential_id: &'a str,
1014        payload: &'a [u8],
1015    ) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
1016        Box::pin(
1017            self.retry_call(CredentialResolverError::retryable, || async {
1018                self.target
1019                    .credential_sign(credential_id, payload)
1020                    .await
1021                    .and_then(decode_signature_reply)
1022            }),
1023        )
1024    }
1025
1026    fn public_key<'a>(
1027        &'a self,
1028        credential_id: &'a str,
1029    ) -> CredentialResolverFuture<'a, Result<CredentialPublicKey, CredentialResolverError>> {
1030        Box::pin(
1031            self.retry_call(CredentialResolverError::retryable, || async {
1032                self.target
1033                    .credential_public_key(credential_id)
1034                    .await
1035                    .and_then(decode_public_key_reply)
1036            }),
1037        )
1038    }
1039
1040    fn seal<'a>(
1041        &'a self,
1042        request: SealRequest<'a>,
1043    ) -> CredentialResolverFuture<'a, Result<CredentialSeal, CredentialResolverError>> {
1044        // One attempt only; see the trait method for why seal is never retried here.
1045        Box::pin(async move {
1046            self.target
1047                .credential_seal(request)
1048                .await
1049                .and_then(decode_seal_reply)
1050        })
1051    }
1052
1053    fn list_scoped(
1054        &self,
1055    ) -> CredentialResolverFuture<'_, Result<ScopedCredentialListing, CredentialResolverError>>
1056    {
1057        // One attempt per call: the caller polls on its own cadence, so a failed
1058        // listing is simply retried at the next poll.
1059        Box::pin(async move {
1060            self.target
1061                .credential_list_scoped()
1062                .await
1063                .and_then(decode_list_scoped_reply)
1064        })
1065    }
1066}
1067
1068#[cfg(feature = "transport")]
1069trait CredentialConsumerConnection: Send {
1070    fn sensitive_request(
1071        &mut self,
1072        _request: Secret<Vec<u8>>,
1073    ) -> CredentialResolverFuture<'_, Result<Secret<Vec<u8>>, CredentialResolverError>> {
1074        Box::pin(async { Err(CredentialResolverError::unavailable()) })
1075    }
1076    fn into_scoped_watch(
1077        self: Box<Self>,
1078        _enrollment_token: Option<String>,
1079    ) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
1080        Box::pin(async { Err(CredentialResolverError::unavailable()) })
1081    }
1082
1083    fn into_policy_watch(
1084        self: Box<Self>,
1085    ) -> CredentialResolverFuture<'static, Result<PolicyWatch, CredentialResolverError>> {
1086        Box::pin(async { Err(CredentialResolverError::unavailable()) })
1087    }
1088
1089    fn credential_get<'a>(
1090        &'a mut self,
1091        raw_handle: &'a str,
1092        min_ttl_ms: Option<u64>,
1093        force_refresh: bool,
1094    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1095        Box::pin(async move {
1096            self.credential_request(
1097                credential_get_request(raw_handle, min_ttl_ms, force_refresh),
1098                "credential.get",
1099            )
1100            .await
1101        })
1102    }
1103
1104    fn credential_get_scoped<'a>(
1105        &'a mut self,
1106        credential_id: &'a str,
1107        min_ttl_ms: Option<u64>,
1108    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1109        Box::pin(async move {
1110            self.credential_request(
1111                credential_get_scoped_request(credential_id, min_ttl_ms),
1112                CREDENTIAL_GET_SCOPED_OP,
1113            )
1114            .await
1115        })
1116    }
1117
1118    fn credential_report_auth_failure<'a>(
1119        &'a mut self,
1120        credential_id: &'a str,
1121        record_version: u64,
1122        provider_status: u16,
1123    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1124        Box::pin(async move {
1125            self.credential_request(
1126                credential_report_auth_failure_request(
1127                    credential_id,
1128                    record_version,
1129                    provider_status,
1130                ),
1131                CREDENTIAL_REPORT_AUTH_FAILURE_OP,
1132            )
1133            .await
1134        })
1135    }
1136
1137    fn credential_status<'a>(
1138        &'a mut self,
1139        credential_id: &'a str,
1140    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1141        Box::pin(async move {
1142            self.credential_request(
1143                credential_status_request(credential_id),
1144                CREDENTIAL_STATUS_OP,
1145            )
1146            .await
1147        })
1148    }
1149
1150    fn credential_sign<'a>(
1151        &'a mut self,
1152        credential_id: &'a str,
1153        payload: &'a [u8],
1154    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1155        Box::pin(async move {
1156            self.credential_request(
1157                credential_sign_request(credential_id, payload),
1158                CREDENTIAL_SIGN_OP,
1159            )
1160            .await
1161        })
1162    }
1163
1164    fn credential_public_key<'a>(
1165        &'a mut self,
1166        credential_id: &'a str,
1167    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1168        Box::pin(async move {
1169            self.credential_request(
1170                credential_public_key_request(credential_id),
1171                CREDENTIAL_PUBLIC_KEY_OP,
1172            )
1173            .await
1174        })
1175    }
1176
1177    fn credential_seal<'a>(
1178        &'a mut self,
1179        request: SealRequest<'a>,
1180    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1181        Box::pin(async move {
1182            self.credential_request(credential_seal_request(request), CREDENTIAL_SEAL_OP)
1183                .await
1184        })
1185    }
1186
1187    fn credential_list_scoped(
1188        &mut self,
1189    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
1190        self.credential_request(credential_list_scoped_request(), CREDENTIAL_LIST_SCOPED_OP)
1191    }
1192
1193    fn credential_request<'a>(
1194        &'a mut self,
1195        _request: Value,
1196        _operation: &'a str,
1197    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1198        Box::pin(async { Err(CredentialResolverError::unavailable()) })
1199    }
1200}
1201
1202#[cfg(feature = "transport")]
1203trait CredentialConsumerConnector: Send + Sync {
1204    fn connect<'a>(
1205        &'a self,
1206    ) -> CredentialResolverFuture<
1207        'a,
1208        Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
1209    >;
1210
1211    fn connect_policy_watch(
1212        &self,
1213    ) -> CredentialResolverFuture<
1214        '_,
1215        Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
1216    > {
1217        self.connect()
1218    }
1219}
1220
1221#[cfg(feature = "transport")]
1222struct LiveCredentialConnector {
1223    connection_file_path: PathBuf,
1224    consumer_module_id: String,
1225}
1226
1227#[cfg(feature = "transport")]
1228impl CredentialConsumerConnector for LiveCredentialConnector {
1229    fn connect<'a>(
1230        &'a self,
1231    ) -> CredentialResolverFuture<
1232        'a,
1233        Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
1234    > {
1235        Box::pin(async move {
1236            ClaustrumConsumer::connect(&self.connection_file_path, &self.consumer_module_id)
1237                .await
1238                .map(|consumer| Box::new(consumer) as Box<dyn CredentialConsumerConnection>)
1239        })
1240    }
1241}
1242
1243#[cfg(feature = "transport")]
1244struct LiveCredentialGetTarget {
1245    connector: Arc<dyn CredentialConsumerConnector>,
1246    call_deadline: Duration,
1247    consumer: AsyncMutex<Option<Box<dyn CredentialConsumerConnection>>>,
1248}
1249
1250#[cfg(feature = "transport")]
1251impl LiveCredentialGetTarget {
1252    fn new(connector: Arc<dyn CredentialConsumerConnector>, call_deadline: Duration) -> Self {
1253        Self {
1254            connector,
1255            call_deadline,
1256            consumer: AsyncMutex::new(None),
1257        }
1258    }
1259
1260    async fn connect_if_needed(
1261        &self,
1262        consumer: &mut Option<Box<dyn CredentialConsumerConnection>>,
1263    ) -> Result<(), CredentialResolverError> {
1264        if consumer.is_none() {
1265            *consumer = Some(self.connector.connect().await?);
1266        }
1267        Ok(())
1268    }
1269
1270    async fn unary_call<P, T>(
1271        &self,
1272        operation: &str,
1273        params: P,
1274        send: impl for<'a> FnOnce(
1275            &'a mut dyn CredentialConsumerConnection,
1276            &'a P,
1277        )
1278            -> CredentialResolverFuture<'a, Result<T, CredentialResolverError>>,
1279    ) -> Result<T, CredentialResolverError> {
1280        let deadline = Instant::now() + self.call_deadline;
1281        let mut consumer = tokio::time::timeout_at(deadline, self.consumer.lock())
1282            .await
1283            .map_err(|_| Self::deadline_error(operation))?;
1284        // Tokio can grant the lock on the same poll as an expired timer. No
1285        // request used the held route, so leave it cached on a queue timeout.
1286        if Instant::now() >= deadline {
1287            return Err(Self::deadline_error(operation));
1288        }
1289        let result = tokio::time::timeout_at(deadline, async {
1290            self.connect_if_needed(&mut consumer).await?;
1291            if Instant::now() >= deadline {
1292                return Err(Self::deadline_error(operation));
1293            }
1294            let result = send(
1295                consumer
1296                    .as_deref_mut()
1297                    .expect("credential consumer initialized"),
1298                &params,
1299            )
1300            .await;
1301            if Instant::now() >= deadline {
1302                Err(Self::deadline_error(operation))
1303            } else {
1304                result
1305            }
1306        })
1307        .await
1308        .unwrap_or_else(|_| Err(Self::deadline_error(operation)));
1309        Self::clear_failed_transport(&mut consumer, &result);
1310        result
1311    }
1312
1313    async fn get_scoped(
1314        &self,
1315        credential_id: &str,
1316        min_ttl_ms: Option<u64>,
1317    ) -> Result<Value, CredentialResolverError> {
1318        self.unary_call(
1319            CREDENTIAL_GET_SCOPED_OP,
1320            (credential_id, min_ttl_ms),
1321            |consumer, &(id, ttl)| consumer.credential_get_scoped(id, ttl),
1322        )
1323        .await
1324    }
1325
1326    async fn sensitive_request(
1327        &self,
1328        request: Secret<Vec<u8>>,
1329        operation: &str,
1330    ) -> Result<Secret<Vec<u8>>, CredentialResolverError> {
1331        self.unary_call(operation, (), move |consumer, &()| {
1332            consumer.sensitive_request(request)
1333        })
1334        .await
1335    }
1336
1337    async fn condition_request(
1338        &self,
1339        operation: &str,
1340        params: Value,
1341    ) -> Result<Value, CredentialResolverError> {
1342        self.unary_call(operation, operation, move |consumer, &op| {
1343            consumer.credential_request(json!({ "method": op, "params": params }), op)
1344        })
1345        .await
1346    }
1347
1348    fn deadline_error(operation: &str) -> CredentialResolverError {
1349        CredentialResolverError::transport(format!(
1350            "{operation} timed out waiting for the credential route"
1351        ))
1352    }
1353
1354    fn clear_failed_transport<T>(
1355        consumer: &mut Option<Box<dyn CredentialConsumerConnection>>,
1356        result: &Result<T, CredentialResolverError>,
1357    ) {
1358        if result
1359            .as_ref()
1360            .is_err_and(CredentialResolverError::is_transport)
1361        {
1362            *consumer = None;
1363        }
1364    }
1365}
1366
1367#[cfg(feature = "transport")]
1368impl CredentialGetTarget for LiveCredentialGetTarget {
1369    fn credential_watch_scoped<'a>(
1370        &'a self,
1371        enrollment_token: Option<&'a str>,
1372    ) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
1373        Box::pin(async move {
1374            // A watch owns a separate transport handle so it cannot hold the unary-call mutex.
1375            tokio::time::timeout(self.call_deadline, async {
1376                self.connector
1377                    .connect()
1378                    .await?
1379                    .into_scoped_watch(enrollment_token.map(str::to_owned))
1380                    .await
1381            })
1382            .await
1383            .unwrap_or_else(|_| Err(Self::deadline_error("auth.watch_scoped")))
1384        })
1385    }
1386
1387    fn credential_get<'a>(
1388        &'a self,
1389        raw_handle: &'a str,
1390        min_ttl_ms: Option<u64>,
1391        force_refresh: bool,
1392    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1393        Box::pin(self.unary_call(
1394            CREDENTIAL_GET_OP,
1395            (raw_handle, min_ttl_ms, force_refresh),
1396            |consumer, &(handle, ttl, force)| consumer.credential_get(handle, ttl, force),
1397        ))
1398    }
1399
1400    fn credential_get_scoped<'a>(
1401        &'a self,
1402        credential_id: &'a str,
1403    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1404        Box::pin(self.get_scoped(credential_id, None))
1405    }
1406
1407    fn credential_get_scoped_with_min_ttl<'a>(
1408        &'a self,
1409        credential_id: &'a str,
1410        min_ttl_ms: u64,
1411    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1412        Box::pin(self.get_scoped(credential_id, Some(min_ttl_ms)))
1413    }
1414
1415    fn credential_report_auth_failure<'a>(
1416        &'a self,
1417        credential_id: &'a str,
1418        record_version: u64,
1419        provider_status: u16,
1420    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1421        Box::pin(self.unary_call(
1422            CREDENTIAL_REPORT_AUTH_FAILURE_OP,
1423            (credential_id, record_version, provider_status),
1424            |consumer, &(id, version, status)| {
1425                consumer.credential_report_auth_failure(id, version, status)
1426            },
1427        ))
1428    }
1429
1430    fn credential_report_condition<'a>(
1431        &'a self,
1432        credential_id: &'a str,
1433        record_version: u64,
1434        reason: &'a str,
1435        provider_status: u16,
1436        action_url: Option<&'a str>,
1437        enrollment_token: Option<&'a str>,
1438    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1439        Box::pin(async move {
1440            let mut params = condition_params(credential_id, record_version, enrollment_token);
1441            params["reason"] = json!(reason);
1442            params["provider_status"] = json!(provider_status);
1443            if let Some(action_url) = action_url {
1444                params["action_url"] = json!(action_url);
1445            }
1446            self.condition_request(CREDENTIAL_REPORT_CONDITION_OP, params)
1447                .await
1448        })
1449    }
1450
1451    fn credential_clear_condition<'a>(
1452        &'a self,
1453        credential_id: &'a str,
1454        record_version: u64,
1455        enrollment_token: Option<&'a str>,
1456    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1457        Box::pin(async move {
1458            self.condition_request(
1459                CREDENTIAL_CLEAR_CONDITION_OP,
1460                condition_params(credential_id, record_version, enrollment_token),
1461            )
1462            .await
1463        })
1464    }
1465
1466    fn credential_status<'a>(
1467        &'a self,
1468        credential_id: &'a str,
1469    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1470        Box::pin(
1471            self.unary_call(CREDENTIAL_STATUS_OP, credential_id, |consumer, &id| {
1472                consumer.credential_status(id)
1473            }),
1474        )
1475    }
1476
1477    fn credential_sign<'a>(
1478        &'a self,
1479        credential_id: &'a str,
1480        payload: &'a [u8],
1481    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1482        Box::pin(self.unary_call(
1483            CREDENTIAL_SIGN_OP,
1484            (credential_id, payload),
1485            |consumer, &(id, payload)| consumer.credential_sign(id, payload),
1486        ))
1487    }
1488
1489    fn credential_public_key<'a>(
1490        &'a self,
1491        credential_id: &'a str,
1492    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1493        Box::pin(
1494            self.unary_call(CREDENTIAL_PUBLIC_KEY_OP, credential_id, |consumer, &id| {
1495                consumer.credential_public_key(id)
1496            }),
1497        )
1498    }
1499
1500    fn credential_seal<'a>(
1501        &'a self,
1502        request: SealRequest<'a>,
1503    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1504        Box::pin(
1505            self.unary_call(CREDENTIAL_SEAL_OP, request, |consumer, &request| {
1506                consumer.credential_seal(request)
1507            }),
1508        )
1509    }
1510
1511    fn credential_list_scoped(
1512        &self,
1513    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
1514        Box::pin(
1515            self.unary_call(CREDENTIAL_LIST_SCOPED_OP, (), |consumer, &()| {
1516                consumer.credential_list_scoped()
1517            }),
1518        )
1519    }
1520}
1521
1522#[cfg(feature = "transport")]
1523struct ClaustrumConsumer {
1524    stream: TcpStream,
1525    route_channel: u16,
1526    route_epoch: u32,
1527    next_corr: u64,
1528}
1529
1530#[cfg(feature = "transport")]
1531impl ClaustrumConsumer {
1532    async fn connect(
1533        connection_file_path: &Path,
1534        consumer_module_id: &str,
1535    ) -> Result<Self, CredentialResolverError> {
1536        let connection = connection_file::read(connection_file_path).map_err(|error| {
1537            CredentialResolverError::transport(format!(
1538                "credential route connection metadata is unavailable: {error}"
1539            ))
1540        })?;
1541        let endpoint = connection.endpoints.first().ok_or_else(|| {
1542            CredentialResolverError::transport("credential route has no daemon endpoint")
1543        })?;
1544        let address = format!("{}:{}", endpoint.host, endpoint.port);
1545        let mut stream =
1546            tokio::time::timeout(CREDENTIAL_CONNECT_TIMEOUT, TcpStream::connect(address))
1547                .await
1548                .map_err(|error| {
1549                    CredentialResolverError::transport(format!(
1550                        "credential route connection timed out: {error}"
1551                    ))
1552                })?
1553                .map_err(|error| {
1554                    CredentialResolverError::transport(format!(
1555                        "credential route connection failed: {error}"
1556                    ))
1557                })?;
1558        authenticate_client(&mut stream, &connection, CREDENTIAL_READ_TIMEOUT)
1559            .await
1560            .map_err(|_| {
1561                CredentialResolverError::new(
1562                    CredentialErrorClass::AuthRequired,
1563                    "credential route authentication failed",
1564                )
1565            })?;
1566        let mut consumer = Self {
1567            stream,
1568            route_channel: 0,
1569            route_epoch: 0,
1570            next_corr: 1,
1571        };
1572        (consumer.route_channel, consumer.route_epoch) =
1573            consumer.route_open(consumer_module_id).await?;
1574        Ok(consumer)
1575    }
1576
1577    fn next_correlation(&mut self) -> u64 {
1578        let correlation = self.next_corr;
1579        self.next_corr += 1;
1580        correlation
1581    }
1582
1583    async fn route_open(
1584        &mut self,
1585        consumer_module_id: &str,
1586    ) -> Result<(u16, u32), CredentialResolverError> {
1587        let correlation = self.next_correlation();
1588        // A missing launch nonce refuses here, before anything is written: the route
1589        // must never open unscoped.
1590        let body = route_open_body(consumer_module_id)?;
1591        let reply = tokio::time::timeout(CREDENTIAL_READ_TIMEOUT, async {
1592            self.write_request(0, 0, correlation, Priority::Passive, body)
1593                .await?;
1594            self.read_reply(0, 0, correlation).await
1595        })
1596        .await
1597        .map_err(|_| CredentialResolverError::transport("credential route open timed out"))??;
1598        if reply.header.ty == FrameType::Error {
1599            return Err(decode_wire_error(&reply.body));
1600        }
1601        let value: Value = serde_json::from_slice(&reply.body).map_err(|_| {
1602            CredentialResolverError::new(
1603                CredentialErrorClass::InvalidResponse,
1604                "credential route-open reply is not valid JSON",
1605            )
1606        })?;
1607        let channel = value
1608            .get("route_channel")
1609            .and_then(Value::as_u64)
1610            .and_then(|value| u16::try_from(value).ok())
1611            .ok_or_else(|| {
1612                CredentialResolverError::new(
1613                    CredentialErrorClass::InvalidResponse,
1614                    "credential route-open reply has no valid channel",
1615                )
1616            })?;
1617        let epoch = value
1618            .get("route_epoch")
1619            .and_then(Value::as_u64)
1620            .and_then(|value| u32::try_from(value).ok())
1621            .ok_or_else(|| {
1622                CredentialResolverError::new(
1623                    CredentialErrorClass::InvalidResponse,
1624                    "credential route-open reply has no valid epoch",
1625                )
1626            })?;
1627        Ok((channel, epoch))
1628    }
1629
1630    async fn write_request(
1631        &mut self,
1632        channel: u16,
1633        epoch: u32,
1634        correlation: u64,
1635        priority: Priority,
1636        body: Value,
1637    ) -> Result<(), CredentialResolverError> {
1638        self.write_bytes(
1639            channel,
1640            epoch,
1641            correlation,
1642            priority,
1643            transport::encode_request(&body)?,
1644        )
1645        .await
1646    }
1647
1648    async fn write_bytes(
1649        &mut self,
1650        channel: u16,
1651        epoch: u32,
1652        correlation: u64,
1653        priority: Priority,
1654        bytes: Vec<u8>,
1655    ) -> Result<(), CredentialResolverError> {
1656        let frame = Frame::build(
1657            FrameType::Request,
1658            Flags::new(false, priority, false),
1659            channel,
1660            epoch,
1661            correlation,
1662            bytes,
1663        )
1664        .map_err(|_| {
1665            CredentialResolverError::new(
1666                CredentialErrorClass::Permanent,
1667                "credential request framing failed",
1668            )
1669        })?;
1670        write_frame(&mut self.stream, &frame)
1671            .await
1672            .map_err(|error| {
1673                CredentialResolverError::transport(format!(
1674                    "credential route write failed: {error}"
1675                ))
1676            })
1677    }
1678
1679    async fn read_reply(
1680        &mut self,
1681        channel: u16,
1682        epoch: u32,
1683        correlation: u64,
1684    ) -> Result<Frame, CredentialResolverError> {
1685        loop {
1686            let frame = read_frame(&mut self.stream)
1687                .await
1688                .map_err(|error| {
1689                    CredentialResolverError::transport(format!(
1690                        "credential route read failed: {error}"
1691                    ))
1692                })?
1693                .ok_or_else(|| {
1694                    CredentialResolverError::transport("credential route closed before replying")
1695                })?;
1696            if frame.header.channel == channel
1697                && frame.header.epoch == epoch
1698                && frame.header.corr == correlation
1699                && matches!(frame.header.ty, FrameType::Response | FrameType::Error)
1700            {
1701                return Ok(frame);
1702            }
1703        }
1704    }
1705}
1706
1707#[cfg(feature = "transport")]
1708impl CredentialConsumerConnection for ClaustrumConsumer {
1709    fn sensitive_request(
1710        &mut self,
1711        request: Secret<Vec<u8>>,
1712    ) -> CredentialResolverFuture<'_, Result<Secret<Vec<u8>>, CredentialResolverError>> {
1713        Box::pin(transport::sensitive_request(self, request))
1714    }
1715    fn into_scoped_watch(
1716        self: Box<Self>,
1717        enrollment_token: Option<String>,
1718    ) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
1719        Box::pin(async move { (*self).start_scoped_watch(enrollment_token).await })
1720    }
1721
1722    fn into_policy_watch(
1723        self: Box<Self>,
1724    ) -> CredentialResolverFuture<'static, Result<PolicyWatch, CredentialResolverError>> {
1725        Box::pin(watch::start_policy_watch(*self))
1726    }
1727
1728    fn credential_request<'a>(
1729        &'a mut self,
1730        request: Value,
1731        operation: &'a str,
1732    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1733        Box::pin(transport::credential_request(self, request, operation))
1734    }
1735}
1736
1737#[cfg(any(feature = "transport", test))]
1738fn credential_list_scoped_request() -> Value {
1739    // A supervised module is identified by its route's reserved principal, so it
1740    // sends no enrollment token; the vault refuses unknown parameters.
1741    json!({
1742        "method": CREDENTIAL_LIST_SCOPED_OP,
1743        "params": {},
1744    })
1745}
1746
1747fn optional_string(value: &Value, key: &str) -> Option<String> {
1748    value
1749        .get(key)
1750        .and_then(Value::as_str)
1751        .filter(|text| !text.is_empty())
1752        .map(str::to_owned)
1753}
1754
1755fn invalid_listing(detail: &str) -> CredentialResolverError {
1756    CredentialResolverError::new(
1757        CredentialErrorClass::InvalidResponse,
1758        format!("credential.list_scoped reply {detail}"),
1759    )
1760}
1761
1762fn listing_strings(row: &Value, key: &str, optional: bool) -> Result<Vec<String>, String> {
1763    // An optional field sent as explicit null means the same as an omitted one. The
1764    // vault omits absent fields, but rejecting null would drop a usable credential
1765    // from the listing over a serialization choice.
1766    if optional && matches!(row.get(key), None | Some(Value::Null)) {
1767        return Ok(Vec::new());
1768    }
1769    let items = row
1770        .get(key)
1771        .and_then(Value::as_array)
1772        .ok_or_else(|| format!("{key} is not an array"))?;
1773    items
1774        .iter()
1775        .map(|item| {
1776            item.as_str()
1777                .map(str::to_owned)
1778                .ok_or_else(|| format!("{key} contains a non-string"))
1779        })
1780        .collect()
1781}
1782
1783fn listing_string(row: &Value, key: &str) -> Result<String, String> {
1784    optional_string(row, key).ok_or_else(|| format!("{key} is not a non-empty string"))
1785}
1786
1787fn decode_optional_string(row: &Value, key: &str) -> Result<Option<String>, String> {
1788    match row.get(key) {
1789        // Null is absent too; see listing_strings for why it isn't a decode failure.
1790        None | Some(Value::Null) => Ok(None),
1791        Some(value) => value
1792            .as_str()
1793            .map(|s| Some(s.to_owned()))
1794            .ok_or_else(|| format!("{key} is not a string")),
1795    }
1796}
1797
1798fn decode_optional_hosts(row: &Value) -> Result<Option<Vec<String>>, String> {
1799    match row.get("hosts") {
1800        None | Some(Value::Null) => Ok(None),
1801        Some(_) => listing_strings(row, "hosts", false).map(Some),
1802    }
1803}
1804
1805fn decode_optional_headers(row: &Value) -> Result<Option<BTreeMap<String, String>>, String> {
1806    let headers = match row.get("headers") {
1807        None | Some(Value::Null) => return Ok(None),
1808        Some(Value::Object(headers)) => headers,
1809        Some(_) => return Err("headers is not an object".into()),
1810    };
1811    headers
1812        .iter()
1813        .map(|(name, value)| {
1814            value
1815                .as_str()
1816                .map(|value| (name.clone(), value.to_owned()))
1817                .ok_or_else(|| "headers contains a non-string value".to_string())
1818        })
1819        .collect::<Result<BTreeMap<_, _>, _>>()
1820        .map(Some)
1821}
1822
1823fn decode_optional_auth(row: &Value) -> Result<Option<AuthDescriptor>, String> {
1824    let auth = match row.get("auth") {
1825        None | Some(Value::Null) => return Ok(None),
1826        Some(auth) if auth.is_object() => auth,
1827        Some(_) => return Err("auth is not an object".into()),
1828    };
1829    let header = auth
1830        .get("header")
1831        .and_then(Value::as_str)
1832        .ok_or_else(|| "auth.header is not a string".to_string())?
1833        .to_owned();
1834    let scheme = match auth.get("scheme").and_then(Value::as_str) {
1835        Some("bearer") => AuthScheme::Bearer,
1836        Some("raw") => AuthScheme::Raw,
1837        _ => return Err("auth.scheme is not bearer or raw".into()),
1838    };
1839    Ok(Some(AuthDescriptor { header, scheme }))
1840}
1841
1842fn decode_optional_invalid_key(row: &Value) -> Result<Option<InvalidKeyEvidence>, String> {
1843    let evidence = match row.get("invalid_key") {
1844        None | Some(Value::Null) => return Ok(None),
1845        Some(evidence) if evidence.is_object() => evidence,
1846        Some(_) => return Err("invalid_key is not an object".into()),
1847    };
1848    let status = evidence
1849        .get("status")
1850        .and_then(Value::as_u64)
1851        .and_then(|status| u16::try_from(status).ok())
1852        .ok_or_else(|| "invalid_key.status is not a u16".to_string())?;
1853    let error_code = decode_optional_string(evidence, "error_code")
1854        .map_err(|error| format!("invalid_key.{error}"))?;
1855    let error_code_field = decode_optional_string(evidence, "error_code_field")
1856        .map_err(|error| format!("invalid_key.{error}"))?;
1857    if error_code.is_some() != error_code_field.is_some() {
1858        return Err("invalid_key error_code and error_code_field must be present together".into());
1859    }
1860    Ok(Some(InvalidKeyEvidence {
1861        status,
1862        error_code,
1863        error_code_field,
1864    }))
1865}
1866
1867fn decode_optional_condition(row: &Value) -> Result<Option<ListedCredentialCondition>, String> {
1868    let condition = match row.get("condition") {
1869        None | Some(Value::Null) => return Ok(None),
1870        Some(condition) if condition.is_object() => condition,
1871        Some(_) => return Err("condition is not an object".into()),
1872    };
1873    let reason = condition
1874        .get("reason")
1875        .and_then(Value::as_str)
1876        .ok_or_else(|| "condition.reason is not a string".to_string())?;
1877    let since_ms = condition
1878        .get("since_ms")
1879        .and_then(Value::as_u64)
1880        .filter(|&since_ms| since_ms <= MAX_SCOPED_CONDITION_SINCE_MS)
1881        .ok_or_else(|| "condition.since_ms is not a non-negative safe integer".to_string())?;
1882    Ok(Some(ListedCredentialCondition {
1883        reason: reason.to_owned(),
1884        since_ms,
1885    }))
1886}
1887
1888fn decode_optional_github_app(row: &Value) -> Result<Option<ListedGitHubApp>, String> {
1889    let app = match row.get("github_app") {
1890        None | Some(Value::Null) => return Ok(None),
1891        Some(app) => app,
1892    };
1893    if !app.is_object() {
1894        return Err("github_app is not an object".into());
1895    }
1896    let (created_by, created_at_ms, agent) = match (
1897        app.get("created_by"),
1898        app.get("created_at_ms"),
1899        app.get("agent"),
1900    ) {
1901        (None, None, None) => (None, None, None),
1902        (Some(created_by), Some(created_at_ms), Some(agent)) => (
1903            Some(
1904                created_by
1905                    .as_str()
1906                    .filter(|&s| s == "vault")
1907                    .ok_or("github_app.created_by is not the string vault")?
1908                    .to_owned(),
1909            ),
1910            Some(
1911                created_at_ms
1912                    .as_u64()
1913                    .ok_or("github_app.created_at_ms is not a non-negative integer")?,
1914            ),
1915            Some(
1916                agent
1917                    .as_str()
1918                    .ok_or("github_app.agent is not a string")?
1919                    .to_owned(),
1920            ),
1921        ),
1922        _ => return Err("github_app attestation is incomplete".into()),
1923    };
1924    Ok(Some(ListedGitHubApp {
1925        app_id: listing_string(app, "app_id").map_err(|error| format!("github_app.{error}"))?,
1926        slug: listing_string(app, "slug").map_err(|error| format!("github_app.{error}"))?,
1927        created_by,
1928        created_at_ms,
1929        agent,
1930    }))
1931}
1932
1933const MAX_LISTED_ORG_ID_BYTES: usize = 128;
1934
1935// Mirrors `claustrum_model::record::is_valid_org_id`; the published client cannot
1936// depend on the vault's unpublished model crate.
1937fn is_valid_listed_org_id(value: &str) -> bool {
1938    !value.is_empty()
1939        && value.len() <= MAX_LISTED_ORG_ID_BYTES
1940        && value
1941            .bytes()
1942            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
1943}
1944
1945fn decode_listed_credential(row: &Value) -> Result<ListedCredential, String> {
1946    Ok(ListedCredential {
1947        plan_tier_since_ms: row
1948            .get("plan_tier_since_ms")
1949            .filter(|value| !value.is_null())
1950            .map(|value| {
1951                value
1952                    .as_u64()
1953                    .ok_or_else(|| "plan_tier_since_ms is not a non-negative integer".to_string())
1954            })
1955            .transpose()?,
1956        provider: decode_optional_string(row, "provider")?,
1957        fusiform_provider_id: decode_optional_string(row, "fusiform_provider_id")?,
1958        hosts: decode_optional_hosts(row)?,
1959        incarnation: decode_optional_string(row, "incarnation")?,
1960        plan_tier_observed_at_ms: match row.get("plan_tier_observed_at_ms") {
1961            None | Some(Value::Null) => None,
1962            Some(value) => Some(
1963                value
1964                    .as_i64()
1965                    .ok_or_else(|| "plan_tier_observed_at_ms is not an integer".to_string())?,
1966            ),
1967        },
1968        id: listing_string(row, "id")?,
1969        categories: listing_strings(row, "categories", false)?,
1970        credential_type: listing_string(row, "type")?,
1971        serves: listing_strings(row, "serves", false)?,
1972        provider_ids: listing_strings(row, "provider_ids", true)?,
1973        auth_method: decode_optional_string(row, "auth_method")?,
1974        refresh_adapter: decode_optional_string(row, "refresh_adapter")?,
1975        state: listing_string(row, "state")?,
1976        record_version: row
1977            .get("record_version")
1978            .and_then(Value::as_u64)
1979            .ok_or_else(|| "record_version is not an unsigned integer".to_string())?,
1980        operations: listing_strings(row, "operations", false)?,
1981        account_id: decode_optional_string(row, "account_id")?,
1982        email: decode_optional_string(row, "email")?,
1983        org_name: decode_optional_string(row, "org_name")?,
1984        org_id: row
1985            .get("org_id")
1986            .filter(|value| !value.is_null())
1987            .map(|value| {
1988                value
1989                    .as_str()
1990                    .filter(|value| is_valid_listed_org_id(value))
1991                    .map(str::to_owned)
1992                    .ok_or_else(|| "org_id is not a valid organization id".to_string())
1993            })
1994            .transpose()?,
1995        plan_tier: decode_optional_string(row, "plan_tier")?,
1996        plan_tier_source: decode_optional_string(row, "plan_tier_source")?,
1997        condition: decode_optional_condition(row)?,
1998        github_app: decode_optional_github_app(row)?,
1999    })
2000}
2001
2002fn decode_listed_grant(tuple: &Value) -> Result<ListedGrant, String> {
2003    Ok(ListedGrant {
2004        selector_kind: listing_string(tuple, "selector_kind")?,
2005        selector: listing_string(tuple, "selector")?,
2006        operation: listing_string(tuple, "operation")?,
2007    })
2008}
2009
2010/// Decode metadata row by row: a malformed credential or grant must not discard
2011/// healthy entries listed alongside it. Envelope failures still reject the listing.
2012pub fn decode_list_scoped_reply(
2013    value: Value,
2014) -> Result<ScopedCredentialListing, CredentialResolverError> {
2015    let result = reply_result(value)?;
2016    let view = result
2017        .get("view")
2018        .and_then(Value::as_str)
2019        .ok_or_else(|| invalid_listing("has no view digest"))?
2020        .to_owned();
2021    let rows = result
2022        .get("credentials")
2023        .and_then(Value::as_array)
2024        .ok_or_else(|| invalid_listing("has no credentials array"))?;
2025    let mut credentials = Vec::with_capacity(rows.len());
2026    let mut undecodable_credentials = Vec::new();
2027    for (index, row) in rows.iter().enumerate() {
2028        match decode_listed_credential(row) {
2029            Ok(credential) => credentials.push(credential),
2030            Err(error) => {
2031                let id = optional_string(row, "id").unwrap_or_else(|| format!("row {index}"));
2032                let detail = format!("{id}: {error}");
2033                undecodable_credentials.push(detail);
2034            }
2035        }
2036    }
2037    let mut grant_tuples = Vec::new();
2038    let mut undecodable_grants = Vec::new();
2039    if let Some(tuples) = result.get("grant_tuples") {
2040        let tuples = tuples
2041            .as_array()
2042            .ok_or_else(|| invalid_listing("grant_tuples is not an array"))?;
2043        for (index, tuple) in tuples.iter().enumerate() {
2044            match decode_listed_grant(tuple) {
2045                Ok(grant) => grant_tuples.push(grant),
2046                Err(error) => undecodable_grants.push(format!("grant tuple {index}: {error}")),
2047            }
2048        }
2049    }
2050    Ok(ScopedCredentialListing {
2051        credentials,
2052        undecodable_credentials,
2053        grant_tuples,
2054        undecodable_grants,
2055        view,
2056    })
2057}
2058
2059#[cfg(any(feature = "transport", test))]
2060fn credential_get_request(raw_handle: &str, min_ttl_ms: Option<u64>, force_refresh: bool) -> Value {
2061    let mut params =
2062        serde_json::Map::from_iter([("handle".to_owned(), Value::String(raw_handle.to_owned()))]);
2063    if let Some(min_ttl_ms) = min_ttl_ms {
2064        params.insert("min_ttl_ms".to_owned(), Value::from(min_ttl_ms));
2065    }
2066    if force_refresh {
2067        params.insert("force_refresh".to_owned(), Value::Bool(true));
2068    }
2069    json!({
2070        "method": CREDENTIAL_GET_OP,
2071        "params": params,
2072    })
2073}
2074
2075#[cfg(any(feature = "transport", test))]
2076fn credential_get_scoped_request(credential_id: &str, min_ttl_ms: Option<u64>) -> Value {
2077    let mut params = json!({ "credential_id": credential_id });
2078    if let Some(min_ttl_ms) = min_ttl_ms {
2079        params["min_ttl_ms"] = json!(min_ttl_ms);
2080    }
2081    json!({
2082        "method": CREDENTIAL_GET_SCOPED_OP,
2083        "params": params,
2084    })
2085}
2086
2087#[cfg(any(feature = "transport", test))]
2088fn credential_report_auth_failure_request(
2089    credential_id: &str,
2090    record_version: u64,
2091    provider_status: u16,
2092) -> Value {
2093    json!({
2094        "method": CREDENTIAL_REPORT_AUTH_FAILURE_OP,
2095        "params": {
2096            "credential_id": credential_id,
2097            "provider_status": provider_status,
2098            "record_version": record_version,
2099        },
2100    })
2101}
2102
2103#[cfg(feature = "transport")]
2104fn condition_params(
2105    credential_id: &str,
2106    record_version: u64,
2107    enrollment_token: Option<&str>,
2108) -> Value {
2109    let mut params = json!({ "credential_id": credential_id, "record_version": record_version });
2110    if let Some(enrollment_token) = enrollment_token {
2111        params["enrollment_token"] = json!(enrollment_token);
2112    }
2113    params
2114}
2115
2116#[cfg(any(feature = "transport", test))]
2117fn credential_status_request(credential_id: &str) -> Value {
2118    json!({
2119        "method": CREDENTIAL_STATUS_OP,
2120        "params": { "credential_id": credential_id },
2121    })
2122}
2123
2124#[cfg(any(feature = "transport", test))]
2125fn credential_sign_request(credential_id: &str, payload: &[u8]) -> Value {
2126    // CKCRED 3aaf0e3: sign is handle-less - authorized by the launch-nonce
2127    // principal against the grant table's sign authority, addressed by the
2128    // credential NAME. A handle here would be a bearer capability for a
2129    // signing key, the shape the handle-less revision exists to delete.
2130    json!({
2131        "method": CREDENTIAL_SIGN_OP,
2132        "params": {
2133            "credential_id": credential_id,
2134            "payload_b64": base64::engine::general_purpose::STANDARD.encode(payload),
2135        },
2136    })
2137}
2138
2139#[cfg(any(feature = "transport", test))]
2140fn credential_public_key_request(credential_id: &str) -> Value {
2141    // The launch-nonce principal authorizes this named credential lookup; a
2142    // bearer capability handle must never cross the public-key request.
2143    json!({
2144        "method": CREDENTIAL_PUBLIC_KEY_OP,
2145        "params": { "credential_id": credential_id },
2146    })
2147}
2148
2149#[cfg(any(feature = "transport", test))]
2150fn credential_seal_request(request: SealRequest<'_>) -> Value {
2151    // Addressed by credential NAME under the route principal's exact seal grant, like
2152    // sign. The vault refuses unknown parameters, so no enrollment token is sent.
2153    let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
2154    json!({
2155        "method": CREDENTIAL_SEAL_OP,
2156        "params": {
2157            "credential_id": request.credential_id,
2158            "recipient_public_key_b64": encode(request.recipient_public_key),
2159            "info_b64": encode(request.info),
2160            "aad_b64": encode(request.aad),
2161            "plaintext_b64": encode(request.plaintext),
2162        },
2163    })
2164}
2165
2166/// Decodes a subc Error frame answering `route.open`.
2167pub fn decode_wire_error(bytes: &[u8]) -> CredentialResolverError {
2168    decode_wire_error_with(bytes, classify_route_open_error)
2169}
2170
2171/// Decodes a subc Error frame received on an established route or watch.
2172pub fn decode_established_route_wire_error(flags: Flags, bytes: &[u8]) -> CredentialResolverError {
2173    decode_wire_error_with(bytes, |body| classify_established_route_error(flags, body))
2174}
2175
2176fn decode_wire_error_with(
2177    bytes: &[u8],
2178    classify: impl FnOnce(ErrorBody) -> CredentialResolverError,
2179) -> CredentialResolverError {
2180    let value = serde_json::from_slice::<Value>(bytes).unwrap_or(Value::Null);
2181    let Some(code) = value.get("code").and_then(Value::as_str) else {
2182        return CredentialResolverError::transport(
2183            "credential service returned an invalid error frame",
2184        );
2185    };
2186    classify(ErrorBody {
2187        code: code.to_owned(),
2188        message: value
2189            .get("message")
2190            .and_then(Value::as_str)
2191            .unwrap_or("credential route refused the request")
2192            .to_owned(),
2193        detail: value.get("detail").cloned(),
2194    })
2195}
2196
2197fn classify_route_open_error(body: ErrorBody) -> CredentialResolverError {
2198    // Error frames describe the route, not credential state. Honor the daemon's
2199    // recovery verdict instead of inferring it from the failure message.
2200    if subc_protocol::error_codes::is_retryable_route_open_refusal(&body) {
2201        CredentialResolverError {
2202            class: CredentialErrorClass::Transport,
2203            code: body.code,
2204            safe_message: body.message,
2205            established_route_dead: false,
2206        }
2207    } else {
2208        CredentialResolverError::unclassified(body.code, body.message)
2209    }
2210}
2211
2212fn classify_established_route_error(flags: Flags, body: ErrorBody) -> CredentialResolverError {
2213    let route_dead = subc_protocol::error_codes::is_established_route_dead(flags, &body.code);
2214    classify_established_route_verdict(body, route_dead)
2215}
2216
2217fn classify_established_route_verdict(
2218    body: ErrorBody,
2219    route_dead: bool,
2220) -> CredentialResolverError {
2221    if route_dead {
2222        return CredentialResolverError {
2223            class: CredentialErrorClass::Transport,
2224            code: body.code,
2225            safe_message: body.message,
2226            established_route_dead: true,
2227        };
2228    }
2229    // Keep the previous classification for errors that do not invalidate the route.
2230    classify_route_open_error(body)
2231}
2232
2233/// Classify a credential refusal in a `result.error` member of a Response frame.
2234/// The broad class drives retry
2235/// behavior, while preserving the producer's code in the safe message lets an
2236/// operator distinguish a missing, revoked, or denied credential.
2237fn classify_error_value(value: &Value) -> CredentialResolverError {
2238    let class = value
2239        .get("class")
2240        .or_else(|| value.pointer("/error/class"))
2241        .or_else(|| value.pointer("/error/data/class"))
2242        .and_then(Value::as_str);
2243    let class = match class {
2244        Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
2245        Some("credential_absent") => Some(CredentialErrorClass::CredentialAbsent),
2246        Some("unauthorized") => Some(CredentialErrorClass::Unauthorized),
2247        Some("permanent") => Some(CredentialErrorClass::Permanent),
2248        Some("transient") => Some(CredentialErrorClass::Transient),
2249        Some("context_overflow") => Some(CredentialErrorClass::ContextOverflow),
2250        _ => None,
2251    };
2252    let code_field = value
2253        .get("code")
2254        .or_else(|| value.pointer("/error/code"))
2255        .and_then(Value::as_str);
2256    // A missing record or authentication refusal requires operator repair, not
2257    // another signing attempt, even if a producer supplies a broad retry class.
2258    let class = match code_field {
2259        Some("not_found") => Some(CredentialErrorClass::CredentialAbsent),
2260        Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
2261        _ => class,
2262    };
2263    if let Some(class) = class {
2264        let message = match code_field {
2265            Some(code) => format!("credential service rejected the request: {code}"),
2266            None => "credential service rejected the request".to_string(),
2267        };
2268        return CredentialResolverError::new(class, message);
2269    }
2270    let code = value
2271        .get("code")
2272        .or_else(|| value.pointer("/error/code"))
2273        .and_then(Value::as_str)
2274        .unwrap_or("credential_unclassified");
2275    let message = value
2276        .get("message")
2277        .or_else(|| value.pointer("/error/message"))
2278        .and_then(Value::as_str)
2279        .unwrap_or("credential service returned an unclassified error");
2280    CredentialResolverError::unclassified(code, message)
2281}
2282
2283/// The route.open frame for the credential module. Reserved-principal identity
2284/// is carried in `consumer_identity`, not the bind parameters. The credential
2285/// service derives that principal by matching the launch nonce; if it is absent,
2286/// claustrum silently treats the caller as unscoped. Route opening must therefore
2287/// fail before scoped reads are reduced to an ambiguous `not_found`.
2288#[cfg(feature = "transport")]
2289fn route_open_body(consumer_module_id: &str) -> Result<Value, CredentialResolverError> {
2290    // The process-wide accessor, never the environment: after the first read
2291    // closes the pipe the daemon handed over, a second independent reader
2292    // would read whatever the process opened next at that descriptor number.
2293    let read = subc_os::launch_nonce()
2294        .map(|nonce| nonce.map(|nonce| nonce.value().to_owned()))
2295        .map_err(|error| error.to_string());
2296    Ok(route_open_body_with_nonce(
2297        consumer_module_id,
2298        &required_launch_nonce(read)?,
2299    ))
2300}
2301
2302/// The nonce from a read of it, or an `AuthRequired` refusal when there is none.
2303/// Without the nonce the route would open unscoped, so the caller must stop before
2304/// sending anything; returning an error (never panicking) lets a module process
2305/// refuse cleanly and report why, instead of crashing.
2306#[cfg(feature = "transport")]
2307fn required_launch_nonce(
2308    read: Result<Option<String>, String>,
2309) -> Result<String, CredentialResolverError> {
2310    match read {
2311        Ok(Some(nonce)) if !nonce.trim().is_empty() => Ok(nonce),
2312        Ok(_) => Err(CredentialResolverError::new(
2313            CredentialErrorClass::AuthRequired,
2314            "credential consumer requires a non-empty launch nonce for the reserved principal",
2315        )),
2316        Err(error) => Err(CredentialResolverError::new(
2317            CredentialErrorClass::AuthRequired,
2318            format!(
2319                "credential consumer could not read the launch nonce for the reserved principal: {error}"
2320            ),
2321        )),
2322    }
2323}
2324
2325#[cfg(feature = "transport")]
2326fn route_open_body_with_nonce(consumer_module_id: &str, launch_nonce: &str) -> Value {
2327    json!({
2328        "op": "route.open",
2329        "target": {
2330            "kind": "management_surface",
2331            "module_id": CREDENTIAL_MODULE_ID,
2332        },
2333        "identity": {
2334            "harness": consumer_module_id,
2335            "session": "campaign-credential-consumer",
2336        },
2337        "consumer_identity": {
2338            "module_id": consumer_module_id,
2339            "launch_nonce": launch_nonce,
2340        },
2341        "config": [],
2342    })
2343}
2344
2345fn reply_result(value: Value) -> Result<Value, CredentialResolverError> {
2346    let result = value.get("result").cloned().unwrap_or(value);
2347    if result.get("error").is_some() {
2348        return Err(classify_error_value(&result));
2349    }
2350    Ok(result)
2351}
2352
2353fn valid_lower_hex(value: &str, length: usize) -> bool {
2354    value.len() == length
2355        && value
2356            .bytes()
2357            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2358}
2359
2360fn hex_bytes(bytes: &[u8]) -> String {
2361    let mut encoded = String::with_capacity(bytes.len() * 2);
2362    for byte in bytes {
2363        encoded.push_str(&format!("{byte:02x}"));
2364    }
2365    encoded
2366}
2367
2368/// Decodes a `credential.sign` response, validating the Ed25519 signature shape.
2369pub fn decode_signature_reply(
2370    value: Value,
2371) -> Result<CredentialSignature, CredentialResolverError> {
2372    let result = reply_result(value)?;
2373    let signature_b64 = result
2374        .get("signature_b64")
2375        .and_then(Value::as_str)
2376        .ok_or_else(|| {
2377            CredentialResolverError::new(
2378                CredentialErrorClass::InvalidResponse,
2379                "credential signing reply has no signature_b64",
2380            )
2381        })?;
2382    let signature = base64::engine::general_purpose::STANDARD
2383        .decode(signature_b64)
2384        .map_err(|_| {
2385            CredentialResolverError::new(
2386                CredentialErrorClass::InvalidResponse,
2387                "credential signing reply has invalid base64",
2388            )
2389        })?;
2390    if signature.len() != 64 {
2391        return Err(CredentialResolverError::new(
2392            CredentialErrorClass::InvalidResponse,
2393            "credential signing reply has a non-Ed25519 signature length",
2394        ));
2395    }
2396    let key_id = result
2397        .get("key_id")
2398        .and_then(Value::as_str)
2399        .filter(|value| valid_lower_hex(value, 16))
2400        .ok_or_else(|| {
2401            CredentialResolverError::new(
2402                CredentialErrorClass::InvalidResponse,
2403                "credential signing reply has no valid key_id",
2404            )
2405        })?;
2406    Ok(CredentialSignature {
2407        signature_hex: hex_bytes(&signature),
2408        key_id: key_id.to_owned(),
2409    })
2410}
2411
2412/// Decodes a `credential.public_key` response, validating its public key and ID.
2413///
2414/// The reply is either an Ed25519 signing key or an X25519 KEM key. Both are 32
2415/// bytes, and the vault derives both kinds' `key_id` the same way (the first 8 bytes
2416/// of SHA-256 over the public key), so one length check and one key-id check cover
2417/// both. Any other `algorithm` is refused.
2418pub fn decode_public_key_reply(
2419    value: Value,
2420) -> Result<CredentialPublicKey, CredentialResolverError> {
2421    let result = reply_result(value)?;
2422    let public_key_hex = result
2423        .get("public_key_hex")
2424        .and_then(Value::as_str)
2425        .filter(|value| valid_lower_hex(value, 64))
2426        .ok_or_else(|| {
2427            CredentialResolverError::new(
2428                CredentialErrorClass::InvalidResponse,
2429                "credential public-key reply has no valid public_key_hex",
2430            )
2431        })?;
2432    let key_id = result
2433        .get("key_id")
2434        .and_then(Value::as_str)
2435        .filter(|value| valid_lower_hex(value, 16))
2436        .ok_or_else(|| {
2437            CredentialResolverError::new(
2438                CredentialErrorClass::InvalidResponse,
2439                "credential public-key reply has no valid key_id",
2440            )
2441        })?;
2442    let public_key_bytes = (0..public_key_hex.len())
2443        .step_by(2)
2444        .map(|index| u8::from_str_radix(&public_key_hex[index..index + 2], 16))
2445        .collect::<Result<Vec<_>, _>>()
2446        .expect("validated lowercase hex decodes");
2447    let expected_key_id = hex_bytes(&Sha256::digest(&public_key_bytes)[..8]);
2448    if key_id != expected_key_id {
2449        return Err(CredentialResolverError::new(
2450            CredentialErrorClass::InvalidResponse,
2451            "credential public-key reply key_id does not identify public_key_hex",
2452        ));
2453    }
2454    let algorithm = match result.get("algorithm").and_then(Value::as_str) {
2455        Some("ed25519") => PublicKeyAlgorithm::Ed25519,
2456        Some("x25519") => PublicKeyAlgorithm::X25519,
2457        _ => {
2458            return Err(CredentialResolverError::new(
2459                CredentialErrorClass::InvalidResponse,
2460                "credential public-key reply is neither Ed25519 nor X25519",
2461            ))
2462        }
2463    };
2464    Ok(CredentialPublicKey {
2465        public_key_hex: public_key_hex.to_owned(),
2466        key_id: key_id.to_owned(),
2467        algorithm,
2468    })
2469}
2470
2471/// Decodes a `credential.seal` response: a 32-byte encapsulated key, a ciphertext at
2472/// least as long as the AEAD tag, and a key id in `credential.public_key` format.
2473pub fn decode_seal_reply(value: Value) -> Result<CredentialSeal, CredentialResolverError> {
2474    let result = reply_result(value)?;
2475    let invalid = |detail: &str| {
2476        CredentialResolverError::new(
2477            CredentialErrorClass::InvalidResponse,
2478            format!("credential seal reply {detail}"),
2479        )
2480    };
2481    let bytes = |field: &str| {
2482        let text = result
2483            .get(field)
2484            .and_then(Value::as_str)
2485            .ok_or_else(|| invalid(&format!("has no {field}")))?;
2486        base64::engine::general_purpose::STANDARD
2487            .decode(text)
2488            .map_err(|_| invalid(&format!("has invalid base64 in {field}")))
2489    };
2490    let enc = bytes("enc_b64")?;
2491    if enc.len() != 32 {
2492        return Err(invalid("has a non-X25519 encapsulated key length"));
2493    }
2494    let ciphertext = bytes("ciphertext_b64")?;
2495    if ciphertext.len() < 16 {
2496        return Err(invalid("has a ciphertext shorter than the AEAD tag"));
2497    }
2498    let key_id = result
2499        .get("key_id")
2500        .and_then(Value::as_str)
2501        .filter(|value| valid_lower_hex(value, 16))
2502        .ok_or_else(|| invalid("has no valid key_id"))?;
2503    Ok(CredentialSeal {
2504        enc,
2505        ciphertext,
2506        key_id: key_id.to_owned(),
2507    })
2508}
2509
2510/// Decodes a `credential.status` response without fetching credential material.
2511pub fn decode_credential_status_reply(
2512    value: Value,
2513) -> Result<CredentialStatus, CredentialResolverError> {
2514    let result = reply_result(value)?;
2515    let ready = result
2516        .get("ready")
2517        .and_then(Value::as_bool)
2518        .ok_or_else(|| {
2519            CredentialResolverError::new(
2520                CredentialErrorClass::InvalidResponse,
2521                "credential status reply has no ready flag",
2522            )
2523        })?;
2524    let record_version = result
2525        .get("record_version")
2526        .map(decode_record_version)
2527        .transpose()?;
2528    Ok(CredentialStatus {
2529        ready,
2530        record_version,
2531        stale_pending: result
2532            .get("stale_pending")
2533            .map(|value| {
2534                value
2535                    .as_bool()
2536                    .ok_or_else(|| invalid_metadata("stale_pending is not a boolean"))
2537            })
2538            .transpose()?
2539            .unwrap_or(false),
2540        last_error_code: decode_optional_string(&result, "last_error_code")
2541            .map_err(invalid_metadata)?,
2542    })
2543}
2544
2545fn invalid_metadata(detail: impl Into<String>) -> CredentialResolverError {
2546    CredentialResolverError::new(CredentialErrorClass::InvalidResponse, detail)
2547}
2548
2549fn decode_record_version(value: &Value) -> Result<String, CredentialResolverError> {
2550    value
2551        .as_u64()
2552        .map(|version| version.to_string())
2553        .ok_or_else(|| invalid_metadata("record_version is not an unsigned integer"))
2554}
2555
2556/// Decodes a `credential.get` or `credential.get_scoped` response into secret bytes.
2557pub fn decode_credential_reply(
2558    value: Value,
2559) -> Result<ResolvedCredential, CredentialResolverError> {
2560    let result = reply_result(value)?;
2561    let payload = match result.get("payload") {
2562        Some(Value::Array(payload)) => payload
2563            .iter()
2564            .map(|byte| {
2565                byte.as_u64()
2566                    .and_then(|byte| u8::try_from(byte).ok())
2567                    .ok_or_else(|| {
2568                        CredentialResolverError::new(
2569                            CredentialErrorClass::InvalidResponse,
2570                            "credential payload contains a non-byte value",
2571                        )
2572                    })
2573            })
2574            .collect::<Result<Vec<_>, _>>()?,
2575        _ => {
2576            return Err(CredentialResolverError::new(
2577                CredentialErrorClass::InvalidResponse,
2578                "credential reply has no opaque payload",
2579            ));
2580        }
2581    };
2582    let version = result
2583        .get("record_version")
2584        .ok_or_else(|| invalid_metadata("credential reply has no record version"))
2585        .and_then(decode_record_version)?;
2586    let expires_at_ms = match result.get("expires_at_ms") {
2587        None | Some(Value::Null) => None,
2588        Some(value) => Some(
2589            value
2590                .as_i64()
2591                .ok_or_else(|| invalid_metadata("expires_at_ms is not an integer"))?,
2592        ),
2593    };
2594    let mut credential = ResolvedCredential::new_with_identity(
2595        payload,
2596        version,
2597        expires_at_ms,
2598        decode_optional_string(&result, "account_id").map_err(invalid_metadata)?,
2599        decode_optional_string(&result, "email").map_err(invalid_metadata)?,
2600        decode_optional_string(&result, "org_name").map_err(invalid_metadata)?,
2601    );
2602    credential.auth = decode_optional_auth(&result).map_err(invalid_metadata)?;
2603    credential.hosts = decode_optional_hosts(&result).map_err(invalid_metadata)?;
2604    credential.invalid_key = decode_optional_invalid_key(&result).map_err(invalid_metadata)?;
2605    credential.base_url = decode_optional_string(&result, "base_url").map_err(invalid_metadata)?;
2606    credential.headers = decode_optional_headers(&result).map_err(invalid_metadata)?;
2607    Ok(credential)
2608}
2609
2610/// Decodes whether `credential.report_auth_failure` accepted the report.
2611pub fn decode_report_auth_failure_reply(value: Value) -> Result<bool, CredentialResolverError> {
2612    let result = value.get("result").unwrap_or(&value);
2613    if result.get("error").is_some() {
2614        return Err(classify_error_value(result));
2615    }
2616    result
2617        .get("accepted")
2618        .and_then(Value::as_bool)
2619        .ok_or_else(|| {
2620            CredentialResolverError::new(
2621                CredentialErrorClass::InvalidResponse,
2622                "auth-failure report reply has no accepted value",
2623            )
2624        })
2625}
2626
2627/// Decodes whether `credential.report_condition` accepted the report.
2628pub fn decode_report_condition_reply(value: Value) -> Result<bool, CredentialResolverError> {
2629    decode_condition_reply(value, "accepted")
2630}
2631
2632/// Decodes whether `credential.clear_condition` removed a condition.
2633pub fn decode_clear_condition_reply(value: Value) -> Result<bool, CredentialResolverError> {
2634    decode_condition_reply(value, "cleared")
2635}
2636
2637fn decode_condition_reply(value: Value, field: &str) -> Result<bool, CredentialResolverError> {
2638    reply_result(value)?
2639        .get(field)
2640        .and_then(Value::as_bool)
2641        .ok_or_else(|| {
2642            CredentialResolverError::new(
2643                CredentialErrorClass::InvalidResponse,
2644                format!("credential condition reply has no boolean {field} value"),
2645            )
2646        })
2647}
2648#[cfg(test)]
2649mod contract_tests;
2650
2651#[cfg(test)]
2652mod client_regressions;
2653
2654#[cfg(test)]
2655mod condition_tests;
2656
2657#[cfg(test)]
2658mod tests {
2659    #[cfg(feature = "transport")]
2660    use std::sync::atomic::{AtomicUsize, Ordering};
2661
2662    use super::*;
2663
2664    #[cfg(feature = "transport")]
2665    #[derive(Debug)]
2666    struct FakeCkcredTarget {
2667        script: Mutex<VecDeque<Result<Value, CredentialResolverError>>>,
2668        requests: Mutex<Vec<(String, Option<u64>, bool)>>,
2669        reports: Mutex<Vec<(String, u64, u16)>>,
2670    }
2671
2672    #[cfg(feature = "transport")]
2673    impl CredentialGetTarget for FakeCkcredTarget {
2674        fn credential_get<'a>(
2675            &'a self,
2676            raw_handle: &'a str,
2677            min_ttl_ms: Option<u64>,
2678            force_refresh: bool,
2679        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2680            Box::pin(async move {
2681                self.requests
2682                    .lock()
2683                    .expect("fake CKCRED target poisoned")
2684                    .push((raw_handle.to_owned(), min_ttl_ms, force_refresh));
2685                self.script
2686                    .lock()
2687                    .expect("fake CKCRED target poisoned")
2688                    .pop_front()
2689                    .expect("fake CKCRED target script exhausted")
2690            })
2691        }
2692
2693        fn credential_get_scoped<'a>(
2694            &'a self,
2695            credential_id: &'a str,
2696        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2697            Box::pin(async move {
2698                self.requests
2699                    .lock()
2700                    .expect("fake CKCRED target poisoned")
2701                    .push((credential_id.to_owned(), None, false));
2702                self.script
2703                    .lock()
2704                    .expect("fake CKCRED target poisoned")
2705                    .pop_front()
2706                    .expect("fake CKCRED target script exhausted")
2707            })
2708        }
2709
2710        fn credential_get_scoped_with_min_ttl<'a>(
2711            &'a self,
2712            credential_id: &'a str,
2713            min_ttl_ms: u64,
2714        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2715            Box::pin(async move {
2716                self.requests
2717                    .lock()
2718                    .expect("fake CKCRED target poisoned")
2719                    .push((credential_id.to_owned(), Some(min_ttl_ms), false));
2720                self.script
2721                    .lock()
2722                    .expect("fake CKCRED target script exhausted")
2723                    .pop_front()
2724                    .expect("fake CKCRED target script exhausted")
2725            })
2726        }
2727
2728        fn credential_report_auth_failure<'a>(
2729            &'a self,
2730            credential_id: &'a str,
2731            record_version: u64,
2732            provider_status: u16,
2733        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2734            Box::pin(async move {
2735                self.reports
2736                    .lock()
2737                    .expect("fake CKCRED target poisoned")
2738                    .push((credential_id.to_owned(), record_version, provider_status));
2739                self.script
2740                    .lock()
2741                    .expect("fake CKCRED target script exhausted")
2742                    .pop_front()
2743                    .expect("fake CKCRED target script exhausted")
2744            })
2745        }
2746    }
2747
2748    #[cfg(feature = "transport")]
2749    #[derive(Debug)]
2750    struct DeadlineConnector {
2751        dials: Arc<AtomicUsize>,
2752    }
2753
2754    #[cfg(feature = "transport")]
2755    impl CredentialConsumerConnector for DeadlineConnector {
2756        fn connect<'a>(
2757            &'a self,
2758        ) -> CredentialResolverFuture<
2759            'a,
2760            Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
2761        > {
2762            Box::pin(async move {
2763                let dial = self.dials.fetch_add(1, Ordering::SeqCst);
2764                Ok(Box::new(DeadlineConsumer { hangs: dial == 0 })
2765                    as Box<dyn CredentialConsumerConnection>)
2766            })
2767        }
2768    }
2769
2770    #[cfg(feature = "transport")]
2771    struct DeadlineConsumer {
2772        hangs: bool,
2773    }
2774
2775    #[cfg(feature = "transport")]
2776    impl CredentialConsumerConnection for DeadlineConsumer {
2777        fn credential_get<'a>(
2778            &'a mut self,
2779            _raw_handle: &'a str,
2780            _min_ttl_ms: Option<u64>,
2781            _force_refresh: bool,
2782        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2783            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2784        }
2785
2786        fn credential_get_scoped<'a>(
2787            &'a mut self,
2788            _credential_id: &'a str,
2789            _min_ttl_ms: Option<u64>,
2790        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2791            Box::pin(async move {
2792                if self.hangs {
2793                    std::future::pending().await
2794                } else {
2795                    Ok(json!({
2796                        "payload": b"reconnected-secret".to_vec(),
2797                        "record_version": 2,
2798                    }))
2799                }
2800            })
2801        }
2802
2803        fn credential_sign<'a>(
2804            &'a mut self,
2805            _credential_id: &'a str,
2806            _payload: &'a [u8],
2807        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2808            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2809        }
2810
2811        fn credential_public_key<'a>(
2812            &'a mut self,
2813            _credential_id: &'a str,
2814        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2815            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2816        }
2817    }
2818
2819    #[cfg(feature = "transport")]
2820    #[tokio::test(start_paused = true)]
2821    async fn silent_call_deadline_is_transport_rebuilds_and_releases_mutex_mutation_proof() {
2822        let dials = Arc::new(AtomicUsize::new(0));
2823        let deadline = Duration::from_millis(20);
2824        let target = Arc::new(LiveCredentialGetTarget::new(
2825            Arc::new(DeadlineConnector {
2826                dials: Arc::clone(&dials),
2827            }),
2828            deadline,
2829        ));
2830        let first_error = tokio::time::timeout(
2831            deadline.saturating_mul(3),
2832            target.credential_get_scoped("github_app:first"),
2833        )
2834        .await
2835        .expect("the scoped call's own timeout must fire")
2836        .expect_err("the silent first consumer must reach the whole-call deadline");
2837        assert_eq!(dials.load(Ordering::SeqCst), 1);
2838
2839        // Start the recovery call after the timeout so it has its own full budget.
2840        let second = tokio::time::timeout(
2841            deadline.saturating_mul(3),
2842            target.credential_get_scoped("github_app:second"),
2843        )
2844        .await
2845        .expect("a timed-out holder must release the consumer mutex")
2846        .expect("the rebuilt consumer must serve the second caller");
2847        assert_eq!(first_error.class, CredentialErrorClass::Transport);
2848        assert!(first_error.retryable());
2849        assert_eq!(
2850            first_error.to_string(),
2851            "credential_transport: credential.get_scoped timed out waiting for the credential route"
2852        );
2853        assert_eq!(second["payload"], json!(b"reconnected-secret".to_vec()));
2854        assert_eq!(
2855            dials.load(Ordering::SeqCst),
2856            2,
2857            "the deadline must clear the stale cached consumer before the next call"
2858        );
2859    }
2860
2861    #[cfg(feature = "transport")]
2862    #[tokio::test(start_paused = true)]
2863    async fn handle_and_seal_deadlines_include_the_queue_without_dialing() {
2864        let dials = Arc::new(AtomicUsize::new(0));
2865        let deadline = Duration::from_secs(5);
2866        let target = LiveCredentialGetTarget::new(
2867            Arc::new(DeadlineConnector {
2868                dials: dials.clone(),
2869            }),
2870            deadline,
2871        );
2872        let mut holder = target.consumer.lock().await;
2873        *holder = Some(Box::new(DeadlineConsumer { hangs: false }));
2874        let (get, seal) = tokio::time::timeout(deadline + Duration::from_millis(1), async {
2875            tokio::join!(
2876                target.credential_get("fixture-handle", None, false),
2877                target.credential_seal(SealRequest {
2878                    credential_id: "kem:fixture",
2879                    recipient_public_key: &[1; 32],
2880                    info: b"",
2881                    aad: b"",
2882                    plaintext: b"fixture",
2883                }),
2884            )
2885        })
2886        .await
2887        .expect("handle and seal must time out while the route is held");
2888        assert!(get.unwrap_err().is_transport());
2889        assert!(seal.unwrap_err().is_transport());
2890        assert!(holder.is_some());
2891        assert_eq!(dials.load(Ordering::SeqCst), 0);
2892    }
2893
2894    #[cfg(feature = "transport")]
2895    #[tokio::test(start_paused = true)]
2896    async fn scoped_read_deadlines_expire_in_the_queue_without_clearing_the_held_route() {
2897        let dials = Arc::new(AtomicUsize::new(0));
2898        let deadline = Duration::from_secs(5);
2899        let target = LiveCredentialGetTarget::new(
2900            Arc::new(DeadlineConnector {
2901                dials: dials.clone(),
2902            }),
2903            deadline,
2904        );
2905        let mut holder = target.consumer.lock().await;
2906        *holder = Some(Box::new(DeadlineConsumer { hangs: false }));
2907
2908        let results = tokio::time::timeout(deadline + Duration::from_millis(1), async {
2909            tokio::join!(
2910                target.credential_get_scoped("github_app:queued"),
2911                target.credential_get_scoped_with_min_ttl("github_app:queued", 1),
2912                target.credential_status("github_app:queued"),
2913                target.credential_list_scoped(),
2914            )
2915        })
2916        .await
2917        .expect("queued reads must time out while another caller still holds the route");
2918        for result in [results.0, results.1, results.2, results.3] {
2919            assert!(result.unwrap_err().is_transport());
2920        }
2921        assert!(holder.is_some());
2922        drop(holder);
2923        target
2924            .credential_get_scoped("github_app:later")
2925            .await
2926            .unwrap();
2927        assert_eq!(
2928            dials.load(Ordering::SeqCst),
2929            0,
2930            "the holder's route must be reused"
2931        );
2932    }
2933
2934    #[cfg(feature = "transport")]
2935    #[tokio::test(start_paused = true)]
2936    async fn scoped_read_shares_one_deadline_between_connecting_and_calling() {
2937        #[derive(Debug)]
2938        struct SlowConnector(Duration);
2939
2940        impl CredentialConsumerConnector for SlowConnector {
2941            fn connect(
2942                &self,
2943            ) -> CredentialResolverFuture<
2944                '_,
2945                Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
2946            > {
2947                Box::pin(async move {
2948                    tokio::time::sleep(self.0).await;
2949                    Ok(Box::new(DeadlineConsumer { hangs: true })
2950                        as Box<dyn CredentialConsumerConnection>)
2951                })
2952            }
2953        }
2954
2955        let deadline = Duration::from_secs(5);
2956        for dial_time in [Duration::from_secs(3), Duration::from_secs(6)] {
2957            let target = LiveCredentialGetTarget::new(Arc::new(SlowConnector(dial_time)), deadline);
2958            let error = tokio::time::timeout(
2959                deadline + Duration::from_millis(1),
2960                target.credential_get_scoped("github_app:slow"),
2961            )
2962            .await
2963            .expect("dial and request must share one deadline")
2964            .unwrap_err();
2965            assert!(error.is_transport());
2966            assert!(target.consumer.lock().await.is_none());
2967        }
2968    }
2969
2970    #[cfg(feature = "transport")]
2971    #[tokio::test]
2972    async fn live_shape_red_proof_retry_class_and_capability_redaction() {
2973        let raw_handle = "capability-handle-must-never-leak";
2974        let target = Arc::new(FakeCkcredTarget {
2975            script: Mutex::new(VecDeque::from([
2976                Err(CredentialResolverError::new(
2977                    CredentialErrorClass::Transport,
2978                    "credential service is temporarily unavailable",
2979                )),
2980                Ok(json!({
2981                    "result": {
2982                        "payload": b"api-secret".to_vec(),
2983                        "record_version": 7,
2984                        "expires_at_ms": 1234,
2985                    }
2986                })),
2987            ])),
2988            requests: Mutex::new(Vec::new()),
2989            reports: Mutex::new(Vec::new()),
2990        });
2991        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2992
2993        let credential = resolver.resolve(raw_handle, Some(500), true).await.unwrap();
2994        assert_eq!(credential.expose(), b"api-secret");
2995        assert_eq!(credential.record_version, "7");
2996        assert_eq!(target.requests.lock().unwrap().len(), 2);
2997        assert!(!format!("{credential:?}").contains(raw_handle));
2998
2999        let permanent = CredentialResolverError::new(
3000            CredentialErrorClass::Permanent,
3001            "credential service rejected the request",
3002        );
3003        assert!(!permanent.retryable());
3004        assert!(!permanent.to_string().contains(raw_handle));
3005    }
3006
3007    #[test]
3008    fn wire_refusals_follow_the_daemon_recovery_verdict() {
3009        for (code, expected_back, retryable) in [
3010            ("unknown_module", None, false),
3011            ("unknown_channel", None, false),
3012            ("stale_route_epoch", None, false),
3013            ("missing_identity", None, false),
3014            ("future_refusal", None, false),
3015            ("module_warming", None, true),
3016            ("module_reloading", None, true),
3017            ("target_unavailable", Some(true), true),
3018            ("target_unavailable", Some(false), false),
3019            ("module_timeout", None, true),
3020        ] {
3021            let error = decode_wire_error(
3022                &serde_json::to_vec(&json!({
3023                    "code": code,
3024                    "message": format!("{code} 1"),
3025                    "detail": { "expected_back": expected_back },
3026                }))
3027                .unwrap(),
3028            );
3029            assert_eq!(error.retryable(), retryable, "{code} {expected_back:?}");
3030            assert!(error.to_string().contains(code), "verbatim code preserved");
3031        }
3032        // A Response refusal with an unknown code is not a transport verdict.
3033        let other = classify_error_value(&json!({"code": "weird_new_code"}));
3034        assert!(!other.is_transport());
3035    }
3036
3037    #[test]
3038    fn ckcred_contract_red_proof_request_shape_and_error_capability_redaction() {
3039        let raw_handle = "raw-capability-token";
3040        assert_eq!(
3041            credential_get_request(raw_handle, Some(250), true),
3042            json!({
3043                "method": "credential.get",
3044                "params": {
3045                    "handle": raw_handle,
3046                    "min_ttl_ms": 250,
3047                    "force_refresh": true,
3048                }
3049            })
3050        );
3051        let credential_id = "github_app:scoped-agent";
3052        assert_eq!(
3053            credential_get_scoped_request(credential_id, None),
3054            json!({
3055                "method": "credential.get_scoped",
3056                "params": { "credential_id": credential_id },
3057            })
3058        );
3059        assert_eq!(
3060            credential_get_scoped_request(credential_id, Some(500)),
3061            json!({
3062                "method": "credential.get_scoped",
3063                "params": {
3064                    "credential_id": credential_id,
3065                    "min_ttl_ms": 500,
3066                },
3067            })
3068        );
3069        assert_eq!(
3070            credential_report_auth_failure_request(credential_id, 7, 401),
3071            json!({
3072                "method": "credential.report_auth_failure",
3073                "params": {
3074                    "credential_id": credential_id,
3075                    "provider_status": 401,
3076                    "record_version": 7,
3077                },
3078            })
3079        );
3080        assert_eq!(
3081            credential_status_request(credential_id),
3082            json!({
3083                "method": "credential.status",
3084                "params": { "credential_id": credential_id },
3085            })
3086        );
3087        // CKCRED 3aaf0e3: sign and public_key are handle-less - addressed by
3088        // credential NAME under principal authority, never a bearer handle
3089        // (the handle spelling was the pre-cutover wire and now refuses).
3090        let signing_credential = "signing:agent-assertion:1";
3091        assert_eq!(
3092            credential_sign_request(signing_credential, b"abc"),
3093            json!({
3094                "method": "credential.sign",
3095                "params": {
3096                    "credential_id": signing_credential,
3097                    "payload_b64": "YWJj",
3098                },
3099            })
3100        );
3101        assert_eq!(
3102            credential_public_key_request(signing_credential),
3103            json!({
3104                "method": "credential.public_key",
3105                "params": { "credential_id": signing_credential },
3106            })
3107        );
3108        let error = decode_credential_reply(json!({"result": {"error": {
3109            "class": "auth_required",
3110            "code": "needs_login",
3111            "message": format!("unknown handle {raw_handle}"),
3112        }}}))
3113        .unwrap_err();
3114        assert_eq!(error.class, CredentialErrorClass::AuthRequired);
3115        assert_eq!(error.code(), "credential_auth_required");
3116        assert!(!error.to_string().contains(raw_handle));
3117    }
3118
3119    #[test]
3120    fn signing_replies_decode_exact_ed25519_material_and_reject_wrong_algorithm() {
3121        let signature = decode_signature_reply(json!({
3122            "result": {
3123                "signature_b64": base64::engine::general_purpose::STANDARD.encode([7_u8; 64]),
3124                "key_id": "0123456789abcdef",
3125            }
3126        }))
3127        .unwrap();
3128        assert_eq!(signature.signature_hex, "07".repeat(64));
3129        assert_eq!(signature.key_id, "0123456789abcdef");
3130
3131        let public_key_hex = "ab".repeat(32);
3132        let public_key_bytes = [0xab_u8; 32];
3133        let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
3134        let public_key = decode_public_key_reply(json!({
3135            "result": {
3136                "public_key_hex": public_key_hex,
3137                "key_id": key_id,
3138                "algorithm": "ed25519",
3139            }
3140        }))
3141        .unwrap();
3142        assert_eq!(public_key.public_key_hex, "ab".repeat(32));
3143        assert_eq!(public_key.algorithm, PublicKeyAlgorithm::Ed25519);
3144
3145        let error = decode_public_key_reply(json!({
3146            "result": {
3147                "public_key_hex": "ab".repeat(32),
3148                "key_id": hex_bytes(&Sha256::digest(public_key_bytes)[..8]),
3149                "algorithm": "rsa",
3150            }
3151        }))
3152        .unwrap_err();
3153        assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
3154    }
3155
3156    #[test]
3157    fn public_key_replies_type_x25519_and_refuse_unknown_algorithms_and_wrong_key_ids() {
3158        let public_key_bytes = [0xcd_u8; 32];
3159        let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
3160        let reply = |algorithm: &str, key_id: &str| {
3161            json!({
3162                "result": {
3163                    "public_key_hex": "cd".repeat(32),
3164                    "key_id": key_id,
3165                    "algorithm": algorithm,
3166                }
3167            })
3168        };
3169
3170        let x25519 = decode_public_key_reply(reply("x25519", &key_id)).unwrap();
3171        assert_eq!(x25519.algorithm, PublicKeyAlgorithm::X25519);
3172        assert_eq!(x25519.algorithm.as_str(), "x25519");
3173        assert_eq!(x25519.public_key_hex, "cd".repeat(32));
3174        assert_eq!(x25519.key_id, key_id);
3175        let ed25519 = decode_public_key_reply(reply("ed25519", &key_id)).unwrap();
3176        assert_eq!(ed25519.algorithm, PublicKeyAlgorithm::Ed25519);
3177
3178        // Only the two exact lowercase names the vault sends are keys this client knows
3179        // how to use; anything else, including a case variant, is a bad reply.
3180        for algorithm in ["rsa", "X25519", "Ed25519", ""] {
3181            assert_eq!(
3182                decode_public_key_reply(reply(algorithm, &key_id))
3183                    .unwrap_err()
3184                    .class,
3185                CredentialErrorClass::InvalidResponse,
3186                "{algorithm:?}"
3187            );
3188        }
3189        // A key id that does not identify the key is refused for both kinds, so an
3190        // X25519 reply gets the same binding check a signing key does.
3191        let wrong_key_id = hex_bytes(&Sha256::digest([0xab_u8; 32])[..8]);
3192        for algorithm in ["x25519", "ed25519"] {
3193            let error = decode_public_key_reply(reply(algorithm, &wrong_key_id)).unwrap_err();
3194            assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
3195            assert!(
3196                error.to_string().contains("key_id does not identify"),
3197                "{algorithm}: {error}"
3198            );
3199        }
3200    }
3201
3202    #[test]
3203    fn unknown_method_without_a_class_remains_unclassified_and_preserves_producer_details() {
3204        let error = decode_established_route_wire_error(
3205            Flags(0),
3206            br#"{"code":"unknown_method","message":"unknown method 'credential.put'"}"#,
3207        );
3208        assert_eq!(error.class, CredentialErrorClass::Unclassified);
3209        assert_eq!(error.code(), "unknown_method");
3210        assert!(!error.retryable());
3211        assert_ne!(error.class, CredentialErrorClass::Permanent);
3212        assert_eq!(
3213            error.to_string(),
3214            "unknown_method: unknown method 'credential.put'"
3215        );
3216    }
3217
3218    #[test]
3219    fn error_shaped_success_reply_surfaces_the_typed_class_and_code() {
3220        // The vault answers a principal-bound handle miss as a SUCCESS frame
3221        // carrying result.error; demanding a payload from it laundered the
3222        // typed answer into invalid_response on the first live push fetch.
3223        let error = decode_credential_reply(json!({
3224            "result": { "error": { "class": "permanent", "code": "not_found" } }
3225        }))
3226        .expect_err("an error reply must not decode as a credential");
3227        assert_eq!(error.class, CredentialErrorClass::CredentialAbsent);
3228        assert!(
3229            error.to_string().contains("not_found"),
3230            "the producer's code must survive classification: {error}"
3231        );
3232        assert!(
3233            !error.to_string().contains("opaque payload"),
3234            "a typed refusal must never render as invalid_response: {error}"
3235        );
3236    }
3237
3238    #[cfg(feature = "transport")]
3239    #[tokio::test]
3240    async fn scoped_transport_failure_returns_without_internal_retry_ladder_mutation_proof() {
3241        let credential_id = "github_app:bounded-agent";
3242        let target = Arc::new(FakeCkcredTarget {
3243            script: Mutex::new(VecDeque::from([
3244                Err(CredentialResolverError::transport(
3245                    "connection reset by peer",
3246                )),
3247                Ok(json!({
3248                    "payload": b"must-not-be-reached".to_vec(),
3249                    "record_version": 2,
3250                })),
3251            ])),
3252            requests: Mutex::new(Vec::new()),
3253            reports: Mutex::new(Vec::new()),
3254        });
3255        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
3256
3257        let error = resolver
3258            .get_scoped(credential_id)
3259            .await
3260            .expect_err("caller owns the scoped redial");
3261
3262        assert_eq!(error.class, CredentialErrorClass::Transport);
3263        assert_eq!(target.requests.lock().unwrap().len(), 1);
3264    }
3265
3266    #[cfg(feature = "transport")]
3267    #[tokio::test]
3268    async fn scoped_get_with_min_ttl_forwards_the_requested_bound() {
3269        let credential_id = "oauth:anthropic";
3270        let target = Arc::new(FakeCkcredTarget {
3271            script: Mutex::new(VecDeque::from([Ok(json!({
3272                "payload": b"served-token".to_vec(),
3273                "record_version": 4,
3274                "expires_at_ms": 1_900_000_000_000_i64,
3275            }))])),
3276            requests: Mutex::new(Vec::new()),
3277            reports: Mutex::new(Vec::new()),
3278        });
3279        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
3280
3281        let credential = resolver
3282            .get_scoped_with_min_ttl(credential_id, 300_000)
3283            .await
3284            .unwrap();
3285
3286        assert_eq!(credential.expose(), b"served-token");
3287        assert_eq!(
3288            target.requests.lock().unwrap().as_slice(),
3289            &[(credential_id.to_owned(), Some(300_000), false)]
3290        );
3291    }
3292
3293    #[cfg(feature = "transport")]
3294    #[tokio::test]
3295    async fn report_auth_failure_rejects_unsupported_status_before_sending() {
3296        let credential_id = "apikey:openrouter";
3297        let target = Arc::new(FakeCkcredTarget {
3298            script: Mutex::new(VecDeque::from([Ok(json!({
3299                "result": { "accepted": true }
3300            }))])),
3301            requests: Mutex::new(Vec::new()),
3302            reports: Mutex::new(Vec::new()),
3303        });
3304        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
3305
3306        let error = resolver
3307            .report_auth_failure(credential_id, 12, 429)
3308            .await
3309            .expect_err("only provider 401 and 403 statuses are sent");
3310        assert_eq!(error.class, CredentialErrorClass::Permanent);
3311        assert!(target.reports.lock().unwrap().is_empty());
3312    }
3313
3314    #[cfg(feature = "transport")]
3315    #[tokio::test]
3316    async fn scoped_reads_use_the_credential_id_and_decode_the_record_directly() {
3317        let credential_id = "github_app:scoped-agent";
3318        let target = Arc::new(FakeCkcredTarget {
3319            script: Mutex::new(VecDeque::from([Ok(json!({
3320                "payload": b"-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----".to_vec(),
3321                "record_version": 7,
3322            }))])),
3323            requests: Mutex::new(Vec::new()),
3324            reports: Mutex::new(Vec::new()),
3325        });
3326        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
3327
3328        let credential = resolver.get_scoped(credential_id).await.unwrap();
3329
3330        assert_eq!(
3331            credential.expose(),
3332            b"-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----"
3333        );
3334        assert_eq!(credential.record_version, "7");
3335        assert_eq!(
3336            target.requests.lock().unwrap().as_slice(),
3337            &[(credential_id.to_owned(), None, false)]
3338        );
3339    }
3340
3341    #[cfg(feature = "transport")]
3342    #[test]
3343    fn route_open_body_omits_project_fields() {
3344        let body = route_open_body_with_nonce("prefrontal-core", "nonce-under-test");
3345        assert_eq!(
3346            body["identity"],
3347            json!({
3348                "harness": "prefrontal-core",
3349                "session": "campaign-credential-consumer",
3350            })
3351        );
3352        assert!(body.get("project_root").is_none());
3353        assert!(body.get("project_id").is_none());
3354    }
3355
3356    #[cfg(feature = "transport")]
3357    #[test]
3358    fn route_open_body_carries_the_reserved_consumer_identity_when_the_nonce_is_present() {
3359        let body = route_open_body_with_nonce("prefrontal-core", "nonce-under-test");
3360        assert_eq!(
3361            body.pointer("/consumer_identity/module_id")
3362                .and_then(Value::as_str),
3363            Some("prefrontal-core"),
3364            "a supervised launch must ride the reserved principal"
3365        );
3366        assert_eq!(
3367            body.pointer("/consumer_identity/launch_nonce")
3368                .and_then(Value::as_str),
3369            Some("nonce-under-test")
3370        );
3371    }
3372
3373    #[cfg(feature = "transport")]
3374    #[test]
3375    fn motor_credential_route_presents_its_launch_nonce() {
3376        let body = route_open_body_with_nonce("ck-motor", "motor-nonce");
3377        assert_eq!(body["op"], "route.open");
3378        assert_eq!(body["target"]["module_id"], "claustrum");
3379        assert_eq!(
3380            body["consumer_identity"],
3381            json!({"module_id":"ck-motor", "launch_nonce":"motor-nonce"})
3382        );
3383    }
3384
3385    #[cfg(feature = "transport")]
3386    #[tokio::test]
3387    async fn signing_not_found_and_auth_required_are_terminal_without_retries() {
3388        struct TerminalTarget {
3389            code: &'static str,
3390            calls: AtomicUsize,
3391        }
3392        impl CredentialGetTarget for TerminalTarget {
3393            fn credential_get<'a>(
3394                &'a self,
3395                _: &'a str,
3396                _: Option<u64>,
3397                _: bool,
3398            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
3399                panic!("signing must not read private credentials")
3400            }
3401            fn credential_sign<'a>(
3402                &'a self,
3403                _: &'a str,
3404                _: &'a [u8],
3405            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
3406                Box::pin(async move {
3407                    self.calls.fetch_add(1, Ordering::SeqCst);
3408                    Err(classify_error_value(
3409                        &json!({"code":self.code, "class":"transient", "message":"do not log vault material"}),
3410                    ))
3411                })
3412            }
3413            fn credential_public_key<'a>(
3414                &'a self,
3415                _: &'a str,
3416            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
3417                self.credential_sign("unused", b"")
3418            }
3419        }
3420        for (code, class) in [
3421            ("not_found", CredentialErrorClass::CredentialAbsent),
3422            ("auth_required", CredentialErrorClass::AuthRequired),
3423        ] {
3424            let target = Arc::new(TerminalTarget {
3425                code,
3426                calls: AtomicUsize::new(0),
3427            });
3428            let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
3429            assert_eq!(
3430                resolver
3431                    .sign("signing:ck-motor-ssh:1", b"challenge")
3432                    .await
3433                    .unwrap_err()
3434                    .class,
3435                class
3436            );
3437            assert_eq!(
3438                resolver
3439                    .public_key("signing:ck-motor-ssh:1")
3440                    .await
3441                    .unwrap_err()
3442                    .class,
3443                class
3444            );
3445            assert_eq!(target.calls.load(Ordering::SeqCst), 2);
3446            for wire in [
3447                json!({"code":code}),
3448                json!({"error":{"code":code}}),
3449                json!({"error":{"code":code,"class":"transient"}}),
3450            ] {
3451                let error = classify_error_value(&wire);
3452                assert_eq!(error.class, class);
3453                assert!(!error.retryable());
3454                assert!(!error.is_transport());
3455                assert!(!error.to_string().contains("do not log vault material"));
3456            }
3457        }
3458    }
3459
3460    #[cfg(feature = "transport")]
3461    #[test]
3462    fn route_open_body_carries_prefrontal_routing_as_consumer_id() {
3463        let body = route_open_body_with_nonce("prefrontal-routing", "routing-nonce-under-test");
3464
3465        assert_eq!(
3466            body.pointer("/consumer_identity/module_id")
3467                .and_then(Value::as_str),
3468            Some("prefrontal-routing")
3469        );
3470        assert_eq!(
3471            body.pointer("/identity/harness").and_then(Value::as_str),
3472            Some("prefrontal-routing")
3473        );
3474    }
3475
3476    /// An absent, blank or unreadable nonce stops the route open instead of letting it
3477    /// through unscoped, and does so with an error the module can refuse with, not a
3478    /// panic that would take the module process down.
3479    #[cfg(feature = "transport")]
3480    #[test]
3481    fn route_open_body_requires_the_launch_nonce_for_the_reserved_principal() {
3482        assert_eq!(
3483            required_launch_nonce(Ok(Some("nonce".to_string()))).unwrap(),
3484            "nonce"
3485        );
3486        for read in [
3487            Ok(None),
3488            Ok(Some("  ".to_string())),
3489            Err("descriptor 3 is not open".to_string()),
3490        ] {
3491            let result = std::panic::catch_unwind(|| required_launch_nonce(read.clone()));
3492            let refusal = result
3493                .unwrap_or_else(|_| panic!("{read:?} panicked instead of refusing"))
3494                .expect_err("a missing nonce must not yield one");
3495            assert_eq!(
3496                refusal.class,
3497                CredentialErrorClass::AuthRequired,
3498                "{read:?}"
3499            );
3500            assert!(!refusal.retryable(), "{read:?}");
3501        }
3502    }
3503
3504    #[test]
3505    fn list_scoped_request_sends_no_enrollment_token() {
3506        assert_eq!(
3507            credential_list_scoped_request(),
3508            json!({ "method": "credential.list_scoped", "params": {} })
3509        );
3510    }
3511
3512    /// The reply shape is claustrum's `ListScopedResult` / `ListScopedCredential`
3513    /// serialization (credentials-module `read_surface.rs`): optional fields are
3514    /// omitted when absent, and the id is `id`, not `credential_id`. It is built
3515    /// from that struct, not captured from a live vault, because no principal of
3516    /// this repository yet holds a grant that lists Claude rows.
3517    #[test]
3518    fn list_scoped_reply_decodes_identity_rows_grants_and_view() {
3519        let listing = decode_list_scoped_reply(json!({
3520            "result": {
3521                "credentials": [
3522                    {
3523                        "id": "oauth:anthropic:yiyi",
3524                        "categories": ["anthropic-native", "llm-provider"],
3525                        "type": "oauth",
3526                        "serves": ["anthropic"],
3527                        "refresh_adapter": "anthropic",
3528                        "state": "active",
3529                        "record_version": 227,
3530                        "operations": ["list"],
3531                        "account_id": "acct-1",
3532                        "email": "a@example.test"
3533                    },
3534                    {
3535                        "id": "apikey:artificial-analysis",
3536                        "categories": [],
3537                        "type": "apikey",
3538                        "serves": [],
3539                        "state": "active",
3540                        "record_version": 1,
3541                        "operations": ["read"]
3542                    }
3543                ],
3544                "grants": 1,
3545                "grant_tuples": [
3546                    {"selector_kind": "category", "selector": "anthropic-native", "operation": "list"}
3547                ],
3548                "view": "digest"
3549            }
3550        }))
3551        .expect("listing decodes");
3552        assert_eq!(listing.view, "digest");
3553        assert_eq!(listing.credentials.len(), 2);
3554        let claude = &listing.credentials[0];
3555        assert_eq!(claude.id, "oauth:anthropic:yiyi");
3556        assert_eq!(claude.refresh_adapter.as_deref(), Some("anthropic"));
3557        assert_eq!(claude.account_id.as_deref(), Some("acct-1"));
3558        assert_eq!(claude.record_version, 227);
3559        assert_eq!(listing.credentials[1].account_id, None);
3560        assert_eq!(listing.credentials[1].refresh_adapter, None);
3561        assert_eq!(
3562            listing.grant_tuples,
3563            vec![ListedGrant {
3564                selector_kind: "category".into(),
3565                selector: "anthropic-native".into(),
3566                operation: "list".into(),
3567            }]
3568        );
3569    }
3570
3571    #[test]
3572    fn list_scoped_reply_without_view_is_invalid_and_unreadable_rows_are_local() {
3573        let no_view = decode_list_scoped_reply(json!({ "result": { "credentials": [] } }))
3574            .expect_err("no view");
3575        assert_eq!(no_view.class, CredentialErrorClass::InvalidResponse);
3576        let no_id = decode_list_scoped_reply(json!({
3577            "result": { "credentials": [{ "state": "active" }], "view": "v" }
3578        }))
3579        .expect("row without id does not reject the listing");
3580        assert!(no_id.credentials.is_empty());
3581        assert_eq!(
3582            no_id.undecodable_credentials,
3583            ["row 0: id is not a non-empty string"]
3584        );
3585    }
3586
3587    /// Optional metadata sent as explicit null decodes as absent, so the row stays in
3588    /// the listing; a wrong type in the same field is still a row-local decode failure.
3589    #[test]
3590    fn list_scoped_reply_treats_explicit_null_optional_fields_as_absent() {
3591        let row = |extra: Value| {
3592            let mut row = json!({
3593                "id": "oauth:anthropic",
3594                "categories": ["llm-provider"],
3595                "type": "oauth",
3596                "serves": ["anthropic"],
3597                "state": "active",
3598                "record_version": 3,
3599                "operations": ["read"],
3600            });
3601            row.as_object_mut()
3602                .unwrap()
3603                .extend(extra.as_object().unwrap().clone());
3604            row
3605        };
3606        let listing = decode_list_scoped_reply(json!({
3607            "result": {
3608                "credentials": [
3609                    row(json!({
3610                        "provider_ids": null,
3611                        "auth_method": null,
3612                        "refresh_adapter": null,
3613                        "account_id": null,
3614                        "email": null,
3615                        "org_name": null,
3616                        "plan_tier": null,
3617                        "plan_tier_source": null,
3618                        "plan_tier_since_ms": null,
3619                        "org_id": null,
3620                        "github_app": null,
3621                    })),
3622                    row(json!({ "plan_tier": 20 })),
3623                ],
3624                "view": "v",
3625            }
3626        }))
3627        .expect("listing");
3628        assert_eq!(
3629            listing.credentials.len(),
3630            1,
3631            "{:?}",
3632            listing.undecodable_credentials
3633        );
3634        let listed = &listing.credentials[0];
3635        assert!(listed.provider_ids.is_empty());
3636        assert!(listed.plan_tier_since_ms.is_none());
3637        assert!(listed.org_id.is_none());
3638        assert!(listed.github_app.is_none());
3639        assert_eq!(
3640            (
3641                &listed.auth_method,
3642                &listed.refresh_adapter,
3643                &listed.account_id,
3644                &listed.email,
3645                &listed.org_name,
3646                &listed.plan_tier,
3647                &listed.plan_tier_source,
3648            ),
3649            (&None, &None, &None, &None, &None, &None, &None)
3650        );
3651        assert_eq!(
3652            listing.undecodable_credentials,
3653            ["oauth:anthropic: plan_tier is not a string"]
3654        );
3655    }
3656}