Skip to main content

hyprstream_rpc/proof/
policy.rs

1//! Generated per-method signature policy (§4.4, §5.2).
2//!
3//! Enrollment equivalence is not authorization. An enrolled signer proves who
4//! signed; the **method's** generated policy decides what signing topology that
5//! method requires: whether it may be called with no credential at all, which
6//! cryptographic suite the primary logical signer must use, and whether
7//! additional enrolled approvers are required.
8//!
9//! The policy is a property of the decoded leaf, not of the caller. It is
10//! resolved after the single Cap'n Proto decode and evaluated before replay
11//! admission, so a request that fails it never consumes store capacity.
12//!
13//! A leaf with no policy row is **unlisted** and denies. That is the same rule
14//! the design gives for a leaf that exists only in a newer client schema: an
15//! unlisted `(service, leaf path)` denies, never falls back to a coarser row.
16
17use 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
26/// The system-low label — the exact expansion of `$dispatchPublic` and the
27/// mandatory value of every row's `transitional_label` during migration
28/// (v16 §7.3). Public ⇔ `target_label` is exactly this label.
29pub const SYSTEM_LOW_LABEL: SecurityLabel = SecurityLabel {
30    level: Level::Public,
31    assurance: Assurance::Unverified,
32    compartments: CompartmentSet::EMPTY,
33};
34
35/// Construct a dispatch label from its parsed axes (v16 §6). This is the ONE
36/// constructor generated rows use — there is no permissive default and no
37/// string parsing at runtime; the grammar was checked at code generation
38/// against the checked-in `InitialLabelMap`.
39pub 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
53/// The read-class authorization actions (S3 `ScopeAction` Block A). A leaf may
54/// explicitly classify bounded session/subscription state under either action;
55/// every other action requires a mutation policy.
56pub const READ_CLASS_ACTIONS: &[&str] = &["query", "subscribe"];
57
58/// The generated application policy a mutating method declares (v16 §4.8) —
59/// distinct from request-proof replay admission. The declaration metadata
60/// describes each method's retry semantics or activation prerequisite; the
61/// annotation itself does not implement enforcement.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum MutationSemantics {
64    /// Retrying the method with the same intent is safe without extra
65    /// machinery.
66    NaturallyIdempotent,
67    /// Activation prerequisite: before retry is enabled for the method, its
68    /// payload must carry a caller application idempotency key and the
69    /// service must durably bind that key to the recorded result so the
70    /// retry returns it. This declaration does not establish that the
71    /// key/result mechanism exists; activation must verify the method
72    /// implementation.
73    IdempotencyKeyRequired,
74    /// Reserved for a separately claimed exactly-once-visible contract: the
75    /// mutation commits with the ledger in one transaction or an equivalent
76    /// fencing protocol. The declaration is metadata; the claimed contract
77    /// must exist per method before this label is used.
78    TransactionLedgerRequired,
79}
80
81/// The cryptographic suite a method requires of its primary logical signer.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CryptoSuite {
84    /// Standalone Ed25519 (`hs-cose-sign-ed25519-v1`).
85    Classical,
86    /// Weakly-non-separable Ed25519 + ML-DSA-65
87    /// (`hs-cose-sign-ed25519-mldsa65-wns-v1`).
88    Hybrid,
89}
90
91impl CryptoSuite {
92    /// The exact suite ID a signed plan must declare for this suite.
93    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/// One approver group the generated policy allows, pinned exactly.
102///
103/// A group is identified by the signed plan's logical signer group ID, and
104/// must present the suite and hold the enrolled approver role this row names.
105/// Nothing outside this set may appear in a proof.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct AllowedApproverGroup {
108    /// The logical signer group ID this approver must occupy in the signed plan.
109    pub group_id: u64,
110    /// The exact suite this group must declare and verify under.
111    pub suite: CryptoSuite,
112    /// The enrolled approver role this group must hold.
113    pub role: String,
114}
115
116/// How many, and which, additional enrolled logical signers must approve.
117///
118/// Every variant carries the complete allowed set: an approver group whose ID
119/// is not listed, or whose verified suite or enrolled role does not match its
120/// row, denies before any threshold is counted. A threshold can therefore
121/// never be satisfied — or accompanied — by a group the method did not name.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum ApproverRule {
124    /// Every listed group must be present.
125    All { groups: Vec<AllowedApproverGroup> },
126    /// Any `k` of the listed groups must be present.
127    KOfN {
128        k: usize,
129        groups: Vec<AllowedApproverGroup>,
130    },
131    /// `k` of the listed groups holding the named role must be present.
132    Role {
133        role: String,
134        k: usize,
135        groups: Vec<AllowedApproverGroup>,
136    },
137}
138
139impl ApproverRule {
140    /// The complete set of approver groups this rule allows.
141    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/// The signing topology a method requires.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum SignaturePolicy {
151    /// Legal only for a `$dispatchPublic` method. With no credential the proof
152    /// key set receives no identity, role, clearance, or assurance. With a
153    /// credential presented, the proof MUST instead be credential-bound —
154    /// presenting a token never leaves the proof in the unattributed branch.
155    UnauthenticatedOrTokenBound { suite: CryptoSuite },
156    /// The primary logical signer's verified suite keys must match the
157    /// credential `cnf`-resolved signer-suite record.
158    TokenBound { suite: CryptoSuite },
159    /// As `TokenBound`, plus distinct enrolled approvers satisfying the rule.
160    TokenBoundAndApproved {
161        primary_suite: CryptoSuite,
162        approver_rule: ApproverRule,
163    },
164}
165
166impl SignaturePolicy {
167    /// The suite required of the primary logical signer.
168    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    /// Whether this method may be dispatched with no credential at all.
176    pub fn allows_unattributed(&self) -> bool {
177        matches!(self, Self::UnauthenticatedOrTokenBound { .. })
178    }
179}
180
181/// Resolves the generated policy row for one decoded leaf.
182///
183/// Rows are produced by code generation from the service schema; this trait is
184/// how the generated table reaches dispatch. There is no permissive default
185/// and no wildcard fallback: a leaf the table does not list denies.
186pub trait DispatchMethodPolicy: Send + Sync {
187    fn policy_for(&self, service_domain: &str, leaf_path: &str) -> Option<SignaturePolicy>;
188}
189
190/// An explicit policy table keyed by `(service domain, leaf path)`.
191#[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/// Whether a generated row admits the `Unauthenticated` disposition (v16 §6.1).
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub enum AuthenticationRequirement {
224    /// The method requires a verified credential; `$scope`-annotated leaves.
225    CredentialRequired,
226    /// The method is publicly dispatchable (`$scopeExempt` leaves) — legal
227    /// only together with an `UnauthenticatedOrTokenBound` signature policy
228    /// and a recorded public reason.
229    UnauthenticatedAllowed,
230}
231
232/// One generated method-policy row (v16 §6.1).
233///
234/// Rows are emitted by `generate_rpc_service!` from the same leaf-tree walk
235/// that produces the service's signed-body decoder, so the decoder can never
236/// derive a leaf the inventory does not list and vice versa. They are
237/// aggregated across all linked service crates through [`inventory`] and
238/// installed once at startup by [`install_generated_method_policy`].
239#[derive(Debug, Clone)]
240pub struct GeneratedMethodPolicyRow {
241    /// Canonical service domain (the dispatcher's `RequestService::name`).
242    pub service: &'static str,
243    /// Full numeric union-discriminant chain from the service root union.
244    pub leaf_path: &'static [u16],
245    /// Dotted human-readable path — review metadata, never a lookup key.
246    pub symbolic_path: &'static str,
247    /// `$scope`/`$capability` action; empty for `$dispatchPublic` leaves and
248    /// for `$dispatchMac` leaves whose control-plane scope is explicitly
249    /// exempted (`$scopeExempt` — the gate is a different mechanism, e.g. a
250    /// CA-signed JWT attestation, documented in the schema).
251    pub scope_action: &'static str,
252    /// Whether the leaf's control-plane scope is `$scopeExempt`-exempted. The
253    /// DISPATCH floor is unaffected (a `$scopeExempt` + `$dispatchMac` leaf
254    /// still requires a credential); this records why `scope_action` is empty
255    /// on a credential-required row.
256    pub scope_exempt: bool,
257    /// Whether the leaf admits the `Unauthenticated` disposition.
258    pub authentication: AuthenticationRequirement,
259    /// The signing topology the leaf requires.
260    pub signature_policy: SignaturePolicy,
261    /// The application mutation policy an effectful leaf declares (v16 §4.8).
262    /// `None` means no declared application effect, including ordinary reads.
263    pub mutation_semantics: Option<MutationSemantics>,
264    /// The migration label: always system low while the transitional column
265    /// is selected (v16 §7.3); deleted after the target flip.
266    pub transitional_label: SecurityLabel,
267    /// The operator-reviewable target label parsed from `$dispatchMac`, or
268    /// exactly system low for a `$dispatchPublic` leaf.
269    pub target_label: SecurityLabel,
270    /// The audited reason a publicly dispatchable leaf is public.
271    pub public_reason: Option<&'static str>,
272}
273
274impl GeneratedMethodPolicyRow {
275    /// The dotted numeric leaf key the policy table is resolved with.
276    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
285/// Inventory registration submitted by every server-side generated module.
286pub struct GeneratedMethodPolicyProvider {
287    /// The schema/service name the rows belong to.
288    pub service: &'static str,
289    /// Builder for the service's complete generated row set.
290    pub rows_fn: fn() -> Vec<GeneratedMethodPolicyRow>,
291    /// The same bounded body decoder used by this service's dispatch.
292    #[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/// Recover the only policy action an authenticated scoped request may mediate.
300/// The returned action is derived from the signed request leaf, not supplied
301/// by the mediator.
302#[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/// Bind a mediated query's operation to the original signed request leaf.
335/// This does not authenticate the body or grant authority: callers must first
336/// verify the holder transcript, credential, target, freshness and replay.
337#[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
346/// Validate one complete generated row set (v16 §6.1 build gates).
347///
348/// Every violation here is a **build error** — this function runs both in a
349/// permanent unit test over the full linked inventory (so CI fails when a
350/// schema change produces an invalid inventory) and at startup installation
351/// (so a production process refuses to serve under an invalid table rather
352/// than serving a partial one).
353pub 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        // A publicly dispatchable row and an identity-only signer policy are
389        // contradictory in both directions (v16 §6.1).
390        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                // `$dispatchPublic` expands to exactly system low (v16 §6) —
419                // anything else on a public row is a generation defect.
420                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                // An empty scope action on a credential-required row is legal
438                // only as a recorded control-plane exemption ($scopeExempt:
439                // the leaf is gated by a different, documented mechanism such
440                // as a CA-signed JWT attestation — the dispatch floor still
441                // requires the credential).
442                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                // A MAC'd leaf whose target is exactly system low would be
459                // indistinguishable from a public row — the label grammar
460                // rejects this at codegen; this is the generated-row floor.
461                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                // A public reason belongs to the public branch only.
470                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        // The transitional column is system low for every row while migration
481        // runs (v16 §7.3) — a generated row carrying anything else is a
482        // generation defect, never an operator choice.
483        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        // Mutation consistency (v16 §6.1): every non-read scope action requires
494        // explicit `MutationSemantics`. A read-class action may carry an
495        // explicit policy for bounded session/subscription state; authorization
496        // and application effects are separate axes. A public row carries no
497        // scope action and is reviewed through its public reason instead.
498        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        // A scope-exempt leaf may be public/read-only with no policy, or a
512        // separately authenticated control-plane mutator with an explicit one.
513        // Empty scope alone never erases explicit mutation metadata.
514        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        // Approver rules must be satisfiable and exact.
523        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/// Collect the complete generated inventory, deterministically sorted by
596/// `(service, numeric leaf path)`.
597#[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/// Build and validate the complete generated method-policy table.
622#[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/// Install the complete generated method-policy inventory as the process
638/// policy table (v16 §6.1). Returns the number of installed rows.
639///
640/// Fails — leaving proof-bearing dispatch fail-closed with **no** table —
641/// when the inventory is empty, inconsistent, colliding, or contradictory,
642/// or when a table was already installed.
643#[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
663/// Evaluate a resolved policy against a verified proof.
664///
665/// Called after signature verification, so the disposition, the primary
666/// suite, and the approver set are all facts established by cryptography and
667/// enrollment rather than claims read off the wire.
668pub fn evaluate(
669    policy: &SignaturePolicy,
670    disposition: ProofDisposition,
671    verified: &VerifiedProof,
672) -> Result<()> {
673    // 1. Disposition. Only a public method may be dispatched unattributed.
674    if disposition == ProofDisposition::Unattributed && !policy.allows_unattributed() {
675        bail!("method requires a credential-bound proof; unattributed proof denied");
676    }
677
678    // 2. The primary logical signer's suite must be exactly the one the method
679    //    declares — a standalone proof cannot satisfy a hybrid method, and a
680    //    hybrid proof cannot be presented where a standalone suite is declared.
681    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    // 3. Approvers.
691    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    // 1. Every group the proof carries must be one this method named, matched
712    //    by its signed logical group ID, and must present exactly the suite
713    //    and enrolled role that row pins. An unknown or mismatched group is a
714    //    denial, not a group that merely fails to count.
715    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    // 2. No group may be presented twice, and distinct groups must resolve to
744    //    distinct principals — one holder can never satisfy two approvals.
745    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    // 3. Threshold, counted only over groups that passed (1).
764    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    /// Approvers as (group_id, principal, role), all on the classical suite
816    /// unless a test overrides it.
817    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    // ── Generated-inventory validation: seeded negative controls ─────────
856    //
857    // Each control seeds one invalid generated-row shape and proves the
858    // validator fails the build/install for it (v16 §6.1). CI fails if any
859    // seeded invalid case stops failing.
860
861    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    /// The §6.1 contradiction in both directions: a public method with an
934    /// identity-only signer policy, and a credential-required method with an
935    /// unauthenticated-capable signer policy.
936    #[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    /// The `$dispatchMac`/`$dispatchPublic` label gates (v16 §6/§7.3): public
959    /// expands to exactly system low, a MAC'd row may never be system low, and
960    /// the transitional column is fixed at system low until the target flip.
961    #[test]
962    fn label_column_contradictions_fail_the_build() {
963        // A public row whose target is anything but system low.
964        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        // A credential-required row whose target IS system low.
969        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        // Any row whose transitional label left system low during migration.
974        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        // Compartments ride along on the target label and validate.
980        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    /// A `$scopeExempt` + `$dispatchMac` leaf (e.g. `policy.registerServiceKey`,
986    /// gated by CA-signed JWT attestation at the control plane) carries an empty
987    /// scope action LEGALLY — but only with the exemption recorded, and never
988    /// together with a scope action.
989    #[test]
990    fn control_plane_exemptions_on_mac_rows_are_recorded_and_exact() {
991        // Exempt + empty scope + credential required: legal.
992        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        // Empty scope WITHOUT the recorded exemption: build error.
998        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        // Exempt AND carrying a scope action: contradictory.
1009        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    /// Mutation consistency (v16 §6.1): non-read scope actions require an
1020    /// explicit `MutationSemantics`; stateful read-class leaves may claim one.
1021    #[test]
1022    fn mutation_semantics_mismatch_fails_the_build() {
1023        // A query scope may explicitly classify bounded session state while
1024        // preserving its existing query authorization.
1025        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        // mutating + None = contradiction. A public row (empty scope action)
1031        // is exempt from this gate — it is reviewed via its public reason.
1032        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        // A control-plane exemption can still be a declared mutator when its
1039        // separate authentication gate is documented; empty scope is not an
1040        // implicit read classification.
1041        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        // mutating + Some stays green, for each declared variant.
1048        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        // Subscribe can likewise classify effectful subscription state.
1060        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        // No allowed groups at all.
1077        assert!(
1078            validate_generated_rows(&[approved(ApproverRule::All { groups: vec![] })]).is_err()
1079        );
1080        // Threshold of zero, and threshold above the allowed set.
1081        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        // Duplicate group IDs in the allowed set.
1092        assert!(validate_generated_rows(&[approved(ApproverRule::All {
1093            groups: vec![group(2, "security"), group(2, "finance")],
1094        })])
1095        .is_err());
1096        // A role rule naming a role no allowed group holds (unknown group/role).
1097        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        // An empty role on an allowed group.
1104        assert!(validate_generated_rows(&[approved(ApproverRule::KOfN {
1105            k: 1,
1106            groups: vec![group(2, "")],
1107        })])
1108        .is_err());
1109        // The satisfiable control stays green.
1110        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    /// Extra approvals on a method that declares no approver rule are not
1169    /// harmless: an unrecognized signature group denies.
1170    #[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    /// A group the method never named cannot satisfy a threshold, and cannot
1187    /// ride along beside groups that do.
1188    #[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    /// Each allowed group is pinned to its own suite: a group signing under a
1212    /// different suite denies even though its ID and role match.
1213    #[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    /// A group present under an enrolled role the method did not pin for that
1227    /// group denies — roles are per-group, not a global pool.
1228    #[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    /// One principal counted twice can never satisfy a threshold, whether it
1256    /// arrives as one group repeated or as two allowed groups.
1257    #[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}