capsule_core/crypto/provenance/record.rs
1//! Append-only, hash-chained provenance log per asset (SSoT: [Cryptography — Provenance
2//! § Provenance of Library Modifications]).
3//!
4//! Each non-create record references its predecessor by SHA-256 hash; a rewrite of any
5//! past record breaks the chain at that point and is detectable by any reader walking
6//! forward from `create`. This is the structure that lets a key-holding attacker be
7//! detected after the fact: history is read-only.
8//!
9//! [Cryptography — Provenance § Provenance of Library Modifications]: https://docs/design/cryptography/provenance/#provenance-of-library-modifications
10
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13use uuid::Uuid;
14
15use super::manifest::AssetManifest;
16use crate::cbor;
17use crate::crypto::hash::{self, Hash32};
18
19/// The provenance-record version this build writes, and the newest it reads.
20pub const PROVENANCE_RECORD_VERSION: u16 = 1;
21
22/// One link in an asset's provenance chain.
23///
24/// The record leads with its [`version`](Self::version) ([Versioning — invariant 2]): the key
25/// sorts first in canonical CBOR, and [`decode`](Self::decode) reads it before anything else,
26/// so a record from a newer writer is recognised as such rather than misread as this version.
27/// Every other decode path refuses it too, because the field's own decoder rejects a version
28/// this build does not implement.
29///
30/// [Versioning — invariant 2]: https://docs/design/versioning/#system-invariants
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct ProvenanceRecord {
33 /// The record schema version; [`PROVENANCE_RECORD_VERSION`] on every record this build
34 /// writes.
35 #[serde(deserialize_with = "known_record_version")]
36 pub version: u16,
37 /// The asset this chain belongs to.
38 pub asset_id: Uuid,
39 /// The signed manifest for this transition.
40 pub manifest: AssetManifest,
41 /// SHA-256 of the previous record; null only for `action = create`. Mirrors the
42 /// manifest's own `prior_provenance_hash`, so signing the manifest signs this link.
43 pub prior_provenance_hash: Option<Hash32>,
44}
45
46/// Why a provenance record's bytes could not be decoded.
47#[derive(Debug, Error, PartialEq, Eq)]
48pub enum RecordDecodeError {
49 /// The record declares a version newer than this build implements. It must be stored
50 /// verbatim and quarantined, never applied, modified or re-encoded (versioning invariants
51 /// 3 and 5); it becomes readable once the user updates.
52 #[error("provenance record version {found} is newer than this build reads ({max_known})")]
53 UnsupportedVersion {
54 /// The version the record declares.
55 found: u64,
56 /// The newest version this build reads ([`PROVENANCE_RECORD_VERSION`]).
57 max_known: u16,
58 },
59 /// The bytes are not a well-formed record of a version this build reads.
60 #[error("malformed provenance record: {0}")]
61 Malformed(String),
62}
63
64/// The `version` field's decoder: a version this build does not read is a decode error on
65/// every path, so no caller can mistake a newer record for a current one.
66fn known_record_version<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u16, D::Error> {
67 let version = u16::deserialize(d)?;
68 if version == 0 || version > PROVENANCE_RECORD_VERSION {
69 return Err(serde::de::Error::custom(format!(
70 "unsupported provenance record version {version}; this build reads 1..={PROVENANCE_RECORD_VERSION}"
71 )));
72 }
73 Ok(version)
74}
75
76impl ProvenanceRecord {
77 /// A current-version record linking `manifest` into `asset_id`'s chain behind `prior`.
78 pub fn new(asset_id: Uuid, manifest: AssetManifest, prior: Option<Hash32>) -> Self {
79 Self {
80 version: PROVENANCE_RECORD_VERSION,
81 asset_id,
82 manifest,
83 prior_provenance_hash: prior,
84 }
85 }
86
87 /// Decode one record, reading its leading `version` before anything else.
88 ///
89 /// # Errors
90 ///
91 /// [`RecordDecodeError::UnsupportedVersion`] for a record a newer writer produced — the
92 /// caller quarantines it — and [`RecordDecodeError::Malformed`] for anything else that does
93 /// not decode, including a missing or non-integer version.
94 pub fn decode(bytes: &[u8]) -> Result<Self, RecordDecodeError> {
95 let value: ciborium::Value =
96 cbor::from_slice(bytes).map_err(|e| RecordDecodeError::Malformed(e.to_string()))?;
97 let version = value
98 .as_map()
99 .and_then(|map| map.iter().find(|(k, _)| k.as_text() == Some("version")))
100 .and_then(|(_, v)| v.as_integer())
101 .ok_or_else(|| {
102 RecordDecodeError::Malformed("missing or non-integer record version".into())
103 })?;
104 let version = i128::from(version);
105 if version > i128::from(PROVENANCE_RECORD_VERSION) {
106 tracing::warn!(
107 version = %version,
108 max_known = PROVENANCE_RECORD_VERSION,
109 "provenance record: version newer than this build reads"
110 );
111 return Err(RecordDecodeError::UnsupportedVersion {
112 found: u64::try_from(version).unwrap_or(u64::MAX),
113 max_known: PROVENANCE_RECORD_VERSION,
114 });
115 }
116 cbor::from_slice(bytes).map_err(|e| RecordDecodeError::Malformed(e.to_string()))
117 }
118
119 /// The content hash of this record (SHA-256 over its canonical CBOR, signatures
120 /// included), used as the next record's `prior_provenance_hash`.
121 pub fn record_hash(&self) -> Hash32 {
122 hash::hash_bytes(&cbor::to_canonical_vec(self).expect("provenance record serializes"))
123 }
124
125 /// Whether the manifest's `prior_provenance_hash` mirrors the record's, as required.
126 ///
127 /// Public because the chain walker is not the only checker: `capsule-library`'s
128 /// `Workspace::apply_remote_entry` decodes a record straight off the wire and must run the
129 /// same check before it trusts either copy. provenance.md's *Chained, Append-Only Structure*
130 /// is explicit that the two copies are "a checked invariant, not trusted redundancy", and a
131 /// checker that lived in one place would leave the wire path unchecked.
132 pub fn mirrors_manifest(&self) -> bool {
133 self.manifest.core.prior_provenance_hash == self.prior_provenance_hash
134 }
135}
136
137/// Errors from building or walking a provenance chain.
138#[derive(Debug, Error, PartialEq, Eq)]
139pub enum ChainError {
140 /// The first record was not a `create`, or a `create` appeared mid-chain.
141 #[error("chain root must be a single create record")]
142 BadRoot,
143 /// A record's `prior_provenance_hash` does not match the current chain head.
144 #[error("record does not chain to the current head (stale or forked)")]
145 BrokenLink,
146 /// A record's manifest prior hash does not mirror the record's prior hash.
147 #[error("manifest prior hash does not mirror the record")]
148 MirrorMismatch,
149}
150
151/// An in-memory append-only provenance chain for one asset.
152#[derive(Debug, Clone, Default)]
153pub struct ProvenanceChain {
154 records: Vec<ProvenanceRecord>,
155}
156
157impl ProvenanceChain {
158 /// An empty chain.
159 pub fn new() -> Self {
160 Self::default()
161 }
162
163 /// The current chain head hash (the last record's hash), or `None` if empty.
164 pub fn head(&self) -> Option<Hash32> {
165 self.records.last().map(ProvenanceRecord::record_hash)
166 }
167
168 /// All records, oldest first.
169 pub fn records(&self) -> &[ProvenanceRecord] {
170 &self.records
171 }
172
173 /// Append a record, enforcing the chain invariants:
174 /// the first record must be a `create` with a null prior; every later record's prior
175 /// must equal the current head; and each record's manifest prior must mirror it.
176 pub fn append(&mut self, record: ProvenanceRecord) -> Result<(), ChainError> {
177 if !record.mirrors_manifest() {
178 return Err(ChainError::MirrorMismatch);
179 }
180 match self.head() {
181 None => {
182 if !record.manifest.core.action.is_create()
183 || record.prior_provenance_hash.is_some()
184 {
185 return Err(ChainError::BadRoot);
186 }
187 }
188 Some(head) => {
189 if record.manifest.core.action.is_create() {
190 return Err(ChainError::BadRoot);
191 }
192 if record.prior_provenance_hash != Some(head) {
193 return Err(ChainError::BrokenLink);
194 }
195 }
196 }
197 self.records.push(record);
198 Ok(())
199 }
200
201 /// Walk the chain forward from `create`, asserting every link and mirror holds. Detects
202 /// a dropped or rewritten record as a non-matching prior hash. (Signature verification
203 /// is `verify_asset`'s job; this is structural chain integrity.)
204 pub fn verify_walk(records: &[ProvenanceRecord]) -> Result<(), ChainError> {
205 let mut expected_prior: Option<Hash32> = None;
206 for (i, rec) in records.iter().enumerate() {
207 if !rec.mirrors_manifest() {
208 return Err(ChainError::MirrorMismatch);
209 }
210 let is_create = rec.manifest.core.action.is_create();
211 if i == 0 {
212 if !is_create || rec.prior_provenance_hash.is_some() {
213 return Err(ChainError::BadRoot);
214 }
215 } else {
216 if is_create {
217 return Err(ChainError::BadRoot);
218 }
219 if rec.prior_provenance_hash != expected_prior {
220 return Err(ChainError::BrokenLink);
221 }
222 }
223 expected_prior = Some(rec.record_hash());
224 }
225 Ok(())
226 }
227}
228
229#[cfg(test)]
230mod tests;