interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-evidence / src / lib.rs

898 lines · 32760 bytes Raw Blame History
1//! Evidence receipts bound to a `ChangesetId` and the `CrumbContextDigest` the runner saw
2//! (ADR 0004 deliverable D4).
3//!
4//! An [`EvidenceReceipt`] is a separate, versioned, Ed25519-signed record. It references a
5//! changeset by its `ChangesetId`; it is not part of the `ChangesetEnvelope` and does not
6//! replace the envelope's `EvidenceAttachment` list. Record version 1 is shaped so that it
7//! can grow into ADR 0003's E1 receipt (section 5.5) under a later `record_version`, not
8//! into a second format.
9//!
10//! What a v1 receipt binds:
11//!
12//! * the repository and the `ChangesetId` under test;
13//! * the source revision the changeset was built on ([`SourceRevision`]: its base `GitOid`
14//! and parent `ChangesetId`s, exactly as the envelope states them);
15//! * one [`CrumbContextBinding`] per distinct directory of the changed path set, holding two
16//! `CrumbContextDigest`s of that directory's Directory Crumb context: at the base revision
17//! (what the author saw) and in the changeset's own tree (what the runner tested under);
18//! * the inputs, named by an [`InputRootDigest`] over a list of repository members (one
19//! member in v1; ADR 0003 L1's composite multi-repository input root is the same digest
20//! over more than one member);
21//! * the test identity ([`TestIdentity`]: name, command, toolchain, platform, environment);
22//! * the result ([`ReceiptResult`]: exit status, typed [`Outcome`], declared output digests);
23//! * an [`Observation`] (log bytes and timings), stored and signed with the receipt but
24//! excluded from its identity.
25//!
26//! Identity. The [`ResultDigest`] covers the exit status, the outcome, and the declared
27//! output digests only. The [`EvidenceReceiptId`] covers the record version, the
28//! [`EvidenceActionDigest`] (what was run, on what, under which context), the
29//! `ResultDigest`, and the executor. Logs and timings never enter either digest, so two runs
30//! that differ only in their observation have the same identity (ADR 0003 section 5.5).
31//!
32//! Authority. A receipt never grants publication. AEGIS stays the sole execution and
33//! publication authority, and Radicle canonical promotion stays independent of receipts. A
34//! valid receipt only states which context, inputs, and test produced which result.
35//!
36//! Coordination records (claims, scents, whispers, presence) are never evidence: no field of
37//! a receipt holds or references one, and nothing in this crate reads the coordination
38//! plane.
39//!
40//! Storage of receipts is out of scope for this crate: it encodes, decodes, signs, and
41//! verifies records only.
42
43use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
44use sha2::{Digest, Sha256};
45use std::fmt;
46use synapse_core::{
47 decode_did_key_ed25519, encode_did_key_ed25519, validate_repo_relative_path, ChangesetId,
48 GitOid, RepoId,
49};
50use synapse_crumb::{CrumbContextDigest, ROOT_DIR};
51
52/// The only receipt record version this crate reads or writes.
53pub const EVIDENCE_RECEIPT_VERSION_V1: u16 = 1;
54
55/// Domain tag that opens every encoded receipt record.
56pub const DOMAIN_EVIDENCE_RECEIPT_V1: &[u8] = b"SYNAPSE_EVIDENCE_RECEIPT_V1\0";
57/// Domain tag for the executor's Ed25519 signature over a receipt.
58pub const DOMAIN_EVIDENCE_RECEIPT_SIGN_V1: &[u8] = b"SYNAPSE_EVIDENCE_RECEIPT_SIGN_V1\0";
59/// Domain tag for [`EvidenceReceiptId`].
60pub const DOMAIN_EVIDENCE_RECEIPT_ID_V1: &[u8] = b"SYNAPSE_EVIDENCE_RECEIPT_ID_V1\0";
61/// Domain tag for [`EvidenceActionDigest`].
62pub const DOMAIN_EVIDENCE_ACTION_V1: &[u8] = b"SYNAPSE_EVIDENCE_ACTION_V1\0";
63/// Domain tag for [`ResultDigest`].
64pub const DOMAIN_EVIDENCE_RESULT_V1: &[u8] = b"SYNAPSE_EVIDENCE_RESULT_V1\0";
65/// Domain tag for [`InputRootDigest`].
66pub const DOMAIN_EVIDENCE_INPUT_ROOT_V1: &[u8] = b"SYNAPSE_EVIDENCE_INPUT_ROOT_V1\0";
67/// Domain tag for [`OutputDigest::of_bytes`].
68pub const DOMAIN_EVIDENCE_OUTPUT_V1: &[u8] = b"SYNAPSE_EVIDENCE_OUTPUT_V1\0";
69
70/// Maximum bytes of any string field.
71pub const MAX_STRING_BYTES: usize = 4096;
72/// Maximum number of items in any list field (parents, contexts, arguments, environment, outputs).
73pub const MAX_LIST_ITEMS: usize = 4096;
74/// Maximum bytes of the observation log carried inline.
75pub const MAX_LOG_BYTES: usize = 1024 * 1024;
76/// Maximum bytes of one whole encoded receipt record: the log cap plus 1 MiB for every other
77/// field. [`EvidenceReceipt::decode`] checks it before parsing or allocating anything, and
78/// [`EvidenceReceipt::sign`] and [`EvidenceReceipt::encode`] refuse to produce a larger record.
79/// The per-field caps alone would allow a record of about 100 MB.
80pub const MAX_RECEIPT_BYTES: usize = MAX_LOG_BYTES + 1024 * 1024;
81
82/// Input root member kind tag for "a whole Synapse changeset tree" (the only v1 kind).
83const INPUT_MEMBER_CHANGESET: u8 = 1;
84
85macro_rules! digest32 {
86 ($(#[$m:meta])* $name:ident) => {
87 $(#[$m])*
88 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
89 pub struct $name(pub [u8; 32]);
90
91 impl $name {
92 pub fn to_hex(self) -> String {
93 hex::encode(self.0)
94 }
95 }
96
97 impl fmt::Debug for $name {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(f, concat!(stringify!($name), "({})"), self.to_hex())
100 }
101 }
102
103 impl fmt::Display for $name {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 f.write_str(&self.to_hex())
106 }
107 }
108 };
109}
110
111digest32!(
112 /// Identity of one receipt (`"SYNAPSE_EVIDENCE_RECEIPT_ID_V1\0"`): record version, action
113 /// digest, result digest, executor. Never a `BlobDigest`, `ChangesetId`, or
114 /// `CrumbContextDigest`.
115 EvidenceReceiptId
116);
117digest32!(
118 /// What was run, on what, under which Directory Crumb context
119 /// (`"SYNAPSE_EVIDENCE_ACTION_V1\0"`). The v1 stand-in for ADR 0003's `ActionDigest`.
120 EvidenceActionDigest
121);
122digest32!(
123 /// The deterministic part of a result (`"SYNAPSE_EVIDENCE_RESULT_V1\0"`): exit status,
124 /// outcome, declared output digests. Logs and timings are never part of it.
125 ResultDigest
126);
127digest32!(
128 /// Digest of the inputs a run read (`"SYNAPSE_EVIDENCE_INPUT_ROOT_V1\0"`), over a sorted
129 /// list of repository members. One member in v1.
130 InputRootDigest
131);
132digest32!(
133 /// Digest of one declared output. [`OutputDigest::of_bytes`] computes it with the
134 /// `"SYNAPSE_EVIDENCE_OUTPUT_V1\0"` tag; a runner may supply its own 32 bytes.
135 OutputDigest
136);
137
138impl OutputDigest {
139 /// Domain-separated SHA-256 of an output's bytes.
140 pub fn of_bytes(bytes: &[u8]) -> Self {
141 let mut h = Sha256::new();
142 h.update(DOMAIN_EVIDENCE_OUTPUT_V1);
143 h.update((bytes.len() as u64).to_le_bytes());
144 h.update(bytes);
145 Self(h.finalize().into())
146 }
147}
148
149/// Why a receipt was refused. Every refusal is typed; nothing is accepted by default.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum ReceiptError {
152 /// The record does not open with `"SYNAPSE_EVIDENCE_RECEIPT_V1\0"`.
153 WrongDomain,
154 /// The record version is not one this crate understands.
155 UnknownVersion(u16),
156 /// The record ends before a field is complete.
157 Truncated,
158 /// Bytes remain after the signature.
159 TrailingBytes,
160 /// A string, list, or log is longer than its cap.
161 OverCap(&'static str),
162 /// A string field is not UTF-8.
163 NotUtf8(&'static str),
164 /// An enum tag byte has no meaning.
165 UnknownTag(&'static str, u8),
166 /// A list that must be strictly sorted and unique is not.
167 Unsorted(&'static str),
168 /// A field that must not be empty is empty.
169 Empty(&'static str),
170 /// A directory or path is not a clean repository-relative path.
171 InvalidPath(String),
172 /// The repository identifier is not valid.
173 InvalidRepoId(String),
174 /// The input root has a member count this record version does not support (v1: one).
175 InputRootUnsupported(usize),
176 /// The input root does not name the receipt's own repository and changeset.
177 InputRootMismatch,
178 /// The outcome contradicts the exit status (a `Pass` must exit with code 0, a `Fail` must not).
179 OutcomeInconsistent,
180 /// The executor's `did:key` is not an Ed25519 key.
181 ExecutorDidInvalid,
182 /// The Ed25519 signature does not verify over the signed bytes.
183 SignatureInvalid,
184}
185
186impl fmt::Display for ReceiptError {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 write!(f, "evidence receipt refused: {self:?}")
189 }
190}
191
192impl std::error::Error for ReceiptError {}
193
194/// The revision a changeset was built on, exactly as its envelope states it.
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct SourceRevision {
197 pub base_git_oid: GitOid,
198 /// Strictly sorted and unique, as in the envelope.
199 pub parent_changesets: Vec<ChangesetId>,
200}
201
202/// The Directory Crumb context of one directory, on both sides of the changeset. The two
203/// digests differ when the changeset edits a `.crumb` on that directory's chain.
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct CrumbContextBinding {
206 /// `"."` for the repository root, else a repository-relative directory.
207 pub dir: String,
208 /// Context at the changeset's base: what the author saw.
209 pub at_base: CrumbContextDigest,
210 /// Context in the changeset's own tree (the input root): what the runner tested under.
211 pub in_changeset: CrumbContextDigest,
212}
213
214/// One repository's contribution to an input root.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct InputRootMember {
217 pub repo_id: RepoId,
218 /// The whole tree of this changeset is the input from this repository.
219 pub changeset_id: ChangesetId,
220}
221
222/// The inputs a run read. v1 has exactly one member: the receipt's own repository and
223/// changeset. ADR 0003 L1 extends this to several members sorted by `repo_id` (the
224/// composite multi-repository input root) under a later record version; a later member kind
225/// can name a `TreeDigest` instead of a changeset (ADR 0003 C1).
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct InputRoot {
228 pub members: Vec<InputRootMember>,
229}
230
231impl InputRoot {
232 /// The v1 input root: the whole tree of one changeset in one repository.
233 pub fn single_repo(repo_id: RepoId, changeset_id: ChangesetId) -> Self {
234 Self {
235 members: vec![InputRootMember {
236 repo_id,
237 changeset_id,
238 }],
239 }
240 }
241
242 /// Domain-separated digest over the member count and each member's repository, kind
243 /// tag, and root.
244 pub fn digest(&self) -> InputRootDigest {
245 let mut h = Sha256::new();
246 h.update(DOMAIN_EVIDENCE_INPUT_ROOT_V1);
247 h.update((self.members.len() as u64).to_le_bytes());
248 for m in &self.members {
249 hash_str(&mut h, m.repo_id.as_str());
250 h.update([INPUT_MEMBER_CHANGESET]);
251 h.update(m.changeset_id.0);
252 }
253 InputRootDigest(h.finalize().into())
254 }
255}
256
257/// One environment variable the test ran with.
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct EnvVar {
260 pub name: String,
261 pub value: String,
262}
263
264/// What was run.
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct TestIdentity {
267 /// Stable name of the test or gate (for example `"cargo-test-workspace"`).
268 pub name: String,
269 /// Exact argument vector, program first.
270 pub command: Vec<String>,
271 /// Toolchain identity (for example `"rustc 1.89.0"`).
272 pub toolchain: String,
273 /// Platform identity (for example `"aarch64-unknown-linux-gnu"`).
274 pub platform: String,
275 /// Strictly sorted by name and unique.
276 pub environment: Vec<EnvVar>,
277}
278
279/// How the test process ended.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum ExitStatus {
282 Code(i32),
283 Signal(i32),
284}
285
286/// The typed verdict of a run.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum Outcome {
289 /// Every declared check passed. Requires exit code 0.
290 Pass,
291 /// A declared check failed. Requires an exit status other than code 0.
292 Fail,
293 /// The runner saw different results for the same action. Never a pass.
294 Flaky,
295 /// The run could not produce a verdict (harness or infrastructure failure). Never a pass.
296 Error,
297}
298
299impl Outcome {
300 /// `true` only for [`Outcome::Pass`]. `Flaky` and `Error` never count as a pass.
301 pub fn is_pass(self) -> bool {
302 matches!(self, Outcome::Pass)
303 }
304
305 fn tag_byte(self) -> u8 {
306 match self {
307 Outcome::Pass => 1,
308 Outcome::Fail => 2,
309 Outcome::Flaky => 3,
310 Outcome::Error => 4,
311 }
312 }
313}
314
315/// One output the action declares (a built artifact, a per-test verdict file).
316#[derive(Debug, Clone, PartialEq, Eq)]
317pub struct DeclaredOutput {
318 pub name: String,
319 pub digest: OutputDigest,
320}
321
322/// The deterministic part of a result. Its digest is the [`ResultDigest`].
323#[derive(Debug, Clone, PartialEq, Eq)]
324pub struct ReceiptResult {
325 pub exit_status: ExitStatus,
326 pub outcome: Outcome,
327 /// Strictly sorted by name and unique.
328 pub outputs: Vec<DeclaredOutput>,
329}
330
331impl ReceiptResult {
332 pub fn digest(&self) -> ResultDigest {
333 let mut buf = Vec::new();
334 put_result(&mut buf, self);
335 let mut h = Sha256::new();
336 h.update(DOMAIN_EVIDENCE_RESULT_V1);
337 h.update((buf.len() as u64).to_le_bytes());
338 h.update(&buf);
339 ResultDigest(h.finalize().into())
340 }
341}
342
343/// The observation part: stored and signed with the receipt, never part of its identity.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct Observation {
346 pub started_at_ms: u64,
347 pub duration_ms: u64,
348 /// At most [`MAX_LOG_BYTES`].
349 pub log: Vec<u8>,
350}
351
352/// Everything a receipt states, before it is signed.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct ReceiptBody {
355 pub repo_id: RepoId,
356 pub changeset_id: ChangesetId,
357 pub source: SourceRevision,
358 /// One per distinct directory of the changeset's mutated paths (a path's parent, `"."`
359 /// for the root), strictly sorted by `dir`.
360 pub crumb_contexts: Vec<CrumbContextBinding>,
361 pub input_root: InputRoot,
362 pub test: TestIdentity,
363 pub result: ReceiptResult,
364 pub observation: Observation,
365}
366
367impl ReceiptBody {
368 /// Check every structural rule of record version 1.
369 pub fn validate(&self) -> Result<(), ReceiptError> {
370 strictly_sorted(
371 self.source.parent_changesets.iter(),
372 "source.parent_changesets",
373 )?;
374 cap_list(
375 self.source.parent_changesets.len(),
376 "source.parent_changesets",
377 )?;
378
379 if self.crumb_contexts.is_empty() {
380 return Err(ReceiptError::Empty("crumb_contexts"));
381 }
382 cap_list(self.crumb_contexts.len(), "crumb_contexts")?;
383 for c in &self.crumb_contexts {
384 if c.dir != ROOT_DIR {
385 validate_repo_relative_path(&c.dir)
386 .map_err(|_| ReceiptError::InvalidPath(c.dir.clone()))?;
387 }
388 }
389 strictly_sorted(self.crumb_contexts.iter().map(|c| &c.dir), "crumb_contexts")?;
390
391 match self.input_root.members.as_slice() {
392 [m] => {
393 if m.repo_id != self.repo_id || m.changeset_id != self.changeset_id {
394 return Err(ReceiptError::InputRootMismatch);
395 }
396 }
397 other => return Err(ReceiptError::InputRootUnsupported(other.len())),
398 }
399
400 let t = &self.test;
401 if t.name.is_empty() {
402 return Err(ReceiptError::Empty("test.name"));
403 }
404 if t.command.is_empty() {
405 return Err(ReceiptError::Empty("test.command"));
406 }
407 cap_str(&t.name, "test.name")?;
408 cap_list(t.command.len(), "test.command")?;
409 for a in &t.command {
410 cap_str(a, "test.command")?;
411 }
412 cap_str(&t.toolchain, "test.toolchain")?;
413 cap_str(&t.platform, "test.platform")?;
414 cap_list(t.environment.len(), "test.environment")?;
415 for e in &t.environment {
416 cap_str(&e.name, "test.environment")?;
417 cap_str(&e.value, "test.environment")?;
418 }
419 strictly_sorted(t.environment.iter().map(|e| &e.name), "test.environment")?;
420
421 let r = &self.result;
422 cap_list(r.outputs.len(), "result.outputs")?;
423 for o in &r.outputs {
424 cap_str(&o.name, "result.outputs")?;
425 }
426 strictly_sorted(r.outputs.iter().map(|o| &o.name), "result.outputs")?;
427 let exited_zero = r.exit_status == ExitStatus::Code(0);
428 match r.outcome {
429 Outcome::Pass if !exited_zero => return Err(ReceiptError::OutcomeInconsistent),
430 Outcome::Fail if exited_zero => return Err(ReceiptError::OutcomeInconsistent),
431 _ => {}
432 }
433
434 if self.observation.log.len() > MAX_LOG_BYTES {
435 return Err(ReceiptError::OverCap("observation.log"));
436 }
437 Ok(())
438 }
439
440 /// What was run, on what, under which context. Excludes the result and the observation.
441 pub fn action_digest(&self) -> EvidenceActionDigest {
442 let mut buf = Vec::new();
443 put_str(&mut buf, self.repo_id.as_str());
444 buf.extend_from_slice(&self.changeset_id.0);
445 put_source(&mut buf, &self.source);
446 put_contexts(&mut buf, &self.crumb_contexts);
447 buf.extend_from_slice(&self.input_root.digest().0);
448 put_test(&mut buf, &self.test);
449 let mut h = Sha256::new();
450 h.update(DOMAIN_EVIDENCE_ACTION_V1);
451 h.update(EVIDENCE_RECEIPT_VERSION_V1.to_le_bytes());
452 h.update((buf.len() as u64).to_le_bytes());
453 h.update(&buf);
454 EvidenceActionDigest(h.finalize().into())
455 }
456}
457
458/// A signed evidence receipt, record version 1.
459#[derive(Debug, Clone, PartialEq, Eq)]
460pub struct EvidenceReceipt {
461 pub record_version: u16,
462 pub body: ReceiptBody,
463 /// `did:key` of the executor's Ed25519 key.
464 pub executor_did: String,
465 pub signature: [u8; 64],
466}
467
468impl EvidenceReceipt {
469 /// Validate `body` and sign it as record version 1 with the executor's key, named by its
470 /// canonical `did:key`. Refuses a body whose record would exceed [`MAX_RECEIPT_BYTES`].
471 pub fn sign(body: ReceiptBody, executor: &SigningKey) -> Result<Self, ReceiptError> {
472 body.validate()?;
473 let mut receipt = Self {
474 record_version: EVIDENCE_RECEIPT_VERSION_V1,
475 body,
476 executor_did: encode_did_key_ed25519(&executor.verifying_key().to_bytes()),
477 signature: [0; 64],
478 };
479 let signable = receipt.signable_bytes();
480 // The record is the signable bytes with the record tag in place of the sign tag, plus
481 // the 64-byte signature.
482 let record_len = signable.len() - DOMAIN_EVIDENCE_RECEIPT_SIGN_V1.len()
483 + DOMAIN_EVIDENCE_RECEIPT_V1.len()
484 + 64;
485 if record_len > MAX_RECEIPT_BYTES {
486 return Err(ReceiptError::OverCap("receipt"));
487 }
488 receipt.signature = executor.sign(&signable).to_bytes();
489 Ok(receipt)
490 }
491
492 /// Bytes the executor signs: sign tag, version, body (observation included), executor.
493 pub fn signable_bytes(&self) -> Vec<u8> {
494 let mut buf = Vec::with_capacity(512 + self.body.observation.log.len());
495 buf.extend_from_slice(DOMAIN_EVIDENCE_RECEIPT_SIGN_V1);
496 buf.extend_from_slice(&self.record_version.to_le_bytes());
497 put_body(&mut buf, &self.body);
498 put_str(&mut buf, &self.executor_did);
499 buf
500 }
501
502 /// Check version, structure, executor key, and signature (strict Ed25519). Returns the
503 /// receipt's identity. A receipt that passes still grants nothing.
504 pub fn verify(&self) -> Result<EvidenceReceiptId, ReceiptError> {
505 if self.record_version != EVIDENCE_RECEIPT_VERSION_V1 {
506 return Err(ReceiptError::UnknownVersion(self.record_version));
507 }
508 self.body.validate()?;
509 let key_bytes = decode_did_key_ed25519(&self.executor_did)
510 .map_err(|_| ReceiptError::ExecutorDidInvalid)?;
511 // One key has exactly one accepted spelling (`did:key:z6Mk...`), so the receipt
512 // identity, which hashes the DID string, is a function of the key.
513 if self.executor_did != encode_did_key_ed25519(&key_bytes) {
514 return Err(ReceiptError::ExecutorDidInvalid);
515 }
516 let key =
517 VerifyingKey::from_bytes(&key_bytes).map_err(|_| ReceiptError::ExecutorDidInvalid)?;
518 key.verify_strict(
519 &self.signable_bytes(),
520 &Signature::from_bytes(&self.signature),
521 )
522 .map_err(|_| ReceiptError::SignatureInvalid)?;
523 Ok(self.id())
524 }
525
526 /// The deterministic part's digest: exit status, outcome, declared outputs.
527 pub fn result_digest(&self) -> ResultDigest {
528 self.body.result.digest()
529 }
530
531 /// Receipt identity: version, action digest, result digest, executor. Logs and timings
532 /// are excluded. Computed without checking the signature; use [`Self::verify`].
533 pub fn id(&self) -> EvidenceReceiptId {
534 let mut h = Sha256::new();
535 h.update(DOMAIN_EVIDENCE_RECEIPT_ID_V1);
536 h.update(self.record_version.to_le_bytes());
537 h.update(self.body.action_digest().0);
538 h.update(self.result_digest().0);
539 hash_str(&mut h, &self.executor_did);
540 EvidenceReceiptId(h.finalize().into())
541 }
542
543 /// Canonical record bytes: record tag, version, body, executor, signature. Refuses an
544 /// unknown version, a body that breaks a version 1 rule (so no length or count is ever
545 /// truncated into its u32 prefix), and a record over [`MAX_RECEIPT_BYTES`]. Does not
546 /// check the signature.
547 pub fn encode(&self) -> Result<Vec<u8>, ReceiptError> {
548 if self.record_version != EVIDENCE_RECEIPT_VERSION_V1 {
549 return Err(ReceiptError::UnknownVersion(self.record_version));
550 }
551 self.body.validate()?;
552 cap_str(&self.executor_did, "executor_did")?;
553 let mut buf = Vec::with_capacity(512 + self.body.observation.log.len());
554 buf.extend_from_slice(DOMAIN_EVIDENCE_RECEIPT_V1);
555 buf.extend_from_slice(&self.record_version.to_le_bytes());
556 put_body(&mut buf, &self.body);
557 put_str(&mut buf, &self.executor_did);
558 buf.extend_from_slice(&self.signature);
559 if buf.len() > MAX_RECEIPT_BYTES {
560 return Err(ReceiptError::OverCap("receipt"));
561 }
562 Ok(buf)
563 }
564
565 /// Parse canonical record bytes. Refuses a record over [`MAX_RECEIPT_BYTES`] first, then
566 /// a wrong domain tag and an unknown version before reading anything else; every length
567 /// is checked against its cap before any allocation. Does not verify the signature; see
568 /// [`Self::decode_verified`].
569 pub fn decode(bytes: &[u8]) -> Result<Self, ReceiptError> {
570 if bytes.len() > MAX_RECEIPT_BYTES {
571 return Err(ReceiptError::OverCap("receipt"));
572 }
573 let mut r = Reader { bytes, pos: 0 };
574 if r.take(DOMAIN_EVIDENCE_RECEIPT_V1.len())
575 .map_err(|_| ReceiptError::WrongDomain)?
576 != DOMAIN_EVIDENCE_RECEIPT_V1
577 {
578 return Err(ReceiptError::WrongDomain);
579 }
580 let record_version = r.u16()?;
581 if record_version != EVIDENCE_RECEIPT_VERSION_V1 {
582 return Err(ReceiptError::UnknownVersion(record_version));
583 }
584 let body = read_body(&mut r)?;
585 let executor_did = r.string("executor_did")?;
586 let signature: [u8; 64] = r.array()?;
587 if r.pos != bytes.len() {
588 return Err(ReceiptError::TrailingBytes);
589 }
590 Ok(Self {
591 record_version,
592 body,
593 executor_did,
594 signature,
595 })
596 }
597
598 /// [`Self::decode`] followed by [`Self::verify`].
599 pub fn decode_verified(bytes: &[u8]) -> Result<(Self, EvidenceReceiptId), ReceiptError> {
600 let receipt = Self::decode(bytes)?;
601 let id = receipt.verify()?;
602 Ok((receipt, id))
603 }
604}
605
606// ---------------------------------------------------------------------------------------
607// Canonical encoding. Integers are little-endian; strings and byte runs are prefixed with a
608// u32 length; lists with a u32 count. The encoding is injective, so equal bytes mean equal
609// records and any change to a field changes the signed bytes.
610
611fn put_str(buf: &mut Vec<u8>, s: &str) {
612 put_bytes(buf, s.as_bytes());
613}
614
615fn put_bytes(buf: &mut Vec<u8>, b: &[u8]) {
616 buf.extend_from_slice(&(b.len() as u32).to_le_bytes());
617 buf.extend_from_slice(b);
618}
619
620fn put_count(buf: &mut Vec<u8>, n: usize) {
621 buf.extend_from_slice(&(n as u32).to_le_bytes());
622}
623
624fn hash_str(h: &mut Sha256, s: &str) {
625 h.update((s.len() as u64).to_le_bytes());
626 h.update(s.as_bytes());
627}
628
629fn put_source(buf: &mut Vec<u8>, s: &SourceRevision) {
630 buf.extend_from_slice(&s.base_git_oid.0);
631 put_count(buf, s.parent_changesets.len());
632 for p in &s.parent_changesets {
633 buf.extend_from_slice(&p.0);
634 }
635}
636
637fn put_contexts(buf: &mut Vec<u8>, cs: &[CrumbContextBinding]) {
638 put_count(buf, cs.len());
639 for c in cs {
640 put_str(buf, &c.dir);
641 buf.extend_from_slice(&c.at_base.0);
642 buf.extend_from_slice(&c.in_changeset.0);
643 }
644}
645
646fn put_test(buf: &mut Vec<u8>, t: &TestIdentity) {
647 put_str(buf, &t.name);
648 put_count(buf, t.command.len());
649 for a in &t.command {
650 put_str(buf, a);
651 }
652 put_str(buf, &t.toolchain);
653 put_str(buf, &t.platform);
654 put_count(buf, t.environment.len());
655 for e in &t.environment {
656 put_str(buf, &e.name);
657 put_str(buf, &e.value);
658 }
659}
660
661fn put_result(buf: &mut Vec<u8>, r: &ReceiptResult) {
662 let (tag, value) = match r.exit_status {
663 ExitStatus::Code(c) => (1u8, c),
664 ExitStatus::Signal(s) => (2u8, s),
665 };
666 buf.push(tag);
667 buf.extend_from_slice(&value.to_le_bytes());
668 buf.push(r.outcome.tag_byte());
669 put_count(buf, r.outputs.len());
670 for o in &r.outputs {
671 put_str(buf, &o.name);
672 buf.extend_from_slice(&o.digest.0);
673 }
674}
675
676fn put_body(buf: &mut Vec<u8>, b: &ReceiptBody) {
677 put_str(buf, b.repo_id.as_str());
678 buf.extend_from_slice(&b.changeset_id.0);
679 put_source(buf, &b.source);
680 put_contexts(buf, &b.crumb_contexts);
681 put_count(buf, b.input_root.members.len());
682 for m in &b.input_root.members {
683 put_str(buf, m.repo_id.as_str());
684 buf.push(INPUT_MEMBER_CHANGESET);
685 buf.extend_from_slice(&m.changeset_id.0);
686 }
687 put_test(buf, &b.test);
688 put_result(buf, &b.result);
689 buf.extend_from_slice(&b.observation.started_at_ms.to_le_bytes());
690 buf.extend_from_slice(&b.observation.duration_ms.to_le_bytes());
691 put_bytes(buf, &b.observation.log);
692}
693
694struct Reader<'a> {
695 bytes: &'a [u8],
696 pos: usize,
697}
698
699impl<'a> Reader<'a> {
700 fn take(&mut self, n: usize) -> Result<&'a [u8], ReceiptError> {
701 let end = self.pos.checked_add(n).ok_or(ReceiptError::Truncated)?;
702 let out = self
703 .bytes
704 .get(self.pos..end)
705 .ok_or(ReceiptError::Truncated)?;
706 self.pos = end;
707 Ok(out)
708 }
709
710 fn array<const N: usize>(&mut self) -> Result<[u8; N], ReceiptError> {
711 let mut out = [0u8; N];
712 out.copy_from_slice(self.take(N)?);
713 Ok(out)
714 }
715
716 fn u8(&mut self) -> Result<u8, ReceiptError> {
717 Ok(self.array::<1>()?[0])
718 }
719
720 fn u16(&mut self) -> Result<u16, ReceiptError> {
721 Ok(u16::from_le_bytes(self.array()?))
722 }
723
724 fn u32(&mut self) -> Result<u32, ReceiptError> {
725 Ok(u32::from_le_bytes(self.array()?))
726 }
727
728 fn u64(&mut self) -> Result<u64, ReceiptError> {
729 Ok(u64::from_le_bytes(self.array()?))
730 }
731
732 fn i32(&mut self) -> Result<i32, ReceiptError> {
733 Ok(i32::from_le_bytes(self.array()?))
734 }
735
736 /// A u32 length checked against `cap` before anything is read or allocated.
737 fn len(&mut self, cap: usize, field: &'static str) -> Result<usize, ReceiptError> {
738 let n = self.u32()? as usize;
739 if n > cap {
740 return Err(ReceiptError::OverCap(field));
741 }
742 Ok(n)
743 }
744
745 fn string(&mut self, field: &'static str) -> Result<String, ReceiptError> {
746 let n = self.len(MAX_STRING_BYTES, field)?;
747 let raw = self.take(n)?;
748 String::from_utf8(raw.to_vec()).map_err(|_| ReceiptError::NotUtf8(field))
749 }
750
751 fn repo_id(&mut self, field: &'static str) -> Result<RepoId, ReceiptError> {
752 let s = self.string(field)?;
753 RepoId::new(s.clone()).map_err(|_| ReceiptError::InvalidRepoId(s))
754 }
755}
756
757fn read_body(r: &mut Reader<'_>) -> Result<ReceiptBody, ReceiptError> {
758 let repo_id = r.repo_id("repo_id")?;
759 let changeset_id = ChangesetId(r.array()?);
760
761 let base_git_oid = GitOid(r.array()?);
762 let n = r.len(MAX_LIST_ITEMS, "source.parent_changesets")?;
763 let mut parent_changesets = Vec::with_capacity(n);
764 for _ in 0..n {
765 parent_changesets.push(ChangesetId(r.array()?));
766 }
767
768 let n = r.len(MAX_LIST_ITEMS, "crumb_contexts")?;
769 let mut crumb_contexts = Vec::with_capacity(n);
770 for _ in 0..n {
771 let dir = r.string("crumb_contexts")?;
772 crumb_contexts.push(CrumbContextBinding {
773 dir,
774 at_base: CrumbContextDigest(r.array()?),
775 in_changeset: CrumbContextDigest(r.array()?),
776 });
777 }
778
779 let n = r.len(MAX_LIST_ITEMS, "input_root")?;
780 let mut members = Vec::with_capacity(n);
781 for _ in 0..n {
782 let repo_id = r.repo_id("input_root")?;
783 let kind = r.u8()?;
784 if kind != INPUT_MEMBER_CHANGESET {
785 return Err(ReceiptError::UnknownTag("input_root.kind", kind));
786 }
787 members.push(InputRootMember {
788 repo_id,
789 changeset_id: ChangesetId(r.array()?),
790 });
791 }
792
793 let name = r.string("test.name")?;
794 let n = r.len(MAX_LIST_ITEMS, "test.command")?;
795 let mut command = Vec::with_capacity(n);
796 for _ in 0..n {
797 command.push(r.string("test.command")?);
798 }
799 let toolchain = r.string("test.toolchain")?;
800 let platform = r.string("test.platform")?;
801 let n = r.len(MAX_LIST_ITEMS, "test.environment")?;
802 let mut environment = Vec::with_capacity(n);
803 for _ in 0..n {
804 environment.push(EnvVar {
805 name: r.string("test.environment")?,
806 value: r.string("test.environment")?,
807 });
808 }
809
810 let exit_status = match r.u8()? {
811 1 => ExitStatus::Code(r.i32()?),
812 2 => ExitStatus::Signal(r.i32()?),
813 t => return Err(ReceiptError::UnknownTag("result.exit_status", t)),
814 };
815 let outcome = match r.u8()? {
816 1 => Outcome::Pass,
817 2 => Outcome::Fail,
818 3 => Outcome::Flaky,
819 4 => Outcome::Error,
820 t => return Err(ReceiptError::UnknownTag("result.outcome", t)),
821 };
822 let n = r.len(MAX_LIST_ITEMS, "result.outputs")?;
823 let mut outputs = Vec::with_capacity(n);
824 for _ in 0..n {
825 outputs.push(DeclaredOutput {
826 name: r.string("result.outputs")?,
827 digest: OutputDigest(r.array()?),
828 });
829 }
830
831 let started_at_ms = r.u64()?;
832 let duration_ms = r.u64()?;
833 let n = r.len(MAX_LOG_BYTES, "observation.log")?;
834 let log = r.take(n)?.to_vec();
835
836 let body = ReceiptBody {
837 repo_id,
838 changeset_id,
839 source: SourceRevision {
840 base_git_oid,
841 parent_changesets,
842 },
843 crumb_contexts,
844 input_root: InputRoot { members },
845 test: TestIdentity {
846 name,
847 command,
848 toolchain,
849 platform,
850 environment,
851 },
852 result: ReceiptResult {
853 exit_status,
854 outcome,
855 outputs,
856 },
857 observation: Observation {
858 started_at_ms,
859 duration_ms,
860 log,
861 },
862 };
863 body.validate()?;
864 Ok(body)
865}
866
867fn cap_str(s: &str, field: &'static str) -> Result<(), ReceiptError> {
868 if s.len() > MAX_STRING_BYTES {
869 return Err(ReceiptError::OverCap(field));
870 }
871 Ok(())
872}
873
874fn cap_list(n: usize, field: &'static str) -> Result<(), ReceiptError> {
875 if n > MAX_LIST_ITEMS {
876 return Err(ReceiptError::OverCap(field));
877 }
878 Ok(())
879}
880
881fn strictly_sorted<T: Ord, I: Iterator<Item = T>>(
882 mut it: I,
883 field: &'static str,
884) -> Result<(), ReceiptError> {
885 let Some(mut prev) = it.next() else {
886 return Ok(());
887 };
888 for next in it {
889 if next <= prev {
890 return Err(ReceiptError::Unsorted(field));
891 }
892 prev = next;
893 }
894 Ok(())
895}
896
897#[cfg(test)]
898mod tests;