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        let body = route_open_body(project_root, consumer_module_id);
1285        self.write_request(0, 0, correlation, Priority::Passive, body)
1286            .await?;
1287        let reply = self.read_reply(0, 0, correlation).await?;
1288        if reply.header.ty == FrameType::Error {
1289            return Err(decode_wire_error(&reply.body));
1290        }
1291        let value: Value = serde_json::from_slice(&reply.body).map_err(|_| {
1292            CredentialResolverError::new(
1293                CredentialErrorClass::InvalidResponse,
1294                "credential route-open reply is not valid JSON",
1295            )
1296        })?;
1297        let channel = value
1298            .get("route_channel")
1299            .and_then(Value::as_u64)
1300            .and_then(|value| u16::try_from(value).ok())
1301            .ok_or_else(|| {
1302                CredentialResolverError::new(
1303                    CredentialErrorClass::InvalidResponse,
1304                    "credential route-open reply has no valid channel",
1305                )
1306            })?;
1307        let epoch = value
1308            .get("route_epoch")
1309            .and_then(Value::as_u64)
1310            .and_then(|value| u32::try_from(value).ok())
1311            .ok_or_else(|| {
1312                CredentialResolverError::new(
1313                    CredentialErrorClass::InvalidResponse,
1314                    "credential route-open reply has no valid epoch",
1315                )
1316            })?;
1317        Ok((channel, epoch))
1318    }
1319
1320    async fn credential_get(
1321        &mut self,
1322        raw_handle: &str,
1323        min_ttl_ms: Option<u64>,
1324        force_refresh: bool,
1325    ) -> Result<Value, CredentialResolverError> {
1326        self.credential_request(
1327            credential_get_request(raw_handle, min_ttl_ms, force_refresh),
1328            "credential.get",
1329        )
1330        .await
1331    }
1332
1333    async fn credential_get_scoped(
1334        &mut self,
1335        credential_id: &str,
1336        min_ttl_ms: Option<u64>,
1337    ) -> Result<Value, CredentialResolverError> {
1338        self.credential_request(
1339            credential_get_scoped_request(credential_id, min_ttl_ms),
1340            CREDENTIAL_GET_SCOPED_OP,
1341        )
1342        .await
1343    }
1344
1345    async fn credential_report_auth_failure(
1346        &mut self,
1347        credential_id: &str,
1348        record_version: u64,
1349        provider_status: u16,
1350    ) -> Result<Value, CredentialResolverError> {
1351        self.credential_request(
1352            credential_report_auth_failure_request(credential_id, record_version, provider_status),
1353            CREDENTIAL_REPORT_AUTH_FAILURE_OP,
1354        )
1355        .await
1356    }
1357
1358    async fn credential_status(
1359        &mut self,
1360        credential_id: &str,
1361    ) -> Result<Value, CredentialResolverError> {
1362        self.credential_request(
1363            credential_status_request(credential_id),
1364            CREDENTIAL_STATUS_OP,
1365        )
1366        .await
1367    }
1368
1369    async fn credential_sign(
1370        &mut self,
1371        credential_id: &str,
1372        payload: &[u8],
1373    ) -> Result<Value, CredentialResolverError> {
1374        self.credential_request(
1375            credential_sign_request(credential_id, payload),
1376            CREDENTIAL_SIGN_OP,
1377        )
1378        .await
1379    }
1380
1381    async fn credential_public_key(
1382        &mut self,
1383        credential_id: &str,
1384    ) -> Result<Value, CredentialResolverError> {
1385        self.credential_request(
1386            credential_public_key_request(credential_id),
1387            CREDENTIAL_PUBLIC_KEY_OP,
1388        )
1389        .await
1390    }
1391
1392    async fn credential_seal(
1393        &mut self,
1394        request: SealRequest<'_>,
1395    ) -> Result<Value, CredentialResolverError> {
1396        self.credential_request(credential_seal_request(request), CREDENTIAL_SEAL_OP)
1397            .await
1398    }
1399
1400    async fn credential_request(
1401        &mut self,
1402        request: Value,
1403        operation: &str,
1404    ) -> Result<Value, CredentialResolverError> {
1405        let correlation = self.next_correlation();
1406        self.write_request(
1407            self.route_channel,
1408            self.route_epoch,
1409            correlation,
1410            Priority::Interactive,
1411            request,
1412        )
1413        .await?;
1414        let reply = self
1415            .read_reply(self.route_channel, self.route_epoch, correlation)
1416            .await?;
1417        if reply.header.ty == FrameType::Error {
1418            return Err(decode_wire_error(&reply.body));
1419        }
1420        serde_json::from_slice(&reply.body).map_err(|_| {
1421            CredentialResolverError::new(
1422                CredentialErrorClass::InvalidResponse,
1423                format!("{operation} reply is not valid JSON"),
1424            )
1425        })
1426    }
1427
1428    async fn write_request(
1429        &mut self,
1430        channel: u16,
1431        epoch: u32,
1432        correlation: u64,
1433        priority: Priority,
1434        body: Value,
1435    ) -> Result<(), CredentialResolverError> {
1436        let bytes = serde_json::to_vec(&body).map_err(|_| {
1437            CredentialResolverError::new(
1438                CredentialErrorClass::Permanent,
1439                "credential request encoding failed",
1440            )
1441        })?;
1442        let frame = Frame::build(
1443            FrameType::Request,
1444            Flags::new(false, priority, false),
1445            channel,
1446            epoch,
1447            correlation,
1448            bytes,
1449        )
1450        .map_err(|_| {
1451            CredentialResolverError::new(
1452                CredentialErrorClass::Permanent,
1453                "credential request framing failed",
1454            )
1455        })?;
1456        write_frame(&mut self.stream, &frame)
1457            .await
1458            .map_err(|error| {
1459                CredentialResolverError::transport(format!(
1460                    "credential route write failed: {error}"
1461                ))
1462            })
1463    }
1464
1465    async fn read_reply(
1466        &mut self,
1467        channel: u16,
1468        epoch: u32,
1469        correlation: u64,
1470    ) -> Result<Frame, CredentialResolverError> {
1471        loop {
1472            let frame = tokio::time::timeout(CREDENTIAL_READ_TIMEOUT, read_frame(&mut self.stream))
1473                .await
1474                .map_err(|error| {
1475                    CredentialResolverError::transport(format!(
1476                        "credential route reply timed out: {error}"
1477                    ))
1478                })?
1479                .map_err(|error| {
1480                    CredentialResolverError::transport(format!(
1481                        "credential route read failed: {error}"
1482                    ))
1483                })?
1484                .ok_or_else(|| {
1485                    CredentialResolverError::transport("credential route closed before replying")
1486                })?;
1487            if frame.header.channel == channel
1488                && frame.header.epoch == epoch
1489                && frame.header.corr == correlation
1490                && matches!(frame.header.ty, FrameType::Response | FrameType::Error)
1491            {
1492                return Ok(frame);
1493            }
1494        }
1495    }
1496}
1497
1498#[cfg(feature = "transport")]
1499impl CredentialConsumerConnection for ClaustrumConsumer {
1500    fn into_scoped_watch(
1501        self: Box<Self>,
1502        enrollment_token: Option<String>,
1503    ) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
1504        Box::pin(async move { (*self).start_scoped_watch(enrollment_token).await })
1505    }
1506
1507    fn credential_get<'a>(
1508        &'a mut self,
1509        raw_handle: &'a str,
1510        min_ttl_ms: Option<u64>,
1511        force_refresh: bool,
1512    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1513        Box::pin(ClaustrumConsumer::credential_get(
1514            self,
1515            raw_handle,
1516            min_ttl_ms,
1517            force_refresh,
1518        ))
1519    }
1520
1521    fn credential_get_scoped<'a>(
1522        &'a mut self,
1523        credential_id: &'a str,
1524        min_ttl_ms: Option<u64>,
1525    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1526        Box::pin(ClaustrumConsumer::credential_get_scoped(
1527            self,
1528            credential_id,
1529            min_ttl_ms,
1530        ))
1531    }
1532
1533    fn credential_report_auth_failure<'a>(
1534        &'a mut self,
1535        credential_id: &'a str,
1536        record_version: u64,
1537        provider_status: u16,
1538    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1539        Box::pin(ClaustrumConsumer::credential_report_auth_failure(
1540            self,
1541            credential_id,
1542            record_version,
1543            provider_status,
1544        ))
1545    }
1546
1547    fn credential_status<'a>(
1548        &'a mut self,
1549        credential_id: &'a str,
1550    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1551        Box::pin(ClaustrumConsumer::credential_status(self, credential_id))
1552    }
1553
1554    fn credential_sign<'a>(
1555        &'a mut self,
1556        credential_id: &'a str,
1557        payload: &'a [u8],
1558    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1559        Box::pin(ClaustrumConsumer::credential_sign(
1560            self,
1561            credential_id,
1562            payload,
1563        ))
1564    }
1565
1566    fn credential_public_key<'a>(
1567        &'a mut self,
1568        credential_id: &'a str,
1569    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1570        Box::pin(ClaustrumConsumer::credential_public_key(
1571            self,
1572            credential_id,
1573        ))
1574    }
1575
1576    fn credential_seal<'a>(
1577        &'a mut self,
1578        request: SealRequest<'a>,
1579    ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
1580        Box::pin(ClaustrumConsumer::credential_seal(self, request))
1581    }
1582
1583    fn credential_list_scoped(
1584        &mut self,
1585    ) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
1586        Box::pin(
1587            self.credential_request(credential_list_scoped_request(), CREDENTIAL_LIST_SCOPED_OP),
1588        )
1589    }
1590}
1591
1592#[cfg(any(feature = "transport", test))]
1593fn credential_list_scoped_request() -> Value {
1594    // A supervised module is identified by its route's reserved principal, so it
1595    // sends no enrollment token; the vault refuses unknown parameters.
1596    json!({
1597        "method": CREDENTIAL_LIST_SCOPED_OP,
1598        "params": {},
1599    })
1600}
1601
1602fn optional_string(value: &Value, key: &str) -> Option<String> {
1603    value
1604        .get(key)
1605        .and_then(Value::as_str)
1606        .filter(|text| !text.is_empty())
1607        .map(str::to_owned)
1608}
1609
1610fn invalid_listing(detail: &str) -> CredentialResolverError {
1611    CredentialResolverError::new(
1612        CredentialErrorClass::InvalidResponse,
1613        format!("credential.list_scoped reply {detail}"),
1614    )
1615}
1616
1617fn listing_strings(row: &Value, key: &str, optional: bool) -> Result<Vec<String>, String> {
1618    if optional && row.get(key).is_none() {
1619        return Ok(Vec::new());
1620    }
1621    let items = row
1622        .get(key)
1623        .and_then(Value::as_array)
1624        .ok_or_else(|| format!("{key} is not an array"))?;
1625    items
1626        .iter()
1627        .map(|item| {
1628            item.as_str()
1629                .map(str::to_owned)
1630                .ok_or_else(|| format!("{key} contains a non-string"))
1631        })
1632        .collect()
1633}
1634
1635fn listing_string(row: &Value, key: &str) -> Result<String, String> {
1636    optional_string(row, key).ok_or_else(|| format!("{key} is not a non-empty string"))
1637}
1638
1639fn listing_optional_string(row: &Value, key: &str) -> Result<Option<String>, String> {
1640    match row.get(key) {
1641        None => Ok(None),
1642        Some(value) => value
1643            .as_str()
1644            .map(|s| Some(s.to_owned()))
1645            .ok_or_else(|| format!("{key} is not a string")),
1646    }
1647}
1648
1649fn decode_listed_credential(row: &Value) -> Result<ListedCredential, String> {
1650    Ok(ListedCredential {
1651        id: listing_string(row, "id")?,
1652        categories: listing_strings(row, "categories", false)?,
1653        credential_type: listing_string(row, "type")?,
1654        serves: listing_strings(row, "serves", false)?,
1655        provider_ids: listing_strings(row, "provider_ids", true)?,
1656        auth_method: listing_optional_string(row, "auth_method")?,
1657        refresh_adapter: listing_optional_string(row, "refresh_adapter")?,
1658        state: listing_string(row, "state")?,
1659        record_version: row
1660            .get("record_version")
1661            .and_then(Value::as_u64)
1662            .ok_or_else(|| "record_version is not an unsigned integer".to_string())?,
1663        operations: listing_strings(row, "operations", false)?,
1664        account_id: listing_optional_string(row, "account_id")?,
1665        email: listing_optional_string(row, "email")?,
1666        org_name: listing_optional_string(row, "org_name")?,
1667        plan_tier: listing_optional_string(row, "plan_tier")?,
1668        plan_tier_source: listing_optional_string(row, "plan_tier_source")?,
1669    })
1670}
1671
1672fn decode_listed_grant(tuple: &Value) -> Result<ListedGrant, String> {
1673    Ok(ListedGrant {
1674        selector_kind: listing_string(tuple, "selector_kind")?,
1675        selector: listing_string(tuple, "selector")?,
1676        operation: listing_string(tuple, "operation")?,
1677    })
1678}
1679
1680/// Decode metadata row by row: a malformed credential or grant must not discard
1681/// healthy entries listed alongside it. Envelope failures still reject the listing.
1682pub fn decode_list_scoped_reply(
1683    value: Value,
1684) -> Result<ScopedCredentialListing, CredentialResolverError> {
1685    let result = reply_result(value)?;
1686    let view = result
1687        .get("view")
1688        .and_then(Value::as_str)
1689        .ok_or_else(|| invalid_listing("has no view digest"))?
1690        .to_owned();
1691    let rows = result
1692        .get("credentials")
1693        .and_then(Value::as_array)
1694        .ok_or_else(|| invalid_listing("has no credentials array"))?;
1695    let mut credentials = Vec::with_capacity(rows.len());
1696    let mut undecodable_credentials = Vec::new();
1697    for (index, row) in rows.iter().enumerate() {
1698        match decode_listed_credential(row) {
1699            Ok(credential) => credentials.push(credential),
1700            Err(error) => {
1701                let id = optional_string(row, "id").unwrap_or_else(|| format!("row {index}"));
1702                let detail = format!("{id}: {error}");
1703                undecodable_credentials.push(detail);
1704            }
1705        }
1706    }
1707    let mut grant_tuples = Vec::new();
1708    let mut undecodable_grants = Vec::new();
1709    if let Some(tuples) = result.get("grant_tuples").and_then(Value::as_array) {
1710        for (index, tuple) in tuples.iter().enumerate() {
1711            match decode_listed_grant(tuple) {
1712                Ok(grant) => grant_tuples.push(grant),
1713                Err(error) => undecodable_grants.push(format!("grant tuple {index}: {error}")),
1714            }
1715        }
1716    }
1717    Ok(ScopedCredentialListing {
1718        credentials,
1719        undecodable_credentials,
1720        grant_tuples,
1721        undecodable_grants,
1722        view,
1723    })
1724}
1725
1726#[cfg(any(feature = "transport", test))]
1727fn credential_get_request(raw_handle: &str, min_ttl_ms: Option<u64>, force_refresh: bool) -> Value {
1728    let mut params =
1729        serde_json::Map::from_iter([("handle".to_owned(), Value::String(raw_handle.to_owned()))]);
1730    if let Some(min_ttl_ms) = min_ttl_ms {
1731        params.insert("min_ttl_ms".to_owned(), Value::from(min_ttl_ms));
1732    }
1733    if force_refresh {
1734        params.insert("force_refresh".to_owned(), Value::Bool(true));
1735    }
1736    json!({
1737        "method": CREDENTIAL_GET_OP,
1738        "params": params,
1739    })
1740}
1741
1742#[cfg(any(feature = "transport", test))]
1743fn credential_get_scoped_request(credential_id: &str, min_ttl_ms: Option<u64>) -> Value {
1744    let mut params = json!({ "credential_id": credential_id });
1745    if let Some(min_ttl_ms) = min_ttl_ms {
1746        params["min_ttl_ms"] = json!(min_ttl_ms);
1747    }
1748    json!({
1749        "method": CREDENTIAL_GET_SCOPED_OP,
1750        "params": params,
1751    })
1752}
1753
1754#[cfg(any(feature = "transport", test))]
1755fn credential_report_auth_failure_request(
1756    credential_id: &str,
1757    record_version: u64,
1758    provider_status: u16,
1759) -> Value {
1760    json!({
1761        "method": CREDENTIAL_REPORT_AUTH_FAILURE_OP,
1762        "params": {
1763            "credential_id": credential_id,
1764            "provider_status": provider_status,
1765            "record_version": record_version,
1766        },
1767    })
1768}
1769
1770#[cfg(any(feature = "transport", test))]
1771fn credential_status_request(credential_id: &str) -> Value {
1772    json!({
1773        "method": CREDENTIAL_STATUS_OP,
1774        "params": { "credential_id": credential_id },
1775    })
1776}
1777
1778#[cfg(any(feature = "transport", test))]
1779fn credential_sign_request(credential_id: &str, payload: &[u8]) -> Value {
1780    // CKCRED 3aaf0e3: sign is handle-less - authorized by the launch-nonce
1781    // principal against the grant table's sign authority, addressed by the
1782    // credential NAME. A handle here would be a bearer capability for a
1783    // signing key, the shape the handle-less revision exists to delete.
1784    json!({
1785        "method": CREDENTIAL_SIGN_OP,
1786        "params": {
1787            "credential_id": credential_id,
1788            "payload_b64": base64::engine::general_purpose::STANDARD.encode(payload),
1789        },
1790    })
1791}
1792
1793#[cfg(any(feature = "transport", test))]
1794fn credential_public_key_request(credential_id: &str) -> Value {
1795    // The launch-nonce principal authorizes this named credential lookup; a
1796    // bearer capability handle must never cross the public-key request.
1797    json!({
1798        "method": CREDENTIAL_PUBLIC_KEY_OP,
1799        "params": { "credential_id": credential_id },
1800    })
1801}
1802
1803#[cfg(any(feature = "transport", test))]
1804fn credential_seal_request(request: SealRequest<'_>) -> Value {
1805    // Addressed by credential NAME under the route principal's exact seal grant, like
1806    // sign. The vault refuses unknown parameters, so no enrollment token is sent.
1807    let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
1808    json!({
1809        "method": CREDENTIAL_SEAL_OP,
1810        "params": {
1811            "credential_id": request.credential_id,
1812            "recipient_public_key_b64": encode(request.recipient_public_key),
1813            "info_b64": encode(request.info),
1814            "aad_b64": encode(request.aad),
1815            "plaintext_b64": encode(request.plaintext),
1816        },
1817    })
1818}
1819
1820/// Decodes a subc error-frame body without opening a connection.
1821pub fn decode_wire_error(bytes: &[u8]) -> CredentialResolverError {
1822    let value = serde_json::from_slice::<Value>(bytes).unwrap_or(Value::Null);
1823    classify_error_value(&value)
1824}
1825
1826/// Daemon relay refusals: the frame never reached the credential service.
1827const RELAY_ROUTING_CODES: [&str; 7] = [
1828    subc_protocol::error_codes::UNKNOWN_MODULE,
1829    subc_protocol::error_codes::MODULE_RELOADING,
1830    subc_protocol::error_codes::MODULE_WARMING,
1831    subc_protocol::error_codes::TARGET_UNAVAILABLE,
1832    subc_protocol::error_codes::MODULE_TIMEOUT,
1833    "unknown_channel",
1834    "stale_route_epoch",
1835];
1836
1837/// Classify a refusal that may arrive as an error frame body or as a
1838/// `result.error` member of a success frame. The broad class drives retry
1839/// behavior, while preserving the producer's code in the safe message lets an
1840/// operator distinguish a missing, revoked, or denied credential.
1841fn classify_error_value(value: &Value) -> CredentialResolverError {
1842    let class = value
1843        .get("class")
1844        .or_else(|| value.pointer("/error/class"))
1845        .or_else(|| value.pointer("/error/data/class"))
1846        .and_then(Value::as_str);
1847    let class = match class {
1848        Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
1849        Some("credential_absent") => Some(CredentialErrorClass::CredentialAbsent),
1850        Some("unauthorized") => Some(CredentialErrorClass::Unauthorized),
1851        Some("permanent") => Some(CredentialErrorClass::Permanent),
1852        Some("transient") => Some(CredentialErrorClass::Transient),
1853        Some("context_overflow") => Some(CredentialErrorClass::ContextOverflow),
1854        _ => None,
1855    };
1856    let code_field = value
1857        .get("code")
1858        .or_else(|| value.pointer("/error/code"))
1859        .and_then(Value::as_str);
1860    // A missing record or authentication refusal requires operator repair, not
1861    // another signing attempt, even if a producer supplies a broad retry class.
1862    let class = match code_field {
1863        Some("not_found") => Some(CredentialErrorClass::CredentialAbsent),
1864        Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
1865        _ => class,
1866    };
1867    if let Some(class) = class {
1868        let message = match code_field {
1869            Some(code) => format!("credential service rejected the request: {code}"),
1870            None => "credential service rejected the request".to_string(),
1871        };
1872        return CredentialResolverError::new(class, message);
1873    }
1874    let code = value
1875        .get("code")
1876        .or_else(|| value.pointer("/error/code"))
1877        .and_then(Value::as_str)
1878        .unwrap_or("credential_unclassified");
1879    let message = value
1880        .get("message")
1881        .or_else(|| value.pointer("/error/message"))
1882        .and_then(Value::as_str)
1883        .unwrap_or("credential service returned an unclassified error");
1884    // Relay routing refusals mean the DAEMON could not route the frame: the
1885    // credential service never spoke, so nothing about custody can be concluded
1886    // from them. Classify these class-less refusals as transport errors so the
1887    // client can redial a stale channel. The set is named here
1888    // rather than borrowed from the protocol's retryable route-open list:
1889    // whether the SDK retries a code is SUBC's policy, and subc-protocol 0.25
1890    // made `unknown_module` terminal, which silently turned "the credential
1891    // module is not there" back into a custody verdict. A copied list also
1892    // missed `module_warming` once (GitHub #48). The two data-path codes cover
1893    // an established route that died: `unknown_channel` and `stale_route_epoch`
1894    // (the module restarted under the route; the SDK retries each once in place
1895    // and surfaces it only when the retry fails the same way, GitHub #59).
1896    if RELAY_ROUTING_CODES.contains(&code) {
1897        return CredentialResolverError::new(
1898            CredentialErrorClass::Transport,
1899            format!("{code}: {message}"),
1900        );
1901    }
1902    CredentialResolverError::unclassified(code, message)
1903}
1904
1905/// The route.open frame for the credential module. Reserved-principal identity
1906/// is carried in `consumer_identity`, not the bind parameters. The credential
1907/// service derives that principal by matching the launch nonce; if it is absent,
1908/// claustrum silently treats the caller as unscoped. Route opening must therefore
1909/// fail before scoped reads are reduced to an ambiguous `not_found`.
1910#[cfg(feature = "transport")]
1911fn route_open_body(project_root: &Path, consumer_module_id: &str) -> Value {
1912    // The process-wide accessor, never the environment: after the first read
1913    // closes the pipe the daemon handed over, a second independent reader
1914    // would read whatever the process opened next at that descriptor number.
1915    let read = subc_os::launch_nonce()
1916        .map(|nonce| nonce.map(|nonce| nonce.value().to_owned()))
1917        .map_err(|error| error.to_string());
1918    route_open_body_with_nonce(
1919        project_root,
1920        consumer_module_id,
1921        &required_launch_nonce(read),
1922    )
1923}
1924
1925/// The nonce from a read of it, panicking when there is none: without it the
1926/// route would open unscoped (see [`route_open_body`]).
1927#[cfg(feature = "transport")]
1928fn required_launch_nonce(read: Result<Option<String>, String>) -> String {
1929    match read {
1930        Ok(Some(nonce)) if !nonce.trim().is_empty() => nonce,
1931        Ok(_) => panic!(
1932            "credential consumer requires a non-empty launch nonce for the reserved principal"
1933        ),
1934        Err(error) => panic!(
1935            "credential consumer could not read the launch nonce for the reserved principal: {error}"
1936        ),
1937    }
1938}
1939
1940#[cfg(feature = "transport")]
1941fn route_open_body_with_nonce(
1942    project_root: &Path,
1943    consumer_module_id: &str,
1944    launch_nonce: &str,
1945) -> Value {
1946    json!({
1947        "op": "route.open",
1948        "target": {
1949            "kind": "management_surface",
1950            "module_id": CREDENTIAL_MODULE_ID,
1951        },
1952        "identity": {
1953            "project_root": project_root,
1954            "harness": consumer_module_id,
1955            "session": "campaign-credential-consumer",
1956        },
1957        "consumer_identity": {
1958            "module_id": consumer_module_id,
1959            "launch_nonce": launch_nonce,
1960        },
1961        "config": [],
1962    })
1963}
1964
1965fn reply_result(value: Value) -> Result<Value, CredentialResolverError> {
1966    let result = value.get("result").cloned().unwrap_or(value);
1967    if result.get("error").is_some() {
1968        return Err(classify_error_value(&result));
1969    }
1970    Ok(result)
1971}
1972
1973fn valid_lower_hex(value: &str, length: usize) -> bool {
1974    value.len() == length
1975        && value
1976            .bytes()
1977            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1978}
1979
1980fn hex_bytes(bytes: &[u8]) -> String {
1981    let mut encoded = String::with_capacity(bytes.len() * 2);
1982    for byte in bytes {
1983        encoded.push_str(&format!("{byte:02x}"));
1984    }
1985    encoded
1986}
1987
1988/// Decodes a `credential.sign` response, validating the Ed25519 signature shape.
1989pub fn decode_signature_reply(
1990    value: Value,
1991) -> Result<CredentialSignature, CredentialResolverError> {
1992    let result = reply_result(value)?;
1993    let signature_b64 = result
1994        .get("signature_b64")
1995        .and_then(Value::as_str)
1996        .ok_or_else(|| {
1997            CredentialResolverError::new(
1998                CredentialErrorClass::InvalidResponse,
1999                "credential signing reply has no signature_b64",
2000            )
2001        })?;
2002    let signature = base64::engine::general_purpose::STANDARD
2003        .decode(signature_b64)
2004        .map_err(|_| {
2005            CredentialResolverError::new(
2006                CredentialErrorClass::InvalidResponse,
2007                "credential signing reply has invalid base64",
2008            )
2009        })?;
2010    if signature.len() != 64 {
2011        return Err(CredentialResolverError::new(
2012            CredentialErrorClass::InvalidResponse,
2013            "credential signing reply has a non-Ed25519 signature length",
2014        ));
2015    }
2016    let key_id = result
2017        .get("key_id")
2018        .and_then(Value::as_str)
2019        .filter(|value| valid_lower_hex(value, 16))
2020        .ok_or_else(|| {
2021            CredentialResolverError::new(
2022                CredentialErrorClass::InvalidResponse,
2023                "credential signing reply has no valid key_id",
2024            )
2025        })?;
2026    Ok(CredentialSignature {
2027        signature_hex: hex_bytes(&signature),
2028        key_id: key_id.to_owned(),
2029    })
2030}
2031
2032/// Decodes a `credential.public_key` response, validating its public key and ID.
2033///
2034/// The reply is either an Ed25519 signing key or an X25519 KEM key. Both are 32
2035/// bytes, and the vault derives both kinds' `key_id` the same way (the first 8 bytes
2036/// of SHA-256 over the public key), so one length check and one key-id check cover
2037/// both. Any other `algorithm` is refused.
2038pub fn decode_public_key_reply(
2039    value: Value,
2040) -> Result<CredentialPublicKey, CredentialResolverError> {
2041    let result = reply_result(value)?;
2042    let public_key_hex = result
2043        .get("public_key_hex")
2044        .and_then(Value::as_str)
2045        .filter(|value| valid_lower_hex(value, 64))
2046        .ok_or_else(|| {
2047            CredentialResolverError::new(
2048                CredentialErrorClass::InvalidResponse,
2049                "credential public-key reply has no valid public_key_hex",
2050            )
2051        })?;
2052    let key_id = result
2053        .get("key_id")
2054        .and_then(Value::as_str)
2055        .filter(|value| valid_lower_hex(value, 16))
2056        .ok_or_else(|| {
2057            CredentialResolverError::new(
2058                CredentialErrorClass::InvalidResponse,
2059                "credential public-key reply has no valid key_id",
2060            )
2061        })?;
2062    let public_key_bytes = (0..public_key_hex.len())
2063        .step_by(2)
2064        .map(|index| u8::from_str_radix(&public_key_hex[index..index + 2], 16))
2065        .collect::<Result<Vec<_>, _>>()
2066        .expect("validated lowercase hex decodes");
2067    let expected_key_id = hex_bytes(&Sha256::digest(&public_key_bytes)[..8]);
2068    if key_id != expected_key_id {
2069        return Err(CredentialResolverError::new(
2070            CredentialErrorClass::InvalidResponse,
2071            "credential public-key reply key_id does not identify public_key_hex",
2072        ));
2073    }
2074    let algorithm = match result.get("algorithm").and_then(Value::as_str) {
2075        Some("ed25519") => PublicKeyAlgorithm::Ed25519,
2076        Some("x25519") => PublicKeyAlgorithm::X25519,
2077        _ => {
2078            return Err(CredentialResolverError::new(
2079                CredentialErrorClass::InvalidResponse,
2080                "credential public-key reply is neither Ed25519 nor X25519",
2081            ))
2082        }
2083    };
2084    Ok(CredentialPublicKey {
2085        public_key_hex: public_key_hex.to_owned(),
2086        key_id: key_id.to_owned(),
2087        algorithm,
2088    })
2089}
2090
2091/// Decodes a `credential.seal` response: a 32-byte encapsulated key, a ciphertext at
2092/// least as long as the AEAD tag, and a key id in `credential.public_key` format.
2093pub fn decode_seal_reply(value: Value) -> Result<CredentialSeal, CredentialResolverError> {
2094    let result = reply_result(value)?;
2095    let invalid = |detail: &str| {
2096        CredentialResolverError::new(
2097            CredentialErrorClass::InvalidResponse,
2098            format!("credential seal reply {detail}"),
2099        )
2100    };
2101    let bytes = |field: &str| {
2102        let text = result
2103            .get(field)
2104            .and_then(Value::as_str)
2105            .ok_or_else(|| invalid(&format!("has no {field}")))?;
2106        base64::engine::general_purpose::STANDARD
2107            .decode(text)
2108            .map_err(|_| invalid(&format!("has invalid base64 in {field}")))
2109    };
2110    let enc = bytes("enc_b64")?;
2111    if enc.len() != 32 {
2112        return Err(invalid("has a non-X25519 encapsulated key length"));
2113    }
2114    let ciphertext = bytes("ciphertext_b64")?;
2115    if ciphertext.len() < 16 {
2116        return Err(invalid("has a ciphertext shorter than the AEAD tag"));
2117    }
2118    let key_id = result
2119        .get("key_id")
2120        .and_then(Value::as_str)
2121        .filter(|value| valid_lower_hex(value, 16))
2122        .ok_or_else(|| invalid("has no valid key_id"))?;
2123    Ok(CredentialSeal {
2124        enc,
2125        ciphertext,
2126        key_id: key_id.to_owned(),
2127    })
2128}
2129
2130/// Decodes a `credential.status` response without fetching credential material.
2131pub fn decode_credential_status_reply(
2132    value: Value,
2133) -> Result<CredentialStatus, CredentialResolverError> {
2134    let result = reply_result(value)?;
2135    let ready = result
2136        .get("ready")
2137        .and_then(Value::as_bool)
2138        .ok_or_else(|| {
2139            CredentialResolverError::new(
2140                CredentialErrorClass::InvalidResponse,
2141                "credential status reply has no ready flag",
2142            )
2143        })?;
2144    let record_version = result.get("record_version").and_then(|value| match value {
2145        Value::String(version) if !version.is_empty() => Some(version.clone()),
2146        Value::Number(version) => Some(version.to_string()),
2147        _ => None,
2148    });
2149    Ok(CredentialStatus {
2150        ready,
2151        record_version,
2152        stale_pending: result
2153            .get("stale_pending")
2154            .and_then(Value::as_bool)
2155            .unwrap_or(false),
2156        last_error_code: result
2157            .get("last_error_code")
2158            .and_then(Value::as_str)
2159            .map(str::to_owned),
2160    })
2161}
2162
2163/// Decodes a `credential.get` or `credential.get_scoped` response into secret bytes.
2164pub fn decode_credential_reply(
2165    value: Value,
2166) -> Result<ResolvedCredential, CredentialResolverError> {
2167    let result = value.get("result").unwrap_or(&value);
2168    // A refusal arrives as a SUCCESS frame carrying `result.error`; demanding a
2169    // payload from it would launder the vault's typed answer (class + code)
2170    // into invalid_response - the first live push fetch reported "no opaque
2171    // payload" for a reply that said permanent/not_found in plain sight.
2172    if result.get("error").is_some() {
2173        return Err(classify_error_value(result));
2174    }
2175    let payload = match result.get("payload") {
2176        Some(Value::String(payload)) => payload.as_bytes().to_vec(),
2177        Some(Value::Array(payload)) => payload
2178            .iter()
2179            .map(|byte| {
2180                byte.as_u64()
2181                    .and_then(|byte| u8::try_from(byte).ok())
2182                    .ok_or_else(|| {
2183                        CredentialResolverError::new(
2184                            CredentialErrorClass::InvalidResponse,
2185                            "credential payload contains a non-byte value",
2186                        )
2187                    })
2188            })
2189            .collect::<Result<Vec<_>, _>>()?,
2190        _ => {
2191            return Err(CredentialResolverError::new(
2192                CredentialErrorClass::InvalidResponse,
2193                "credential reply has no opaque payload",
2194            ));
2195        }
2196    };
2197    let version = result
2198        .get("record_version")
2199        .map(|version| match version {
2200            Value::String(version) => version.clone(),
2201            version => version.to_string(),
2202        })
2203        .filter(|version| !version.is_empty())
2204        .ok_or_else(|| {
2205            CredentialResolverError::new(
2206                CredentialErrorClass::InvalidResponse,
2207                "credential reply has no record version",
2208            )
2209        })?;
2210    let expires_at_ms = result.get("expires_at_ms").and_then(Value::as_i64);
2211    Ok(ResolvedCredential::new_with_identity(
2212        payload,
2213        version,
2214        expires_at_ms,
2215        optional_string(result, "account_id"),
2216        optional_string(result, "email"),
2217        optional_string(result, "org_name"),
2218    ))
2219}
2220
2221/// Decodes whether `credential.report_auth_failure` accepted the report.
2222pub fn decode_report_auth_failure_reply(value: Value) -> Result<bool, CredentialResolverError> {
2223    let result = value.get("result").unwrap_or(&value);
2224    if result.get("error").is_some() {
2225        return Err(classify_error_value(result));
2226    }
2227    result
2228        .get("accepted")
2229        .and_then(Value::as_bool)
2230        .ok_or_else(|| {
2231            CredentialResolverError::new(
2232                CredentialErrorClass::InvalidResponse,
2233                "auth-failure report reply has no accepted value",
2234            )
2235        })
2236}
2237#[cfg(test)]
2238mod contract_tests;
2239
2240#[cfg(test)]
2241mod tests {
2242    #[cfg(feature = "transport")]
2243    use std::sync::atomic::{AtomicUsize, Ordering};
2244
2245    use super::*;
2246
2247    #[cfg(feature = "transport")]
2248    #[derive(Debug)]
2249    struct FakeCkcredTarget {
2250        script: Mutex<VecDeque<Result<Value, CredentialResolverError>>>,
2251        requests: Mutex<Vec<(String, Option<u64>, bool)>>,
2252        reports: Mutex<Vec<(String, u64, u16)>>,
2253    }
2254
2255    #[cfg(feature = "transport")]
2256    impl CredentialGetTarget for FakeCkcredTarget {
2257        fn credential_get<'a>(
2258            &'a self,
2259            raw_handle: &'a str,
2260            min_ttl_ms: Option<u64>,
2261            force_refresh: bool,
2262        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2263            Box::pin(async move {
2264                self.requests
2265                    .lock()
2266                    .expect("fake CKCRED target poisoned")
2267                    .push((raw_handle.to_owned(), min_ttl_ms, force_refresh));
2268                self.script
2269                    .lock()
2270                    .expect("fake CKCRED target poisoned")
2271                    .pop_front()
2272                    .expect("fake CKCRED target script exhausted")
2273            })
2274        }
2275
2276        fn credential_get_scoped<'a>(
2277            &'a self,
2278            credential_id: &'a str,
2279        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2280            Box::pin(async move {
2281                self.requests
2282                    .lock()
2283                    .expect("fake CKCRED target poisoned")
2284                    .push((credential_id.to_owned(), None, false));
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_with_min_ttl<'a>(
2294            &'a self,
2295            credential_id: &'a str,
2296            min_ttl_ms: u64,
2297        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2298            Box::pin(async move {
2299                self.requests
2300                    .lock()
2301                    .expect("fake CKCRED target poisoned")
2302                    .push((credential_id.to_owned(), Some(min_ttl_ms), false));
2303                self.script
2304                    .lock()
2305                    .expect("fake CKCRED target script exhausted")
2306                    .pop_front()
2307                    .expect("fake CKCRED target script exhausted")
2308            })
2309        }
2310
2311        fn credential_report_auth_failure<'a>(
2312            &'a self,
2313            credential_id: &'a str,
2314            record_version: u64,
2315            provider_status: u16,
2316        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2317            Box::pin(async move {
2318                self.reports
2319                    .lock()
2320                    .expect("fake CKCRED target poisoned")
2321                    .push((credential_id.to_owned(), record_version, provider_status));
2322                self.script
2323                    .lock()
2324                    .expect("fake CKCRED target script exhausted")
2325                    .pop_front()
2326                    .expect("fake CKCRED target script exhausted")
2327            })
2328        }
2329    }
2330
2331    #[cfg(feature = "transport")]
2332    #[derive(Debug)]
2333    struct DeadlineConnector {
2334        dials: Arc<AtomicUsize>,
2335    }
2336
2337    #[cfg(feature = "transport")]
2338    impl CredentialConsumerConnector for DeadlineConnector {
2339        fn connect<'a>(
2340            &'a self,
2341        ) -> CredentialResolverFuture<
2342            'a,
2343            Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
2344        > {
2345            Box::pin(async move {
2346                let dial = self.dials.fetch_add(1, Ordering::SeqCst);
2347                Ok(Box::new(DeadlineConsumer { hangs: dial == 0 })
2348                    as Box<dyn CredentialConsumerConnection>)
2349            })
2350        }
2351    }
2352
2353    #[cfg(feature = "transport")]
2354    struct DeadlineConsumer {
2355        hangs: bool,
2356    }
2357
2358    #[cfg(feature = "transport")]
2359    impl CredentialConsumerConnection for DeadlineConsumer {
2360        fn credential_get<'a>(
2361            &'a mut self,
2362            _raw_handle: &'a str,
2363            _min_ttl_ms: Option<u64>,
2364            _force_refresh: bool,
2365        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2366            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2367        }
2368
2369        fn credential_get_scoped<'a>(
2370            &'a mut self,
2371            _credential_id: &'a str,
2372            _min_ttl_ms: Option<u64>,
2373        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2374            Box::pin(async move {
2375                if self.hangs {
2376                    std::future::pending().await
2377                } else {
2378                    Ok(json!({
2379                        "payload": "reconnected-secret",
2380                        "record_version": "2",
2381                    }))
2382                }
2383            })
2384        }
2385
2386        fn credential_sign<'a>(
2387            &'a mut self,
2388            _credential_id: &'a str,
2389            _payload: &'a [u8],
2390        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2391            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2392        }
2393
2394        fn credential_public_key<'a>(
2395            &'a mut self,
2396            _credential_id: &'a str,
2397        ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2398            Box::pin(async { panic!("deadline fixture only supports scoped reads") })
2399        }
2400    }
2401
2402    #[cfg(feature = "transport")]
2403    #[tokio::test]
2404    async fn silent_call_deadline_is_transport_rebuilds_and_releases_mutex_mutation_proof() {
2405        let dials = Arc::new(AtomicUsize::new(0));
2406        let deadline = Duration::from_millis(20);
2407        let target = Arc::new(LiveCredentialGetTarget::new(
2408            Arc::new(DeadlineConnector {
2409                dials: Arc::clone(&dials),
2410            }),
2411            deadline,
2412        ));
2413        let first = tokio::spawn({
2414            let target = Arc::clone(&target);
2415            async move { target.credential_get_scoped("github_app:first").await }
2416        });
2417        tokio::time::timeout(deadline, async {
2418            while dials.load(Ordering::SeqCst) == 0 {
2419                tokio::task::yield_now().await;
2420            }
2421        })
2422        .await
2423        .expect("first call must dial before the fixture deadline");
2424
2425        let second = tokio::time::timeout(
2426            deadline.saturating_mul(3),
2427            target.credential_get_scoped("github_app:second"),
2428        )
2429        .await
2430        .expect("a timed-out holder must release the consumer mutex")
2431        .expect("the rebuilt consumer must serve the second caller");
2432        let first_error = first
2433            .await
2434            .expect("deadline task must join")
2435            .expect_err("the silent first consumer must reach the whole-call deadline");
2436
2437        assert_eq!(first_error.class, CredentialErrorClass::Transport);
2438        assert!(first_error.retryable());
2439        assert_eq!(
2440            first_error.to_string(),
2441            "credential_transport: credential.get_scoped timed out waiting for the credential route"
2442        );
2443        assert_eq!(second["payload"], json!("reconnected-secret"));
2444        assert_eq!(
2445            dials.load(Ordering::SeqCst),
2446            2,
2447            "the deadline must clear the stale cached consumer before the next call"
2448        );
2449    }
2450
2451    #[cfg(feature = "transport")]
2452    #[tokio::test]
2453    async fn live_shape_red_proof_retry_class_and_capability_redaction() {
2454        let raw_handle = "capability-handle-must-never-leak";
2455        let target = Arc::new(FakeCkcredTarget {
2456            script: Mutex::new(VecDeque::from([
2457                Err(CredentialResolverError::new(
2458                    CredentialErrorClass::Transient,
2459                    "credential service is temporarily unavailable",
2460                )),
2461                Ok(json!({
2462                    "result": {
2463                        "payload": "api-secret",
2464                        "record_version": 7,
2465                        "expires_at_ms": 1234,
2466                    }
2467                })),
2468            ])),
2469            requests: Mutex::new(Vec::new()),
2470            reports: Mutex::new(Vec::new()),
2471        });
2472        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2473
2474        let credential = resolver.resolve(raw_handle, Some(500), true).await.unwrap();
2475        assert_eq!(credential.expose(), b"api-secret");
2476        assert_eq!(credential.record_version, "7");
2477        assert_eq!(target.requests.lock().unwrap().len(), 2);
2478        assert!(!format!("{credential:?}").contains(raw_handle));
2479
2480        let permanent = CredentialResolverError::new(
2481            CredentialErrorClass::Permanent,
2482            "credential service rejected the request",
2483        );
2484        assert!(!permanent.retryable());
2485        assert!(!permanent.to_string().contains(raw_handle));
2486    }
2487
2488    #[test]
2489    fn relay_routing_codes_classify_transport_so_redial_arms_fire() {
2490        // The live specimen from the 2026-08-26 speech outage: the relay's
2491        // class-less unknown_channel refusal after a credential-module restart.
2492        // Without transport classification this class-less routing refusal is
2493        // treated as a custody refusal. Transport classification permits redial.
2494        // `module_warming` is the daemon's spelling for the pre-HELLO respawn
2495        // window since subc #53 (it was `target_unavailable`); a copied two-code
2496        // list rendered it as a custody verdict again (GitHub #48).
2497        for code in [
2498            "unknown_channel",
2499            "stale_route_epoch",
2500            "unknown_module",
2501            "module_warming",
2502            "module_reloading",
2503            "target_unavailable",
2504            "module_timeout",
2505        ] {
2506            let error = classify_error_value(&json!({
2507                "code": code,
2508                "message": format!("{code} 1"),
2509            }));
2510            assert!(
2511                error.is_transport(),
2512                "{code} must classify transport (got {:?})",
2513                error.class
2514            );
2515            assert!(error.to_string().contains(code), "verbatim code preserved");
2516        }
2517        // The catch-all still exists for genuinely unknown codes.
2518        let other = classify_error_value(&json!({"code": "weird_new_code"}));
2519        assert!(!other.is_transport());
2520    }
2521
2522    #[test]
2523    fn ckcred_contract_red_proof_request_shape_and_error_capability_redaction() {
2524        let raw_handle = "raw-capability-token";
2525        assert_eq!(
2526            credential_get_request(raw_handle, Some(250), true),
2527            json!({
2528                "method": "credential.get",
2529                "params": {
2530                    "handle": raw_handle,
2531                    "min_ttl_ms": 250,
2532                    "force_refresh": true,
2533                }
2534            })
2535        );
2536        let credential_id = "github_app:scoped-agent";
2537        assert_eq!(
2538            credential_get_scoped_request(credential_id, None),
2539            json!({
2540                "method": "credential.get_scoped",
2541                "params": { "credential_id": credential_id },
2542            })
2543        );
2544        assert_eq!(
2545            credential_get_scoped_request(credential_id, Some(500)),
2546            json!({
2547                "method": "credential.get_scoped",
2548                "params": {
2549                    "credential_id": credential_id,
2550                    "min_ttl_ms": 500,
2551                },
2552            })
2553        );
2554        assert_eq!(
2555            credential_report_auth_failure_request(credential_id, 7, 401),
2556            json!({
2557                "method": "credential.report_auth_failure",
2558                "params": {
2559                    "credential_id": credential_id,
2560                    "provider_status": 401,
2561                    "record_version": 7,
2562                },
2563            })
2564        );
2565        assert_eq!(
2566            credential_status_request(credential_id),
2567            json!({
2568                "method": "credential.status",
2569                "params": { "credential_id": credential_id },
2570            })
2571        );
2572        // CKCRED 3aaf0e3: sign and public_key are handle-less - addressed by
2573        // credential NAME under principal authority, never a bearer handle
2574        // (the handle spelling was the pre-cutover wire and now refuses).
2575        let signing_credential = "signing:agent-assertion:1";
2576        assert_eq!(
2577            credential_sign_request(signing_credential, b"abc"),
2578            json!({
2579                "method": "credential.sign",
2580                "params": {
2581                    "credential_id": signing_credential,
2582                    "payload_b64": "YWJj",
2583                },
2584            })
2585        );
2586        assert_eq!(
2587            credential_public_key_request(signing_credential),
2588            json!({
2589                "method": "credential.public_key",
2590                "params": { "credential_id": signing_credential },
2591            })
2592        );
2593        let error = decode_wire_error(
2594            json!({
2595                "class": "auth_required",
2596                "message": format!("unknown handle {raw_handle}"),
2597            })
2598            .to_string()
2599            .as_bytes(),
2600        );
2601        assert_eq!(error.class, CredentialErrorClass::AuthRequired);
2602        assert_eq!(error.code(), "credential_auth_required");
2603        assert!(!error.to_string().contains(raw_handle));
2604    }
2605
2606    #[test]
2607    fn signing_replies_decode_exact_ed25519_material_and_reject_wrong_algorithm() {
2608        let signature = decode_signature_reply(json!({
2609            "result": {
2610                "signature_b64": base64::engine::general_purpose::STANDARD.encode([7_u8; 64]),
2611                "key_id": "0123456789abcdef",
2612            }
2613        }))
2614        .unwrap();
2615        assert_eq!(signature.signature_hex, "07".repeat(64));
2616        assert_eq!(signature.key_id, "0123456789abcdef");
2617
2618        let public_key_hex = "ab".repeat(32);
2619        let public_key_bytes = [0xab_u8; 32];
2620        let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
2621        let public_key = decode_public_key_reply(json!({
2622            "result": {
2623                "public_key_hex": public_key_hex,
2624                "key_id": key_id,
2625                "algorithm": "ed25519",
2626            }
2627        }))
2628        .unwrap();
2629        assert_eq!(public_key.public_key_hex, "ab".repeat(32));
2630        assert_eq!(public_key.algorithm, PublicKeyAlgorithm::Ed25519);
2631
2632        let error = decode_public_key_reply(json!({
2633            "result": {
2634                "public_key_hex": "ab".repeat(32),
2635                "key_id": hex_bytes(&Sha256::digest(public_key_bytes)[..8]),
2636                "algorithm": "rsa",
2637            }
2638        }))
2639        .unwrap_err();
2640        assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
2641    }
2642
2643    #[test]
2644    fn public_key_replies_type_x25519_and_refuse_unknown_algorithms_and_wrong_key_ids() {
2645        let public_key_bytes = [0xcd_u8; 32];
2646        let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
2647        let reply = |algorithm: &str, key_id: &str| {
2648            json!({
2649                "result": {
2650                    "public_key_hex": "cd".repeat(32),
2651                    "key_id": key_id,
2652                    "algorithm": algorithm,
2653                }
2654            })
2655        };
2656
2657        let x25519 = decode_public_key_reply(reply("x25519", &key_id)).unwrap();
2658        assert_eq!(x25519.algorithm, PublicKeyAlgorithm::X25519);
2659        assert_eq!(x25519.algorithm.as_str(), "x25519");
2660        assert_eq!(x25519.public_key_hex, "cd".repeat(32));
2661        assert_eq!(x25519.key_id, key_id);
2662        let ed25519 = decode_public_key_reply(reply("ed25519", &key_id)).unwrap();
2663        assert_eq!(ed25519.algorithm, PublicKeyAlgorithm::Ed25519);
2664
2665        // Only the two exact lowercase names the vault sends are keys this client knows
2666        // how to use; anything else, including a case variant, is a bad reply.
2667        for algorithm in ["rsa", "X25519", "Ed25519", ""] {
2668            assert_eq!(
2669                decode_public_key_reply(reply(algorithm, &key_id))
2670                    .unwrap_err()
2671                    .class,
2672                CredentialErrorClass::InvalidResponse,
2673                "{algorithm:?}"
2674            );
2675        }
2676        // A key id that does not identify the key is refused for both kinds, so an
2677        // X25519 reply gets the same binding check a signing key does.
2678        let wrong_key_id = hex_bytes(&Sha256::digest([0xab_u8; 32])[..8]);
2679        for algorithm in ["x25519", "ed25519"] {
2680            let error = decode_public_key_reply(reply(algorithm, &wrong_key_id)).unwrap_err();
2681            assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
2682            assert!(
2683                error.to_string().contains("key_id does not identify"),
2684                "{algorithm}: {error}"
2685            );
2686        }
2687    }
2688
2689    #[test]
2690    fn unknown_method_without_a_class_remains_unclassified_and_preserves_producer_details() {
2691        let error = decode_wire_error(
2692            br#"{"code":"unknown_method","message":"unknown method 'credential.put'"}"#,
2693        );
2694        assert_eq!(error.class, CredentialErrorClass::Unclassified);
2695        assert_eq!(error.code(), "unknown_method");
2696        assert!(!error.retryable());
2697        assert_ne!(error.class, CredentialErrorClass::Permanent);
2698        assert_eq!(
2699            error.to_string(),
2700            "unknown_method: unknown method 'credential.put'"
2701        );
2702    }
2703
2704    #[test]
2705    fn error_shaped_success_reply_surfaces_the_typed_class_and_code() {
2706        // The vault answers a principal-bound handle miss as a SUCCESS frame
2707        // carrying result.error; demanding a payload from it laundered the
2708        // typed answer into invalid_response on the first live push fetch.
2709        let error = decode_credential_reply(json!({
2710            "result": { "error": { "class": "permanent", "code": "not_found" } }
2711        }))
2712        .expect_err("an error reply must not decode as a credential");
2713        assert_eq!(error.class, CredentialErrorClass::CredentialAbsent);
2714        assert!(
2715            error.to_string().contains("not_found"),
2716            "the producer's code must survive classification: {error}"
2717        );
2718        assert!(
2719            !error.to_string().contains("opaque payload"),
2720            "a typed refusal must never render as invalid_response: {error}"
2721        );
2722    }
2723
2724    #[cfg(feature = "transport")]
2725    #[tokio::test]
2726    async fn scoped_transport_failure_returns_without_internal_retry_ladder_mutation_proof() {
2727        let credential_id = "github_app:bounded-agent";
2728        let target = Arc::new(FakeCkcredTarget {
2729            script: Mutex::new(VecDeque::from([
2730                Err(CredentialResolverError::transport(
2731                    "connection reset by peer",
2732                )),
2733                Ok(json!({
2734                    "payload": "must-not-be-reached",
2735                    "record_version": "2",
2736                })),
2737            ])),
2738            requests: Mutex::new(Vec::new()),
2739            reports: Mutex::new(Vec::new()),
2740        });
2741        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2742
2743        let error = resolver
2744            .get_scoped(credential_id)
2745            .await
2746            .expect_err("caller owns the scoped redial");
2747
2748        assert_eq!(error.class, CredentialErrorClass::Transport);
2749        assert_eq!(target.requests.lock().unwrap().len(), 1);
2750    }
2751
2752    #[cfg(feature = "transport")]
2753    #[tokio::test]
2754    async fn scoped_get_with_min_ttl_forwards_the_requested_bound() {
2755        let credential_id = "oauth:anthropic";
2756        let target = Arc::new(FakeCkcredTarget {
2757            script: Mutex::new(VecDeque::from([Ok(json!({
2758                "payload": "served-token",
2759                "record_version": 4,
2760                "expires_at_ms": 1_900_000_000_000_i64,
2761            }))])),
2762            requests: Mutex::new(Vec::new()),
2763            reports: Mutex::new(Vec::new()),
2764        });
2765        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
2766
2767        let credential = resolver
2768            .get_scoped_with_min_ttl(credential_id, 300_000)
2769            .await
2770            .unwrap();
2771
2772        assert_eq!(credential.expose(), b"served-token");
2773        assert_eq!(
2774            target.requests.lock().unwrap().as_slice(),
2775            &[(credential_id.to_owned(), Some(300_000), false)]
2776        );
2777    }
2778
2779    #[cfg(feature = "transport")]
2780    #[tokio::test]
2781    async fn report_auth_failure_rejects_unsupported_status_before_sending() {
2782        let credential_id = "apikey:openrouter";
2783        let target = Arc::new(FakeCkcredTarget {
2784            script: Mutex::new(VecDeque::from([Ok(json!({
2785                "result": { "accepted": true }
2786            }))])),
2787            requests: Mutex::new(Vec::new()),
2788            reports: Mutex::new(Vec::new()),
2789        });
2790        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
2791
2792        let error = resolver
2793            .report_auth_failure(credential_id, 12, 429)
2794            .await
2795            .expect_err("only provider 401 and 403 statuses are sent");
2796        assert_eq!(error.class, CredentialErrorClass::Permanent);
2797        assert!(target.reports.lock().unwrap().is_empty());
2798    }
2799
2800    #[cfg(feature = "transport")]
2801    #[tokio::test]
2802    async fn scoped_reads_use_the_credential_id_and_decode_the_record_directly() {
2803        let credential_id = "github_app:scoped-agent";
2804        let target = Arc::new(FakeCkcredTarget {
2805            script: Mutex::new(VecDeque::from([Ok(json!({
2806                "payload": "-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----",
2807                "record_version": "7",
2808            }))])),
2809            requests: Mutex::new(Vec::new()),
2810            reports: Mutex::new(Vec::new()),
2811        });
2812        let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
2813
2814        let credential = resolver.get_scoped(credential_id).await.unwrap();
2815
2816        assert_eq!(
2817            credential.expose(),
2818            b"-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----"
2819        );
2820        assert_eq!(credential.record_version, "7");
2821        assert_eq!(
2822            target.requests.lock().unwrap().as_slice(),
2823            &[(credential_id.to_owned(), None, false)]
2824        );
2825    }
2826
2827    #[cfg(feature = "transport")]
2828    #[test]
2829    fn route_open_body_carries_the_reserved_consumer_identity_when_the_nonce_is_present() {
2830        let root = Path::new("/probe/root");
2831        let body = route_open_body_with_nonce(root, "prefrontal-core", "nonce-under-test");
2832        assert_eq!(
2833            body.pointer("/consumer_identity/module_id")
2834                .and_then(Value::as_str),
2835            Some("prefrontal-core"),
2836            "a supervised launch must ride the reserved principal"
2837        );
2838        assert_eq!(
2839            body.pointer("/consumer_identity/launch_nonce")
2840                .and_then(Value::as_str),
2841            Some("nonce-under-test")
2842        );
2843    }
2844
2845    #[cfg(feature = "transport")]
2846    #[test]
2847    fn motor_credential_route_presents_its_launch_nonce() {
2848        let body =
2849            route_open_body_with_nonce(Path::new("/motor-project"), "ck-motor", "motor-nonce");
2850        assert_eq!(body["op"], "route.open");
2851        assert_eq!(body["target"]["module_id"], "claustrum");
2852        assert_eq!(
2853            body["consumer_identity"],
2854            json!({"module_id":"ck-motor", "launch_nonce":"motor-nonce"})
2855        );
2856    }
2857
2858    #[cfg(feature = "transport")]
2859    #[tokio::test]
2860    async fn signing_not_found_and_auth_required_are_terminal_without_retries() {
2861        struct TerminalTarget {
2862            code: &'static str,
2863            calls: AtomicUsize,
2864        }
2865        impl CredentialGetTarget for TerminalTarget {
2866            fn credential_get<'a>(
2867                &'a self,
2868                _: &'a str,
2869                _: Option<u64>,
2870                _: bool,
2871            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2872                panic!("signing must not read private credentials")
2873            }
2874            fn credential_sign<'a>(
2875                &'a self,
2876                _: &'a str,
2877                _: &'a [u8],
2878            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2879                Box::pin(async move {
2880                    self.calls.fetch_add(1, Ordering::SeqCst);
2881                    Err(classify_error_value(
2882                        &json!({"code":self.code, "class":"transient", "message":"do not log vault material"}),
2883                    ))
2884                })
2885            }
2886            fn credential_public_key<'a>(
2887                &'a self,
2888                _: &'a str,
2889            ) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
2890                self.credential_sign("unused", b"")
2891            }
2892        }
2893        for (code, class) in [
2894            ("not_found", CredentialErrorClass::CredentialAbsent),
2895            ("auth_required", CredentialErrorClass::AuthRequired),
2896        ] {
2897            let target = Arc::new(TerminalTarget {
2898                code,
2899                calls: AtomicUsize::new(0),
2900            });
2901            let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
2902            assert_eq!(
2903                resolver
2904                    .sign("signing:ck-motor-ssh:1", b"challenge")
2905                    .await
2906                    .unwrap_err()
2907                    .class,
2908                class
2909            );
2910            assert_eq!(
2911                resolver
2912                    .public_key("signing:ck-motor-ssh:1")
2913                    .await
2914                    .unwrap_err()
2915                    .class,
2916                class
2917            );
2918            assert_eq!(target.calls.load(Ordering::SeqCst), 2);
2919            for wire in [
2920                json!({"code":code}),
2921                json!({"error":{"code":code}}),
2922                json!({"error":{"code":code,"class":"transient"}}),
2923            ] {
2924                let error = classify_error_value(&wire);
2925                assert_eq!(error.class, class);
2926                assert!(!error.retryable());
2927                assert!(!error.is_transport());
2928                assert!(!error.to_string().contains("do not log vault material"));
2929            }
2930        }
2931    }
2932
2933    #[cfg(feature = "transport")]
2934    #[test]
2935    fn route_open_body_carries_prefrontal_routing_as_consumer_id() {
2936        let body = route_open_body_with_nonce(
2937            Path::new("/probe/routing"),
2938            "prefrontal-routing",
2939            "routing-nonce-under-test",
2940        );
2941
2942        assert_eq!(
2943            body.pointer("/consumer_identity/module_id")
2944                .and_then(Value::as_str),
2945            Some("prefrontal-routing")
2946        );
2947        assert_eq!(
2948            body.pointer("/identity/harness").and_then(Value::as_str),
2949            Some("prefrontal-routing")
2950        );
2951    }
2952
2953    /// An absent, blank or unreadable nonce stops the route open instead of
2954    /// letting it through unscoped.
2955    #[cfg(feature = "transport")]
2956    #[test]
2957    fn route_open_body_requires_the_launch_nonce_for_the_reserved_principal() {
2958        assert_eq!(
2959            required_launch_nonce(Ok(Some("nonce".to_string()))),
2960            "nonce"
2961        );
2962        for read in [
2963            Ok(None),
2964            Ok(Some("  ".to_string())),
2965            Err("descriptor 3 is not open".to_string()),
2966        ] {
2967            let result = std::panic::catch_unwind(|| required_launch_nonce(read.clone()));
2968            assert!(result.is_err(), "{read:?} must not yield a nonce");
2969        }
2970    }
2971
2972    #[test]
2973    fn list_scoped_request_sends_no_enrollment_token() {
2974        assert_eq!(
2975            credential_list_scoped_request(),
2976            json!({ "method": "credential.list_scoped", "params": {} })
2977        );
2978    }
2979
2980    /// The reply shape is claustrum's `ListScopedResult` / `ListScopedCredential`
2981    /// serialization (credentials-module `read_surface.rs`): optional fields are
2982    /// omitted when absent, and the id is `id`, not `credential_id`. It is built
2983    /// from that struct, not captured from a live vault, because no principal of
2984    /// this repository yet holds a grant that lists Claude rows.
2985    #[test]
2986    fn list_scoped_reply_decodes_identity_rows_grants_and_view() {
2987        let listing = decode_list_scoped_reply(json!({
2988            "result": {
2989                "credentials": [
2990                    {
2991                        "id": "oauth:anthropic:yiyi",
2992                        "categories": ["anthropic-native", "llm-provider"],
2993                        "type": "oauth",
2994                        "serves": ["anthropic"],
2995                        "refresh_adapter": "anthropic",
2996                        "state": "active",
2997                        "record_version": 227,
2998                        "operations": ["list"],
2999                        "account_id": "acct-1",
3000                        "email": "a@example.test"
3001                    },
3002                    {
3003                        "id": "apikey:artificial-analysis",
3004                        "categories": [],
3005                        "type": "apikey",
3006                        "serves": [],
3007                        "state": "active",
3008                        "record_version": 1,
3009                        "operations": ["read"]
3010                    }
3011                ],
3012                "grants": 1,
3013                "grant_tuples": [
3014                    {"selector_kind": "category", "selector": "anthropic-native", "operation": "list"}
3015                ],
3016                "view": "digest"
3017            }
3018        }))
3019        .expect("listing decodes");
3020        assert_eq!(listing.view, "digest");
3021        assert_eq!(listing.credentials.len(), 2);
3022        let claude = &listing.credentials[0];
3023        assert_eq!(claude.id, "oauth:anthropic:yiyi");
3024        assert_eq!(claude.refresh_adapter.as_deref(), Some("anthropic"));
3025        assert_eq!(claude.account_id.as_deref(), Some("acct-1"));
3026        assert_eq!(claude.record_version, 227);
3027        assert_eq!(listing.credentials[1].account_id, None);
3028        assert_eq!(listing.credentials[1].refresh_adapter, None);
3029        assert_eq!(
3030            listing.grant_tuples,
3031            vec![ListedGrant {
3032                selector_kind: "category".into(),
3033                selector: "anthropic-native".into(),
3034                operation: "list".into(),
3035            }]
3036        );
3037    }
3038
3039    #[test]
3040    fn list_scoped_reply_without_view_is_invalid_and_unreadable_rows_are_local() {
3041        let no_view = decode_list_scoped_reply(json!({ "result": { "credentials": [] } }))
3042            .expect_err("no view");
3043        assert_eq!(no_view.class, CredentialErrorClass::InvalidResponse);
3044        let no_id = decode_list_scoped_reply(json!({
3045            "result": { "credentials": [{ "state": "active" }], "view": "v" }
3046        }))
3047        .expect("row without id does not reject the listing");
3048        assert!(no_id.credentials.is_empty());
3049        assert_eq!(
3050            no_id.undecodable_credentials,
3051            ["row 0: id is not a non-empty string"]
3052        );
3053    }
3054}