1use std::sync::Arc;
59
60use anyhow::Context as _;
61use ed25519_dalek::SigningKey;
62use hyprstream_rpc::auth::mac::{
63 MacDecision, MacDenyReason, RpcObjectLabelResolver, SecurityContext, SecurityLabel,
64};
65use hyprstream_vfs::Subject;
66
67use crate::mac::audit::{AuditRecord, AuditSink, DecisionReason};
68use crate::mac::te::{Decision, ObjectType, SubjectType};
69use crate::storage::cas::{DedupDomain, TrustBoundary};
70
71const CAS_SUBJECT_TYPE: SubjectType = SubjectType(u32::MAX - 3);
74const CAS_OBJECT_TYPE: ObjectType = ObjectType(u32::MAX - 3);
75const CAS_SERVICE_DOMAIN: &str = "cas";
76
77pub fn domain_label(domain: &DedupDomain) -> SecurityLabel {
106 use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level};
107 let level = match domain.trust_boundary {
108 TrustBoundary::Local => Level::Internal,
109 TrustBoundary::SharedRemote => Level::Confidential,
110 };
111 SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
112}
113
114pub fn seal_label(domain: &DedupDomain, hint: Option<SecurityLabel>) -> SecurityLabel {
128 let base = domain_label(domain);
129 match hint {
130 Some(h) => base.join(&h),
131 None => base,
132 }
133}
134
135#[derive(Debug, Clone, Copy)]
145pub struct CasObjectLabelResolver {
146 label: Option<SecurityLabel>,
147}
148
149impl CasObjectLabelResolver {
150 pub const fn new(label: Option<SecurityLabel>) -> Self {
152 Self { label }
153 }
154
155 pub fn from_domain(domain: &DedupDomain) -> Self {
157 Self::new(Some(domain_label(domain)))
158 }
159}
160
161impl RpcObjectLabelResolver for CasObjectLabelResolver {
162 fn resolve(&self, service_domain: &str, method: Option<&[u16]>) -> Option<SecurityLabel> {
163 if service_domain == CAS_SERVICE_DOMAIN && method.is_none() {
164 self.label
165 } else {
166 None
167 }
168 }
169}
170
171#[async_trait::async_trait]
194pub trait CasClearanceSource: Send + Sync {
195 async fn clearance_for(
197 &self,
198 subject_id: &str,
199 verified_tenant: Option<&str>,
200 ) -> Option<SecurityContext>;
201}
202
203pub struct DenyAllClearanceSource;
208
209#[async_trait::async_trait]
210impl CasClearanceSource for DenyAllClearanceSource {
211 async fn clearance_for(
212 &self,
213 _subject_id: &str,
214 _verified_tenant: Option<&str>,
215 ) -> Option<SecurityContext> {
216 None
217 }
218}
219
220#[derive(Debug, Default, Clone, Copy)]
223pub struct VerifiedClaimsCasClearanceSource;
224
225#[async_trait::async_trait]
226impl CasClearanceSource for VerifiedClaimsCasClearanceSource {
227 async fn clearance_for(
228 &self,
229 subject_id: &str,
230 verified_tenant: Option<&str>,
231 ) -> Option<SecurityContext> {
232 hyprstream_rpc::auth::mac::subject_context(
233 &Subject::new(subject_id.to_owned()),
234 verified_tenant,
235 )
236 .await
237 }
238}
239
240pub struct CasPep {
255 clearance_source: Arc<dyn CasClearanceSource>,
256 sink: Arc<dyn AuditSink>,
257}
258
259impl CasPep {
260 pub fn new(clearance_source: Arc<dyn CasClearanceSource>, sink: Arc<dyn AuditSink>) -> Self {
262 Self {
263 clearance_source,
264 sink,
265 }
266 }
267
268 pub fn fail_closed() -> Self {
272 Self::new(
273 Arc::new(DenyAllClearanceSource),
274 Arc::new(crate::mac::audit::NullAuditSink),
275 )
276 }
277
278 #[must_use]
287 pub async fn check_read(
288 &self,
289 subject_id: &str,
290 verified_tenant: Option<&str>,
291 resolver: &dyn RpcObjectLabelResolver,
292 ) -> MacDecision {
293 self.check(
294 subject_id,
295 verified_tenant,
296 resolver.resolve(CAS_SERVICE_DOMAIN, None),
297 )
298 .await
299 }
300
301 async fn check(
303 &self,
304 subject_id: &str,
305 verified_tenant: Option<&str>,
306 label: Option<SecurityLabel>,
307 ) -> MacDecision {
308 let Some(ctx) = self
309 .clearance_source
310 .clearance_for(subject_id, verified_tenant)
311 .await
312 else {
313 return self.audit(
314 subject_id,
315 verified_tenant,
316 None,
317 label,
318 MacDecision::Deny(MacDenyReason::NoClearance),
319 );
320 };
321
322 let Some(label) = label else {
323 return self.audit(
324 subject_id,
325 verified_tenant,
326 Some(&ctx),
327 None,
328 MacDecision::Deny(MacDenyReason::UnlabeledObject),
329 );
330 };
331
332 let decision = if ctx.can_access(&label) {
333 MacDecision::Permit
334 } else {
335 MacDecision::Deny(MacDenyReason::FloorDeny)
336 };
337 self.audit(
338 subject_id,
339 verified_tenant,
340 Some(&ctx),
341 Some(label),
342 decision,
343 )
344 }
345
346 fn audit(
347 &self,
348 subject_id: &str,
349 verified_tenant: Option<&str>,
350 ctx: Option<&SecurityContext>,
351 label: Option<SecurityLabel>,
352 decision: MacDecision,
353 ) -> MacDecision {
354 use std::time::{SystemTime, UNIX_EPOCH};
355
356 let (audit_decision, reason) = match decision {
357 MacDecision::Permit => (Decision::Permit, DecisionReason::Permit),
358 MacDecision::Deny(MacDenyReason::NoClearance) => {
359 (Decision::Deny, DecisionReason::NoClearance)
360 }
361 MacDecision::Deny(MacDenyReason::UnlabeledObject) => {
362 (Decision::Deny, DecisionReason::UnlabeledObject)
363 }
364 MacDecision::Deny(
365 MacDenyReason::FloorDeny
366 | MacDenyReason::NoPepInstalled
367 | MacDenyReason::StaleAuthority,
368 ) => (Decision::Deny, DecisionReason::FloorDeny),
369 };
370 let policy = crate::mac::compiled_policy();
371 let generation = policy.as_ref().map_or(0, |p| p.generation);
372 let policy_hash = policy.as_ref().and_then(|p| p.policy_hash().ok());
373 let record = AuditRecord {
374 seq: 0,
375 prev_hash: [0; 32],
376 ts_unix_nanos: SystemTime::now()
377 .duration_since(UNIX_EPOCH)
378 .map_or(0, |d| d.as_nanos()),
379 decision: audit_decision,
380 generation,
381 policy_hash,
382 subject_type: CAS_SUBJECT_TYPE,
383 subject_clearance: ctx
384 .map(|c| *c.clearance())
385 .unwrap_or_else(SecurityLabel::bottom),
386 on_behalf_of: None,
387 object_type: CAS_OBJECT_TYPE,
388 object_label: label.unwrap_or_else(SecurityLabel::bottom),
389 action: crate::mac::te::Action::from_scope_action(crate::mac::te::ScopeAction::Query),
390 reason,
391 subject_id: Some(subject_id.to_owned()),
392 object_id: Some(match verified_tenant {
393 Some(tenant) => format!("{tenant}/{CAS_SERVICE_DOMAIN}"),
394 None => CAS_SERVICE_DOMAIN.to_owned(),
395 }),
396 };
397
398 match self.sink.record(&record) {
399 Ok(()) => decision,
400 Err(error) => {
401 let deny_record = AuditRecord {
402 decision: Decision::Deny,
403 reason: DecisionReason::AuditFailClosed,
404 ..record
405 };
406 let _ = self.sink.record(&deny_record);
407 tracing::error!(
408 target: "hyprstream.mac.cas_pep",
409 %error,
410 reason = DecisionReason::AuditFailClosed.as_str(),
411 "CAS PEP decision could not be durably audited; enforcing deny"
412 );
413 MacDecision::Deny(MacDenyReason::FloorDeny)
417 }
418 }
419 }
420}
421
422pub struct MacCasAuthorizer {
436 pep: Arc<CasPep>,
437}
438
439impl MacCasAuthorizer {
440 pub fn new(pep: Arc<CasPep>) -> Self {
442 Self { pep }
443 }
444
445 pub fn fail_closed() -> Self {
449 Self::new(Arc::new(CasPep::fail_closed()))
450 }
451}
452
453#[async_trait::async_trait]
454impl crate::storage::cas::CasMountAuthorizer for MacCasAuthorizer {
455 async fn authorize(
456 &self,
457 caller: &Subject,
458 request: crate::storage::cas::CasMountAuthzRequest<'_>,
459 ) -> Result<(), hyprstream_vfs::MountError> {
460 let resolver = CasObjectLabelResolver::from_domain(request.domain);
461 let decision = self
462 .pep
463 .check_read(&caller.to_string(), request.verified_tenant, &resolver)
464 .await;
465 if decision.is_permit() {
466 Ok(())
467 } else {
468 Err(hyprstream_vfs::MountError::PermissionDenied(format!(
469 "CAS MAC {} {:?} {} denied for {}: {decision:?} (#1270)",
470 request.operation, request.kind, request.address, caller,
471 )))
472 }
473 }
474}
475
476pub async fn production_cas_pep(
480 signing_key: SigningKey,
481 oauth: &crate::config::OAuthConfig,
482 audit_stream: &str,
483) -> anyhow::Result<Arc<CasPep>> {
484 anyhow::ensure!(
485 !audit_stream.is_empty()
486 && audit_stream
487 .bytes()
488 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'),
489 "invalid CAS MAC audit stream name"
490 );
491 let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
492 let ml_dsa_store = crate::auth::key_rotation::global_ml_dsa_key_store(&secrets_dir, oauth);
493 let signer = crate::mac::audit::cose::OwnedCoseAuditSigner::new(
494 Arc::new(signing_key),
495 ml_dsa_store.active_key().await,
496 hyprstream_rpc::envelope::mandatory_envelope_policy(),
497 );
498 anyhow::ensure!(
499 signer.can_sign(),
500 "CAS MAC PEP audit signer unavailable under mandatory Hybrid policy"
501 );
502 let audit_store = crate::mac::audit::WalAuditStore::open(
503 secrets_dir.join("mac-audit").join(audit_stream),
504 signer,
505 )
506 .context("open CAS MAC audit store")?;
507 Ok(Arc::new(CasPep::new(
508 Arc::new(VerifiedClaimsCasClearanceSource),
509 Arc::new(audit_store),
510 )))
511}
512
513#[cfg(test)]
518#[allow(clippy::unwrap_used, clippy::expect_used)]
519mod tests {
520 use parking_lot::Mutex;
521
522 use hyprstream_rpc::auth::mac::{
523 Assurance, CompartmentSet, Level, SecurityContext, SecurityLabel, VerifiedKeyMaterial,
524 };
525
526 use super::*;
527 use crate::mac::audit::{AuditError, AuditRecord};
528 use crate::storage::cas::{CasMountAuthorizer, CasMountAuthzRequest, CasMountObjectKind};
529 use crate::storage::cas::{DedupDomain, TrustBoundary};
530
531 #[test]
534 fn local_domain_label_is_internal() {
535 let label = domain_label(&DedupDomain::local_default());
536 assert_eq!(label.level, Level::Internal);
537 assert_eq!(label.assurance, Assurance::Classical);
538 assert!(label.compartments.is_empty());
539 }
540
541 #[test]
542 fn shared_remote_domain_label_is_confidential() {
543 let domain = DedupDomain {
544 trust_boundary: TrustBoundary::SharedRemote,
545 ..DedupDomain::local_default()
546 };
547 let label = domain_label(&domain);
548 assert_eq!(label.level, Level::Confidential);
549 }
550
551 #[test]
554 fn seal_label_without_hint_is_domain_label() {
555 let domain = DedupDomain::local_default();
556 assert_eq!(seal_label(&domain, None), domain_label(&domain));
557 }
558
559 #[test]
560 fn seal_label_join_is_restrict_only() {
561 let domain = DedupDomain::local_default();
563 let hint = SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY);
564 let effective = seal_label(&domain, Some(hint));
565 assert_eq!(effective.level, Level::Secret);
566 }
567
568 #[test]
569 fn seal_label_hint_cannot_lower_below_domain() {
570 let domain = DedupDomain {
573 trust_boundary: TrustBoundary::SharedRemote,
574 ..DedupDomain::local_default()
575 };
576 let hint = SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
577 let effective = seal_label(&domain, Some(hint));
578 assert_eq!(
579 effective.level,
580 Level::Confidential,
581 "seal label must never be less restrictive than the domain floor"
582 );
583 }
584
585 #[test]
586 fn cas_resolver_uses_canonical_service_and_non_browser_method() {
587 let resolver = CasObjectLabelResolver::from_domain(&DedupDomain::local_default());
588 assert!(resolver.resolve(CAS_SERVICE_DOMAIN, None).is_some());
589 assert!(resolver.resolve("registry", None).is_none());
590 assert!(resolver
591 .resolve(CAS_SERVICE_DOMAIN, Some(&[1][..]))
592 .is_none());
593 }
594
595 #[tokio::test]
598 async fn deny_all_clearance_source_returns_none() {
599 let src = DenyAllClearanceSource;
600 assert!(src
601 .clearance_for("anyone", Some("tenant-a"))
602 .await
603 .is_none());
604 assert!(src.clearance_for("admin", None).await.is_none());
605 }
606
607 #[tokio::test]
610 async fn fail_closed_pep_denies_every_read() {
611 let pep = CasPep::fail_closed();
612 let label = domain_label(&DedupDomain::local_default());
613 let labeled = CasObjectLabelResolver::new(Some(label));
614 assert_eq!(
615 pep.check_read("any-subject", Some("tenant-a"), &labeled)
616 .await,
617 MacDecision::Deny(MacDenyReason::NoClearance)
618 );
619 let unlabeled = CasObjectLabelResolver::new(None);
621 assert_eq!(
622 pep.check_read("any-subject", Some("tenant-a"), &unlabeled)
623 .await,
624 MacDecision::Deny(MacDenyReason::NoClearance)
625 );
626 }
627
628 struct FixtureClearance {
631 subject: String,
632 ctx: SecurityContext,
633 }
634
635 #[async_trait::async_trait]
636 impl CasClearanceSource for FixtureClearance {
637 async fn clearance_for(
638 &self,
639 subject_id: &str,
640 _verified_tenant: Option<&str>,
641 ) -> Option<SecurityContext> {
642 if subject_id == self.subject {
643 Some(self.ctx.clone())
644 } else {
645 None
646 }
647 }
648 }
649
650 fn ctx(level: Level) -> SecurityContext {
651 SecurityContext::from_clearance(
652 SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY),
653 VerifiedKeyMaterial::Classical,
654 )
655 }
656
657 struct TenantClearance;
658
659 #[async_trait::async_trait]
660 impl CasClearanceSource for TenantClearance {
661 async fn clearance_for(
662 &self,
663 subject_id: &str,
664 verified_tenant: Option<&str>,
665 ) -> Option<SecurityContext> {
666 (subject_id == "alice" && verified_tenant == Some("tenant-a"))
667 .then(|| ctx(Level::Secret))
668 }
669 }
670
671 async fn check(pep: &CasPep, subject_id: &str, label: Option<SecurityLabel>) -> MacDecision {
672 let resolver = CasObjectLabelResolver::new(label);
673 pep.check_read(subject_id, Some("tenant-a"), &resolver)
674 .await
675 }
676
677 #[derive(Default)]
678 struct SpySink {
679 records: Mutex<Vec<AuditRecord>>,
680 }
681
682 impl AuditSink for SpySink {
683 fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
684 self.records.lock().push(record.clone());
685 Ok(())
686 }
687 }
688
689 #[tokio::test]
690 async fn pep_permits_when_clearance_dominates_label() {
691 let sink = Arc::new(SpySink::default());
692 let pep = CasPep::new(
693 Arc::new(FixtureClearance {
694 subject: "secret-user".to_owned(),
695 ctx: ctx(Level::Secret),
696 }),
697 sink.clone(),
698 );
699 let label = domain_label(&DedupDomain::local_default()); assert_eq!(
701 check(&pep, "secret-user", Some(label)).await,
702 MacDecision::Permit
703 );
704
705 let records = sink.records.lock();
706 assert_eq!(records.len(), 1);
707 assert_eq!(records[0].decision, Decision::Permit);
708 }
709
710 #[tokio::test]
711 async fn pep_threads_verified_tenant_to_clearance_source() {
712 let pep = CasPep::new(Arc::new(TenantClearance), Arc::new(SpySink::default()));
713 let resolver = CasObjectLabelResolver::from_domain(&DedupDomain::local_default());
714 assert_eq!(
715 pep.check_read("alice", Some("tenant-a"), &resolver).await,
716 MacDecision::Permit
717 );
718 assert_eq!(
719 pep.check_read("alice", None, &resolver).await,
720 MacDecision::Deny(MacDenyReason::NoClearance)
721 );
722 }
723
724 #[tokio::test]
725 async fn pep_denies_when_clearance_insufficient() {
726 let sink = Arc::new(SpySink::default());
727 let pep = CasPep::new(
728 Arc::new(FixtureClearance {
729 subject: "public-user".to_owned(),
730 ctx: ctx(Level::Public),
731 }),
732 sink.clone(),
733 );
734 let label = domain_label(&DedupDomain::local_default()); assert_eq!(
736 check(&pep, "public-user", Some(label)).await,
737 MacDecision::Deny(MacDenyReason::FloorDeny)
738 );
739
740 let records = sink.records.lock();
741 assert_eq!(records[0].decision, Decision::Deny);
742 assert_eq!(records[0].reason, DecisionReason::FloorDeny);
743 assert_eq!(records[0].subject_id.as_deref(), Some("public-user"));
744 assert_eq!(records[0].object_id.as_deref(), Some("tenant-a/cas"));
745 }
746
747 #[tokio::test]
748 async fn pep_denies_unresolvable_subject() {
749 let sink = Arc::new(SpySink::default());
750 let pep = CasPep::new(
751 Arc::new(FixtureClearance {
752 subject: "known".to_owned(),
753 ctx: ctx(Level::Secret),
754 }),
755 sink.clone(),
756 );
757 let label = domain_label(&DedupDomain::local_default());
758 assert_eq!(
759 check(&pep, "unknown", Some(label)).await,
760 MacDecision::Deny(MacDenyReason::NoClearance)
761 );
762
763 let records = sink.records.lock();
764 assert_eq!(records[0].reason, DecisionReason::NoClearance);
765 }
766
767 #[tokio::test]
768 async fn pep_denies_unlabeled_object_even_with_clearance() {
769 let sink = Arc::new(SpySink::default());
770 let pep = CasPep::new(
771 Arc::new(FixtureClearance {
772 subject: "admin".to_owned(),
773 ctx: ctx(Level::Secret),
774 }),
775 sink.clone(),
776 );
777 assert_eq!(
778 check(&pep, "admin", None).await,
779 MacDecision::Deny(MacDenyReason::UnlabeledObject)
780 );
781
782 let records = sink.records.lock();
783 assert_eq!(records[0].reason, DecisionReason::UnlabeledObject);
784 }
785
786 #[tokio::test]
789 async fn mac_cas_authorizer_denies_with_fail_closed_pep() {
790 let authz = MacCasAuthorizer::fail_closed();
791 let domain = DedupDomain::local_default();
792 let req = CasMountAuthzRequest {
793 kind: CasMountObjectKind::Xorb,
794 address: "deadbeef",
795 domain: &domain,
796 verified_tenant: Some("tenant-a"),
797 operation: "read",
798 requested_label: None,
799 };
800 let subject = Subject::new("user");
801 assert!(authz.authorize(&subject, req).await.is_err());
802 }
803
804 #[tokio::test]
805 async fn mac_cas_authorizer_permits_with_dominating_clearance() {
806 let sink = Arc::new(SpySink::default());
807 let pep = Arc::new(CasPep::new(
808 Arc::new(FixtureClearance {
809 subject: "secret-user".to_owned(),
810 ctx: ctx(Level::Secret),
811 }),
812 sink,
813 ));
814 let authz = MacCasAuthorizer::new(pep);
815 let domain = DedupDomain::local_default();
816 let req = CasMountAuthzRequest {
817 kind: CasMountObjectKind::Xorb,
818 address: "deadbeef",
819 domain: &domain,
820 verified_tenant: Some("tenant-a"),
821 operation: "read",
822 requested_label: None,
823 };
824 let subject = Subject::new("secret-user");
825 assert!(authz.authorize(&subject, req).await.is_ok());
826 }
827
828 #[tokio::test]
829 async fn mac_cas_authorizer_uses_verified_http_tenant_for_clearance() {
830 let pep = Arc::new(CasPep::new(
831 Arc::new(TenantClearance),
832 Arc::new(SpySink::default()),
833 ));
834 let authz = MacCasAuthorizer::new(pep);
835 let domain = DedupDomain::local_default();
836 let subject = Subject::new("alice");
837
838 let tenant_a = CasMountAuthzRequest {
839 kind: CasMountObjectKind::Xorb,
840 address: "deadbeef",
841 domain: &domain,
842 verified_tenant: Some("tenant-a"),
843 operation: "read",
844 requested_label: None,
845 };
846 assert!(authz.authorize(&subject, tenant_a).await.is_ok());
847
848 let tenant_b = CasMountAuthzRequest {
849 kind: CasMountObjectKind::Xorb,
850 address: "deadbeef",
851 domain: &domain,
852 verified_tenant: Some("tenant-b"),
853 operation: "read",
854 requested_label: None,
855 };
856 assert!(authz.authorize(&subject, tenant_b).await.is_err());
857 }
858
859 #[tokio::test]
860 async fn mac_cas_authorizer_uses_domain_for_label() {
861 let sink = Arc::new(SpySink::default());
864 let pep = Arc::new(CasPep::new(
865 Arc::new(FixtureClearance {
866 subject: "public-user".to_owned(),
867 ctx: ctx(Level::Public),
868 }),
869 sink,
870 ));
871 let authz = MacCasAuthorizer::new(pep);
872 let domain = DedupDomain {
873 trust_boundary: TrustBoundary::SharedRemote,
874 ..DedupDomain::local_default()
875 };
876 let req = CasMountAuthzRequest {
877 kind: CasMountObjectKind::Object,
878 address: "some-addr",
879 domain: &domain,
880 verified_tenant: Some("tenant-a"),
881 operation: "open",
882 requested_label: None,
883 };
884 let subject = Subject::new("public-user");
885 assert!(
886 authz.authorize(&subject, req).await.is_err(),
887 "Public clearance must not read Confidential (shared-remote) content"
888 );
889 }
890}