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