1use std::collections::HashMap;
18use std::sync::OnceLock;
19
20use anyhow::{bail, Result};
21
22use crate::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel};
23
24use super::{verify::VerifiedProof, ProofDisposition, SUITE_CLASSICAL, SUITE_HYBRID};
25
26pub const SYSTEM_LOW_LABEL: SecurityLabel = SecurityLabel {
30 level: Level::Public,
31 assurance: Assurance::Unverified,
32 compartments: CompartmentSet::EMPTY,
33};
34
35pub const fn dispatch_label(level: Level, assurance: Assurance, bits: &[u32]) -> SecurityLabel {
40 let mut set = CompartmentSet::EMPTY;
41 let mut i = 0;
42 while i < bits.len() {
43 set = set.union(CompartmentSet::single(bits[i]));
44 i += 1;
45 }
46 SecurityLabel {
47 level,
48 assurance,
49 compartments: set,
50 }
51}
52
53pub const READ_CLASS_ACTIONS: &[&str] = &["query", "subscribe"];
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum MutationSemantics {
64 NaturallyIdempotent,
67 IdempotencyKeyRequired,
74 TransactionLedgerRequired,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CryptoSuite {
84 Classical,
86 Hybrid,
89}
90
91impl CryptoSuite {
92 pub fn suite_id(self) -> &'static str {
94 match self {
95 Self::Classical => SUITE_CLASSICAL,
96 Self::Hybrid => SUITE_HYBRID,
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct AllowedApproverGroup {
108 pub group_id: u64,
110 pub suite: CryptoSuite,
112 pub role: String,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum ApproverRule {
124 All { groups: Vec<AllowedApproverGroup> },
126 KOfN {
128 k: usize,
129 groups: Vec<AllowedApproverGroup>,
130 },
131 Role {
133 role: String,
134 k: usize,
135 groups: Vec<AllowedApproverGroup>,
136 },
137}
138
139impl ApproverRule {
140 pub fn allowed_groups(&self) -> &[AllowedApproverGroup] {
142 match self {
143 Self::All { groups } | Self::KOfN { groups, .. } | Self::Role { groups, .. } => groups,
144 }
145 }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum SignaturePolicy {
151 UnauthenticatedOrTokenBound { suite: CryptoSuite },
156 TokenBound { suite: CryptoSuite },
159 TokenBoundAndApproved {
161 primary_suite: CryptoSuite,
162 approver_rule: ApproverRule,
163 },
164}
165
166impl SignaturePolicy {
167 pub fn primary_suite(&self) -> CryptoSuite {
169 match self {
170 Self::UnauthenticatedOrTokenBound { suite } | Self::TokenBound { suite } => *suite,
171 Self::TokenBoundAndApproved { primary_suite, .. } => *primary_suite,
172 }
173 }
174
175 pub fn allows_unattributed(&self) -> bool {
177 matches!(self, Self::UnauthenticatedOrTokenBound { .. })
178 }
179}
180
181pub trait DispatchMethodPolicy: Send + Sync {
187 fn policy_for(&self, service_domain: &str, leaf_path: &str) -> Option<SignaturePolicy>;
188}
189
190#[derive(Default)]
192pub struct InMemoryMethodPolicy {
193 rows: HashMap<(String, String), SignaturePolicy>,
194}
195
196impl InMemoryMethodPolicy {
197 pub fn new() -> Self {
198 Self::default()
199 }
200
201 pub fn insert(
202 &mut self,
203 service_domain: &str,
204 leaf_path: &str,
205 policy: SignaturePolicy,
206 ) -> &mut Self {
207 self.rows
208 .insert((service_domain.to_owned(), leaf_path.to_owned()), policy);
209 self
210 }
211}
212
213impl DispatchMethodPolicy for InMemoryMethodPolicy {
214 fn policy_for(&self, service_domain: &str, leaf_path: &str) -> Option<SignaturePolicy> {
215 self.rows
216 .get(&(service_domain.to_owned(), leaf_path.to_owned()))
217 .cloned()
218 }
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub enum AuthenticationRequirement {
224 CredentialRequired,
226 UnauthenticatedAllowed,
230}
231
232#[derive(Debug, Clone)]
240pub struct GeneratedMethodPolicyRow {
241 pub service: &'static str,
243 pub leaf_path: &'static [u16],
245 pub symbolic_path: &'static str,
247 pub scope_action: &'static str,
252 pub scope_exempt: bool,
257 pub authentication: AuthenticationRequirement,
259 pub signature_policy: SignaturePolicy,
261 pub mutation_semantics: Option<MutationSemantics>,
264 pub transitional_label: SecurityLabel,
267 pub target_label: SecurityLabel,
270 pub public_reason: Option<&'static str>,
272}
273
274impl GeneratedMethodPolicyRow {
275 pub fn leaf_key(&self) -> String {
277 self.leaf_path
278 .iter()
279 .map(u16::to_string)
280 .collect::<Vec<_>>()
281 .join(".")
282 }
283}
284
285pub struct GeneratedMethodPolicyProvider {
287 pub service: &'static str,
289 pub rows_fn: fn() -> Vec<GeneratedMethodPolicyRow>,
291 #[cfg(not(target_arch = "wasm32"))]
293 pub decode_fn: fn(&[u8]) -> Result<crate::service::DecodedRequestBody>,
294}
295
296#[cfg(not(target_arch = "wasm32"))]
297inventory::collect!(GeneratedMethodPolicyProvider);
298
299#[cfg(not(target_arch = "wasm32"))]
303pub fn mediated_operation_for_request(service: &str, signed_body: &[u8]) -> Result<String> {
304 let mut providers = inventory::iter::<GeneratedMethodPolicyProvider>
305 .into_iter()
306 .filter(|provider| provider.service == service);
307 let provider = providers
308 .next()
309 .ok_or_else(|| anyhow::anyhow!("unknown mediated service"))?;
310 anyhow::ensure!(providers.next().is_none(), "ambiguous mediated service");
311 let body = (provider.decode_fn)(signed_body)?;
312 let leaf = body
313 .leaf_path()
314 .ok_or_else(|| anyhow::anyhow!("missing mediated method leaf"))?;
315 let rows = (provider.rows_fn)();
316 validate_generated_rows(&rows)?;
317 anyhow::ensure!(
318 rows.iter().all(|row| row.service == service),
319 "mediated provider namespace mismatch"
320 );
321 let row = rows
322 .iter()
323 .find(|row| row.leaf_path == leaf)
324 .ok_or_else(|| anyhow::anyhow!("unknown mediated method leaf"))?;
325 anyhow::ensure!(
326 row.authentication == AuthenticationRequirement::CredentialRequired
327 && !row.scope_exempt
328 && !row.scope_action.is_empty(),
329 "mediated request is not an authenticated scoped method"
330 );
331 Ok(row.scope_action.to_owned())
332}
333
334#[cfg(not(target_arch = "wasm32"))]
338pub fn verify_mediated_operation(service: &str, signed_body: &[u8], operation: &str) -> Result<()> {
339 anyhow::ensure!(
340 mediated_operation_for_request(service, signed_body)? == operation,
341 "mediated operation does not match an authenticated scoped method"
342 );
343 Ok(())
344}
345
346pub fn validate_generated_rows(rows: &[GeneratedMethodPolicyRow]) -> Result<()> {
354 use std::collections::HashSet;
355 let mut leaf_keys: HashSet<(&str, String)> = HashSet::new();
356 let mut symbolic: HashSet<(&str, &str)> = HashSet::new();
357
358 for row in rows {
359 if row.leaf_path.is_empty() {
360 bail!(
361 "generated policy row '{}':'{}' has an empty leaf path",
362 row.service,
363 row.symbolic_path
364 );
365 }
366 if row.symbolic_path.is_empty() {
367 bail!(
368 "generated policy row '{}' has an empty symbolic path",
369 row.service
370 );
371 }
372 if !leaf_keys.insert((row.service, row.leaf_key())) {
373 bail!(
374 "generated policy collision: duplicate leaf '{}':'{}' ({})",
375 row.service,
376 row.leaf_key(),
377 row.symbolic_path
378 );
379 }
380 if !symbolic.insert((row.service, row.symbolic_path)) {
381 bail!(
382 "generated policy symbolic-name drift: duplicate '{}':'{}'",
383 row.service,
384 row.symbolic_path
385 );
386 }
387
388 match row.authentication {
391 AuthenticationRequirement::UnauthenticatedAllowed => {
392 if !row.signature_policy.allows_unattributed() {
393 bail!(
394 "public leaf '{}':'{}' carries an identity-only signature policy",
395 row.service,
396 row.symbolic_path
397 );
398 }
399 let reason_ok = row
400 .public_reason
401 .map(|r| !r.trim().is_empty())
402 .unwrap_or(false);
403 if !reason_ok {
404 bail!(
405 "public leaf '{}':'{}' has no recorded public reason",
406 row.service,
407 row.symbolic_path
408 );
409 }
410 if !row.scope_action.is_empty() {
411 bail!(
412 "public leaf '{}':'{}' also declares scope action '{}'",
413 row.service,
414 row.symbolic_path,
415 row.scope_action
416 );
417 }
418 if row.target_label != SYSTEM_LOW_LABEL {
421 bail!(
422 "public leaf '{}':'{}' target label {} is not exactly system low",
423 row.service,
424 row.symbolic_path,
425 row.target_label
426 );
427 }
428 }
429 AuthenticationRequirement::CredentialRequired => {
430 if row.signature_policy.allows_unattributed() {
431 bail!(
432 "credential-required leaf '{}':'{}' carries an unauthenticated-capable signature policy",
433 row.service,
434 row.symbolic_path
435 );
436 }
437 if row.scope_action.is_empty() && !row.scope_exempt {
443 bail!(
444 "credential-required leaf '{}':'{}' has no scope action and no recorded \
445 control-plane exemption",
446 row.service,
447 row.symbolic_path
448 );
449 }
450 if !row.scope_action.is_empty() && row.scope_exempt {
451 bail!(
452 "leaf '{}':'{}' is scope-exempt but carries scope action '{}'",
453 row.service,
454 row.symbolic_path,
455 row.scope_action
456 );
457 }
458 if row.target_label == SYSTEM_LOW_LABEL {
462 bail!(
463 "credential-required leaf '{}':'{}' has the system-low target label — \
464 system low through the MAC path is a build error (v16 §6)",
465 row.service,
466 row.symbolic_path
467 );
468 }
469 if row.public_reason.is_some() {
471 bail!(
472 "credential-required leaf '{}':'{}' carries a public reason",
473 row.service,
474 row.symbolic_path
475 );
476 }
477 }
478 }
479
480 if row.transitional_label != SYSTEM_LOW_LABEL {
484 bail!(
485 "row '{}':'{}' transitional label {} is not system low — the \
486 transitional column is fixed until the target flip (v16 §7.3)",
487 row.service,
488 row.symbolic_path,
489 row.transitional_label
490 );
491 }
492
493 if !row.scope_action.is_empty() {
499 let is_read_class = READ_CLASS_ACTIONS.contains(&row.scope_action);
500 if !is_read_class && row.mutation_semantics.is_none() {
501 bail!(
502 "mutating leaf '{}':'{}' (scope '{}') has no MutationSemantics — a \
503 mutating scope action requires an explicit one (v16 §6.1)",
504 row.service,
505 row.symbolic_path,
506 row.scope_action
507 );
508 }
509 }
510
511 if row.scope_action.is_empty() && !row.scope_exempt && row.mutation_semantics.is_some() {
515 bail!(
516 "unscoped non-exempt leaf '{}':'{}' declares MutationSemantics",
517 row.service,
518 row.symbolic_path
519 );
520 }
521
522 if let SignaturePolicy::TokenBoundAndApproved { approver_rule, .. } = &row.signature_policy
524 {
525 validate_approver_rule(row, approver_rule)?;
526 }
527 }
528 Ok(())
529}
530
531fn validate_approver_rule(row: &GeneratedMethodPolicyRow, rule: &ApproverRule) -> Result<()> {
532 let groups = rule.allowed_groups();
533 if groups.is_empty() {
534 bail!(
535 "approved leaf '{}':'{}' names no allowed approver groups",
536 row.service,
537 row.symbolic_path
538 );
539 }
540 let mut ids: Vec<u64> = groups.iter().map(|g| g.group_id).collect();
541 let count = ids.len();
542 ids.sort_unstable();
543 ids.dedup();
544 if ids.len() != count {
545 bail!(
546 "approved leaf '{}':'{}' names a duplicate approver group ID",
547 row.service,
548 row.symbolic_path
549 );
550 }
551 for group in groups {
552 if group.role.trim().is_empty() {
553 bail!(
554 "approved leaf '{}':'{}' names approver group {} with an empty role",
555 row.service,
556 row.symbolic_path,
557 group.group_id
558 );
559 }
560 }
561 match rule {
562 ApproverRule::All { .. } => Ok(()),
563 ApproverRule::KOfN { k, groups } => {
564 if *k == 0 || *k > groups.len() {
565 bail!(
566 "approved leaf '{}':'{}' has an unsatisfiable threshold {k} of {}",
567 row.service,
568 row.symbolic_path,
569 groups.len()
570 );
571 }
572 Ok(())
573 }
574 ApproverRule::Role { role, k, groups } => {
575 if role.trim().is_empty() {
576 bail!(
577 "approved leaf '{}':'{}' has a role rule with an empty role",
578 row.service,
579 row.symbolic_path
580 );
581 }
582 let holding = groups.iter().filter(|g| g.role == *role).count();
583 if *k == 0 || *k > holding {
584 bail!(
585 "approved leaf '{}':'{}' requires {k} group(s) holding role '{role}' but names {holding}",
586 row.service,
587 row.symbolic_path
588 );
589 }
590 Ok(())
591 }
592 }
593}
594
595#[cfg(not(target_arch = "wasm32"))]
598pub fn collect_generated_rows() -> Result<Vec<GeneratedMethodPolicyRow>> {
599 let mut rows: Vec<GeneratedMethodPolicyRow> = Vec::new();
600 for provider in inventory::iter::<GeneratedMethodPolicyProvider> {
601 let provided = (provider.rows_fn)();
602 for row in &provided {
603 if row.service != provider.service {
604 bail!(
605 "generated policy provider '{}' emitted a row for service '{}'",
606 provider.service,
607 row.service
608 );
609 }
610 }
611 rows.extend(provided);
612 }
613 rows.sort_by(|a, b| {
614 a.service
615 .cmp(b.service)
616 .then_with(|| a.leaf_path.cmp(b.leaf_path))
617 });
618 Ok(rows)
619}
620
621#[cfg(not(target_arch = "wasm32"))]
623pub fn build_generated_method_policy() -> Result<(InMemoryMethodPolicy, usize)> {
624 let rows = collect_generated_rows()?;
625 if rows.is_empty() {
626 bail!("no generated method-policy rows are linked into this binary");
627 }
628 validate_generated_rows(&rows)?;
629 let mut table = InMemoryMethodPolicy::new();
630 let count = rows.len();
631 for row in rows {
632 table.insert(row.service, &row.leaf_key(), row.signature_policy);
633 }
634 Ok((table, count))
635}
636
637#[cfg(not(target_arch = "wasm32"))]
644pub fn install_generated_method_policy() -> Result<usize> {
645 let (table, count) = build_generated_method_policy()?;
646 set_global_method_policy(Box::new(table))
647 .map_err(|_| anyhow::anyhow!("a global method-policy table is already installed"))?;
648 Ok(count)
649}
650
651static METHOD_POLICY: OnceLock<Box<dyn DispatchMethodPolicy>> = OnceLock::new();
652
653pub fn set_global_method_policy(
654 table: Box<dyn DispatchMethodPolicy>,
655) -> std::result::Result<(), Box<dyn DispatchMethodPolicy>> {
656 METHOD_POLICY.set(table)
657}
658
659pub fn global_method_policy() -> Option<&'static dyn DispatchMethodPolicy> {
660 METHOD_POLICY.get().map(|t| &**t)
661}
662
663pub fn evaluate(
669 policy: &SignaturePolicy,
670 disposition: ProofDisposition,
671 verified: &VerifiedProof,
672) -> Result<()> {
673 if disposition == ProofDisposition::Unattributed && !policy.allows_unattributed() {
675 bail!("method requires a credential-bound proof; unattributed proof denied");
676 }
677
678 let required = policy.primary_suite().suite_id();
682 if verified.primary_suite != required {
683 bail!(
684 "method requires primary suite '{}', proof declares '{}'",
685 required,
686 verified.primary_suite
687 );
688 }
689
690 match policy {
692 SignaturePolicy::UnauthenticatedOrTokenBound { .. }
693 | SignaturePolicy::TokenBound { .. } => {
694 if !verified.approvers.is_empty() {
695 bail!(
696 "method declares no approver rule but the proof carries {} approver group(s)",
697 verified.approvers.len()
698 );
699 }
700 Ok(())
701 }
702 SignaturePolicy::TokenBoundAndApproved { approver_rule, .. } => {
703 evaluate_approvers(approver_rule, verified)
704 }
705 }
706}
707
708fn evaluate_approvers(rule: &ApproverRule, verified: &VerifiedProof) -> Result<()> {
709 let allowed = rule.allowed_groups();
710
711 for approver in &verified.approvers {
716 let row = allowed
717 .iter()
718 .find(|row| row.group_id == approver.group_id)
719 .ok_or_else(|| {
720 anyhow::anyhow!(
721 "signer group {} is not an approver group this method allows",
722 approver.group_id
723 )
724 })?;
725 if approver.suite != row.suite.suite_id() {
726 bail!(
727 "approver group {} must use suite '{}', proof declares '{}'",
728 approver.group_id,
729 row.suite.suite_id(),
730 approver.suite
731 );
732 }
733 if approver.role.as_deref() != Some(row.role.as_str()) {
734 bail!(
735 "approver group {} must be enrolled with role '{}', enrollment holds {:?}",
736 approver.group_id,
737 row.role,
738 approver.role
739 );
740 }
741 }
742
743 let mut group_ids: Vec<u64> = verified.approvers.iter().map(|a| a.group_id).collect();
746 let presented = group_ids.len();
747 group_ids.sort_unstable();
748 group_ids.dedup();
749 if group_ids.len() != presented {
750 bail!("the same approver group is presented more than once");
751 }
752 let mut principals: Vec<&str> = verified
753 .approvers
754 .iter()
755 .map(|a| a.principal.as_str())
756 .collect();
757 principals.sort_unstable();
758 principals.dedup();
759 if principals.len() != presented {
760 bail!("approver groups do not resolve to distinct principals");
761 }
762
763 match rule {
765 ApproverRule::All { groups } => {
766 for row in groups {
767 if !verified
768 .approvers
769 .iter()
770 .any(|a| a.group_id == row.group_id)
771 {
772 bail!(
773 "approver rule requires group {} (role '{}'), which did not sign",
774 row.group_id,
775 row.role
776 );
777 }
778 }
779 Ok(())
780 }
781 ApproverRule::KOfN { k, .. } => {
782 if presented < *k {
783 bail!(
784 "approver rule requires {k} of the allowed groups, proof carries {presented}"
785 );
786 }
787 Ok(())
788 }
789 ApproverRule::Role { role, k, groups } => {
790 let holding = verified
791 .approvers
792 .iter()
793 .filter(|a| {
794 groups
795 .iter()
796 .any(|row| row.group_id == a.group_id && row.role == *role)
797 })
798 .count();
799 if holding < *k {
800 bail!(
801 "approver rule requires {k} allowed group(s) holding role '{role}', proof carries {holding}"
802 );
803 }
804 Ok(())
805 }
806 }
807}
808
809#[cfg(test)]
810#[allow(clippy::unwrap_used, clippy::expect_used)]
811mod tests {
812 use super::super::verify::VerifiedApprover;
813 use super::*;
814
815 fn verified(suite: CryptoSuite, approvers: &[(u64, &str, Option<&str>)]) -> VerifiedProof {
818 verified_with_suites(
819 suite,
820 &approvers
821 .iter()
822 .map(|(g, p, r)| (*g, CryptoSuite::Classical, *p, *r))
823 .collect::<Vec<_>>(),
824 )
825 }
826
827 fn verified_with_suites(
828 suite: CryptoSuite,
829 approvers: &[(u64, CryptoSuite, &str, Option<&str>)],
830 ) -> VerifiedProof {
831 VerifiedProof {
832 replay_thumbprint: [0u8; 32],
833 primary_principal: Some("client".into()),
834 primary_suite: suite.suite_id().to_owned(),
835 approvers: approvers
836 .iter()
837 .map(|(group_id, group_suite, p, r)| VerifiedApprover {
838 group_id: *group_id,
839 suite: group_suite.suite_id().to_owned(),
840 principal: (*p).to_owned(),
841 role: r.map(ToOwned::to_owned),
842 })
843 .collect(),
844 }
845 }
846
847 fn group(group_id: u64, role: &str) -> AllowedApproverGroup {
848 AllowedApproverGroup {
849 group_id,
850 suite: CryptoSuite::Classical,
851 role: role.to_owned(),
852 }
853 }
854
855 fn valid_row(leaf: &'static [u16], symbolic: &'static str) -> GeneratedMethodPolicyRow {
862 GeneratedMethodPolicyRow {
863 service: "svc",
864 leaf_path: leaf,
865 symbolic_path: symbolic,
866 scope_action: "query",
867 scope_exempt: false,
868 authentication: AuthenticationRequirement::CredentialRequired,
869 signature_policy: SignaturePolicy::TokenBound {
870 suite: CryptoSuite::Hybrid,
871 },
872 mutation_semantics: None,
873 transitional_label: SYSTEM_LOW_LABEL,
874 target_label: dispatch_label(Level::Internal, Assurance::PqHybrid, &[]),
875 public_reason: None,
876 }
877 }
878
879 fn public_row(leaf: &'static [u16], symbolic: &'static str) -> GeneratedMethodPolicyRow {
880 GeneratedMethodPolicyRow {
881 service: "svc",
882 leaf_path: leaf,
883 symbolic_path: symbolic,
884 scope_action: "",
885 scope_exempt: true,
886 authentication: AuthenticationRequirement::UnauthenticatedAllowed,
887 signature_policy: SignaturePolicy::UnauthenticatedOrTokenBound {
888 suite: CryptoSuite::Hybrid,
889 },
890 mutation_semantics: None,
891 transitional_label: SYSTEM_LOW_LABEL,
892 target_label: SYSTEM_LOW_LABEL,
893 public_reason: Some("declared $dispatchPublic in the service schema"),
894 }
895 }
896
897 #[test]
898 fn a_valid_generated_inventory_validates() {
899 let rows = vec![
900 valid_row(&[0], "a"),
901 valid_row(&[1, 0], "b.c"),
902 public_row(&[2], "p"),
903 ];
904 validate_generated_rows(&rows).expect("valid inventory must validate");
905 }
906
907 #[test]
908 fn a_leaf_path_collision_fails_the_build() {
909 let rows = vec![valid_row(&[0], "a"), valid_row(&[0], "b")];
910 assert!(validate_generated_rows(&rows).is_err());
911 }
912
913 #[test]
914 fn symbolic_name_drift_fails_the_build() {
915 let rows = vec![valid_row(&[0], "a"), valid_row(&[1], "a")];
916 assert!(validate_generated_rows(&rows).is_err());
917 }
918
919 #[test]
920 fn an_empty_leaf_path_fails_the_build() {
921 assert!(validate_generated_rows(&[valid_row(&[], "a")]).is_err());
922 }
923
924 #[test]
925 fn a_public_row_without_a_reason_fails_the_build() {
926 let mut row = public_row(&[0], "p");
927 row.public_reason = None;
928 assert!(validate_generated_rows(&[row.clone()]).is_err());
929 row.public_reason = Some(" ");
930 assert!(validate_generated_rows(&[row]).is_err());
931 }
932
933 #[test]
937 fn public_and_identity_only_contradictions_fail_the_build() {
938 let mut public_identity_only = public_row(&[0], "p");
939 public_identity_only.signature_policy = SignaturePolicy::TokenBound {
940 suite: CryptoSuite::Hybrid,
941 };
942 assert!(validate_generated_rows(&[public_identity_only]).is_err());
943
944 let mut credential_unattributed = valid_row(&[0], "a");
945 credential_unattributed.signature_policy = SignaturePolicy::UnauthenticatedOrTokenBound {
946 suite: CryptoSuite::Hybrid,
947 };
948 assert!(validate_generated_rows(&[credential_unattributed]).is_err());
949 }
950
951 #[test]
952 fn a_credential_required_row_without_a_scope_fails_the_build() {
953 let mut row = valid_row(&[0], "a");
954 row.scope_action = "";
955 assert!(validate_generated_rows(&[row]).is_err());
956 }
957
958 #[test]
962 fn label_column_contradictions_fail_the_build() {
963 let mut public_labeled = public_row(&[0], "p");
965 public_labeled.target_label = dispatch_label(Level::Internal, Assurance::PqHybrid, &[]);
966 assert!(validate_generated_rows(&[public_labeled]).is_err());
967
968 let mut mac_system_low = valid_row(&[0], "a");
970 mac_system_low.target_label = SYSTEM_LOW_LABEL;
971 assert!(validate_generated_rows(&[mac_system_low]).is_err());
972
973 let mut bad_transitional = valid_row(&[0], "a");
975 bad_transitional.transitional_label =
976 dispatch_label(Level::Internal, Assurance::PqHybrid, &[]);
977 assert!(validate_generated_rows(&[bad_transitional]).is_err());
978
979 let mut compartmented = valid_row(&[0], "a");
981 compartmented.target_label = dispatch_label(Level::Secret, Assurance::PqHybrid, &[0, 3]);
982 assert!(validate_generated_rows(&[compartmented]).is_ok());
983 }
984
985 #[test]
990 fn control_plane_exemptions_on_mac_rows_are_recorded_and_exact() {
991 let mut exempt = valid_row(&[0], "a");
993 exempt.scope_action = "";
994 exempt.scope_exempt = true;
995 assert!(validate_generated_rows(&[exempt]).is_ok());
996
997 let mut bare = valid_row(&[0], "a");
999 bare.scope_action = "";
1000 bare.scope_exempt = false;
1001 let err = validate_generated_rows(&[bare]).unwrap_err();
1002 assert!(
1003 err.to_string()
1004 .contains("no recorded control-plane exemption"),
1005 "{err}"
1006 );
1007
1008 let mut both = valid_row(&[0], "a");
1010 both.scope_exempt = true;
1011 let err = validate_generated_rows(&[both]).unwrap_err();
1012 assert!(
1013 err.to_string()
1014 .contains("scope-exempt but carries scope action"),
1015 "{err}"
1016 );
1017 }
1018
1019 #[test]
1022 fn mutation_semantics_mismatch_fails_the_build() {
1023 let mut read_claiming = valid_row(&[0], "a");
1026 read_claiming.scope_action = "query";
1027 read_claiming.mutation_semantics = Some(MutationSemantics::NaturallyIdempotent);
1028 assert!(validate_generated_rows(&[read_claiming]).is_ok());
1029
1030 let mut mutating_bare = valid_row(&[0], "a");
1033 mutating_bare.scope_action = "write";
1034 mutating_bare.mutation_semantics = None;
1035 assert!(validate_generated_rows(&[mutating_bare]).is_err());
1036 assert!(validate_generated_rows(&[public_row(&[3], "p2")]).is_ok());
1037
1038 let mut exempt_mutator = valid_row(&[4], "registerServiceKey");
1042 exempt_mutator.scope_action = "";
1043 exempt_mutator.scope_exempt = true;
1044 exempt_mutator.mutation_semantics = Some(MutationSemantics::NaturallyIdempotent);
1045 assert!(validate_generated_rows(&[exempt_mutator]).is_ok());
1046
1047 for semantics in [
1049 MutationSemantics::NaturallyIdempotent,
1050 MutationSemantics::IdempotencyKeyRequired,
1051 MutationSemantics::TransactionLedgerRequired,
1052 ] {
1053 let mut row = valid_row(&[0], "a");
1054 row.scope_action = "write";
1055 row.mutation_semantics = Some(semantics);
1056 assert!(validate_generated_rows(&[row]).is_ok());
1057 }
1058
1059 let mut subscribe = valid_row(&[0], "a");
1061 subscribe.scope_action = "subscribe";
1062 subscribe.mutation_semantics = Some(MutationSemantics::NaturallyIdempotent);
1063 assert!(validate_generated_rows(&[subscribe]).is_ok());
1064 }
1065
1066 #[test]
1067 fn unsatisfiable_or_malformed_approver_rules_fail_the_build() {
1068 let approved = |rule: ApproverRule| {
1069 let mut row = valid_row(&[0], "a");
1070 row.signature_policy = SignaturePolicy::TokenBoundAndApproved {
1071 primary_suite: CryptoSuite::Hybrid,
1072 approver_rule: rule,
1073 };
1074 row
1075 };
1076 assert!(
1078 validate_generated_rows(&[approved(ApproverRule::All { groups: vec![] })]).is_err()
1079 );
1080 assert!(validate_generated_rows(&[approved(ApproverRule::KOfN {
1082 k: 0,
1083 groups: vec![group(2, "security")],
1084 })])
1085 .is_err());
1086 assert!(validate_generated_rows(&[approved(ApproverRule::KOfN {
1087 k: 2,
1088 groups: vec![group(2, "security")],
1089 })])
1090 .is_err());
1091 assert!(validate_generated_rows(&[approved(ApproverRule::All {
1093 groups: vec![group(2, "security"), group(2, "finance")],
1094 })])
1095 .is_err());
1096 assert!(validate_generated_rows(&[approved(ApproverRule::Role {
1098 role: "legal".into(),
1099 k: 1,
1100 groups: vec![group(2, "security")],
1101 })])
1102 .is_err());
1103 assert!(validate_generated_rows(&[approved(ApproverRule::KOfN {
1105 k: 1,
1106 groups: vec![group(2, "")],
1107 })])
1108 .is_err());
1109 assert!(validate_generated_rows(&[approved(ApproverRule::KOfN {
1111 k: 1,
1112 groups: vec![group(2, "security")],
1113 })])
1114 .is_ok());
1115 }
1116
1117 #[test]
1118 fn an_unlisted_leaf_has_no_policy() {
1119 let table = InMemoryMethodPolicy::new();
1120 assert!(table.policy_for("registry.svc", "create").is_none());
1121 }
1122
1123 #[test]
1124 fn a_policy_row_is_exact_and_never_wildcarded() {
1125 let mut table = InMemoryMethodPolicy::new();
1126 table.insert(
1127 "registry.svc",
1128 "create",
1129 SignaturePolicy::TokenBound {
1130 suite: CryptoSuite::Hybrid,
1131 },
1132 );
1133 assert!(table.policy_for("registry.svc", "create").is_some());
1134 assert!(table.policy_for("registry.svc", "delete").is_none());
1135 assert!(table.policy_for("other.svc", "create").is_none());
1136 assert!(table.policy_for("registry.svc", "*").is_none());
1137 }
1138
1139 #[test]
1140 fn only_a_public_method_accepts_an_unattributed_proof() {
1141 let v = verified(CryptoSuite::Classical, &[]);
1142 let public = SignaturePolicy::UnauthenticatedOrTokenBound {
1143 suite: CryptoSuite::Classical,
1144 };
1145 let bound = SignaturePolicy::TokenBound {
1146 suite: CryptoSuite::Classical,
1147 };
1148 assert!(evaluate(&public, ProofDisposition::Unattributed, &v).is_ok());
1149 assert!(evaluate(&bound, ProofDisposition::Unattributed, &v).is_err());
1150 assert!(evaluate(&bound, ProofDisposition::Authenticated, &v).is_ok());
1151 }
1152
1153 #[test]
1154 fn the_primary_suite_must_match_exactly() {
1155 let classical = verified(CryptoSuite::Classical, &[]);
1156 let hybrid = verified(CryptoSuite::Hybrid, &[]);
1157 let needs_hybrid = SignaturePolicy::TokenBound {
1158 suite: CryptoSuite::Hybrid,
1159 };
1160 let needs_classical = SignaturePolicy::TokenBound {
1161 suite: CryptoSuite::Classical,
1162 };
1163 assert!(evaluate(&needs_hybrid, ProofDisposition::Authenticated, &classical).is_err());
1164 assert!(evaluate(&needs_classical, ProofDisposition::Authenticated, &hybrid).is_err());
1165 assert!(evaluate(&needs_hybrid, ProofDisposition::Authenticated, &hybrid).is_ok());
1166 }
1167
1168 #[test]
1171 fn unexpected_approvers_deny() {
1172 let v = verified(CryptoSuite::Classical, &[(2, "approver", Some("security"))]);
1173 let bound = SignaturePolicy::TokenBound {
1174 suite: CryptoSuite::Classical,
1175 };
1176 assert!(evaluate(&bound, ProofDisposition::Authenticated, &v).is_err());
1177 }
1178
1179 fn approved(rule: ApproverRule) -> SignaturePolicy {
1180 SignaturePolicy::TokenBoundAndApproved {
1181 primary_suite: CryptoSuite::Classical,
1182 approver_rule: rule,
1183 }
1184 }
1185
1186 #[test]
1189 fn an_unnamed_approver_group_denies() {
1190 let policy = approved(ApproverRule::KOfN {
1191 k: 1,
1192 groups: vec![group(2, "security")],
1193 });
1194 let named = verified(CryptoSuite::Classical, &[(2, "a", Some("security"))]);
1195 let unnamed = verified(CryptoSuite::Classical, &[(3, "b", Some("security"))]);
1196 let both = verified(
1197 CryptoSuite::Classical,
1198 &[(2, "a", Some("security")), (3, "b", Some("security"))],
1199 );
1200 assert!(evaluate(&policy, ProofDisposition::Authenticated, &named).is_ok());
1201 assert!(
1202 evaluate(&policy, ProofDisposition::Authenticated, &unnamed).is_err(),
1203 "an unnamed group must not satisfy the threshold"
1204 );
1205 assert!(
1206 evaluate(&policy, ProofDisposition::Authenticated, &both).is_err(),
1207 "an unnamed group must not merely accompany a satisfied threshold"
1208 );
1209 }
1210
1211 #[test]
1214 fn an_approver_group_under_the_wrong_suite_denies() {
1215 let policy = approved(ApproverRule::KOfN {
1216 k: 1,
1217 groups: vec![group(2, "security")],
1218 });
1219 let wrong_suite = verified_with_suites(
1220 CryptoSuite::Classical,
1221 &[(2, CryptoSuite::Hybrid, "a", Some("security"))],
1222 );
1223 assert!(evaluate(&policy, ProofDisposition::Authenticated, &wrong_suite).is_err());
1224 }
1225
1226 #[test]
1229 fn an_approver_group_with_the_wrong_enrolled_role_denies() {
1230 let policy = approved(ApproverRule::KOfN {
1231 k: 1,
1232 groups: vec![group(2, "security")],
1233 });
1234 for role in [Some("finance"), None] {
1235 let v = verified(CryptoSuite::Classical, &[(2, "a", role)]);
1236 assert!(evaluate(&policy, ProofDisposition::Authenticated, &v).is_err());
1237 }
1238 }
1239
1240 #[test]
1241 fn k_of_n_counts_only_allowed_groups() {
1242 let policy = approved(ApproverRule::KOfN {
1243 k: 2,
1244 groups: vec![group(2, "security"), group(3, "finance")],
1245 });
1246 let one = verified(CryptoSuite::Classical, &[(2, "a", Some("security"))]);
1247 let two = verified(
1248 CryptoSuite::Classical,
1249 &[(2, "a", Some("security")), (3, "b", Some("finance"))],
1250 );
1251 assert!(evaluate(&policy, ProofDisposition::Authenticated, &one).is_err());
1252 assert!(evaluate(&policy, ProofDisposition::Authenticated, &two).is_ok());
1253 }
1254
1255 #[test]
1258 fn a_repeated_group_or_principal_cannot_satisfy_a_threshold() {
1259 let policy = approved(ApproverRule::KOfN {
1260 k: 2,
1261 groups: vec![group(2, "security"), group(3, "finance")],
1262 });
1263 let repeated_group = verified(
1264 CryptoSuite::Classical,
1265 &[(2, "a", Some("security")), (2, "b", Some("security"))],
1266 );
1267 let repeated_principal = verified(
1268 CryptoSuite::Classical,
1269 &[(2, "a", Some("security")), (3, "a", Some("finance"))],
1270 );
1271 assert!(evaluate(&policy, ProofDisposition::Authenticated, &repeated_group).is_err());
1272 assert!(evaluate(
1273 &policy,
1274 ProofDisposition::Authenticated,
1275 &repeated_principal
1276 )
1277 .is_err());
1278 }
1279
1280 #[test]
1281 fn role_rules_count_only_allowed_groups_holding_that_role() {
1282 let policy = approved(ApproverRule::Role {
1283 role: "security".into(),
1284 k: 2,
1285 groups: vec![
1286 group(2, "security"),
1287 group(3, "security"),
1288 group(4, "finance"),
1289 ],
1290 });
1291 let one_security = verified(
1292 CryptoSuite::Classical,
1293 &[(2, "a", Some("security")), (4, "b", Some("finance"))],
1294 );
1295 let two_security = verified(
1296 CryptoSuite::Classical,
1297 &[(2, "a", Some("security")), (3, "b", Some("security"))],
1298 );
1299 assert!(evaluate(&policy, ProofDisposition::Authenticated, &one_security).is_err());
1300 assert!(evaluate(&policy, ProofDisposition::Authenticated, &two_security).is_ok());
1301 }
1302
1303 #[test]
1304 fn all_rules_require_every_named_group() {
1305 let policy = approved(ApproverRule::All {
1306 groups: vec![group(2, "security"), group(3, "finance")],
1307 });
1308 let missing = verified(CryptoSuite::Classical, &[(2, "a", Some("security"))]);
1309 let complete = verified(
1310 CryptoSuite::Classical,
1311 &[(2, "a", Some("security")), (3, "b", Some("finance"))],
1312 );
1313 let extra = verified(
1314 CryptoSuite::Classical,
1315 &[
1316 (2, "a", Some("security")),
1317 (3, "b", Some("finance")),
1318 (5, "c", Some("legal")),
1319 ],
1320 );
1321 assert!(evaluate(&policy, ProofDisposition::Authenticated, &missing).is_err());
1322 assert!(evaluate(&policy, ProofDisposition::Authenticated, &complete).is_ok());
1323 assert!(evaluate(&policy, ProofDisposition::Authenticated, &extra).is_err());
1324 }
1325}