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": "example", "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    pub fn new(
634        connection_file_path: PathBuf,
635        project_root: PathBuf,
636        consumer_module_id: impl Into<String>,
637    ) -> Self {
638        Self {
639            target: Arc::new(LiveCredentialGetTarget::new(
640                Arc::new(LiveCredentialConnector {
641                    connection_file_path,
642                    project_root,
643                    consumer_module_id: consumer_module_id.into(),
644                }),
645                CREDENTIAL_CALL_DEADLINE,
646            )),
647            transient_retries: DEFAULT_TRANSIENT_RETRIES,
648        }
649    }
650
651    #[doc(hidden)]
652    pub fn with_live_consumer_identity(
653        connection_file_path: PathBuf,
654        project_root: PathBuf,
655        consumer_module_id: String,
656    ) -> Self {
657        Self {
658            target: Arc::new(LiveCredentialGetTarget::new(
659                Arc::new(LiveCredentialConnector {
660                    connection_file_path,
661                    project_root,
662                    consumer_module_id,
663                }),
664                CREDENTIAL_CALL_DEADLINE,
665            )),
666            transient_retries: DEFAULT_TRANSIENT_RETRIES,
667        }
668    }
669
670    #[doc(hidden)]
671    pub fn with_target(target: Arc<dyn CredentialGetTarget>, transient_retries: usize) -> Self {
672        Self {
673            target,
674            transient_retries,
675        }
676    }
677}
678
679#[cfg(feature = "transport")]
680impl CredentialResolver for ClaustrumCredentialResolver {
681    fn watch_scoped<'a>(
682        &'a self,
683        enrollment_token: Option<&'a str>,
684    ) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
685        self.target.credential_watch_scoped(enrollment_token)
686    }
687
688    fn resolve<'a>(
689        &'a self,
690        raw_handle: &'a str,
691        min_ttl_ms: Option<u64>,
692        force_refresh: bool,
693    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
694        Box::pin(async move {
695            let mut retries = 0;
696            loop {
697                match self
698                    .target
699                    .credential_get(raw_handle, min_ttl_ms, force_refresh)
700                    .await
701                {
702                    Ok(reply) => return decode_credential_reply(reply),
703                    Err(error) if error.retryable() && retries < self.transient_retries => {
704                        retries += 1;
705                    }
706                    Err(error) => return Err(error),
707                }
708            }
709        })
710    }
711
712    fn get_scoped<'a>(
713        &'a self,
714        credential_id: &'a str,
715    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
716        Box::pin(async move {
717            self.target
718                .credential_get_scoped(credential_id)
719                .await
720                .and_then(decode_credential_reply)
721        })
722    }
723
724    fn get_scoped_with_min_ttl<'a>(
725        &'a self,
726        credential_id: &'a str,
727        min_ttl_ms: u64,
728    ) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
729        Box::pin(async move {
730            self.target
731                .credential_get_scoped_with_min_ttl(credential_id, min_ttl_ms)
732                .await
733                .and_then(decode_credential_reply)
734        })
735    }
736
737    fn report_auth_failure<'a>(
738        &'a self,
739        credential_id: &'a str,
740        record_version: u64,
741        provider_status: u16,
742    ) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
743        Box::pin(async move {
744            if !matches!(provider_status, 401 | 403) {
745                return Err(CredentialResolverError::new(
746                    CredentialErrorClass::Permanent,
747                    "provider status must be 401 or 403",
748                ));
749            }
750            self.target
751                .credential_report_auth_failure(credential_id, record_version, provider_status)
752                .await
753                .and_then(decode_report_auth_failure_reply)
754        })
755    }
756
757    fn status_scoped<'a>(
758        &'a self,
759        credential_id: &'a str,
760    ) -> CredentialResolverFuture<'a, Result<CredentialStatus, CredentialResolverError>> {
761        Box::pin(async move {
762            self.target
763                .credential_status(credential_id)
764                .await
765                .and_then(decode_credential_status_reply)
766        })
767    }
768
769    fn sign<'a>(
770        &'a self,
771        credential_id: &'a str,
772        payload: &'a [u8],
773    ) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
774        Box::pin(async move {
775            let mut retries = 0;
776            loop {
777                match self.target.credential_sign(credential_id, payload).await {
778                    Ok(reply) => return decode_signature_reply(reply),
779                    Err(error) if error.retryable() && retries < self.transient_retries => {
780                        retries += 1;
781                    }
782                    Err(error) => return Err(error),
783                }
784            }
785        })
786    }
787
788    fn public_key<'a>(
789        &'a self,
790        credential_id: &'a str,
791    ) -> CredentialResolverFuture<'a, Result<CredentialPublicKey, CredentialResolverError>> {
792        Box::pin(async move {
793            let mut retries = 0;
794            loop {
795                match self.target.credential_public_key(credential_id).await {
796                    Ok(reply) => return decode_public_key_reply(reply),
797                    Err(error) if error.retryable() && retries < self.transient_retries => {
798                        retries += 1;
799                    }
800                    Err(error) => return Err(error),
801                }
802            }
803        })
804    }
805
806    fn seal<'a>(
807        &'a self,
808        request: SealRequest<'a>,
809    ) -> CredentialResolverFuture<'a, Result<CredentialSeal, CredentialResolverError>> {
810        // One attempt only; see the trait method for why seal is never retried here.
811        Box::pin(async move {
812            self.target
813                .credential_seal(request)
814                .await
815                .and_then(decode_seal_reply)
816        })
817    }
818
819    fn list_scoped(
820        &self,
821    ) -> CredentialResolverFuture<'_, Result<ScopedCredentialListing, CredentialResolverError>>
822    {
823        // One attempt per call: the caller polls on its own cadence, so a failed
824        // listing is simply retried at the next poll.
825        Box::pin(async move {
826            self.target
827                .credential_list_scoped()
828                .await
829                .and_then(decode_list_scoped_reply)
830        })
831    }
832}
833
834#[cfg(feature = "transport")]
835trait CredentialConsumerConnection: Send {
836    fn into_scoped_watch(
837        self: Box<Self>,
838        _enrollment_token: Option<String>,
839    ) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
840        Box::pin(async { Err(CredentialResolverError::unavailable()) })
841    }
842
843    fn credential_get<'a>(
844        &'a mut self,
845        raw_handle: &'a str,
846        min_ttl_ms: Option<u64>,
847        force_refresh: bool,
848    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
849
850    fn credential_get_scoped<'a>(
851        &'a mut self,
852        credential_id: &'a str,
853        min_ttl_ms: Option<u64>,
854    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
855
856    fn credential_report_auth_failure<'a>(
857        &'a mut self,
858        _credential_id: &'a str,
859        _record_version: u64,
860        _provider_status: u16,
861    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
862        Box::pin(async {
863            Err(CredentialResolverError::new(
864                CredentialErrorClass::Unavailable,
865                "credential auth-failure reports are unavailable",
866            ))
867        })
868    }
869
870    fn credential_status<'a>(
871        &'a mut self,
872        _credential_id: &'a str,
873    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
874        Box::pin(async {
875            Err(CredentialResolverError::new(
876                CredentialErrorClass::Permanent,
877                "credential status reads are unavailable",
878            ))
879        })
880    }
881
882    fn credential_sign<'a>(
883        &'a mut self,
884        credential_id: &'a str,
885        payload: &'a [u8],
886    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
887
888    fn credential_public_key<'a>(
889        &'a mut self,
890        credential_id: &'a str,
891    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
892
893    fn credential_seal<'a>(
894        &'a mut self,
895        _request: SealRequest<'a>,
896    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
897        Box::pin(async {
898            Err(CredentialResolverError::new(
899                CredentialErrorClass::Permanent,
900                "credential sealing is unavailable",
901            ))
902        })
903    }
904
905    fn credential_list_scoped(
906        &mut self,
907    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
908        Box::pin(async {
909            Err(CredentialResolverError::new(
910                CredentialErrorClass::Permanent,
911                "credential listing is unavailable",
912            ))
913        })
914    }
915}
916
917#[cfg(feature = "transport")]
918trait CredentialConsumerConnector: Send + Sync {
919    fn connect<'a>(
920        &'a self,
921    ) -> CredentialResolverFuture<
922        'a,
923        Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
924    >;
925}
926
927#[cfg(feature = "transport")]
928struct LiveCredentialConnector {
929    connection_file_path: PathBuf,
930    project_root: PathBuf,
931    consumer_module_id: String,
932}
933
934#[cfg(feature = "transport")]
935impl CredentialConsumerConnector for LiveCredentialConnector {
936    fn connect<'a>(
937        &'a self,
938    ) -> CredentialResolverFuture<
939        'a,
940        Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
941    > {
942        Box::pin(async move {
943            ClaustrumConsumer::connect(
944                &self.connection_file_path,
945                &self.project_root,
946                &self.consumer_module_id,
947            )
948            .await
949            .map(|consumer| Box::new(consumer) as Box<dyn CredentialConsumerConnection>)
950        })
951    }
952}
953
954#[cfg(feature = "transport")]
955struct LiveCredentialGetTarget {
956    connector: Arc<dyn CredentialConsumerConnector>,
957    call_deadline: Duration,
958    consumer: AsyncMutex<Option<Box<dyn CredentialConsumerConnection>>>,
959}
960
961#[cfg(feature = "transport")]
962impl LiveCredentialGetTarget {
963    fn new(connector: Arc<dyn CredentialConsumerConnector>, call_deadline: Duration) -> Self {
964        Self {
965            connector,
966            call_deadline,
967            consumer: AsyncMutex::new(None),
968        }
969    }
970
971    async fn connect_if_needed(
972        &self,
973        consumer: &mut Option<Box<dyn CredentialConsumerConnection>>,
974    ) -> Result<(), CredentialResolverError> {
975        if consumer.is_none() {
976            *consumer = Some(self.connector.connect().await?);
977        }
978        Ok(())
979    }
980
981    fn deadline_error(operation: &str) -> CredentialResolverError {
982        CredentialResolverError::transport(format!(
983            "{operation} timed out waiting for the credential route"
984        ))
985    }
986
987    fn clear_failed_transport<T>(
988        consumer: &mut Option<Box<dyn CredentialConsumerConnection>>,
989        result: &Result<T, CredentialResolverError>,
990    ) {
991        if result
992            .as_ref()
993            .is_err_and(CredentialResolverError::is_transport)
994        {
995            *consumer = None;
996        }
997    }
998}
999
1000#[cfg(feature = "transport")]
1001impl CredentialGetTarget for LiveCredentialGetTarget {
1002    fn credential_watch_scoped<'a>(
1003        &'a self,
1004        enrollment_token: Option<&'a str>,
1005    ) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
1006        Box::pin(async move {
1007            // A watch owns a separate connection so it cannot hold the unary-call mutex.
1008            tokio::time::timeout(self.call_deadline, async {
1009                self.connector
1010                    .connect()
1011                    .await?
1012                    .into_scoped_watch(enrollment_token.map(str::to_owned))
1013                    .await
1014            })
1015            .await
1016            .unwrap_or_else(|_| Err(Self::deadline_error("auth.watch_scoped")))
1017        })
1018    }
1019
1020    fn credential_get<'a>(
1021        &'a self,
1022        raw_handle: &'a str,
1023        min_ttl_ms: Option<u64>,
1024        force_refresh: bool,
1025    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1026        Box::pin(async move {
1027            let mut consumer = self.consumer.lock().await;
1028            self.connect_if_needed(&mut consumer).await?;
1029            let result = tokio::time::timeout(
1030                self.call_deadline,
1031                consumer
1032                    .as_mut()
1033                    .expect("credential consumer initialized")
1034                    .credential_get(raw_handle, min_ttl_ms, force_refresh),
1035            )
1036            .await
1037            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_GET_OP)));
1038            Self::clear_failed_transport(&mut consumer, &result);
1039            result
1040        })
1041    }
1042
1043    fn credential_get_scoped<'a>(
1044        &'a self,
1045        credential_id: &'a str,
1046    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1047        Box::pin(async move {
1048            let mut consumer = self.consumer.lock().await;
1049            self.connect_if_needed(&mut consumer).await?;
1050            let result = tokio::time::timeout(
1051                self.call_deadline,
1052                consumer
1053                    .as_mut()
1054                    .expect("credential consumer initialized")
1055                    .credential_get_scoped(credential_id, None),
1056            )
1057            .await
1058            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_GET_SCOPED_OP)));
1059            Self::clear_failed_transport(&mut consumer, &result);
1060            result
1061        })
1062    }
1063
1064    fn credential_get_scoped_with_min_ttl<'a>(
1065        &'a self,
1066        credential_id: &'a str,
1067        min_ttl_ms: u64,
1068    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1069        Box::pin(async move {
1070            let mut consumer = self.consumer.lock().await;
1071            self.connect_if_needed(&mut consumer).await?;
1072            let result = tokio::time::timeout(
1073                self.call_deadline,
1074                consumer
1075                    .as_mut()
1076                    .expect("credential consumer initialized")
1077                    .credential_get_scoped(credential_id, Some(min_ttl_ms)),
1078            )
1079            .await
1080            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_GET_SCOPED_OP)));
1081            Self::clear_failed_transport(&mut consumer, &result);
1082            result
1083        })
1084    }
1085
1086    fn credential_report_auth_failure<'a>(
1087        &'a self,
1088        credential_id: &'a str,
1089        record_version: u64,
1090        provider_status: u16,
1091    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1092        Box::pin(async move {
1093            let mut consumer = self.consumer.lock().await;
1094            self.connect_if_needed(&mut consumer).await?;
1095            let result = tokio::time::timeout(
1096                self.call_deadline,
1097                consumer
1098                    .as_mut()
1099                    .expect("credential consumer initialized")
1100                    .credential_report_auth_failure(credential_id, record_version, provider_status),
1101            )
1102            .await
1103            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_REPORT_AUTH_FAILURE_OP)));
1104            Self::clear_failed_transport(&mut consumer, &result);
1105            result
1106        })
1107    }
1108
1109    fn credential_status<'a>(
1110        &'a self,
1111        credential_id: &'a str,
1112    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1113        Box::pin(async move {
1114            let mut consumer = self.consumer.lock().await;
1115            self.connect_if_needed(&mut consumer).await?;
1116            let result = tokio::time::timeout(
1117                self.call_deadline,
1118                consumer
1119                    .as_mut()
1120                    .expect("credential consumer initialized")
1121                    .credential_status(credential_id),
1122            )
1123            .await
1124            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_STATUS_OP)));
1125            Self::clear_failed_transport(&mut consumer, &result);
1126            result
1127        })
1128    }
1129
1130    fn credential_sign<'a>(
1131        &'a self,
1132        credential_id: &'a str,
1133        payload: &'a [u8],
1134    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1135        Box::pin(async move {
1136            let mut consumer = self.consumer.lock().await;
1137            self.connect_if_needed(&mut consumer).await?;
1138            let result = tokio::time::timeout(
1139                self.call_deadline,
1140                consumer
1141                    .as_mut()
1142                    .expect("credential consumer initialized")
1143                    .credential_sign(credential_id, payload),
1144            )
1145            .await
1146            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_SIGN_OP)));
1147            Self::clear_failed_transport(&mut consumer, &result);
1148            result
1149        })
1150    }
1151
1152    fn credential_public_key<'a>(
1153        &'a self,
1154        credential_id: &'a str,
1155    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1156        Box::pin(async move {
1157            let mut consumer = self.consumer.lock().await;
1158            self.connect_if_needed(&mut consumer).await?;
1159            let result = tokio::time::timeout(
1160                self.call_deadline,
1161                consumer
1162                    .as_mut()
1163                    .expect("credential consumer initialized")
1164                    .credential_public_key(credential_id),
1165            )
1166            .await
1167            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_PUBLIC_KEY_OP)));
1168            Self::clear_failed_transport(&mut consumer, &result);
1169            result
1170        })
1171    }
1172
1173    fn credential_seal<'a>(
1174        &'a self,
1175        request: SealRequest<'a>,
1176    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1177        Box::pin(async move {
1178            let mut consumer = self.consumer.lock().await;
1179            self.connect_if_needed(&mut consumer).await?;
1180            let result = tokio::time::timeout(
1181                self.call_deadline,
1182                consumer
1183                    .as_mut()
1184                    .expect("credential consumer initialized")
1185                    .credential_seal(request),
1186            )
1187            .await
1188            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_SEAL_OP)));
1189            Self::clear_failed_transport(&mut consumer, &result);
1190            result
1191        })
1192    }
1193
1194    fn credential_list_scoped(
1195        &self,
1196    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
1197        Box::pin(async move {
1198            let mut consumer = self.consumer.lock().await;
1199            self.connect_if_needed(&mut consumer).await?;
1200            let result = tokio::time::timeout(
1201                self.call_deadline,
1202                consumer
1203                    .as_mut()
1204                    .expect("credential consumer initialized")
1205                    .credential_list_scoped(),
1206            )
1207            .await
1208            .unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_LIST_SCOPED_OP)));
1209            Self::clear_failed_transport(&mut consumer, &result);
1210            result
1211        })
1212    }
1213}
1214
1215#[cfg(feature = "transport")]
1216struct ClaustrumConsumer {
1217    stream: TcpStream,
1218    route_channel: u16,
1219    route_epoch: u32,
1220    next_corr: u64,
1221}
1222
1223#[cfg(feature = "transport")]
1224impl ClaustrumConsumer {
1225    async fn connect(
1226        connection_file_path: &Path,
1227        project_root: &Path,
1228        consumer_module_id: &str,
1229    ) -> Result<Self, CredentialResolverError> {
1230        let connection = connection_file::read(connection_file_path).map_err(|error| {
1231            CredentialResolverError::transport(format!(
1232                "credential route connection metadata is unavailable: {error}"
1233            ))
1234        })?;
1235        let endpoint = connection.endpoints.first().ok_or_else(|| {
1236            CredentialResolverError::transport("credential route has no daemon endpoint")
1237        })?;
1238        let address = format!("{}:{}", endpoint.host, endpoint.port);
1239        let mut stream =
1240            tokio::time::timeout(CREDENTIAL_CONNECT_TIMEOUT, TcpStream::connect(address))
1241                .await
1242                .map_err(|error| {
1243                    CredentialResolverError::transport(format!(
1244                        "credential route connection timed out: {error}"
1245                    ))
1246                })?
1247                .map_err(|error| {
1248                    CredentialResolverError::transport(format!(
1249                        "credential route connection failed: {error}"
1250                    ))
1251                })?;
1252        authenticate_client(&mut stream, &connection, CREDENTIAL_CONNECT_TIMEOUT)
1253            .await
1254            .map_err(|_| {
1255                CredentialResolverError::new(
1256                    CredentialErrorClass::AuthRequired,
1257                    "credential route authentication failed",
1258                )
1259            })?;
1260        let mut consumer = Self {
1261            stream,
1262            route_channel: 0,
1263            route_epoch: 0,
1264            next_corr: 1,
1265        };
1266        (consumer.route_channel, consumer.route_epoch) = consumer
1267            .route_open(project_root, consumer_module_id)
1268            .await?;
1269        Ok(consumer)
1270    }
1271
1272    fn next_correlation(&mut self) -> u64 {
1273        let correlation = self.next_corr;
1274        self.next_corr += 1;
1275        correlation
1276    }
1277
1278    async fn route_open(
1279        &mut self,
1280        project_root: &Path,
1281        consumer_module_id: &str,
1282    ) -> Result<(u16, u32), CredentialResolverError> {
1283        let correlation = self.next_correlation();
1284        // A missing launch nonce refuses here, before anything is written: the route
1285        // must never open unscoped.
1286        let body = route_open_body(project_root, consumer_module_id)?;
1287        self.write_request(0, 0, correlation, Priority::Passive, body)
1288            .await?;
1289        let reply = self.read_reply(0, 0, correlation).await?;
1290        if reply.header.ty == FrameType::Error {
1291            return Err(decode_wire_error(&reply.body));
1292        }
1293        let value: Value = serde_json::from_slice(&reply.body).map_err(|_| {
1294            CredentialResolverError::new(
1295                CredentialErrorClass::InvalidResponse,
1296                "credential route-open reply is not valid JSON",
1297            )
1298        })?;
1299        let channel = value
1300            .get("route_channel")
1301            .and_then(Value::as_u64)
1302            .and_then(|value| u16::try_from(value).ok())
1303            .ok_or_else(|| {
1304                CredentialResolverError::new(
1305                    CredentialErrorClass::InvalidResponse,
1306                    "credential route-open reply has no valid channel",
1307                )
1308            })?;
1309        let epoch = value
1310            .get("route_epoch")
1311            .and_then(Value::as_u64)
1312            .and_then(|value| u32::try_from(value).ok())
1313            .ok_or_else(|| {
1314                CredentialResolverError::new(
1315                    CredentialErrorClass::InvalidResponse,
1316                    "credential route-open reply has no valid epoch",
1317                )
1318            })?;
1319        Ok((channel, epoch))
1320    }
1321
1322    async fn credential_get(
1323        &mut self,
1324        raw_handle: &str,
1325        min_ttl_ms: Option<u64>,
1326        force_refresh: bool,
1327    ) -> Result<Value, CredentialResolverError> {
1328        self.credential_request(
1329            credential_get_request(raw_handle, min_ttl_ms, force_refresh),
1330            "credential.get",
1331        )
1332        .await
1333    }
1334
1335    async fn credential_get_scoped(
1336        &mut self,
1337        credential_id: &str,
1338        min_ttl_ms: Option<u64>,
1339    ) -> Result<Value, CredentialResolverError> {
1340        self.credential_request(
1341            credential_get_scoped_request(credential_id, min_ttl_ms),
1342            CREDENTIAL_GET_SCOPED_OP,
1343        )
1344        .await
1345    }
1346
1347    async fn credential_report_auth_failure(
1348        &mut self,
1349        credential_id: &str,
1350        record_version: u64,
1351        provider_status: u16,
1352    ) -> Result<Value, CredentialResolverError> {
1353        self.credential_request(
1354            credential_report_auth_failure_request(credential_id, record_version, provider_status),
1355            CREDENTIAL_REPORT_AUTH_FAILURE_OP,
1356        )
1357        .await
1358    }
1359
1360    async fn credential_status(
1361        &mut self,
1362        credential_id: &str,
1363    ) -> Result<Value, CredentialResolverError> {
1364        self.credential_request(
1365            credential_status_request(credential_id),
1366            CREDENTIAL_STATUS_OP,
1367        )
1368        .await
1369    }
1370
1371    async fn credential_sign(
1372        &mut self,
1373        credential_id: &str,
1374        payload: &[u8],
1375    ) -> Result<Value, CredentialResolverError> {
1376        self.credential_request(
1377            credential_sign_request(credential_id, payload),
1378            CREDENTIAL_SIGN_OP,
1379        )
1380        .await
1381    }
1382
1383    async fn credential_public_key(
1384        &mut self,
1385        credential_id: &str,
1386    ) -> Result<Value, CredentialResolverError> {
1387        self.credential_request(
1388            credential_public_key_request(credential_id),
1389            CREDENTIAL_PUBLIC_KEY_OP,
1390        )
1391        .await
1392    }
1393
1394    async fn credential_seal(
1395        &mut self,
1396        request: SealRequest<'_>,
1397    ) -> Result<Value, CredentialResolverError> {
1398        self.credential_request(credential_seal_request(request), CREDENTIAL_SEAL_OP)
1399            .await
1400    }
1401
1402    async fn credential_request(
1403        &mut self,
1404        request: Value,
1405        operation: &str,
1406    ) -> Result<Value, CredentialResolverError> {
1407        let correlation = self.next_correlation();
1408        self.write_request(
1409            self.route_channel,
1410            self.route_epoch,
1411            correlation,
1412            Priority::Interactive,
1413            request,
1414        )
1415        .await?;
1416        let reply = self
1417            .read_reply(self.route_channel, self.route_epoch, correlation)
1418            .await?;
1419        if reply.header.ty == FrameType::Error {
1420            return Err(decode_wire_error(&reply.body));
1421        }
1422        serde_json::from_slice(&reply.body).map_err(|_| {
1423            CredentialResolverError::new(
1424                CredentialErrorClass::InvalidResponse,
1425                format!("{operation} reply is not valid JSON"),
1426            )
1427        })
1428    }
1429
1430    async fn write_request(
1431        &mut self,
1432        channel: u16,
1433        epoch: u32,
1434        correlation: u64,
1435        priority: Priority,
1436        body: Value,
1437    ) -> Result<(), CredentialResolverError> {
1438        let bytes = serde_json::to_vec(&body).map_err(|_| {
1439            CredentialResolverError::new(
1440                CredentialErrorClass::Permanent,
1441                "credential request encoding failed",
1442            )
1443        })?;
1444        let frame = Frame::build(
1445            FrameType::Request,
1446            Flags::new(false, priority, false),
1447            channel,
1448            epoch,
1449            correlation,
1450            bytes,
1451        )
1452        .map_err(|_| {
1453            CredentialResolverError::new(
1454                CredentialErrorClass::Permanent,
1455                "credential request framing failed",
1456            )
1457        })?;
1458        write_frame(&mut self.stream, &frame)
1459            .await
1460            .map_err(|error| {
1461                CredentialResolverError::transport(format!(
1462                    "credential route write failed: {error}"
1463                ))
1464            })
1465    }
1466
1467    async fn read_reply(
1468        &mut self,
1469        channel: u16,
1470        epoch: u32,
1471        correlation: u64,
1472    ) -> Result<Frame, CredentialResolverError> {
1473        loop {
1474            let frame = tokio::time::timeout(CREDENTIAL_READ_TIMEOUT, read_frame(&mut self.stream))
1475                .await
1476                .map_err(|error| {
1477                    CredentialResolverError::transport(format!(
1478                        "credential route reply timed out: {error}"
1479                    ))
1480                })?
1481                .map_err(|error| {
1482                    CredentialResolverError::transport(format!(
1483                        "credential route read failed: {error}"
1484                    ))
1485                })?
1486                .ok_or_else(|| {
1487                    CredentialResolverError::transport("credential route closed before replying")
1488                })?;
1489            if frame.header.channel == channel
1490                && frame.header.epoch == epoch
1491                && frame.header.corr == correlation
1492                && matches!(frame.header.ty, FrameType::Response | FrameType::Error)
1493            {
1494                return Ok(frame);
1495            }
1496        }
1497    }
1498}
1499
1500#[cfg(feature = "transport")]
1501impl CredentialConsumerConnection for ClaustrumConsumer {
1502    fn into_scoped_watch(
1503        self: Box<Self>,
1504        enrollment_token: Option<String>,
1505    ) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
1506        Box::pin(async move { (*self).start_scoped_watch(enrollment_token).await })
1507    }
1508
1509    fn credential_get<'a>(
1510        &'a mut self,
1511        raw_handle: &'a str,
1512        min_ttl_ms: Option<u64>,
1513        force_refresh: bool,
1514    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1515        Box::pin(ClaustrumConsumer::credential_get(
1516            self,
1517            raw_handle,
1518            min_ttl_ms,
1519            force_refresh,
1520        ))
1521    }
1522
1523    fn credential_get_scoped<'a>(
1524        &'a mut self,
1525        credential_id: &'a str,
1526        min_ttl_ms: Option<u64>,
1527    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1528        Box::pin(ClaustrumConsumer::credential_get_scoped(
1529            self,
1530            credential_id,
1531            min_ttl_ms,
1532        ))
1533    }
1534
1535    fn credential_report_auth_failure<'a>(
1536        &'a mut self,
1537        credential_id: &'a str,
1538        record_version: u64,
1539        provider_status: u16,
1540    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1541        Box::pin(ClaustrumConsumer::credential_report_auth_failure(
1542            self,
1543            credential_id,
1544            record_version,
1545            provider_status,
1546        ))
1547    }
1548
1549    fn credential_status<'a>(
1550        &'a mut self,
1551        credential_id: &'a str,
1552    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1553        Box::pin(ClaustrumConsumer::credential_status(self, credential_id))
1554    }
1555
1556    fn credential_sign<'a>(
1557        &'a mut self,
1558        credential_id: &'a str,
1559        payload: &'a [u8],
1560    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1561        Box::pin(ClaustrumConsumer::credential_sign(
1562            self,
1563            credential_id,
1564            payload,
1565        ))
1566    }
1567
1568    fn credential_public_key<'a>(
1569        &'a mut self,
1570        credential_id: &'a str,
1571    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1572        Box::pin(ClaustrumConsumer::credential_public_key(
1573            self,
1574            credential_id,
1575        ))
1576    }
1577
1578    fn credential_seal<'a>(
1579        &'a mut self,
1580        request: SealRequest<'a>,
1581    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1582        Box::pin(ClaustrumConsumer::credential_seal(self, request))
1583    }
1584
1585    fn credential_list_scoped(
1586        &mut self,
1587    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
1588        Box::pin(
1589            self.credential_request(credential_list_scoped_request(), CREDENTIAL_LIST_SCOPED_OP),
1590        )
1591    }
1592}
1593
1594#[cfg(any(feature = "transport", test))]
1595fn credential_list_scoped_request() -> Value {
1596    // A supervised module is identified by its route's reserved principal, so it
1597    // sends no enrollment token; the vault refuses unknown parameters.
1598    json!({
1599        "method": CREDENTIAL_LIST_SCOPED_OP,
1600        "params": {},
1601    })
1602}
1603
1604fn optional_string(value: &Value, key: &str) -> Option<String> {
1605    value
1606        .get(key)
1607        .and_then(Value::as_str)
1608        .filter(|text| !text.is_empty())
1609        .map(str::to_owned)
1610}
1611
1612fn invalid_listing(detail: &str) -> CredentialResolverError {
1613    CredentialResolverError::new(
1614        CredentialErrorClass::InvalidResponse,
1615        format!("credential.list_scoped reply {detail}"),
1616    )
1617}
1618
1619fn listing_strings(row: &Value, key: &str, optional: bool) -> Result<Vec<String>, String> {
1620    // An optional field sent as explicit null means the same as an omitted one. The
1621    // vault omits absent fields, but rejecting null would drop a usable credential
1622    // from the listing over a serialization choice.
1623    if optional && matches!(row.get(key), None | Some(Value::Null)) {
1624        return Ok(Vec::new());
1625    }
1626    let items = row
1627        .get(key)
1628        .and_then(Value::as_array)
1629        .ok_or_else(|| format!("{key} is not an array"))?;
1630    items
1631        .iter()
1632        .map(|item| {
1633            item.as_str()
1634                .map(str::to_owned)
1635                .ok_or_else(|| format!("{key} contains a non-string"))
1636        })
1637        .collect()
1638}
1639
1640fn listing_string(row: &Value, key: &str) -> Result<String, String> {
1641    optional_string(row, key).ok_or_else(|| format!("{key} is not a non-empty string"))
1642}
1643
1644fn listing_optional_string(row: &Value, key: &str) -> Result<Option<String>, String> {
1645    match row.get(key) {
1646        // Null is absent too; see listing_strings for why it isn't a decode failure.
1647        None | Some(Value::Null) => Ok(None),
1648        Some(value) => value
1649            .as_str()
1650            .map(|s| Some(s.to_owned()))
1651            .ok_or_else(|| format!("{key} is not a string")),
1652    }
1653}
1654
1655fn decode_listed_credential(row: &Value) -> Result<ListedCredential, String> {
1656    Ok(ListedCredential {
1657        id: listing_string(row, "id")?,
1658        categories: listing_strings(row, "categories", false)?,
1659        credential_type: listing_string(row, "type")?,
1660        serves: listing_strings(row, "serves", false)?,
1661        provider_ids: listing_strings(row, "provider_ids", true)?,
1662        auth_method: listing_optional_string(row, "auth_method")?,
1663        refresh_adapter: listing_optional_string(row, "refresh_adapter")?,
1664        state: listing_string(row, "state")?,
1665        record_version: row
1666            .get("record_version")
1667            .and_then(Value::as_u64)
1668            .ok_or_else(|| "record_version is not an unsigned integer".to_string())?,
1669        operations: listing_strings(row, "operations", false)?,
1670        account_id: listing_optional_string(row, "account_id")?,
1671        email: listing_optional_string(row, "email")?,
1672        org_name: listing_optional_string(row, "org_name")?,
1673        plan_tier: listing_optional_string(row, "plan_tier")?,
1674        plan_tier_source: listing_optional_string(row, "plan_tier_source")?,
1675    })
1676}
1677
1678fn decode_listed_grant(tuple: &Value) -> Result<ListedGrant, String> {
1679    Ok(ListedGrant {
1680        selector_kind: listing_string(tuple, "selector_kind")?,
1681        selector: listing_string(tuple, "selector")?,
1682        operation: listing_string(tuple, "operation")?,
1683    })
1684}
1685
1686/// Decode metadata row by row: a malformed credential or grant must not discard
1687/// healthy entries listed alongside it. Envelope failures still reject the listing.
1688pub fn decode_list_scoped_reply(
1689    value: Value,
1690) -> Result<ScopedCredentialListing, CredentialResolverError> {
1691    let result = reply_result(value)?;
1692    let view = result
1693        .get("view")
1694        .and_then(Value::as_str)
1695        .ok_or_else(|| invalid_listing("has no view digest"))?
1696        .to_owned();
1697    let rows = result
1698        .get("credentials")
1699        .and_then(Value::as_array)
1700        .ok_or_else(|| invalid_listing("has no credentials array"))?;
1701    let mut credentials = Vec::with_capacity(rows.len());
1702    let mut undecodable_credentials = Vec::new();
1703    for (index, row) in rows.iter().enumerate() {
1704        match decode_listed_credential(row) {
1705            Ok(credential) => credentials.push(credential),
1706            Err(error) => {
1707                let id = optional_string(row, "id").unwrap_or_else(|| format!("row {index}"));
1708                let detail = format!("{id}: {error}");
1709                undecodable_credentials.push(detail);
1710            }
1711        }
1712    }
1713    let mut grant_tuples = Vec::new();
1714    let mut undecodable_grants = Vec::new();
1715    if let Some(tuples) = result.get("grant_tuples").and_then(Value::as_array) {
1716        for (index, tuple) in tuples.iter().enumerate() {
1717            match decode_listed_grant(tuple) {
1718                Ok(grant) => grant_tuples.push(grant),
1719                Err(error) => undecodable_grants.push(format!("grant tuple {index}: {error}")),
1720            }
1721        }
1722    }
1723    Ok(ScopedCredentialListing {
1724        credentials,
1725        undecodable_credentials,
1726        grant_tuples,
1727        undecodable_grants,
1728        view,
1729    })
1730}
1731
1732#[cfg(any(feature = "transport", test))]
1733fn credential_get_request(raw_handle: &str, min_ttl_ms: Option<u64>, force_refresh: bool) -> Value {
1734    let mut params =
1735        serde_json::Map::from_iter([("handle".to_owned(), Value::String(raw_handle.to_owned()))]);
1736    if let Some(min_ttl_ms) = min_ttl_ms {
1737        params.insert("min_ttl_ms".to_owned(), Value::from(min_ttl_ms));
1738    }
1739    if force_refresh {
1740        params.insert("force_refresh".to_owned(), Value::Bool(true));
1741    }
1742    json!({
1743        "method": CREDENTIAL_GET_OP,
1744        "params": params,
1745    })
1746}
1747
1748#[cfg(any(feature = "transport", test))]
1749fn credential_get_scoped_request(credential_id: &str, min_ttl_ms: Option<u64>) -> Value {
1750    let mut params = json!({ "credential_id": credential_id });
1751    if let Some(min_ttl_ms) = min_ttl_ms {
1752        params["min_ttl_ms"] = json!(min_ttl_ms);
1753    }
1754    json!({
1755        "method": CREDENTIAL_GET_SCOPED_OP,
1756        "params": params,
1757    })
1758}
1759
1760#[cfg(any(feature = "transport", test))]
1761fn credential_report_auth_failure_request(
1762    credential_id: &str,
1763    record_version: u64,
1764    provider_status: u16,
1765) -> Value {
1766    json!({
1767        "method": CREDENTIAL_REPORT_AUTH_FAILURE_OP,
1768        "params": {
1769            "credential_id": credential_id,
1770            "provider_status": provider_status,
1771            "record_version": record_version,
1772        },
1773    })
1774}
1775
1776#[cfg(any(feature = "transport", test))]
1777fn credential_status_request(credential_id: &str) -> Value {
1778    json!({
1779        "method": CREDENTIAL_STATUS_OP,
1780        "params": { "credential_id": credential_id },
1781    })
1782}
1783
1784#[cfg(any(feature = "transport", test))]
1785fn credential_sign_request(credential_id: &str, payload: &[u8]) -> Value {
1786    // CKCRED 3aaf0e3: sign is handle-less - authorized by the launch-nonce
1787    // principal against the grant table's sign authority, addressed by the
1788    // credential NAME. A handle here would be a bearer capability for a
1789    // signing key, the shape the handle-less revision exists to delete.
1790    json!({
1791        "method": CREDENTIAL_SIGN_OP,
1792        "params": {
1793            "credential_id": credential_id,
1794            "payload_b64": base64::engine::general_purpose::STANDARD.encode(payload),
1795        },
1796    })
1797}
1798
1799#[cfg(any(feature = "transport", test))]
1800fn credential_public_key_request(credential_id: &str) -> Value {
1801    // The launch-nonce principal authorizes this named credential lookup; a
1802    // bearer capability handle must never cross the public-key request.
1803    json!({
1804        "method": CREDENTIAL_PUBLIC_KEY_OP,
1805        "params": { "credential_id": credential_id },
1806    })
1807}
1808
1809#[cfg(any(feature = "transport", test))]
1810fn credential_seal_request(request: SealRequest<'_>) -> Value {
1811    // Addressed by credential NAME under the route principal's exact seal grant, like
1812    // sign. The vault refuses unknown parameters, so no enrollment token is sent.
1813    let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
1814    json!({
1815        "method": CREDENTIAL_SEAL_OP,
1816        "params": {
1817            "credential_id": request.credential_id,
1818            "recipient_public_key_b64": encode(request.recipient_public_key),
1819            "info_b64": encode(request.info),
1820            "aad_b64": encode(request.aad),
1821            "plaintext_b64": encode(request.plaintext),
1822        },
1823    })
1824}
1825
1826/// Decodes a subc error-frame body without opening a connection.
1827pub fn decode_wire_error(bytes: &[u8]) -> CredentialResolverError {
1828    let value = serde_json::from_slice::<Value>(bytes).unwrap_or(Value::Null);
1829    classify_error_value(&value)
1830}
1831
1832/// Daemon relay refusals: the frame never reached the credential service.
1833const RELAY_ROUTING_CODES: [&str; 7] = [
1834    subc_protocol::error_codes::UNKNOWN_MODULE,
1835    subc_protocol::error_codes::MODULE_RELOADING,
1836    subc_protocol::error_codes::MODULE_WARMING,
1837    subc_protocol::error_codes::TARGET_UNAVAILABLE,
1838    subc_protocol::error_codes::MODULE_TIMEOUT,
1839    "unknown_channel",
1840    "stale_route_epoch",
1841];
1842
1843/// Classify a refusal that may arrive as an error frame body or as a
1844/// `result.error` member of a success frame. The broad class drives retry
1845/// behavior, while preserving the producer's code in the safe message lets an
1846/// operator distinguish a missing, revoked, or denied credential.
1847fn classify_error_value(value: &Value) -> CredentialResolverError {
1848    let class = value
1849        .get("class")
1850        .or_else(|| value.pointer("/error/class"))
1851        .or_else(|| value.pointer("/error/data/class"))
1852        .and_then(Value::as_str);
1853    let class = match class {
1854        Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
1855        Some("credential_absent") => Some(CredentialErrorClass::CredentialAbsent),
1856        Some("unauthorized") => Some(CredentialErrorClass::Unauthorized),
1857        Some("permanent") => Some(CredentialErrorClass::Permanent),
1858        Some("transient") => Some(CredentialErrorClass::Transient),
1859        Some("context_overflow") => Some(CredentialErrorClass::ContextOverflow),
1860        _ => None,
1861    };
1862    let code_field = value
1863        .get("code")
1864        .or_else(|| value.pointer("/error/code"))
1865        .and_then(Value::as_str);
1866    // A missing record or authentication refusal requires operator repair, not
1867    // another signing attempt, even if a producer supplies a broad retry class.
1868    let class = match code_field {
1869        Some("not_found") => Some(CredentialErrorClass::CredentialAbsent),
1870        Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
1871        _ => class,
1872    };
1873    if let Some(class) = class {
1874        let message = match code_field {
1875            Some(code) => format!("credential service rejected the request: {code}"),
1876            None => "credential service rejected the request".to_string(),
1877        };
1878        return CredentialResolverError::new(class, message);
1879    }
1880    let code = value
1881        .get("code")
1882        .or_else(|| value.pointer("/error/code"))
1883        .and_then(Value::as_str)
1884        .unwrap_or("credential_unclassified");
1885    let message = value
1886        .get("message")
1887        .or_else(|| value.pointer("/error/message"))
1888        .and_then(Value::as_str)
1889        .unwrap_or("credential service returned an unclassified error");
1890    // Relay routing refusals mean the DAEMON could not route the frame: the
1891    // credential service never spoke, so nothing about custody can be concluded
1892    // from them. Classify these class-less refusals as transport errors so the
1893    // client can redial a stale channel. The set is named here
1894    // rather than borrowed from the protocol's retryable route-open list:
1895    // whether the SDK retries a code is SUBC's policy, and subc-protocol 0.25
1896    // made `unknown_module` terminal, which silently turned "the credential
1897    // module is not there" back into a custody verdict. A copied list also
1898    // missed `module_warming` once (GitHub #48). The two data-path codes cover
1899    // an established route that died: `unknown_channel` and `stale_route_epoch`
1900    // (the module restarted under the route; the SDK retries each once in place
1901    // and surfaces it only when the retry fails the same way, GitHub #59).
1902    if RELAY_ROUTING_CODES.contains(&code) {
1903        return CredentialResolverError::new(
1904            CredentialErrorClass::Transport,
1905            format!("{code}: {message}"),
1906        );
1907    }
1908    CredentialResolverError::unclassified(code, message)
1909}
1910
1911/// The route.open frame for the credential module. Reserved-principal identity
1912/// is carried in `consumer_identity`, not the bind parameters. The credential
1913/// service derives that principal by matching the launch nonce; if it is absent,
1914/// claustrum silently treats the caller as unscoped. Route opening must therefore
1915/// fail before scoped reads are reduced to an ambiguous `not_found`.
1916#[cfg(feature = "transport")]
1917fn route_open_body(
1918    project_root: &Path,
1919    consumer_module_id: &str,
1920) -> Result<Value, CredentialResolverError> {
1921    // The process-wide accessor, never the environment: after the first read
1922    // closes the pipe the daemon handed over, a second independent reader
1923    // would read whatever the process opened next at that descriptor number.
1924    let read = subc_os::launch_nonce()
1925        .map(|nonce| nonce.map(|nonce| nonce.value().to_owned()))
1926        .map_err(|error| error.to_string());
1927    Ok(route_open_body_with_nonce(
1928        project_root,
1929        consumer_module_id,
1930        &required_launch_nonce(read)?,
1931    ))
1932}
1933
1934/// The nonce from a read of it, or an `AuthRequired` refusal when there is none.
1935/// Without the nonce the route would open unscoped, so the caller must stop before
1936/// sending anything; returning an error (never panicking) lets a module process
1937/// refuse cleanly and report why, instead of crashing.
1938#[cfg(feature = "transport")]
1939fn required_launch_nonce(
1940    read: Result<Option<String>, String>,
1941) -> Result<String, CredentialResolverError> {
1942    match read {
1943        Ok(Some(nonce)) if !nonce.trim().is_empty() => Ok(nonce),
1944        Ok(_) => Err(CredentialResolverError::new(
1945            CredentialErrorClass::AuthRequired,
1946            "credential consumer requires a non-empty launch nonce for the reserved principal",
1947        )),
1948        Err(error) => Err(CredentialResolverError::new(
1949            CredentialErrorClass::AuthRequired,
1950            format!(
1951                "credential consumer could not read the launch nonce for the reserved principal: {error}"
1952            ),
1953        )),
1954    }
1955}
1956
1957#[cfg(feature = "transport")]
1958fn route_open_body_with_nonce(
1959    project_root: &Path,
1960    consumer_module_id: &str,
1961    launch_nonce: &str,
1962) -> Value {
1963    json!({
1964        "op": "route.open",
1965        "target": {
1966            "kind": "management_surface",
1967            "module_id": CREDENTIAL_MODULE_ID,
1968        },
1969        "identity": {
1970            "project_root": project_root,
1971            "harness": consumer_module_id,
1972            "session": "campaign-credential-consumer",
1973        },
1974        "consumer_identity": {
1975            "module_id": consumer_module_id,
1976            "launch_nonce": launch_nonce,
1977        },
1978        "config": [],
1979    })
1980}
1981
1982fn reply_result(value: Value) -> Result<Value, CredentialResolverError> {
1983    let result = value.get("result").cloned().unwrap_or(value);
1984    if result.get("error").is_some() {
1985        return Err(classify_error_value(&result));
1986    }
1987    Ok(result)
1988}
1989
1990fn valid_lower_hex(value: &str, length: usize) -> bool {
1991    value.len() == length
1992        && value
1993            .bytes()
1994            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1995}
1996
1997fn hex_bytes(bytes: &[u8]) -> String {
1998    let mut encoded = String::with_capacity(bytes.len() * 2);
1999    for byte in bytes {
2000        encoded.push_str(&format!("{byte:02x}"));
2001    }
2002    encoded
2003}
2004
2005/// Decodes a `credential.sign` response, validating the Ed25519 signature shape.
2006pub fn decode_signature_reply(
2007    value: Value,
2008) -> Result<CredentialSignature, CredentialResolverError> {
2009    let result = reply_result(value)?;
2010    let signature_b64 = result
2011        .get("signature_b64")
2012        .and_then(Value::as_str)
2013        .ok_or_else(|| {
2014            CredentialResolverError::new(
2015                CredentialErrorClass::InvalidResponse,
2016                "credential signing reply has no signature_b64",
2017            )
2018        })?;
2019    let signature = base64::engine::general_purpose::STANDARD
2020        .decode(signature_b64)
2021        .map_err(|_| {
2022            CredentialResolverError::new(
2023                CredentialErrorClass::InvalidResponse,
2024                "credential signing reply has invalid base64",
2025            )
2026        })?;
2027    if signature.len() != 64 {
2028        return Err(CredentialResolverError::new(
2029            CredentialErrorClass::InvalidResponse,
2030            "credential signing reply has a non-Ed25519 signature length",
2031        ));
2032    }
2033    let key_id = result
2034        .get("key_id")
2035        .and_then(Value::as_str)
2036        .filter(|value| valid_lower_hex(value, 16))
2037        .ok_or_else(|| {
2038            CredentialResolverError::new(
2039                CredentialErrorClass::InvalidResponse,
2040                "credential signing reply has no valid key_id",
2041            )
2042        })?;
2043    Ok(CredentialSignature {
2044        signature_hex: hex_bytes(&signature),
2045        key_id: key_id.to_owned(),
2046    })
2047}
2048
2049/// Decodes a `credential.public_key` response, validating its public key and ID.
2050///
2051/// The reply is either an Ed25519 signing key or an X25519 KEM key. Both are 32
2052/// bytes, and the vault derives both kinds' `key_id` the same way (the first 8 bytes
2053/// of SHA-256 over the public key), so one length check and one key-id check cover
2054/// both. Any other `algorithm` is refused.
2055pub fn decode_public_key_reply(
2056    value: Value,
2057) -> Result<CredentialPublicKey, CredentialResolverError> {
2058    let result = reply_result(value)?;
2059    let public_key_hex = result
2060        .get("public_key_hex")
2061        .and_then(Value::as_str)
2062        .filter(|value| valid_lower_hex(value, 64))
2063        .ok_or_else(|| {
2064            CredentialResolverError::new(
2065                CredentialErrorClass::InvalidResponse,
2066                "credential public-key reply has no valid public_key_hex",
2067            )
2068        })?;
2069    let key_id = result
2070        .get("key_id")
2071        .and_then(Value::as_str)
2072        .filter(|value| valid_lower_hex(value, 16))
2073        .ok_or_else(|| {
2074            CredentialResolverError::new(
2075                CredentialErrorClass::InvalidResponse,
2076                "credential public-key reply has no valid key_id",
2077            )
2078        })?;
2079    let public_key_bytes = (0..public_key_hex.len())
2080        .step_by(2)
2081        .map(|index| u8::from_str_radix(&public_key_hex[index..index + 2], 16))
2082        .collect::<Result<Vec<_>, _>>()
2083        .expect("validated lowercase hex decodes");
2084    let expected_key_id = hex_bytes(&Sha256::digest(&public_key_bytes)[..8]);
2085    if key_id != expected_key_id {
2086        return Err(CredentialResolverError::new(
2087            CredentialErrorClass::InvalidResponse,
2088            "credential public-key reply key_id does not identify public_key_hex",
2089        ));
2090    }
2091    let algorithm = match result.get("algorithm").and_then(Value::as_str) {
2092        Some("ed25519") => PublicKeyAlgorithm::Ed25519,
2093        Some("x25519") => PublicKeyAlgorithm::X25519,
2094        _ => {
2095            return Err(CredentialResolverError::new(
2096                CredentialErrorClass::InvalidResponse,
2097                "credential public-key reply is neither Ed25519 nor X25519",
2098            ))
2099        }
2100    };
2101    Ok(CredentialPublicKey {
2102        public_key_hex: public_key_hex.to_owned(),
2103        key_id: key_id.to_owned(),
2104        algorithm,
2105    })
2106}
2107
2108/// Decodes a `credential.seal` response: a 32-byte encapsulated key, a ciphertext at
2109/// least as long as the AEAD tag, and a key id in `credential.public_key` format.
2110pub fn decode_seal_reply(value: Value) -> Result<CredentialSeal, CredentialResolverError> {
2111    let result = reply_result(value)?;
2112    let invalid = |detail: &str| {
2113        CredentialResolverError::new(
2114            CredentialErrorClass::InvalidResponse,
2115            format!("credential seal reply {detail}"),
2116        )
2117    };
2118    let bytes = |field: &str| {
2119        let text = result
2120            .get(field)
2121            .and_then(Value::as_str)
2122            .ok_or_else(|| invalid(&format!("has no {field}")))?;
2123        base64::engine::general_purpose::STANDARD
2124            .decode(text)
2125            .map_err(|_| invalid(&format!("has invalid base64 in {field}")))
2126    };
2127    let enc = bytes("enc_b64")?;
2128    if enc.len() != 32 {
2129        return Err(invalid("has a non-X25519 encapsulated key length"));
2130    }
2131    let ciphertext = bytes("ciphertext_b64")?;
2132    if ciphertext.len() < 16 {
2133        return Err(invalid("has a ciphertext shorter than the AEAD tag"));
2134    }
2135    let key_id = result
2136        .get("key_id")
2137        .and_then(Value::as_str)
2138        .filter(|value| valid_lower_hex(value, 16))
2139        .ok_or_else(|| invalid("has no valid key_id"))?;
2140    Ok(CredentialSeal {
2141        enc,
2142        ciphertext,
2143        key_id: key_id.to_owned(),
2144    })
2145}
2146
2147/// Decodes a `credential.status` response without fetching credential material.
2148pub fn decode_credential_status_reply(
2149    value: Value,
2150) -> Result<CredentialStatus, CredentialResolverError> {
2151    let result = reply_result(value)?;
2152    let ready = result
2153        .get("ready")
2154        .and_then(Value::as_bool)
2155        .ok_or_else(|| {
2156            CredentialResolverError::new(
2157                CredentialErrorClass::InvalidResponse,
2158                "credential status reply has no ready flag",
2159            )
2160        })?;
2161    let record_version = result.get("record_version").and_then(|value| match value {
2162        Value::String(version) if !version.is_empty() => Some(version.clone()),
2163        Value::Number(version) => Some(version.to_string()),
2164        _ => None,
2165    });
2166    Ok(CredentialStatus {
2167        ready,
2168        record_version,
2169        stale_pending: result
2170            .get("stale_pending")
2171            .and_then(Value::as_bool)
2172            .unwrap_or(false),
2173        last_error_code: result
2174            .get("last_error_code")
2175            .and_then(Value::as_str)
2176            .map(str::to_owned),
2177    })
2178}
2179
2180/// Decodes a `credential.get` or `credential.get_scoped` response into secret bytes.
2181pub fn decode_credential_reply(
2182    value: Value,
2183) -> Result<ResolvedCredential, CredentialResolverError> {
2184    let result = value.get("result").unwrap_or(&value);
2185    // A refusal arrives as a SUCCESS frame carrying `result.error`; demanding a
2186    // payload from it would launder the vault's typed answer (class + code)
2187    // into invalid_response - the first live push fetch reported "no opaque
2188    // payload" for a reply that said permanent/not_found in plain sight.
2189    if result.get("error").is_some() {
2190        return Err(classify_error_value(result));
2191    }
2192    let payload = match result.get("payload") {
2193        Some(Value::String(payload)) => payload.as_bytes().to_vec(),
2194        Some(Value::Array(payload)) => payload
2195            .iter()
2196            .map(|byte| {
2197                byte.as_u64()
2198                    .and_then(|byte| u8::try_from(byte).ok())
2199                    .ok_or_else(|| {
2200                        CredentialResolverError::new(
2201                            CredentialErrorClass::InvalidResponse,
2202                            "credential payload contains a non-byte value",
2203                        )
2204                    })
2205            })
2206            .collect::<Result<Vec<_>, _>>()?,
2207        _ => {
2208            return Err(CredentialResolverError::new(
2209                CredentialErrorClass::InvalidResponse,
2210                "credential reply has no opaque payload",
2211            ));
2212        }
2213    };
2214    let version = result
2215        .get("record_version")
2216        .map(|version| match version {
2217            Value::String(version) => version.clone(),
2218            version => version.to_string(),
2219        })
2220        .filter(|version| !version.is_empty())
2221        .ok_or_else(|| {
2222            CredentialResolverError::new(
2223                CredentialErrorClass::InvalidResponse,
2224                "credential reply has no record version",
2225            )
2226        })?;
2227    let expires_at_ms = result.get("expires_at_ms").and_then(Value::as_i64);
2228    Ok(ResolvedCredential::new_with_identity(
2229        payload,
2230        version,
2231        expires_at_ms,
2232        optional_string(result, "account_id"),
2233        optional_string(result, "email"),
2234        optional_string(result, "org_name"),
2235    ))
2236}
2237
2238/// Decodes whether `credential.report_auth_failure` accepted the report.
2239pub fn decode_report_auth_failure_reply(value: Value) -> Result<bool, CredentialResolverError> {
2240    let result = value.get("result").unwrap_or(&value);
2241    if result.get("error").is_some() {
2242        return Err(classify_error_value(result));
2243    }
2244    result
2245        .get("accepted")
2246        .and_then(Value::as_bool)
2247        .ok_or_else(|| {
2248            CredentialResolverError::new(
2249                CredentialErrorClass::InvalidResponse,
2250                "auth-failure report reply has no accepted value",
2251            )
2252        })
2253}
2254#[cfg(test)]
2255mod contract_tests;
2256
2257#[cfg(test)]
2258mod tests {
2259    #[cfg(feature = "transport")]
2260    use std::sync::atomic::{AtomicUsize, Ordering};
2261
2262    use super::*;
2263
2264    #[cfg(feature = "transport")]
2265    #[derive(Debug)]
2266    struct FakeCkcredTarget {
2267        script: Mutex<VecDeque<Result<Value, CredentialResolverError>>>,
2268        requests: Mutex<Vec<(String, Option<u64>, bool)>>,
2269        reports: Mutex<Vec<(String, u64, u16)>>,
2270    }
2271
2272    #[cfg(feature = "transport")]
2273    impl CredentialGetTarget for FakeCkcredTarget {
2274        fn credential_get<'a>(
2275            &'a self,
2276            raw_handle: &'a str,
2277            min_ttl_ms: Option<u64>,
2278            force_refresh: bool,
2279        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2280            Box::pin(async move {
2281                self.requests
2282                    .lock()
2283                    .expect("fake CKCRED target poisoned")
2284                    .push((raw_handle.to_owned(), min_ttl_ms, force_refresh));
2285                self.script
2286                    .lock()
2287                    .expect("fake CKCRED target poisoned")
2288                    .pop_front()
2289                    .expect("fake CKCRED target script exhausted")
2290            })
2291        }
2292
2293        fn credential_get_scoped<'a>(
2294            &'a self,
2295            credential_id: &'a str,
2296        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2297            Box::pin(async move {
2298                self.requests
2299                    .lock()
2300                    .expect("fake CKCRED target poisoned")
2301                    .push((credential_id.to_owned(), None, false));
2302                self.script
2303                    .lock()
2304                    .expect("fake CKCRED target poisoned")
2305                    .pop_front()
2306                    .expect("fake CKCRED target script exhausted")
2307            })
2308        }
2309
2310        fn credential_get_scoped_with_min_ttl<'a>(
2311            &'a self,
2312            credential_id: &'a str,
2313            min_ttl_ms: u64,
2314        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2315            Box::pin(async move {
2316                self.requests
2317                    .lock()
2318                    .expect("fake CKCRED target poisoned")
2319                    .push((credential_id.to_owned(), Some(min_ttl_ms), false));
2320                self.script
2321                    .lock()
2322                    .expect("fake CKCRED target script exhausted")
2323                    .pop_front()
2324                    .expect("fake CKCRED target script exhausted")
2325            })
2326        }
2327
2328        fn credential_report_auth_failure<'a>(
2329            &'a self,
2330            credential_id: &'a str,
2331            record_version: u64,
2332            provider_status: u16,
2333        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2334            Box::pin(async move {
2335                self.reports
2336                    .lock()
2337                    .expect("fake CKCRED target poisoned")
2338                    .push((credential_id.to_owned(), record_version, provider_status));
2339                self.script
2340                    .lock()
2341                    .expect("fake CKCRED target script exhausted")
2342                    .pop_front()
2343                    .expect("fake CKCRED target script exhausted")
2344            })
2345        }
2346    }
2347
2348    #[cfg(feature = "transport")]
2349    #[derive(Debug)]
2350    struct DeadlineConnector {
2351        dials: Arc<AtomicUsize>,
2352    }
2353
2354    #[cfg(feature = "transport")]
2355    impl CredentialConsumerConnector for DeadlineConnector {
2356        fn connect<'a>(
2357            &'a self,
2358        ) -> CredentialResolverFuture<
2359            'a,
2360            Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
2361        > {
2362            Box::pin(async move {
2363                let dial = self.dials.fetch_add(1, Ordering::SeqCst);
2364                Ok(Box::new(DeadlineConsumer { hangs: dial == 0 })
2365                    as Box<dyn CredentialConsumerConnection>)
2366            })
2367        }
2368    }
2369
2370    #[cfg(feature = "transport")]
2371    struct DeadlineConsumer {
2372        hangs: bool,
2373    }
2374
2375    #[cfg(feature = "transport")]
2376    impl CredentialConsumerConnection for DeadlineConsumer {
2377        fn credential_get<'a>(
2378            &'a mut self,
2379            _raw_handle: &'a str,
2380            _min_ttl_ms: Option<u64>,
2381            _force_refresh: bool,
2382        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2383            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2384        }
2385
2386        fn credential_get_scoped<'a>(
2387            &'a mut self,
2388            _credential_id: &'a str,
2389            _min_ttl_ms: Option<u64>,
2390        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2391            Box::pin(async move {
2392                if self.hangs {
2393                    std::future::pending().await
2394                } else {
2395                    Ok(json!({
2396                        "payload": "reconnected-secret",
2397                        "record_version": "2",
2398                    }))
2399                }
2400            })
2401        }
2402
2403        fn credential_sign<'a>(
2404            &'a mut self,
2405            _credential_id: &'a str,
2406            _payload: &'a [u8],
2407        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2408            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2409        }
2410
2411        fn credential_public_key<'a>(
2412            &'a mut self,
2413            _credential_id: &'a str,
2414        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2415            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2416        }
2417    }
2418
2419    #[cfg(feature = "transport")]
2420    #[tokio::test]
2421    async fn silent_call_deadline_is_transport_rebuilds_and_releases_mutex_mutation_proof() {
2422        let dials = Arc::new(AtomicUsize::new(0));
2423        let deadline = Duration::from_millis(20);
2424        let target = Arc::new(LiveCredentialGetTarget::new(
2425            Arc::new(DeadlineConnector {
2426                dials: Arc::clone(&dials),
2427            }),
2428            deadline,
2429        ));
2430        let first = tokio::spawn({
2431            let target = Arc::clone(&target);
2432            async move { target.credential_get_scoped("github_app:first").await }
2433        });
2434        tokio::time::timeout(deadline, async {
2435            while dials.load(Ordering::SeqCst) == 0 {
2436                tokio::task::yield_now().await;
2437            }
2438        })
2439        .await
2440        .expect("first call must dial before the fixture deadline");
2441
2442        let second = tokio::time::timeout(
2443            deadline.saturating_mul(3),
2444            target.credential_get_scoped("github_app:second"),
2445        )
2446        .await
2447        .expect("a timed-out holder must release the consumer mutex")
2448        .expect("the rebuilt consumer must serve the second caller");
2449        let first_error = first
2450            .await
2451            .expect("deadline task must join")
2452            .expect_err("the silent first consumer must reach the whole-call deadline");
2453
2454        assert_eq!(first_error.class, CredentialErrorClass::Transport);
2455        assert!(first_error.retryable());
2456        assert_eq!(
2457            first_error.to_string(),
2458            "credential_transport: credential.get_scoped timed out waiting for the credential route"
2459        );
2460        assert_eq!(second["payload"], json!("reconnected-secret"));
2461        assert_eq!(
2462            dials.load(Ordering::SeqCst),
2463            2,
2464            "the deadline must clear the stale cached consumer before the next call"
2465        );
2466    }
2467
2468    #[cfg(feature = "transport")]
2469    #[tokio::test]
2470    async fn live_shape_red_proof_retry_class_and_capability_redaction() {
2471        let raw_handle = "capability-handle-must-never-leak";
2472        let target = Arc::new(FakeCkcredTarget {
2473            script: Mutex::new(VecDeque::from([
2474                Err(CredentialResolverError::new(
2475                    CredentialErrorClass::Transient,
2476                    "credential service is temporarily unavailable",
2477                )),
2478                Ok(json!({
2479                    "result": {
2480                        "payload": "api-secret",
2481                        "record_version": 7,
2482                        "expires_at_ms": 1234,
2483                    }
2484                })),
2485            ])),
2486            requests: Mutex::new(Vec::new()),
2487            reports: Mutex::new(Vec::new()),
2488        });
2489        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2490
2491        let credential = resolver.resolve(raw_handle, Some(500), true).await.unwrap();
2492        assert_eq!(credential.expose(), b"api-secret");
2493        assert_eq!(credential.record_version, "7");
2494        assert_eq!(target.requests.lock().unwrap().len(), 2);
2495        assert!(!format!("{credential:?}").contains(raw_handle));
2496
2497        let permanent = CredentialResolverError::new(
2498            CredentialErrorClass::Permanent,
2499            "credential service rejected the request",
2500        );
2501        assert!(!permanent.retryable());
2502        assert!(!permanent.to_string().contains(raw_handle));
2503    }
2504
2505    #[test]
2506    fn relay_routing_codes_classify_transport_so_redial_arms_fire() {
2507        // The live specimen from the 2026-08-26 speech outage: the relay's
2508        // class-less unknown_channel refusal after a credential-module restart.
2509        // Without transport classification this class-less routing refusal is
2510        // treated as a custody refusal. Transport classification permits redial.
2511        // `module_warming` is the daemon's spelling for the pre-HELLO respawn
2512        // window since subc #53 (it was `target_unavailable`); a copied two-code
2513        // list rendered it as a custody verdict again (GitHub #48).
2514        for code in [
2515            "unknown_channel",
2516            "stale_route_epoch",
2517            "unknown_module",
2518            "module_warming",
2519            "module_reloading",
2520            "target_unavailable",
2521            "module_timeout",
2522        ] {
2523            let error = classify_error_value(&json!({
2524                "code": code,
2525                "message": format!("{code} 1"),
2526            }));
2527            assert!(
2528                error.is_transport(),
2529                "{code} must classify transport (got {:?})",
2530                error.class
2531            );
2532            assert!(error.to_string().contains(code), "verbatim code preserved");
2533        }
2534        // The catch-all still exists for genuinely unknown codes.
2535        let other = classify_error_value(&json!({"code": "weird_new_code"}));
2536        assert!(!other.is_transport());
2537    }
2538
2539    #[test]
2540    fn ckcred_contract_red_proof_request_shape_and_error_capability_redaction() {
2541        let raw_handle = "raw-capability-token";
2542        assert_eq!(
2543            credential_get_request(raw_handle, Some(250), true),
2544            json!({
2545                "method": "credential.get",
2546                "params": {
2547                    "handle": raw_handle,
2548                    "min_ttl_ms": 250,
2549                    "force_refresh": true,
2550                }
2551            })
2552        );
2553        let credential_id = "github_app:scoped-agent";
2554        assert_eq!(
2555            credential_get_scoped_request(credential_id, None),
2556            json!({
2557                "method": "credential.get_scoped",
2558                "params": { "credential_id": credential_id },
2559            })
2560        );
2561        assert_eq!(
2562            credential_get_scoped_request(credential_id, Some(500)),
2563            json!({
2564                "method": "credential.get_scoped",
2565                "params": {
2566                    "credential_id": credential_id,
2567                    "min_ttl_ms": 500,
2568                },
2569            })
2570        );
2571        assert_eq!(
2572            credential_report_auth_failure_request(credential_id, 7, 401),
2573            json!({
2574                "method": "credential.report_auth_failure",
2575                "params": {
2576                    "credential_id": credential_id,
2577                    "provider_status": 401,
2578                    "record_version": 7,
2579                },
2580            })
2581        );
2582        assert_eq!(
2583            credential_status_request(credential_id),
2584            json!({
2585                "method": "credential.status",
2586                "params": { "credential_id": credential_id },
2587            })
2588        );
2589        // CKCRED 3aaf0e3: sign and public_key are handle-less - addressed by
2590        // credential NAME under principal authority, never a bearer handle
2591        // (the handle spelling was the pre-cutover wire and now refuses).
2592        let signing_credential = "signing:agent-assertion:1";
2593        assert_eq!(
2594            credential_sign_request(signing_credential, b"abc"),
2595            json!({
2596                "method": "credential.sign",
2597                "params": {
2598                    "credential_id": signing_credential,
2599                    "payload_b64": "YWJj",
2600                },
2601            })
2602        );
2603        assert_eq!(
2604            credential_public_key_request(signing_credential),
2605            json!({
2606                "method": "credential.public_key",
2607                "params": { "credential_id": signing_credential },
2608            })
2609        );
2610        let error = decode_wire_error(
2611            json!({
2612                "class": "auth_required",
2613                "message": format!("unknown handle {raw_handle}"),
2614            })
2615            .to_string()
2616            .as_bytes(),
2617        );
2618        assert_eq!(error.class, CredentialErrorClass::AuthRequired);
2619        assert_eq!(error.code(), "credential_auth_required");
2620        assert!(!error.to_string().contains(raw_handle));
2621    }
2622
2623    #[test]
2624    fn signing_replies_decode_exact_ed25519_material_and_reject_wrong_algorithm() {
2625        let signature = decode_signature_reply(json!({
2626            "result": {
2627                "signature_b64": base64::engine::general_purpose::STANDARD.encode([7_u8; 64]),
2628                "key_id": "0123456789abcdef",
2629            }
2630        }))
2631        .unwrap();
2632        assert_eq!(signature.signature_hex, "07".repeat(64));
2633        assert_eq!(signature.key_id, "0123456789abcdef");
2634
2635        let public_key_hex = "ab".repeat(32);
2636        let public_key_bytes = [0xab_u8; 32];
2637        let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
2638        let public_key = decode_public_key_reply(json!({
2639            "result": {
2640                "public_key_hex": public_key_hex,
2641                "key_id": key_id,
2642                "algorithm": "ed25519",
2643            }
2644        }))
2645        .unwrap();
2646        assert_eq!(public_key.public_key_hex, "ab".repeat(32));
2647        assert_eq!(public_key.algorithm, PublicKeyAlgorithm::Ed25519);
2648
2649        let error = decode_public_key_reply(json!({
2650            "result": {
2651                "public_key_hex": "ab".repeat(32),
2652                "key_id": hex_bytes(&Sha256::digest(public_key_bytes)[..8]),
2653                "algorithm": "rsa",
2654            }
2655        }))
2656        .unwrap_err();
2657        assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
2658    }
2659
2660    #[test]
2661    fn public_key_replies_type_x25519_and_refuse_unknown_algorithms_and_wrong_key_ids() {
2662        let public_key_bytes = [0xcd_u8; 32];
2663        let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
2664        let reply = |algorithm: &str, key_id: &str| {
2665            json!({
2666                "result": {
2667                    "public_key_hex": "cd".repeat(32),
2668                    "key_id": key_id,
2669                    "algorithm": algorithm,
2670                }
2671            })
2672        };
2673
2674        let x25519 = decode_public_key_reply(reply("x25519", &key_id)).unwrap();
2675        assert_eq!(x25519.algorithm, PublicKeyAlgorithm::X25519);
2676        assert_eq!(x25519.algorithm.as_str(), "x25519");
2677        assert_eq!(x25519.public_key_hex, "cd".repeat(32));
2678        assert_eq!(x25519.key_id, key_id);
2679        let ed25519 = decode_public_key_reply(reply("ed25519", &key_id)).unwrap();
2680        assert_eq!(ed25519.algorithm, PublicKeyAlgorithm::Ed25519);
2681
2682        // Only the two exact lowercase names the vault sends are keys this client knows
2683        // how to use; anything else, including a case variant, is a bad reply.
2684        for algorithm in ["rsa", "X25519", "Ed25519", ""] {
2685            assert_eq!(
2686                decode_public_key_reply(reply(algorithm, &key_id))
2687                    .unwrap_err()
2688                    .class,
2689                CredentialErrorClass::InvalidResponse,
2690                "{algorithm:?}"
2691            );
2692        }
2693        // A key id that does not identify the key is refused for both kinds, so an
2694        // X25519 reply gets the same binding check a signing key does.
2695        let wrong_key_id = hex_bytes(&Sha256::digest([0xab_u8; 32])[..8]);
2696        for algorithm in ["x25519", "ed25519"] {
2697            let error = decode_public_key_reply(reply(algorithm, &wrong_key_id)).unwrap_err();
2698            assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
2699            assert!(
2700                error.to_string().contains("key_id does not identify"),
2701                "{algorithm}: {error}"
2702            );
2703        }
2704    }
2705
2706    #[test]
2707    fn unknown_method_without_a_class_remains_unclassified_and_preserves_producer_details() {
2708        let error = decode_wire_error(
2709            br#"{"code":"unknown_method","message":"unknown method 'credential.put'"}"#,
2710        );
2711        assert_eq!(error.class, CredentialErrorClass::Unclassified);
2712        assert_eq!(error.code(), "unknown_method");
2713        assert!(!error.retryable());
2714        assert_ne!(error.class, CredentialErrorClass::Permanent);
2715        assert_eq!(
2716            error.to_string(),
2717            "unknown_method: unknown method 'credential.put'"
2718        );
2719    }
2720
2721    #[test]
2722    fn error_shaped_success_reply_surfaces_the_typed_class_and_code() {
2723        // The vault answers a principal-bound handle miss as a SUCCESS frame
2724        // carrying result.error; demanding a payload from it laundered the
2725        // typed answer into invalid_response on the first live push fetch.
2726        let error = decode_credential_reply(json!({
2727            "result": { "error": { "class": "permanent", "code": "not_found" } }
2728        }))
2729        .expect_err("an error reply must not decode as a credential");
2730        assert_eq!(error.class, CredentialErrorClass::CredentialAbsent);
2731        assert!(
2732            error.to_string().contains("not_found"),
2733            "the producer's code must survive classification: {error}"
2734        );
2735        assert!(
2736            !error.to_string().contains("opaque payload"),
2737            "a typed refusal must never render as invalid_response: {error}"
2738        );
2739    }
2740
2741    #[cfg(feature = "transport")]
2742    #[tokio::test]
2743    async fn scoped_transport_failure_returns_without_internal_retry_ladder_mutation_proof() {
2744        let credential_id = "github_app:bounded-agent";
2745        let target = Arc::new(FakeCkcredTarget {
2746            script: Mutex::new(VecDeque::from([
2747                Err(CredentialResolverError::transport(
2748                    "connection reset by peer",
2749                )),
2750                Ok(json!({
2751                    "payload": "must-not-be-reached",
2752                    "record_version": "2",
2753                })),
2754            ])),
2755            requests: Mutex::new(Vec::new()),
2756            reports: Mutex::new(Vec::new()),
2757        });
2758        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2759
2760        let error = resolver
2761            .get_scoped(credential_id)
2762            .await
2763            .expect_err("caller owns the scoped redial");
2764
2765        assert_eq!(error.class, CredentialErrorClass::Transport);
2766        assert_eq!(target.requests.lock().unwrap().len(), 1);
2767    }
2768
2769    #[cfg(feature = "transport")]
2770    #[tokio::test]
2771    async fn scoped_get_with_min_ttl_forwards_the_requested_bound() {
2772        let credential_id = "oauth:anthropic";
2773        let target = Arc::new(FakeCkcredTarget {
2774            script: Mutex::new(VecDeque::from([Ok(json!({
2775                "payload": "served-token",
2776                "record_version": 4,
2777                "expires_at_ms": 1_900_000_000_000_i64,
2778            }))])),
2779            requests: Mutex::new(Vec::new()),
2780            reports: Mutex::new(Vec::new()),
2781        });
2782        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
2783
2784        let credential = resolver
2785            .get_scoped_with_min_ttl(credential_id, 300_000)
2786            .await
2787            .unwrap();
2788
2789        assert_eq!(credential.expose(), b"served-token");
2790        assert_eq!(
2791            target.requests.lock().unwrap().as_slice(),
2792            &[(credential_id.to_owned(), Some(300_000), false)]
2793        );
2794    }
2795
2796    #[cfg(feature = "transport")]
2797    #[tokio::test]
2798    async fn report_auth_failure_rejects_unsupported_status_before_sending() {
2799        let credential_id = "apikey:openrouter";
2800        let target = Arc::new(FakeCkcredTarget {
2801            script: Mutex::new(VecDeque::from([Ok(json!({
2802                "result": { "accepted": true }
2803            }))])),
2804            requests: Mutex::new(Vec::new()),
2805            reports: Mutex::new(Vec::new()),
2806        });
2807        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
2808
2809        let error = resolver
2810            .report_auth_failure(credential_id, 12, 429)
2811            .await
2812            .expect_err("only provider 401 and 403 statuses are sent");
2813        assert_eq!(error.class, CredentialErrorClass::Permanent);
2814        assert!(target.reports.lock().unwrap().is_empty());
2815    }
2816
2817    #[cfg(feature = "transport")]
2818    #[tokio::test]
2819    async fn scoped_reads_use_the_credential_id_and_decode_the_record_directly() {
2820        let credential_id = "github_app:scoped-agent";
2821        let target = Arc::new(FakeCkcredTarget {
2822            script: Mutex::new(VecDeque::from([Ok(json!({
2823                "payload": "-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----",
2824                "record_version": "7",
2825            }))])),
2826            requests: Mutex::new(Vec::new()),
2827            reports: Mutex::new(Vec::new()),
2828        });
2829        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
2830
2831        let credential = resolver.get_scoped(credential_id).await.unwrap();
2832
2833        assert_eq!(
2834            credential.expose(),
2835            b"-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----"
2836        );
2837        assert_eq!(credential.record_version, "7");
2838        assert_eq!(
2839            target.requests.lock().unwrap().as_slice(),
2840            &[(credential_id.to_owned(), None, false)]
2841        );
2842    }
2843
2844    #[cfg(feature = "transport")]
2845    #[test]
2846    fn route_open_body_carries_the_reserved_consumer_identity_when_the_nonce_is_present() {
2847        let root = Path::new("/probe/root");
2848        let body = route_open_body_with_nonce(root, "prefrontal-core", "nonce-under-test");
2849        assert_eq!(
2850            body.pointer("/consumer_identity/module_id")
2851                .and_then(Value::as_str),
2852            Some("prefrontal-core"),
2853            "a supervised launch must ride the reserved principal"
2854        );
2855        assert_eq!(
2856            body.pointer("/consumer_identity/launch_nonce")
2857                .and_then(Value::as_str),
2858            Some("nonce-under-test")
2859        );
2860    }
2861
2862    #[cfg(feature = "transport")]
2863    #[test]
2864    fn motor_credential_route_presents_its_launch_nonce() {
2865        let body =
2866            route_open_body_with_nonce(Path::new("/motor-project"), "ck-motor", "motor-nonce");
2867        assert_eq!(body["op"], "route.open");
2868        assert_eq!(body["target"]["module_id"], "claustrum");
2869        assert_eq!(
2870            body["consumer_identity"],
2871            json!({"module_id":"ck-motor", "launch_nonce":"motor-nonce"})
2872        );
2873    }
2874
2875    #[cfg(feature = "transport")]
2876    #[tokio::test]
2877    async fn signing_not_found_and_auth_required_are_terminal_without_retries() {
2878        struct TerminalTarget {
2879            code: &'static str,
2880            calls: AtomicUsize,
2881        }
2882        impl CredentialGetTarget for TerminalTarget {
2883            fn credential_get<'a>(
2884                &'a self,
2885                _: &'a str,
2886                _: Option<u64>,
2887                _: bool,
2888            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2889                panic!("signing must not read private credentials")
2890            }
2891            fn credential_sign<'a>(
2892                &'a self,
2893                _: &'a str,
2894                _: &'a [u8],
2895            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2896                Box::pin(async move {
2897                    self.calls.fetch_add(1, Ordering::SeqCst);
2898                    Err(classify_error_value(
2899                        &json!({"code":self.code, "class":"transient", "message":"do not log vault material"}),
2900                    ))
2901                })
2902            }
2903            fn credential_public_key<'a>(
2904                &'a self,
2905                _: &'a str,
2906            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2907                self.credential_sign("unused", b"")
2908            }
2909        }
2910        for (code, class) in [
2911            ("not_found", CredentialErrorClass::CredentialAbsent),
2912            ("auth_required", CredentialErrorClass::AuthRequired),
2913        ] {
2914            let target = Arc::new(TerminalTarget {
2915                code,
2916                calls: AtomicUsize::new(0),
2917            });
2918            let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2919            assert_eq!(
2920                resolver
2921                    .sign("signing:ck-motor-ssh:1", b"challenge")
2922                    .await
2923                    .unwrap_err()
2924                    .class,
2925                class
2926            );
2927            assert_eq!(
2928                resolver
2929                    .public_key("signing:ck-motor-ssh:1")
2930                    .await
2931                    .unwrap_err()
2932                    .class,
2933                class
2934            );
2935            assert_eq!(target.calls.load(Ordering::SeqCst), 2);
2936            for wire in [
2937                json!({"code":code}),
2938                json!({"error":{"code":code}}),
2939                json!({"error":{"code":code,"class":"transient"}}),
2940            ] {
2941                let error = classify_error_value(&wire);
2942                assert_eq!(error.class, class);
2943                assert!(!error.retryable());
2944                assert!(!error.is_transport());
2945                assert!(!error.to_string().contains("do not log vault material"));
2946            }
2947        }
2948    }
2949
2950    #[cfg(feature = "transport")]
2951    #[test]
2952    fn route_open_body_carries_prefrontal_routing_as_consumer_id() {
2953        let body = route_open_body_with_nonce(
2954            Path::new("/probe/routing"),
2955            "prefrontal-routing",
2956            "routing-nonce-under-test",
2957        );
2958
2959        assert_eq!(
2960            body.pointer("/consumer_identity/module_id")
2961                .and_then(Value::as_str),
2962            Some("prefrontal-routing")
2963        );
2964        assert_eq!(
2965            body.pointer("/identity/harness").and_then(Value::as_str),
2966            Some("prefrontal-routing")
2967        );
2968    }
2969
2970    /// An absent, blank or unreadable nonce stops the route open instead of letting it
2971    /// through unscoped, and does so with an error the module can refuse with, not a
2972    /// panic that would take the module process down.
2973    #[cfg(feature = "transport")]
2974    #[test]
2975    fn route_open_body_requires_the_launch_nonce_for_the_reserved_principal() {
2976        assert_eq!(
2977            required_launch_nonce(Ok(Some("nonce".to_string()))).unwrap(),
2978            "nonce"
2979        );
2980        for read in [
2981            Ok(None),
2982            Ok(Some("  ".to_string())),
2983            Err("descriptor 3 is not open".to_string()),
2984        ] {
2985            let result = std::panic::catch_unwind(|| required_launch_nonce(read.clone()));
2986            let refusal = result
2987                .unwrap_or_else(|_| panic!("{read:?} panicked instead of refusing"))
2988                .expect_err("a missing nonce must not yield one");
2989            assert_eq!(
2990                refusal.class,
2991                CredentialErrorClass::AuthRequired,
2992                "{read:?}"
2993            );
2994            assert!(!refusal.retryable(), "{read:?}");
2995        }
2996    }
2997
2998    #[test]
2999    fn list_scoped_request_sends_no_enrollment_token() {
3000        assert_eq!(
3001            credential_list_scoped_request(),
3002            json!({ "method": "credential.list_scoped", "params": {} })
3003        );
3004    }
3005
3006    /// The reply shape is claustrum's `ListScopedResult` / `ListScopedCredential`
3007    /// serialization (credentials-module `read_surface.rs`): optional fields are
3008    /// omitted when absent, and the id is `id`, not `credential_id`. It is built
3009    /// from that struct, not captured from a live vault, because no principal of
3010    /// this repository yet holds a grant that lists Claude rows.
3011    #[test]
3012    fn list_scoped_reply_decodes_identity_rows_grants_and_view() {
3013        let listing = decode_list_scoped_reply(json!({
3014            "result": {
3015                "credentials": [
3016                    {
3017                        "id": "oauth:anthropic:yiyi",
3018                        "categories": ["anthropic-native", "llm-provider"],
3019                        "type": "oauth",
3020                        "serves": ["anthropic"],
3021                        "refresh_adapter": "anthropic",
3022                        "state": "active",
3023                        "record_version": 227,
3024                        "operations": ["list"],
3025                        "account_id": "acct-1",
3026                        "email": "a@example.test"
3027                    },
3028                    {
3029                        "id": "apikey:artificial-analysis",
3030                        "categories": [],
3031                        "type": "apikey",
3032                        "serves": [],
3033                        "state": "active",
3034                        "record_version": 1,
3035                        "operations": ["read"]
3036                    }
3037                ],
3038                "grants": 1,
3039                "grant_tuples": [
3040                    {"selector_kind": "category", "selector": "anthropic-native", "operation": "list"}
3041                ],
3042                "view": "digest"
3043            }
3044        }))
3045        .expect("listing decodes");
3046        assert_eq!(listing.view, "digest");
3047        assert_eq!(listing.credentials.len(), 2);
3048        let claude = &listing.credentials[0];
3049        assert_eq!(claude.id, "oauth:anthropic:yiyi");
3050        assert_eq!(claude.refresh_adapter.as_deref(), Some("anthropic"));
3051        assert_eq!(claude.account_id.as_deref(), Some("acct-1"));
3052        assert_eq!(claude.record_version, 227);
3053        assert_eq!(listing.credentials[1].account_id, None);
3054        assert_eq!(listing.credentials[1].refresh_adapter, None);
3055        assert_eq!(
3056            listing.grant_tuples,
3057            vec![ListedGrant {
3058                selector_kind: "category".into(),
3059                selector: "anthropic-native".into(),
3060                operation: "list".into(),
3061            }]
3062        );
3063    }
3064
3065    #[test]
3066    fn list_scoped_reply_without_view_is_invalid_and_unreadable_rows_are_local() {
3067        let no_view = decode_list_scoped_reply(json!({ "result": { "credentials": [] } }))
3068            .expect_err("no view");
3069        assert_eq!(no_view.class, CredentialErrorClass::InvalidResponse);
3070        let no_id = decode_list_scoped_reply(json!({
3071            "result": { "credentials": [{ "state": "active" }], "view": "v" }
3072        }))
3073        .expect("row without id does not reject the listing");
3074        assert!(no_id.credentials.is_empty());
3075        assert_eq!(
3076            no_id.undecodable_credentials,
3077            ["row 0: id is not a non-empty string"]
3078        );
3079    }
3080
3081    /// Optional metadata sent as explicit null decodes as absent, so the row stays in
3082    /// the listing; a wrong type in the same field is still a row-local decode failure.
3083    #[test]
3084    fn list_scoped_reply_treats_explicit_null_optional_fields_as_absent() {
3085        let row = |extra: Value| {
3086            let mut row = json!({
3087                "id": "oauth:anthropic",
3088                "categories": ["llm-provider"],
3089                "type": "oauth",
3090                "serves": ["anthropic"],
3091                "state": "active",
3092                "record_version": 3,
3093                "operations": ["read"],
3094            });
3095            row.as_object_mut()
3096                .unwrap()
3097                .extend(extra.as_object().unwrap().clone());
3098            row
3099        };
3100        let listing = decode_list_scoped_reply(json!({
3101            "result": {
3102                "credentials": [
3103                    row(json!({
3104                        "provider_ids": null,
3105                        "auth_method": null,
3106                        "refresh_adapter": null,
3107                        "account_id": null,
3108                        "email": null,
3109                        "org_name": null,
3110                        "plan_tier": null,
3111                        "plan_tier_source": null,
3112                    })),
3113                    row(json!({ "plan_tier": 20 })),
3114                ],
3115                "view": "v",
3116            }
3117        }))
3118        .expect("listing");
3119        assert_eq!(
3120            listing.credentials.len(),
3121            1,
3122            "{:?}",
3123            listing.undecodable_credentials
3124        );
3125        let listed = &listing.credentials[0];
3126        assert!(listed.provider_ids.is_empty());
3127        assert_eq!(
3128            (
3129                &listed.auth_method,
3130                &listed.refresh_adapter,
3131                &listed.account_id,
3132                &listed.email,
3133                &listed.org_name,
3134                &listed.plan_tier,
3135                &listed.plan_tier_source,
3136            ),
3137            (&None, &None, &None, &None, &None, &None, &None)
3138        );
3139        assert_eq!(
3140            listing.undecodable_credentials,
3141            ["oauth:anthropic: plan_tier is not a string"]
3142        );
3143    }
3144}