Skip to main content

vela_protocol/policy/
acceptance_policy.rs

1//! Policy-bound acceptance (the human-governance redesign, `vela_human_governance_memo`).
2//!
3//! The governing change: instead of a key-holding human accepting EVERY trusted
4//! transition, a human (or quorum) signs a scoped, revocable [`AcceptancePolicy`]
5//! ONCE, and a deterministic evaluator then routes each proposal to `permit`,
6//! `defer`, or `deny`. Humans sign policies, delegations, exceptions, and
7//! irreversible commitments; the engine signs routine executions that already
8//! satisfy a human-signed policy. This is a separation of duties, NOT a relaxation
9//! of the gate: policy decides *authority*, never *evidence* — a transition is only
10//! eligible for an auto-`permit` lane if its assurance profile already passed
11//! (`verifier_attachment::exact_lane_attachment_admit` / `derive_gate_status`).
12//!
13//! The evaluator is **pure and replayable**: a decision is reproducible from the
14//! proposal digest, the state root, the policy digest, the assurance evidence, the
15//! actor credential, a bounded context object, and the evaluator version. It is
16//! **monotonic on unknown data**: an unrecognized field or missing evidence can
17//! only move a `permit` to `defer`/`deny`, never the reverse. The safe default is
18//! `defer` (never silent denial or forced acceptance). Today this runs in SHADOW —
19//! it decides and certifies but does not change the canonical accept path (no new
20//! event kind, no wire change), so the autonomy can be proven before it is granted.
21
22use serde::{
23    Deserialize, Serialize,
24    de::{self, DeserializeOwned, DeserializeSeed, MapAccess, SeqAccess, Visitor},
25};
26use serde_json::{Map, Value};
27use sha2::{Digest, Sha256};
28use std::{collections::HashSet, fmt};
29
30use crate::receipt_v1::{ExecutionBindingV1, is_full_sha256_root};
31
32/// The three routing outcomes. `defer` is the safe default and carries the reason
33/// the transition needs a named human; `deny` is a structural/authority/explicit
34/// prohibition.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37pub enum Outcome {
38    Permit,
39    Defer,
40    Deny,
41}
42
43impl Outcome {
44    #[must_use]
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Outcome::Permit => "permit",
48            Outcome::Defer => "defer",
49            Outcome::Deny => "deny",
50        }
51    }
52}
53
54/// The bounded, structured context a rule is evaluated against. Every field is
55/// derived deterministically from the proposal + its assurance evidence + the
56/// frontier state (see the host that builds it). The evaluator reads ONLY these
57/// fields; it never makes a network call, reads wall-clock outside `now`, or
58/// consults a mutable reputation score.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct PolicyContext {
61    /// The structural claim class (e.g. "sidon_lower_bound", "formal_theorem",
62    /// "literature_finding", "metadata_repair", "governance").
63    pub claim_class: String,
64    /// Assurance level A0..A4 (0..4): A2 = one exact/formal check passed, A3 =
65    /// independent corroboration, A4 = adversarial+semantic fidelity. Derived from
66    /// the gate, NOT self-asserted.
67    pub assurance_level: u8,
68    /// Transition impact tier I0..I4 (0..4).
69    pub impact_tier: u8,
70    pub changed_findings: u32,
71    pub downstream_dependents: u32,
72    /// Does the proposal mutate claim LANGUAGE (vs attach exact evidence)?
73    pub assertion_text_mutated: bool,
74    pub target_contested: bool,
75    pub governance_mutation: bool,
76    /// Independence derived from failure-domain diversity (not self-declared).
77    pub independence_satisfied: bool,
78    /// MethodIntegrity::Sound on the matched attachments.
79    pub method_integrity_sound: bool,
80    /// The producer/delegate credential resolved and is unexpired/unrevoked.
81    pub credential_valid: bool,
82    /// The evaluator saw a field it does not recognize → never permit (monotonic).
83    pub has_unknown_fields: bool,
84    /// The originating receipt's honest replay classification (`exact` | `bounded`
85    /// | `approximate` | `unavailable` | `unknown`; docs/RECEIPTS.md). Hosts set
86    /// `unknown` explicitly for non-receipt transitions. A policy MAY require
87    /// `exact` to auto-admit a serious claim class.
88    pub replayability: String,
89    /// Optional closed Receipt v1 execution identity. It is absent from
90    /// historical contexts and ignored by policy v0.1; policy v0.2/v0.3 may
91    /// require exact full-root matches before Permit.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub execution_binding: Option<ExecutionBindingV1>,
94    /// Full root of the verified Receipt v1 producer identity binding. It is
95    /// absent from historical contexts and populated only for policy v0.3 so
96    /// v0.1/v0.2 decision certificates retain their exact context bytes.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub producer_credential_root: Option<String>,
99}
100
101impl Default for PolicyContext {
102    fn default() -> Self {
103        // The maximally-cautious context: nothing proven, everything that would
104        // force a defer/deny set. A rule must positively clear each gate.
105        PolicyContext {
106            claim_class: String::new(),
107            assurance_level: 0,
108            impact_tier: 4,
109            changed_findings: u32::MAX,
110            downstream_dependents: u32::MAX,
111            assertion_text_mutated: true,
112            target_contested: true,
113            governance_mutation: true,
114            independence_satisfied: false,
115            method_integrity_sound: false,
116            credential_valid: false,
117            has_unknown_fields: true,
118            replayability: "unknown".to_string(),
119            execution_binding: None,
120            producer_credential_root: None,
121        }
122    }
123}
124
125impl PolicyContext {
126    /// Canonical digest of the complete input surface consumed by the live
127    /// policy language.
128    ///
129    /// Keep this helper beside [`PolicyContext`]: callers must not maintain a
130    /// second hand-picked projection that can drift when the evaluator gains a
131    /// field. The digest is evidence about which facts were evaluated; it is
132    /// not an authority token and cannot turn a producer assertion into a
133    /// verified fact.
134    pub fn policy_language_digest(&self) -> Result<String, String> {
135        crate::canonical::sha256_canonical(self).map(|digest| format!("sha256:{digest}"))
136    }
137}
138
139/// The constraints a `permit` rule places on the transition. A `permit` fires only
140/// if ALL hold; otherwise the rule does not match and routing falls through.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143pub struct Constraints {
144    pub max_changed_findings: u32,
145    pub max_downstream_dependents: u32,
146    /// Lowest assurance level (0..4) that satisfies the rule.
147    pub required_assurance_min: u8,
148    /// `false` (the default) forbids claim-language mutation in this lane.
149    #[serde(default)]
150    pub allow_semantic_text_change: bool,
151    #[serde(default)]
152    pub allow_contested: bool,
153    #[serde(default)]
154    pub allow_governance_mutation: bool,
155    /// Require failure-domain-diverse independent verification.
156    #[serde(default)]
157    pub require_independence: bool,
158    /// Require MethodIntegrity::Sound.
159    #[serde(default)]
160    pub require_method_integrity: bool,
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub allowed_packet_roots: Option<Vec<String>>,
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub allowed_profile_roots: Option<Vec<String>>,
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub allowed_verifier_capsule_roots: Option<Vec<String>>,
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub allowed_result_contract_roots: Option<Vec<String>>,
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub allowed_producer_credential_roots: Option<Vec<String>>,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub required_replayability: Option<String>,
173}
174
175impl Default for Constraints {
176    fn default() -> Self {
177        Constraints {
178            max_changed_findings: 0,
179            max_downstream_dependents: 0,
180            required_assurance_min: 4,
181            allow_semantic_text_change: false,
182            allow_contested: false,
183            allow_governance_mutation: false,
184            require_independence: true,
185            require_method_integrity: true,
186            allowed_packet_roots: None,
187            allowed_profile_roots: None,
188            allowed_verifier_capsule_roots: None,
189            allowed_result_contract_roots: None,
190            allowed_producer_credential_roots: None,
191            required_replayability: None,
192        }
193    }
194}
195
196/// One rule: an effect plus the claim classes and constraints it applies to.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(deny_unknown_fields)]
199pub struct PolicyRule {
200    pub id: String,
201    pub effect: Outcome,
202    /// Claim classes this rule governs. Empty = applies to any class.
203    #[serde(default)]
204    pub claim_classes: Vec<String>,
205    #[serde(default)]
206    pub constraints: Constraints,
207}
208
209impl PolicyRule {
210    fn applies_to_class(&self, class: &str) -> bool {
211        self.claim_classes.is_empty() || self.claim_classes.iter().any(|c| c == class)
212    }
213}
214
215/// The quorum that must have signed the policy for it to carry authority.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct Quorum {
219    pub threshold: u32,
220    #[serde(default)]
221    pub eligible_roles: Vec<String>,
222}
223
224/// A scoped, revocable, content-addressed acceptance policy. Humans sign THIS
225/// (once); the evaluator applies it (many times). Shares signature/quorum/expiry/
226/// revocation shape with registry governance; this governs ordinary scientific
227/// state transitions, not owner rotation.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(deny_unknown_fields)]
230pub struct AcceptancePolicy {
231    pub schema: String,
232    pub id: String,
233    pub frontier_id: String,
234    pub epoch: u32,
235    pub issued_by: Vec<String>,
236    pub quorum: Quorum,
237    pub rules: Vec<PolicyRule>,
238    /// MUST be `Defer` or `Deny` (a permit default would be a footgun).
239    pub default: Outcome,
240    /// RFC3339; the evaluator denies after this instant.
241    pub expires_at: String,
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub revocation_ref: Option<String>,
244}
245
246pub const ACCEPTANCE_POLICY_V0_1_SCHEMA: &str = "vela.acceptance_policy.v0.1";
247pub const ACCEPTANCE_POLICY_V0_2_SCHEMA: &str = "vela.acceptance_policy.v0.2";
248pub const ACCEPTANCE_POLICY_V0_3_SCHEMA: &str = "vela.acceptance_policy.v0.3";
249
250/// The evaluator version, bound into every decision for replay.
251pub const EVALUATOR_VERSION: &str = "vela-policy@0.1.0";
252pub const EVALUATOR_VERSION_V0_2: &str = "vela-policy@0.2.0";
253pub const EVALUATOR_VERSION_V0_3: &str = "vela-policy@0.3.0";
254
255impl AcceptancePolicy {
256    /// Content address of the policy's normative body (everything but `id`), so
257    /// the id is reproducible and a tampered policy fails to verify. `vap_` prefix.
258    #[must_use]
259    pub fn content_address(&self) -> String {
260        let mut body = self.clone();
261        body.id.clear();
262        // AcceptancePolicy contains only the canonical JSON data model. Keep
263        // its content address on the same canonical bytes used by signatures;
264        // never collapse a serialization failure to the hash of empty bytes.
265        let bytes = crate::canonical::to_canonical_bytes(&body)
266            .expect("AcceptancePolicy must serialize as canonical JSON");
267        let mut h = Sha256::new();
268        h.update(&bytes);
269        format!("vap_{}", hex16(&h.finalize()))
270    }
271
272    /// True iff `id` matches the content address (tamper check).
273    #[must_use]
274    pub fn id_is_valid(&self) -> bool {
275        self.id == self.content_address()
276    }
277
278    /// Is the policy expired at `now`? Both values are parsed as RFC3339
279    /// instants before comparison, so equivalent offsets compare correctly.
280    /// Malformed lifecycle data fails closed and is treated as expired.
281    #[must_use]
282    pub fn is_expired(&self, now_rfc3339: &str) -> bool {
283        let Ok(expires_at) = chrono::DateTime::parse_from_rfc3339(&self.expires_at) else {
284            return true;
285        };
286        let Ok(now) = chrono::DateTime::parse_from_rfc3339(now_rfc3339) else {
287            return true;
288        };
289        now >= expires_at
290    }
291}
292
293/// A pure, replayable routing decision.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295pub struct Decision {
296    pub outcome: Outcome,
297    pub matched_rule_ids: Vec<String>,
298    /// Machine-readable reason codes (always non-empty).
299    pub reasons: Vec<String>,
300    pub evaluator: String,
301    pub policy_id: String,
302}
303
304/// The deterministic routing engine (memo Appendix C). Order of precedence:
305/// 1. structural/authority DENY (expired/revoked policy, governance mutation
306///    without an explicit governance-permit rule, invalid credential);
307/// 2. any matching `deny` rule → DENY;
308/// 3. escalation triggers (contested, semantic mutation, missing independence/
309///    integrity where required, downstream over bound, unknown fields) → DEFER;
310/// 4. a matching `permit` rule whose constraints all hold → PERMIT;
311/// 5. otherwise the policy `default` (DEFER or DENY).
312///
313/// Monotonic on unknown: `has_unknown_fields` or an unrecognized class can only
314/// push toward `defer`/`deny`.
315#[must_use]
316pub fn evaluate(policy: &AcceptancePolicy, ctx: &PolicyContext, now_rfc3339: &str) -> Decision {
317    let evaluator = match policy.schema.as_str() {
318        ACCEPTANCE_POLICY_V0_2_SCHEMA => EVALUATOR_VERSION_V0_2,
319        ACCEPTANCE_POLICY_V0_3_SCHEMA => EVALUATOR_VERSION_V0_3,
320        _ => EVALUATOR_VERSION,
321    };
322    let mk = |outcome: Outcome, rules: Vec<String>, reasons: Vec<String>| Decision {
323        outcome,
324        matched_rule_ids: rules,
325        reasons: if reasons.is_empty() {
326            vec!["default".to_string()]
327        } else {
328            reasons
329        },
330        evaluator: evaluator.to_string(),
331        policy_id: policy.id.clone(),
332    };
333
334    // (0) Policy integrity + lifecycle: structural DENY.
335    if !matches!(
336        policy.schema.as_str(),
337        ACCEPTANCE_POLICY_V0_1_SCHEMA
338            | ACCEPTANCE_POLICY_V0_2_SCHEMA
339            | ACCEPTANCE_POLICY_V0_3_SCHEMA
340    ) {
341        return mk(
342            Outcome::Deny,
343            vec![],
344            vec!["policy_schema_unsupported".into()],
345        );
346    }
347    if !policy.id_is_valid() {
348        return mk(Outcome::Deny, vec![], vec!["policy_id_mismatch".into()]);
349    }
350    if policy.is_expired(now_rfc3339) {
351        return mk(Outcome::Deny, vec![], vec!["policy_expired".into()]);
352    }
353    if policy.revocation_ref.is_some() {
354        return mk(Outcome::Deny, vec![], vec!["policy_revoked".into()]);
355    }
356    if !matches!(policy.default, Outcome::Defer | Outcome::Deny) {
357        // A permit default is rejected at evaluation time, defense in depth.
358        return mk(Outcome::Deny, vec![], vec!["illegal_permit_default".into()]);
359    }
360    if let Some(reason) = binding_policy_error(policy) {
361        return mk(Outcome::Deny, vec![], vec![reason]);
362    }
363
364    // (1) Explicit DENY rules win over everything below.
365    for r in &policy.rules {
366        if r.effect == Outcome::Deny && r.applies_to_class(&ctx.claim_class) {
367            return mk(
368                Outcome::Deny,
369                vec![r.id.clone()],
370                vec!["explicit_deny_rule".into()],
371            );
372        }
373    }
374
375    // (2) Find a permit rule for this class; if it matches but constraints fail,
376    // that is an escalation (defer), not a silent denial.
377    let mut escalations: Vec<String> = Vec::new();
378    for r in &policy.rules {
379        if r.effect != Outcome::Permit || !r.applies_to_class(&ctx.claim_class) {
380            continue;
381        }
382        let c = &r.constraints;
383        let mut blocked: Vec<String> = Vec::new();
384
385        // Monotonic-on-unknown + the universal escalation triggers.
386        if ctx.has_unknown_fields {
387            blocked.push("unknown_fields".into());
388        }
389        if policy.schema == ACCEPTANCE_POLICY_V0_3_SCHEMA {
390            match ctx.producer_credential_root.as_ref() {
391                Some(root)
392                    if c.allowed_producer_credential_roots
393                        .as_ref()
394                        .is_some_and(|roots| roots.iter().any(|allowed| allowed == root)) => {}
395                Some(_) => blocked.push("producer_credential_root_not_allowed".into()),
396                None => blocked.push("producer_credential_root_missing".into()),
397            }
398        } else if !ctx.credential_valid {
399            blocked.push("credential_invalid".into());
400        }
401        if ctx.governance_mutation && !c.allow_governance_mutation {
402            blocked.push("governance_mutation".into());
403        }
404        if ctx.target_contested && !c.allow_contested {
405            blocked.push("target_contested".into());
406        }
407        if ctx.assertion_text_mutated && !c.allow_semantic_text_change {
408            blocked.push("semantic_text_change".into());
409        }
410        if ctx.assurance_level < c.required_assurance_min {
411            blocked.push(format!(
412                "assurance_below_min({}<{})",
413                ctx.assurance_level, c.required_assurance_min
414            ));
415        }
416        if ctx.changed_findings > c.max_changed_findings {
417            blocked.push("changed_findings_over_bound".into());
418        }
419        if ctx.downstream_dependents > c.max_downstream_dependents {
420            blocked.push("downstream_over_bound".into());
421        }
422        if c.require_independence && !ctx.independence_satisfied {
423            blocked.push("independence_unsatisfied".into());
424        }
425        if c.require_method_integrity && !ctx.method_integrity_sound {
426            blocked.push("method_integrity_unattested".into());
427        }
428        if matches!(
429            policy.schema.as_str(),
430            ACCEPTANCE_POLICY_V0_2_SCHEMA | ACCEPTANCE_POLICY_V0_3_SCHEMA
431        ) {
432            let Some(binding) = ctx.execution_binding.as_ref() else {
433                blocked.push("execution_binding_missing".into());
434                escalations.extend(
435                    blocked
436                        .into_iter()
437                        .map(|reason| format!("{}:{reason}", r.id)),
438                );
439                continue;
440            };
441            if binding.validate().is_err() {
442                blocked.push("execution_binding_invalid".into());
443                escalations.extend(
444                    blocked
445                        .into_iter()
446                        .map(|reason| format!("{}:{reason}", r.id)),
447                );
448                continue;
449            }
450            for (field, allowlist, actual) in [
451                ("packet_root", &c.allowed_packet_roots, &binding.packet_root),
452                (
453                    "profile_root",
454                    &c.allowed_profile_roots,
455                    &binding.profile_root,
456                ),
457                (
458                    "verifier_capsule_root",
459                    &c.allowed_verifier_capsule_roots,
460                    &binding.verifier_capsule_root,
461                ),
462                (
463                    "result_contract_root",
464                    &c.allowed_result_contract_roots,
465                    &binding.result_contract_root,
466                ),
467            ] {
468                if !allowlist
469                    .as_ref()
470                    .is_some_and(|roots| roots.iter().any(|root| root == actual))
471                {
472                    blocked.push(format!("{field}_not_allowed"));
473                }
474            }
475            if c.required_replayability.as_deref() != Some(ctx.replayability.as_str()) {
476                blocked.push("replayability_not_allowed".into());
477            }
478        }
479
480        if blocked.is_empty() {
481            return mk(
482                Outcome::Permit,
483                vec![r.id.clone()],
484                vec!["all_constraints_satisfied".into()],
485            );
486        }
487        // This permit rule matched the class but is blocked → remember why; a
488        // matched-but-blocked permit rule means the item is plausibly valid but
489        // needs human judgment, so we DEFER (not deny).
490        escalations.extend(blocked.into_iter().map(|b| format!("{}:{}", r.id, b)));
491    }
492
493    if !escalations.is_empty() {
494        return mk(Outcome::Defer, vec![], escalations);
495    }
496
497    // (3) No deny, no matching permit → the policy default.
498    mk(
499        policy.default,
500        vec![],
501        vec![format!("default_{}", policy.default.as_str())],
502    )
503}
504
505fn binding_policy_error(policy: &AcceptancePolicy) -> Option<String> {
506    for rule in policy
507        .rules
508        .iter()
509        .filter(|rule| rule.effect == Outcome::Permit)
510    {
511        let constraints = &rule.constraints;
512        let v2_fields_present = constraints.allowed_packet_roots.is_some()
513            || constraints.allowed_profile_roots.is_some()
514            || constraints.allowed_verifier_capsule_roots.is_some()
515            || constraints.allowed_result_contract_roots.is_some()
516            || constraints.required_replayability.is_some();
517        let v3_fields_present = constraints.allowed_producer_credential_roots.is_some();
518        if policy.schema == ACCEPTANCE_POLICY_V0_1_SCHEMA {
519            if v2_fields_present || v3_fields_present {
520                return Some("policy_v0_2_constraints_under_v0_1".to_string());
521            }
522            continue;
523        }
524        if policy.schema == ACCEPTANCE_POLICY_V0_2_SCHEMA && v3_fields_present {
525            return Some("policy_v0_3_constraints_under_v0_2".to_string());
526        }
527        if !matches!(
528            policy.schema.as_str(),
529            ACCEPTANCE_POLICY_V0_2_SCHEMA | ACCEPTANCE_POLICY_V0_3_SCHEMA
530        ) {
531            continue;
532        }
533        for (field, roots) in [
534            ("packet", &constraints.allowed_packet_roots),
535            ("profile", &constraints.allowed_profile_roots),
536            (
537                "verifier_capsule",
538                &constraints.allowed_verifier_capsule_roots,
539            ),
540            (
541                "result_contract",
542                &constraints.allowed_result_contract_roots,
543            ),
544        ] {
545            let Some(roots) = roots.as_ref() else {
546                return Some(format!("policy_{field}_allowlist_missing"));
547            };
548            if roots.is_empty() || roots.iter().any(|root| !is_full_sha256_root(root)) {
549                return Some(format!("policy_{field}_allowlist_invalid"));
550            }
551        }
552        if constraints.required_replayability.as_deref() != Some("exact") {
553            return Some("policy_exact_replayability_required".to_string());
554        }
555        if policy.schema == ACCEPTANCE_POLICY_V0_3_SCHEMA {
556            let Some(roots) = constraints.allowed_producer_credential_roots.as_ref() else {
557                return Some("policy_producer_credential_allowlist_missing".to_string());
558            };
559            if roots.is_empty() || roots.iter().any(|root| !is_full_sha256_root(root)) {
560                return Some("policy_producer_credential_allowlist_invalid".to_string());
561            }
562            let unique = roots.iter().collect::<HashSet<_>>();
563            if unique.len() != roots.len() {
564                return Some("policy_producer_credential_allowlist_duplicate".to_string());
565            }
566            if roots.len() != 1 {
567                return Some("policy_producer_credential_allowlist_invalid".to_string());
568            }
569            for (_, allowed) in [
570                ("packet", &constraints.allowed_packet_roots),
571                ("profile", &constraints.allowed_profile_roots),
572                (
573                    "verifier_capsule",
574                    &constraints.allowed_verifier_capsule_roots,
575                ),
576                (
577                    "result_contract",
578                    &constraints.allowed_result_contract_roots,
579                ),
580            ] {
581                let roots = allowed.as_ref().expect("v0.3 exact roots validated above");
582                if roots.iter().collect::<HashSet<_>>().len() != roots.len() {
583                    return Some("policy_exact_allowlist_duplicate".to_string());
584                }
585            }
586        }
587    }
588    None
589}
590
591/// First 16 bytes of a digest as hex (mirrors the substrate's short-id style).
592fn hex16(digest: &[u8]) -> String {
593    digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
594}
595
596/// How the transition was authorized. `PolicyDelegation` = a human-signed policy
597/// permitted it (the engine executed); `DirectHuman` = a person signed this item;
598/// `Quorum` = a governance quorum signed. Never collapse these into one "signed".
599#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
600#[serde(rename_all = "snake_case")]
601pub enum AuthorityMode {
602    PolicyDelegation,
603    DirectHuman,
604    Quorum,
605}
606
607/// The portable, content-addressed receipt of one acceptance decision — produced
608/// by the engine, not performed by a human. It binds the proposal, the exact state
609/// roots, the policy + matched rules, the authority chain, the assurance profile,
610/// and (once recorded) the event + log inclusion proof, so any relying party can
611/// REPLAY the decision. Reading it requires no signature; only a durable
612/// endorsement/commitment does (the memo's separation of receipt from endorsement).
613#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
614pub struct DecisionCertificate {
615    #[serde(default = "default_cert_schema")]
616    pub schema: String,
617    pub id: String,
618    pub frontier_id: String,
619    pub proposal_id: String,
620    pub state_root_before: String,
621    pub state_root_after: String,
622    pub outcome: Outcome,
623    pub policy_id: String,
624    pub rule_ids: Vec<String>,
625    pub evaluator: String,
626    pub authority_mode: AuthorityMode,
627    /// The human(s)/quorum whose signed policy authorized this (for PolicyDelegation).
628    pub human_authorizers: Vec<String>,
629    /// The service/agent that executed under the policy.
630    pub executor: String,
631    /// The named assurance profile the evidence cleared (e.g.
632    /// "exact_construction_dual_check_v1"); the policy NEVER manufactures this.
633    pub assurance_profile: String,
634    pub assurance_level: u8,
635    pub claim_digest: String,
636    pub impact_tier: u8,
637    pub reasons: Vec<String>,
638    /// Selected for post-accept audit (the calibrated-sample rollout).
639    pub audit_required: bool,
640}
641
642fn default_cert_schema() -> String {
643    "vela.decision_certificate.v0.1".to_string()
644}
645
646impl DecisionCertificate {
647    /// Build a certificate from a decision + its bindings. `vdc_` prefix; the id is
648    /// the content address of everything but `id`, so it is reproducible and a
649    /// tampered certificate fails `id_is_valid`.
650    #[must_use]
651    #[allow(clippy::too_many_arguments)]
652    pub fn build(
653        decision: &Decision,
654        frontier_id: &str,
655        proposal_id: &str,
656        state_root_before: &str,
657        state_root_after: &str,
658        authority_mode: AuthorityMode,
659        human_authorizers: Vec<String>,
660        executor: &str,
661        assurance_profile: &str,
662        assurance_level: u8,
663        claim_digest: &str,
664        impact_tier: u8,
665        audit_required: bool,
666    ) -> Self {
667        let mut c = DecisionCertificate {
668            schema: default_cert_schema(),
669            id: String::new(),
670            frontier_id: frontier_id.to_string(),
671            proposal_id: proposal_id.to_string(),
672            state_root_before: state_root_before.to_string(),
673            state_root_after: state_root_after.to_string(),
674            outcome: decision.outcome,
675            policy_id: decision.policy_id.clone(),
676            rule_ids: decision.matched_rule_ids.clone(),
677            evaluator: decision.evaluator.clone(),
678            authority_mode,
679            human_authorizers,
680            executor: executor.to_string(),
681            assurance_profile: assurance_profile.to_string(),
682            assurance_level,
683            claim_digest: claim_digest.to_string(),
684            impact_tier,
685            reasons: decision.reasons.clone(),
686            audit_required,
687        };
688        c.id = c.content_address();
689        c
690    }
691
692    #[must_use]
693    pub fn content_address(&self) -> String {
694        let mut probe = self.clone();
695        probe.id = String::new();
696        let bytes = serde_json::to_vec(&probe).unwrap_or_default();
697        let mut h = Sha256::new();
698        h.update(&bytes);
699        format!("vdc_{}", hex16(&h.finalize()))
700    }
701
702    #[must_use]
703    pub fn id_is_valid(&self) -> bool {
704        self.id == self.content_address()
705    }
706}
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711    use ed25519_dalek::Signer;
712    use serde_json::json;
713    use tempfile::TempDir;
714
715    fn exact_sidon_policy() -> AcceptancePolicy {
716        let mut p = AcceptancePolicy {
717            schema: ACCEPTANCE_POLICY_V0_1_SCHEMA.to_string(),
718            id: String::new(),
719            frontier_id: "vfr_test".into(),
720            epoch: 1,
721            issued_by: vec!["reviewer:will".into()],
722            quorum: Quorum {
723                threshold: 1,
724                eligible_roles: vec!["steward".into()],
725            },
726            rules: vec![PolicyRule {
727                id: "sidon-exact-auto-v1".into(),
728                effect: Outcome::Permit,
729                claim_classes: vec!["sidon_lower_bound".into()],
730                constraints: Constraints {
731                    max_changed_findings: 1,
732                    max_downstream_dependents: 5,
733                    required_assurance_min: 3,
734                    allow_semantic_text_change: false,
735                    allow_contested: false,
736                    allow_governance_mutation: false,
737                    require_independence: true,
738                    require_method_integrity: true,
739                    ..Constraints::default()
740                },
741            }],
742            default: Outcome::Defer,
743            expires_at: "2099-12-31T23:59:59Z".into(),
744            revocation_ref: None,
745        };
746        p.id = p.content_address();
747        p
748    }
749
750    fn clean_exact_ctx() -> PolicyContext {
751        PolicyContext {
752            claim_class: "sidon_lower_bound".into(),
753            assurance_level: 3,
754            impact_tier: 2,
755            changed_findings: 1,
756            downstream_dependents: 0,
757            assertion_text_mutated: false,
758            target_contested: false,
759            governance_mutation: false,
760            independence_satisfied: true,
761            method_integrity_sound: true,
762            credential_valid: true,
763            has_unknown_fields: false,
764            replayability: "unknown".to_string(),
765            execution_binding: None,
766            producer_credential_root: None,
767        }
768    }
769
770    const NOW: &str = "2026-06-23T00:00:00Z";
771    const SIGNED_AT: &str = "2026-06-22T00:00:00Z";
772
773    fn signed_policy_bytes(policy: &AcceptancePolicy, signed_at: &str) -> (Vec<u8>, Vec<u8>) {
774        let key = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
775        let preimage = policy_signature_preimage(policy, signed_at).unwrap();
776        let signature = key.sign(&preimage);
777        let record = PolicySignatureRecord {
778            policy_id: policy.id.clone(),
779            signer_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
780            signature: hex::encode(signature.to_bytes()),
781            signed_at: signed_at.to_string(),
782        };
783        (
784            serde_json::to_vec_pretty(policy).unwrap(),
785            serde_json::to_vec_pretty(&record).unwrap(),
786        )
787    }
788
789    fn write_active_pair(policy_bytes: &[u8], signature_bytes: &[u8]) -> TempDir {
790        let temp = TempDir::new().unwrap();
791        let directory = temp.path().join(".vela/policies");
792        std::fs::create_dir_all(&directory).unwrap();
793        std::fs::write(directory.join("active.json"), policy_bytes).unwrap();
794        std::fs::write(directory.join("active.sig.json"), signature_bytes).unwrap();
795        temp
796    }
797
798    #[test]
799    fn exact_clean_witness_permits() {
800        let d = evaluate(&exact_sidon_policy(), &clean_exact_ctx(), NOW);
801        assert_eq!(d.outcome, Outcome::Permit);
802        assert_eq!(d.matched_rule_ids, vec!["sidon-exact-auto-v1"]);
803    }
804
805    #[test]
806    fn contested_target_escalates_to_defer() {
807        let mut ctx = clean_exact_ctx();
808        ctx.target_contested = true;
809        let d = evaluate(&exact_sidon_policy(), &ctx, NOW);
810        assert_eq!(d.outcome, Outcome::Defer);
811        assert!(d.reasons.iter().any(|r| r.contains("target_contested")));
812    }
813
814    #[test]
815    fn semantic_text_mutation_escalates_to_defer() {
816        let mut ctx = clean_exact_ctx();
817        ctx.assertion_text_mutated = true;
818        assert_eq!(
819            evaluate(&exact_sidon_policy(), &ctx, NOW).outcome,
820            Outcome::Defer
821        );
822    }
823
824    #[test]
825    fn low_assurance_escalates_to_defer() {
826        let mut ctx = clean_exact_ctx();
827        ctx.assurance_level = 2; // below the rule's min of 3
828        let d = evaluate(&exact_sidon_policy(), &ctx, NOW);
829        assert_eq!(d.outcome, Outcome::Defer);
830        assert!(d.reasons.iter().any(|r| r.contains("assurance_below_min")));
831    }
832
833    #[test]
834    fn monotonic_on_unknown_fields() {
835        let mut ctx = clean_exact_ctx();
836        ctx.has_unknown_fields = true;
837        assert_eq!(
838            evaluate(&exact_sidon_policy(), &ctx, NOW).outcome,
839            Outcome::Defer
840        );
841    }
842
843    #[test]
844    fn unknown_claim_class_falls_through_to_default_defer() {
845        let mut ctx = clean_exact_ctx();
846        ctx.claim_class = "literature_finding".into(); // no rule covers it
847        let d = evaluate(&exact_sidon_policy(), &ctx, NOW);
848        assert_eq!(d.outcome, Outcome::Defer);
849        assert!(d.reasons.iter().any(|r| r.contains("default")));
850    }
851
852    #[test]
853    fn expired_policy_denies() {
854        let p = exact_sidon_policy();
855        let d = evaluate(&p, &clean_exact_ctx(), "2100-01-01T00:00:00Z");
856        assert_eq!(d.outcome, Outcome::Deny);
857        assert!(d.reasons.iter().any(|r| r == "policy_expired"));
858    }
859
860    #[test]
861    fn expiry_compares_rfc3339_instants_and_malformed_values_fail_closed() {
862        let mut policy = exact_sidon_policy();
863        policy.expires_at = "2026-06-23T00:00:00Z".to_string();
864
865        assert!(!policy.is_expired("2026-06-23T01:59:59+02:00"));
866        assert!(policy.is_expired("2026-06-22T20:00:00-04:00"));
867        assert!(policy.is_expired("not-rfc3339"));
868
869        policy.id = policy.content_address();
870        let decision = evaluate(&policy, &clean_exact_ctx(), "not-rfc3339");
871        assert_eq!(decision.outcome, Outcome::Deny);
872        assert_eq!(decision.reasons, vec!["policy_expired"]);
873
874        policy.expires_at = "also-not-rfc3339".to_string();
875        assert!(policy.is_expired(NOW));
876    }
877
878    #[test]
879    fn unsupported_policy_schema_denies_even_with_a_matching_id() {
880        let mut policy = exact_sidon_policy();
881        policy.schema = "vela.acceptance_policy.v999".to_string();
882        policy.id = policy.content_address();
883        let decision = evaluate(&policy, &clean_exact_ctx(), NOW);
884        assert_eq!(decision.outcome, Outcome::Deny);
885        assert_eq!(decision.reasons, vec!["policy_schema_unsupported"]);
886    }
887
888    #[test]
889    fn policy_scoped_producer_credential_is_exact_and_narrower_than_registry_status() {
890        let root = |digit: char| format!("sha256:{}", digit.to_string().repeat(64));
891        let binding = ExecutionBindingV1 {
892            schema: crate::receipt_v1::EXECUTION_BINDING_SCHEMA.to_string(),
893            packet_root: root('1'),
894            profile_root: root('2'),
895            verifier_capsule_root: root('3'),
896            result_contract_root: root('4'),
897        };
898        let credential = root('5');
899        let mut policy = exact_sidon_policy();
900        policy.schema = ACCEPTANCE_POLICY_V0_3_SCHEMA.to_string();
901        let constraints = &mut policy.rules[0].constraints;
902        constraints.allowed_packet_roots = Some(vec![binding.packet_root.clone()]);
903        constraints.allowed_profile_roots = Some(vec![binding.profile_root.clone()]);
904        constraints.allowed_verifier_capsule_roots =
905            Some(vec![binding.verifier_capsule_root.clone()]);
906        constraints.allowed_result_contract_roots =
907            Some(vec![binding.result_contract_root.clone()]);
908        constraints.allowed_producer_credential_roots = Some(vec![credential.clone()]);
909        constraints.required_replayability = Some("exact".to_string());
910        policy.id = policy.content_address();
911
912        let mut context = clean_exact_ctx();
913        context.credential_valid = false;
914        context.replayability = "exact".to_string();
915        context.execution_binding = Some(binding);
916        context.producer_credential_root = Some(credential.clone());
917        let decision = evaluate(&policy, &context, NOW);
918        assert_eq!(decision.outcome, Outcome::Permit, "{decision:?}");
919        assert_eq!(decision.evaluator, EVALUATOR_VERSION_V0_3);
920
921        context.credential_valid = true;
922        context.producer_credential_root = Some(root('6'));
923        let wrong = evaluate(&policy, &context, NOW);
924        assert_eq!(wrong.outcome, Outcome::Defer);
925        assert!(
926            wrong
927                .reasons
928                .iter()
929                .any(|reason| reason.ends_with("producer_credential_root_not_allowed"))
930        );
931
932        context.producer_credential_root = None;
933        let missing = evaluate(&policy, &context, NOW);
934        assert_eq!(missing.outcome, Outcome::Defer);
935        assert!(
936            missing
937                .reasons
938                .iter()
939                .any(|reason| reason.ends_with("producer_credential_root_missing"))
940        );
941
942        let mut duplicate = policy.clone();
943        duplicate.rules[0]
944            .constraints
945            .allowed_producer_credential_roots = Some(vec![credential.clone(), credential]);
946        duplicate.id = duplicate.content_address();
947        let denied = evaluate(&duplicate, &context, NOW);
948        assert_eq!(denied.outcome, Outcome::Deny);
949        assert_eq!(
950            denied.reasons,
951            vec!["policy_producer_credential_allowlist_duplicate"]
952        );
953    }
954
955    #[test]
956    fn tampered_policy_id_denies() {
957        let mut p = exact_sidon_policy();
958        p.rules[0].constraints.required_assurance_min = 0; // change body, keep old id
959        let d = evaluate(&p, &clean_exact_ctx(), NOW);
960        assert_eq!(d.outcome, Outcome::Deny);
961        assert!(d.reasons.iter().any(|r| r == "policy_id_mismatch"));
962    }
963
964    #[test]
965    fn revoked_policy_denies() {
966        let mut p = exact_sidon_policy();
967        p.revocation_ref = Some("vrv_x".into());
968        p.id = p.content_address();
969        assert_eq!(evaluate(&p, &clean_exact_ctx(), NOW).outcome, Outcome::Deny);
970    }
971
972    #[test]
973    fn governance_mutation_without_permission_escalates() {
974        let mut ctx = clean_exact_ctx();
975        ctx.governance_mutation = true;
976        let d = evaluate(&exact_sidon_policy(), &ctx, NOW);
977        assert_eq!(d.outcome, Outcome::Defer);
978        assert!(d.reasons.iter().any(|r| r.contains("governance_mutation")));
979    }
980
981    #[test]
982    fn evaluation_is_deterministic() {
983        let p = exact_sidon_policy();
984        let ctx = clean_exact_ctx();
985        assert_eq!(evaluate(&p, &ctx, NOW), evaluate(&p, &ctx, NOW));
986    }
987
988    #[test]
989    fn policy_context_digest_is_canonical_and_binds_every_live_field() {
990        let baseline = clean_exact_ctx();
991        let digest = baseline.policy_language_digest().unwrap();
992        assert!(digest.starts_with("sha256:"));
993        assert_eq!(digest, baseline.policy_language_digest().unwrap());
994
995        let mut variants = Vec::new();
996        let mut value = baseline.clone();
997        value.claim_class.push_str("_changed");
998        variants.push(value);
999        let mut value = baseline.clone();
1000        value.assurance_level += 1;
1001        variants.push(value);
1002        let mut value = baseline.clone();
1003        value.impact_tier += 1;
1004        variants.push(value);
1005        let mut value = baseline.clone();
1006        value.changed_findings += 1;
1007        variants.push(value);
1008        let mut value = baseline.clone();
1009        value.downstream_dependents += 1;
1010        variants.push(value);
1011        let mut value = baseline.clone();
1012        value.assertion_text_mutated = !value.assertion_text_mutated;
1013        variants.push(value);
1014        let mut value = baseline.clone();
1015        value.target_contested = !value.target_contested;
1016        variants.push(value);
1017        let mut value = baseline.clone();
1018        value.governance_mutation = !value.governance_mutation;
1019        variants.push(value);
1020        let mut value = baseline.clone();
1021        value.independence_satisfied = !value.independence_satisfied;
1022        variants.push(value);
1023        let mut value = baseline.clone();
1024        value.method_integrity_sound = !value.method_integrity_sound;
1025        variants.push(value);
1026        let mut value = baseline.clone();
1027        value.credential_valid = !value.credential_valid;
1028        variants.push(value);
1029        let mut value = baseline.clone();
1030        value.has_unknown_fields = !value.has_unknown_fields;
1031        variants.push(value);
1032        let mut value = baseline.clone();
1033        value.replayability = "exact".to_string();
1034        variants.push(value);
1035        let mut value = baseline.clone();
1036        value.execution_binding = Some(ExecutionBindingV1 {
1037            schema: crate::receipt_v1::EXECUTION_BINDING_SCHEMA.to_string(),
1038            packet_root: format!("sha256:{}", "1".repeat(64)),
1039            profile_root: format!("sha256:{}", "2".repeat(64)),
1040            verifier_capsule_root: format!("sha256:{}", "3".repeat(64)),
1041            result_contract_root: format!("sha256:{}", "4".repeat(64)),
1042        });
1043        variants.push(value);
1044        let mut value = baseline.clone();
1045        value.producer_credential_root = Some(format!("sha256:{}", "5".repeat(64)));
1046        variants.push(value);
1047
1048        for variant in variants {
1049            assert_ne!(digest, variant.policy_language_digest().unwrap());
1050        }
1051    }
1052
1053    #[test]
1054    fn policy_context_wire_requires_replayability() {
1055        let mut value = serde_json::to_value(clean_exact_ctx()).unwrap();
1056        value.as_object_mut().unwrap().remove("replayability");
1057        assert!(serde_json::from_value::<PolicyContext>(value).is_err());
1058    }
1059
1060    #[test]
1061    fn content_address_is_stable_and_prefixed() {
1062        let p = exact_sidon_policy();
1063        assert!(p.id.starts_with("vap_"));
1064        assert!(p.id_is_valid());
1065
1066        let mut body = p.clone();
1067        body.id.clear();
1068        let canonical = crate::canonical::to_canonical_bytes(&body).unwrap();
1069        let mut digest = Sha256::new();
1070        digest.update(canonical);
1071        assert_eq!(p.id, format!("vap_{}", hex16(&digest.finalize())));
1072    }
1073
1074    #[test]
1075    fn bounded_closed_parser_accepts_only_the_supported_policy_shape() {
1076        let policy = exact_sidon_policy();
1077        let (policy_bytes, signature_bytes) = signed_policy_bytes(&policy, SIGNED_AT);
1078        let verified = verify_policy_signature_bytes(
1079            &policy_bytes,
1080            &signature_bytes,
1081            Some(&policy.id),
1082            "test policy",
1083        )
1084        .unwrap();
1085        assert_eq!(verified.policy, policy);
1086
1087        let mut cases = Vec::new();
1088        let mut value = serde_json::to_value(&policy).unwrap();
1089        value["unexpected"] = json!(true);
1090        cases.push(value);
1091        let mut value = serde_json::to_value(&policy).unwrap();
1092        value["quorum"]["unexpected"] = json!(true);
1093        cases.push(value);
1094        let mut value = serde_json::to_value(&policy).unwrap();
1095        value["rules"][0]["unexpected"] = json!(true);
1096        cases.push(value);
1097        let mut value = serde_json::to_value(&policy).unwrap();
1098        value["rules"][0]["constraints"]["unexpected"] = json!(true);
1099        cases.push(value);
1100
1101        for value in cases {
1102            let error = verify_policy_signature_bytes(
1103                &serde_json::to_vec(&value).unwrap(),
1104                &signature_bytes,
1105                None,
1106                "test policy",
1107            )
1108            .unwrap_err();
1109            assert!(error.contains("unknown field `unexpected`"), "{error}");
1110        }
1111
1112        let mut missing_schema = serde_json::to_value(&policy).unwrap();
1113        missing_schema.as_object_mut().unwrap().remove("schema");
1114        let error = verify_policy_signature_bytes(
1115            &serde_json::to_vec(&missing_schema).unwrap(),
1116            &signature_bytes,
1117            None,
1118            "test policy",
1119        )
1120        .unwrap_err();
1121        assert!(error.contains("missing field `schema`"), "{error}");
1122
1123        let mut unsupported_schema = serde_json::to_value(&policy).unwrap();
1124        unsupported_schema["schema"] = json!("vela.acceptance_policy.v999");
1125        let error = verify_policy_signature_bytes(
1126            &serde_json::to_vec(&unsupported_schema).unwrap(),
1127            &signature_bytes,
1128            None,
1129            "test policy",
1130        )
1131        .unwrap_err();
1132        assert!(error.contains("schema must be"), "{error}");
1133
1134        let mut bad_expiry = serde_json::to_value(&policy).unwrap();
1135        bad_expiry["expires_at"] = json!("not-rfc3339");
1136        let error = verify_policy_signature_bytes(
1137            &serde_json::to_vec(&bad_expiry).unwrap(),
1138            &signature_bytes,
1139            None,
1140            "test policy",
1141        )
1142        .unwrap_err();
1143        assert!(error.contains("expires_at must be RFC3339"), "{error}");
1144
1145        let mut signature_value: Value = serde_json::from_slice(&signature_bytes).unwrap();
1146        signature_value["unexpected"] = json!(true);
1147        let error = verify_policy_signature_bytes(
1148            &policy_bytes,
1149            &serde_json::to_vec(&signature_value).unwrap(),
1150            None,
1151            "test policy",
1152        )
1153        .unwrap_err();
1154        assert!(error.contains("unknown field `unexpected`"), "{error}");
1155    }
1156
1157    #[test]
1158    fn duplicate_names_are_rejected_in_policy_and_signature_envelopes() {
1159        let policy = exact_sidon_policy();
1160        let (policy_bytes, signature_bytes) = signed_policy_bytes(&policy, SIGNED_AT);
1161        let policy_json = String::from_utf8(policy_bytes).unwrap();
1162        for malicious in [
1163            policy_json.replacen("\"epoch\": 1", "\"epoch\": 1,\n  \"epoch\": 2", 1),
1164            policy_json.replacen("\"epoch\": 1", "\"epoch\": 1,\n  \"e\\u0070och\": 2", 1),
1165            policy_json.replacen(
1166                "\"threshold\": 1",
1167                "\"threshold\": 1,\n    \"threshold\": 2",
1168                1,
1169            ),
1170        ] {
1171            let error = verify_policy_signature_bytes(
1172                malicious.as_bytes(),
1173                &signature_bytes,
1174                None,
1175                "test policy",
1176            )
1177            .unwrap_err();
1178            assert!(error.contains("duplicate object name"), "{error}");
1179        }
1180
1181        let signature_json = String::from_utf8(signature_bytes).unwrap();
1182        let malicious = signature_json.replacen(
1183            &format!("\"signed_at\": \"{SIGNED_AT}\""),
1184            &format!("\"signed_at\": \"{SIGNED_AT}\",\n  \"signed_at\": \"2099-01-01T00:00:00Z\""),
1185            1,
1186        );
1187        let policy_bytes = serde_json::to_vec(&policy).unwrap();
1188        let error =
1189            verify_policy_signature_bytes(&policy_bytes, malicious.as_bytes(), None, "test policy")
1190                .unwrap_err();
1191        assert!(error.contains("duplicate object name"), "{error}");
1192    }
1193
1194    #[test]
1195    fn parser_budgets_reject_oversized_and_excessively_deep_governance_json() {
1196        let policy = exact_sidon_policy();
1197        let (_, signature_bytes) = signed_policy_bytes(&policy, SIGNED_AT);
1198        let oversized = vec![b' '; POLICY_JSON_MAX_BYTES + 1];
1199        let error =
1200            verify_policy_signature_bytes(&oversized, &signature_bytes, None, "test policy")
1201                .unwrap_err();
1202        assert!(error.contains("limit is 65536 bytes"), "{error}");
1203
1204        let deep = format!(
1205            "{}0{}",
1206            "{\"nested\":".repeat(GOVERNANCE_JSON_MAX_DEPTH + 1),
1207            "}".repeat(GOVERNANCE_JSON_MAX_DEPTH + 1)
1208        );
1209        let error =
1210            verify_policy_signature_bytes(deep.as_bytes(), &signature_bytes, None, "test policy")
1211                .unwrap_err();
1212        assert!(error.contains("JSON depth"), "{error}");
1213
1214        let policy_bytes = serde_json::to_vec(&policy).unwrap();
1215        let oversized_signature = vec![b' '; POLICY_SIGNATURE_JSON_MAX_BYTES + 1];
1216        let error =
1217            verify_policy_signature_bytes(&policy_bytes, &oversized_signature, None, "test policy")
1218                .unwrap_err();
1219        assert!(error.contains("limit is 8192 bytes"), "{error}");
1220    }
1221
1222    #[test]
1223    fn signatures_require_supported_policy_and_bound_signed_at() {
1224        let policy = exact_sidon_policy();
1225        let (policy_bytes, signature_bytes) = signed_policy_bytes(&policy, SIGNED_AT);
1226
1227        let mut rewritten: PolicySignatureRecord =
1228            serde_json::from_slice(&signature_bytes).unwrap();
1229        rewritten.signed_at = "2026-06-22T00:00:01Z".to_string();
1230        let error = verify_policy_signature_bytes(
1231            &policy_bytes,
1232            &serde_json::to_vec(&rewritten).unwrap(),
1233            None,
1234            "test policy",
1235        )
1236        .unwrap_err();
1237        assert!(error.contains("signature does not verify"), "{error}");
1238
1239        rewritten.signed_at = "not-rfc3339".to_string();
1240        let error = verify_policy_signature_bytes(
1241            &policy_bytes,
1242            &serde_json::to_vec(&rewritten).unwrap(),
1243            None,
1244            "test policy",
1245        )
1246        .unwrap_err();
1247        assert!(error.contains("signed_at must be RFC3339"), "{error}");
1248        assert!(policy_signature_preimage(&policy, "not-rfc3339").is_err());
1249
1250        let key = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
1251        let unbound_signature = key.sign(&crate::canonical::to_canonical_bytes(&policy).unwrap());
1252        let unbound_record = PolicySignatureRecord {
1253            policy_id: policy.id.clone(),
1254            signer_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
1255            signature: hex::encode(unbound_signature.to_bytes()),
1256            signed_at: SIGNED_AT.to_string(),
1257        };
1258        let error = verify_policy_signature_bytes(
1259            &policy_bytes,
1260            &serde_json::to_vec(&unbound_record).unwrap(),
1261            None,
1262            "test policy",
1263        )
1264        .unwrap_err();
1265        assert!(error.contains("signature does not verify"), "{error}");
1266
1267        let mut changed = policy.clone();
1268        changed.expires_at = "2098-12-31T23:59:59Z".to_string();
1269        changed.id = changed.content_address();
1270        let mut stale_record: PolicySignatureRecord =
1271            serde_json::from_slice(&signature_bytes).unwrap();
1272        stale_record.policy_id = changed.id.clone();
1273        let error = verify_policy_signature_bytes(
1274            &serde_json::to_vec(&changed).unwrap(),
1275            &serde_json::to_vec(&stale_record).unwrap(),
1276            None,
1277            "test policy",
1278        )
1279        .unwrap_err();
1280        assert!(error.contains("signature does not verify"), "{error}");
1281    }
1282
1283    #[test]
1284    fn active_pair_accepts_only_current_id_and_bound_signature() {
1285        let policy = exact_sidon_policy();
1286        let (policy_bytes, signature_bytes) = signed_policy_bytes(&policy, SIGNED_AT);
1287
1288        let mut wrong_id = policy.clone();
1289        wrong_id.id = "vap_00000000000000000000000000000000".to_string();
1290        let temp = write_active_pair(&serde_json::to_vec(&wrong_id).unwrap(), &signature_bytes);
1291        let error = load_active_policy_snapshot(temp.path())
1292            .expect_err("a non-current content address must be a strict error");
1293        assert!(error.contains("id does not re-derive"), "{error}");
1294
1295        let key = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
1296        let unbound = key.sign(&crate::canonical::to_canonical_bytes(&policy).unwrap());
1297        let record = PolicySignatureRecord {
1298            policy_id: policy.id,
1299            signer_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
1300            signature: hex::encode(unbound.to_bytes()),
1301            signed_at: SIGNED_AT.to_string(),
1302        };
1303        let temp = write_active_pair(&policy_bytes, &serde_json::to_vec(&record).unwrap());
1304        let error = load_active_policy_snapshot(temp.path())
1305            .expect_err("an unbound signature must be a strict error");
1306        assert!(error.contains("signature does not verify"), "{error}");
1307    }
1308
1309    #[test]
1310    fn malformed_or_stale_unsigned_policy_is_broken_not_staged() {
1311        let temp = TempDir::new().unwrap();
1312        let directory = temp.path().join(".vela/policies");
1313        std::fs::create_dir_all(&directory).unwrap();
1314        std::fs::write(directory.join("active.json"), b"{not-json\n").unwrap();
1315        let error = load_active_policy_snapshot(temp.path())
1316            .expect_err("malformed unsigned bytes must not become a staged policy");
1317        assert!(error.contains("active policy parse"), "{error}");
1318
1319        let mut stale = exact_sidon_policy();
1320        stale.id = "vap_00000000000000000000000000000000".to_string();
1321        std::fs::write(
1322            directory.join("active.json"),
1323            serde_json::to_vec_pretty(&stale).unwrap(),
1324        )
1325        .unwrap();
1326        let error = load_active_policy_snapshot(temp.path())
1327            .expect_err("a stale unsigned id must not become a staged policy");
1328        assert!(error.contains("id does not re-derive"), "{error}");
1329    }
1330
1331    #[test]
1332    fn active_snapshot_retains_the_policy_parsed_from_its_exact_bytes() {
1333        let temp = TempDir::new().unwrap();
1334        let directory = temp.path().join(".vela/policies");
1335        std::fs::create_dir_all(&directory).unwrap();
1336
1337        let original = exact_sidon_policy();
1338        let original_bytes = serde_json::to_vec_pretty(&original).unwrap();
1339        std::fs::write(directory.join("active.json"), &original_bytes).unwrap();
1340        let snapshot = load_active_policy_snapshot(temp.path()).unwrap();
1341
1342        let mut replacement = original.clone();
1343        replacement.epoch += 1;
1344        replacement.id = replacement.content_address();
1345        std::fs::write(
1346            directory.join("active.json"),
1347            serde_json::to_vec_pretty(&replacement).unwrap(),
1348        )
1349        .unwrap();
1350
1351        assert_eq!(
1352            snapshot.policy_bytes.as_deref(),
1353            Some(original_bytes.as_slice())
1354        );
1355        assert_eq!(
1356            snapshot.policy().map(|policy| policy.id.as_str()),
1357            Some(original.id.as_str())
1358        );
1359        assert_ne!(snapshot.policy().unwrap().id, replacement.id);
1360    }
1361
1362    #[test]
1363    fn decision_certificate_binds_and_verifies() {
1364        let p = exact_sidon_policy();
1365        let d = evaluate(&p, &clean_exact_ctx(), NOW);
1366        let c = DecisionCertificate::build(
1367            &d,
1368            "vfr_test",
1369            "vpr_abc",
1370            "sha256:before",
1371            "sha256:after",
1372            AuthorityMode::PolicyDelegation,
1373            vec!["reviewer:will".into()],
1374            "service:vela-policy-engine",
1375            "exact_construction_dual_check_v1",
1376            3,
1377            "sha256:claim",
1378            2,
1379            true,
1380        );
1381        assert!(c.id.starts_with("vdc_"));
1382        assert!(c.id_is_valid());
1383        assert_eq!(c.outcome, Outcome::Permit);
1384        assert_eq!(c.authority_mode, AuthorityMode::PolicyDelegation);
1385        // The authority is the policy a human signed, NOT a per-item human click.
1386        assert_eq!(c.human_authorizers, vec!["reviewer:will"]);
1387        assert_eq!(c.executor, "service:vela-policy-engine");
1388        // Tamper detection.
1389        let mut bad = c.clone();
1390        bad.outcome = Outcome::Deny;
1391        assert!(!bad.id_is_valid());
1392    }
1393}
1394
1395/// The signature envelope over a SEALED policy: the one governance act.
1396///
1397/// Signatures are Ed25519 over [`policy_signature_preimage`], which binds both
1398/// the sealed policy and `signed_at`. Every other signature preimage is rejected.
1399#[derive(Debug, Clone, Serialize, Deserialize)]
1400#[serde(deny_unknown_fields)]
1401pub struct PolicySignatureRecord {
1402    pub policy_id: String,
1403    pub signer_pubkey_hex: String,
1404    pub signature: String,
1405    pub signed_at: String,
1406}
1407
1408/// A policy that passed loading checks: sealed id re-derives and the
1409/// signature verifies over the sealed bytes. AUTHORITY still requires the
1410/// caller to check the signer is a registered human reviewer on the
1411/// frontier — the file system is not an actor table.
1412#[derive(Debug, Clone)]
1413pub struct VerifiedPolicy {
1414    pub policy: AcceptancePolicy,
1415    pub signer_pubkey_hex: String,
1416    pub signed_at: String,
1417}
1418
1419/// Classification of the mutable active-policy pointer. Only `Active` carries
1420/// a [`VerifiedPolicy`]. Any other signed encoding is a strict load error.
1421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1422pub enum ActivePolicyMode {
1423    Absent,
1424    StagedUnsigned,
1425    Active,
1426}
1427
1428impl ActivePolicyMode {
1429    #[must_use]
1430    pub fn as_str(self) -> &'static str {
1431        match self {
1432            Self::Absent => "absent",
1433            Self::StagedUnsigned => "staged_unsigned",
1434            Self::Active => "active",
1435        }
1436    }
1437}
1438
1439/// One read of both mutable active-policy paths while the caller owns its
1440/// frontier recovery barrier. The exact bytes (or exact absence) are retained
1441/// so callers can bind the same snapshot into a marker-time read set and copy
1442/// the same bytes into a content-addressed policy snapshot.
1443#[derive(Debug, Clone)]
1444pub struct ActivePolicySnapshot {
1445    pub policy_bytes: Option<Vec<u8>>,
1446    pub signature_bytes: Option<Vec<u8>>,
1447    pub verified: Option<VerifiedPolicy>,
1448    pub mode: ActivePolicyMode,
1449    policy: Option<AcceptancePolicy>,
1450}
1451
1452impl ActivePolicySnapshot {
1453    /// Return the policy parsed from this exact byte snapshot. This never
1454    /// re-reads the mutable active-policy pointer.
1455    #[must_use]
1456    pub fn policy(&self) -> Option<&AcceptancePolicy> {
1457        self.policy.as_ref()
1458    }
1459}
1460
1461// Governance files are deliberately much smaller than general repository
1462// objects. The byte ceiling is the first bound; the structural budgets prevent
1463// a compact adversarial document from spending unbounded parser work.
1464pub const POLICY_JSON_MAX_BYTES: usize = 64 * 1024;
1465pub const POLICY_SIGNATURE_JSON_MAX_BYTES: usize = 8 * 1024;
1466const GOVERNANCE_JSON_MAX_DEPTH: usize = 16;
1467const GOVERNANCE_JSON_MAX_NODES: usize = 4_096;
1468const GOVERNANCE_JSON_MAX_OBJECT_FIELDS: usize = 2_048;
1469const GOVERNANCE_JSON_MAX_ARRAY_ELEMENTS: usize = 2_048;
1470const GOVERNANCE_JSON_MAX_STRING_BYTES: usize = 16 * 1024;
1471
1472#[derive(Debug, Clone, Copy)]
1473struct GovernanceJsonLimits {
1474    bytes: usize,
1475}
1476
1477#[derive(Debug)]
1478struct GovernanceJsonState {
1479    nodes: usize,
1480    object_fields: usize,
1481    array_elements: usize,
1482}
1483
1484impl GovernanceJsonState {
1485    fn bump_node<E: de::Error>(&mut self, path: &str) -> Result<(), E> {
1486        self.nodes = self.nodes.saturating_add(1);
1487        if self.nodes > GOVERNANCE_JSON_MAX_NODES {
1488            return Err(E::custom(format!(
1489                "{path}: JSON node budget exceeds {GOVERNANCE_JSON_MAX_NODES}"
1490            )));
1491        }
1492        Ok(())
1493    }
1494
1495    fn bump_object_field<E: de::Error>(&mut self, path: &str) -> Result<(), E> {
1496        self.object_fields = self.object_fields.saturating_add(1);
1497        if self.object_fields > GOVERNANCE_JSON_MAX_OBJECT_FIELDS {
1498            return Err(E::custom(format!(
1499                "{path}: object-field budget exceeds {GOVERNANCE_JSON_MAX_OBJECT_FIELDS}"
1500            )));
1501        }
1502        Ok(())
1503    }
1504
1505    fn bump_array_element<E: de::Error>(&mut self, path: &str) -> Result<(), E> {
1506        self.array_elements = self.array_elements.saturating_add(1);
1507        if self.array_elements > GOVERNANCE_JSON_MAX_ARRAY_ELEMENTS {
1508            return Err(E::custom(format!(
1509                "{path}: array-element budget exceeds {GOVERNANCE_JSON_MAX_ARRAY_ELEMENTS}"
1510            )));
1511        }
1512        Ok(())
1513    }
1514
1515    fn check_depth<E: de::Error>(&self, path: &str, depth: usize) -> Result<(), E> {
1516        if depth > GOVERNANCE_JSON_MAX_DEPTH {
1517            return Err(E::custom(format!(
1518                "{path}: JSON depth is {depth}; limit is {GOVERNANCE_JSON_MAX_DEPTH}"
1519            )));
1520        }
1521        Ok(())
1522    }
1523
1524    fn check_string<E: de::Error>(&self, path: &str, value: &str) -> Result<(), E> {
1525        if value.len() > GOVERNANCE_JSON_MAX_STRING_BYTES {
1526            return Err(E::custom(format!(
1527                "{path}: string is {} bytes; limit is {GOVERNANCE_JSON_MAX_STRING_BYTES} bytes",
1528                value.len()
1529            )));
1530        }
1531        Ok(())
1532    }
1533}
1534
1535struct GovernanceValueSeed<'a> {
1536    state: &'a mut GovernanceJsonState,
1537    parent_depth: usize,
1538    path: String,
1539}
1540
1541impl<'de> DeserializeSeed<'de> for GovernanceValueSeed<'_> {
1542    type Value = Value;
1543
1544    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1545    where
1546        D: de::Deserializer<'de>,
1547    {
1548        self.state.bump_node::<D::Error>(&self.path)?;
1549        deserializer.deserialize_any(GovernanceValueVisitor {
1550            state: self.state,
1551            parent_depth: self.parent_depth,
1552            path: self.path,
1553        })
1554    }
1555}
1556
1557struct GovernanceValueVisitor<'a> {
1558    state: &'a mut GovernanceJsonState,
1559    parent_depth: usize,
1560    path: String,
1561}
1562
1563impl<'de> Visitor<'de> for GovernanceValueVisitor<'_> {
1564    type Value = Value;
1565
1566    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1567        formatter.write_str("bounded JSON without duplicate object names")
1568    }
1569
1570    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
1571        Ok(Value::Bool(value))
1572    }
1573
1574    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
1575        Ok(Value::Number(value.into()))
1576    }
1577
1578    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
1579        Ok(Value::Number(value.into()))
1580    }
1581
1582    fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1583    where
1584        E: de::Error,
1585    {
1586        serde_json::Number::from_f64(value)
1587            .map(Value::Number)
1588            .ok_or_else(|| E::custom(format!("{}: non-finite number", self.path)))
1589    }
1590
1591    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1592    where
1593        E: de::Error,
1594    {
1595        self.state.check_string::<E>(&self.path, value)?;
1596        Ok(Value::String(value.to_string()))
1597    }
1598
1599    fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
1600    where
1601        E: de::Error,
1602    {
1603        self.visit_str(value)
1604    }
1605
1606    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1607    where
1608        E: de::Error,
1609    {
1610        self.state.check_string::<E>(&self.path, &value)?;
1611        Ok(Value::String(value))
1612    }
1613
1614    fn visit_none<E>(self) -> Result<Self::Value, E> {
1615        Ok(Value::Null)
1616    }
1617
1618    fn visit_unit<E>(self) -> Result<Self::Value, E> {
1619        Ok(Value::Null)
1620    }
1621
1622    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1623    where
1624        A: SeqAccess<'de>,
1625    {
1626        let depth = self.parent_depth.saturating_add(1);
1627        self.state.check_depth::<A::Error>(&self.path, depth)?;
1628        let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(256));
1629        let mut index = 0usize;
1630        loop {
1631            let child_path = format!("{}[{index}]", self.path);
1632            let seed = GovernanceValueSeed {
1633                state: self.state,
1634                parent_depth: depth,
1635                path: child_path.clone(),
1636            };
1637            let Some(value) = sequence.next_element_seed(seed)? else {
1638                break;
1639            };
1640            self.state.bump_array_element::<A::Error>(&child_path)?;
1641            values.push(value);
1642            index = index.saturating_add(1);
1643        }
1644        Ok(Value::Array(values))
1645    }
1646
1647    fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
1648    where
1649        A: MapAccess<'de>,
1650    {
1651        let depth = self.parent_depth.saturating_add(1);
1652        self.state.check_depth::<A::Error>(&self.path, depth)?;
1653        let mut value = Map::new();
1654        let mut names = HashSet::new();
1655        while let Some(key) = entries.next_key::<String>()? {
1656            self.state.check_string::<A::Error>(&self.path, &key)?;
1657            let child_path = format!("{}.{}", self.path, key);
1658            self.state.bump_object_field::<A::Error>(&child_path)?;
1659            if !names.insert(key.clone()) {
1660                return Err(<A::Error as de::Error>::custom(format!(
1661                    "{child_path}: duplicate object name `{key}`"
1662                )));
1663            }
1664            let item = entries.next_value_seed(GovernanceValueSeed {
1665                state: self.state,
1666                parent_depth: depth,
1667                path: child_path,
1668            })?;
1669            value.insert(key, item);
1670        }
1671        Ok(Value::Object(value))
1672    }
1673}
1674
1675fn parse_bounded_governance_json<T: DeserializeOwned>(
1676    bytes: &[u8],
1677    limits: GovernanceJsonLimits,
1678    label: &str,
1679) -> Result<T, String> {
1680    if bytes.len() > limits.bytes {
1681        return Err(format!(
1682            "{label} parse: encoded JSON is {} bytes; limit is {} bytes",
1683            bytes.len(),
1684            limits.bytes
1685        ));
1686    }
1687    let mut state = GovernanceJsonState {
1688        nodes: 0,
1689        object_fields: 0,
1690        array_elements: 0,
1691    };
1692    let mut deserializer = serde_json::Deserializer::from_slice(bytes);
1693    let value = GovernanceValueSeed {
1694        state: &mut state,
1695        parent_depth: 0,
1696        path: "$".to_string(),
1697    }
1698    .deserialize(&mut deserializer)
1699    .map_err(|error| format!("{label} parse: {error}"))?;
1700    deserializer
1701        .end()
1702        .map_err(|error| format!("{label} parse: {error}"))?;
1703    serde_json::from_value(value).map_err(|error| format!("{label} parse: {error}"))
1704}
1705
1706fn validate_rfc3339(label: &str, value: &str) -> Result<(), String> {
1707    chrono::DateTime::parse_from_rfc3339(value)
1708        .map(|_| ())
1709        .map_err(|error| format!("{label} must be RFC3339: {error}"))
1710}
1711
1712fn validate_supported_policy(policy: &AcceptancePolicy, label: &str) -> Result<(), String> {
1713    if !matches!(
1714        policy.schema.as_str(),
1715        ACCEPTANCE_POLICY_V0_1_SCHEMA
1716            | ACCEPTANCE_POLICY_V0_2_SCHEMA
1717            | ACCEPTANCE_POLICY_V0_3_SCHEMA
1718    ) {
1719        return Err(format!(
1720            "{label} schema must be {ACCEPTANCE_POLICY_V0_1_SCHEMA}, {ACCEPTANCE_POLICY_V0_2_SCHEMA}, or {ACCEPTANCE_POLICY_V0_3_SCHEMA}, got {}",
1721            policy.schema
1722        ));
1723    }
1724    if let Some(reason) = binding_policy_error(policy) {
1725        return Err(format!("{label} binding constraints are invalid: {reason}"));
1726    }
1727    validate_rfc3339(&format!("{label} expires_at"), &policy.expires_at)
1728}
1729
1730const POLICY_SIGNATURE_INPUT_SCHEMA: &str = "vela.policy-signature-input.v1";
1731
1732#[derive(Serialize)]
1733struct PolicySignatureInput<'a> {
1734    schema: &'static str,
1735    policy: &'a AcceptancePolicy,
1736    signed_at: &'a str,
1737}
1738
1739/// Domain-separated bytes signed by every newly issued policy signature.
1740/// Binding `signed_at` prevents an attacker from rewriting policy chronology
1741/// while retaining a valid signature over the policy body.
1742pub fn policy_signature_preimage(
1743    policy: &AcceptancePolicy,
1744    signed_at: &str,
1745) -> Result<Vec<u8>, String> {
1746    validate_supported_policy(policy, "policy signature input")?;
1747    validate_rfc3339("policy signed_at", signed_at)?;
1748    crate::canonical::to_canonical_bytes(&PolicySignatureInput {
1749        schema: POLICY_SIGNATURE_INPUT_SCHEMA,
1750        policy,
1751        signed_at,
1752    })
1753    .map_err(|error| format!("canonical policy signature input: {error}"))
1754}
1755
1756/// Frontier-scoped authority resolved from a verified singular policy
1757/// signature. Actor ids, rather than public keys, are the durable human
1758/// authorizers carried into decision certificates.
1759#[derive(Debug, Clone, PartialEq, Eq)]
1760pub struct PolicyAuthority {
1761    pub human_authorizers: Vec<String>,
1762}
1763
1764/// Resolve the human authority behind a cryptographically valid policy.
1765///
1766/// Loading first proves a closed, supported policy shape and a signature that
1767/// binds its timestamp. This frontier-scoped predicate then proves lifecycle
1768/// and actor authority for both live Permit and strict replay. The current
1769/// signature envelope contains one signature, so it can satisfy only a
1770/// one-person quorum whose eligible roles admit a reviewer or steward.
1771pub fn resolve_policy_authority(
1772    project: &crate::project::Project,
1773    verified: &VerifiedPolicy,
1774    decision_time: &str,
1775) -> Result<PolicyAuthority, String> {
1776    resolve_policy_authority_inner(project, verified, decision_time)
1777}
1778
1779fn resolve_policy_authority_inner(
1780    project: &crate::project::Project,
1781    verified: &VerifiedPolicy,
1782    decision_time: &str,
1783) -> Result<PolicyAuthority, String> {
1784    validate_supported_policy(&verified.policy, "verified policy")?;
1785    if !verified.policy.id_is_valid() {
1786        return Err(format!(
1787            "verified policy {} id does not re-derive",
1788            verified.policy.id
1789        ));
1790    }
1791    validate_rfc3339("policy decision time", decision_time)?;
1792    if verified.policy.is_expired(decision_time) {
1793        return Err(format!(
1794            "policy {} is expired at decision time",
1795            verified.policy.id
1796        ));
1797    }
1798    if verified.policy.revocation_ref.is_some() {
1799        return Err(format!("policy {} is revoked", verified.policy.id));
1800    }
1801    let frontier_id = project
1802        .frontier_id
1803        .as_deref()
1804        .ok_or_else(|| "policy authority requires a frontier id".to_string())?;
1805    if verified.policy.frontier_id != frontier_id {
1806        return Err(format!(
1807            "policy frontier mismatch: policy {} targets {}, current frontier is {frontier_id}",
1808            verified.policy.id, verified.policy.frontier_id
1809        ));
1810    }
1811
1812    if verified.policy.quorum.threshold != 1 {
1813        return Err(format!(
1814            "singular policy signature cannot satisfy quorum threshold {} (must be exactly 1)",
1815            verified.policy.quorum.threshold
1816        ));
1817    }
1818    let eligible_roles = verified
1819        .policy
1820        .quorum
1821        .eligible_roles
1822        .iter()
1823        .map(|role| role.trim().to_ascii_lowercase())
1824        .collect::<std::collections::BTreeSet<_>>();
1825    if !eligible_roles
1826        .iter()
1827        .any(|role| matches!(role.as_str(), "reviewer" | "steward"))
1828    {
1829        return Err("policy quorum eligible_roles must admit a reviewer or steward".to_string());
1830    }
1831
1832    let matching = project
1833        .actors
1834        .iter()
1835        .filter(|actor| {
1836            actor
1837                .public_key
1838                .eq_ignore_ascii_case(&verified.signer_pubkey_hex)
1839        })
1840        .collect::<Vec<_>>();
1841    let actor = match matching.as_slice() {
1842        [] => {
1843            return Err(format!(
1844                "policy signer pubkey {} is not a registered actor on this frontier",
1845                verified.signer_pubkey_hex
1846            ));
1847        }
1848        [actor] => *actor,
1849        _ => {
1850            return Err(format!(
1851                "policy signer pubkey {} resolves ambiguously to {} actors on this frontier",
1852                verified.signer_pubkey_hex,
1853                matching.len()
1854            ));
1855        }
1856    };
1857    let actor_role = actor
1858        .id
1859        .split_once(':')
1860        .map(|(role, _)| role.trim().to_ascii_lowercase())
1861        .unwrap_or_default();
1862    let registered_human_role = matches!(actor_role.as_str(), "reviewer" | "steward")
1863        && !crate::proposals::is_placeholder_reviewer(&actor.id);
1864    if !registered_human_role {
1865        return Err(format!(
1866            "policy signer actor '{}' is not a registered reviewer or steward human",
1867            actor.id
1868        ));
1869    }
1870    if !eligible_roles.contains(&actor_role) {
1871        return Err(format!(
1872            "policy signer actor '{}' has registered role '{}', which is not in eligible_roles",
1873            actor.id, actor_role
1874        ));
1875    }
1876    if !verified
1877        .policy
1878        .issued_by
1879        .iter()
1880        .any(|issuer| issuer == &actor.id)
1881    {
1882        return Err(format!(
1883            "policy signer actor '{}' is not named in issued_by",
1884            actor.id
1885        ));
1886    }
1887
1888    let parse_time = |label: &str, value: &str| {
1889        chrono::DateTime::parse_from_rfc3339(value)
1890            .map_err(|error| format!("{label} must be RFC3339: {error}"))
1891    };
1892    let actor_created_at = parse_time("actor created_at", &actor.created_at)?;
1893    let signed_at = parse_time("policy signed_at", &verified.signed_at)?;
1894    let decision_at = parse_time("policy decision time", decision_time)?;
1895    if actor_created_at >= signed_at {
1896        return Err(format!(
1897            "policy signer actor '{}' was not registered before policy signing",
1898            actor.id
1899        ));
1900    }
1901    if signed_at > decision_at {
1902        return Err(format!(
1903            "policy {} was signed after the decision time",
1904            verified.policy.id
1905        ));
1906    }
1907    if let Some(revoked_at) = actor.revoked_at.as_deref() {
1908        let revoked_at = parse_time("actor revoked_at", revoked_at)?;
1909        if revoked_at <= signed_at {
1910            return Err(format!(
1911                "policy signer actor '{}' was revoked at policy signing",
1912                actor.id
1913            ));
1914        }
1915        if revoked_at <= decision_at {
1916            return Err(format!(
1917                "policy signer actor '{}' is revoked at decision time",
1918                actor.id
1919            ));
1920        }
1921    }
1922
1923    Ok(PolicyAuthority {
1924        human_authorizers: vec![actor.id.clone()],
1925    })
1926}
1927
1928/// Load `.vela/policies/active.json` + `active.sig.json` from a frontier
1929/// dir. Returns None when absent; Err on a present-but-broken pair (corrupt
1930/// governance must never fail open into the absent state).
1931pub fn load_active_policy(
1932    frontier_dir: &std::path::Path,
1933) -> Result<Option<VerifiedPolicy>, String> {
1934    Ok(load_active_policy_snapshot(frontier_dir)?.verified)
1935}
1936
1937/// Content observation for a prelaunch policy pair that no longer parses as a
1938/// supported [`AcceptancePolicy`]. This is provenance for a human retirement
1939/// proposal, never policy authority: it deliberately does not rederive the
1940/// policy id, validate the current schema, or verify the historical signature.
1941#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1942#[serde(deny_unknown_fields)]
1943pub struct LegacyPolicyPairObservation {
1944    pub stored_policy_id: String,
1945    pub policy_bytes_root: String,
1946    pub signature_bytes_root: String,
1947}
1948
1949/// Inspect exact legacy policy/signature bytes under the same structural and
1950/// byte budgets as current governance inputs. Duplicate object names are
1951/// rejected before the two stored ids are compared. A successful observation
1952/// says only which immutable bytes are present; it must never be interpreted as
1953/// a valid signature or an authorization to admit scientific state.
1954pub fn observe_legacy_policy_pair_bytes(
1955    policy_bytes: &[u8],
1956    signature_bytes: &[u8],
1957) -> Result<LegacyPolicyPairObservation, String> {
1958    let policy: Value = parse_bounded_governance_json(
1959        policy_bytes,
1960        GovernanceJsonLimits {
1961            bytes: POLICY_JSON_MAX_BYTES,
1962        },
1963        "legacy active policy",
1964    )?;
1965    let signature: Value = parse_bounded_governance_json(
1966        signature_bytes,
1967        GovernanceJsonLimits {
1968            bytes: POLICY_SIGNATURE_JSON_MAX_BYTES,
1969        },
1970        "legacy active policy signature",
1971    )?;
1972    let stored_policy_id = policy
1973        .as_object()
1974        .and_then(|object| object.get("id"))
1975        .and_then(Value::as_str)
1976        .ok_or_else(|| "legacy active policy must contain a string id".to_string())?;
1977    let signature_policy_id = signature
1978        .as_object()
1979        .and_then(|object| object.get("policy_id"))
1980        .and_then(Value::as_str)
1981        .ok_or_else(|| {
1982            "legacy active policy signature must contain a string policy_id".to_string()
1983        })?;
1984    if !is_policy_id_shape(stored_policy_id) {
1985        return Err(
1986            "legacy active policy id must be vap_ followed by 32 lowercase hex characters"
1987                .to_string(),
1988        );
1989    }
1990    if signature_policy_id != stored_policy_id {
1991        return Err(
1992            "legacy active policy and signature name different stored policy ids".to_string(),
1993        );
1994    }
1995    Ok(LegacyPolicyPairObservation {
1996        stored_policy_id: stored_policy_id.to_string(),
1997        policy_bytes_root: format!("sha256:{}", hex::encode(Sha256::digest(policy_bytes))),
1998        signature_bytes_root: format!("sha256:{}", hex::encode(Sha256::digest(signature_bytes))),
1999    })
2000}
2001
2002fn is_policy_id_shape(value: &str) -> bool {
2003    value.strip_prefix("vap_").is_some_and(|digest| {
2004        digest.len() == 32
2005            && digest
2006                .bytes()
2007                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2008    })
2009}
2010
2011#[cfg(test)]
2012mod legacy_pair_observation_tests {
2013    use super::*;
2014
2015    #[test]
2016    fn observes_legacy_bytes_without_granting_current_policy_authority() {
2017        let id = "vap_e0abc750544408e637bd90e0661bac15";
2018        let policy =
2019            format!(r#"{{"schema":"vela.acceptance_policy.prelaunch","id":"{id}","legacy":true}}"#);
2020        let signature = format!(
2021            r#"{{"policy_id":"{id}","signer_pubkey_hex":"not-authority","signature":"historical","signed_at":"before-current-format"}}"#
2022        );
2023        let observed =
2024            observe_legacy_policy_pair_bytes(policy.as_bytes(), signature.as_bytes()).unwrap();
2025        assert_eq!(observed.stored_policy_id, id);
2026        assert_eq!(
2027            observed.policy_bytes_root,
2028            format!("sha256:{}", hex::encode(Sha256::digest(policy.as_bytes())))
2029        );
2030        assert!(
2031            verify_policy_signature_bytes(
2032                policy.as_bytes(),
2033                signature.as_bytes(),
2034                None,
2035                "legacy fixture"
2036            )
2037            .is_err(),
2038            "observation must not make unsupported legacy bytes authoritative"
2039        );
2040    }
2041
2042    #[test]
2043    fn rejects_duplicate_names_and_mismatched_envelope_ids() {
2044        let id = "vap_e0abc750544408e637bd90e0661bac15";
2045        let duplicate = format!(r#"{{"id":"{id}","id":"{id}"}}"#);
2046        let signature = format!(r#"{{"policy_id":"{id}"}}"#);
2047        let error = observe_legacy_policy_pair_bytes(duplicate.as_bytes(), signature.as_bytes())
2048            .unwrap_err();
2049        assert!(error.contains("duplicate object name"), "{error}");
2050
2051        let other = "vap_dbbc9caf67767317e42e217c65bab979";
2052        let policy = format!(r#"{{"id":"{id}"}}"#);
2053        let signature = format!(r#"{{"policy_id":"{other}"}}"#);
2054        let error =
2055            observe_legacy_policy_pair_bytes(policy.as_bytes(), signature.as_bytes()).unwrap_err();
2056        assert!(error.contains("different stored policy ids"), "{error}");
2057    }
2058}
2059
2060/// Load the active policy paths exactly once, retaining the bytes that were
2061/// verified. A present policy without a signature is staged and human-only;
2062/// an orphan signature is corruption and never fails open.
2063pub fn load_active_policy_snapshot(
2064    frontier_dir: &std::path::Path,
2065) -> Result<ActivePolicySnapshot, String> {
2066    let dir = frontier_dir.join(".vela").join("policies");
2067    let policy_path = dir.join("active.json");
2068    let sig_path = dir.join("active.sig.json");
2069    let policy_bytes =
2070        read_optional_regular_file(&policy_path, "active policy", POLICY_JSON_MAX_BYTES)?;
2071    let signature_bytes = read_optional_regular_file(
2072        &sig_path,
2073        "active policy signature",
2074        POLICY_SIGNATURE_JSON_MAX_BYTES,
2075    )?;
2076    let (mode, policy, verified) = match (&policy_bytes, &signature_bytes) {
2077        (None, None) => (ActivePolicyMode::Absent, None, None),
2078        (Some(policy), None) => {
2079            let policy = parse_supported_policy_bytes(policy, "active policy")?;
2080            if !policy.id_is_valid() {
2081                return Err(format!(
2082                    "active policy id does not re-derive: stored {}, sealed {}",
2083                    policy.id,
2084                    policy.content_address()
2085                ));
2086            }
2087            (ActivePolicyMode::StagedUnsigned, Some(policy), None)
2088        }
2089        (None, Some(_)) => {
2090            return Err(
2091                "active policy signature exists without .vela/policies/active.json".to_string(),
2092            );
2093        }
2094        (Some(policy), Some(signature)) => {
2095            let verified = verify_policy_signature_bytes(policy, signature, None, "active policy")?;
2096            (
2097                ActivePolicyMode::Active,
2098                Some(verified.policy.clone()),
2099                Some(verified),
2100            )
2101        }
2102    };
2103    Ok(ActivePolicySnapshot {
2104        policy_bytes,
2105        signature_bytes,
2106        verified,
2107        mode,
2108        policy,
2109    })
2110}
2111
2112fn parse_supported_policy_bytes(
2113    policy_bytes: &[u8],
2114    label: &str,
2115) -> Result<AcceptancePolicy, String> {
2116    let policy: AcceptancePolicy = parse_bounded_governance_json(
2117        policy_bytes,
2118        GovernanceJsonLimits {
2119            bytes: POLICY_JSON_MAX_BYTES,
2120        },
2121        label,
2122    )?;
2123    validate_supported_policy(&policy, label)?;
2124    Ok(policy)
2125}
2126
2127fn read_optional_regular_file(
2128    path: &std::path::Path,
2129    label: &str,
2130    max_bytes: usize,
2131) -> Result<Option<Vec<u8>>, String> {
2132    match std::fs::symlink_metadata(path) {
2133        Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => {
2134            if metadata.len() > max_bytes as u64 {
2135                return Err(format!(
2136                    "{label} exceeds the {max_bytes}-byte input limit: {}",
2137                    path.display()
2138                ));
2139            }
2140            std::fs::read(path)
2141                .map(Some)
2142                .map_err(|error| format!("read {label} {}: {error}", path.display()))
2143        }
2144        Ok(_) => Err(format!(
2145            "{label} must be a regular non-symlink file: {}",
2146            path.display()
2147        )),
2148        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2149        Err(error) => Err(format!("inspect {label} {}: {error}", path.display())),
2150    }
2151}
2152
2153/// Verify an exact policy/signature byte pair. `expected_policy_id` binds
2154/// content-addressed historical snapshots to their path name.
2155pub fn verify_policy_signature_bytes(
2156    policy_bytes: &[u8],
2157    signature_bytes: &[u8],
2158    expected_policy_id: Option<&str>,
2159    label: &str,
2160) -> Result<VerifiedPolicy, String> {
2161    use ed25519_dalek::Verifier;
2162
2163    let policy: AcceptancePolicy = parse_bounded_governance_json(
2164        policy_bytes,
2165        GovernanceJsonLimits {
2166            bytes: POLICY_JSON_MAX_BYTES,
2167        },
2168        label,
2169    )?;
2170    validate_supported_policy(&policy, label)?;
2171    if expected_policy_id.is_some_and(|expected| expected != policy.id) || !policy.id_is_valid() {
2172        return Err(format!(
2173            "{label} id does not re-derive: stored {}, sealed {}",
2174            policy.id,
2175            policy.content_address()
2176        ));
2177    }
2178    let signature_label = format!("{label} signature");
2179    let sig: PolicySignatureRecord = parse_bounded_governance_json(
2180        signature_bytes,
2181        GovernanceJsonLimits {
2182            bytes: POLICY_SIGNATURE_JSON_MAX_BYTES,
2183        },
2184        &signature_label,
2185    )?;
2186    validate_rfc3339("policy signed_at", &sig.signed_at)?;
2187    if sig.policy_id != policy.id {
2188        return Err(format!("{label} signature is for a different policy id"));
2189    }
2190    let pk_bytes: [u8; 32] = hex::decode(&sig.signer_pubkey_hex)
2191        .map_err(|e| format!("pubkey hex: {e}"))?
2192        .try_into()
2193        .map_err(|_| "pubkey must be 32 bytes".to_string())?;
2194    let vk = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes).map_err(|e| e.to_string())?;
2195    let sig_bytes: [u8; 64] = hex::decode(&sig.signature)
2196        .map_err(|e| format!("signature hex: {e}"))?
2197        .try_into()
2198        .map_err(|_| "signature must be 64 bytes".to_string())?;
2199    let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);
2200    let bound_body = policy_signature_preimage(&policy, &sig.signed_at)?;
2201    vk.verify(&bound_body, &signature)
2202        .map_err(|_| format!("{label} signature does not verify"))?;
2203    Ok(VerifiedPolicy {
2204        policy,
2205        signer_pubkey_hex: sig.signer_pubkey_hex,
2206        signed_at: sig.signed_at,
2207    })
2208}