Skip to main content

vela_protocol/kernel/
authority.rs

1//! Era-1 attributed repository-authority records and DSSE verification.
2//!
3//! These types are read/verify-only in the first migration slice. The released
4//! Era-0 event and signer path remains the sole writer until shadow evaluation
5//! and migration gates pass.
6
7use std::collections::BTreeSet;
8
9use base64::Engine as _;
10use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
11use ed25519_dalek::{Signature, Verifier, VerifyingKey};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15pub use crate::authentication::{
16    AuthenticationAssurance, AuthenticationMethod, AuthenticationObservationV1,
17};
18use crate::canonical::{sha256_canonical, to_canonical_bytes};
19use crate::events::{
20    EVENT_SCHEMA, EventKind, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
21};
22pub use crate::principal_capability::PrincipalClass;
23use crate::principal_capability::VerifiedCapabilityClaimV1;
24
25pub const AUTHORITY_KEYSET_SCHEMA_V1: &str = "vela.authority-keyset.v1";
26pub const AUTHORITY_RECORD_SCHEMA_V1: &str = "vela.authority-record.v1";
27pub const AUTHORITY_EVENT_SCHEMA_V1: &str = "vela.event.v1";
28pub const AUTHORITY_PAYLOAD_TYPE_V1: &str = "application/vnd.vela.authority-record.v1+json";
29pub const AUTHORITY_KEY_ALGORITHM: &str = "ed25519";
30pub const AUTHORITY_KEY_PURPOSE: &str = "repository_authority";
31pub const AUTHORITY_MODE: &str = "repository_authority";
32pub const CEDAR_ENGINE: &str = "cedar-policy";
33pub const CEDAR_ENGINE_VERSION: &str = "4.11.2";
34pub const CEDAR_PROFILE_V1: &str = "vela.cedar-restricted.v1";
35pub const POLICY_BUNDLE_SCHEMA_V1: &str = "vela.policy-bundle.v1";
36
37fn is_false(value: &bool) -> bool {
38    !*value
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum CedarDecision {
44    Allow,
45    Deny,
46}
47
48/// Canonicalizable authorization result retained by an authority record.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct CedarEvaluation {
52    pub engine: String,
53    pub engine_version: String,
54    pub profile: String,
55    pub valid: bool,
56    pub decision: CedarDecision,
57    pub automatic_permit: bool,
58    pub determining_policies: Vec<String>,
59    pub diagnostics: Vec<String>,
60}
61
62/// Closed policy-bundle manifest. Bundle files remain separate canonical
63/// bytes; this manifest binds their full roots and the exact evaluator.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(deny_unknown_fields)]
66pub struct PolicyBundleV1 {
67    pub schema: String,
68    pub frontier_id: String,
69    pub cedar_schema_root: String,
70    pub policies_root: String,
71    pub entities_root: String,
72    pub tests_root: String,
73    pub engine: String,
74    pub engine_version: String,
75    pub restricted_profile: String,
76    pub previous_bundle_root: Option<String>,
77    pub authority_summary: String,
78}
79
80impl PolicyBundleV1 {
81    pub fn validate(&self) -> Result<(), String> {
82        if self.schema != POLICY_BUNDLE_SCHEMA_V1 {
83            return Err(format!(
84                "policy bundle schema must be {POLICY_BUNDLE_SCHEMA_V1}"
85            ));
86        }
87        if self.engine != CEDAR_ENGINE
88            || self.engine_version != CEDAR_ENGINE_VERSION
89            || self.restricted_profile != CEDAR_PROFILE_V1
90        {
91            return Err("policy bundle evaluator identity is not the pinned Vela profile".into());
92        }
93        for (name, value) in [
94            ("cedar_schema_root", self.cedar_schema_root.as_str()),
95            ("policies_root", self.policies_root.as_str()),
96            ("entities_root", self.entities_root.as_str()),
97            ("tests_root", self.tests_root.as_str()),
98        ] {
99            require_sha256(name, value)?;
100        }
101        if let Some(root) = &self.previous_bundle_root {
102            require_sha256("previous_bundle_root", root)?;
103        }
104        if self.frontier_id.trim().is_empty() || self.authority_summary.trim().is_empty() {
105            return Err("policy bundle frontier and authority summary must be non-empty".into());
106        }
107        Ok(())
108    }
109
110    pub fn root(&self) -> Result<String, String> {
111        self.validate()?;
112        Ok(format!("sha256:{}", sha256_canonical(self)?))
113    }
114}
115
116/// Era-1 event content. Authority is carried by the covering transaction
117/// record rather than a per-event human signature.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119#[serde(deny_unknown_fields)]
120pub struct AuthorityEventContentV1 {
121    pub transaction_id: String,
122    pub principal_id: String,
123    pub authority_mode: String,
124    pub kind: EventKind,
125    pub target: StateTarget,
126    pub actor: StateActor,
127    pub timestamp: String,
128    pub reason: String,
129    pub before_hash: String,
130    pub after_hash: String,
131    #[serde(default)]
132    pub payload: Value,
133    #[serde(default)]
134    pub caveats: Vec<String>,
135}
136
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138#[serde(deny_unknown_fields)]
139pub struct AuthorityEventV1 {
140    pub schema: String,
141    pub id: String,
142    pub content: AuthorityEventContentV1,
143}
144
145impl AuthorityEventV1 {
146    pub fn new(content: AuthorityEventContentV1) -> Result<Self, String> {
147        let digest = sha256_canonical(&content)?;
148        let event = Self {
149            schema: AUTHORITY_EVENT_SCHEMA_V1.into(),
150            id: format!("vev_{}", &digest[..16]),
151            content,
152        };
153        event.validate()?;
154        Ok(event)
155    }
156
157    pub fn derive_id(&self) -> Result<String, String> {
158        let digest = sha256_canonical(&self.content)?;
159        Ok(format!("vev_{}", &digest[..16]))
160    }
161
162    pub fn root(&self) -> Result<String, String> {
163        self.validate()?;
164        Ok(format!("sha256:{}", sha256_canonical(self)?))
165    }
166
167    /// Recover the transaction-independent semantic event consumed by the
168    /// scientific reducer.
169    ///
170    /// Era-1 authority event IDs cover repository attribution, including the
171    /// transaction ID. Scientific event links such as
172    /// `review.accepted.payload.applied_event_id` must not depend on that
173    /// transaction ID or they create a hash cycle. The reducer identity is
174    /// therefore the ordinary unsigned `StateEvent` identity derived from the
175    /// exact shared semantic fields. The covering authority record remains the
176    /// sole authority for the resulting event bytes.
177    pub fn semantic_state_event(&self) -> Result<StateEvent, String> {
178        self.validate()?;
179        let mut event = StateEvent {
180            schema: EVENT_SCHEMA.into(),
181            id: String::new(),
182            kind: self.content.kind.clone(),
183            target: self.content.target.clone(),
184            actor: self.content.actor.clone(),
185            timestamp: self.content.timestamp.clone(),
186            reason: self.content.reason.clone(),
187            before_hash: self.content.before_hash.clone(),
188            after_hash: self.content.after_hash.clone(),
189            payload: self.content.payload.clone(),
190            caveats: self.content.caveats.clone(),
191            signature: None,
192        };
193        event.id = compute_event_id(&event);
194        Ok(event)
195    }
196
197    pub fn semantic_event_id(&self) -> Result<String, String> {
198        Ok(self.semantic_state_event()?.id)
199    }
200
201    pub fn validate(&self) -> Result<(), String> {
202        if self.schema != AUTHORITY_EVENT_SCHEMA_V1 || self.id != self.derive_id()? {
203            return Err("Era-1 event schema or content address is invalid".into());
204        }
205        if self.content.transaction_id.trim().is_empty()
206            || self.content.principal_id.trim().is_empty()
207            || self.content.authority_mode != AUTHORITY_MODE
208            || self.content.actor.id.trim().is_empty()
209            || self.content.timestamp.trim().is_empty()
210            || self.content.reason.trim().is_empty()
211        {
212            return Err("Era-1 event attribution and transaction fields must be explicit".into());
213        }
214        require_state_root("before_hash", &self.content.before_hash)?;
215        require_state_root("after_hash", &self.content.after_hash)?;
216        Ok(())
217    }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(deny_unknown_fields)]
222pub struct AuthorityKeyV1 {
223    pub key_id: String,
224    pub algorithm: String,
225    pub public_key: String,
226    pub valid_from_sequence: u64,
227    pub valid_through_sequence: Option<u64>,
228    pub purpose: String,
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(deny_unknown_fields)]
233pub struct AuthorityKeysetV1 {
234    pub schema: String,
235    pub frontier_id: String,
236    pub generation: u64,
237    pub threshold: u32,
238    pub keys: Vec<AuthorityKeyV1>,
239    pub previous_keyset_root: Option<String>,
240    pub activation_record_root: Option<String>,
241    /// A terminal successor keyset closes future repository authority. The
242    /// field is omitted for every historical/open v1 keyset, preserving its
243    /// canonical bytes and root.
244    #[serde(default, skip_serializing_if = "is_false")]
245    pub closed: bool,
246}
247
248impl AuthorityKeysetV1 {
249    pub fn validate(&self) -> Result<(), String> {
250        if self.schema != AUTHORITY_KEYSET_SCHEMA_V1 {
251            return Err(format!(
252                "authority keyset schema must be {AUTHORITY_KEYSET_SCHEMA_V1}"
253            ));
254        }
255        if self.frontier_id.trim().is_empty() || self.generation == 0 {
256            return Err("authority keyset frontier and generation must be set".into());
257        }
258        if self.closed {
259            if !self.keys.is_empty()
260                || self.threshold != 0
261                || self.previous_keyset_root.is_none()
262                || self.activation_record_root.is_none()
263            {
264                return Err(
265                    "closed authority keyset must be an empty terminal successor generation".into(),
266                );
267            }
268        } else if self.keys.is_empty()
269            || self.threshold == 0
270            || usize::try_from(self.threshold).unwrap_or(usize::MAX) > self.keys.len()
271        {
272            return Err("authority keyset threshold must be within the key count".into());
273        }
274        let mut key_ids = BTreeSet::new();
275        let mut public_keys = BTreeSet::new();
276        for key in &self.keys {
277            if !key_ids.insert(key.key_id.as_str()) {
278                return Err(format!("duplicate authority key ID {}", key.key_id));
279            }
280            let public_key = decode_fixed_hex::<32>("authority public key", &key.public_key)?;
281            if !public_keys.insert(public_key) {
282                return Err(format!(
283                    "authority key {} duplicates public-key material",
284                    key.key_id
285                ));
286            }
287            if key.algorithm != AUTHORITY_KEY_ALGORITHM
288                || key.purpose != AUTHORITY_KEY_PURPOSE
289                || key.valid_from_sequence == 0
290            {
291                return Err(format!(
292                    "authority key {} has an invalid algorithm, purpose, or sequence",
293                    key.key_id
294                ));
295            }
296            if let Some(through) = key.valid_through_sequence
297                && through < key.valid_from_sequence
298            {
299                return Err(format!(
300                    "authority key {} validity window is inverted",
301                    key.key_id
302                ));
303            }
304        }
305        if let Some(root) = &self.previous_keyset_root {
306            require_sha256("previous_keyset_root", root)?;
307        }
308        if let Some(root) = &self.activation_record_root {
309            require_sha256("activation_record_root", root)?;
310        }
311        Ok(())
312    }
313
314    pub fn root(&self) -> Result<String, String> {
315        self.validate()?;
316        Ok(format!("sha256:{}", sha256_canonical(self)?))
317    }
318}
319
320/// Verify a non-cyclic repository-authority keyset rotation.
321///
322/// The new keyset links the prior keyset root and the authority-record root
323/// that existed immediately before the rotation transaction. The rotation
324/// record can then cover the new keyset root without requiring either object
325/// to contain the other's root. The new keyset becomes usable only on the
326/// following authority-record sequence.
327pub fn verify_authority_keyset_transition(
328    current: &AuthorityKeysetV1,
329    next: &AuthorityKeysetV1,
330    activation_sequence: u64,
331    previous_authority_record_root: &str,
332) -> Result<(), String> {
333    current.validate()?;
334    next.validate()?;
335    require_sha256(
336        "previous_authority_record_root",
337        previous_authority_record_root,
338    )?;
339    if current.closed {
340        return Err("closed repository authority cannot transition again".into());
341    }
342    if activation_sequence <= 1 {
343        return Err("rotated authority keyset cannot activate at sequence 1".into());
344    }
345    if current.frontier_id != next.frontier_id
346        || next.generation != current.generation.saturating_add(1)
347        || next.previous_keyset_root.as_deref() != Some(current.root()?.as_str())
348        || next.activation_record_root.as_deref() != Some(previous_authority_record_root)
349    {
350        return Err(
351            "rotated authority keyset does not extend the exact prior generation and chain head"
352                .into(),
353        );
354    }
355    if !next.closed {
356        let active_keys = next
357            .keys
358            .iter()
359            .filter(|key| {
360                key.valid_from_sequence <= activation_sequence
361                    && key
362                        .valid_through_sequence
363                        .is_none_or(|through| activation_sequence <= through)
364            })
365            .count();
366        if active_keys < usize::try_from(next.threshold).unwrap_or(usize::MAX) {
367            return Err("rotated authority keyset cannot meet threshold at activation".into());
368        }
369    }
370    Ok(())
371}
372
373/// Verify a content-addressed policy-bundle rotation.
374///
375/// Activation is recorded by the covering authority transaction, so the
376/// bundle needs only the exact prior bundle root and introduces no record-root
377/// hash cycle.
378pub fn verify_policy_bundle_transition(
379    current: &PolicyBundleV1,
380    next: &PolicyBundleV1,
381) -> Result<(), String> {
382    current.validate()?;
383    next.validate()?;
384    if current.frontier_id != next.frontier_id
385        || next.previous_bundle_root.as_deref() != Some(current.root()?.as_str())
386    {
387        return Err("rotated policy bundle does not extend the exact prior bundle".into());
388    }
389    Ok(())
390}
391
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(deny_unknown_fields)]
394pub struct PrincipalSnapshotV1 {
395    pub principal_id: String,
396    pub principal_class: PrincipalClass,
397    pub display_name: Option<String>,
398    pub affiliation: Option<String>,
399    pub account_links: Vec<String>,
400}
401
402pub type AuthenticationClaimV1 = AuthenticationObservationV1;
403
404pub type DelegationClaimV1 = VerifiedCapabilityClaimV1;
405
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct AuthorizationClaimV1 {
409    pub policy_bundle_root: String,
410    pub request_root: String,
411    pub entity_snapshot_root: String,
412    pub evaluation: CedarEvaluation,
413}
414
415#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
416#[serde(deny_unknown_fields)]
417pub struct SemanticApprovalV1 {
418    pub principal_id: String,
419    pub role: String,
420    pub action: String,
421    pub reason: String,
422    pub approved_at: String,
423    pub intent_digest: String,
424}
425
426#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
427#[serde(deny_unknown_fields)]
428pub struct ObjectDeltaV1 {
429    pub path: String,
430    pub before_root: Option<String>,
431    pub after_root: Option<String>,
432    pub object_kind: String,
433}
434
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
436#[serde(deny_unknown_fields)]
437pub struct ExecutionClaimV1 {
438    pub vela_version: String,
439    pub binary_sha256: String,
440    pub transaction_read_set_root: String,
441    pub transaction_write_set_root: String,
442    pub completed_at: String,
443}
444
445/// Content-addressed body. The short `record_id` is derived from these bytes;
446/// the full content root is the security identity.
447#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
448#[serde(deny_unknown_fields)]
449pub struct AuthorityRecordContentV1 {
450    pub frontier_id: String,
451    pub sequence: u64,
452    pub previous_authority_record_root: Option<String>,
453    pub operation_id: String,
454    pub transaction_id: String,
455    pub intent_digest: String,
456    pub before_event_log_root: String,
457    pub after_event_log_root: String,
458    pub event_ids: Vec<String>,
459    pub object_delta: Vec<ObjectDeltaV1>,
460    pub principal: PrincipalSnapshotV1,
461    pub authentication: AuthenticationClaimV1,
462    pub delegation: Option<DelegationClaimV1>,
463    pub authorization: AuthorizationClaimV1,
464    pub semantic_approvals: Vec<SemanticApprovalV1>,
465    pub execution: ExecutionClaimV1,
466    pub authority_keyset_root: String,
467    pub recorded_at: String,
468}
469
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(deny_unknown_fields)]
472pub struct AuthorityRecordV1 {
473    pub schema: String,
474    pub record_id: String,
475    pub content: AuthorityRecordContentV1,
476}
477
478impl AuthorityRecordV1 {
479    pub fn new(content: AuthorityRecordContentV1) -> Result<Self, String> {
480        let digest = sha256_canonical(&content)?;
481        let record = Self {
482            schema: AUTHORITY_RECORD_SCHEMA_V1.into(),
483            record_id: format!("var_{}", &digest[..16]),
484            content,
485        };
486        record.validate()?;
487        Ok(record)
488    }
489
490    pub fn derive_id(&self) -> Result<String, String> {
491        let digest = sha256_canonical(&self.content)?;
492        Ok(format!("var_{}", &digest[..16]))
493    }
494
495    pub fn root(&self) -> Result<String, String> {
496        self.validate()?;
497        Ok(format!("sha256:{}", sha256_canonical(self)?))
498    }
499
500    pub fn validate(&self) -> Result<(), String> {
501        if self.schema != AUTHORITY_RECORD_SCHEMA_V1 {
502            return Err(format!(
503                "authority record schema must be {AUTHORITY_RECORD_SCHEMA_V1}"
504            ));
505        }
506        if self.record_id != self.derive_id()? {
507            return Err("authority record ID does not match its content".into());
508        }
509        let content = &self.content;
510        if content.frontier_id.trim().is_empty()
511            || content.operation_id.trim().is_empty()
512            || content.transaction_id.trim().is_empty()
513            || (content.event_ids.is_empty() && content.object_delta.is_empty())
514        {
515            return Err(
516                "authority record frontier, operation, transaction, and a changed event or object are required"
517                    .into(),
518            );
519        }
520        if content.sequence == 0
521            || (content.sequence == 1 && content.previous_authority_record_root.is_some())
522            || (content.sequence > 1 && content.previous_authority_record_root.is_none())
523        {
524            return Err("authority record sequence and previous root are inconsistent".into());
525        }
526        for (name, root) in [
527            ("intent_digest", content.intent_digest.as_str()),
528            (
529                "before_event_log_root",
530                content.before_event_log_root.as_str(),
531            ),
532            (
533                "after_event_log_root",
534                content.after_event_log_root.as_str(),
535            ),
536            (
537                "authority_keyset_root",
538                content.authority_keyset_root.as_str(),
539            ),
540            (
541                "policy_bundle_root",
542                content.authorization.policy_bundle_root.as_str(),
543            ),
544            ("request_root", content.authorization.request_root.as_str()),
545            (
546                "entity_snapshot_root",
547                content.authorization.entity_snapshot_root.as_str(),
548            ),
549            ("binary_sha256", content.execution.binary_sha256.as_str()),
550            (
551                "transaction_read_set_root",
552                content.execution.transaction_read_set_root.as_str(),
553            ),
554            (
555                "transaction_write_set_root",
556                content.execution.transaction_write_set_root.as_str(),
557            ),
558        ] {
559            require_sha256(name, root)?;
560        }
561        if let Some(root) = &content.previous_authority_record_root {
562            require_sha256("previous_authority_record_root", root)?;
563        }
564        let mut event_ids = BTreeSet::new();
565        for event_id in &content.event_ids {
566            if !event_id.starts_with("vev_") || !event_ids.insert(event_id) {
567                return Err(format!("invalid or duplicate event ID {event_id}"));
568            }
569        }
570        let mut paths = BTreeSet::new();
571        for delta in &content.object_delta {
572            if delta.path.is_empty() || !paths.insert(delta.path.as_str()) {
573                return Err(format!(
574                    "empty or duplicate object-delta path {}",
575                    delta.path
576                ));
577            }
578            if let Some(root) = &delta.before_root {
579                require_sha256("object_delta.before_root", root)?;
580            }
581            if let Some(root) = &delta.after_root {
582                require_sha256("object_delta.after_root", root)?;
583            }
584            if delta.before_root == delta.after_root {
585                return Err(format!("object delta {} changes no bytes", delta.path));
586            }
587        }
588        content.authentication.validate()?;
589        if content.principal.principal_id.trim().is_empty()
590            || content.principal.principal_id != content.authentication.principal_id
591            || content.principal.principal_class != content.authentication.principal_class
592            || !content
593                .principal
594                .account_links
595                .contains(&content.principal.principal_id)
596        {
597            return Err("authority attribution and authentication must be explicit".into());
598        }
599        if let Some(delegation) = &content.delegation {
600            delegation.validate()?;
601            if delegation.subject_principal_id != content.principal.principal_id
602                || delegation.current_actor_principal_id != content.principal.principal_id
603                || delegation.frontier_id != content.frontier_id
604            {
605                return Err(
606                    "authority-record principal or Frontier differs from its capability".into(),
607                );
608            }
609        }
610        Ok(())
611    }
612}
613
614#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
615#[serde(deny_unknown_fields)]
616pub struct DsseSignatureV1 {
617    pub keyid: String,
618    pub sig: String,
619}
620
621#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
622#[serde(deny_unknown_fields)]
623pub struct AuthorityEnvelopeV1 {
624    #[serde(rename = "payloadType")]
625    pub payload_type: String,
626    pub payload: String,
627    pub signatures: Vec<DsseSignatureV1>,
628}
629
630impl AuthorityEnvelopeV1 {
631    pub fn from_record(
632        record: &AuthorityRecordV1,
633        signatures: Vec<DsseSignatureV1>,
634    ) -> Result<Self, String> {
635        record.validate()?;
636        Ok(Self {
637            payload_type: AUTHORITY_PAYLOAD_TYPE_V1.into(),
638            payload: BASE64_STANDARD.encode(to_canonical_bytes(record)?),
639            signatures,
640        })
641    }
642}
643
644#[derive(Debug, Clone, PartialEq, Eq)]
645pub struct VerifiedAuthorityRecord {
646    pub record: AuthorityRecordV1,
647    pub record_root: String,
648    pub verified_key_ids: Vec<String>,
649}
650
651pub fn verify_authority_envelope(
652    envelope: &AuthorityEnvelopeV1,
653    keyset: &AuthorityKeysetV1,
654    expected_frontier_id: &str,
655    expected_sequence: u64,
656    expected_previous_root: Option<&str>,
657) -> Result<VerifiedAuthorityRecord, String> {
658    keyset.validate()?;
659    if envelope.payload_type != AUTHORITY_PAYLOAD_TYPE_V1 {
660        return Err("authority envelope payload type is invalid".into());
661    }
662    if envelope.signatures.is_empty() {
663        return Err("authority envelope has no signatures".into());
664    }
665    let payload = BASE64_STANDARD
666        .decode(&envelope.payload)
667        .map_err(|error| format!("authority envelope payload is not base64: {error}"))?;
668    let record: AuthorityRecordV1 = serde_json::from_slice(&payload)
669        .map_err(|error| format!("authority record JSON is invalid: {error}"))?;
670    if to_canonical_bytes(&record)? != payload {
671        return Err("authority record payload is not canonical JSON".into());
672    }
673    record.validate()?;
674    if record.content.frontier_id != expected_frontier_id
675        || record.content.frontier_id != keyset.frontier_id
676        || record.content.sequence != expected_sequence
677        || record.content.previous_authority_record_root.as_deref() != expected_previous_root
678    {
679        return Err("authority record frontier or chain position is invalid".into());
680    }
681    if record.content.authority_keyset_root != keyset.root()? {
682        return Err("authority record does not bind the supplied keyset".into());
683    }
684
685    let pae = dsse_pae(&envelope.payload_type, &payload);
686    let mut verified = BTreeSet::new();
687    for signed in &envelope.signatures {
688        if !verified.insert(signed.keyid.clone()) {
689            return Err(format!("duplicate DSSE signature from {}", signed.keyid));
690        }
691        let key = keyset
692            .keys
693            .iter()
694            .find(|candidate| candidate.key_id == signed.keyid)
695            .ok_or_else(|| format!("unknown authority key {}", signed.keyid))?;
696        if record.content.sequence < key.valid_from_sequence
697            || key
698                .valid_through_sequence
699                .is_some_and(|through| record.content.sequence > through)
700        {
701            return Err(format!(
702                "authority key {} is outside its sequence window",
703                key.key_id
704            ));
705        }
706        let public_key = VerifyingKey::from_bytes(&decode_fixed_hex::<32>(
707            "authority public key",
708            &key.public_key,
709        )?)
710        .map_err(|error| format!("invalid authority public key: {error}"))?;
711        let signature_bytes = BASE64_STANDARD
712            .decode(&signed.sig)
713            .map_err(|error| format!("authority signature is not base64: {error}"))?;
714        let signature = Signature::from_bytes(
715            &signature_bytes
716                .try_into()
717                .map_err(|_| "authority signature must be exactly 64 bytes".to_string())?,
718        );
719        public_key
720            .verify(&pae, &signature)
721            .map_err(|error| format!("authority signature verification failed: {error}"))?;
722    }
723    if verified.len() < usize::try_from(keyset.threshold).unwrap_or(usize::MAX) {
724        return Err("authority signature threshold was not met".into());
725    }
726
727    Ok(VerifiedAuthorityRecord {
728        record_root: record.root()?,
729        record,
730        verified_key_ids: verified.into_iter().collect(),
731    })
732}
733
734/// DSSE Pre-Authentication Encoding:
735/// `DSSEv1 SP LEN(payloadType) SP payloadType SP LEN(payload) SP payload`.
736pub fn dsse_pae(payload_type: &str, payload: &[u8]) -> Vec<u8> {
737    let mut output = Vec::with_capacity(payload_type.len() + payload.len() + 32);
738    output.extend_from_slice(b"DSSEv1 ");
739    output.extend_from_slice(payload_type.len().to_string().as_bytes());
740    output.push(b' ');
741    output.extend_from_slice(payload_type.as_bytes());
742    output.push(b' ');
743    output.extend_from_slice(payload.len().to_string().as_bytes());
744    output.push(b' ');
745    output.extend_from_slice(payload);
746    output
747}
748
749fn require_sha256(name: &str, value: &str) -> Result<(), String> {
750    let Some(hex) = value.strip_prefix("sha256:") else {
751        return Err(format!("{name} must use a full sha256: digest"));
752    };
753    if hex.len() != 64
754        || !hex
755            .bytes()
756            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
757    {
758        return Err(format!(
759            "{name} must contain 64 lowercase hexadecimal characters"
760        ));
761    }
762    Ok(())
763}
764
765fn require_state_root(name: &str, value: &str) -> Result<(), String> {
766    if value == NULL_HASH {
767        return Ok(());
768    }
769    require_sha256(name, value)
770}
771
772fn decode_fixed_hex<const N: usize>(name: &str, value: &str) -> Result<[u8; N], String> {
773    hex::decode(value)
774        .map_err(|error| format!("{name} is not hexadecimal: {error}"))?
775        .try_into()
776        .map_err(|_| format!("{name} must be exactly {N} bytes"))
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use ed25519_dalek::{Signer, SigningKey};
783
784    fn root(byte: char) -> String {
785        format!("sha256:{}", byte.to_string().repeat(64))
786    }
787
788    #[test]
789    fn era_one_event_is_transaction_bound_and_content_addressed() {
790        let event = AuthorityEventV1::new(AuthorityEventContentV1 {
791            transaction_id: "txn_fixture".into(),
792            principal_id: "local:device-1|uid:501".into(),
793            authority_mode: AUTHORITY_MODE.into(),
794            kind: EventKind::ReviewRejected,
795            target: StateTarget {
796                r#type: "proposal".into(),
797                id: "vpr_0123456789abcdef".into(),
798            },
799            actor: StateActor {
800                id: "local:device-1|uid:501".into(),
801                r#type: "human".into(),
802            },
803            timestamp: "2026-07-24T12:00:00Z".into(),
804            reason: "The evidence does not satisfy the claim.".into(),
805            before_hash: root('a'),
806            after_hash: root('a'),
807            payload: serde_json::json!({"proposal_id": "vpr_0123456789abcdef"}),
808            caveats: Vec::new(),
809        })
810        .unwrap();
811        assert!(event.id.starts_with("vev_"));
812        assert!(event.root().unwrap().starts_with("sha256:"));
813
814        let mut tampered = event.clone();
815        tampered.content.transaction_id = "txn_other".into();
816        assert!(tampered.validate().is_err());
817    }
818
819    #[test]
820    fn era_one_event_recovers_transaction_independent_reducer_identity() {
821        let content = AuthorityEventContentV1 {
822            transaction_id: "vtx_first".into(),
823            principal_id: "local:device-1|uid:501".into(),
824            authority_mode: AUTHORITY_MODE.into(),
825            kind: EventKind::FindingNoted,
826            target: StateTarget {
827                r#type: "finding".into(),
828                id: "vf_0123456789abcdef".into(),
829            },
830            actor: StateActor {
831                id: "local:device-1|uid:501".into(),
832                r#type: "human".into(),
833            },
834            timestamp: "2026-07-24T12:00:00Z".into(),
835            reason: "Retain the exact scientific annotation.".into(),
836            before_hash: root('a'),
837            after_hash: root('b'),
838            payload: serde_json::json!({"annotation": "bounded"}),
839            caveats: vec!["scope remains exact".into()],
840        };
841        let first = AuthorityEventV1::new(content.clone()).unwrap();
842        let second = AuthorityEventV1::new(AuthorityEventContentV1 {
843            transaction_id: "vtx_second".into(),
844            ..content
845        })
846        .unwrap();
847
848        assert_ne!(first.id, second.id);
849        assert_eq!(
850            first.semantic_event_id().unwrap(),
851            second.semantic_event_id().unwrap()
852        );
853        let semantic = first.semantic_state_event().unwrap();
854        assert_eq!(semantic.id, first.semantic_event_id().unwrap());
855        assert_eq!(semantic.kind, first.content.kind);
856        assert!(semantic.signature.is_none());
857    }
858
859    #[test]
860    fn era_one_non_scientific_event_accepts_the_protocol_null_root() {
861        let event = AuthorityEventV1::new(AuthorityEventContentV1 {
862            transaction_id: "txn_lease_fixture".into(),
863            principal_id: "agent:fixture".into(),
864            authority_mode: AUTHORITY_MODE.into(),
865            kind: EventKind::Other("work.claimed".into()),
866            target: StateTarget {
867                r#type: "target".into(),
868                id: "erdos:124".into(),
869            },
870            actor: StateActor {
871                id: "agent:fixture".into(),
872                r#type: "agent".into(),
873            },
874            timestamp: "2026-07-24T12:00:00Z".into(),
875            reason: "Claim one exact bounded work target.".into(),
876            before_hash: NULL_HASH.into(),
877            after_hash: NULL_HASH.into(),
878            payload: serde_json::json!({"target_id": "erdos:124"}),
879            caveats: Vec::new(),
880        })
881        .unwrap();
882        assert_eq!(event.content.before_hash, NULL_HASH);
883        assert_eq!(event.content.after_hash, NULL_HASH);
884    }
885
886    fn fixture() -> (AuthorityRecordV1, AuthorityKeysetV1, SigningKey) {
887        let key = SigningKey::from_bytes(&[7; 32]);
888        let mut keyset = AuthorityKeysetV1 {
889            schema: AUTHORITY_KEYSET_SCHEMA_V1.into(),
890            frontier_id: "vfr_fixture".into(),
891            generation: 1,
892            threshold: 1,
893            keys: vec![AuthorityKeyV1 {
894                key_id: "repo-key-1".into(),
895                algorithm: AUTHORITY_KEY_ALGORITHM.into(),
896                public_key: hex::encode(key.verifying_key().to_bytes()),
897                valid_from_sequence: 1,
898                valid_through_sequence: None,
899                purpose: AUTHORITY_KEY_PURPOSE.into(),
900            }],
901            previous_keyset_root: None,
902            activation_record_root: None,
903            closed: false,
904        };
905        let content = AuthorityRecordContentV1 {
906            frontier_id: "vfr_fixture".into(),
907            sequence: 1,
908            previous_authority_record_root: None,
909            operation_id: "vop_fixture".into(),
910            transaction_id: "txn_fixture".into(),
911            intent_digest: root('a'),
912            before_event_log_root: root('b'),
913            after_event_log_root: root('c'),
914            event_ids: vec!["vev_0123456789abcdef".into()],
915            object_delta: vec![ObjectDeltaV1 {
916                path: ".vela/events/vev_0123456789abcdef.json".into(),
917                before_root: None,
918                after_root: Some(root('d')),
919                object_kind: "event".into(),
920            }],
921            principal: PrincipalSnapshotV1 {
922                principal_id: "local:device-1|uid:501".into(),
923                principal_class: PrincipalClass::Human,
924                display_name: Some("Alice".into()),
925                affiliation: None,
926                account_links: vec!["local:device-1|uid:501".into()],
927            },
928            authentication: AuthenticationClaimV1 {
929                schema: crate::authentication::AUTHENTICATION_OBSERVATION_SCHEMA_V1.into(),
930                principal_id: "local:device-1|uid:501".into(),
931                principal_class: PrincipalClass::Human,
932                issuer: "device-1".into(),
933                subject: "uid:501".into(),
934                method: AuthenticationMethod::LocalOsSession,
935                assurance: AuthenticationAssurance::LocalSession,
936                session_root: root('9'),
937                authenticated_at: "2026-07-24T12:00:00Z".into(),
938                observed_at: "2026-07-24T12:00:00Z".into(),
939                expires_at: "2026-07-24T13:00:00Z".into(),
940                user_presence: false,
941                user_verification: false,
942                recovery_recent: false,
943                revocation_ref: None,
944            },
945            delegation: None,
946            authorization: AuthorizationClaimV1 {
947                policy_bundle_root: root('e'),
948                request_root: root('f'),
949                entity_snapshot_root: root('1'),
950                evaluation: CedarEvaluation {
951                    engine: CEDAR_ENGINE.into(),
952                    engine_version: CEDAR_ENGINE_VERSION.into(),
953                    profile: CEDAR_PROFILE_V1.into(),
954                    valid: true,
955                    decision: CedarDecision::Allow,
956                    automatic_permit: false,
957                    determining_policies: vec!["policy0".into()],
958                    diagnostics: Vec::new(),
959                },
960            },
961            semantic_approvals: vec![SemanticApprovalV1 {
962                principal_id: "local:device-1|uid:501".into(),
963                role: "reviewer".into(),
964                action: "review_reject".into(),
965                reason: "Evidence does not satisfy the claim.".into(),
966                approved_at: "2026-07-24T12:00:00Z".into(),
967                intent_digest: root('a'),
968            }],
969            execution: ExecutionClaimV1 {
970                vela_version: "0.930.0-rc.1".into(),
971                binary_sha256: root('2'),
972                transaction_read_set_root: root('3'),
973                transaction_write_set_root: root('4'),
974                completed_at: "2026-07-24T12:00:01Z".into(),
975            },
976            authority_keyset_root: String::new(),
977            recorded_at: "2026-07-24T12:00:01Z".into(),
978        };
979        let keyset_root = keyset.root().unwrap();
980        let mut content = content;
981        content.authority_keyset_root = keyset_root;
982        let record = AuthorityRecordV1::new(content).unwrap();
983        // Keep this mutation explicit so future keyset fields cannot
984        // accidentally depend on the record they activate.
985        keyset.activation_record_root = None;
986        (record, keyset, key)
987    }
988
989    fn signed_envelope(record: &AuthorityRecordV1, key: &SigningKey) -> AuthorityEnvelopeV1 {
990        let mut envelope = AuthorityEnvelopeV1::from_record(record, Vec::new()).unwrap();
991        let payload = BASE64_STANDARD.decode(&envelope.payload).unwrap();
992        let signature = key.sign(&dsse_pae(&envelope.payload_type, &payload));
993        envelope.signatures.push(DsseSignatureV1 {
994            keyid: "repo-key-1".into(),
995            sig: BASE64_STANDARD.encode(signature.to_bytes()),
996        });
997        envelope
998    }
999
1000    #[test]
1001    fn authority_record_roundtrips_through_dsse() {
1002        let (record, keyset, key) = fixture();
1003        let verified = verify_authority_envelope(
1004            &signed_envelope(&record, &key),
1005            &keyset,
1006            "vfr_fixture",
1007            1,
1008            None,
1009        )
1010        .unwrap();
1011        assert_eq!(verified.record, record);
1012        assert_eq!(verified.verified_key_ids, vec!["repo-key-1"]);
1013    }
1014
1015    #[test]
1016    fn authority_record_rejects_object_delta_with_identical_roots() {
1017        let (record, _, _) = fixture();
1018        let mut content = record.content;
1019        content.object_delta[0].before_root = content.object_delta[0].after_root.clone();
1020        let error = AuthorityRecordV1::new(content).unwrap_err();
1021        assert!(error.contains("changes no bytes"), "{error}");
1022    }
1023
1024    #[test]
1025    fn authority_record_tampering_fails_closed() {
1026        let (record, keyset, key) = fixture();
1027        let mut envelope = signed_envelope(&record, &key);
1028        let mut value: serde_json::Value =
1029            serde_json::from_slice(&BASE64_STANDARD.decode(&envelope.payload).unwrap()).unwrap();
1030        value["content"]["after_event_log_root"] = serde_json::json!(root('9'));
1031        envelope.payload = BASE64_STANDARD.encode(to_canonical_bytes(&value).unwrap());
1032        assert!(verify_authority_envelope(&envelope, &keyset, "vfr_fixture", 1, None).is_err());
1033    }
1034
1035    #[test]
1036    fn authority_record_rejects_authentication_identity_and_bearer_material() {
1037        let (record, _, _) = fixture();
1038        let mut mismatched = record.content.clone();
1039        mismatched.authentication.principal_id = "local:other-device|uid:501".into();
1040        assert!(AuthorityRecordV1::new(mismatched).is_err());
1041
1042        let mut value = serde_json::to_value(&record).unwrap();
1043        value["content"]["authentication"]["bearer_token"] =
1044            serde_json::json!("must-not-enter-history");
1045        assert!(serde_json::from_value::<AuthorityRecordV1>(value).is_err());
1046    }
1047
1048    #[test]
1049    fn authority_record_rejects_wrong_type_key_and_chain_position() {
1050        let (record, keyset, key) = fixture();
1051        let envelope = signed_envelope(&record, &key);
1052
1053        let mut wrong_type = envelope.clone();
1054        wrong_type.payload_type = "application/json".into();
1055        assert!(verify_authority_envelope(&wrong_type, &keyset, "vfr_fixture", 1, None).is_err());
1056
1057        let wrong_key = SigningKey::from_bytes(&[8; 32]);
1058        assert!(
1059            verify_authority_envelope(
1060                &signed_envelope(&record, &wrong_key),
1061                &keyset,
1062                "vfr_fixture",
1063                1,
1064                None
1065            )
1066            .is_err()
1067        );
1068        assert!(
1069            verify_authority_envelope(&envelope, &keyset, "vfr_fixture", 2, Some(&root('9')))
1070                .is_err()
1071        );
1072    }
1073
1074    #[test]
1075    fn authority_record_rejects_noncanonical_payload_and_duplicate_signer() {
1076        let (record, keyset, key) = fixture();
1077        let mut envelope = signed_envelope(&record, &key);
1078        let decoded = BASE64_STANDARD.decode(&envelope.payload).unwrap();
1079        let pretty = serde_json::to_vec_pretty(
1080            &serde_json::from_slice::<serde_json::Value>(&decoded).unwrap(),
1081        )
1082        .unwrap();
1083        envelope.payload = BASE64_STANDARD.encode(pretty);
1084        assert!(verify_authority_envelope(&envelope, &keyset, "vfr_fixture", 1, None).is_err());
1085
1086        let mut duplicate = signed_envelope(&record, &key);
1087        duplicate.signatures.push(duplicate.signatures[0].clone());
1088        assert!(verify_authority_envelope(&duplicate, &keyset, "vfr_fixture", 1, None).is_err());
1089    }
1090
1091    #[test]
1092    fn authority_key_window_and_threshold_fail_closed() {
1093        let (record, mut keyset, key) = fixture();
1094        keyset.keys[0].valid_from_sequence = 2;
1095        let error = verify_authority_envelope(
1096            &signed_envelope(&record, &key),
1097            &keyset,
1098            "vfr_fixture",
1099            1,
1100            None,
1101        )
1102        .unwrap_err();
1103        assert!(
1104            error.contains("keyset") || error.contains("sequence"),
1105            "{error}"
1106        );
1107
1108        let (_, mut keyset, _) = fixture();
1109        keyset.threshold = 2;
1110        assert!(keyset.validate().is_err());
1111    }
1112
1113    #[test]
1114    fn authority_keyset_rejects_duplicate_public_key_material() {
1115        let (_, mut keyset, _) = fixture();
1116        let duplicate = AuthorityKeyV1 {
1117            key_id: "repo-key-alias".into(),
1118            ..keyset.keys[0].clone()
1119        };
1120        keyset.keys.push(duplicate);
1121        keyset.threshold = 2;
1122        assert!(
1123            keyset
1124                .validate()
1125                .unwrap_err()
1126                .contains("duplicates public-key material")
1127        );
1128
1129        keyset.keys[1].public_key = keyset.keys[1].public_key.to_uppercase();
1130        assert!(
1131            keyset
1132                .validate()
1133                .unwrap_err()
1134                .contains("duplicates public-key material")
1135        );
1136    }
1137
1138    #[test]
1139    fn keyset_rotation_is_non_cyclic_and_exact() {
1140        let (_, current, _) = fixture();
1141        let next_key = SigningKey::from_bytes(&[9; 32]);
1142        let previous_record_root = root('9');
1143        let mut next = AuthorityKeysetV1 {
1144            schema: AUTHORITY_KEYSET_SCHEMA_V1.into(),
1145            frontier_id: current.frontier_id.clone(),
1146            generation: 2,
1147            threshold: 1,
1148            keys: vec![AuthorityKeyV1 {
1149                key_id: "repo-key-2".into(),
1150                algorithm: AUTHORITY_KEY_ALGORITHM.into(),
1151                public_key: hex::encode(next_key.verifying_key().to_bytes()),
1152                valid_from_sequence: 3,
1153                valid_through_sequence: None,
1154                purpose: AUTHORITY_KEY_PURPOSE.into(),
1155            }],
1156            previous_keyset_root: Some(current.root().unwrap()),
1157            activation_record_root: Some(previous_record_root.clone()),
1158            closed: false,
1159        };
1160        verify_authority_keyset_transition(&current, &next, 3, &previous_record_root).unwrap();
1161
1162        next.generation = 3;
1163        assert!(
1164            verify_authority_keyset_transition(&current, &next, 3, &previous_record_root)
1165                .unwrap_err()
1166                .contains("exact prior generation")
1167        );
1168        next.generation = 2;
1169        next.keys[0].valid_from_sequence = 4;
1170        assert!(
1171            verify_authority_keyset_transition(&current, &next, 3, &previous_record_root)
1172                .unwrap_err()
1173                .contains("cannot meet threshold")
1174        );
1175        next.keys[0].valid_from_sequence = 3;
1176        next.activation_record_root = Some(root('8'));
1177        assert!(
1178            verify_authority_keyset_transition(&current, &next, 3, &previous_record_root)
1179                .unwrap_err()
1180                .contains("chain head")
1181        );
1182
1183        let closed = AuthorityKeysetV1 {
1184            schema: AUTHORITY_KEYSET_SCHEMA_V1.into(),
1185            frontier_id: current.frontier_id.clone(),
1186            generation: 2,
1187            threshold: 0,
1188            keys: Vec::new(),
1189            previous_keyset_root: Some(current.root().unwrap()),
1190            activation_record_root: Some(previous_record_root.clone()),
1191            closed: true,
1192        };
1193        verify_authority_keyset_transition(&current, &closed, 3, &previous_record_root).unwrap();
1194
1195        let mut invalid_closed = closed.clone();
1196        invalid_closed.threshold = 1;
1197        assert!(
1198            invalid_closed
1199                .validate()
1200                .unwrap_err()
1201                .contains("empty terminal successor")
1202        );
1203        assert!(
1204            verify_authority_keyset_transition(&closed, &next, 4, &previous_record_root)
1205                .unwrap_err()
1206                .contains("cannot transition again")
1207        );
1208    }
1209
1210    #[test]
1211    fn policy_bundle_rotation_extends_one_exact_root() {
1212        let current = PolicyBundleV1 {
1213            schema: POLICY_BUNDLE_SCHEMA_V1.into(),
1214            frontier_id: "vfr_fixture".into(),
1215            cedar_schema_root: root('1'),
1216            policies_root: root('2'),
1217            entities_root: root('3'),
1218            tests_root: root('4'),
1219            engine: CEDAR_ENGINE.into(),
1220            engine_version: CEDAR_ENGINE_VERSION.into(),
1221            restricted_profile: CEDAR_PROFILE_V1.into(),
1222            previous_bundle_root: None,
1223            authority_summary: "Initial repository authority.".into(),
1224        };
1225        let mut next = PolicyBundleV1 {
1226            policies_root: root('5'),
1227            tests_root: root('6'),
1228            previous_bundle_root: Some(current.root().unwrap()),
1229            authority_summary: "Rotated repository authority.".into(),
1230            ..current.clone()
1231        };
1232        verify_policy_bundle_transition(&current, &next).unwrap();
1233
1234        next.previous_bundle_root = Some(root('7'));
1235        assert!(
1236            verify_policy_bundle_transition(&current, &next)
1237                .unwrap_err()
1238                .contains("exact prior bundle")
1239        );
1240    }
1241
1242    #[test]
1243    fn authority_record_unknown_fields_fail_to_decode() {
1244        let value = serde_json::json!({
1245            "schema": AUTHORITY_RECORD_SCHEMA_V1,
1246            "record_id": "var_bad",
1247            "content": {},
1248            "extra": true
1249        });
1250        assert!(serde_json::from_value::<AuthorityRecordV1>(value).is_err());
1251    }
1252
1253    #[test]
1254    fn dsse_pae_matches_the_spec_shape() {
1255        assert_eq!(
1256            dsse_pae("text/plain", b"hello"),
1257            b"DSSEv1 10 text/plain 5 hello"
1258        );
1259    }
1260}