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