1use std::collections::BTreeMap;
31use std::path::Path;
32use std::sync::Arc;
33
34use anyhow::{ensure, Context};
35use ed25519_dalek::SigningKey;
36use hyprstream_rpc::auth::ucan::approval::{ApprovalBinding, SignedApproval};
37use hyprstream_rpc::auth::ucan::token::{Did, Ucan, UcanPayload};
38use hyprstream_rpc::crypto::pq::MlDsaSigningKey;
39
40use crate::mac::compiled::cose::{HybridPolicySigner, HybridPolicyVerifier};
41use crate::mac::compiled::{
42 sign_policy, CompiledPolicy, PolicyApproval, PolicyDistError, PolicyLoader, SignedPolicy,
43};
44use crate::mac::compiler::{compile, PermissionMap};
45use crate::mac::install_compiled_policy;
46use crate::mac::lattice::{Lattice, LatticeVersion, SecurityLabel};
47use crate::mac::permission_map::ScopePermissionMap;
48use crate::mac::te::SubjectType;
49
50#[derive(Debug, thiserror::Error)]
53pub enum BootPolicyError {
54 #[error("policy bootload failed: {0}")]
56 Policy(#[from] PolicyDistError),
57}
58
59pub fn install_configured_boot_policy(
64 artifacts: &crate::config::MacBootPolicyConfig,
65 secrets_dir: &Path,
66 is_os_owned_bootstrap: bool,
67) -> anyhow::Result<Arc<CompiledPolicy>> {
68 ensure!(
69 is_os_owned_bootstrap,
70 "configured MAC boot policy requires OS-owned deployment trust"
71 );
72 let entries = crate::auth::identity_store::load_bootstrap_pubkeys_hybrid(secrets_dir)?;
73 crate::auth::identity_store::ensure_bootstrap_pubkeys_hybrid(&entries)?;
74 crate::auth::identity_store::ensure_bootstrap_pubkeys_enrolled(secrets_dir, &entries)?;
75 let authority = entries
76 .get("policy")
77 .context("no enrolled Policy authority in bootstrap roster")?;
78 let policy = Arc::new(load_boot_policy_files(artifacts, authority)?);
79 ensure!(
80 install_compiled_policy(policy.clone()),
81 "MAC policy already installed; configured policy cannot replace write-once seam"
82 );
83 Ok(policy)
84}
85
86fn load_boot_policy_files(
87 artifacts: &crate::config::MacBootPolicyConfig,
88 authority: &crate::auth::identity_store::BootstrapPubkey,
89) -> anyhow::Result<CompiledPolicy> {
90 let signed: SignedPolicy = serde_json::from_slice(
91 &std::fs::read(&artifacts.policy_path).context("cannot read signed MAC policy")?,
92 )
93 .context("invalid signed MAC policy JSON")?;
94 let approval: SignedApproval = serde_json::from_slice(
95 &std::fs::read(&artifacts.approval_path).context("cannot read signed MAC approval")?,
96 )
97 .context("invalid signed MAC approval JSON")?;
98 let policy = verify_boot_policy(&signed, &approval, authority)?;
99 let expected_hash: [u8; 32] = hex::decode(&artifacts.expected_policy_hash)
100 .context("expected MAC boot-policy hash must be hexadecimal")?
101 .try_into()
102 .map_err(|_| anyhow::anyhow!("expected MAC boot-policy hash must be exactly 32 bytes"))?;
103 check_reviewed_policy(&policy, artifacts.expected_generation, &expected_hash)
104 .context("configured MAC boot-policy rollback pin rejected")?;
105 Ok(policy)
106}
107
108fn verify_boot_policy(
109 signed: &SignedPolicy,
110 approval: &SignedApproval,
111 authority: &crate::auth::identity_store::BootstrapPubkey,
112) -> anyhow::Result<CompiledPolicy> {
113 let pq_vk = authority
114 .ml_dsa_65
115 .as_ref()
116 .context("Policy authority lacks ML-DSA-65 key")?;
117 let binding = approval
118 .verify(&authority.ed25519, pq_vk)
119 .context("MAC policy approval signature rejected")?;
120 let verifier = HybridPolicyVerifier {
121 ed_vk: &authority.ed25519,
122 pq_vk: Some(pq_vk),
123 require_pq: true,
124 };
125 let policy = PolicyLoader::new(verifier)
126 .with_approval(PolicyApproval::from_verified(binding))
127 .load(signed)?;
128 let (allow, escalate) = policy.matrix.sorted_rules();
129 ensure!(
130 allow.is_empty() && escalate.is_empty(),
131 "configured MAC boot policy is enrollment-only: TE allow and escalation rules must be empty"
132 );
133 Ok(policy)
134}
135
136pub fn hash_reviewed_boot_policy(
139 args: &crate::cli::commands::trust::HashMacBootPolicyArgs,
140) -> anyhow::Result<()> {
141 let (policy, grant) = read_reviewed_boot_inputs(&args.policy_input, &args.reviewed_ucan)?;
142 check_enrollment_only(&policy, &grant)?;
143 ensure!(
144 policy.generation == policy.lattice()?.version().generation(),
145 "reviewed policy/lattice generation mismatch"
146 );
147 use std::io::Write as _;
148 writeln!(
149 std::io::stdout().lock(),
150 "generation={} hash={}",
151 policy.generation,
152 hex::encode(policy.policy_hash()?)
153 )
154 .context("cannot write reviewed policy hash")?;
155 Ok(())
156}
157
158fn read_reviewed_boot_inputs(
159 policy_input: &Path,
160 reviewed_ucan: &Path,
161) -> anyhow::Result<(CompiledPolicy, Ucan)> {
162 let policy: CompiledPolicy = serde_json::from_slice(
163 &std::fs::read(policy_input).context("cannot read reviewed policy")?,
164 )
165 .context("invalid reviewed CompiledPolicy JSON")?;
166 let grant: Ucan =
167 serde_json::from_slice(&std::fs::read(reviewed_ucan).context("cannot read reviewed UCAN")?)
168 .context("invalid reviewed UCAN JSON")?;
169 Ok((policy, grant))
170}
171
172pub fn sign_reviewed_boot_policy(
178 args: &crate::cli::commands::trust::SignMacBootPolicyArgs,
179) -> anyhow::Result<()> {
180 let (policy, grant) = read_reviewed_boot_inputs(&args.policy_input, &args.reviewed_ucan)?;
181 let expected_hash: [u8; 32] = hex::decode(&args.expected_hash)
182 .context("expected hash must be hexadecimal")?
183 .try_into()
184 .map_err(|_| anyhow::anyhow!("expected hash must be exactly 32 bytes"))?;
185 check_reviewed_policy(&policy, args.expected_generation, &expected_hash)?;
187 check_enrollment_only(&policy, &grant)?;
188 let entries = crate::auth::identity_store::load_bootstrap_pubkeys_hybrid(&args.secrets_dir)?;
189 crate::auth::identity_store::ensure_bootstrap_pubkeys_hybrid(&entries)?;
190 crate::auth::identity_store::ensure_bootstrap_pubkeys_enrolled(&args.secrets_dir, &entries)?;
191 let authority = entries
192 .get("policy")
193 .context("no enrolled Policy authority in bootstrap roster")?;
194 let ed_sk = crate::auth::identity_store::load_existing_service_signing_key(
195 &args.secrets_dir,
196 "policy",
197 crate::auth::identity_store::SecretsProfile::SharedDirectory,
198 )?;
199 let (signed, approval) = sign_reviewed_policy(
200 &policy,
201 &grant,
202 args.expected_generation,
203 &expected_hash,
204 &ed_sk,
205 authority,
206 )?;
207 publish_boot_artifacts(&args.output_dir, &signed, &approval)
208}
209
210fn check_reviewed_policy(
211 policy: &CompiledPolicy,
212 generation: u64,
213 hash: &[u8; 32],
214) -> anyhow::Result<()> {
215 ensure!(
216 policy.generation == generation,
217 "reviewed policy generation mismatch"
218 );
219 ensure!(
220 policy.lattice()?.version().generation() == generation,
221 "reviewed lattice generation mismatch"
222 );
223 ensure!(
224 policy.policy_hash()? == *hash,
225 "reviewed policy hash mismatch (including enrollment)"
226 );
227 Ok(())
228}
229
230pub(crate) fn check_enrollment_only(policy: &CompiledPolicy, grant: &Ucan) -> anyhow::Result<()> {
231 let (allow, escalate) = policy.matrix.sorted_rules();
232 ensure!(
233 allow.is_empty() && escalate.is_empty() && grant.payload.capabilities.is_empty(),
234 "boot artifact authoring is enrollment-only: TE rules and UCAN capabilities must be empty"
235 );
236 Ok(())
237}
238
239fn sign_reviewed_policy(
240 policy: &CompiledPolicy,
241 grant: &Ucan,
242 generation: u64,
243 hash: &[u8; 32],
244 ed_sk: &SigningKey,
245 authority: &crate::auth::identity_store::BootstrapPubkey,
246) -> anyhow::Result<(SignedPolicy, SignedApproval)> {
247 check_reviewed_policy(policy, generation, hash)?;
248 check_enrollment_only(policy, grant)?;
249 let signer_public = crate::auth::identity_store::BootstrapPubkey::for_service_key(ed_sk)?;
250 ensure!(
251 authority.is_hybrid() && signer_public.to_key_bytes() == authority.to_key_bytes(),
252 "existing Policy signer does not match the enrolled hybrid authority"
253 );
254 let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(ed_sk);
255 let signed = sign_policy(
256 policy,
257 &HybridPolicySigner {
258 ed_sk,
259 pq_sk: Some(&pq_sk),
260 },
261 )?;
262 let approval = SignedApproval::sign(
263 ApprovalBinding::new(grant, generation, *hash)?,
264 ed_sk,
265 &pq_sk,
266 )?;
267 verify_boot_policy(&signed, &approval, authority)?;
269 Ok((signed, approval))
270}
271
272fn publish_boot_artifacts(
273 output_dir: &Path,
274 signed: &SignedPolicy,
275 approval: &SignedApproval,
276) -> anyhow::Result<()> {
277 use std::io::Write as _;
278 let parent = output_dir
279 .parent()
280 .filter(|p| !p.as_os_str().is_empty())
281 .unwrap_or_else(|| Path::new("."));
282 let staged = tempfile::tempdir_in(parent).context("cannot stage MAC boot artifacts")?;
283 for (name, bytes) in [
284 ("signed-policy.json", serde_json::to_vec(signed)?),
285 ("signed-approval.json", serde_json::to_vec(approval)?),
286 ] {
287 let mut file = std::fs::File::create(staged.path().join(name))?;
288 file.write_all(&bytes)?;
289 #[cfg(unix)]
290 {
291 use std::os::unix::fs::PermissionsExt as _;
292 file.set_permissions(std::fs::Permissions::from_mode(0o644))?;
293 }
294 file.sync_all()?;
295 }
296 #[cfg(unix)]
297 {
298 use std::os::unix::fs::PermissionsExt as _;
299 std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755))?;
300 }
301 std::fs::File::open(staged.path())?.sync_all()?;
302 std::fs::create_dir(output_dir).context("MAC boot output directory must not exist")?;
307 std::fs::rename(staged.path(), output_dir).context("cannot publish MAC boot artifacts")?;
308 std::fs::File::open(parent)?.sync_all()?;
309 Ok(())
310}
311
312pub fn compile_sign_load_install(
354 grant: &Ucan,
355 lattice: &Lattice,
356 permissions: &impl PermissionMap,
357 enrollment: BTreeMap<String, SecurityLabel>,
358 approval: PolicyApproval,
359 ed_sk: &SigningKey,
360 pq_sk: &MlDsaSigningKey,
361) -> Result<(Arc<CompiledPolicy>, bool), BootPolicyError> {
362 let policy = compile(grant, lattice, permissions).with_enrollment(enrollment);
365
366 sign_load_install(policy, approval, ed_sk, pq_sk)
367}
368
369fn sign_load_install(
373 policy: CompiledPolicy,
374 approval: PolicyApproval,
375 ed_sk: &SigningKey,
376 pq_sk: &MlDsaSigningKey,
377) -> Result<(Arc<CompiledPolicy>, bool), BootPolicyError> {
378 let signer = HybridPolicySigner {
381 ed_sk,
382 pq_sk: Some(pq_sk),
383 };
384 let signed = sign_policy(&policy, &signer)?;
385
386 let ed_vk = ed_sk.verifying_key();
389 let pq_vk = ml_dsa::Keypair::verifying_key(pq_sk).clone();
393 let verifier = HybridPolicyVerifier {
394 ed_vk: &ed_vk,
395 pq_vk: Some(&pq_vk),
396 require_pq: true,
397 };
398 let loaded = PolicyLoader::new(verifier)
399 .with_approval(approval)
400 .load(&signed)?;
401
402 let policy = Arc::new(loaded);
403 let installed = install_compiled_policy(policy.clone());
404 Ok((policy, installed))
405}
406
407fn install_self_approved_empty_baseline(
412 ed_sk: &SigningKey,
413 pq_sk: &MlDsaSigningKey,
414) -> Result<(Arc<CompiledPolicy>, bool), BootPolicyError> {
415 let did = Did::from_ed25519(&ed_sk.verifying_key().to_bytes());
416 let grant = Ucan {
417 payload: UcanPayload {
418 issuer: did.clone(),
419 audience: did,
420 capabilities: vec![],
421 not_before: None,
422 expiration: None,
423 nonce: vec![],
424 },
425 proofs: vec![],
426 signature: vec![],
427 };
428
429 let lattice = Lattice::new(LatticeVersion(1), []);
430 let permissions = ScopePermissionMap::new(SubjectType(1), Vec::<(String, String)>::new());
431 let policy = compile(&grant, &lattice, &permissions).with_enrollment(BTreeMap::new());
432 let approval = PolicyApproval {
433 generation: policy.generation,
434 approved_hash: policy.policy_hash()?,
435 };
436
437 sign_load_install(policy, approval, ed_sk, pq_sk)
438}
439
440pub fn install_baseline_boot_policy(
463 ed_sk: &SigningKey,
464 pq_sk: &MlDsaSigningKey,
465) -> Result<(Arc<CompiledPolicy>, bool), BootPolicyError> {
466 install_self_approved_empty_baseline(ed_sk, pq_sk)
467}
468
469#[cfg(test)]
470#[allow(clippy::unwrap_used, clippy::expect_used)]
471mod tests {
472 use super::*;
473 use crate::mac::compiled_policy;
474 use crate::mac::lattice::{Assurance, CompartmentSet, Level};
475 use crate::mac::EnrollmentSubjectContextResolver;
476 use crate::services::oauth::token_exchange::SubjectContextResolver as _;
477 use hyprstream_rpc::auth::ucan::approval::{ApprovalBinding, SignedApproval};
478 use hyprstream_rpc::auth::ucan::capability::{Ability, Capability, Resource};
479 use hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair;
480 use rand::rngs::OsRng;
481
482 fn cap(res: &str, ab: &str) -> Capability {
483 Capability::new(Resource::new(res), Ability::new(ab))
484 }
485
486 fn grant_with(caps: Vec<Capability>) -> Ucan {
487 let did = Did::from_ed25519(&[0u8; 32]);
488 Ucan {
489 payload: UcanPayload {
490 issuer: did.clone(),
491 audience: did,
492 capabilities: caps,
493 not_before: None,
494 expiration: None,
495 nonce: vec![],
496 },
497 proofs: vec![],
498 signature: vec![],
499 }
500 }
501
502 fn boot_artifacts() -> (
503 SignedPolicy,
504 SignedApproval,
505 crate::auth::identity_store::BootstrapPubkey,
506 SigningKey,
507 MlDsaSigningKey,
508 ) {
509 boot_artifacts_at_generation(7)
510 }
511
512 fn boot_artifacts_at_generation(
513 generation: u32,
514 ) -> (
515 SignedPolicy,
516 SignedApproval,
517 crate::auth::identity_store::BootstrapPubkey,
518 SigningKey,
519 MlDsaSigningKey,
520 ) {
521 let ed = SigningKey::generate(&mut OsRng);
522 let (pq, pq_vk) = ml_dsa_generate_keypair();
523 let policy = CompiledPolicy::new(
524 crate::mac::te::TeMatrix::default(),
525 &Lattice::new(LatticeVersion(generation), []),
526 )
527 .with_enrollment(BTreeMap::from([(
528 "did:key:zApprovedBootFixture".to_owned(),
529 SecurityLabel::new(
530 Level::Internal,
531 Assurance::Unverified,
532 CompartmentSet::EMPTY,
533 ),
534 )]));
535 let signed = sign_policy(
536 &policy,
537 &HybridPolicySigner {
538 ed_sk: &ed,
539 pq_sk: Some(&pq),
540 },
541 )
542 .unwrap();
543 let binding = ApprovalBinding::new(
544 &grant_with(vec![]),
545 policy.generation,
546 policy.policy_hash().unwrap(),
547 )
548 .unwrap();
549 let approval = SignedApproval::sign(binding, &ed, &pq).unwrap();
550 let authority =
551 crate::auth::identity_store::BootstrapPubkey::hybrid(ed.verifying_key(), pq_vk);
552 (signed, approval, authority, ed, pq)
553 }
554
555 #[test]
556 fn configured_boot_files_load_reviewed_enrollment_without_te_authority() {
557 let (signed, approval, authority, _, _) = boot_artifacts();
558 let expected = verify_boot_policy(&signed, &approval, &authority).unwrap();
559 let dir = tempfile::tempdir().unwrap();
560 let config = crate::config::MacBootPolicyConfig {
561 policy_path: dir.path().join("policy.json"),
562 approval_path: dir.path().join("approval.json"),
563 expected_generation: expected.generation,
564 expected_policy_hash: hex::encode(expected.policy_hash().unwrap()),
565 };
566 std::fs::write(&config.policy_path, serde_json::to_vec(&signed).unwrap()).unwrap();
567 std::fs::write(
568 &config.approval_path,
569 serde_json::to_vec(&approval).unwrap(),
570 )
571 .unwrap();
572 let policy = load_boot_policy_files(&config, &authority).unwrap();
573 assert_eq!(policy.matrix.allow_len(), 0);
574 assert_eq!(
575 policy.clearance_for("did:key:zApprovedBootFixture"),
576 Some(SecurityLabel::new(
577 Level::Internal,
578 Assurance::Unverified,
579 CompartmentSet::EMPTY
580 ))
581 );
582 let resolver = EnrollmentSubjectContextResolver::new(Arc::new(policy));
583 assert!(resolver.resolve("did:key:zApprovedBootFixture").is_some());
584 assert!(resolver.resolve("did:key:zNotEnrolled").is_none());
585
586 std::fs::remove_file(&config.approval_path).unwrap();
587 assert!(load_boot_policy_files(&config, &authority).is_err());
588 std::fs::write(&config.approval_path, b"{}").unwrap();
589 assert!(load_boot_policy_files(&config, &authority).is_err());
590 std::fs::remove_file(&config.policy_path).unwrap();
591 assert!(load_boot_policy_files(&config, &authority).is_err());
592 }
593
594 #[test]
595 fn configured_boot_pin_rejects_older_valid_pair_after_restart_reload() {
596 let (current_signed, current_approval, authority, ed, pq) = boot_artifacts_at_generation(7);
597 let current = verify_boot_policy(¤t_signed, ¤t_approval, &authority).unwrap();
598 let older = CompiledPolicy::new(
599 crate::mac::te::TeMatrix::default(),
600 &Lattice::new(LatticeVersion(6), []),
601 )
602 .with_enrollment(current.enrollment.clone());
603 let older_signed = sign_policy(
604 &older,
605 &HybridPolicySigner {
606 ed_sk: &ed,
607 pq_sk: Some(&pq),
608 },
609 )
610 .unwrap();
611 let older_binding = ApprovalBinding::new(
612 &grant_with(vec![]),
613 older.generation,
614 older.policy_hash().unwrap(),
615 )
616 .unwrap();
617 let older_approval = SignedApproval::sign(older_binding, &ed, &pq).unwrap();
618 let dir = tempfile::tempdir().unwrap();
619 let config = crate::config::MacBootPolicyConfig {
620 policy_path: dir.path().join("policy.json"),
621 approval_path: dir.path().join("approval.json"),
622 expected_generation: current.generation,
623 expected_policy_hash: hex::encode(current.policy_hash().unwrap()),
624 };
625
626 std::fs::write(
629 &config.policy_path,
630 serde_json::to_vec(¤t_signed).unwrap(),
631 )
632 .unwrap();
633 std::fs::write(
634 &config.approval_path,
635 serde_json::to_vec(¤t_approval).unwrap(),
636 )
637 .unwrap();
638 assert_eq!(
639 load_boot_policy_files(&config, &authority)
640 .unwrap()
641 .generation,
642 7
643 );
644 assert_eq!(
645 load_boot_policy_files(&config, &authority)
646 .unwrap()
647 .generation,
648 7
649 );
650
651 std::fs::write(
655 &config.policy_path,
656 serde_json::to_vec(&older_signed).unwrap(),
657 )
658 .unwrap();
659 std::fs::write(
660 &config.approval_path,
661 serde_json::to_vec(&older_approval).unwrap(),
662 )
663 .unwrap();
664 let error = load_boot_policy_files(&config, &authority).unwrap_err();
665 assert!(
666 format!("{error:#}").contains("generation mismatch"),
667 "{error:#}"
668 );
669
670 std::fs::write(
673 &config.policy_path,
674 serde_json::to_vec(¤t_signed).unwrap(),
675 )
676 .unwrap();
677 std::fs::write(
678 &config.approval_path,
679 serde_json::to_vec(¤t_approval).unwrap(),
680 )
681 .unwrap();
682 assert_eq!(
683 load_boot_policy_files(&config, &authority)
684 .unwrap()
685 .generation,
686 7
687 );
688 }
689
690 #[test]
691 fn configured_boot_rejects_validly_signed_allow_and_escalation_rules() {
692 use crate::mac::te::{Action, ObjectType, TeMatrix, TeRule};
693 let (signed, approval, authority, ed, pq) = boot_artifacts();
694 let enrolled = verify_boot_policy(&signed, &approval, &authority).unwrap();
695 let rule = TeRule {
696 subject_type: SubjectType(1),
697 object_type: ObjectType(1),
698 action: Action(1),
699 };
700 let dir = tempfile::tempdir().unwrap();
701 let policy_path = dir.path().join("policy.json");
702 let approval_path = dir.path().join("approval.json");
703 for matrix in [
704 TeMatrix::from_allow([rule]),
705 TeMatrix::new(Default::default(), [rule].into_iter().collect()),
706 ] {
707 let mut policy = enrolled.clone();
708 policy.matrix = matrix;
709 let signed = sign_policy(
710 &policy,
711 &HybridPolicySigner {
712 ed_sk: &ed,
713 pq_sk: Some(&pq),
714 },
715 )
716 .unwrap();
717 let config = crate::config::MacBootPolicyConfig {
718 policy_path: policy_path.clone(),
719 approval_path: approval_path.clone(),
720 expected_generation: policy.generation,
721 expected_policy_hash: hex::encode(policy.policy_hash().unwrap()),
722 };
723 let approval = SignedApproval::sign(
724 ApprovalBinding::new(
725 &grant_with(vec![]),
726 policy.generation,
727 policy.policy_hash().unwrap(),
728 )
729 .unwrap(),
730 &ed,
731 &pq,
732 )
733 .unwrap();
734 std::fs::write(&config.policy_path, serde_json::to_vec(&signed).unwrap()).unwrap();
737 std::fs::write(
738 &config.approval_path,
739 serde_json::to_vec(&approval).unwrap(),
740 )
741 .unwrap();
742 let error = load_boot_policy_files(&config, &authority).unwrap_err();
743 assert!(error.to_string().contains("enrollment-only"), "{error:#}");
744 }
745 }
746
747 #[test]
748 fn configured_boot_rejects_tampering_wrong_keys_and_unapproved_hash() {
749 let (signed, approval, authority, ed, pq) = boot_artifacts();
750 let (other_signed, other_approval, other_authority, _, _) = boot_artifacts();
751 assert!(verify_boot_policy(&signed, &approval, &other_authority).is_err());
752 assert!(verify_boot_policy(&other_signed, &approval, &authority).is_err());
753 assert!(verify_boot_policy(&signed, &other_approval, &authority).is_err());
754 let mut bad = signed.clone();
755 bad.signature[0] ^= 1;
756 assert!(verify_boot_policy(&bad, &approval, &authority).is_err());
757 let mut bad_approval = approval.clone();
758 bad_approval.binding.bundle_hash[0] ^= 1;
759 assert!(verify_boot_policy(&signed, &bad_approval, &authority).is_err());
760 let wrong_hash = SignedApproval::sign(bad_approval.binding, &ed, &pq).unwrap();
762 assert!(verify_boot_policy(&signed, &wrong_hash, &authority).is_err());
763 let classical = crate::auth::identity_store::BootstrapPubkey::classical(authority.ed25519);
764 assert!(verify_boot_policy(&signed, &approval, &classical).is_err());
765 let mixed = crate::auth::identity_store::BootstrapPubkey::hybrid(
767 authority.ed25519,
768 other_authority.ml_dsa_65.unwrap(),
769 );
770 assert!(verify_boot_policy(&signed, &approval, &mixed).is_err());
771 }
772
773 #[test]
774 fn configured_boot_refuses_unanchored_roster_and_unsupported_trust_source() {
775 let (_, _, authority, _, _) = boot_artifacts();
776 let dir = tempfile::tempdir().unwrap();
777 let config = crate::config::MacBootPolicyConfig {
778 policy_path: dir.path().join("policy.json"),
779 approval_path: dir.path().join("approval.json"),
780 expected_generation: 7,
781 expected_policy_hash: hex::encode([0u8; 32]),
782 };
783 let err = install_configured_boot_policy(&config, dir.path(), false).unwrap_err();
784 assert!(err.to_string().contains("OS-owned"));
785 crate::auth::identity_store::write_bootstrap_pubkeys_hybrid(
786 dir.path(),
787 &std::collections::HashMap::from([("policy".to_owned(), authority)]),
788 )
789 .unwrap();
790 let err = install_configured_boot_policy(&config, dir.path(), true).unwrap_err();
791 assert!(err.to_string().contains("enrollment attestation"));
792 }
793
794 #[test]
795 fn configured_boot_requires_both_paths_when_present() {
796 assert!(serde_json::from_str::<crate::config::PolicyServiceConfig>(
797 r#"{"boot_policy":{"policy_path":"policy.json"}}"#,
798 )
799 .is_err());
800 assert!(
801 serde_json::from_str::<crate::config::PolicyServiceConfig>("{}")
802 .unwrap()
803 .boot_policy
804 .is_none()
805 );
806 assert!(serde_json::from_str::<crate::config::PolicyServiceConfig>(
807 r#"{"boot_policy":{"policy_path":"policy.json","approval_path":"approval.json","expected_generation":7,"expected_policy_hash":"0000000000000000000000000000000000000000000000000000000000000000"}}"#,
808 )
809 .is_ok());
810 }
811
812 #[test]
813 fn reviewed_boot_authoring_round_trips_and_never_replaces_outputs() {
814 let (signed, approval, authority, ed, _) = boot_artifacts();
815 let policy = verify_boot_policy(&signed, &approval, &authority).unwrap();
816 let derived_authority =
817 crate::auth::identity_store::BootstrapPubkey::for_service_key(&ed).unwrap();
818 let hash = policy.policy_hash().unwrap();
819 let (signed, approval) = sign_reviewed_policy(
820 &policy,
821 &grant_with(vec![]),
822 7,
823 &hash,
824 &ed,
825 &derived_authority,
826 )
827 .unwrap();
828 let dir = tempfile::tempdir().unwrap();
829 let output = dir.path().join("reviewed");
830 publish_boot_artifacts(&output, &signed, &approval).unwrap();
831 let config = crate::config::MacBootPolicyConfig {
832 policy_path: output.join("signed-policy.json"),
833 approval_path: output.join("signed-approval.json"),
834 expected_generation: policy.generation,
835 expected_policy_hash: hex::encode(hash),
836 };
837 let loaded = load_boot_policy_files(&config, &derived_authority).unwrap();
838 assert_eq!(loaded.policy_hash().unwrap(), hash);
839 assert_eq!(loaded.enrollment, policy.enrollment);
840 assert!(publish_boot_artifacts(&output, &signed, &approval).is_err());
841 assert_eq!(
842 load_boot_policy_files(&config, &derived_authority)
843 .unwrap()
844 .policy_hash()
845 .unwrap(),
846 hash
847 );
848 }
849
850 #[test]
851 fn reviewed_boot_authoring_rejects_mismatch_wrong_signer_and_capabilities() {
852 let (signed, approval, authority, ed, _) = boot_artifacts();
853 let mut policy = verify_boot_policy(&signed, &approval, &authority).unwrap();
854 let pinned = crate::auth::identity_store::BootstrapPubkey::for_service_key(&ed).unwrap();
855 let hash = policy.policy_hash().unwrap();
856 let grant = grant_with(vec![]);
857 assert!(sign_reviewed_policy(&policy, &grant, 8, &hash, &ed, &pinned).is_err());
858 assert!(sign_reviewed_policy(&policy, &grant, 7, &[0; 32], &ed, &pinned).is_err());
859 let wrong_ed = SigningKey::generate(&mut OsRng);
860 assert!(sign_reviewed_policy(&policy, &grant, 7, &hash, &wrong_ed, &pinned).is_err());
861 assert!(sign_reviewed_policy(
862 &policy,
863 &grant_with(vec![cap("mac://model/llama", "query")]),
864 7,
865 &hash,
866 &ed,
867 &pinned
868 )
869 .is_err());
870 policy.enrollment.clear();
871 assert!(sign_reviewed_policy(&policy, &grant, 7, &hash, &ed, &pinned).is_err());
872 let nonempty = compile(
873 &grant_with(vec![cap("mac://model/llama", "query")]),
874 &Lattice::new(LatticeVersion(7), []),
875 &ScopePermissionMap::new(SubjectType(1), [("model", "llama")]),
876 );
877 assert!(sign_reviewed_policy(
878 &nonempty,
879 &grant,
880 7,
881 &nonempty.policy_hash().unwrap(),
882 &ed,
883 &pinned
884 )
885 .is_err());
886 }
887
888 #[test]
889 fn public_boot_hash_uses_exact_compiler_and_rejects_nonempty_grants() {
890 let (signed, approval, authority, _, _) = boot_artifacts();
891 let mut policy = verify_boot_policy(&signed, &approval, &authority).unwrap();
892 let dir = tempfile::tempdir().unwrap();
893 let args = crate::cli::commands::trust::HashMacBootPolicyArgs {
894 policy_input: dir.path().join("public-policy.json"),
895 reviewed_ucan: dir.path().join("public-ucan.json"),
896 };
897 let write = |policy: &CompiledPolicy, grant: &Ucan| {
898 std::fs::write(&args.policy_input, serde_json::to_vec(policy).unwrap()).unwrap();
899 std::fs::write(&args.reviewed_ucan, serde_json::to_vec(grant).unwrap()).unwrap();
900 };
901 write(&policy, &grant_with(vec![]));
902 assert_eq!(
903 read_reviewed_boot_inputs(&args.policy_input, &args.reviewed_ucan)
904 .unwrap()
905 .0
906 .policy_hash()
907 .unwrap(),
908 policy.policy_hash().unwrap(),
909 );
910 hash_reviewed_boot_policy(&args).unwrap();
911 write(
912 &policy,
913 &grant_with(vec![cap("mac://model/llama", "query")]),
914 );
915 assert!(hash_reviewed_boot_policy(&args).is_err());
916 policy.generation += 1;
917 write(&policy, &grant_with(vec![]));
918 assert!(hash_reviewed_boot_policy(&args).is_err());
919 }
920
921 #[test]
922 fn reviewed_boot_command_checks_hash_before_loading_any_credentials() {
923 let (signed, approval, authority, _, _) = boot_artifacts();
924 let policy = verify_boot_policy(&signed, &approval, &authority).unwrap();
925 let dir = tempfile::tempdir().unwrap();
926 let args = crate::cli::commands::trust::SignMacBootPolicyArgs {
927 policy_input: dir.path().join("input.json"),
928 reviewed_ucan: dir.path().join("ucan.json"),
929 expected_generation: 7,
930 expected_hash: "00".repeat(32),
931 secrets_dir: dir.path().join("no-credentials"),
932 output_dir: dir.path().join("output"),
933 };
934 std::fs::write(&args.policy_input, serde_json::to_vec(&policy).unwrap()).unwrap();
935 std::fs::write(
936 &args.reviewed_ucan,
937 serde_json::to_vec(&grant_with(vec![])).unwrap(),
938 )
939 .unwrap();
940 assert!(sign_reviewed_boot_policy(&args)
941 .unwrap_err()
942 .to_string()
943 .contains("hash mismatch"));
944 assert!(!args.secrets_dir.exists());
945 assert!(!args.output_dir.exists());
946 }
947
948 #[test]
954 fn boot_installs_policy_and_resolver_resolves_real_clearance() {
955 let ed_sk = SigningKey::generate(&mut OsRng);
956 let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
957
958 let lattice = Lattice::new(LatticeVersion(1), []);
960 let permissions = ScopePermissionMap::new(SubjectType(1), [("model", "llama")]);
961 let grant = grant_with(vec![cap("mac://model/llama", "query")]);
962
963 let did = "did:key:zBootActor";
964 let clearance =
965 SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY);
966 let enrollment = BTreeMap::from([(did.to_owned(), clearance)]);
967
968 let expected = compile(&grant, &lattice, &permissions).with_enrollment(enrollment.clone());
971 let binding =
972 ApprovalBinding::new(&grant, expected.generation, expected.policy_hash().unwrap())
973 .unwrap();
974 let signed_approval = SignedApproval::sign(binding, &ed_sk, &pq_sk).unwrap();
975 signed_approval
976 .verify_binds(
977 &ed_sk.verifying_key(),
978 &pq_vk,
979 &grant,
980 expected.generation,
981 &expected.policy_hash().unwrap(),
982 )
983 .unwrap();
984 let verified = signed_approval
985 .verify(&ed_sk.verifying_key(), &pq_vk)
986 .unwrap();
987 let approval = PolicyApproval::from_verified(verified);
988
989 let (policy, _installed) = compile_sign_load_install(
990 &grant,
991 &lattice,
992 &permissions,
993 enrollment,
994 approval,
995 &ed_sk,
996 &pq_sk,
997 )
998 .expect("hybrid sign + verify-once-at-load must succeed");
999
1000 assert_eq!(policy.matrix.allow_len(), 1, "one model × one verb");
1003
1004 assert!(
1007 compiled_policy().is_some(),
1008 "boot must install the process-global compiled policy"
1009 );
1010
1011 let resolver = EnrollmentSubjectContextResolver::new(policy);
1014 let ctx = resolver
1015 .resolve(did)
1016 .expect("an enrolled DID must resolve to a real clearance, not deny-all");
1017 assert_eq!(ctx.clearance().level, Level::Secret);
1018 assert_eq!(ctx.clearance().assurance, Assurance::Classical);
1020
1021 assert!(resolver.resolve("did:key:zStranger").is_none());
1023 }
1024
1025 #[test]
1026 fn generic_bootload_rejects_mismatched_approval() {
1027 let ed_sk = SigningKey::generate(&mut OsRng);
1028 let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1029 let lattice = Lattice::new(LatticeVersion(7), []);
1030 let permissions = ScopePermissionMap::new(SubjectType(1), [("model", "llama")]);
1031 let grant = grant_with(vec![cap("mac://model/llama", "query")]);
1032 let mismatched = PolicyApproval {
1033 generation: 7,
1034 approved_hash: [0u8; 32],
1035 };
1036
1037 let result = compile_sign_load_install(
1038 &grant,
1039 &lattice,
1040 &permissions,
1041 BTreeMap::new(),
1042 mismatched,
1043 &ed_sk,
1044 &pq_sk,
1045 );
1046
1047 assert!(matches!(
1048 result,
1049 Err(BootPolicyError::Policy(
1050 PolicyDistError::NoMatchingApproval { generation: 7 }
1051 ))
1052 ));
1053 }
1054
1055 #[test]
1059 fn baseline_boot_policy_installs_empty_dormant_matrix() {
1060 let ed_sk = SigningKey::generate(&mut OsRng);
1061 let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1062
1063 let (policy, _installed) = install_baseline_boot_policy(&ed_sk, &pq_sk)
1064 .expect("empty baseline must sign + verify-load");
1065
1066 assert_eq!(policy.generation, 1);
1067 assert_eq!(policy.matrix.allow_len(), 0, "empty grant → empty matrix");
1068 assert!(
1069 policy.clearance_for("did:key:zAnyone").is_none(),
1070 "the baseline enrolls nobody (fail-closed default)"
1071 );
1072 assert!(compiled_policy().is_some());
1073 }
1074
1075 #[test]
1087 fn baseline_boot_flips_seam_on_but_still_denies_every_did() {
1088 let ed_sk = SigningKey::generate(&mut OsRng);
1089 let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1090
1091 let _ = install_baseline_boot_policy(&ed_sk, &pq_sk)
1092 .expect("empty baseline must sign + verify-load");
1093
1094 assert!(
1097 compiled_policy().is_some(),
1098 "the seam must be populated after boot"
1099 );
1100
1101 let resolver = crate::mac::exchange_enrollment_resolver();
1105 assert!(
1106 resolver
1107 .resolve("did:key:zNobodyEverEnrollsThisSeamTest")
1108 .is_none(),
1109 "the flipped-on seam must still deny an unenrolled DID"
1110 );
1111 }
1112}