1use crate::capnp::{FromCapnp, ToCapnp};
11use crate::common_capnp;
12use crate::identity::UNAUTHENTICATED_DID_SENTINEL;
13use anyhow::Result;
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16pub fn compute_jkt(key_bytes: &[u8; 32]) -> String {
22 crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Ed25519 { x: key_bytes })
23}
24
25pub fn is_local_iss(iss: &str, local_issuers: &[&str]) -> bool {
37 if iss.is_empty() {
38 return true;
39 }
40 if local_issuers.is_empty() {
41 false
42 } else {
43 local_issuers.contains(&iss)
44 }
45}
46
47#[derive(Clone, Debug, Default, Serialize, Deserialize)]
49pub struct CnfJwk {
50 pub kty: String,
51 pub crv: String,
52 pub x: String,
54}
55
56#[derive(Clone, Debug, Default, Serialize, Deserialize)]
76pub struct Cnf {
77 #[serde(skip_serializing_if = "Option::is_none")]
78 pub jwk: Option<CnfJwk>,
79 #[serde(skip_serializing_if = "Option::is_none")]
80 pub jkt: Option<String>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub hs_signer_suite: Option<String>,
83}
84
85#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
107pub struct ActClaim {
108 pub sub: String,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub clearance: Option<crate::auth::mac::CredentialClearance>,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub act: Option<Box<ActClaim>>,
123}
124
125#[derive(Clone, Serialize, Deserialize)]
138pub struct Claims {
139 #[serde(default)]
144 pub iss: String,
145 pub sub: String,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub tenant: Option<String>,
152 pub exp: i64,
153 pub iat: i64,
154 #[serde(skip_serializing_if = "Option::is_none")]
156 pub jti: Option<String>,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub sid: Option<String>,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub hs_session_authority_generation: Option<String>,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub hs_profile: Option<String>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub hs_signer_suite_v1: Option<String>,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub hs_signer_pq_key_v1: Option<String>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub hs_signer_inventory_v1: Option<String>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub hs_source_issuer_v1: Option<String>,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub hs_source_subject_v1: Option<String>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub hs_tui_profile: Option<String>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub hs_tui_signer_pq_key_v1: Option<String>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub hs_tui_source_issuer_v1: Option<String>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub hs_tui_source_subject_v1: Option<String>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub workload_session_id: Option<String>,
217 #[serde(skip_serializing_if = "Option::is_none")]
219 pub aud: Option<String>,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub client_id: Option<String>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub scope: Option<String>,
235 #[serde(skip_serializing_if = "Option::is_none")]
242 pub cnf: Option<Cnf>,
243 #[serde(skip)]
253 pub token: Option<String>,
254
255 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub clearance: Option<crate::auth::mac::CredentialClearance>,
274
275 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub act: Option<ActClaim>,
283
284 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub cap: Option<String>,
297}
298
299pub const FEDERATE_STAGING_HOST: &str = "https://discovery.staging.lab.hyprstream.com";
303pub const FEDERATE_STAGING_CLIENT: &str = "cyberdione-www-staging";
304
305static FEDERATE_TUI_CLASS_CLIENT: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
314
315pub fn install_federate_tui_class_client(client_id: Option<&str>) -> anyhow::Result<()> {
319 let value = client_id.map(str::to_owned);
320 let existing = FEDERATE_TUI_CLASS_CLIENT.get_or_init(|| value.clone());
323 anyhow::ensure!(
324 *existing == value,
325 "federate TUI class client already installed with a different id"
326 );
327 Ok(())
328}
329
330pub fn federate_tui_class_client() -> Option<&'static str> {
333 FEDERATE_TUI_CLASS_CLIENT.get().and_then(Option::as_deref)
334}
335
336#[derive(Clone, Debug, PartialEq, Eq)]
339pub struct FederateHost(String);
340
341impl FederateHost {
342 pub fn new(configured: &str) -> anyhow::Result<Self> {
343 let parsed = url::Url::parse(configured)?;
344 anyhow::ensure!(
345 parsed.scheme() == "https"
346 && parsed.host_str().is_some()
347 && parsed.username().is_empty()
348 && parsed.password().is_none()
349 && parsed.query().is_none()
350 && parsed.fragment().is_none()
351 && parsed.path() == "/"
352 && parsed.origin().ascii_serialization() == configured,
353 "Federate requires an exact canonical HTTPS origin"
354 );
355 Ok(Self(configured.to_owned()))
356 }
357
358 pub fn as_str(&self) -> &str {
359 &self.0
360 }
361
362 pub fn token_endpoint(&self) -> String {
363 format!("{}/oauth/token", self.0)
364 }
365}
366
367impl std::fmt::Debug for Claims {
369 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370 f.debug_struct("Claims")
371 .field("iss", &self.iss)
372 .field("sub", &self.sub)
373 .field("tenant", &self.tenant)
374 .field("exp", &self.exp)
375 .field("iat", &self.iat)
376 .field("jti", &self.jti)
377 .field("sid", &self.sid)
378 .field(
379 "hs_session_authority_generation",
380 &self.hs_session_authority_generation,
381 )
382 .field("hs_profile", &self.hs_profile)
383 .field("hs_signer_suite_v1", &self.hs_signer_suite_v1)
384 .field("hs_signer_pq_key_v1", &self.hs_signer_pq_key_v1)
385 .field("hs_signer_inventory_v1", &self.hs_signer_inventory_v1)
386 .field("hs_source_issuer_v1", &self.hs_source_issuer_v1)
387 .field("hs_source_subject_v1", &self.hs_source_subject_v1)
388 .field("hs_tui_profile", &self.hs_tui_profile)
389 .field("hs_tui_signer_pq_key_v1", &self.hs_tui_signer_pq_key_v1)
390 .field("hs_tui_source_issuer_v1", &self.hs_tui_source_issuer_v1)
391 .field("hs_tui_source_subject_v1", &self.hs_tui_source_subject_v1)
392 .field("workload_session_id", &self.workload_session_id)
393 .field("aud", &self.aud)
394 .field("client_id", &self.client_id)
395 .field("scope", &self.scope)
396 .field("cnf", &self.cnf)
397 .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
398 .field("clearance", &self.clearance)
399 .field("act", &self.act)
400 .field("cap", &self.cap)
401 .finish()
402 }
403}
404
405impl ToCapnp for Claims {
406 type Builder<'a> = common_capnp::claims::Builder<'a>;
407
408 fn write_to(&self, builder: &mut Self::Builder<'_>) {
409 builder.set_sub(&self.sub);
410 builder.set_exp(self.exp);
411 builder.set_iat(self.iat);
412 builder.set_admin(false); if let Some(ref aud) = self.aud {
414 builder.set_aud(aud);
415 }
416 if let Some(ref token) = self.token {
417 builder.set_token(token);
418 }
419 if !self.iss.is_empty() {
420 builder.set_iss(&self.iss);
421 }
422 if let Some(ref cnf) = self.cnf {
423 if let Some(ref jwk) = cnf.jwk {
424 builder.set_pub_key(&jwk.x);
425 }
426 }
427 if let Some(ref scope) = self.scope {
428 builder.set_oauth_scope(scope);
429 }
430 builder.reborrow().init_scopes(0);
432 }
433}
434
435impl FromCapnp for Claims {
436 type Reader<'a> = common_capnp::claims::Reader<'a>;
437
438 fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
439 let aud = reader
440 .get_aud()
441 .ok()
442 .and_then(|s| s.to_str().ok())
443 .map(std::borrow::ToOwned::to_owned)
444 .filter(|s| !s.is_empty());
445
446 let scope = reader
447 .get_oauth_scope()
448 .ok()
449 .and_then(|s| s.to_str().ok())
450 .map(std::borrow::ToOwned::to_owned)
451 .filter(|s| !s.is_empty());
452
453 let token = reader
454 .get_token()
455 .ok()
456 .and_then(|s| s.to_str().ok())
457 .map(std::borrow::ToOwned::to_owned)
458 .filter(|s| !s.is_empty());
459
460 let iss = reader
461 .get_iss()
462 .ok()
463 .and_then(|s| s.to_str().ok())
464 .map(std::borrow::ToOwned::to_owned)
465 .unwrap_or_default();
466
467 let cnf = reader
468 .get_pub_key()
469 .ok()
470 .and_then(|s| s.to_str().ok())
471 .filter(|s| !s.is_empty())
472 .map(|x| Cnf {
473 jwk: Some(CnfJwk {
474 kty: "OKP".to_owned(),
475 crv: "Ed25519".to_owned(),
476 x: x.to_owned(),
477 }),
478 jkt: None,
479 hs_signer_suite: None,
480 });
481
482 Ok(Self {
483 iss,
484 sub: reader.get_sub()?.to_str()?.to_owned(),
485 tenant: None,
488 exp: reader.get_exp(),
489 iat: reader.get_iat(),
490 jti: None,
491 sid: None,
494 hs_session_authority_generation: None,
495 hs_profile: None,
496 hs_signer_suite_v1: None,
497 hs_signer_pq_key_v1: None,
498 hs_signer_inventory_v1: None,
499 hs_source_issuer_v1: None,
500 hs_source_subject_v1: None,
501 hs_tui_profile: None,
502 hs_tui_signer_pq_key_v1: None,
503 hs_tui_source_issuer_v1: None,
504 hs_tui_source_subject_v1: None,
505 workload_session_id: None,
506 aud,
507 client_id: None,
508 scope,
511 cnf,
512 token,
513 clearance: None,
518 act: None,
521 cap: None,
523 })
524 }
525}
526
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum SessionClaimError {
531 AmbiguousSessionClaims,
534 EmptySessionIdentifier,
536}
537
538impl std::fmt::Display for SessionClaimError {
539 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
540 match self {
541 Self::AmbiguousSessionClaims => write!(
542 f,
543 "credential carries both sid and workload_session_id (disjoint namespaces)"
544 ),
545 Self::EmptySessionIdentifier => {
546 write!(f, "session identifier is empty")
547 }
548 }
549 }
550}
551
552impl std::error::Error for SessionClaimError {}
553
554impl Claims {
555 pub fn new(sub: String, iat: i64, exp: i64) -> Self {
557 Self {
558 iss: String::new(),
559 sub,
560 tenant: None,
561 exp,
562 iat,
563 jti: None,
564 sid: None,
565 hs_session_authority_generation: None,
566 hs_profile: None,
567 hs_signer_suite_v1: None,
568 hs_signer_pq_key_v1: None,
569 hs_signer_inventory_v1: None,
570 hs_source_issuer_v1: None,
571 hs_source_subject_v1: None,
572 hs_tui_profile: None,
573 hs_tui_signer_pq_key_v1: None,
574 hs_tui_source_issuer_v1: None,
575 hs_tui_source_subject_v1: None,
576 workload_session_id: None,
577 aud: None,
578 client_id: None,
579 scope: None,
580 cnf: None,
581 token: None,
582 clearance: None,
583 act: None,
584 cap: None,
585 }
586 }
587
588 pub fn with_actor(mut self, actor: Option<ActClaim>) -> Self {
590 self.act = actor;
591 self
592 }
593
594 pub fn terminal_actor(&self) -> Option<&str> {
596 let mut current = self.act.as_ref()?;
597 while let Some(next) = current.act.as_deref() {
598 current = next;
599 }
600 Some(current.sub.as_str())
601 }
602
603 pub fn with_jti(mut self) -> Self {
605 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
606 use rand::RngCore as _;
607 let mut bytes = [0u8; 16];
608 rand::rngs::OsRng.fill_bytes(&mut bytes);
609 self.jti = Some(URL_SAFE_NO_PAD.encode(bytes));
610 self
611 }
612
613 pub fn with_sid(mut self, sid: impl Into<String>) -> Self {
615 self.sid = Some(sid.into());
616 self
617 }
618
619 pub fn with_session_authority_generation(mut self, generation: [u8; 32]) -> Self {
623 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
624 self.hs_session_authority_generation = Some(URL_SAFE_NO_PAD.encode(generation));
625 self
626 }
627
628 pub fn session_authority_generation(&self) -> anyhow::Result<Option<[u8; 32]>> {
631 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
632 let Some(encoded) = self.hs_session_authority_generation.as_deref() else {
633 return Ok(None);
634 };
635 anyhow::ensure!(encoded.len() == 43, "invalid session generation length");
636 let raw = URL_SAFE_NO_PAD.decode(encoded)?;
637 let generation: [u8; 32] = raw
638 .try_into()
639 .map_err(|_| anyhow::anyhow!("invalid session generation length"))?;
640 anyhow::ensure!(
641 URL_SAFE_NO_PAD.encode(generation) == encoded,
642 "noncanonical session generation"
643 );
644 Ok(Some(generation))
645 }
646
647 pub fn with_federate_signer_inventory(mut self, inventory: [u8; 32]) -> Self {
651 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
652 self.hs_signer_inventory_v1 = Some(URL_SAFE_NO_PAD.encode(inventory));
653 self
654 }
655
656 pub fn federate_signer_inventory(&self) -> anyhow::Result<Option<[u8; 32]>> {
660 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
661 let Some(encoded) = self.hs_signer_inventory_v1.as_deref() else {
662 return Ok(None);
663 };
664 anyhow::ensure!(
665 encoded.len() == 43,
666 "invalid signer inventory digest length"
667 );
668 let raw = URL_SAFE_NO_PAD.decode(encoded)?;
669 let inventory: [u8; 32] = raw
670 .try_into()
671 .map_err(|_| anyhow::anyhow!("invalid signer inventory digest length"))?;
672 anyhow::ensure!(
673 URL_SAFE_NO_PAD.encode(inventory) == encoded,
674 "noncanonical signer inventory digest"
675 );
676 Ok(Some(inventory))
677 }
678
679 pub fn is_reserved_federate_staging_credential(&self) -> bool {
682 self.is_reserved_federate_credential(FEDERATE_STAGING_HOST)
683 }
684
685 pub fn is_reserved_federate_credential(&self, configured_host: &str) -> bool {
686 self.iss == configured_host && self.client_id.as_deref() == Some(FEDERATE_STAGING_CLIENT)
687 }
688
689 pub fn has_federate_profile_marker(&self) -> bool {
700 self.hs_session_authority_generation.is_some()
701 || self.hs_profile.is_some()
702 || self.hs_signer_suite_v1.is_some()
703 || self.hs_signer_pq_key_v1.is_some()
704 || self.hs_signer_inventory_v1.is_some()
705 || self.hs_source_issuer_v1.is_some()
706 || self.hs_source_subject_v1.is_some()
707 }
708
709 pub fn has_federate_tui_profile_marker(&self) -> bool {
713 self.hs_tui_profile.is_some()
714 || self.hs_tui_signer_pq_key_v1.is_some()
715 || self.hs_tui_source_issuer_v1.is_some()
716 || self.hs_tui_source_subject_v1.is_some()
717 }
718
719 pub fn has_complete_federate_tui_profile(&self) -> bool {
723 self.hs_tui_profile.is_some()
724 && self.hs_tui_signer_pq_key_v1.is_some()
725 && self.hs_tui_source_issuer_v1.is_some()
726 && self.hs_tui_source_subject_v1.is_some()
727 }
728
729 pub fn is_federate_tui_class(&self, local_issuers: &[&str]) -> bool {
736 self.has_federate_tui_profile_marker()
737 || (crate::auth::is_local_iss(&self.iss, local_issuers)
738 && federate_tui_class_client()
739 .is_some_and(|client| self.client_id.as_deref() == Some(client)))
740 }
741
742 pub fn with_federate_tui_markers(
747 mut self,
748 pq_key_b64url: String,
749 source_issuer: String,
750 source_subject: String,
751 ) -> Self {
752 self.hs_tui_profile = Some("federate-tui-v1".to_owned());
753 self.hs_tui_signer_pq_key_v1 = Some(pq_key_b64url);
754 self.hs_tui_source_issuer_v1 = Some(source_issuer);
755 self.hs_tui_source_subject_v1 = Some(source_subject);
756 self
757 }
758
759 pub fn with_federate_signer_suite(mut self, thumbprint_b64url: String) -> Self {
763 self.hs_profile = Some("federate-session-v1".to_owned());
764 self.hs_signer_suite_v1 = Some(thumbprint_b64url);
765 self
766 }
767
768 pub fn with_workload_session_id(mut self, id: impl Into<String>) -> Self {
771 self.workload_session_id = Some(id.into());
772 self
773 }
774
775 pub fn session_key(
786 &self,
787 ) -> std::result::Result<Option<super::credential::SessionKey>, SessionClaimError> {
788 let sid = self.sid.as_deref();
789 let wsid = self.workload_session_id.as_deref();
790 if sid.is_some() && wsid.is_some() {
791 return Err(SessionClaimError::AmbiguousSessionClaims);
792 }
793 if sid.is_some_and(|v| v.trim().is_empty()) || wsid.is_some_and(|v| v.trim().is_empty()) {
794 return Err(SessionClaimError::EmptySessionIdentifier);
795 }
796 Ok(match (sid, wsid) {
797 (Some(sid), None) => Some(super::credential::SessionKey::oidc(&self.iss, sid)),
798 (None, Some(id)) => Some(super::credential::SessionKey::workload(&self.iss, id)),
799 (None, None) => None,
800 (Some(_), Some(_)) => unreachable!("both-present rejected above"),
801 })
802 }
803
804 pub fn with_issuer(mut self, issuer: String) -> Self {
807 self.iss = issuer;
808 self
809 }
810
811 pub fn with_tenant(mut self, tenant: String) -> Self {
813 self.tenant = Some(tenant);
814 self
815 }
816
817 pub fn with_audience(mut self, audience: Option<String>) -> Self {
819 self.aud = audience;
820 self
821 }
822
823 pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
827 let value = client_id.into();
828 self.client_id = (!value.trim().is_empty()).then_some(value);
829 self
830 }
831
832 pub fn with_scope(mut self, scope: Option<String>) -> Self {
834 self.scope = scope.filter(|value| !value.trim().is_empty());
835 self
836 }
837
838 pub fn granted_scopes(&self) -> impl Iterator<Item = &str> {
843 self.scope
844 .as_deref()
845 .into_iter()
846 .flat_map(str::split_whitespace)
847 }
848
849 pub fn has_scope(&self, required: &str) -> bool {
851 self.granted_scopes().any(|granted| granted == required)
852 }
853
854 pub fn with_token(mut self, token: String) -> Self {
856 self.token = Some(token);
857 self
858 }
859
860 pub fn with_cnf_jwk(mut self, key_bytes: &[u8; 32]) -> Self {
865 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
866 let mut cnf = self.cnf.take().unwrap_or_default();
869 cnf.jwk = Some(CnfJwk {
870 kty: "OKP".to_owned(),
871 crv: "Ed25519".to_owned(),
872 x: URL_SAFE_NO_PAD.encode(key_bytes),
873 });
874 self.cnf = Some(cnf);
875 self
876 }
877
878 pub fn with_cnf_hs_signer_suite(mut self, thumbprint_b64url: String) -> Self {
883 let mut cnf = self.cnf.take().unwrap_or_default();
884 cnf.hs_signer_suite = Some(thumbprint_b64url);
885 self.cnf = Some(cnf);
886 self
887 }
888
889 pub fn with_cnf_jkt(mut self, key_bytes: &[u8; 32]) -> Self {
895 let mut cnf = self.cnf.take().unwrap_or_default();
896 cnf.jkt = Some(compute_jkt(key_bytes));
897 self.cnf = Some(cnf);
898 self
899 }
900
901 pub fn with_cnf_jkt_thumbprint(mut self, jkt: String) -> Self {
904 let mut cnf = self.cnf.take().unwrap_or_default();
905 cnf.jkt = Some(jkt);
906 self.cnf = Some(cnf);
907 self
908 }
909
910 pub fn with_clearance(mut self, clearance: crate::auth::mac::SecurityLabel) -> Self {
916 self.clearance = Some(crate::auth::mac::CredentialClearance::from_label(clearance));
919 self
920 }
921
922 pub fn with_credential_clearance(
928 mut self,
929 clearance: crate::auth::mac::CredentialClearance,
930 ) -> Self {
931 self.clearance = Some(clearance);
932 self
933 }
934
935 pub fn with_act(mut self, actor: ActClaim) -> Self {
941 self.act = Some(actor);
942 self
943 }
944
945 pub fn with_cap(mut self, cap: String) -> Self {
948 self.cap = Some(cap);
949 self
950 }
951
952 pub fn cnf_key_bytes(&self) -> Option<[u8; 32]> {
954 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
955 let x = self.cnf.as_ref()?.jwk.as_ref()?.x.as_str();
956 let bytes = URL_SAFE_NO_PAD.decode(x).ok()?;
957 bytes.try_into().ok()
958 }
959
960 pub fn cnf_jkt(&self) -> Option<&str> {
962 self.cnf.as_ref()?.jkt.as_deref()
963 }
964
965 pub fn verify_token(
973 &self,
974 verifying_key: &ed25519_dalek::VerifyingKey,
975 expected_aud: Option<&str>,
976 ) -> std::result::Result<Option<Claims>, super::jwt::JwtError> {
977 match &self.token {
978 Some(token) => {
979 let verified = super::jwt::decode(token, verifying_key, expected_aud)?;
980 Ok(Some(verified))
981 }
982 None => Ok(None),
983 }
984 }
985
986 pub fn is_expired(&self) -> bool {
988 chrono::Utc::now().timestamp() > self.exp.saturating_add(5)
989 }
990
991 pub fn is_local_to(&self, local_issuers: &[&str]) -> bool {
995 is_local_iss(&self.iss, local_issuers)
996 }
997
998 pub fn strip_federated_clearance(&mut self, local_issuers: &[&str]) {
1010 if !self.is_local_to(local_issuers) {
1011 self.clearance = None;
1012 }
1013 }
1014
1015 pub fn strip_federated_tenant(&mut self, local_issuers: &[&str]) {
1023 if !self.is_local_to(local_issuers) {
1024 self.tenant = None;
1025 }
1026 }
1027
1028 pub fn subject(&self, local_issuers: &[&str]) -> crate::envelope::Subject {
1038 if self.sub.is_empty() || self.sub == UNAUTHENTICATED_DID_SENTINEL {
1039 return crate::envelope::Subject::anonymous();
1040 }
1041 if self.is_local_to(local_issuers) {
1042 crate::envelope::Subject::new(self.sub.clone())
1043 } else {
1044 crate::envelope::Subject::federated(&self.iss, &self.sub)
1045 }
1046 }
1047}
1048
1049impl crate::auth::mac::SubjectContextClaims for Claims {
1065 fn credential_clearance(&self) -> Option<crate::auth::mac::CredentialClearance> {
1066 self.clearance
1067 }
1068}
1069
1070#[cfg(test)]
1071#[allow(clippy::unwrap_used, clippy::expect_used)]
1072mod tests {
1073 use super::*;
1074
1075 #[test]
1076 fn federate_host_requires_exact_canonical_https_origin() {
1077 for host in [
1078 FEDERATE_STAGING_HOST,
1079 "https://vm-a.example",
1080 "https://vm-b.example:8443",
1081 ] {
1082 let configured = FederateHost::new(host).unwrap();
1083 assert_eq!(configured.as_str(), host);
1084 assert_eq!(configured.token_endpoint(), format!("{host}/oauth/token"));
1085 }
1086 for host in [
1087 "http://vm.example",
1088 "https://vm.example/",
1089 "https://VM.example",
1090 "https://vm.example:443",
1091 "https://user@vm.example",
1092 "https://vm.example/path",
1093 "https://vm.example?",
1094 "https://vm.example#",
1095 " https://vm.example",
1096 "https://vm.example\\evil",
1097 ] {
1098 assert!(FederateHost::new(host).is_err(), "{host}");
1099 }
1100 }
1101
1102 #[test]
1103 fn oauth_scope_claim_is_exact_and_absence_fails_closed() {
1104 let plain = Claims::new("alice".to_owned(), 1000, 2000);
1105 assert!(!plain.has_scope("atproto"));
1106 assert!(!serde_json::to_string(&plain).unwrap().contains("\"scope\""));
1107
1108 let scoped = plain.with_scope(Some("atproto transition:generic".to_owned()));
1109 assert!(scoped.has_scope("atproto"));
1110 assert!(scoped.has_scope("transition:generic"));
1111 assert!(!scoped.has_scope("transition"));
1112 assert_eq!(
1113 scoped.granted_scopes().collect::<Vec<_>>(),
1114 vec!["atproto", "transition:generic"]
1115 );
1116 }
1117
1118 #[test]
1119 fn oauth_scope_survives_capnp_envelope_roundtrip() -> anyhow::Result<()> {
1120 let claims = Claims::new("alice".to_owned(), 1000, 2000)
1121 .with_scope(Some("atproto transition:generic".to_owned()));
1122 let mut message = capnp::message::Builder::new_default();
1123 let mut builder = message.init_root::<common_capnp::claims::Builder>();
1124 claims.write_to(&mut builder);
1125
1126 let decoded = Claims::read_from(builder.into_reader())?;
1127 assert_eq!(decoded.scope, claims.scope);
1128 assert!(decoded.has_scope("atproto"));
1129 assert!(decoded.has_scope("transition:generic"));
1130 Ok(())
1131 }
1132
1133 #[test]
1134 fn federate_profile_has_one_cnf_key_and_top_level_hybrid_commitment() {
1135 let ed = [0x01; 32];
1136 let claims = Claims::new("alice".to_owned(), 1000, 1300)
1137 .with_cnf_jwk(&ed)
1138 .with_federate_signer_suite("n47qkIMqPn-EuRo0YmrWkGFyyCY0UmVhKE19Bxbtt0U".to_owned());
1139 let json = serde_json::to_value(&claims).unwrap();
1140 assert_eq!(json["hs_profile"], "federate-session-v1");
1141 assert_eq!(
1142 json["hs_signer_suite_v1"],
1143 "n47qkIMqPn-EuRo0YmrWkGFyyCY0UmVhKE19Bxbtt0U"
1144 );
1145 assert_eq!(json["cnf"].as_object().unwrap().len(), 1);
1146 assert_eq!(json["cnf"]["jwk"]["kty"], "OKP");
1147 assert_eq!(json["cnf"]["jwk"]["crv"], "Ed25519");
1148 assert_eq!(
1149 json["cnf"]["jwk"]["x"],
1150 "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE"
1151 );
1152 assert!(json["cnf"].get("hs_signer_suite").is_none());
1153 assert!(json["cnf"].get("jkt").is_none());
1154 let decoded: Claims = serde_json::from_value(json).unwrap();
1155 assert!(decoded.has_federate_profile_marker());
1156 }
1157
1158 #[test]
1159 fn test_act_claim_serde_roundtrip_and_default_none() {
1160 let plain = Claims::new("alice".to_owned(), 1000, 2000);
1163 assert!(plain.act.is_none());
1164 let json = serde_json::to_string(&plain).unwrap();
1165 assert!(
1166 !json.contains("\"act\""),
1167 "plain token must not carry act: {json}"
1168 );
1169
1170 let actor = ActClaim {
1173 sub: "service:mcp".to_owned(),
1174 clearance: None,
1175 act: Some(Box::new(ActClaim {
1176 sub: "service:gateway".to_owned(),
1177 clearance: None,
1178 act: None,
1179 })),
1180 };
1181 let delegated = Claims::new("alice".to_owned(), 1000, 2000)
1182 .with_act(actor.clone())
1183 .with_cap("infer@mac://model/qwen-7b".to_owned());
1184 let json = serde_json::to_string(&delegated).unwrap();
1185 let back: Claims = serde_json::from_str(&json).unwrap();
1186 assert_eq!(back.sub, "alice", "sub stays the delegator");
1187 assert_eq!(
1188 back.act,
1189 Some(actor),
1190 "act round-trips including the nested hop"
1191 );
1192 assert_eq!(
1193 back.cap.as_deref(),
1194 Some("infer@mac://model/qwen-7b"),
1195 "attenuated capability subset rides the token (Fu1/#677)"
1196 );
1197 assert!(plain.cap.is_none(), "plain token carries no cap");
1198 assert_eq!(
1199 back.act.as_ref().unwrap().act.as_ref().unwrap().sub,
1200 "service:gateway"
1201 );
1202 }
1203
1204 #[test]
1205 fn test_debug_shows_act_but_redacts_token() {
1206 let claims = Claims::new("alice".to_owned(), 1000, 2000).with_act(ActClaim {
1207 sub: "service:mcp".to_owned(),
1208 clearance: None,
1209 act: None,
1210 });
1211 let dbg = format!("{claims:?}");
1212 assert!(
1213 dbg.contains("service:mcp"),
1214 "act is not secret, must be visible"
1215 );
1216 assert!(dbg.contains("act:"));
1217 }
1218
1219 #[test]
1220 fn test_claims_new() {
1221 let claims = Claims::new("alice".to_owned(), 1000, 2000);
1222 assert_eq!(claims.sub, "alice");
1223 assert_eq!(claims.iat, 1000);
1224 assert_eq!(claims.exp, 2000);
1225 assert_eq!(claims.iss, "");
1226 assert!(claims.aud.is_none());
1227 assert!(claims.token.is_none());
1228 }
1229
1230 #[test]
1231 fn expiry_check_handles_i64_max_without_wrapping() {
1232 let claims = Claims::new("alice".to_owned(), 0, i64::MAX);
1233 assert!(
1234 !claims.is_expired(),
1235 "an i64::MAX expiry must not wrap into an expired timestamp"
1236 );
1237 }
1238
1239 #[test]
1240 fn test_claims_with_issuer() {
1241 let claims = Claims::new("alice".to_owned(), 1000, 2000)
1242 .with_issuer("https://a.example.com".to_owned());
1243 assert_eq!(claims.iss, "https://a.example.com");
1244 }
1245
1246 use crate::auth::mac::{
1249 Assurance, CompartmentSet, Level, SecurityLabel, SubjectContextClaims as _,
1250 };
1251
1252 fn fu5_clearance() -> SecurityLabel {
1253 SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY)
1254 }
1255
1256 #[test]
1261 fn fu5_federated_clearance_is_stripped() {
1262 let federated = "https://idp.example.com";
1263 let mut claims = Claims::new("alice".to_owned(), 1000, 2000)
1264 .with_issuer(federated.to_owned())
1265 .with_clearance(fu5_clearance());
1266 assert!(
1267 claims.clearance.is_some(),
1268 "precondition: federated token carries a clearance"
1269 );
1270
1271 claims.strip_federated_clearance(&["https://this.node"]);
1273
1274 assert!(
1275 claims.clearance.is_none(),
1276 "a federated token's clearance MUST be ignored (Fu5/#677)"
1277 );
1278 assert!(
1279 claims.credential_clearance().is_none(),
1280 "the MAC PDP reads None ⇒ unlabeled ⇒ deny"
1281 );
1282 }
1283
1284 #[test]
1287 fn fu5_local_clearance_is_preserved() {
1288 let local_iss = "https://this.node";
1289 let mut claims = Claims::new("alice".to_owned(), 1000, 2000)
1290 .with_issuer(local_iss.to_owned())
1291 .with_clearance(fu5_clearance());
1292
1293 claims.strip_federated_clearance(&[local_iss]);
1294
1295 let kept = claims
1296 .clearance
1297 .expect("a local-issuer token keeps its authority-asserted clearance");
1298 assert_eq!(kept.level, Level::Secret);
1299 }
1300
1301 #[test]
1304 fn fu5_unconfigured_node_strips_all_clearance() {
1305 let mut claims = Claims::new("alice".to_owned(), 1000, 2000)
1306 .with_issuer("https://some.idp".to_owned())
1307 .with_clearance(fu5_clearance());
1308
1309 claims.strip_federated_clearance(&[]);
1310
1311 assert!(
1312 claims.clearance.is_none(),
1313 "an unconfigured node honors no clearance (deny-by-default)"
1314 );
1315 }
1316
1317 #[test]
1324 fn session_key_is_exact_one_never_or_else() {
1325 use crate::auth::credential::SessionIdentifier;
1326 let base =
1327 || Claims::new("alice".to_owned(), 0, 100).with_issuer("https://iss.test".to_owned());
1328
1329 assert_eq!(base().session_key(), Ok(None));
1331
1332 let oidc = base().with_sid("s1").session_key().unwrap().unwrap();
1334 assert_eq!(oidc.issuer, "https://iss.test");
1335 assert!(matches!(oidc.id, SessionIdentifier::OidcSid(ref v) if v == "s1"));
1336
1337 let wl = base()
1339 .with_workload_session_id("w1")
1340 .session_key()
1341 .unwrap()
1342 .unwrap();
1343 assert!(matches!(wl.id, SessionIdentifier::WorkloadSessionId(ref v) if v == "w1"));
1344
1345 assert_eq!(
1347 base()
1348 .with_sid("s1")
1349 .with_workload_session_id("w1")
1350 .session_key(),
1351 Err(SessionClaimError::AmbiguousSessionClaims)
1352 );
1353
1354 assert_eq!(
1356 base().with_sid("").session_key(),
1357 Err(SessionClaimError::EmptySessionIdentifier)
1358 );
1359 assert_eq!(
1360 base().with_sid(" ").session_key(),
1361 Err(SessionClaimError::EmptySessionIdentifier)
1362 );
1363 assert_eq!(
1364 base().with_workload_session_id("").session_key(),
1365 Err(SessionClaimError::EmptySessionIdentifier)
1366 );
1367 }
1368
1369 #[test]
1370 fn test_claims_with_audience() {
1371 let claims = Claims::new("alice".to_owned(), 1000, 2000)
1372 .with_audience(Some("https://api.example.com".to_owned()));
1373 assert_eq!(claims.aud, Some("https://api.example.com".to_owned()));
1374 }
1375
1376 #[test]
1377 fn test_claims_with_token() {
1378 let claims =
1379 Claims::new("alice".to_owned(), 1000, 2000).with_token("eyJ.test.token".to_owned());
1380 assert_eq!(claims.token, Some("eyJ.test.token".to_owned()));
1381 }
1382
1383 #[test]
1384 fn test_claims_token_not_in_json() {
1385 let claims =
1386 Claims::new("alice".to_owned(), 1000, 2000).with_token("eyJ.secret.token".to_owned());
1387 let json = serde_json::to_string(&claims).unwrap();
1388 assert!(!json.contains("secret"));
1389 assert!(!json.contains("token"));
1390 }
1391
1392 #[test]
1393 fn test_claims_debug_redacts_token() {
1394 let claims =
1395 Claims::new("alice".to_owned(), 1000, 2000).with_token("eyJ.secret.token".to_owned());
1396 let debug = format!("{:?}", claims);
1397 assert!(debug.contains("[REDACTED]"));
1398 assert!(!debug.contains("secret"));
1399 }
1400
1401 #[test]
1402 fn test_claims_subject() {
1403 use crate::envelope::Subject;
1404 let claims = Claims::new("alice".to_owned(), 1000, 2000);
1405 assert_eq!(Subject::from(&claims), Subject::new("alice"));
1406
1407 let sentinel = Claims::new(UNAUTHENTICATED_DID_SENTINEL.to_owned(), 1000, 2000);
1408 assert_eq!(Subject::from(&sentinel), Subject::anonymous());
1409 }
1410
1411 #[test]
1412 fn test_claims_is_local_to() {
1413 let local = Claims::new("alice".to_owned(), 0, 9999)
1414 .with_issuer("https://local.example.com".to_owned());
1415 let federated = Claims::new("bob".to_owned(), 0, 9999)
1416 .with_issuer("https://other.example.com".to_owned());
1417 let legacy = Claims::new("carol".to_owned(), 0, 9999); assert!(local.is_local_to(&["https://local.example.com"]));
1420 assert!(!local.is_local_to(&["https://other.example.com"]));
1421 assert!(!federated.is_local_to(&["https://local.example.com"]));
1422 assert!(legacy.is_local_to(&[]));
1424 assert!(legacy.is_local_to(&["https://local.example.com"]));
1425 }
1426
1427 #[test]
1428 fn test_claims_subject_method() {
1429 use crate::envelope::Subject;
1430
1431 let local = Claims::new("alice".to_owned(), 0, 9999)
1432 .with_issuer("https://node.example.com".to_owned());
1433 let federated = Claims::new("bob".to_owned(), 0, 9999)
1434 .with_issuer("https://other.example.com".to_owned());
1435 let no_sub = Claims::new(String::new(), 0, 9999);
1436 let sentinel = Claims::new(UNAUTHENTICATED_DID_SENTINEL.to_owned(), 0, 9999)
1437 .with_issuer("https://node.example.com".to_owned());
1438
1439 assert_eq!(
1440 local.subject(&["https://node.example.com"]),
1441 Subject::new("alice")
1442 );
1443 assert_eq!(
1444 federated.subject(&["https://node.example.com"]),
1445 Subject::federated("https://other.example.com", "bob")
1446 );
1447 assert_eq!(no_sub.subject(&[]), Subject::anonymous());
1448 assert_eq!(
1449 sentinel.subject(&["https://node.example.com"]),
1450 Subject::anonymous()
1451 );
1452 }
1453
1454 #[test]
1455 fn test_claims_roundtrip_with_iss() {
1456 use super::super::jwt;
1457 use ed25519_dalek::SigningKey;
1458
1459 let signing_key = SigningKey::from_bytes(&[42u8; 32]);
1460 let verifying_key = signing_key.verifying_key();
1461
1462 let claims = Claims::new("alice".to_owned(), 0, 9_999_999_999)
1463 .with_issuer("https://a.example.com".to_owned());
1464
1465 let token = jwt::encode(&claims, &signing_key);
1466 let decoded = jwt::decode(&token, &verifying_key, None).expect("decode failed");
1467
1468 assert_eq!(decoded.iss, "https://a.example.com");
1469 assert_eq!(decoded.sub, "alice");
1470 assert_eq!(decoded.exp, 9_999_999_999);
1471 }
1472
1473 #[test]
1474 fn test_claims_iss_absent_defaults_to_empty() {
1475 let json = r#"{"sub":"bob","exp":9999999999,"iat":0}"#;
1478 let claims: Claims = serde_json::from_str(json)
1479 .expect("old token without iss should deserialize successfully");
1480 assert_eq!(claims.iss, "");
1481 assert_eq!(claims.sub, "bob");
1482 }
1483
1484 #[test]
1485 fn test_claims_iss_not_in_json_when_empty() {
1486 let claims = Claims::new("alice".to_owned(), 0, 9_999_999_999)
1490 .with_issuer("https://cloud.example.com".to_owned());
1491 let json = serde_json::to_string(&claims).unwrap();
1492 assert!(json.contains("\"iss\":\"https://cloud.example.com\""));
1493 }
1494}
1495
1496#[derive(Clone, Debug, PartialEq, Eq)]
1504pub enum OneOrMany {
1505 One(String),
1507 Many(Vec<String>),
1509}
1510
1511impl OneOrMany {
1512 pub fn one(value: impl Into<String>) -> Self {
1514 Self::One(value.into())
1515 }
1516
1517 pub fn from_vec(mut values: Vec<String>) -> Self {
1519 if values.len() == 1 {
1520 Self::One(values.swap_remove(0))
1521 } else {
1522 Self::Many(values)
1523 }
1524 }
1525
1526 pub fn as_slice(&self) -> &[String] {
1528 match self {
1529 Self::One(v) => std::slice::from_ref(v),
1530 Self::Many(v) => v,
1531 }
1532 }
1533}
1534
1535impl Serialize for OneOrMany {
1536 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1537 match self {
1538 Self::One(v) => serializer.serialize_str(v),
1539 Self::Many(v) => v.serialize(serializer),
1540 }
1541 }
1542}
1543
1544impl<'de> Deserialize<'de> for OneOrMany {
1545 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
1546 let value = serde_json::Value::deserialize(deserializer)?;
1547 match value {
1548 serde_json::Value::String(s) => Ok(Self::One(s)),
1549 serde_json::Value::Array(arr) => {
1550 let strings: std::result::Result<Vec<String>, _> = arr
1551 .into_iter()
1552 .map(|v| {
1553 v.as_str().map(String::from).ok_or_else(|| {
1554 serde::de::Error::custom("aud array must contain strings")
1555 })
1556 })
1557 .collect();
1558 Ok(Self::from_vec(strings?))
1559 }
1560 _ => Err(serde::de::Error::custom("aud must be a string or array")),
1561 }
1562 }
1563}
1564
1565#[derive(Clone, Debug, Serialize, Deserialize)]
1573pub struct IdTokenClaims {
1574 pub iss: String,
1577 pub sub: String,
1579 pub aud: OneOrMany,
1581 pub exp: i64,
1583 pub iat: i64,
1585
1586 #[serde(skip_serializing_if = "Option::is_none")]
1589 pub nonce: Option<String>,
1590 #[serde(skip_serializing_if = "Option::is_none")]
1592 pub auth_time: Option<i64>,
1593 #[serde(skip_serializing_if = "Option::is_none")]
1595 pub azp: Option<String>,
1596 #[serde(skip_serializing_if = "Option::is_none")]
1598 pub tenant: Option<String>,
1599
1600 #[serde(skip_serializing_if = "Option::is_none")]
1603 pub name: Option<String>,
1604 #[serde(skip_serializing_if = "Option::is_none")]
1606 pub email: Option<String>,
1607 #[serde(skip_serializing_if = "Option::is_none")]
1609 pub email_verified: Option<bool>,
1610 #[serde(skip_serializing_if = "Option::is_none")]
1612 pub preferred_username: Option<String>,
1613}
1614
1615impl IdTokenClaims {
1616 pub fn new(iss: String, sub: String, aud: String, iat: i64, exp: i64) -> Self {
1618 Self {
1619 iss,
1620 sub,
1621 aud: OneOrMany::one(aud),
1622 exp,
1623 iat,
1624 nonce: None,
1625 auth_time: None,
1626 azp: None,
1627 tenant: None,
1628 name: None,
1629 email: None,
1630 email_verified: None,
1631 preferred_username: None,
1632 }
1633 }
1634
1635 pub fn with_nonce(mut self, nonce: Option<String>) -> Self {
1637 self.nonce = nonce;
1638 self
1639 }
1640
1641 pub fn with_auth_time(mut self, auth_time: i64) -> Self {
1643 self.auth_time = Some(auth_time);
1644 self
1645 }
1646
1647 pub fn with_tenant(mut self, tenant: String) -> Self {
1649 self.tenant = Some(tenant);
1650 self
1651 }
1652
1653 pub fn with_profile(
1655 mut self,
1656 name: Option<String>,
1657 email: Option<String>,
1658 email_verified: Option<bool>,
1659 preferred_username: Option<String>,
1660 ) -> Self {
1661 self.name = name;
1662 self.email = email;
1663 self.email_verified = email_verified;
1664 self.preferred_username = preferred_username;
1665 self
1666 }
1667}
1668
1669#[cfg(test)]
1670#[allow(clippy::unwrap_used, clippy::expect_used)]
1671mod id_token_tests {
1672 use super::*;
1673
1674 #[test]
1675 fn test_id_token_claims_serialization() {
1676 let claims = IdTokenClaims::new(
1677 "https://example.com".into(),
1678 "f47ac10b-58cc-4372-a567-0e02b2c3d479".into(),
1679 "my-client".into(),
1680 1000,
1681 2000,
1682 );
1683 let json = serde_json::to_string(&claims).unwrap();
1684 assert!(json.contains("\"aud\":\"my-client\""));
1686 assert!(json.contains("\"sub\":\"f47ac10b-"));
1687 assert!(!json.contains("nonce"));
1689 assert!(!json.contains("name"));
1690 assert!(!json.contains("email"));
1691 }
1692
1693 #[test]
1694 fn test_id_token_claims_with_profile() {
1695 let claims = IdTokenClaims::new(
1696 "https://example.com".into(),
1697 "uuid-123".into(),
1698 "client-1".into(),
1699 1000,
1700 2000,
1701 )
1702 .with_nonce(Some("abc123".into()))
1703 .with_auth_time(999)
1704 .with_profile(
1705 Some("Alice".into()),
1706 Some("alice@example.com".into()),
1707 Some(true),
1708 Some("alice".into()),
1709 );
1710 let json = serde_json::to_string(&claims).unwrap();
1711 assert!(json.contains("\"nonce\":\"abc123\""));
1712 assert!(json.contains("\"auth_time\":999"));
1713 assert!(json.contains("\"name\":\"Alice\""));
1714 assert!(json.contains("\"email\":\"alice@example.com\""));
1715 assert!(json.contains("\"email_verified\":true"));
1716 assert!(json.contains("\"preferred_username\":\"alice\""));
1717 }
1718
1719 #[test]
1720 fn test_one_or_many_single() {
1721 let aud = OneOrMany::one("client-1");
1722 let json = serde_json::to_string(&aud).unwrap();
1723 assert_eq!(json, "\"client-1\"");
1724 }
1725
1726 #[test]
1727 fn test_one_or_many_multiple() {
1728 let aud = OneOrMany::from_vec(vec!["a".into(), "b".into()]);
1729 let json = serde_json::to_string(&aud).unwrap();
1730 assert_eq!(json, "[\"a\",\"b\"]");
1731 }
1732
1733 #[test]
1734 fn test_one_or_many_deserialize_string() {
1735 let aud: OneOrMany = serde_json::from_str("\"client-1\"").unwrap();
1736 assert_eq!(aud, OneOrMany::One("client-1".into()));
1737 }
1738
1739 #[test]
1740 fn test_one_or_many_deserialize_array() {
1741 let aud: OneOrMany = serde_json::from_str("[\"a\",\"b\"]").unwrap();
1742 assert_eq!(aud, OneOrMany::Many(vec!["a".into(), "b".into()]));
1743 }
1744
1745 #[test]
1746 fn test_one_or_many_collapse_single_element() {
1747 let aud = OneOrMany::from_vec(vec!["only-one".into()]);
1748 assert_eq!(aud, OneOrMany::One("only-one".into()));
1749 }
1750
1751 #[test]
1757 fn terminal_actor_resolves_the_deepest_delegation_hop() {
1758 let inner = ActClaim {
1759 sub: "service:worker".into(),
1760 clearance: None,
1761 act: None,
1762 };
1763 let outer = ActClaim {
1764 sub: "service:mcp".into(),
1765 clearance: None,
1766 act: Some(Box::new(inner)),
1767 };
1768 let c = Claims::new("user:alice".into(), 1000, 1030).with_actor(Some(outer));
1769 assert_eq!(c.terminal_actor(), Some("service:worker"));
1770
1771 let plain = Claims::new("user:alice".into(), 1000, 1030);
1773 assert_eq!(plain.terminal_actor(), None);
1774 }
1775
1776 #[test]
1777 fn federate_generation_is_signed_jwt_only_and_canonical() {
1778 let original = [0x42; 32];
1779 let claims = Claims::new("alice".into(), 1, 2).with_session_authority_generation(original);
1780 assert_eq!(
1781 claims.session_authority_generation().unwrap(),
1782 Some(original)
1783 );
1784 let json = serde_json::to_vec(&claims).unwrap();
1785 let decoded: Claims = serde_json::from_slice(&json).unwrap();
1786 assert_eq!(
1787 decoded.session_authority_generation().unwrap(),
1788 Some(original)
1789 );
1790 let mut malformed = decoded.clone();
1791 for bad in [
1792 "",
1793 "A",
1794 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
1795 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+",
1796 ] {
1797 malformed.hs_session_authority_generation = Some(bad.into());
1798 assert!(
1799 malformed.session_authority_generation().is_err(),
1800 "accepted {bad:?}"
1801 );
1802 }
1803 assert!(Claims::new("alice".into(), 1, 2)
1804 .session_authority_generation()
1805 .unwrap()
1806 .is_none());
1807 }
1808
1809 #[test]
1810 fn federate_signer_inventory_is_signed_jwt_only_and_canonical() {
1811 let original = [0x24; 32];
1812 let claims = Claims::new("alice".into(), 1, 2).with_federate_signer_inventory(original);
1813 assert_eq!(claims.federate_signer_inventory().unwrap(), Some(original));
1814 let json = serde_json::to_vec(&claims).unwrap();
1815 let decoded: Claims = serde_json::from_slice(&json).unwrap();
1816 assert_eq!(decoded.federate_signer_inventory().unwrap(), Some(original));
1817 let mut malformed = decoded.clone();
1818 for bad in [
1819 "",
1820 "A",
1821 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
1822 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+",
1823 ] {
1824 malformed.hs_signer_inventory_v1 = Some(bad.into());
1825 assert!(
1826 malformed.federate_signer_inventory().is_err(),
1827 "accepted {bad:?}"
1828 );
1829 }
1830 assert!(Claims::new("alice".into(), 1, 2)
1831 .federate_signer_inventory()
1832 .unwrap()
1833 .is_none());
1834 }
1835}