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