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