Skip to main content

cortexkit_claustrum_client/
lib.rs

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