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