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