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