1use std::collections::{BTreeSet, HashMap};
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::sync::OnceLock;
14
15use parking_lot::RwLock;
16
17use super::{
18 Assurance, CompartmentSet, GenesisReport, Level, SecurityContext, SecurityLabel,
19 VerifiedKeyMaterial,
20};
21use crate::envelope::Subject;
22use crate::service::EnvelopeContext;
23
24const FLOOR_ONLY: u8 = 0;
25const IDENTITY_AWARE: u8 = 1;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum MacActivationMode {
30 FloorOnly,
32 IdentityAware,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct MacActivationError {
39 pub unlabeled: usize,
40 pub ill_formed: usize,
41 pub missing_gates: Vec<&'static str>,
42 pub blocked_transports: Vec<&'static str>,
43}
44
45impl std::fmt::Display for MacActivationError {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 write!(
48 f,
49 "MAC identity-aware widening refused: readiness evidence incomplete \
50 (unlabeled={}, ill_formed={}, missing_gates={:?}, blocked_transports={:?})",
51 self.unlabeled, self.ill_formed, self.missing_gates, self.blocked_transports
52 )
53 }
54}
55
56impl std::error::Error for MacActivationError {}
57
58pub struct MacActivationEvidence<'a> {
65 pub genesis: &'a GenesisReport,
66 pub mediation_integrity_g2: bool,
67 pub denial_handling_g4: bool,
68 pub observability_g5: bool,
69 pub runbook_signoff_g6: bool,
70 pub revocation_reload_g7: bool,
71}
72
73impl MacActivationEvidence<'_> {
74 fn missing_gates(&self) -> Vec<&'static str> {
75 let mut missing = Vec::new();
76 if !self.genesis.is_complete() {
77 missing.push("G1");
78 }
79 if !self.mediation_integrity_g2 {
80 missing.push("G2");
81 }
82 if !self.denial_handling_g4 {
83 missing.push("G4");
84 }
85 if !self.observability_g5 {
86 missing.push("G5");
87 }
88 if !self.runbook_signoff_g6 {
89 missing.push("G6");
90 }
91 if !self.revocation_reload_g7 {
92 missing.push("G7");
93 }
94 missing
95 }
96}
97
98#[derive(Debug)]
100pub struct MacActivationControl {
101 mode: AtomicU8,
102 unverified_attach_transports: RwLock<BTreeSet<&'static str>>,
103}
104
105impl Default for MacActivationControl {
106 fn default() -> Self {
107 Self {
108 mode: AtomicU8::new(IDENTITY_AWARE),
113 unverified_attach_transports: RwLock::new(BTreeSet::new()),
114 }
115 }
116}
117
118impl MacActivationControl {
119 #[must_use]
121 pub fn mode(&self) -> MacActivationMode {
122 if self.mode.load(Ordering::Acquire) == IDENTITY_AWARE {
123 MacActivationMode::IdentityAware
124 } else {
125 MacActivationMode::FloorOnly
126 }
127 }
128
129 pub fn widen_identity_aware(
132 &self,
133 evidence: &MacActivationEvidence<'_>,
134 ) -> Result<(), MacActivationError> {
135 let blocked_transports = self.blocked_transports();
136 let mut missing_gates = evidence.missing_gates();
137 if !blocked_transports.is_empty() && !missing_gates.contains(&"G2") {
138 missing_gates.push("G2");
139 }
140 if !missing_gates.is_empty() {
141 return Err(MacActivationError {
142 unlabeled: evidence.genesis.unlabeled.len(),
143 ill_formed: evidence.genesis.ill_formed.len(),
144 missing_gates,
145 blocked_transports,
146 });
147 }
148 flush_verified_subject_cache_generation();
151 self.mode.store(IDENTITY_AWARE, Ordering::Release);
152 Ok(())
153 }
154
155 pub fn narrow_to_floor(&self) {
158 self.mode.store(FLOOR_ONLY, Ordering::Release);
159 flush_verified_subject_cache_generation();
160 }
161
162 #[must_use]
164 pub fn select_context(&self, verified: Option<SecurityContext>) -> Option<SecurityContext> {
165 match self.mode() {
166 MacActivationMode::FloorOnly => Some(anonymous_floor()),
167 MacActivationMode::IdentityAware => verified,
168 }
169 }
170
171 pub fn block_unverified_attach_transport(&self, transport: &'static str) {
178 self.unverified_attach_transports.write().insert(transport);
179 self.narrow_to_floor();
180 }
181
182 #[must_use]
184 pub fn blocked_transports(&self) -> Vec<&'static str> {
185 self.unverified_attach_transports
186 .read()
187 .iter()
188 .copied()
189 .collect()
190 }
191}
192
193#[must_use]
195pub fn global_mac_activation_control() -> &'static MacActivationControl {
196 static CONTROL: OnceLock<MacActivationControl> = OnceLock::new();
197 CONTROL.get_or_init(MacActivationControl::default)
198}
199
200pub fn block_identity_widening_for_unverified_attach_transport(transport: &'static str) {
205 global_mac_activation_control().block_unverified_attach_transport(transport);
206}
207
208#[must_use]
210pub fn anonymous_floor() -> SecurityContext {
211 SecurityContext::from_clearance(
212 SecurityLabel::new(Level::Public, Assurance::Unverified, CompartmentSet::EMPTY),
213 VerifiedKeyMaterial::Unverified,
214 )
215}
216
217#[derive(Clone)]
218struct VerifiedSubjectEntry {
219 context: SecurityContext,
220 tenant: Option<String>,
221 expires_at: i64,
222 credential_id: Option<crate::auth::CredentialId>,
226 session_key: Option<crate::auth::SessionKey>,
230 generation: u64,
231}
232
233#[derive(Default)]
234struct VerifiedSubjectCache {
235 generation: u64,
236 subjects: HashMap<String, VerifiedSubjectEntry>,
237}
238
239fn verified_subjects() -> &'static RwLock<VerifiedSubjectCache> {
240 static SUBJECTS: OnceLock<RwLock<VerifiedSubjectCache>> = OnceLock::new();
241 SUBJECTS.get_or_init(|| RwLock::new(VerifiedSubjectCache::default()))
242}
243
244pub fn revoke_verified_subject_credential(id: &crate::auth::CredentialId) -> usize {
252 let mut cache = verified_subjects().write();
253 let before = cache.subjects.len();
254 cache
255 .subjects
256 .retain(|_, entry| entry.credential_id.as_ref() != Some(id));
257 before.saturating_sub(cache.subjects.len())
258}
259
260pub fn flush_verified_subject_cache_generation() -> u64 {
265 let mut cache = verified_subjects().write();
266 cache.generation = cache.generation.saturating_add(1);
267 cache.subjects.clear();
268 cache.generation
269}
270
271pub fn remember_verified_subject(ctx: &EnvelopeContext) {
280 let Some(claims) = ctx.claims() else {
281 return;
282 };
283 let subject = ctx.subject();
284 remember_verified_claims(
285 &subject,
286 claims,
287 ctx.verified_key_material(),
288 ctx.verified_tenant(),
289 );
290}
291
292pub fn remember_verified_claims(
299 subject: &Subject,
300 claims: &crate::auth::Claims,
301 key_material: VerifiedKeyMaterial,
302 verified_tenant: Option<&str>,
303) {
304 use super::SubjectContextClaims as _;
305
306 let Some(name) = subject.name() else {
307 return;
308 };
309 if claims.exp <= chrono::Utc::now().timestamp() {
310 return;
311 }
312 if claims.sub != name {
313 return;
314 }
315 let Some(context) = claims.security_context(key_material) else {
316 return;
317 };
318 let credential_id = claims
322 .jti
323 .as_ref()
324 .map(|jti| crate::auth::CredentialId::jwt(&claims.iss, jti));
325 let Ok(session_key) = claims.session_key() else {
329 return;
330 };
331 insert_verified_subject_entry(
332 name,
333 context,
334 verified_tenant,
335 claims.exp,
336 credential_id,
337 session_key,
338 );
339}
340
341pub fn remember_verified_claims_with_credential(
357 subject: &Subject,
358 claims: &crate::auth::Claims,
359 key_material: VerifiedKeyMaterial,
360 verified_tenant: Option<&str>,
361 credential_id: crate::auth::CredentialId,
362) {
363 use super::SubjectContextClaims as _;
364
365 let Some(name) = subject.name() else {
366 return;
367 };
368 if claims.exp <= chrono::Utc::now().timestamp() {
369 return;
370 }
371 if claims.sub != name {
372 return;
373 }
374 let Some(context) = claims.security_context(key_material) else {
375 return;
376 };
377 if !credential_id.is_valid() || credential_id.issuer != claims.iss {
381 return;
382 }
383 let Ok(session_key) = claims.session_key() else {
387 return;
388 };
389 insert_verified_subject_entry(
390 name,
391 context,
392 verified_tenant,
393 claims.exp,
394 Some(credential_id),
395 session_key,
396 );
397}
398
399fn insert_verified_subject_entry(
400 name: &str,
401 context: SecurityContext,
402 verified_tenant: Option<&str>,
403 expires_at: i64,
404 credential_id: Option<crate::auth::CredentialId>,
405 session_key: Option<crate::auth::SessionKey>,
406) {
407 let mut cache = verified_subjects().write();
408 let generation = cache.generation;
409 cache.subjects.insert(
410 name.to_owned(),
411 VerifiedSubjectEntry {
412 context,
413 tenant: verified_tenant.map(str::to_owned),
414 expires_at,
415 credential_id,
416 session_key,
417 generation,
418 },
419 );
420}
421
422pub async fn subject_context(
439 subject: &Subject,
440 verified_tenant: Option<&str>,
441) -> Option<SecurityContext> {
442 subject_context_with(
443 crate::auth::global_credential_revocation_store().map(std::convert::AsRef::as_ref),
444 crate::auth::global_session_registry().map(std::convert::AsRef::as_ref),
445 subject,
446 verified_tenant,
447 )
448 .await
449}
450
451pub async fn subject_context_with(
455 store: Option<&dyn crate::auth::CredentialRevocationStore>,
456 session_registry: Option<&dyn crate::auth::SessionRegistry>,
457 subject: &Subject,
458 verified_tenant: Option<&str>,
459) -> Option<SecurityContext> {
460 let verified = match subject.name() {
461 Some(name) => {
462 let entry = {
465 let now = chrono::Utc::now().timestamp();
466 let mut cache = verified_subjects().write();
467 match cache.subjects.get(name) {
468 Some(entry) => {
469 let entry = entry.clone();
470 if entry.generation != cache.generation || entry.expires_at <= now {
471 cache.subjects.remove(name);
472 None
473 } else if let Some(expected) = verified_tenant {
474 if entry.tenant.as_deref() != Some(expected) {
475 None
476 } else {
477 Some(entry)
478 }
479 } else {
480 Some(entry)
481 }
482 }
483 None => None,
484 }
485 };
486 match entry {
487 Some(entry) => {
488 if let Some(ref credential_id) = entry.credential_id {
491 let revoked = match store {
492 Some(store) => store.is_revoked(credential_id).await,
493 None => true,
495 };
496 if revoked {
497 revoke_verified_subject_credential(credential_id);
498 return global_mac_activation_control().select_context(None);
499 }
500 }
501 if let Some(ref session_key) = entry.session_key {
502 let session_revoked = match session_registry {
503 Some(registry) => registry.is_revoked(session_key).await,
504 None => true,
506 };
507 if session_revoked {
508 let mut cache = verified_subjects().write();
509 cache.subjects.remove(name);
510 return global_mac_activation_control().select_context(None);
511 }
512 }
513 Some(entry.context)
514 }
515 None => None,
516 }
517 }
518 None => None,
519 };
520 global_mac_activation_control().select_context(verified)
521}
522
523#[cfg(test)]
527pub(crate) static CACHE_TEST_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532
533 fn report(complete: bool) -> GenesisReport {
534 GenesisReport {
535 labeled: vec!["/".to_owned()],
536 unlabeled: if complete {
537 Vec::new()
538 } else {
539 vec!["/gap".to_owned()]
540 },
541 ill_formed: Vec::new(),
542 }
543 }
544
545 #[test]
546 fn widening_requires_complete_coverage_and_narrowing_is_always_available() {
547 let _guard = CACHE_TEST_LOCK.lock();
548 let control = MacActivationControl::default();
549 assert_eq!(control.mode(), MacActivationMode::IdentityAware);
550 control.narrow_to_floor();
551 let incomplete = report(false);
552 let mut evidence = MacActivationEvidence {
553 genesis: &incomplete,
554 mediation_integrity_g2: true,
555 denial_handling_g4: true,
556 observability_g5: true,
557 runbook_signoff_g6: true,
558 revocation_reload_g7: true,
559 };
560 assert!(control.widen_identity_aware(&evidence).is_err());
561 assert_eq!(control.mode(), MacActivationMode::FloorOnly);
562 let complete = report(true);
563 evidence.genesis = &complete;
564 assert!(control.widen_identity_aware(&evidence).is_ok());
565 assert_eq!(control.mode(), MacActivationMode::IdentityAware);
566 control.narrow_to_floor();
567 assert_eq!(control.mode(), MacActivationMode::FloorOnly);
568 }
569
570 #[test]
571 fn unverified_attach_transport_structurally_blocks_g2_widening() {
572 let _guard = CACHE_TEST_LOCK.lock();
573 let control = MacActivationControl::default();
574 control.narrow_to_floor();
575 control.block_unverified_attach_transport("worker-uds-vsock");
576
577 let complete = report(true);
578 let evidence = MacActivationEvidence {
579 genesis: &complete,
580 mediation_integrity_g2: true,
581 denial_handling_g4: true,
582 observability_g5: true,
583 runbook_signoff_g6: true,
584 revocation_reload_g7: true,
585 };
586 let Err(error) = control.widen_identity_aware(&evidence) else {
587 panic!("unverified worker transport must block identity-aware widening");
588 };
589 assert_eq!(control.mode(), MacActivationMode::FloorOnly);
590 assert!(error.missing_gates.contains(&"G2"));
591 assert_eq!(error.blocked_transports, vec!["worker-uds-vsock"]);
592 }
593
594 #[test]
595 fn jti_revocation_and_generation_rotation_evict_cached_subjects() {
596 let _guard = CACHE_TEST_LOCK.lock();
597 flush_verified_subject_cache_generation();
598
599 let now = chrono::Utc::now().timestamp();
600 let mut claims =
601 crate::auth::Claims::new("did:web:alice".to_owned(), now, now + 300).with_clearance(
602 SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY),
603 );
604 claims.iss = "https://local.example".to_owned();
605 claims.jti = Some("revocable-jti".to_owned());
606 let subject = Subject::new("did:web:alice");
607 remember_verified_claims(
608 &subject,
609 &claims,
610 VerifiedKeyMaterial::Classical,
611 Some("tenant-a"),
612 );
613
614 assert_eq!(verified_subjects().read().subjects.len(), 1);
615 let other_id = crate::auth::CredentialId::jwt("https://local.example", "other-jti");
616 let revocable_id = crate::auth::CredentialId::jwt("https://local.example", "revocable-jti");
617 let cross_issuer_id =
618 crate::auth::CredentialId::jwt("https://other.example", "revocable-jti");
619 assert_eq!(revoke_verified_subject_credential(&other_id), 0);
620 assert_eq!(
621 revoke_verified_subject_credential(&cross_issuer_id),
622 0,
623 "same jti from a different issuer must NOT evict"
624 );
625 assert_eq!(revoke_verified_subject_credential(&revocable_id), 1);
626 assert!(verified_subjects().read().subjects.is_empty());
627
628 remember_verified_claims(
629 &subject,
630 &claims,
631 VerifiedKeyMaterial::Classical,
632 Some("tenant-a"),
633 );
634 let old_generation = verified_subjects().read().generation;
635 let new_generation = flush_verified_subject_cache_generation();
636 assert!(new_generation >= old_generation);
637 assert!(verified_subjects().read().subjects.is_empty());
638 }
639
640 #[test]
646 fn ambiguous_session_claims_are_never_cached() {
647 let _guard = CACHE_TEST_LOCK.lock();
648 flush_verified_subject_cache_generation();
649 assert!(verified_subjects().read().subjects.is_empty());
650
651 let now = chrono::Utc::now().timestamp();
652 let clearance =
653 SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY);
654 let mut ambiguous = crate::auth::Claims::new("did:web:alice".to_owned(), now, now + 300)
655 .with_clearance(clearance)
656 .with_sid("oidc-1")
657 .with_workload_session_id("wl-1");
658 ambiguous.iss = "https://local.example".to_owned();
659 ambiguous.jti = Some("ambiguous-jti".to_owned());
660 remember_verified_claims(
661 &Subject::new("did:web:alice"),
662 &ambiguous,
663 VerifiedKeyMaterial::Classical,
664 Some("tenant-a"),
665 );
666 assert!(
667 verified_subjects().read().subjects.is_empty(),
668 "a credential with ambiguous session claims must never be cached"
669 );
670
671 let mut ok = crate::auth::Claims::new("did:web:alice".to_owned(), now, now + 300)
673 .with_clearance(clearance)
674 .with_sid("oidc-1");
675 ok.iss = "https://local.example".to_owned();
676 ok.jti = Some("ok-jti".to_owned());
677 remember_verified_claims(
678 &Subject::new("did:web:alice"),
679 &ok,
680 VerifiedKeyMaterial::Classical,
681 Some("tenant-a"),
682 );
683 assert_eq!(verified_subjects().read().subjects.len(), 1);
684 flush_verified_subject_cache_generation();
685 }
686}