1use std::collections::HashSet;
23use std::fmt;
24
25use base64::Engine as _;
26use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
27use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
28use serde::{Deserialize, Serialize, Serializer};
29use serde_json::{Map, Value, json};
30
31const RECEIPT_V1_SCHEMA: &str = "vela.receipt.v1";
32const MAX_RECEIPT_V1_BYTES: usize = 8 * 1024 * 1024;
33const MAX_RECEIPT_V1_DEPTH: usize = 64;
34const MAX_RECEIPT_V1_STRING_BYTES: usize = 1024 * 1024;
35const MAX_RECEIPT_V1_ARTIFACTS: usize = 10_000;
36const MAX_RECEIPT_V1_LOCATOR_BYTES: usize = 16 * 1024;
37const MAX_RECEIPT_V1_OBJECT_FIELDS: usize = 65_536;
38const MAX_RECEIPT_V1_ARRAY_ELEMENTS: usize = 65_536;
39const MAX_RECEIPT_V1_NODES: usize = 131_072;
40const MAX_RECEIPT_V1_DSSE_BYTES: usize = 1024 * 1024;
41const MAX_PORTABLE_JSON_INTEGER: u64 = (1_u64 << 53) - 1;
48const MAX_RESTRICTED_ARTIFACT_OPAQUE_ID_BYTES: usize = 512;
49const MAX_RESTRICTED_ARTIFACT_KIND_BYTES: usize = 128;
50const MAX_RESTRICTED_ARTIFACT_MEDIA_TYPE_BYTES: usize = 255;
51const RECEIPT_BODY_BINDING_FIELD: &str = "vela:receipt_body";
52const RECEIPT_PREDICATE_SCHEMA: &str = "vela.receipt.predicate.v1";
53const NEUTRAL_RECEIPT_GENERATOR: &str = "vela-protocol/neutral-receipt-v1";
54const NO_ACTIVE_POLICY_REF: &str = "urn:vela:policy:none";
55const SCIENTIFIC_CHAIN_SCHEMA: &str = "vela.scientific-chain.producer.v1";
56pub const EXECUTION_BINDING_SCHEMA: &str = "vela.execution-binding.v1";
57const SCIENTIFIC_CHAIN_MAX_TEXT_BYTES: usize = 16 * 1024;
58const SCIENTIFIC_CHAIN_MAX_REFERENCE_BYTES: usize = 16 * 1024;
59const SCIENTIFIC_CHAIN_MAX_REFERENCES: usize = 64;
60
61const RECEIPT_V1_REQUIRED_FIELDS: &[&str] = &[
63 "schema",
64 "claim",
65 "type",
66 "replayability",
67 "artifacts",
68 "caveats",
69 "verifier_runs",
70 "environment",
71 "provenance",
72 "status",
73 "machine",
74 "acceptance",
75 "distillation",
76 "lineage",
77 "contributors",
78 "signature_identities",
79 "attestation",
80];
81
82const CLAIM_TYPES: &[&str] = &[
83 "computational",
84 "theoretical",
85 "empirical",
86 "negative",
87 "contradiction",
88];
89const REPLAYABILITY: &[&str] = &["exact", "bounded", "approximate", "unavailable", "unknown"];
90const VERIFIER_OUTCOMES: &[&str] = &["pass", "fail", "error", "skipped", "unknown"];
91const STATUS_KINDS: &[&str] = &[
92 "draft",
93 "emitted",
94 "proposed",
95 "runs",
96 "minimal_sanity_check",
97 "reported_metric_rederived",
98 "full_reproduction",
99 "landed_pending",
100 "accepted",
101 "rejected",
102 "superseded",
103 "retracted",
104 "contested",
105 "failed_reproduction",
106];
107const STATUS_AUTHORITIES: &[&str] = &["producer", "vela_landing", "human_key", "signed_policy"];
108const CONTRIBUTOR_ROLES: &[&str] = &[
109 "conceptualization",
110 "data_curation",
111 "formal_analysis",
112 "funding_acquisition",
113 "investigation",
114 "methodology",
115 "project_administration",
116 "resources",
117 "software",
118 "supervision",
119 "validation",
120 "visualization",
121 "writing_original_draft",
122 "writing_review_editing",
123 "machine_producer",
124 "human_formalizer",
125 "human_distiller",
126 "reviewer",
127 "acceptor",
128 "profile_maintainer",
129];
130const IDENTITY_MECHANISMS: &[&str] = &[
131 "sigstore_keyless_oidc",
132 "sigstore_keyless_oidc_fixture",
133 "ed25519_key_custody_ceremony",
134 "ed25519_key_custody_ceremony_fixture",
135];
136const ACCEPTANCE_MECHANISM: &str = "accountable_scientific_steward_signoff";
137const INTOTO_STATEMENT_TYPE: &str = "https://in-toto.io/Statement/v1";
138const VELA_PREDICATE_TYPE: &str = "https://vela.science/receipt/v1";
139const INTOTO_PAYLOAD_TYPE: &str = "application/vnd.in-toto+json";
140
141#[derive(Debug, Clone, Copy)]
142struct ReceiptLimits {
143 bytes: usize,
144 depth: usize,
145 string_bytes: usize,
146 artifacts: usize,
147 locator_bytes: usize,
148 object_fields: usize,
149 array_elements: usize,
150 nodes: usize,
151 dsse_bytes: usize,
152}
153
154const LIMITS: ReceiptLimits = ReceiptLimits {
155 bytes: MAX_RECEIPT_V1_BYTES,
156 depth: MAX_RECEIPT_V1_DEPTH,
157 string_bytes: MAX_RECEIPT_V1_STRING_BYTES,
158 artifacts: MAX_RECEIPT_V1_ARTIFACTS,
159 locator_bytes: MAX_RECEIPT_V1_LOCATOR_BYTES,
160 object_fields: MAX_RECEIPT_V1_OBJECT_FIELDS,
161 array_elements: MAX_RECEIPT_V1_ARRAY_ELEMENTS,
162 nodes: MAX_RECEIPT_V1_NODES,
163 dsse_bytes: MAX_RECEIPT_V1_DSSE_BYTES,
164};
165
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ReceiptV1Error {
168 path: String,
169 message: String,
170}
171
172impl ReceiptV1Error {
173 fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
174 Self {
175 path: path.into(),
176 message: message.into(),
177 }
178 }
179
180 pub fn path(&self) -> &str {
181 &self.path
182 }
183
184 pub fn message(&self) -> &str {
185 &self.message
186 }
187}
188
189impl fmt::Display for ReceiptV1Error {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 write!(f, "receipt v1 {}: {}", self.path, self.message)
192 }
193}
194
195impl std::error::Error for ReceiptV1Error {}
196
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields)]
204pub struct ExecutionBindingV1 {
205 pub schema: String,
206 pub packet_root: String,
207 pub profile_root: String,
208 pub verifier_capsule_root: String,
209 pub result_contract_root: String,
210}
211
212impl ExecutionBindingV1 {
213 pub fn validate(&self) -> Result<(), String> {
214 if self.schema != EXECUTION_BINDING_SCHEMA {
215 return Err(format!("schema must be {EXECUTION_BINDING_SCHEMA}"));
216 }
217 for (field, value) in [
218 ("packet_root", &self.packet_root),
219 ("profile_root", &self.profile_root),
220 ("verifier_capsule_root", &self.verifier_capsule_root),
221 ("result_contract_root", &self.result_contract_root),
222 ] {
223 if !is_full_sha256_root(value) {
224 return Err(format!("{field} must be a full lowercase sha256 root"));
225 }
226 }
227 Ok(())
228 }
229}
230
231pub fn is_full_sha256_root(value: &str) -> bool {
232 value.strip_prefix("sha256:").is_some_and(|digest| {
233 digest.len() == 64
234 && digest
235 .bytes()
236 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
237 })
238}
239
240#[derive(Debug, Clone, PartialEq)]
246pub struct ReceiptV1 {
247 value: Value,
248}
249
250impl ReceiptV1 {
251 pub fn parse(bytes: &[u8]) -> Result<Self, ReceiptV1Error> {
252 Self::parse_with_limits(bytes, LIMITS)
253 }
254
255 fn parse_with_limits(bytes: &[u8], limits: ReceiptLimits) -> Result<Self, ReceiptV1Error> {
256 if bytes.len() > limits.bytes {
257 return Err(error(
258 "$",
259 format!(
260 "encoded JSON is {} bytes; limit is {} bytes",
261 bytes.len(),
262 limits.bytes
263 ),
264 ));
265 }
266 let value = decode_bounded_json(bytes, limits, "$", false)?;
267 Self::from_value_with_limits(value, limits)
268 }
269
270 pub(crate) fn from_trusted_value(value: Value) -> Result<Self, ReceiptV1Error> {
274 Self::from_value_with_limits(value, LIMITS)
275 }
276
277 fn from_value_with_limits(value: Value, limits: ReceiptLimits) -> Result<Self, ReceiptV1Error> {
278 validate_limits(&value, limits)?;
279 validate_portable_numeric_domain(&value, "$")?;
280 validate_schema_exact(&value)?;
281 validate_semantics(&value, limits)?;
282 let canonical = canonical_receipt_bytes(&value)?;
283 if canonical.len() > limits.bytes {
284 return Err(error(
285 "$",
286 format!(
287 "canonical JSON is {} bytes; limit is {} bytes",
288 canonical.len(),
289 limits.bytes
290 ),
291 ));
292 }
293 Ok(Self { value })
294 }
295
296 pub fn as_value(&self) -> &Value {
297 &self.value
298 }
299
300 pub fn into_value(self) -> Value {
301 self.value
302 }
303
304 pub fn canonical_bytes(&self) -> Result<Vec<u8>, ReceiptV1Error> {
305 canonical_receipt_bytes(&self.value)
306 }
307
308 pub fn canonical_root(&self) -> Result<String, ReceiptV1Error> {
310 use sha2::{Digest as _, Sha256};
311
312 canonical_receipt_bytes(&self.value)
313 .map(|bytes| format!("sha256:{}", hex::encode(Sha256::digest(bytes))))
314 }
315
316 pub fn validate_safe_public_artifact_descriptors(&self) -> Result<(), ReceiptV1Error> {
328 validate_safe_public_artifact_descriptors(object(&self.value, "$")?)
329 }
330
331 pub fn execution_binding(&self) -> Result<Option<ExecutionBindingV1>, ReceiptV1Error> {
333 parse_execution_binding_extension(object(&self.value, "$")?)
334 }
335
336 pub fn producer_identity_binding(
339 &self,
340 ) -> Result<Option<crate::identity::IdentityBinding>, ReceiptV1Error> {
341 let environment = object(&self.value["environment"], "$.environment")?;
342 let Some(context_value) = environment.get("vela:producer_context") else {
343 return Ok(None);
344 };
345 let context = object(context_value, "$.environment.vela:producer_context")?;
346 let Some(binding_value) = context.get("identity_binding") else {
347 return Ok(None);
348 };
349 let binding =
350 serde_json::from_value::<crate::identity::IdentityBinding>(binding_value.clone())
351 .map_err(|cause| {
352 error(
353 "$.environment.vela:producer_context.identity_binding",
354 format!("must be a complete IdentityBinding: {cause}"),
355 )
356 })?;
357 binding.verify().map_err(|cause| {
358 error(
359 "$.environment.vela:producer_context.identity_binding",
360 format!("does not verify proof of possession: {cause}"),
361 )
362 })?;
363 Ok(Some(binding))
364 }
365}
366
367impl AsRef<Value> for ReceiptV1 {
368 fn as_ref(&self) -> &Value {
369 self.as_value()
370 }
371}
372
373impl Serialize for ReceiptV1 {
374 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
375 where
376 S: Serializer,
377 {
378 self.value.serialize(serializer)
379 }
380}
381
382fn error(path: impl Into<String>, message: impl Into<String>) -> ReceiptV1Error {
383 ReceiptV1Error::new(path, message)
384}
385
386#[derive(Debug)]
387struct DecodeState {
388 limits: ReceiptLimits,
389 nodes: usize,
390 object_fields: usize,
391 array_elements: usize,
392}
393
394impl DecodeState {
395 fn new(limits: ReceiptLimits) -> Self {
396 Self {
397 limits,
398 nodes: 0,
399 object_fields: 0,
400 array_elements: 0,
401 }
402 }
403
404 fn bump_node<E: de::Error>(&mut self, path: &str) -> Result<(), E> {
405 self.nodes = self.nodes.saturating_add(1);
406 if self.nodes > self.limits.nodes {
407 return Err(E::custom(format!(
408 "{path}: JSON node budget exceeds {}",
409 self.limits.nodes
410 )));
411 }
412 Ok(())
413 }
414
415 fn bump_object_field<E: de::Error>(&mut self, path: &str) -> Result<(), E> {
416 self.object_fields = self.object_fields.saturating_add(1);
417 if self.object_fields > self.limits.object_fields {
418 return Err(E::custom(format!(
419 "{path}: object-field budget exceeds {}",
420 self.limits.object_fields
421 )));
422 }
423 Ok(())
424 }
425
426 fn bump_array_element<E: de::Error>(&mut self, path: &str) -> Result<(), E> {
427 self.array_elements = self.array_elements.saturating_add(1);
428 if self.array_elements > self.limits.array_elements {
429 return Err(E::custom(format!(
430 "{path}: array-element budget exceeds {}",
431 self.limits.array_elements
432 )));
433 }
434 Ok(())
435 }
436
437 fn check_container_depth<E: de::Error>(&self, path: &str, depth: usize) -> Result<(), E> {
438 if depth > self.limits.depth {
439 return Err(E::custom(format!(
440 "{path}: JSON depth is {depth}; limit is {}",
441 self.limits.depth
442 )));
443 }
444 Ok(())
445 }
446
447 fn check_string<E: de::Error>(&self, path: &str, value: &str) -> Result<(), E> {
448 if value.len() > self.limits.string_bytes {
449 return Err(E::custom(format!(
450 "{path}: string is {} bytes; limit is {} bytes",
451 value.len(),
452 self.limits.string_bytes
453 )));
454 }
455 Ok(())
456 }
457}
458
459struct BoundedValueSeed<'a> {
460 state: &'a mut DecodeState,
461 parent_depth: usize,
462 path: String,
463}
464
465impl<'de> DeserializeSeed<'de> for BoundedValueSeed<'_> {
466 type Value = Value;
467
468 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
469 where
470 D: de::Deserializer<'de>,
471 {
472 self.state.bump_node::<D::Error>(&self.path)?;
473 deserializer.deserialize_any(BoundedValueVisitor {
474 state: self.state,
475 parent_depth: self.parent_depth,
476 path: self.path,
477 })
478 }
479}
480
481struct BoundedValueVisitor<'a> {
482 state: &'a mut DecodeState,
483 parent_depth: usize,
484 path: String,
485}
486
487impl<'de> Visitor<'de> for BoundedValueVisitor<'_> {
488 type Value = Value;
489
490 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
491 formatter.write_str("a bounded JSON value without duplicate object names")
492 }
493
494 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
495 where
496 E: de::Error,
497 {
498 Ok(Value::Bool(value))
499 }
500
501 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
502 where
503 E: de::Error,
504 {
505 if value.unsigned_abs() > MAX_PORTABLE_JSON_INTEGER {
506 return Err(E::custom(format!(
507 "{}: integer {value} is outside the portable JSON range -{MAX_PORTABLE_JSON_INTEGER}..={MAX_PORTABLE_JSON_INTEGER}",
508 self.path
509 )));
510 }
511 Ok(Value::Number(value.into()))
512 }
513
514 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
515 where
516 E: de::Error,
517 {
518 if value > MAX_PORTABLE_JSON_INTEGER {
519 return Err(E::custom(format!(
520 "{}: integer {value} is outside the portable JSON range -{MAX_PORTABLE_JSON_INTEGER}..={MAX_PORTABLE_JSON_INTEGER}",
521 self.path
522 )));
523 }
524 Ok(Value::Number(value.into()))
525 }
526
527 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
528 where
529 E: de::Error,
530 {
531 if !value.is_finite() {
532 return Err(E::custom(format!("{}: non-finite JSON number", self.path)));
533 }
534 if value.fract() == 0.0 && value.abs() > MAX_PORTABLE_JSON_INTEGER as f64 {
535 return Err(E::custom(format!(
536 "{}: integral number {value} is outside the portable JSON range -{MAX_PORTABLE_JSON_INTEGER}..={MAX_PORTABLE_JSON_INTEGER}",
537 self.path
538 )));
539 }
540 serde_json::Number::from_f64(value)
541 .map(Value::Number)
542 .ok_or_else(|| E::custom(format!("{}: non-finite JSON number", self.path)))
543 }
544
545 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
546 where
547 E: de::Error,
548 {
549 self.state.check_string::<E>(&self.path, value)?;
550 Ok(Value::String(value.to_string()))
551 }
552
553 fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
554 where
555 E: de::Error,
556 {
557 self.visit_str(value)
558 }
559
560 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
561 where
562 E: de::Error,
563 {
564 self.state.check_string::<E>(&self.path, &value)?;
565 Ok(Value::String(value))
566 }
567
568 fn visit_none<E>(self) -> Result<Self::Value, E>
569 where
570 E: de::Error,
571 {
572 Ok(Value::Null)
573 }
574
575 fn visit_unit<E>(self) -> Result<Self::Value, E>
576 where
577 E: de::Error,
578 {
579 Ok(Value::Null)
580 }
581
582 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
583 where
584 A: SeqAccess<'de>,
585 {
586 let depth = self.parent_depth.saturating_add(1);
587 self.state
588 .check_container_depth::<A::Error>(&self.path, depth)?;
589 let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(1024));
590 let mut index = 0usize;
591 loop {
592 let child_path = format!("{}[{index}]", self.path);
593 let seed = BoundedValueSeed {
594 state: self.state,
595 parent_depth: depth,
596 path: child_path.clone(),
597 };
598 let Some(value) = sequence.next_element_seed(seed)? else {
599 break;
600 };
601 self.state.bump_array_element::<A::Error>(&child_path)?;
602 values.push(value);
603 index = index.saturating_add(1);
604 }
605 Ok(Value::Array(values))
606 }
607
608 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
609 where
610 A: MapAccess<'de>,
611 {
612 let depth = self.parent_depth.saturating_add(1);
613 self.state
614 .check_container_depth::<A::Error>(&self.path, depth)?;
615 let mut value = Map::new();
616 let mut names = HashSet::new();
617 while let Some(key) = entries.next_key::<String>()? {
618 self.state.check_string::<A::Error>(&self.path, &key)?;
619 let child_path = format!("{}.{}", self.path, key);
620 self.state.bump_object_field::<A::Error>(&child_path)?;
621 if !names.insert(key.clone()) {
622 return Err(<A::Error as de::Error>::custom(format!(
623 "{child_path}: duplicate object name `{key}`"
624 )));
625 }
626 let item = entries.next_value_seed(BoundedValueSeed {
627 state: self.state,
628 parent_depth: depth,
629 path: child_path.clone(),
630 })?;
631 if is_locator_key(&key) {
632 validate_locator_value(&item, &child_path, self.state.limits.locator_bytes)
633 .map_err(<A::Error as de::Error>::custom)?;
634 }
635 value.insert(key, item);
636 }
637 Ok(Value::Object(value))
638 }
639}
640
641fn decode_bounded_json(
642 bytes: &[u8],
643 limits: ReceiptLimits,
644 root_path: &str,
645 dsse_payload: bool,
646) -> Result<Value, ReceiptV1Error> {
647 let byte_limit = if dsse_payload {
648 limits.dsse_bytes
649 } else {
650 limits.bytes
651 };
652 if bytes.len() > byte_limit {
653 return Err(error(
654 root_path,
655 format!(
656 "encoded JSON is {} bytes; limit is {} bytes",
657 bytes.len(),
658 byte_limit
659 ),
660 ));
661 }
662 let mut state = DecodeState::new(limits);
663 let mut deserializer = serde_json::Deserializer::from_slice(bytes);
664 let value = BoundedValueSeed {
665 state: &mut state,
666 parent_depth: 0,
667 path: root_path.to_string(),
668 }
669 .deserialize(&mut deserializer)
670 .map_err(|cause| error(root_path, format!("invalid JSON: {cause}")))?;
671 deserializer
672 .end()
673 .map_err(|cause| error(root_path, format!("invalid JSON: {cause}")))?;
674 Ok(value)
675}
676
677fn is_locator_key(key: &str) -> bool {
678 let local = key
679 .rsplit([':', '#', '/'])
680 .next()
681 .unwrap_or(key)
682 .chars()
683 .filter(char::is_ascii_alphanumeric)
684 .flat_map(char::to_lowercase)
685 .collect::<String>();
686 matches!(
687 local.as_str(),
688 "parents" | "supersedes" | "derivedfrom" | "sourcerefs"
689 ) || [
690 "path",
691 "uri",
692 "url",
693 "locator",
694 "ref",
695 "refs",
696 "reference",
697 "references",
698 ]
699 .iter()
700 .any(|suffix| local == *suffix || local.ends_with(suffix))
701}
702
703fn validate_locator_value(value: &Value, path: &str, limit: usize) -> Result<(), String> {
704 let locators: Vec<&str> = match value {
705 Value::String(text) => vec![text],
706 Value::Array(items) => items.iter().filter_map(Value::as_str).collect(),
707 _ => Vec::new(),
708 };
709 for locator in locators {
710 if locator.len() > limit {
711 return Err(format!(
712 "{path}: locator is {} bytes; limit is {limit} bytes",
713 locator.len()
714 ));
715 }
716 }
717 Ok(())
718}
719
720fn validate_portable_numeric_domain(value: &Value, path: &str) -> Result<(), ReceiptV1Error> {
721 match value {
722 Value::Number(number) => {
723 let portable_integer = number
724 .as_i64()
725 .is_some_and(|value| value.unsigned_abs() <= MAX_PORTABLE_JSON_INTEGER)
726 || number
727 .as_u64()
728 .is_some_and(|value| value <= MAX_PORTABLE_JSON_INTEGER);
729 let portable_float = number.as_f64().is_some_and(|value| {
730 value.is_finite()
731 && (value.fract() != 0.0 || value.abs() <= MAX_PORTABLE_JSON_INTEGER as f64)
732 });
733 let portable = portable_integer || portable_float;
734 if !portable {
735 return Err(error(
736 path,
737 format!(
738 "integral JSON numbers must be in -{MAX_PORTABLE_JSON_INTEGER}..={MAX_PORTABLE_JSON_INTEGER}; encode larger exact quantities as strings"
739 ),
740 ));
741 }
742 }
743 Value::Array(items) => {
744 for (index, item) in items.iter().enumerate() {
745 validate_portable_numeric_domain(item, &format!("{path}[{index}]"))?;
746 }
747 }
748 Value::Object(entries) => {
749 for (key, item) in entries {
750 validate_portable_numeric_domain(item, &format!("{path}.{key}"))?;
751 }
752 }
753 Value::Null | Value::Bool(_) | Value::String(_) => {}
754 }
755 Ok(())
756}
757
758fn canonical_receipt_bytes(value: &Value) -> Result<Vec<u8>, ReceiptV1Error> {
761 validate_portable_numeric_domain(value, "$")?;
762 serde_json_canonicalizer::to_vec(value)
763 .map_err(|cause| error("$", format!("canonical Receipt JSON failed: {cause}")))
764}
765
766fn validate_limits(value: &Value, limits: ReceiptLimits) -> Result<(), ReceiptV1Error> {
767 let artifacts = value
768 .get("artifacts")
769 .and_then(Value::as_array)
770 .map_or(0, Vec::len);
771 if artifacts > limits.artifacts {
772 return Err(error(
773 "$.artifacts",
774 format!(
775 "contains {artifacts} descriptors; limit is {}",
776 limits.artifacts
777 ),
778 ));
779 }
780 let mut counts = LimitCounts::default();
781 let root_depth = usize::from(value.is_object() || value.is_array());
782 walk_limits(value, "$", root_depth, limits, &mut counts)
783}
784
785#[derive(Debug, Default)]
786struct LimitCounts {
787 nodes: usize,
788 object_fields: usize,
789 array_elements: usize,
790}
791
792fn walk_limits(
793 value: &Value,
794 path: &str,
795 depth: usize,
796 limits: ReceiptLimits,
797 counts: &mut LimitCounts,
798) -> Result<(), ReceiptV1Error> {
799 counts.nodes = counts.nodes.saturating_add(1);
800 if counts.nodes > limits.nodes {
801 return Err(error(
802 path,
803 format!("JSON node budget exceeds {}", limits.nodes),
804 ));
805 }
806 if depth > limits.depth {
807 return Err(error(
808 path,
809 format!("JSON depth is {depth}; limit is {}", limits.depth),
810 ));
811 }
812 match value {
813 Value::String(text) if text.len() > limits.string_bytes => Err(error(
814 path,
815 format!(
816 "string is {} bytes; limit is {} bytes",
817 text.len(),
818 limits.string_bytes
819 ),
820 )),
821 Value::Array(items) => {
822 counts.array_elements = counts.array_elements.saturating_add(items.len());
823 if counts.array_elements > limits.array_elements {
824 return Err(error(
825 path,
826 format!("array-element budget exceeds {}", limits.array_elements),
827 ));
828 }
829 for (index, item) in items.iter().enumerate() {
830 let child_depth = depth + usize::from(item.is_object() || item.is_array());
831 walk_limits(
832 item,
833 &format!("{path}[{index}]"),
834 child_depth,
835 limits,
836 counts,
837 )?;
838 }
839 Ok(())
840 }
841 Value::Object(object) => {
842 counts.object_fields = counts.object_fields.saturating_add(object.len());
843 if counts.object_fields > limits.object_fields {
844 return Err(error(
845 path,
846 format!("object-field budget exceeds {}", limits.object_fields),
847 ));
848 }
849 for (key, item) in object {
850 if key.len() > limits.string_bytes {
851 return Err(error(path, "object key exceeds the string-byte limit"));
852 }
853 let child_path = format!("{path}.{key}");
854 if is_locator_key(key) {
855 validate_locator_value(item, &child_path, limits.locator_bytes)
856 .map_err(|message| error(&child_path, message))?;
857 }
858 let child_depth = depth + usize::from(item.is_object() || item.is_array());
859 walk_limits(item, &child_path, child_depth, limits, counts)?;
860 }
861 Ok(())
862 }
863 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => Ok(()),
864 }
865}
866
867fn object<'a>(value: &'a Value, path: &str) -> Result<&'a Map<String, Value>, ReceiptV1Error> {
868 value
869 .as_object()
870 .ok_or_else(|| error(path, "must be an object"))
871}
872
873fn array<'a>(value: &'a Value, path: &str) -> Result<&'a Vec<Value>, ReceiptV1Error> {
874 value
875 .as_array()
876 .ok_or_else(|| error(path, "must be an array"))
877}
878
879fn required<'a>(
880 object: &'a Map<String, Value>,
881 key: &str,
882 path: &str,
883) -> Result<&'a Value, ReceiptV1Error> {
884 object
885 .get(key)
886 .ok_or_else(|| error(format!("{path}.{key}"), "is required"))
887}
888
889fn text<'a>(value: &'a Value, path: &str, nonempty: bool) -> Result<&'a str, ReceiptV1Error> {
890 let text = value
891 .as_str()
892 .ok_or_else(|| error(path, "must be a string"))?;
893 if nonempty && text.trim().is_empty() {
894 return Err(error(path, "must be a non-empty string"));
895 }
896 Ok(text)
897}
898
899fn enum_text<'a>(
900 value: &'a Value,
901 path: &str,
902 allowed: &[&str],
903) -> Result<&'a str, ReceiptV1Error> {
904 let text = text(value, path, false)?;
905 if !allowed.contains(&text) {
906 return Err(error(
907 path,
908 format!("must be one of {}", allowed.join(", ")),
909 ));
910 }
911 Ok(text)
912}
913
914#[allow(dead_code)]
922mod schema_exact {
923 use serde::Deserialize;
924 use serde_json::{Map, Value};
925
926 struct Optional<T>(Option<T>);
927
928 impl<T> Default for Optional<T> {
929 fn default() -> Self {
930 Self(None)
931 }
932 }
933
934 impl<'de, T> Deserialize<'de> for Optional<T>
935 where
936 T: Deserialize<'de>,
937 {
938 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
939 where
940 D: serde::Deserializer<'de>,
941 {
942 T::deserialize(deserializer).map(|value| Self(Some(value)))
943 }
944 }
945
946 struct Nullable<T>(Option<T>);
947
948 impl<'de, T> Deserialize<'de> for Nullable<T>
949 where
950 T: Deserialize<'de>,
951 {
952 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
953 where
954 D: serde::Deserializer<'de>,
955 {
956 Option::<T>::deserialize(deserializer).map(Self)
957 }
958 }
959
960 #[derive(Deserialize)]
961 #[serde(rename_all = "snake_case")]
962 enum ClaimType {
963 Computational,
964 Theoretical,
965 Empirical,
966 Negative,
967 Contradiction,
968 }
969
970 #[derive(Deserialize)]
971 #[serde(rename_all = "snake_case")]
972 enum Replayability {
973 Exact,
974 Bounded,
975 Approximate,
976 Unavailable,
977 Unknown,
978 }
979
980 #[derive(Deserialize)]
981 #[serde(rename_all = "snake_case")]
982 enum VerifierOutcome {
983 Pass,
984 Fail,
985 Error,
986 Skipped,
987 Unknown,
988 }
989
990 #[derive(Deserialize)]
991 #[serde(rename_all = "snake_case")]
992 enum StatusKind {
993 Draft,
994 Emitted,
995 Proposed,
996 Runs,
997 MinimalSanityCheck,
998 ReportedMetricRederived,
999 FullReproduction,
1000 LandedPending,
1001 Accepted,
1002 Rejected,
1003 Superseded,
1004 Retracted,
1005 Contested,
1006 FailedReproduction,
1007 }
1008
1009 #[derive(Deserialize)]
1010 #[serde(rename_all = "snake_case")]
1011 enum StatusAuthority {
1012 Producer,
1013 VelaLanding,
1014 HumanKey,
1015 SignedPolicy,
1016 }
1017
1018 #[derive(Deserialize)]
1019 #[serde(rename_all = "snake_case")]
1020 enum EvidenceStatus {
1021 Proposed,
1022 Runs,
1023 MinimalSanityCheck,
1024 ReportedMetricRederived,
1025 FullReproduction,
1026 Accepted,
1027 Superseded,
1028 Retracted,
1029 Contested,
1030 FailedReproduction,
1031 }
1032
1033 #[derive(Deserialize)]
1034 #[serde(rename_all = "snake_case")]
1035 enum AcceptanceScope {
1036 MachineVerified,
1037 HumanSeen,
1038 LocallyAccepted,
1039 FrontierAccepted,
1040 CanonAccepted,
1041 HypothesisOnly,
1042 Retracted,
1043 Superseded,
1044 }
1045
1046 #[derive(Deserialize)]
1047 #[serde(rename_all = "snake_case")]
1048 enum EvidenceLevel {
1049 LocalSignoff,
1050 ConsortiumReviewed,
1051 JournalAccepted,
1052 Replicated,
1053 RegulatorGrade,
1054 }
1055
1056 #[derive(Deserialize)]
1057 #[serde(rename_all = "snake_case")]
1058 enum DistillationStatus {
1059 Missing,
1060 NotRequired,
1061 Draft,
1062 Accepted,
1063 Rejected,
1064 Superseded,
1065 Retracted,
1066 }
1067
1068 #[derive(Deserialize)]
1069 #[serde(rename_all = "snake_case")]
1070 enum ContributorRole {
1071 Conceptualization,
1072 DataCuration,
1073 FormalAnalysis,
1074 FundingAcquisition,
1075 Investigation,
1076 Methodology,
1077 ProjectAdministration,
1078 Resources,
1079 Software,
1080 Supervision,
1081 Validation,
1082 Visualization,
1083 WritingOriginalDraft,
1084 WritingReviewEditing,
1085 MachineProducer,
1086 HumanFormalizer,
1087 HumanDistiller,
1088 Reviewer,
1089 Acceptor,
1090 ProfileMaintainer,
1091 }
1092
1093 #[derive(Deserialize)]
1094 #[serde(rename_all = "snake_case")]
1095 enum IdentityRole {
1096 Producer,
1097 Acceptor,
1098 }
1099
1100 #[derive(Deserialize)]
1101 #[serde(rename_all = "snake_case")]
1102 enum IdentityMechanism {
1103 SigstoreKeylessOidc,
1104 SigstoreKeylessOidcFixture,
1105 Ed25519KeyCustodyCeremony,
1106 Ed25519KeyCustodyCeremonyFixture,
1107 }
1108
1109 #[derive(Deserialize)]
1110 struct Artifact {
1111 path: String,
1112 kind: String,
1113 #[serde(default)]
1114 sha256: Optional<String>,
1115 #[serde(default)]
1116 media_type: Optional<String>,
1117 #[serde(default)]
1118 uri: Optional<String>,
1119 }
1120
1121 #[derive(Deserialize)]
1122 struct VerifierRun {
1123 method: String,
1124 outcome: VerifierOutcome,
1125 #[serde(default)]
1126 log: Optional<String>,
1127 #[serde(default)]
1128 solver: Optional<String>,
1129 #[serde(default)]
1130 replay_command: Optional<String>,
1131 }
1132
1133 #[derive(Deserialize)]
1134 struct Provenance {
1135 generated_by: String,
1136 emitted_at: String,
1137 #[serde(default)]
1138 submitter: Optional<Map<String, Value>>,
1139 }
1140
1141 #[derive(Deserialize)]
1142 struct Status {
1143 kind: StatusKind,
1144 authority: StatusAuthority,
1145 #[serde(default)]
1146 evidence_status: Optional<EvidenceStatus>,
1147 #[serde(default)]
1148 scope: Optional<Map<String, Value>>,
1149 }
1150
1151 #[derive(Deserialize)]
1152 struct MachineClaim {
1153 text: Value,
1154 #[serde(rename = "type")]
1155 claim_type: Value,
1156 }
1157
1158 #[derive(Deserialize)]
1159 struct MachineVerification {
1160 status: Value,
1161 verifier_runs: Value,
1162 trust_base: Value,
1163 }
1164
1165 #[derive(Deserialize)]
1166 struct MachineLayer {
1167 subject: Vec<Value>,
1168 claim: MachineClaim,
1169 verification: MachineVerification,
1170 }
1171
1172 #[derive(Deserialize)]
1173 struct AcceptanceLayer {
1174 profile: String,
1175 mechanism: String,
1176 acceptor: Nullable<String>,
1177 #[serde(rename = "policyRef")]
1178 policy_ref: String,
1179 #[serde(rename = "evidenceRefs")]
1180 evidence_refs: Vec<String>,
1181 #[serde(default, rename = "evidenceLevel")]
1182 evidence_level: Optional<Nullable<EvidenceLevel>>,
1183 artifact_verification: Map<String, Value>,
1184 claim_acceptance: Map<String, Value>,
1185 distillation_acceptance: Map<String, Value>,
1186 acceptance_scope: AcceptanceScope,
1187 }
1188
1189 #[derive(Deserialize)]
1190 struct DistillationLayer {
1191 status: DistillationStatus,
1192 audience: String,
1193 rubric: String,
1194 #[serde(default)]
1195 uri: Optional<Nullable<String>>,
1196 #[serde(default)]
1197 digest: Optional<Nullable<Map<String, Value>>>,
1198 #[serde(default)]
1199 level: Optional<String>,
1200 #[serde(default)]
1201 accepted_by: Optional<Nullable<String>>,
1202 #[serde(default)]
1203 comprehension_budget: Optional<String>,
1204 #[serde(default)]
1205 inheritance_note: Optional<String>,
1206 #[serde(default)]
1207 known_gaps: Optional<Vec<Value>>,
1208 #[serde(default)]
1209 signature_refs: Optional<Vec<Value>>,
1210 }
1211
1212 #[derive(Deserialize)]
1213 struct LineageLayer {
1214 parents: Value,
1215 derived_from: Value,
1216 source_refs: Value,
1217 }
1218
1219 #[derive(Deserialize)]
1220 #[serde(deny_unknown_fields)]
1221 struct Contributor {
1222 id: String,
1223 roles: Vec<ContributorRole>,
1224 #[serde(default)]
1225 credit_taxonomy: Optional<String>,
1226 #[serde(default)]
1227 author: Optional<bool>,
1228 #[serde(default)]
1229 note: Optional<String>,
1230 }
1231
1232 #[derive(Deserialize)]
1233 struct SignatureIdentity {
1234 role: IdentityRole,
1235 mechanism: IdentityMechanism,
1236 #[serde(default, rename = "signatureRef")]
1237 signature_ref: Optional<Nullable<String>>,
1238 #[serde(default, rename = "oidcIssuer")]
1239 oidc_issuer: Optional<String>,
1240 #[serde(default)]
1241 orcid: Optional<String>,
1242 #[serde(default)]
1243 subject: Optional<String>,
1244 }
1245
1246 #[derive(Deserialize)]
1247 struct SignatureIdentities {
1248 producer: SignatureIdentity,
1249 #[serde(default)]
1250 acceptor: Optional<SignatureIdentity>,
1251 }
1252
1253 #[derive(Deserialize)]
1254 struct StatementPredicate {
1255 machine: Value,
1256 acceptance: Value,
1257 distillation: Value,
1258 lineage: Value,
1259 provenance: Value,
1260 }
1261
1262 #[derive(Deserialize)]
1263 struct Statement {
1264 #[serde(rename = "_type")]
1265 statement_type: String,
1266 subject: Vec<Value>,
1267 #[serde(rename = "predicateType")]
1268 predicate_type: String,
1269 predicate: StatementPredicate,
1270 }
1271
1272 #[derive(Deserialize)]
1273 struct DsseEnvelope {
1274 #[serde(rename = "payloadType")]
1275 payload_type: String,
1276 payload: String,
1277 signatures: Vec<Value>,
1278 }
1279
1280 #[derive(Deserialize)]
1281 struct Attestation {
1282 format: String,
1283 statement: Statement,
1284 dsse_envelope: DsseEnvelope,
1285 }
1286
1287 #[derive(Deserialize)]
1288 struct Receipt {
1289 schema: String,
1290 #[serde(default)]
1291 claim_id: Optional<String>,
1292 claim: String,
1293 #[serde(rename = "type")]
1294 claim_type: ClaimType,
1295 replayability: Replayability,
1296 artifacts: Vec<Artifact>,
1297 caveats: Vec<String>,
1298 verifier_runs: Vec<VerifierRun>,
1299 #[serde(default)]
1300 conditions: Optional<Vec<String>>,
1301 #[serde(default)]
1302 verification_requirements: Optional<Vec<String>>,
1303 #[serde(default)]
1304 state_diff: Optional<Map<String, Value>>,
1305 environment: Map<String, Value>,
1306 provenance: Provenance,
1307 status: Status,
1308 machine: MachineLayer,
1309 acceptance: AcceptanceLayer,
1310 distillation: DistillationLayer,
1311 lineage: LineageLayer,
1312 contributors: Vec<Contributor>,
1313 signature_identities: SignatureIdentities,
1314 attestation: Attestation,
1315 }
1316
1317 pub(super) fn validate(value: &Value) -> Result<(), String> {
1318 serde_json::from_value::<Receipt>(value.clone())
1319 .map(|_| ())
1320 .map_err(|cause| cause.to_string())
1321 }
1322}
1323
1324fn validate_schema_exact(value: &Value) -> Result<(), ReceiptV1Error> {
1325 schema_exact::validate(value).map_err(|cause| {
1326 error(
1327 "$",
1328 format!("does not match frozen Receipt v1 schema: {cause}"),
1329 )
1330 })
1331}
1332
1333fn validate_semantics(value: &Value, limits: ReceiptLimits) -> Result<(), ReceiptV1Error> {
1336 let receipt = object(value, "$")?;
1337 for field in RECEIPT_V1_REQUIRED_FIELDS {
1338 required(receipt, field, "$")?;
1339 }
1340 if text(required(receipt, "schema", "$")?, "$.schema", false)? != RECEIPT_V1_SCHEMA {
1341 return Err(error("$.schema", format!("must be {RECEIPT_V1_SCHEMA}")));
1342 }
1343 text(required(receipt, "claim", "$")?, "$.claim", true)?;
1344 enum_text(required(receipt, "type", "$")?, "$.type", CLAIM_TYPES)?;
1345 enum_text(
1346 required(receipt, "replayability", "$")?,
1347 "$.replayability",
1348 REPLAYABILITY,
1349 )?;
1350
1351 let artifacts = array(required(receipt, "artifacts", "$")?, "$.artifacts")?;
1352 for (index, item) in artifacts.iter().enumerate() {
1353 let path = format!("$.artifacts[{index}]");
1354 let item = object(item, &path)?;
1355 text(
1356 required(item, "path", &path)?,
1357 &format!("{path}.path"),
1358 true,
1359 )?;
1360 text(
1361 required(item, "kind", &path)?,
1362 &format!("{path}.kind"),
1363 true,
1364 )?;
1365 if let Some(hash) = item.get("sha256") {
1366 let hash = text(hash, &format!("{path}.sha256"), false)?;
1367 if hash.len() != 64
1368 || !hash
1369 .bytes()
1370 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1371 {
1372 return Err(error(
1373 format!("{path}.sha256"),
1374 "must be 64 lowercase hexadecimal characters",
1375 ));
1376 }
1377 }
1378 }
1379 validate_safe_public_artifact_descriptors(receipt)?;
1380 validate_scientific_chain_extension(receipt)?;
1381 validate_execution_binding_extension(receipt)?;
1382
1383 let caveats = array(required(receipt, "caveats", "$")?, "$.caveats")?;
1384 if caveats.is_empty() {
1385 return Err(error("$.caveats", "must contain at least one caveat"));
1386 }
1387 for (index, caveat) in caveats.iter().enumerate() {
1388 text(caveat, &format!("$.caveats[{index}]"), true)?;
1389 }
1390
1391 let runs = array(required(receipt, "verifier_runs", "$")?, "$.verifier_runs")?;
1392 for (index, run) in runs.iter().enumerate() {
1393 let path = format!("$.verifier_runs[{index}]");
1394 let run = object(run, &path)?;
1395 text(
1396 required(run, "method", &path)?,
1397 &format!("{path}.method"),
1398 true,
1399 )?;
1400 enum_text(
1401 required(run, "outcome", &path)?,
1402 &format!("{path}.outcome"),
1403 VERIFIER_OUTCOMES,
1404 )?;
1405 }
1406
1407 for field in [
1408 "environment",
1409 "provenance",
1410 "status",
1411 "machine",
1412 "acceptance",
1413 "distillation",
1414 "lineage",
1415 "signature_identities",
1416 "attestation",
1417 ] {
1418 object(required(receipt, field, "$")?, &format!("$.{field}"))?;
1419 }
1420 validate_provenance(receipt)?;
1421 validate_status(receipt)?;
1422 validate_machine(receipt)?;
1423 validate_acceptance(receipt)?;
1424 validate_distillation_and_lineage(receipt)?;
1425 validate_contributors(receipt)?;
1426 validate_identities(receipt)?;
1427 validate_attestation(receipt, limits)
1428}
1429
1430fn validate_scientific_chain_extension(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1431 let environment = object(&receipt["environment"], "$.environment")?;
1432 let Some(value) = environment.get("vela:scientific_chain") else {
1433 return Ok(());
1434 };
1435 let path = "$.environment.vela:scientific_chain";
1436 let assertion = object(value, path)?;
1437 let allowed = [
1438 "schema",
1439 "authority",
1440 "predicted_observable",
1441 "not_applicable",
1442 "performed_test",
1443 "result",
1444 "evidence",
1445 "counterevidence",
1446 ];
1447 if let Some(field) = assertion
1448 .keys()
1449 .find(|field| !allowed.contains(&field.as_str()))
1450 {
1451 return Err(error(
1452 format!("{path}.{field}"),
1453 "is not a scientific-chain producer assertion field",
1454 ));
1455 }
1456 if text(
1457 required(assertion, "schema", path)?,
1458 &format!("{path}.schema"),
1459 false,
1460 )? != SCIENTIFIC_CHAIN_SCHEMA
1461 {
1462 return Err(error(
1463 format!("{path}.schema"),
1464 format!("must be {SCIENTIFIC_CHAIN_SCHEMA}"),
1465 ));
1466 }
1467 if text(
1468 required(assertion, "authority", path)?,
1469 &format!("{path}.authority"),
1470 false,
1471 )? != "producer"
1472 {
1473 return Err(error(format!("{path}.authority"), "must be producer"));
1474 }
1475 let predicted = assertion
1476 .get("predicted_observable")
1477 .map(|value| scientific_chain_text(value, &format!("{path}.predicted_observable")))
1478 .transpose()?;
1479 let not_applicable = required(assertion, "not_applicable", path)?
1480 .as_bool()
1481 .ok_or_else(|| error(format!("{path}.not_applicable"), "must be a boolean"))?;
1482 if predicted.is_some() == not_applicable {
1483 return Err(error(
1484 format!("{path}.predicted_observable"),
1485 "exactly one prediction mode is required: predicted_observable or not_applicable=true",
1486 ));
1487 }
1488 scientific_chain_text(
1489 required(assertion, "performed_test", path)?,
1490 &format!("{path}.performed_test"),
1491 )?;
1492 scientific_chain_text(
1493 required(assertion, "result", path)?,
1494 &format!("{path}.result"),
1495 )?;
1496 scientific_chain_references(
1497 required(assertion, "evidence", path)?,
1498 &format!("{path}.evidence"),
1499 true,
1500 )?;
1501 scientific_chain_references(
1502 required(assertion, "counterevidence", path)?,
1503 &format!("{path}.counterevidence"),
1504 false,
1505 )?;
1506 Ok(())
1507}
1508
1509fn parse_execution_binding_extension(
1510 receipt: &Map<String, Value>,
1511) -> Result<Option<ExecutionBindingV1>, ReceiptV1Error> {
1512 let environment = object(&receipt["environment"], "$.environment")?;
1513 let Some(value) = environment.get("vela:execution_binding") else {
1514 return Ok(None);
1515 };
1516 let binding: ExecutionBindingV1 = serde_json::from_value(value.clone()).map_err(|cause| {
1517 error(
1518 "$.environment.vela:execution_binding",
1519 format!("must match the closed {EXECUTION_BINDING_SCHEMA} shape: {cause}"),
1520 )
1521 })?;
1522 binding.validate().map_err(|cause| {
1523 error(
1524 "$.environment.vela:execution_binding",
1525 format!("is invalid: {cause}"),
1526 )
1527 })?;
1528 Ok(Some(binding))
1529}
1530
1531fn validate_execution_binding_extension(
1532 receipt: &Map<String, Value>,
1533) -> Result<(), ReceiptV1Error> {
1534 parse_execution_binding_extension(receipt).map(|_| ())
1535}
1536
1537fn scientific_chain_text<'a>(value: &'a Value, path: &str) -> Result<&'a str, ReceiptV1Error> {
1538 let value = text(value, path, true)?;
1539 if value != value.trim() {
1540 return Err(error(path, "must be trimmed"));
1541 }
1542 if value.len() > SCIENTIFIC_CHAIN_MAX_TEXT_BYTES {
1543 return Err(error(
1544 path,
1545 format!(
1546 "is {} bytes; limit is {} bytes",
1547 value.len(),
1548 SCIENTIFIC_CHAIN_MAX_TEXT_BYTES
1549 ),
1550 ));
1551 }
1552 Ok(value)
1553}
1554
1555fn scientific_chain_references(
1556 value: &Value,
1557 path: &str,
1558 required_nonempty: bool,
1559) -> Result<(), ReceiptV1Error> {
1560 let values = array(value, path)?;
1561 if required_nonempty && values.is_empty() {
1562 return Err(error(path, "must contain at least one evidence reference"));
1563 }
1564 if values.len() > SCIENTIFIC_CHAIN_MAX_REFERENCES {
1565 return Err(error(
1566 path,
1567 format!(
1568 "contains {} references; limit is {}",
1569 values.len(),
1570 SCIENTIFIC_CHAIN_MAX_REFERENCES
1571 ),
1572 ));
1573 }
1574 for (index, value) in values.iter().enumerate() {
1575 let item_path = format!("{path}[{index}]");
1576 let reference = text(value, &item_path, true)?;
1577 if reference != reference.trim() || reference.chars().any(char::is_control) {
1578 return Err(error(
1579 item_path,
1580 "must be trimmed and contain no control characters",
1581 ));
1582 }
1583 if reference.len() > SCIENTIFIC_CHAIN_MAX_REFERENCE_BYTES {
1584 return Err(error(
1585 item_path,
1586 format!(
1587 "is {} bytes; limit is {} bytes",
1588 reference.len(),
1589 SCIENTIFIC_CHAIN_MAX_REFERENCE_BYTES
1590 ),
1591 ));
1592 }
1593 }
1594 Ok(())
1595}
1596
1597fn validate_safe_public_artifact_descriptors(
1602 receipt: &Map<String, Value>,
1603) -> Result<(), ReceiptV1Error> {
1604 let artifacts = array(required(receipt, "artifacts", "$")?, "$.artifacts")?;
1605 for (index, artifact) in artifacts.iter().enumerate() {
1606 let artifact_path = format!("$.artifacts[{index}]");
1607 let artifact = object(artifact, &artifact_path)?;
1608 let disclosure = match artifact.get("disclosure") {
1609 None => None,
1610 Some(value) => Some(text(value, &format!("{artifact_path}.disclosure"), false)?),
1611 };
1612 if let Some(value) = disclosure
1613 && !matches!(value, "public" | "restricted")
1614 {
1615 return Err(error(
1616 format!("{artifact_path}.disclosure"),
1617 "must be public or restricted",
1618 ));
1619 }
1620
1621 for alias in ["visibility", "access_tier", "accessTier"] {
1626 let Some(value) = artifact.get(alias).and_then(Value::as_str) else {
1627 continue;
1628 };
1629 if matches!(value, "restricted" | "classified" | "private" | "sealed")
1630 && disclosure != Some("restricted")
1631 {
1632 return Err(error(
1633 format!("{artifact_path}.{alias}"),
1634 "sensitive artifacts must use disclosure: restricted",
1635 ));
1636 }
1637 }
1638
1639 if disclosure != Some("restricted") {
1640 continue;
1641 }
1642
1643 for field in artifact.keys() {
1644 if !matches!(
1645 field.as_str(),
1646 "path"
1647 | "kind"
1648 | "disclosure"
1649 | "media_type"
1650 | "locator_integrity"
1651 | "availability"
1652 ) {
1653 return Err(error(
1654 format!("{artifact_path}.{field}"),
1655 "is not permitted in a restricted artifact's safe-public descriptor",
1656 ));
1657 }
1658 }
1659
1660 let locator = text(
1661 required(artifact, "path", &artifact_path)?,
1662 &format!("{artifact_path}.path"),
1663 true,
1664 )?;
1665 validate_restricted_opaque_locator(locator, &format!("{artifact_path}.path"))?;
1666
1667 let kind_path = format!("{artifact_path}.kind");
1668 let kind = text(
1669 required(artifact, "kind", &artifact_path)?,
1670 &kind_path,
1671 true,
1672 )?;
1673 validate_safe_public_metadata_text(kind, &kind_path, MAX_RESTRICTED_ARTIFACT_KIND_BYTES)?;
1674
1675 if let Some(media_type) = artifact.get("media_type") {
1676 let media_type_path = format!("{artifact_path}.media_type");
1677 let media_type = text(media_type, &media_type_path, true)?;
1678 validate_safe_public_metadata_text(
1679 media_type,
1680 &media_type_path,
1681 MAX_RESTRICTED_ARTIFACT_MEDIA_TYPE_BYTES,
1682 )?;
1683 }
1684 if let Some(integrity) = artifact.get("locator_integrity") {
1685 enum_text(
1686 integrity,
1687 &format!("{artifact_path}.locator_integrity"),
1688 &["immutable", "mutable", "unknown"],
1689 )?;
1690 }
1691 if let Some(availability) = artifact.get("availability") {
1692 enum_text(
1693 availability,
1694 &format!("{artifact_path}.availability"),
1695 &["available", "unavailable", "unknown"],
1696 )?;
1697 }
1698 }
1699 validate_restricted_artifact_mirrors(receipt, artifacts)?;
1700 Ok(())
1701}
1702
1703fn validate_restricted_artifact_mirrors(
1708 receipt: &Map<String, Value>,
1709 artifacts: &[Value],
1710) -> Result<(), ReceiptV1Error> {
1711 let mut restricted = Vec::new();
1712 let mut expected_subjects = Vec::with_capacity(artifacts.len());
1713 for (index, artifact) in artifacts.iter().enumerate() {
1714 let artifact_path = format!("$.artifacts[{index}]");
1715 let artifact = object(artifact, &artifact_path)?;
1716 let locator = text(
1717 required(artifact, "path", &artifact_path)?,
1718 &format!("{artifact_path}.path"),
1719 true,
1720 )?;
1721 let is_restricted =
1722 artifact.get("disclosure").and_then(Value::as_str) == Some("restricted");
1723 let mut subject = Map::new();
1724 subject.insert("name".to_string(), Value::String(locator.to_string()));
1725 if is_restricted {
1726 restricted.push(locator.to_string());
1727 } else {
1728 if let Some(digest) = artifact.get("sha256") {
1729 subject.insert("digest".to_string(), json!({"sha256": digest}));
1730 }
1731 if let Some(uri) = artifact.get("uri") {
1732 subject.insert("uri".to_string(), uri.clone());
1733 }
1734 }
1735 expected_subjects.push(Value::Object(subject));
1736 }
1737 if restricted.is_empty() {
1738 return Ok(());
1739 }
1740 let expected_subjects = Value::Array(expected_subjects);
1741
1742 let machine = object(required(receipt, "machine", "$")?, "$.machine")?;
1743 if required(machine, "subject", "$.machine")? != &expected_subjects {
1744 return Err(error(
1745 "$.machine.subject",
1746 "must be the artifact-derived public subject projection when restricted artifacts are present; restricted subjects may contain only their opaque name",
1747 ));
1748 }
1749
1750 let attestation = object(required(receipt, "attestation", "$")?, "$.attestation")?;
1751 let statement = object(
1752 required(attestation, "statement", "$.attestation")?,
1753 "$.attestation.statement",
1754 )?;
1755 if required(statement, "subject", "$.attestation.statement")? != &expected_subjects {
1756 return Err(error(
1757 "$.attestation.statement.subject",
1758 "must not add a digest, opening, or resolvable locator for a restricted artifact",
1759 ));
1760 }
1761 let predicate = object(
1762 required(statement, "predicate", "$.attestation.statement")?,
1763 "$.attestation.statement.predicate",
1764 )?;
1765 let predicate_machine = object(
1766 required(predicate, "machine", "$.attestation.statement.predicate")?,
1767 "$.attestation.statement.predicate.machine",
1768 )?;
1769 if required(
1770 predicate_machine,
1771 "subject",
1772 "$.attestation.statement.predicate.machine",
1773 )? != &expected_subjects
1774 {
1775 return Err(error(
1776 "$.attestation.statement.predicate.machine.subject",
1777 "must not add a digest, opening, or resolvable locator for a restricted artifact",
1778 ));
1779 }
1780
1781 if let Some(prov) = attestation.get("prov") {
1782 let prov = object(prov, "$.attestation.prov")?;
1783 if let Some(entities) = prov.get("entity") {
1784 let entities = object(entities, "$.attestation.prov.entity")?;
1785 for locator in &restricted {
1786 let entity_id = format!("artifact:{locator}");
1787 let Some(entity) = entities.get(&entity_id) else {
1788 continue;
1789 };
1790 let entity_path = format!("$.attestation.prov.entity.{entity_id}");
1791 let entity = object(entity, &entity_path)?;
1792 for field in entity.keys() {
1793 if !matches!(field.as_str(), "prov:type" | "vela:kind") {
1794 return Err(error(
1795 format!("{entity_path}.{field}"),
1796 "is not permitted in the public PROV mirror of a restricted artifact",
1797 ));
1798 }
1799 }
1800 }
1801 }
1802 }
1803 Ok(())
1804}
1805
1806fn validate_restricted_opaque_locator(locator: &str, path: &str) -> Result<(), ReceiptV1Error> {
1807 let opaque_id = locator
1808 .strip_prefix("custodian:")
1809 .or_else(|| locator.strip_prefix("opaque:"))
1810 .ok_or_else(|| {
1811 error(
1812 path,
1813 "restricted artifacts require a non-resolving custodian: or opaque: identifier",
1814 )
1815 })?;
1816 if opaque_id.is_empty()
1817 || opaque_id.len() > MAX_RESTRICTED_ARTIFACT_OPAQUE_ID_BYTES
1818 || !opaque_id
1819 .bytes()
1820 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
1821 {
1822 return Err(error(
1823 path,
1824 format!(
1825 "opaque identifier must be 1..={} ASCII identifier bytes and contain no path, URL, query, fragment, whitespace, or control syntax",
1826 MAX_RESTRICTED_ARTIFACT_OPAQUE_ID_BYTES
1827 ),
1828 ));
1829 }
1830 Ok(())
1831}
1832
1833fn validate_safe_public_metadata_text(
1834 value: &str,
1835 path: &str,
1836 limit: usize,
1837) -> Result<(), ReceiptV1Error> {
1838 if value != value.trim() || value.len() > limit || value.chars().any(char::is_control) {
1839 return Err(error(
1840 path,
1841 format!(
1842 "safe-public metadata must be trimmed, control-free, and at most {limit} bytes"
1843 ),
1844 ));
1845 }
1846 Ok(())
1847}
1848
1849fn validate_provenance(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1850 let provenance = object(&receipt["provenance"], "$.provenance")?;
1851 text(
1852 required(provenance, "generated_by", "$.provenance")?,
1853 "$.provenance.generated_by",
1854 true,
1855 )?;
1856 let emitted_at = text(
1857 required(provenance, "emitted_at", "$.provenance")?,
1858 "$.provenance.emitted_at",
1859 true,
1860 )?;
1861 chrono::DateTime::parse_from_rfc3339(emitted_at)
1862 .map_err(|_| error("$.provenance.emitted_at", "must be an RFC 3339 date-time"))?;
1863 Ok(())
1864}
1865
1866fn validate_status(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1867 let status = object(&receipt["status"], "$.status")?;
1868 let kind = enum_text(
1869 required(status, "kind", "$.status")?,
1870 "$.status.kind",
1871 STATUS_KINDS,
1872 )?;
1873 let authority = enum_text(
1874 required(status, "authority", "$.status")?,
1875 "$.status.authority",
1876 STATUS_AUTHORITIES,
1877 )?;
1878 if authority == "producer" && !["draft", "emitted"].contains(&kind) {
1879 return Err(error(
1880 "$.status",
1881 "producer authority may emit only draft or emitted status",
1882 ));
1883 }
1884 Ok(())
1885}
1886
1887fn validate_machine(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1888 let machine = object(&receipt["machine"], "$.machine")?;
1889 if array(
1890 required(machine, "subject", "$.machine")?,
1891 "$.machine.subject",
1892 )?
1893 .is_empty()
1894 {
1895 return Err(error("$.machine.subject", "must not be empty"));
1896 }
1897 for (field, path) in [
1898 ("claim", "$.machine.claim"),
1899 ("verification", "$.machine.verification"),
1900 ] {
1901 object(required(machine, field, "$.machine")?, path)?;
1902 }
1903 let claim = object(&machine["claim"], "$.machine.claim")?;
1904 required(claim, "text", "$.machine.claim")?;
1905 required(claim, "type", "$.machine.claim")?;
1906 let verification = object(&machine["verification"], "$.machine.verification")?;
1907 for field in ["status", "verifier_runs", "trust_base"] {
1908 required(verification, field, "$.machine.verification")?;
1909 }
1910 Ok(())
1911}
1912
1913fn validate_acceptance(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1914 let acceptance = object(&receipt["acceptance"], "$.acceptance")?;
1915 for field in [
1916 "profile",
1917 "mechanism",
1918 "acceptor",
1919 "policyRef",
1920 "evidenceRefs",
1921 "artifact_verification",
1922 "claim_acceptance",
1923 "distillation_acceptance",
1924 "acceptance_scope",
1925 ] {
1926 required(acceptance, field, "$.acceptance")?;
1927 }
1928 text(&acceptance["profile"], "$.acceptance.profile", true)?;
1929 if acceptance["mechanism"] != ACCEPTANCE_MECHANISM {
1930 return Err(error(
1931 "$.acceptance.mechanism",
1932 format!("must be {ACCEPTANCE_MECHANISM}"),
1933 ));
1934 }
1935 if !acceptance["acceptor"].is_null() {
1936 text(&acceptance["acceptor"], "$.acceptance.acceptor", false)?;
1937 }
1938 text(&acceptance["policyRef"], "$.acceptance.policyRef", true)?;
1939 array(&acceptance["evidenceRefs"], "$.acceptance.evidenceRefs")?;
1940 for field in [
1941 "artifact_verification",
1942 "claim_acceptance",
1943 "distillation_acceptance",
1944 ] {
1945 object(&acceptance[field], &format!("$.acceptance.{field}"))?;
1946 }
1947 let scope = text(
1948 &acceptance["acceptance_scope"],
1949 "$.acceptance.acceptance_scope",
1950 false,
1951 )?;
1952 if AcceptanceScope::parse(scope).is_none() {
1953 return Err(error(
1954 "$.acceptance.acceptance_scope",
1955 "is not a published v1 scope",
1956 ));
1957 }
1958 Ok(())
1959}
1960
1961fn validate_distillation_and_lineage(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1962 let distillation = object(&receipt["distillation"], "$.distillation")?;
1963 for field in ["status", "audience", "rubric"] {
1964 required(distillation, field, "$.distillation")?;
1965 }
1966 let lineage = object(&receipt["lineage"], "$.lineage")?;
1967 for field in ["parents", "derived_from", "source_refs"] {
1968 required(lineage, field, "$.lineage")?;
1969 }
1970 Ok(())
1971}
1972
1973fn validate_contributors(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
1974 let contributors = array(&receipt["contributors"], "$.contributors")?;
1975 if contributors.is_empty() {
1976 return Err(error("$.contributors", "must not be empty"));
1977 }
1978 for (index, contributor) in contributors.iter().enumerate() {
1979 let path = format!("$.contributors[{index}]");
1980 let contributor = object(contributor, &path)?;
1981 text(
1982 required(contributor, "id", &path)?,
1983 &format!("{path}.id"),
1984 true,
1985 )?;
1986 let roles = array(
1987 required(contributor, "roles", &path)?,
1988 &format!("{path}.roles"),
1989 )?;
1990 if roles.is_empty() {
1991 return Err(error(format!("{path}.roles"), "must not be empty"));
1992 }
1993 for (role_index, role) in roles.iter().enumerate() {
1994 enum_text(
1995 role,
1996 &format!("{path}.roles[{role_index}]"),
1997 CONTRIBUTOR_ROLES,
1998 )?;
1999 }
2000 }
2001 Ok(())
2002}
2003
2004fn validate_identities(receipt: &Map<String, Value>) -> Result<(), ReceiptV1Error> {
2005 let identities = object(&receipt["signature_identities"], "$.signature_identities")?;
2006 validate_identity(
2007 required(identities, "producer", "$.signature_identities")?,
2008 "$.signature_identities.producer",
2009 "producer",
2010 )?;
2011 if let Some(acceptor) = identities.get("acceptor") {
2012 validate_identity(acceptor, "$.signature_identities.acceptor", "acceptor")?;
2013 }
2014 validate_embedded_producer_identity(receipt, identities)?;
2015 Ok(())
2016}
2017
2018fn validate_identity(value: &Value, path: &str, role: &str) -> Result<(), ReceiptV1Error> {
2019 let identity = object(value, path)?;
2020 if text(
2021 required(identity, "role", path)?,
2022 &format!("{path}.role"),
2023 false,
2024 )? != role
2025 {
2026 return Err(error(format!("{path}.role"), format!("must be {role}")));
2027 }
2028 enum_text(
2029 required(identity, "mechanism", path)?,
2030 &format!("{path}.mechanism"),
2031 IDENTITY_MECHANISMS,
2032 )?;
2033 Ok(())
2034}
2035
2036fn validate_embedded_producer_identity(
2037 receipt: &Map<String, Value>,
2038 identities: &Map<String, Value>,
2039) -> Result<(), ReceiptV1Error> {
2040 let environment = object(&receipt["environment"], "$.environment")?;
2041 let context = environment
2042 .get("vela:producer_context")
2043 .map(|value| object(value, "$.environment.vela:producer_context"))
2044 .transpose()?;
2045 let generated_by = receipt["provenance"]["generated_by"].as_str();
2046 let binding_value = context.and_then(|context| context.get("identity_binding"));
2047 if binding_value.is_none() {
2048 if generated_by == Some(NEUTRAL_RECEIPT_GENERATOR) {
2049 return Err(error(
2050 "$.environment.vela:producer_context.identity_binding",
2051 "neutral protocol emissions require the full self-signed producer binding",
2052 ));
2053 }
2054 return Ok(());
2055 }
2056 let binding: crate::identity::IdentityBinding =
2057 serde_json::from_value(binding_value.cloned().unwrap()).map_err(|cause| {
2058 error(
2059 "$.environment.vela:producer_context.identity_binding",
2060 format!("must be a complete IdentityBinding: {cause}"),
2061 )
2062 })?;
2063 binding.verify().map_err(|cause| {
2064 error(
2065 "$.environment.vela:producer_context.identity_binding",
2066 format!("does not verify proof of possession: {cause}"),
2067 )
2068 })?;
2069 if binding.actor_class != crate::identity::ActorClass::Agent {
2070 return Err(error(
2071 "$.environment.vela:producer_context.identity_binding.actor_class",
2072 "must be agent",
2073 ));
2074 }
2075 let context = context.expect("binding implies context");
2076 let actor_suffix = binding
2077 .actor_id
2078 .strip_prefix("agent:")
2079 .or_else(|| binding.actor_id.strip_prefix("ci:"))
2080 .filter(|suffix| !suffix.trim().is_empty())
2081 .ok_or_else(|| {
2082 error(
2083 "$.environment.vela:producer_context.identity_binding.actor_id",
2084 "must be a non-empty agent: or ci: identity",
2085 )
2086 })?;
2087 if actor_suffix != actor_suffix.trim() || actor_suffix.chars().any(char::is_control) {
2088 return Err(error(
2089 "$.environment.vela:producer_context.identity_binding.actor_id",
2090 "identity suffix must be trimmed and contain no controls",
2091 ));
2092 }
2093 let event_log_root = text(
2094 required(
2095 context,
2096 "event_log_root",
2097 "$.environment.vela:producer_context",
2098 )?,
2099 "$.environment.vela:producer_context.event_log_root",
2100 false,
2101 )?;
2102 if !event_log_root
2103 .strip_prefix("sha256:")
2104 .is_some_and(|hex| is_lower_hex_length(hex, 64))
2105 {
2106 return Err(error(
2107 "$.environment.vela:producer_context.event_log_root",
2108 "must be sha256: followed by 64 lowercase hexadecimal characters",
2109 ));
2110 }
2111 if let Some(task_contract_root) = context.get("task_contract_root") {
2112 let task_contract_root = text(
2113 task_contract_root,
2114 "$.environment.vela:producer_context.task_contract_root",
2115 false,
2116 )?;
2117 if !task_contract_root
2118 .strip_prefix("sha256:")
2119 .is_some_and(|hex| is_lower_hex_length(hex, 64))
2120 {
2121 return Err(error(
2122 "$.environment.vela:producer_context.task_contract_root",
2123 "must be sha256: followed by 64 lowercase hexadecimal characters",
2124 ));
2125 }
2126 }
2127 let operation_id = text(
2128 required(
2129 context,
2130 "operation_id",
2131 "$.environment.vela:producer_context",
2132 )?,
2133 "$.environment.vela:producer_context.operation_id",
2134 false,
2135 )?;
2136 if !operation_id
2137 .strip_prefix("vop_")
2138 .is_some_and(|hex| is_lower_hex_length(hex, 64))
2139 {
2140 return Err(error(
2141 "$.environment.vela:producer_context.operation_id",
2142 "must be vop_ followed by 64 lowercase hexadecimal characters",
2143 ));
2144 }
2145 let base_path = text(
2146 required(context, "base_path", "$.environment.vela:producer_context")?,
2147 "$.environment.vela:producer_context.base_path",
2148 true,
2149 )?;
2150 if base_path != base_path.trim() || base_path.chars().any(char::is_control) {
2151 return Err(error(
2152 "$.environment.vela:producer_context.base_path",
2153 "must be a trimmed path without control characters",
2154 ));
2155 }
2156 let policy_ref = text(
2157 required(context, "policy_ref", "$.environment.vela:producer_context")?,
2158 "$.environment.vela:producer_context.policy_ref",
2159 false,
2160 )?;
2161 if policy_ref != NO_ACTIVE_POLICY_REF
2162 && !policy_ref
2163 .strip_prefix("vap_")
2164 .is_some_and(|hex| is_lower_hex_length(hex, 32))
2165 {
2166 return Err(error(
2167 "$.environment.vela:producer_context.policy_ref",
2168 "must be a vap_ content address or urn:vela:policy:none",
2169 ));
2170 }
2171 if receipt["acceptance"]["policyRef"].as_str() != Some(policy_ref) {
2172 return Err(error(
2173 "$.acceptance.policyRef",
2174 "must match the mechanical producer context",
2175 ));
2176 }
2177 let producer = object(
2178 required(identities, "producer", "$.signature_identities")?,
2179 "$.signature_identities.producer",
2180 )?;
2181 for (path, actual, expected) in [
2182 (
2183 "$.environment.vela:producer_context.actor",
2184 context.get("actor"),
2185 binding.actor_id.as_str(),
2186 ),
2187 (
2188 "$.environment.vela:producer_context.identity_binding_ref",
2189 context.get("identity_binding_ref"),
2190 binding.binding_id.as_str(),
2191 ),
2192 (
2193 "$.signature_identities.producer.subject",
2194 producer.get("subject"),
2195 binding.actor_id.as_str(),
2196 ),
2197 (
2198 "$.signature_identities.producer.publicKey",
2199 producer.get("publicKey"),
2200 binding.public_key_hex.as_str(),
2201 ),
2202 (
2203 "$.signature_identities.producer.identityBindingRef",
2204 producer.get("identityBindingRef"),
2205 binding.binding_id.as_str(),
2206 ),
2207 (
2208 "$.signature_identities.producer.signatureRef",
2209 producer.get("signatureRef"),
2210 binding.binding_id.as_str(),
2211 ),
2212 ] {
2213 if actual.and_then(Value::as_str) != Some(expected) {
2214 return Err(error(path, "must match the embedded producer binding"));
2215 }
2216 }
2217 if producer.get("mechanism").and_then(Value::as_str) != Some("ed25519_key_custody_ceremony") {
2218 return Err(error(
2219 "$.signature_identities.producer.mechanism",
2220 "embedded producer bindings require ed25519_key_custody_ceremony",
2221 ));
2222 }
2223 let provenance = object(&receipt["provenance"], "$.provenance")?;
2224 let submitter = object(
2225 required(provenance, "submitter", "$.provenance")?,
2226 "$.provenance.submitter",
2227 )?;
2228 if submitter.get("actor").and_then(Value::as_str) != Some(binding.actor_id.as_str())
2229 || submitter
2230 .get("identity_binding_ref")
2231 .and_then(Value::as_str)
2232 != Some(binding.binding_id.as_str())
2233 || submitter.get("operation_id").and_then(Value::as_str) != Some(operation_id)
2234 {
2235 return Err(error(
2236 "$.provenance.submitter",
2237 "must reference the embedded producer binding",
2238 ));
2239 }
2240 Ok(())
2241}
2242
2243fn is_lower_hex_length(value: &str, length: usize) -> bool {
2244 value.len() == length
2245 && value
2246 .bytes()
2247 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2248}
2249
2250fn receipt_body(receipt: &Map<String, Value>) -> Value {
2251 let mut body = receipt.clone();
2252 body.remove("attestation");
2253 Value::Object(body)
2254}
2255
2256fn receipt_body_sha256(receipt: &Map<String, Value>) -> Result<String, ReceiptV1Error> {
2257 use sha2::{Digest as _, Sha256};
2258
2259 canonical_receipt_bytes(&receipt_body(receipt))
2260 .map(|bytes| hex::encode(Sha256::digest(bytes)))
2261 .map_err(|cause| error("$", format!("canonical receipt body: {cause}")))
2262}
2263
2264fn statement_projection(receipt: &Map<String, Value>) -> Result<Value, ReceiptV1Error> {
2265 let machine = required(receipt, "machine", "$")?;
2266 let machine_object = object(machine, "$.machine")?;
2267 let subject = required(machine_object, "subject", "$.machine")?;
2268 Ok(json!({
2269 "_type": INTOTO_STATEMENT_TYPE,
2270 "subject": subject,
2271 "predicateType": VELA_PREDICATE_TYPE,
2272 "predicate": {
2273 "schema": RECEIPT_PREDICATE_SCHEMA,
2274 "machine": machine,
2275 "acceptance": required(receipt, "acceptance", "$")?,
2276 "distillation": required(receipt, "distillation", "$")?,
2277 "lineage": required(receipt, "lineage", "$")?,
2278 "contributors": required(receipt, "contributors", "$")?,
2279 "signature_identities": required(receipt, "signature_identities", "$")?,
2280 "provenance": required(receipt, "provenance", "$")?,
2281 (RECEIPT_BODY_BINDING_FIELD): {
2282 "sha256": receipt_body_sha256(receipt)?,
2283 },
2284 }
2285 }))
2286}
2287
2288fn validate_bound_statement_projection(
2289 receipt: &Map<String, Value>,
2290 statement: &Map<String, Value>,
2291) -> Result<(), ReceiptV1Error> {
2292 let expected = statement_projection(receipt)?;
2293 let expected = object(&expected, "$.attestation.statement")?;
2294 for field in ["_type", "subject", "predicateType"] {
2295 if statement.get(field) != expected.get(field) {
2296 return Err(error(
2297 format!("$.attestation.statement.{field}"),
2298 "does not match the canonical receipt-body projection",
2299 ));
2300 }
2301 }
2302 let predicate = object(
2303 required(statement, "predicate", "$.attestation.statement")?,
2304 "$.attestation.statement.predicate",
2305 )?;
2306 let expected_predicate = object(
2307 required(expected, "predicate", "$.attestation.statement")?,
2308 "$.attestation.statement.predicate",
2309 )?;
2310 for (field, expected_value) in expected_predicate {
2311 if predicate.get(field) != Some(expected_value) {
2312 return Err(error(
2313 format!("$.attestation.statement.predicate.{field}"),
2314 "does not match the canonical receipt-body projection",
2315 ));
2316 }
2317 }
2318 let binding = object(
2319 required(
2320 predicate,
2321 RECEIPT_BODY_BINDING_FIELD,
2322 "$.attestation.statement.predicate",
2323 )?,
2324 "$.attestation.statement.predicate.vela:receipt_body",
2325 )?;
2326 if binding.len() != 1 {
2327 return Err(error(
2328 "$.attestation.statement.predicate.vela:receipt_body",
2329 "must contain only the canonical sha256 body root",
2330 ));
2331 }
2332 let digest = text(
2333 required(
2334 binding,
2335 "sha256",
2336 "$.attestation.statement.predicate.vela:receipt_body",
2337 )?,
2338 "$.attestation.statement.predicate.vela:receipt_body.sha256",
2339 false,
2340 )?;
2341 if digest.len() != 64
2342 || !digest
2343 .bytes()
2344 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2345 {
2346 return Err(error(
2347 "$.attestation.statement.predicate.vela:receipt_body.sha256",
2348 "must be 64 lowercase hexadecimal characters",
2349 ));
2350 }
2351 Ok(())
2352}
2353
2354fn validate_attestation(
2355 receipt: &Map<String, Value>,
2356 limits: ReceiptLimits,
2357) -> Result<(), ReceiptV1Error> {
2358 let attestation = object(&receipt["attestation"], "$.attestation")?;
2359 if required(attestation, "format", "$.attestation")? != "in-toto-statement" {
2360 return Err(error("$.attestation.format", "must be in-toto-statement"));
2361 }
2362 let statement = object(
2363 required(attestation, "statement", "$.attestation")?,
2364 "$.attestation.statement",
2365 )?;
2366 if required(statement, "_type", "$.attestation.statement")? != INTOTO_STATEMENT_TYPE {
2367 return Err(error(
2368 "$.attestation.statement._type",
2369 "invalid in-toto type",
2370 ));
2371 }
2372 if required(statement, "predicateType", "$.attestation.statement")? != VELA_PREDICATE_TYPE {
2373 return Err(error(
2374 "$.attestation.statement.predicateType",
2375 "invalid Vela predicate type",
2376 ));
2377 }
2378 if array(
2379 required(statement, "subject", "$.attestation.statement")?,
2380 "$.attestation.statement.subject",
2381 )?
2382 .is_empty()
2383 {
2384 return Err(error(
2385 "$.attestation.statement.subject",
2386 "must not be empty",
2387 ));
2388 }
2389 let predicate = object(
2390 required(statement, "predicate", "$.attestation.statement")?,
2391 "$.attestation.statement.predicate",
2392 )?;
2393 for field in [
2394 "machine",
2395 "acceptance",
2396 "distillation",
2397 "lineage",
2398 "provenance",
2399 ] {
2400 required(predicate, field, "$.attestation.statement.predicate")?;
2401 }
2402 let envelope = object(
2403 required(attestation, "dsse_envelope", "$.attestation")?,
2404 "$.attestation.dsse_envelope",
2405 )?;
2406 if required(envelope, "payloadType", "$.attestation.dsse_envelope")? != INTOTO_PAYLOAD_TYPE {
2407 return Err(error(
2408 "$.attestation.dsse_envelope.payloadType",
2409 "invalid DSSE payload type",
2410 ));
2411 }
2412 let payload = text(
2413 required(envelope, "payload", "$.attestation.dsse_envelope")?,
2414 "$.attestation.dsse_envelope.payload",
2415 true,
2416 )?;
2417 array(
2418 required(envelope, "signatures", "$.attestation.dsse_envelope")?,
2419 "$.attestation.dsse_envelope.signatures",
2420 )?;
2421 let estimated_decoded = payload.len().saturating_add(3) / 4 * 3;
2422 if estimated_decoded > limits.dsse_bytes {
2423 return Err(error(
2424 "$.attestation.dsse_envelope.payload",
2425 format!(
2426 "decoded DSSE statement may exceed {} bytes",
2427 limits.dsse_bytes
2428 ),
2429 ));
2430 }
2431 let decoded = BASE64_STANDARD
2432 .decode(payload)
2433 .map_err(|_| error("$.attestation.dsse_envelope.payload", "must be base64"))?;
2434 let decoded = decode_bounded_json(
2435 &decoded,
2436 limits,
2437 "$.attestation.dsse_envelope.payload",
2438 true,
2439 )?;
2440 if decoded != Value::Object(statement.clone()) {
2441 return Err(error(
2442 "$.attestation.dsse_envelope.payload",
2443 "does not encode attestation.statement",
2444 ));
2445 }
2446 required(
2447 predicate,
2448 RECEIPT_BODY_BINDING_FIELD,
2449 "$.attestation.statement.predicate",
2450 )?;
2451 validate_bound_statement_projection(receipt, statement)
2452}
2453
2454#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2457#[serde(rename_all = "snake_case")]
2458pub enum AcceptanceScope {
2459 MachineVerified,
2460 HumanSeen,
2461 LocallyAccepted,
2462 FrontierAccepted,
2463 CanonAccepted,
2464 HypothesisOnly,
2465 Retracted,
2466 Superseded,
2467}
2468
2469impl AcceptanceScope {
2470 const ALL: [AcceptanceScope; 8] = [
2471 AcceptanceScope::MachineVerified,
2472 AcceptanceScope::HumanSeen,
2473 AcceptanceScope::LocallyAccepted,
2474 AcceptanceScope::FrontierAccepted,
2475 AcceptanceScope::CanonAccepted,
2476 AcceptanceScope::HypothesisOnly,
2477 AcceptanceScope::Retracted,
2478 AcceptanceScope::Superseded,
2479 ];
2480
2481 pub fn as_str(&self) -> &'static str {
2482 match self {
2483 Self::MachineVerified => "machine_verified",
2484 Self::HumanSeen => "human_seen",
2485 Self::LocallyAccepted => "locally_accepted",
2486 Self::FrontierAccepted => "frontier_accepted",
2487 Self::CanonAccepted => "canon_accepted",
2488 Self::HypothesisOnly => "hypothesis_only",
2489 Self::Retracted => "retracted",
2490 Self::Superseded => "superseded",
2491 }
2492 }
2493
2494 pub fn parse(value: &str) -> Option<Self> {
2495 Self::ALL
2496 .iter()
2497 .copied()
2498 .find(|item| item.as_str() == value)
2499 }
2500}
2501
2502#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2503pub struct ReceiptLineage {
2504 #[serde(default)]
2505 pub parents: Vec<String>,
2506 #[serde(default)]
2507 pub derived_from: Vec<String>,
2508 #[serde(default)]
2509 pub source_refs: Vec<String>,
2510 #[serde(default)]
2511 pub supersedes: Vec<String>,
2512 #[serde(default)]
2513 pub producer_run_id: Option<String>,
2514 #[serde(default)]
2515 pub frontier: Option<String>,
2516}
2517
2518#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2519pub struct IndependenceBasis {
2520 #[serde(default)]
2521 pub method_family: String,
2522 #[serde(default)]
2523 pub solver_identity: String,
2524 #[serde(default)]
2525 pub code_lineage: String,
2526 #[serde(default)]
2527 pub dataset_lineage: String,
2528 #[serde(default)]
2529 pub model_lineage: String,
2530 #[serde(default)]
2531 pub shared_dependencies: Vec<String>,
2532 #[serde(default)]
2533 pub declared_independent_of: Vec<String>,
2534 #[serde(default)]
2535 pub known_couplings: Vec<String>,
2536}
2537
2538pub fn lineage_from_receipt(receipt: &Value) -> Option<ReceiptLineage> {
2539 lineage_from_layer(receipt.get("lineage")?)
2540}
2541
2542pub fn lineage_from_layer(layer: &Value) -> Option<ReceiptLineage> {
2543 layer
2544 .is_object()
2545 .then(|| serde_json::from_value(layer.clone()).ok())
2546 .flatten()
2547}
2548
2549pub fn independence_basis_from_environment(environment: &Value) -> Option<IndependenceBasis> {
2550 let basis = environment.get("independence_basis")?;
2551 basis
2552 .is_object()
2553 .then(|| serde_json::from_value(basis.clone()).ok())
2554 .flatten()
2555}
2556
2557pub fn acceptance_scope_from_receipt(receipt: &Value) -> Option<AcceptanceScope> {
2558 receipt
2559 .get("acceptance")?
2560 .get("acceptance_scope")?
2561 .as_str()
2562 .and_then(AcceptanceScope::parse)
2563}
2564
2565mod authoring {
2569 use base64::Engine as _;
2570 use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
2571 use serde_json::{Value, json};
2572
2573 use super::{
2574 ACCEPTANCE_MECHANISM, ExecutionBindingV1, INTOTO_PAYLOAD_TYPE, NEUTRAL_RECEIPT_GENERATOR,
2575 NO_ACTIVE_POLICY_REF, ReceiptV1, ReceiptV1Error, SCIENTIFIC_CHAIN_SCHEMA,
2576 canonical_receipt_bytes, error, object, statement_projection,
2577 validate_scientific_chain_extension,
2578 };
2579 use crate::identity::{ActorClass, IdentityBinding};
2580
2581 #[derive(Debug, Clone)]
2582 pub(super) struct ProducerContext {
2583 actor: String,
2584 generated_by: String,
2585 producer_pubkey_hex: String,
2586 identity_binding_id: String,
2587 identity_binding: IdentityBinding,
2588 policy_ref: String,
2589 event_log_root: String,
2590 emitted_at: String,
2591 base_path: String,
2592 operation_id: String,
2593 task_contract_root: Option<String>,
2594 }
2595
2596 impl ProducerContext {
2597 fn from_verified_identity(
2598 identity: &IdentityBinding,
2599 actor: &str,
2600 event_log_root: &str,
2601 emitted_at: &str,
2602 base_path: &str,
2603 operation_id: &str,
2604 policy_ref: &str,
2605 ) -> Result<Self, ReceiptV1Error> {
2606 identity.verify().map_err(|cause| {
2607 error(
2608 "$.signature_identities.producer",
2609 format!("identity binding does not verify: {cause}"),
2610 )
2611 })?;
2612 if identity.actor_class != ActorClass::Agent {
2613 return Err(error(
2614 "$.provenance.submitter.actor",
2615 "producer capability must bind an agent-class identity",
2616 ));
2617 }
2618 if identity.actor_id != actor {
2619 return Err(error(
2620 "$.provenance.submitter.actor",
2621 "mechanical actor must exactly match the verified identity binding",
2622 ));
2623 }
2624 validate_actor(actor)?;
2625 for (path, value) in [
2626 ("$.event_log_root", event_log_root),
2627 ("$.base_path", base_path),
2628 ("$.operation_id", operation_id),
2629 ] {
2630 if value.trim().is_empty() {
2631 return Err(error(path, "must be supplied explicitly"));
2632 }
2633 }
2634 chrono::DateTime::parse_from_rfc3339(emitted_at)
2635 .map_err(|_| error("$.provenance.emitted_at", "must be an RFC 3339 date-time"))?;
2636 validate_policy_ref(policy_ref)?;
2637 Ok(Self {
2638 actor: actor.to_string(),
2639 generated_by: NEUTRAL_RECEIPT_GENERATOR.to_string(),
2640 producer_pubkey_hex: identity.public_key_hex.clone(),
2641 identity_binding_id: identity.binding_id.clone(),
2642 identity_binding: identity.clone(),
2643 policy_ref: policy_ref.to_string(),
2644 event_log_root: event_log_root.to_string(),
2645 emitted_at: emitted_at.to_string(),
2646 base_path: base_path.to_string(),
2647 operation_id: operation_id.to_string(),
2648 task_contract_root: None,
2649 })
2650 }
2651 }
2652
2653 fn validate_actor(actor: &str) -> Result<(), ReceiptV1Error> {
2654 let suffix = actor
2655 .strip_prefix("agent:")
2656 .or_else(|| actor.strip_prefix("ci:"))
2657 .filter(|suffix| !suffix.trim().is_empty())
2658 .ok_or_else(|| {
2659 error(
2660 "$.provenance.submitter.actor",
2661 "must be a non-empty agent: or ci: identity",
2662 )
2663 })?;
2664 if suffix != suffix.trim() || suffix.chars().any(char::is_control) {
2665 return Err(error(
2666 "$.provenance.submitter.actor",
2667 "identity suffix must be trimmed and contain no controls",
2668 ));
2669 }
2670 Ok(())
2671 }
2672
2673 fn validate_policy_ref(policy_ref: &str) -> Result<(), ReceiptV1Error> {
2674 if policy_ref == NO_ACTIVE_POLICY_REF
2675 || policy_ref
2676 .strip_prefix("vap_")
2677 .is_some_and(|hex| is_lower_hex(hex, 32))
2678 {
2679 return Ok(());
2680 }
2681 Err(error(
2682 "$.acceptance.policyRef",
2683 "must be a vap_ content address or urn:vela:policy:none",
2684 ))
2685 }
2686
2687 #[derive(Debug, Clone)]
2688 pub struct ArtifactInput {
2689 path: String,
2690 kind: String,
2691 sha256: Option<String>,
2692 uri: Option<String>,
2693 }
2694
2695 impl ArtifactInput {
2696 pub fn new(
2697 path: String,
2698 kind: String,
2699 sha256: Option<String>,
2700 uri: Option<String>,
2701 ) -> Result<Self, ReceiptV1Error> {
2702 if path.trim().is_empty() || kind.trim().is_empty() {
2703 return Err(error(
2704 "$.artifacts",
2705 "artifact path and kind must be explicit non-empty strings",
2706 ));
2707 }
2708 if let Some(hash) = &sha256
2709 && (hash.len() != 64
2710 || !hash
2711 .bytes()
2712 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
2713 {
2714 return Err(error(
2715 "$.artifacts.sha256",
2716 "must be 64 lowercase hexadecimal characters",
2717 ));
2718 }
2719 Ok(Self {
2720 path,
2721 kind,
2722 sha256,
2723 uri,
2724 })
2725 }
2726 }
2727
2728 #[derive(Debug, Clone)]
2729 pub struct VerifierRunInput {
2730 method: String,
2731 outcome: String,
2732 }
2733
2734 impl VerifierRunInput {
2735 pub fn producer_reported(method: String, outcome: String) -> Result<Self, ReceiptV1Error> {
2738 if method.trim().is_empty() {
2739 return Err(error("$.verifier_runs.method", "must not be empty"));
2740 }
2741 if !super::VERIFIER_OUTCOMES.contains(&outcome.as_str()) {
2742 return Err(error(
2743 "$.verifier_runs.outcome",
2744 "is not a published Receipt v1 outcome",
2745 ));
2746 }
2747 Ok(Self { method, outcome })
2748 }
2749 }
2750
2751 #[derive(Debug, Clone, PartialEq, Eq)]
2755 pub struct ScientificChainAssertion {
2756 predicted_observable: Option<String>,
2757 not_applicable: bool,
2758 performed_test: String,
2759 result: String,
2760 evidence: Vec<String>,
2761 counterevidence: Vec<String>,
2762 }
2763
2764 impl ScientificChainAssertion {
2765 #[allow(clippy::too_many_arguments)]
2766 pub fn new(
2767 predicted_observable: Option<String>,
2768 not_applicable: bool,
2769 performed_test: String,
2770 result: String,
2771 evidence: Vec<String>,
2772 counterevidence: Vec<String>,
2773 ) -> Result<Self, ReceiptV1Error> {
2774 let assertion = Self {
2775 predicted_observable,
2776 not_applicable,
2777 performed_test,
2778 result,
2779 evidence,
2780 counterevidence,
2781 };
2782 validate_scientific_chain_assertion(&assertion)?;
2783 Ok(assertion)
2784 }
2785
2786 pub fn as_value(&self) -> Value {
2789 let mut value = json!({
2790 "schema": SCIENTIFIC_CHAIN_SCHEMA,
2791 "authority": "producer",
2792 "not_applicable": self.not_applicable,
2793 "performed_test": self.performed_test,
2794 "result": self.result,
2795 "evidence": self.evidence,
2796 "counterevidence": self.counterevidence,
2797 });
2798 if let Some(predicted_observable) = &self.predicted_observable {
2799 value["predicted_observable"] = json!(predicted_observable);
2800 }
2801 value
2802 }
2803 }
2804
2805 #[derive(Debug, Clone)]
2813 pub struct NeutralReceiptInput {
2814 claim: String,
2815 claim_type: String,
2816 replayability: String,
2817 artifacts: Vec<ArtifactInput>,
2818 caveats: Vec<String>,
2819 verifier_runs: Vec<VerifierRunInput>,
2820 actor: String,
2821 emitted_at: String,
2822 event_log_root: String,
2823 base_path: String,
2824 operation_id: String,
2825 policy_ref: String,
2826 task_contract_root: Option<String>,
2827 scientific_chain: Option<ScientificChainAssertion>,
2828 execution_binding: Option<ExecutionBindingV1>,
2829 }
2830
2831 impl NeutralReceiptInput {
2832 #[allow(clippy::too_many_arguments)]
2833 pub fn new(
2834 claim: String,
2835 claim_type: String,
2836 replayability: String,
2837 artifacts: Vec<ArtifactInput>,
2838 caveats: Vec<String>,
2839 verifier_runs: Vec<VerifierRunInput>,
2840 actor: String,
2841 emitted_at: String,
2842 event_log_root: String,
2843 base_path: String,
2844 operation_id: String,
2845 policy_ref: String,
2846 ) -> Result<Self, ReceiptV1Error> {
2847 let input = Self {
2848 claim,
2849 claim_type,
2850 replayability,
2851 artifacts,
2852 caveats,
2853 verifier_runs,
2854 actor,
2855 emitted_at,
2856 event_log_root,
2857 base_path,
2858 operation_id,
2859 policy_ref,
2860 task_contract_root: None,
2861 scientific_chain: None,
2862 execution_binding: None,
2863 };
2864 validate_neutral_input(&input)?;
2865 Ok(input)
2866 }
2867
2868 pub fn with_task_contract_root(
2871 mut self,
2872 task_contract_root: String,
2873 ) -> Result<Self, ReceiptV1Error> {
2874 if !is_sha256_ref(&task_contract_root) {
2875 return Err(error(
2876 "$.environment.vela:producer_context.task_contract_root",
2877 "must be sha256: followed by 64 lowercase hexadecimal characters",
2878 ));
2879 }
2880 self.task_contract_root = Some(task_contract_root);
2881 Ok(self)
2882 }
2883
2884 pub fn with_scientific_chain(
2887 mut self,
2888 scientific_chain: ScientificChainAssertion,
2889 ) -> Result<Self, ReceiptV1Error> {
2890 validate_scientific_chain_assertion(&scientific_chain)?;
2891 self.scientific_chain = Some(scientific_chain);
2892 Ok(self)
2893 }
2894
2895 pub fn with_execution_binding(
2898 mut self,
2899 execution_binding: ExecutionBindingV1,
2900 ) -> Result<Self, ReceiptV1Error> {
2901 execution_binding.validate().map_err(|cause| {
2902 error(
2903 "$.environment.vela:execution_binding",
2904 format!("is invalid: {cause}"),
2905 )
2906 })?;
2907 self.execution_binding = Some(execution_binding);
2908 Ok(self)
2909 }
2910 }
2911
2912 #[derive(Debug, Clone)]
2913 pub(super) struct ReceiptInput {
2914 claim: String,
2915 claim_type: String,
2916 replayability: String,
2917 artifacts: Vec<ArtifactInput>,
2918 caveats: Vec<String>,
2919 verifier_runs: Vec<VerifierRunInput>,
2920 producer: ProducerContext,
2921 scientific_chain: Option<ScientificChainAssertion>,
2922 execution_binding: Option<ExecutionBindingV1>,
2923 }
2924
2925 impl ReceiptInput {
2926 #[allow(clippy::too_many_arguments)]
2927 pub(super) fn new(
2928 claim: String,
2929 claim_type: String,
2930 replayability: String,
2931 artifacts: Vec<ArtifactInput>,
2932 caveats: Vec<String>,
2933 verifier_runs: Vec<VerifierRunInput>,
2934 producer: ProducerContext,
2935 ) -> Result<Self, ReceiptV1Error> {
2936 let input = Self {
2937 claim,
2938 claim_type,
2939 replayability,
2940 artifacts,
2941 caveats,
2942 verifier_runs,
2943 producer,
2944 scientific_chain: None,
2945 execution_binding: None,
2946 };
2947 validate_input(&input)?;
2948 Ok(input)
2949 }
2950 }
2951
2952 pub struct ReceiptBuilder;
2953
2954 impl ReceiptBuilder {
2955 pub fn build(
2959 input: NeutralReceiptInput,
2960 identity: &IdentityBinding,
2961 ) -> Result<ReceiptV1, ReceiptV1Error> {
2962 validate_neutral_input(&input)?;
2963 let producer = ProducerContext::from_verified_identity(
2964 identity,
2965 &input.actor,
2966 &input.event_log_root,
2967 &input.emitted_at,
2968 &input.base_path,
2969 &input.operation_id,
2970 &input.policy_ref,
2971 )?;
2972 let task_contract_root = input.task_contract_root.clone();
2973 let scientific_chain = input.scientific_chain.clone();
2974 let execution_binding = input.execution_binding.clone();
2975 let NeutralReceiptInput {
2976 claim,
2977 claim_type,
2978 replayability,
2979 artifacts,
2980 caveats,
2981 verifier_runs,
2982 ..
2983 } = input;
2984 let mut validated = ReceiptInput::new(
2985 claim,
2986 claim_type,
2987 replayability,
2988 artifacts,
2989 caveats,
2990 verifier_runs,
2991 producer,
2992 )?;
2993 validated.producer.task_contract_root = task_contract_root;
2994 validated.scientific_chain = scientific_chain;
2995 validated.execution_binding = execution_binding;
2996 Self::build_validated(validated)
2997 }
2998
2999 fn build_validated(input: ReceiptInput) -> Result<ReceiptV1, ReceiptV1Error> {
3000 validate_input(&input)?;
3001 let artifacts: Vec<Value> = input
3002 .artifacts
3003 .iter()
3004 .map(|artifact| {
3005 let mut value = json!({"path": artifact.path, "kind": artifact.kind});
3006 if let Some(hash) = &artifact.sha256 {
3007 value["sha256"] = json!(hash);
3008 }
3009 if let Some(uri) = &artifact.uri {
3010 value["uri"] = json!(uri);
3011 }
3012 value
3013 })
3014 .collect();
3015 let subjects: Vec<Value> = input
3016 .artifacts
3017 .iter()
3018 .map(|artifact| {
3019 let mut value = json!({"name": artifact.path});
3020 if let Some(hash) = &artifact.sha256 {
3021 value["digest"] = json!({"sha256": hash});
3022 }
3023 if let Some(uri) = &artifact.uri {
3024 value["uri"] = json!(uri);
3025 }
3026 value
3027 })
3028 .collect();
3029 let verifier_runs: Vec<Value> = input
3030 .verifier_runs
3031 .iter()
3032 .map(|run| json!({"method": run.method, "outcome": run.outcome}))
3033 .collect();
3034 let scope = "hypothesis_only";
3035 let machine_status = if input.verifier_runs.is_empty() {
3036 "not_assessed"
3037 } else {
3038 "producer_reported"
3039 };
3040
3041 let provenance = json!({
3042 "generated_by": input.producer.generated_by,
3043 "emitted_at": input.producer.emitted_at,
3044 "submitter": {
3045 "actor": input.producer.actor,
3046 "operation_id": input.producer.operation_id,
3047 "identity_binding_ref": input.producer.identity_binding_id,
3048 }
3049 });
3050 let machine = json!({
3051 "subject": subjects,
3052 "claim": {"text": input.claim, "type": input.claim_type},
3053 "verification": {
3054 "status": machine_status,
3055 "verifier_runs": verifier_runs,
3056 "trust_base": {
3057 "kind": "producer_reported",
3058 "authority": "producer",
3059 }
3060 }
3061 });
3062 let acceptance = json!({
3063 "profile": "producer.emission.v1",
3064 "mechanism": ACCEPTANCE_MECHANISM,
3065 "acceptor": null,
3066 "policyRef": input.producer.policy_ref,
3067 "evidenceRefs": [],
3068 "artifact_verification": {"status": "not_assessed", "authority": "producer"},
3069 "claim_acceptance": {
3070 "status": "not_assessed",
3071 "accepted_by": null,
3072 "authority": "producer",
3073 },
3074 "distillation_acceptance": {"status": "not_assessed", "accepted_by": null},
3075 "acceptance_scope": scope,
3076 });
3077 let distillation = json!({
3078 "status": "missing",
3079 "audience": "unspecified",
3080 "rubric": "not_assessed",
3081 });
3082 let lineage = json!({"parents": [], "derived_from": [], "source_refs": []});
3083 let contributors = json!([{
3084 "id": input.producer.actor,
3085 "roles": ["machine_producer"],
3086 "author": false,
3087 "note": "Origin identity only; not scientific acceptance.",
3088 }]);
3089 let identities = json!({
3090 "producer": {
3091 "role": "producer",
3092 "signatureRef": input.producer.identity_binding_id,
3093 "mechanism": "ed25519_key_custody_ceremony",
3094 "subject": input.producer.actor,
3095 "publicKey": input.producer.producer_pubkey_hex,
3096 "identityBindingRef": input.producer.identity_binding_id,
3097 "note": "Self-signed origin binding only; it does not sign this unsigned DSSE receipt or confer scientific acceptance.",
3098 }
3099 });
3100 let mut receipt = json!({
3101 "schema": "vela.receipt.v1",
3102 "claim": input.claim,
3103 "type": input.claim_type,
3104 "replayability": input.replayability,
3105 "artifacts": artifacts,
3106 "caveats": input.caveats,
3107 "verifier_runs": verifier_runs,
3108 "environment": {
3109 "vela:producer_context": {
3110 "actor": input.producer.actor,
3111 "event_log_root": input.producer.event_log_root,
3112 "base_path": input.producer.base_path,
3113 "operation_id": input.producer.operation_id,
3114 "policy_ref": input.producer.policy_ref,
3115 "identity_binding_ref": input.producer.identity_binding_id,
3116 "identity_binding": input.producer.identity_binding,
3117 }
3118 },
3119 "provenance": provenance,
3120 "status": {
3121 "kind": "emitted",
3122 "authority": "producer",
3123 "evidence_status": if input.verifier_runs.is_empty() {"proposed"} else {"runs"},
3124 "scope": {"acceptance_scope": scope},
3125 "note": "Producer emission only. Landing and acceptance are separate.",
3126 },
3127 "machine": machine,
3128 "acceptance": acceptance,
3129 "distillation": distillation,
3130 "lineage": lineage,
3131 "contributors": contributors,
3132 "signature_identities": identities,
3133 });
3134 if let Some(task_contract_root) = input.producer.task_contract_root {
3135 receipt["environment"]["vela:producer_context"]["task_contract_root"] =
3136 json!(task_contract_root);
3137 }
3138 if let Some(scientific_chain) = input.scientific_chain {
3139 receipt["environment"]["vela:scientific_chain"] = scientific_chain.as_value();
3140 }
3141 if let Some(execution_binding) = input.execution_binding {
3142 receipt["environment"]["vela:execution_binding"] =
3143 serde_json::to_value(execution_binding).map_err(|cause| {
3144 error(
3145 "$.environment.vela:execution_binding",
3146 format!("serialize exact binding: {cause}"),
3147 )
3148 })?;
3149 }
3150 let statement = statement_projection(object(&receipt, "$")?)?;
3151 let payload = canonical_receipt_bytes(&statement)
3152 .map_err(|cause| error("$.attestation.statement", cause.to_string()))?;
3153 let attestation = json!({
3154 "format": "in-toto-statement",
3155 "statement": statement,
3156 "dsse_envelope": {
3157 "payloadType": INTOTO_PAYLOAD_TYPE,
3158 "payload": BASE64_STANDARD.encode(payload),
3159 "signatures": [],
3160 }
3161 });
3162 receipt["attestation"] = attestation;
3163 ReceiptV1::from_trusted_value(receipt)
3164 }
3165 }
3166
3167 fn validate_neutral_input(input: &NeutralReceiptInput) -> Result<(), ReceiptV1Error> {
3168 validate_receipt_fields(
3169 &input.claim,
3170 &input.claim_type,
3171 &input.replayability,
3172 &input.artifacts,
3173 &input.caveats,
3174 )?;
3175 validate_actor(&input.actor)?;
3176 chrono::DateTime::parse_from_rfc3339(&input.emitted_at)
3177 .map_err(|_| error("$.provenance.emitted_at", "must be an RFC 3339 date-time"))?;
3178 if input.base_path.trim().is_empty()
3179 || input.base_path != input.base_path.trim()
3180 || input.base_path.chars().any(char::is_control)
3181 {
3182 return Err(error(
3183 "$.environment.vela:producer_context.base_path",
3184 "must be an explicit trimmed path without control characters",
3185 ));
3186 }
3187 if !is_sha256_ref(&input.event_log_root) {
3188 return Err(error(
3189 "$.environment.vela:producer_context.event_log_root",
3190 "must be sha256: followed by 64 lowercase hexadecimal characters",
3191 ));
3192 }
3193 if !is_operation_id(&input.operation_id) {
3194 return Err(error(
3195 "$.environment.vela:producer_context.operation_id",
3196 "must be vop_ followed by 64 lowercase hexadecimal characters",
3197 ));
3198 }
3199 if input
3200 .task_contract_root
3201 .as_deref()
3202 .is_some_and(|root| !is_sha256_ref(root))
3203 {
3204 return Err(error(
3205 "$.environment.vela:producer_context.task_contract_root",
3206 "must be sha256: followed by 64 lowercase hexadecimal characters",
3207 ));
3208 }
3209 validate_policy_ref(&input.policy_ref)?;
3210 if let Some(scientific_chain) = &input.scientific_chain {
3211 validate_scientific_chain_assertion(scientific_chain)?;
3212 }
3213 if let Some(execution_binding) = &input.execution_binding {
3214 execution_binding.validate().map_err(|cause| {
3215 error(
3216 "$.environment.vela:execution_binding",
3217 format!("is invalid: {cause}"),
3218 )
3219 })?;
3220 }
3221 Ok(())
3222 }
3223
3224 fn is_sha256_ref(value: &str) -> bool {
3225 value
3226 .strip_prefix("sha256:")
3227 .is_some_and(|hex| is_lower_hex(hex, 64))
3228 }
3229
3230 fn is_operation_id(value: &str) -> bool {
3231 value
3232 .strip_prefix("vop_")
3233 .is_some_and(|hex| is_lower_hex(hex, 64))
3234 }
3235
3236 fn is_lower_hex(value: &str, length: usize) -> bool {
3237 value.len() == length
3238 && value
3239 .bytes()
3240 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
3241 }
3242
3243 fn validate_input(input: &ReceiptInput) -> Result<(), ReceiptV1Error> {
3244 validate_receipt_fields(
3245 &input.claim,
3246 &input.claim_type,
3247 &input.replayability,
3248 &input.artifacts,
3249 &input.caveats,
3250 )?;
3251 if let Some(scientific_chain) = &input.scientific_chain {
3252 validate_scientific_chain_assertion(scientific_chain)?;
3253 }
3254 if let Some(execution_binding) = &input.execution_binding {
3255 execution_binding.validate().map_err(|cause| {
3256 error(
3257 "$.environment.vela:execution_binding",
3258 format!("is invalid: {cause}"),
3259 )
3260 })?;
3261 }
3262 Ok(())
3263 }
3264
3265 fn validate_scientific_chain_assertion(
3266 assertion: &ScientificChainAssertion,
3267 ) -> Result<(), ReceiptV1Error> {
3268 let receipt = json!({
3269 "environment": {"vela:scientific_chain": assertion.as_value()}
3270 });
3271 let receipt = object(&receipt, "$")?;
3272 validate_scientific_chain_extension(receipt)
3273 }
3274
3275 fn validate_receipt_fields(
3276 claim: &str,
3277 claim_type: &str,
3278 replayability: &str,
3279 artifacts: &[ArtifactInput],
3280 caveats: &[String],
3281 ) -> Result<(), ReceiptV1Error> {
3282 if claim.trim().is_empty() {
3283 return Err(error("$.claim", "must be an explicit non-empty claim"));
3284 }
3285 if artifacts.is_empty() {
3286 return Err(error("$.artifacts", "at least one reference is required"));
3287 }
3288 if caveats.is_empty() || caveats.iter().any(|item| item.trim().is_empty()) {
3289 return Err(error(
3290 "$.caveats",
3291 "explicit non-empty caveats are required",
3292 ));
3293 }
3294 if !super::CLAIM_TYPES.contains(&claim_type) {
3295 return Err(error("$.type", "is not a published Receipt v1 claim type"));
3296 }
3297 if !super::REPLAYABILITY.contains(&replayability) {
3298 return Err(error(
3299 "$.replayability",
3300 "is not a published Receipt v1 replayability class",
3301 ));
3302 }
3303 Ok(())
3304 }
3305}
3306
3307pub use authoring::{
3308 ArtifactInput, NeutralReceiptInput as ReceiptInput, ReceiptBuilder, ScientificChainAssertion,
3309 VerifierRunInput as ProducerReportedRun,
3310};
3311
3312#[cfg(test)]
3313mod tests {
3314 use super::*;
3315 use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
3316 use ed25519_dalek::SigningKey;
3317 use serde_json::json;
3318 use sha2::{Digest, Sha256};
3319
3320 use crate::identity::{ActorClass, IdentityBinding, IdentityBindingDraft};
3321
3322 type ReceiptMutation = (&'static str, Box<dyn Fn(&mut Value)>);
3323
3324 fn identity(actor: &str) -> IdentityBinding {
3325 IdentityBinding::build(
3326 IdentityBindingDraft {
3327 actor_id: actor.into(),
3328 actor_class: ActorClass::Agent,
3329 created_at: "2026-07-13T12:34:55Z".into(),
3330 },
3331 &SigningKey::from_bytes(&[0x42; 32]),
3332 )
3333 .unwrap()
3334 }
3335
3336 fn input(runs: Vec<ProducerReportedRun>) -> ReceiptInput {
3337 input_for_actor(runs, "agent:receipt-test")
3338 }
3339
3340 fn input_for_actor(runs: Vec<ProducerReportedRun>, actor: &str) -> ReceiptInput {
3341 try_input_for_actor(runs, actor).unwrap()
3342 }
3343
3344 fn try_input_for_actor(
3345 runs: Vec<ProducerReportedRun>,
3346 actor: &str,
3347 ) -> Result<ReceiptInput, ReceiptV1Error> {
3348 try_input_with_mechanics(
3349 runs,
3350 actor,
3351 &format!("sha256:{}", "c".repeat(64)),
3352 &format!("vop_{}", "d".repeat(64)),
3353 NO_ACTIVE_POLICY_REF,
3354 )
3355 }
3356
3357 fn try_input_with_mechanics(
3358 runs: Vec<ProducerReportedRun>,
3359 actor: &str,
3360 event_log_root: &str,
3361 operation_id: &str,
3362 policy_ref: &str,
3363 ) -> Result<ReceiptInput, ReceiptV1Error> {
3364 ReceiptInput::new(
3365 "The bounded witness has the declared checksum.".into(),
3366 "computational".into(),
3367 "exact".into(),
3368 vec![
3369 ArtifactInput::new(
3370 "witnesses/result.json".into(),
3371 "witness".into(),
3372 Some("a".repeat(64)),
3373 Some("https://example.test/result.json".into()),
3374 )
3375 .unwrap(),
3376 ],
3377 vec!["This does not establish the unbounded claim.".into()],
3378 runs,
3379 actor.into(),
3380 "2026-07-13T12:34:56Z".into(),
3381 event_log_root.into(),
3382 env!("CARGO_MANIFEST_DIR").into(),
3383 operation_id.into(),
3384 policy_ref.into(),
3385 )
3386 }
3387
3388 fn build(runs: Vec<ProducerReportedRun>) -> ReceiptV1 {
3389 ReceiptBuilder::build(input(runs), &identity("agent:receipt-test")).unwrap()
3390 }
3391
3392 fn schema() -> Value {
3393 let bytes = std::fs::read(concat!(
3394 env!("CARGO_MANIFEST_DIR"),
3395 "/../../docs/schemas/vela.receipt.v1.schema.json"
3396 ))
3397 .unwrap();
3398 serde_json::from_slice(&bytes).unwrap()
3399 }
3400
3401 fn refresh_payload_only(receipt: &mut Value) {
3402 let bytes = canonical_receipt_bytes(&receipt["attestation"]["statement"]).unwrap();
3403 receipt["attestation"]["dsse_envelope"]["payload"] = json!(BASE64_STANDARD.encode(bytes));
3404 }
3405
3406 fn refresh_bound_attestation(receipt: &mut Value) {
3407 let predicate_extensions = receipt["attestation"]["statement"]["predicate"]
3408 .as_object()
3409 .unwrap()
3410 .iter()
3411 .filter(|(key, _)| key.starts_with("x:"))
3412 .map(|(key, value)| (key.clone(), value.clone()))
3413 .collect::<Vec<_>>();
3414 let mut statement = statement_projection(object(receipt, "$").unwrap()).unwrap();
3415 let predicate = statement["predicate"].as_object_mut().unwrap();
3416 for (key, value) in predicate_extensions {
3417 predicate.insert(key, value);
3418 }
3419 receipt["attestation"]["statement"] = statement;
3420 refresh_payload_only(receipt);
3421 }
3422
3423 fn restricted_receipt(locator: &str) -> Value {
3424 let mut receipt = build(Vec::new()).into_value();
3425 receipt["artifacts"][0] = json!({
3426 "path": locator,
3427 "kind": "restricted_witness",
3428 "disclosure": "restricted",
3429 "media_type": "application/octet-stream",
3430 "locator_integrity": "unknown",
3431 "availability": "available",
3432 });
3433 receipt["machine"]["subject"][0] = json!({"name": locator});
3434 refresh_bound_attestation(&mut receipt);
3435 receipt
3436 }
3437
3438 fn reported_pass() -> ProducerReportedRun {
3439 ProducerReportedRun::producer_reported("producer.check".into(), "pass".into()).unwrap()
3440 }
3441
3442 #[test]
3443 fn builder_emits_complete_frozen_shape_without_authority_invention() {
3444 let receipt = build(Vec::new());
3445 let value = receipt.as_value();
3446 let schema = schema();
3447 let required: Vec<&str> = schema["required"]
3448 .as_array()
3449 .unwrap()
3450 .iter()
3451 .map(|item| item.as_str().unwrap())
3452 .collect();
3453 assert_eq!(required, RECEIPT_V1_REQUIRED_FIELDS);
3454 assert!(required.iter().all(|field| value.get(field).is_some()));
3455 assert_eq!(value["schema"], schema["properties"]["schema"]["const"]);
3456 assert_eq!(value["status"]["authority"], "producer");
3457 assert_eq!(value["machine"]["verification"]["status"], "not_assessed");
3458 assert_eq!(value["acceptance"]["acceptor"], Value::Null);
3459 assert_eq!(value["acceptance"]["evidenceRefs"], json!([]));
3460 assert_eq!(
3461 value["acceptance"]["claim_acceptance"]["status"],
3462 "not_assessed"
3463 );
3464 assert_eq!(value["acceptance"]["acceptance_scope"], "hypothesis_only");
3465 assert_eq!(value["acceptance"]["policyRef"], NO_ACTIVE_POLICY_REF);
3466 assert_eq!(
3467 value["signature_identities"]["producer"]["mechanism"],
3468 "ed25519_key_custody_ceremony"
3469 );
3470 assert_eq!(
3471 value["signature_identities"]["producer"]["publicKey"]
3472 .as_str()
3473 .unwrap()
3474 .len(),
3475 64
3476 );
3477 assert!(
3478 value["signature_identities"]["producer"]["identityBindingRef"]
3479 .as_str()
3480 .unwrap()
3481 .starts_with("vib_")
3482 );
3483 assert_eq!(
3484 value["signature_identities"]["producer"]["signatureRef"],
3485 value["signature_identities"]["producer"]["identityBindingRef"]
3486 );
3487 let embedded: IdentityBinding = serde_json::from_value(
3488 value["environment"]["vela:producer_context"]["identity_binding"].clone(),
3489 )
3490 .unwrap();
3491 embedded.verify().unwrap();
3492 assert_eq!(
3493 value["attestation"]["dsse_envelope"]["signatures"],
3494 json!([])
3495 );
3496 assert!(value["environment"].get("source").is_none());
3497 assert!(value["environment"].get("independence_basis").is_none());
3498 assert_eq!(
3499 value["attestation"]["statement"]["predicate"][RECEIPT_BODY_BINDING_FIELD]["sha256"],
3500 receipt_body_sha256(object(value, "$").unwrap()).unwrap()
3501 );
3502 validate_schema_exact(value).unwrap();
3503 assert!(
3504 !String::from_utf8(receipt.canonical_bytes().unwrap())
3505 .unwrap()
3506 .contains("sigstore")
3507 );
3508 assert!(
3509 !String::from_utf8(receipt.canonical_bytes().unwrap())
3510 .unwrap()
3511 .contains("_fixture")
3512 );
3513 }
3514
3515 #[test]
3516 fn execution_binding_is_closed_full_digest_and_body_bound() {
3517 let original_root = build(Vec::new()).canonical_root().unwrap();
3518 let binding = ExecutionBindingV1 {
3519 schema: EXECUTION_BINDING_SCHEMA.to_string(),
3520 packet_root: format!("sha256:{}", "1".repeat(64)),
3521 profile_root: format!("sha256:{}", "2".repeat(64)),
3522 verifier_capsule_root: format!("sha256:{}", "3".repeat(64)),
3523 result_contract_root: format!("sha256:{}", "4".repeat(64)),
3524 };
3525 let receipt = ReceiptBuilder::build(
3526 input(Vec::new())
3527 .with_execution_binding(binding.clone())
3528 .unwrap(),
3529 &identity("agent:receipt-test"),
3530 )
3531 .unwrap();
3532 let value = receipt.as_value().clone();
3533 let parsed = ReceiptV1::parse(&receipt.canonical_bytes().unwrap()).unwrap();
3534 let binding = parsed.execution_binding().unwrap().unwrap();
3535 assert_eq!(binding.schema, EXECUTION_BINDING_SCHEMA);
3536 assert_ne!(parsed.canonical_root().unwrap(), original_root);
3537
3538 for (field, replacement) in [
3539 ("packet_root", json!(format!("sha256:{}", "a".repeat(63)))),
3540 ("profile_root", json!(format!("sha256:{}", "A".repeat(64)))),
3541 ("verifier_capsule_root", json!("vf_short")),
3542 ("result_contract_root", Value::Null),
3543 ] {
3544 let mut malformed = value.clone();
3545 malformed["environment"]["vela:execution_binding"][field] = replacement;
3546 refresh_bound_attestation(&mut malformed);
3547 let error = ReceiptV1::parse(&serde_json::to_vec(&malformed).unwrap()).unwrap_err();
3548 assert!(
3549 error.path().contains("vela:execution_binding"),
3550 "{field}: {error}"
3551 );
3552 }
3553
3554 let mut unknown = value;
3555 unknown["environment"]["vela:execution_binding"]["target_alias"] = json!("sidon:a24");
3556 refresh_bound_attestation(&mut unknown);
3557 assert!(
3558 ReceiptV1::parse(&serde_json::to_vec(&unknown).unwrap())
3559 .unwrap_err()
3560 .path()
3561 .contains("vela:execution_binding")
3562 );
3563 }
3564
3565 #[test]
3566 fn builder_never_infers_authority_from_reported_runs_or_raw_identity_strings() {
3567 let receipt = build(vec![reported_pass()]);
3568 assert_eq!(
3569 receipt.as_value()["acceptance"]["acceptance_scope"],
3570 "hypothesis_only"
3571 );
3572 assert_eq!(
3573 receipt.as_value()["machine"]["verification"]["status"],
3574 "producer_reported"
3575 );
3576 assert_eq!(
3577 receipt.as_value()["acceptance"]["claim_acceptance"]["status"],
3578 "not_assessed"
3579 );
3580 assert!(
3581 !String::from_utf8(receipt.canonical_bytes().unwrap())
3582 .unwrap()
3583 .contains("machine_verified")
3584 );
3585
3586 assert_eq!(
3587 try_input_for_actor(Vec::new(), "agent:")
3588 .unwrap_err()
3589 .path(),
3590 "$.provenance.submitter.actor"
3591 );
3592 let mut forged_identity = identity("agent:receipt-test");
3593 forged_identity.public_key_hex = "b".repeat(64);
3594 assert!(ReceiptBuilder::build(input(Vec::new()), &forged_identity).is_err());
3595 assert_eq!(
3596 ReceiptBuilder::build(
3597 input_for_actor(Vec::new(), "agent:receipt-test"),
3598 &identity("agent:other"),
3599 )
3600 .unwrap_err()
3601 .path(),
3602 "$.provenance.submitter.actor"
3603 );
3604 }
3605
3606 #[test]
3607 fn authoring_api_rejects_untyped_mechanical_and_policy_references() {
3608 assert_eq!(
3609 try_input_with_mechanics(
3610 Vec::new(),
3611 "agent:receipt-test",
3612 "sha256:not-a-root",
3613 &format!("vop_{}", "d".repeat(64)),
3614 NO_ACTIVE_POLICY_REF,
3615 )
3616 .unwrap_err()
3617 .path(),
3618 "$.environment.vela:producer_context.event_log_root"
3619 );
3620 assert_eq!(
3621 try_input_with_mechanics(
3622 Vec::new(),
3623 "agent:receipt-test",
3624 &format!("sha256:{}", "c".repeat(64)),
3625 "vop_short",
3626 NO_ACTIVE_POLICY_REF,
3627 )
3628 .unwrap_err()
3629 .path(),
3630 "$.environment.vela:producer_context.operation_id"
3631 );
3632 assert_eq!(
3633 try_input_with_mechanics(
3634 Vec::new(),
3635 "agent:receipt-test",
3636 &format!("sha256:{}", "c".repeat(64)),
3637 &format!("vop_{}", "d".repeat(64)),
3638 "vap_invented",
3639 )
3640 .unwrap_err()
3641 .path(),
3642 "$.acceptance.policyRef"
3643 );
3644
3645 let policy_ref = format!("vap_{}", "e".repeat(32));
3646 let receipt = ReceiptBuilder::build(
3647 try_input_with_mechanics(
3648 Vec::new(),
3649 "agent:receipt-test",
3650 &format!("sha256:{}", "c".repeat(64)),
3651 &format!("vop_{}", "d".repeat(64)),
3652 &policy_ref,
3653 )
3654 .unwrap(),
3655 &identity("agent:receipt-test"),
3656 )
3657 .unwrap();
3658 assert_eq!(receipt.as_value()["acceptance"]["policyRef"], policy_ref);
3659 assert_eq!(
3660 receipt.as_value()["acceptance"]["acceptance_scope"],
3661 "hypothesis_only"
3662 );
3663 }
3664
3665 #[test]
3666 fn task_contract_root_extension_is_validated_and_bound_on_import() {
3667 let root = format!("sha256:{}", "e".repeat(64));
3668 let receipt = ReceiptBuilder::build(
3669 input(Vec::new())
3670 .with_task_contract_root(root.clone())
3671 .unwrap(),
3672 &identity("agent:receipt-test"),
3673 )
3674 .unwrap();
3675 assert_eq!(
3676 receipt.as_value()["environment"]["vela:producer_context"]["task_contract_root"],
3677 root
3678 );
3679 ReceiptV1::parse(&receipt.canonical_bytes().unwrap()).unwrap();
3680
3681 assert_eq!(
3682 input(Vec::new())
3683 .with_task_contract_root("sha256:not-a-root".to_string())
3684 .unwrap_err()
3685 .path(),
3686 "$.environment.vela:producer_context.task_contract_root"
3687 );
3688
3689 let mut malformed = receipt.into_value();
3690 malformed["environment"]["vela:producer_context"]["task_contract_root"] =
3691 json!("sha256:NOT-CANONICAL");
3692 refresh_bound_attestation(&mut malformed);
3693 let failure = ReceiptV1::parse(&serde_json::to_vec(&malformed).unwrap()).unwrap_err();
3694 assert_eq!(
3695 failure.path(),
3696 "$.environment.vela:producer_context.task_contract_root"
3697 );
3698 }
3699
3700 #[test]
3701 fn scientific_chain_producer_assertion_round_trips_and_is_body_bound() {
3702 let assertion = ScientificChainAssertion::new(
3703 Some("The bounded checksum remains stable on an exact replay.".to_string()),
3704 false,
3705 "Re-run the frozen checksum verifier over witnesses/result.json.".to_string(),
3706 "The verifier returned pass with the declared checksum.".to_string(),
3707 vec![
3708 "witnesses/result.json".to_string(),
3709 "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3710 .to_string(),
3711 ],
3712 vec!["records/attempts/failed-seed.json".to_string()],
3713 )
3714 .unwrap();
3715 let receipt = ReceiptBuilder::build(
3716 input(Vec::new()).with_scientific_chain(assertion).unwrap(),
3717 &identity("agent:receipt-test"),
3718 )
3719 .unwrap();
3720 let expected = json!({
3721 "schema": "vela.scientific-chain.producer.v1",
3722 "authority": "producer",
3723 "predicted_observable": "The bounded checksum remains stable on an exact replay.",
3724 "not_applicable": false,
3725 "performed_test": "Re-run the frozen checksum verifier over witnesses/result.json.",
3726 "result": "The verifier returned pass with the declared checksum.",
3727 "evidence": [
3728 "witnesses/result.json",
3729 "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
3730 ],
3731 "counterevidence": ["records/attempts/failed-seed.json"],
3732 });
3733 assert_eq!(
3734 receipt.as_value()["environment"]["vela:scientific_chain"],
3735 expected
3736 );
3737 let reparsed = ReceiptV1::parse(&receipt.canonical_bytes().unwrap()).unwrap();
3738 assert_eq!(
3739 reparsed.as_value()["environment"]["vela:scientific_chain"],
3740 expected
3741 );
3742
3743 let mut tampered = receipt.into_value();
3744 tampered["environment"]["vela:scientific_chain"]["result"] =
3745 json!("The result was changed after emission.");
3746 let failure = ReceiptV1::parse(&serde_json::to_vec(&tampered).unwrap()).unwrap_err();
3747 assert_eq!(
3748 failure.path(),
3749 "$.attestation.statement.predicate.vela:receipt_body"
3750 );
3751 }
3752
3753 #[test]
3754 fn scientific_chain_is_optional_exactly_one_prediction_mode_and_bounded() {
3755 let plain = build(Vec::new());
3756 assert!(
3757 plain.as_value()["environment"]
3758 .get("vela:scientific_chain")
3759 .is_none()
3760 );
3761
3762 let not_applicable = ScientificChainAssertion::new(
3763 None,
3764 true,
3765 "Inspect the source-only argument.".to_string(),
3766 "No empirical observable applies to this theoretical reduction.".to_string(),
3767 vec!["proof/reduction.md".to_string()],
3768 Vec::new(),
3769 )
3770 .unwrap();
3771 let receipt = ReceiptBuilder::build(
3772 input(Vec::new())
3773 .with_scientific_chain(not_applicable)
3774 .unwrap(),
3775 &identity("agent:receipt-test"),
3776 )
3777 .unwrap();
3778 assert_eq!(
3779 receipt.as_value()["environment"]["vela:scientific_chain"]["not_applicable"],
3780 true
3781 );
3782 assert!(
3783 receipt.as_value()["environment"]["vela:scientific_chain"]
3784 .get("predicted_observable")
3785 .is_none()
3786 );
3787
3788 for (prediction, not_applicable) in [(None, false), (Some("prediction".into()), true)] {
3789 let failure = ScientificChainAssertion::new(
3790 prediction,
3791 not_applicable,
3792 "test".to_string(),
3793 "result".to_string(),
3794 vec!["evidence".to_string()],
3795 Vec::new(),
3796 )
3797 .unwrap_err();
3798 assert_eq!(
3799 failure.path(),
3800 "$.environment.vela:scientific_chain.predicted_observable"
3801 );
3802 }
3803
3804 let too_many = (0..=SCIENTIFIC_CHAIN_MAX_REFERENCES)
3805 .map(|index| format!("evidence:{index}"))
3806 .collect();
3807 assert_eq!(
3808 ScientificChainAssertion::new(
3809 Some("prediction".to_string()),
3810 false,
3811 "test".to_string(),
3812 "result".to_string(),
3813 too_many,
3814 Vec::new(),
3815 )
3816 .unwrap_err()
3817 .path(),
3818 "$.environment.vela:scientific_chain.evidence"
3819 );
3820 assert_eq!(
3821 ScientificChainAssertion::new(
3822 Some("x".repeat(SCIENTIFIC_CHAIN_MAX_TEXT_BYTES + 1)),
3823 false,
3824 "test".to_string(),
3825 "result".to_string(),
3826 vec!["evidence".to_string()],
3827 Vec::new(),
3828 )
3829 .unwrap_err()
3830 .path(),
3831 "$.environment.vela:scientific_chain.predicted_observable"
3832 );
3833 }
3834
3835 #[test]
3836 fn embedded_identity_binding_is_verified_after_clean_clone_import() {
3837 let receipt = build(Vec::new());
3838 let reparsed = ReceiptV1::parse(&receipt.canonical_bytes().unwrap()).unwrap();
3839 let embedded: IdentityBinding = serde_json::from_value(
3840 reparsed.as_value()["environment"]["vela:producer_context"]["identity_binding"].clone(),
3841 )
3842 .unwrap();
3843 embedded.verify().unwrap();
3844
3845 let mut tampered = receipt.into_value();
3846 tampered["environment"]["vela:producer_context"]["identity_binding"]["signature"] =
3847 json!("00".repeat(64));
3848 refresh_bound_attestation(&mut tampered);
3849 let failure = ReceiptV1::parse(&serde_json::to_vec(&tampered).unwrap()).unwrap_err();
3850 assert_eq!(
3851 failure.path(),
3852 "$.environment.vela:producer_context.identity_binding"
3853 );
3854 assert!(failure.message().contains("proof of possession"));
3855 }
3856
3857 #[test]
3858 fn current_schema_accepts_the_protocol_builder() {
3859 let schema = std::fs::read(concat!(
3860 env!("CARGO_MANIFEST_DIR"),
3861 "/../../docs/schemas/vela.receipt.v1.schema.json"
3862 ))
3863 .unwrap();
3864 assert!(!schema.is_empty());
3865 let receipt = build(Vec::new());
3866 validate_schema_exact(receipt.as_value()).unwrap();
3867 }
3868
3869 #[test]
3870 fn rich_unknown_extensions_round_trip_losslessly_and_bind_root() {
3871 let initial = build(Vec::new());
3872 let initial_body = receipt_body_sha256(object(initial.as_value(), "$").unwrap()).unwrap();
3873 let mut raw = initial.into_value();
3874 raw["x:hep-belief"] =
3875 json!({"asserted_by": "collaboration:test", "confidence": ["0.7", "0.9"]});
3876 raw["environment"]["x:codegraph"] =
3877 json!({"root": "sha256:graph", "symbols": [{"name": "α", "span": [7, 11]}]});
3878 raw["acceptance"]["x:external-certificates"] =
3879 json!([{"profile": "independent-review.v2", "certificate": {"opaque": true}}]);
3880 raw["lineage"]["derived_from"] = json!(["arxiv:2607.09195"]);
3881 raw["attestation"]["statement"]["predicate"]["x:article-machine"] = json!({"document": "producer:article-machine", "sections": ["definition", "verification"]});
3882 refresh_bound_attestation(&mut raw);
3883
3884 let parsed = ReceiptV1::parse(&serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
3885 assert_ne!(
3886 initial_body,
3887 receipt_body_sha256(object(parsed.as_value(), "$").unwrap()).unwrap()
3888 );
3889 assert_eq!(parsed.as_value(), &raw);
3890 assert_eq!(serde_json::to_value(&parsed).unwrap(), raw);
3891 let bytes = canonical_receipt_bytes(&raw).unwrap();
3892 assert_eq!(parsed.canonical_bytes().unwrap(), bytes);
3893 assert_eq!(
3894 parsed.canonical_root().unwrap(),
3895 format!("sha256:{}", hex::encode(Sha256::digest(&bytes)))
3896 );
3897 assert_eq!(ReceiptV1::parse(&bytes).unwrap().into_value(), raw);
3898 }
3899
3900 #[test]
3901 fn restricted_artifacts_allow_only_the_reviewed_safe_public_descriptor() {
3902 for locator in ["opaque:custodian-fixture-7", "custodian:lab-a:artifact-17"] {
3903 let raw = restricted_receipt(locator);
3904 let parsed = ReceiptV1::parse(&serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
3905 parsed.validate_safe_public_artifact_descriptors().unwrap();
3906 assert_eq!(
3907 parsed.as_value()["machine"]["subject"],
3908 json!([{"name": locator}])
3909 );
3910 assert_eq!(parsed.as_value(), &raw);
3911 }
3912 }
3913
3914 #[test]
3915 fn restricted_artifact_subject_and_prov_mirrors_cannot_carry_secret_material() {
3916 let secret_digest = "7".repeat(64);
3917
3918 let mut machine_digest = restricted_receipt("opaque:custodian-fixture-7");
3919 machine_digest["machine"]["subject"][0]["digest"] = json!({"sha256": secret_digest});
3920 refresh_bound_attestation(&mut machine_digest);
3921 let failure = ReceiptV1::parse(&serde_json::to_vec(&machine_digest).unwrap()).unwrap_err();
3922 assert_eq!(failure.path(), "$.machine.subject");
3923
3924 let mut machine_opening = restricted_receipt("opaque:custodian-fixture-7");
3925 machine_opening["machine"]["subject"][0]["opening"] = json!("do-not-publish");
3926 refresh_bound_attestation(&mut machine_opening);
3927 let failure = ReceiptV1::parse(&serde_json::to_vec(&machine_opening).unwrap()).unwrap_err();
3928 assert_eq!(failure.path(), "$.machine.subject");
3929
3930 let mut machine_location = restricted_receipt("opaque:custodian-fixture-7");
3931 machine_location["machine"]["subject"][0]["uri"] = json!("file:///private/secret.bin");
3932 refresh_bound_attestation(&mut machine_location);
3933 let failure =
3934 ReceiptV1::parse(&serde_json::to_vec(&machine_location).unwrap()).unwrap_err();
3935 assert_eq!(failure.path(), "$.machine.subject");
3936
3937 let mut statement_location = restricted_receipt("opaque:custodian-fixture-7");
3938 statement_location["attestation"]["statement"]["subject"][0]["uri"] =
3939 json!("https://internal.invalid/secret.bin");
3940 refresh_payload_only(&mut statement_location);
3941 let failure =
3942 ReceiptV1::parse(&serde_json::to_vec(&statement_location).unwrap()).unwrap_err();
3943 assert_eq!(failure.path(), "$.attestation.statement.subject");
3944
3945 let mut predicate_digest = restricted_receipt("opaque:custodian-fixture-7");
3946 predicate_digest["attestation"]["statement"]["predicate"]["machine"]["subject"][0]["digest"] =
3947 json!({"sha256": "8".repeat(64)});
3948 refresh_payload_only(&mut predicate_digest);
3949 let failure =
3950 ReceiptV1::parse(&serde_json::to_vec(&predicate_digest).unwrap()).unwrap_err();
3951 assert_eq!(
3952 failure.path(),
3953 "$.attestation.statement.predicate.machine.subject"
3954 );
3955
3956 for (field, value) in [
3957 ("vela:sha256", json!("9".repeat(64))),
3958 ("opening", json!("do-not-publish")),
3959 ("location", json!("/private/secret.bin")),
3960 ] {
3961 let mut prov = restricted_receipt("opaque:custodian-fixture-7");
3962 prov["attestation"]["prov"] = json!({
3963 "entity": {
3964 "artifact:opaque:custodian-fixture-7": {
3965 "prov:type": "vela:artifact",
3966 "vela:kind": "restricted_witness",
3967 (field): value,
3968 }
3969 }
3970 });
3971 let failure = ReceiptV1::parse(&serde_json::to_vec(&prov).unwrap()).unwrap_err();
3972 assert_eq!(
3973 failure.path(),
3974 format!("$.attestation.prov.entity.artifact:opaque:custodian-fixture-7.{field}")
3975 );
3976 }
3977 }
3978
3979 #[test]
3980 fn mixed_public_and_restricted_subjects_are_derived_without_losing_public_digests() {
3981 let mut raw = restricted_receipt("opaque:custodian-fixture-7");
3982 raw["artifacts"].as_array_mut().unwrap().push(json!({
3983 "path": "artifacts/public.json",
3984 "kind": "witness",
3985 "sha256": "a".repeat(64),
3986 }));
3987 raw["machine"]["subject"] = json!([
3988 {"name": "opaque:custodian-fixture-7"},
3989 {"name": "artifacts/public.json", "digest": {"sha256": "a".repeat(64)}},
3990 ]);
3991 refresh_bound_attestation(&mut raw);
3992 let parsed = ReceiptV1::parse(&serde_json::to_vec(&raw).unwrap()).unwrap();
3993 assert_eq!(parsed.as_value(), &raw);
3994 }
3995
3996 #[test]
3997 fn restricted_artifacts_reject_payload_opening_location_digest_size_and_extensions() {
3998 let cases = [
3999 ("opening", json!("do-not-publish")),
4000 ("content", json!("do-not-publish")),
4001 ("data", json!({"value": "do-not-publish"})),
4002 ("payload", json!("do-not-publish")),
4003 ("bytes", json!([115, 101, 99, 114, 101, 116])),
4004 ("plaintext", json!("do-not-publish")),
4005 ("secret", json!("do-not-publish")),
4006 ("inline", json!("do-not-publish")),
4007 ("uri", json!("file:///private/secret.bin")),
4008 ("url", json!("https://internal.invalid/secret.bin")),
4009 ("location", json!("/private/secret.bin")),
4010 ("sha256", json!("a".repeat(64))),
4011 ("digest", json!({"sha256": "a".repeat(64)})),
4012 ("size", json!(17)),
4013 ("size_bytes", json!(17)),
4014 ("x:apparently-safe", json!({"reviewed": false})),
4015 ("x:opening", json!("do-not-publish")),
4016 ];
4017 for (field, value) in cases {
4018 let mut raw = restricted_receipt("opaque:custodian-fixture-7");
4019 raw["artifacts"][0][field] = value;
4020 refresh_bound_attestation(&mut raw);
4021 let failure = ReceiptV1::parse(&serde_json::to_vec(&raw).unwrap()).unwrap_err();
4022 assert_eq!(failure.path(), format!("$.artifacts[0].{field}"));
4023 assert!(
4024 failure.message().contains("not permitted"),
4025 "{field}: {failure}"
4026 );
4027 }
4028 }
4029
4030 #[test]
4031 fn restricted_artifact_locator_is_opaque_and_non_resolving() {
4032 for locator in [
4033 "witnesses/secret.bin",
4034 "https://example.invalid/secret.bin",
4035 "file:///private/secret.bin",
4036 "opaque:",
4037 "opaque:https://example.invalid/secret.bin",
4038 "custodian:../secret",
4039 "opaque:has whitespace",
4040 ] {
4041 let raw = restricted_receipt(locator);
4042 let failure = ReceiptV1::parse(&serde_json::to_vec(&raw).unwrap()).unwrap_err();
4043 assert_eq!(failure.path(), "$.artifacts[0].path", "{locator}");
4044 }
4045 }
4046
4047 #[test]
4048 fn alternate_sensitive_visibility_cannot_bypass_canonical_disclosure() {
4049 for (field, value) in [
4050 ("visibility", "restricted"),
4051 ("access_tier", "classified"),
4052 ("accessTier", "private"),
4053 ] {
4054 let mut raw = build(Vec::new()).into_value();
4055 raw["artifacts"][0][field] = json!(value);
4056 refresh_bound_attestation(&mut raw);
4057 let failure = ReceiptV1::parse(&serde_json::to_vec(&raw).unwrap()).unwrap_err();
4058 assert_eq!(failure.path(), format!("$.artifacts[0].{field}"));
4059 assert!(failure.message().contains("disclosure: restricted"));
4060 }
4061 }
4062
4063 #[test]
4064 fn public_artifact_extensions_remain_lossless_and_compatible() {
4065 let mut raw = build(Vec::new()).into_value();
4066 raw["artifacts"][0]["x:producer-metadata"] =
4067 json!({"tool": "outside-producer", "result_class": "candidate"});
4068 refresh_bound_attestation(&mut raw);
4069 let parsed = ReceiptV1::parse(&serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
4070 parsed.validate_safe_public_artifact_descriptors().unwrap();
4071 assert_eq!(parsed.into_value(), raw);
4072 }
4073
4074 #[test]
4075 fn numeric_extensions_preserve_frozen_floats_and_bound_safe_integers() {
4076 let mut safe = build(Vec::new()).into_value();
4077 safe["x:numeric-domain"] = json!({
4078 "minimum": -(MAX_PORTABLE_JSON_INTEGER as i64),
4079 "maximum": MAX_PORTABLE_JSON_INTEGER,
4080 "zero": 0,
4081 "pre_adr_decimal": 0.61,
4082 "pre_adr_exponent": 0.000000125,
4083 "exponent_integer": 1000,
4084 });
4085 refresh_bound_attestation(&mut safe);
4086 let canonical = String::from_utf8(canonical_receipt_bytes(&safe).unwrap()).unwrap();
4087 assert!(canonical.contains(r#""pre_adr_decimal":0.61"#));
4088 assert!(canonical.contains(r#""pre_adr_exponent":1.25e-7"#));
4089 let pre_adr_wire = canonical
4090 .replace(
4091 r#""pre_adr_exponent":1.25e-7"#,
4092 r#""pre_adr_exponent":1.25E-7"#,
4093 )
4094 .replace(r#""exponent_integer":1000"#, r#""exponent_integer":1e3"#);
4095 let parsed = ReceiptV1::parse(pre_adr_wire.as_bytes()).unwrap();
4096 assert_eq!(
4097 parsed.as_value()["x:numeric-domain"]["pre_adr_decimal"],
4098 json!(0.61)
4099 );
4100 assert_eq!(
4101 parsed.as_value()["x:numeric-domain"]["pre_adr_exponent"],
4102 json!(0.000000125)
4103 );
4104 assert_eq!(
4105 parsed.as_value()["x:numeric-domain"]["exponent_integer"].as_f64(),
4106 Some(1000.0)
4107 );
4108 assert_eq!(parsed.canonical_bytes().unwrap(), canonical.as_bytes());
4109 assert_eq!(
4110 ReceiptV1::parse(canonical.as_bytes())
4111 .unwrap()
4112 .canonical_bytes()
4113 .unwrap(),
4114 canonical.as_bytes()
4115 );
4116
4117 let canonical = String::from_utf8(build(Vec::new()).canonical_bytes().unwrap()).unwrap();
4118 for token in [
4119 "9007199254740992",
4120 "-9007199254740992",
4121 "9223372036854775807",
4122 "18446744073709551615",
4123 "18446744073709551616",
4124 "9007199254740992.0",
4125 "9.007199254740992e15",
4126 ] {
4127 let malicious = canonical.replacen('{', &format!("{{\"x:numeric\":{token},"), 1);
4128 let failure = ReceiptV1::parse(malicious.as_bytes()).unwrap_err();
4129 assert!(
4130 failure.message().contains("portable JSON range")
4131 || failure.message().contains("integral JSON numbers"),
4132 "{token}: {failure}"
4133 );
4134 }
4135
4136 let mut dsse = build(Vec::new()).into_value();
4137 let payload =
4138 String::from_utf8(canonical_receipt_bytes(&dsse["attestation"]["statement"]).unwrap())
4139 .unwrap();
4140 let payload = payload.replacen('{', "{\"x:numeric\":9.007199254740992e15,", 1);
4141 dsse["attestation"]["dsse_envelope"]["payload"] = json!(BASE64_STANDARD.encode(payload));
4142 let failure = ReceiptV1::parse(&serde_json::to_vec(&dsse).unwrap()).unwrap_err();
4143 assert_eq!(failure.path(), "$.attestation.dsse_envelope.payload");
4144 assert!(failure.message().contains("portable JSON range"));
4145 }
4146
4147 #[test]
4148 fn duplicate_object_names_are_rejected_at_every_boundary() {
4149 let receipt = build(Vec::new());
4150 let canonical = String::from_utf8(receipt.canonical_bytes().unwrap()).unwrap();
4151 let claim = serde_json::to_string(&receipt.as_value()["claim"]).unwrap();
4152 let needle = format!("\"claim\":{claim}");
4153 for duplicate in [
4154 format!("{needle},\"claim\":\"shadow\""),
4155 format!("{needle},\"cl\\u0061im\":\"shadow\""),
4156 ] {
4157 let malicious = canonical.replacen(&needle, &duplicate, 1);
4158 let failure = ReceiptV1::parse(malicious.as_bytes()).unwrap_err();
4159 assert!(failure.message().contains("duplicate object name"));
4160 }
4161
4162 let needle = "\"acceptance_scope\":\"hypothesis_only\"";
4163 let malicious = canonical.replacen(
4164 needle,
4165 &format!("{needle},\"acceptance_scope\":\"machine_verified\""),
4166 1,
4167 );
4168 assert!(
4169 ReceiptV1::parse(malicious.as_bytes())
4170 .unwrap_err()
4171 .message()
4172 .contains("duplicate object name")
4173 );
4174
4175 let mut extension = receipt.into_value();
4176 extension["x:test"] = json!({"name": "first"});
4177 refresh_bound_attestation(&mut extension);
4178 let canonical = String::from_utf8(canonical_receipt_bytes(&extension).unwrap()).unwrap();
4179 let malicious = canonical.replacen(
4180 "\"name\":\"first\"",
4181 "\"name\":\"first\",\"name\":\"second\"",
4182 1,
4183 );
4184 assert!(
4185 ReceiptV1::parse(malicious.as_bytes())
4186 .unwrap_err()
4187 .message()
4188 .contains("duplicate object name")
4189 );
4190
4191 let mut dsse = build(Vec::new()).into_value();
4192 let statement =
4193 String::from_utf8(canonical_receipt_bytes(&dsse["attestation"]["statement"]).unwrap())
4194 .unwrap();
4195 let duplicate_statement = statement.replacen(
4196 "\"_type\":",
4197 "\"_type\":\"https://in-toto.io/Statement/v1\",\"_type\":",
4198 1,
4199 );
4200 dsse["attestation"]["dsse_envelope"]["payload"] =
4201 json!(BASE64_STANDARD.encode(duplicate_statement.as_bytes()));
4202 let failure = ReceiptV1::parse(&serde_json::to_vec(&dsse).unwrap()).unwrap_err();
4203 assert!(failure.message().contains("duplicate object name"));
4204 }
4205
4206 #[test]
4207 fn schema_exact_view_rejects_types_enums_and_closed_contributor_extensions() {
4208 let cases: Vec<ReceiptMutation> = vec![
4209 (
4210 "conditions object",
4211 Box::new(|raw| raw["conditions"] = json!(7)),
4212 ),
4213 (
4214 "conditions item",
4215 Box::new(|raw| raw["conditions"] = json!([7])),
4216 ),
4217 (
4218 "numeric evidence ref",
4219 Box::new(|raw| raw["acceptance"]["evidenceRefs"] = json!([7])),
4220 ),
4221 (
4222 "contributor extension",
4223 Box::new(|raw| raw["contributors"][0]["weight"] = json!(1)),
4224 ),
4225 (
4226 "nullable claim id",
4227 Box::new(|raw| raw["claim_id"] = Value::Null),
4228 ),
4229 (
4230 "bad status enum",
4231 Box::new(|raw| raw["status"]["evidence_status"] = json!("green")),
4232 ),
4233 (
4234 "numeric signature ref",
4235 Box::new(|raw| raw["signature_identities"]["producer"]["signatureRef"] = json!(7)),
4236 ),
4237 (
4238 "known gaps object",
4239 Box::new(|raw| raw["distillation"]["known_gaps"] = json!({})),
4240 ),
4241 ];
4242 for (name, mutate) in cases {
4243 let mut raw = build(Vec::new()).into_value();
4244 mutate(&mut raw);
4245 let failure = ReceiptV1::from_trusted_value(raw).unwrap_err();
4246 assert!(
4247 failure.message().contains("frozen Receipt v1 schema"),
4248 "{name}: {failure}"
4249 );
4250 }
4251 }
4252
4253 #[test]
4254 fn every_trust_relevant_body_field_is_bound_by_one_root() {
4255 let mutators: Vec<ReceiptMutation> = vec![
4256 (
4257 "claim",
4258 Box::new(|raw| raw["claim"] = json!("changed claim")),
4259 ),
4260 ("type", Box::new(|raw| raw["type"] = json!("empirical"))),
4261 (
4262 "artifacts",
4263 Box::new(|raw| raw["artifacts"][0]["x:changed"] = json!(true)),
4264 ),
4265 (
4266 "verifier_runs",
4267 Box::new(|raw| raw["verifier_runs"][0]["method"] = json!("changed.check")),
4268 ),
4269 (
4270 "machine",
4271 Box::new(|raw| raw["machine"]["x:changed"] = json!(true)),
4272 ),
4273 (
4274 "acceptance",
4275 Box::new(|raw| raw["acceptance"]["x:changed"] = json!(true)),
4276 ),
4277 (
4278 "distillation",
4279 Box::new(|raw| raw["distillation"]["x:changed"] = json!(true)),
4280 ),
4281 (
4282 "lineage",
4283 Box::new(|raw| raw["lineage"]["x:changed"] = json!(true)),
4284 ),
4285 (
4286 "provenance",
4287 Box::new(|raw| raw["provenance"]["x:changed"] = json!(true)),
4288 ),
4289 (
4290 "contributors",
4291 Box::new(|raw| raw["contributors"][0]["id"] = json!("agent:changed")),
4292 ),
4293 (
4294 "signature identities",
4295 Box::new(|raw| raw["signature_identities"]["x:changed"] = json!(true)),
4296 ),
4297 (
4298 "environment",
4299 Box::new(|raw| raw["environment"]["x:changed"] = json!(true)),
4300 ),
4301 (
4302 "status",
4303 Box::new(|raw| raw["status"]["x:changed"] = json!(true)),
4304 ),
4305 ];
4306 for (name, mutate) in mutators {
4307 let mut raw = build(vec![reported_pass()]).into_value();
4308 mutate(&mut raw);
4309 let failure = ReceiptV1::from_trusted_value(raw).unwrap_err();
4310 assert!(
4311 failure
4312 .message()
4313 .contains("canonical receipt-body projection"),
4314 "{name}: {failure}"
4315 );
4316 }
4317 }
4318
4319 #[test]
4320 fn recomputed_body_digest_cannot_hide_divergent_duplicated_layers() {
4321 let mut raw = build(Vec::new()).into_value();
4322 raw["machine"]["x:changed"] = json!(true);
4323 let body_root = receipt_body_sha256(object(&raw, "$").unwrap()).unwrap();
4324 raw["attestation"]["statement"]["predicate"][RECEIPT_BODY_BINDING_FIELD]["sha256"] =
4325 json!(body_root);
4326 refresh_payload_only(&mut raw);
4327 let failure = ReceiptV1::from_trusted_value(raw).unwrap_err();
4328 assert_eq!(failure.path(), "$.attestation.statement.predicate.machine");
4329 }
4330
4331 #[test]
4332 fn statement_only_receipts_are_rejected() {
4333 let mut raw = build(Vec::new()).into_value();
4334 raw["attestation"]["statement"]["predicate"]
4335 .as_object_mut()
4336 .unwrap()
4337 .remove(RECEIPT_BODY_BINDING_FIELD);
4338 refresh_payload_only(&mut raw);
4339 let failure = ReceiptV1::parse(&serde_json::to_vec(&raw).unwrap()).unwrap_err();
4340 assert_eq!(
4341 failure.path(),
4342 "$.attestation.statement.predicate.vela:receipt_body"
4343 );
4344 }
4345
4346 #[test]
4347 fn parser_enforces_every_documented_limit() {
4348 let base = ReceiptLimits {
4349 bytes: 4_096,
4350 depth: 8,
4351 string_bytes: 128,
4352 artifacts: 4,
4353 locator_bytes: 64,
4354 object_fields: 16,
4355 array_elements: 16,
4356 nodes: 32,
4357 dsse_bytes: 1_024,
4358 };
4359 let mut limits = base;
4360 limits.bytes = 2;
4361 assert!(
4362 ReceiptV1::parse_with_limits(br#"{ }"#, limits)
4363 .unwrap_err()
4364 .message()
4365 .contains("encoded JSON")
4366 );
4367 let mut limits = base;
4368 limits.depth = 2;
4369 assert!(
4370 ReceiptV1::parse_with_limits(br#"{"x":{"a":{"b":1}}}"#, limits)
4371 .unwrap_err()
4372 .message()
4373 .contains("JSON depth")
4374 );
4375 let mut limits = base;
4376 limits.string_bytes = 4;
4377 assert!(
4378 ReceiptV1::parse_with_limits(br#"{"x":"12345"}"#, limits)
4379 .unwrap_err()
4380 .message()
4381 .contains("string is")
4382 );
4383 let mut limits = base;
4384 limits.artifacts = 1;
4385 assert!(
4386 ReceiptV1::parse_with_limits(br#"{"artifacts":[{},{}]}"#, limits)
4387 .unwrap_err()
4388 .message()
4389 .contains("descriptors")
4390 );
4391 let mut limits = base;
4392 limits.locator_bytes = 4;
4393 assert!(
4394 ReceiptV1::parse_with_limits(br#"{"x:artifactURL":"12345"}"#, limits)
4395 .unwrap_err()
4396 .message()
4397 .contains("locator is")
4398 );
4399 let mut limits = base;
4400 limits.object_fields = 2;
4401 assert!(
4402 ReceiptV1::parse_with_limits(br#"{"x":{"a":1,"b":2}}"#, limits)
4403 .unwrap_err()
4404 .message()
4405 .contains("object-field budget")
4406 );
4407 let mut limits = base;
4408 limits.array_elements = 1;
4409 assert!(
4410 ReceiptV1::parse_with_limits(br#"[1,2]"#, limits)
4411 .unwrap_err()
4412 .message()
4413 .contains("array-element budget")
4414 );
4415 let mut limits = base;
4416 limits.nodes = 2;
4417 assert!(
4418 ReceiptV1::parse_with_limits(br#"{"x":[1,2]}"#, limits)
4419 .unwrap_err()
4420 .message()
4421 .contains("JSON node budget")
4422 );
4423
4424 let receipt = build(Vec::new());
4425 let mut limits = LIMITS;
4426 limits.dsse_bytes = 8;
4427 assert!(
4428 ReceiptV1::parse_with_limits(&receipt.canonical_bytes().unwrap(), limits)
4429 .unwrap_err()
4430 .message()
4431 .contains("decoded DSSE")
4432 );
4433 }
4434
4435 #[test]
4436 fn default_parser_rejects_depth_65_and_one_hundred_thousand_artifacts() {
4437 let depth_65 = format!("{}0{}", "[".repeat(65), "]".repeat(65));
4438 let failure = ReceiptV1::parse(depth_65.as_bytes()).unwrap_err();
4439 assert!(failure.message().contains("JSON depth"), "{failure}");
4440
4441 let mut artifacts = String::with_capacity(300_032);
4446 artifacts.push_str("{\"artifacts\":[");
4447 for index in 0..100_000 {
4448 if index > 0 {
4449 artifacts.push(',');
4450 }
4451 artifacts.push_str("{}");
4452 }
4453 artifacts.push_str("]}");
4454 let failure = ReceiptV1::parse(artifacts.as_bytes()).unwrap_err();
4455 assert!(
4456 failure.message().contains("array-element budget")
4457 || failure.message().contains("JSON node budget")
4458 || failure.message().contains("descriptors"),
4459 "{failure}"
4460 );
4461 }
4462
4463 #[test]
4464 fn malformed_dsse_payload_is_rejected_semantically() {
4465 let mut raw = build(Vec::new()).into_value();
4466 raw["attestation"]["dsse_envelope"]["payload"] = json!("e30=");
4467 assert!(
4468 ReceiptV1::from_trusted_value(raw)
4469 .unwrap_err()
4470 .message()
4471 .contains("does not encode")
4472 );
4473 }
4474
4475 #[test]
4476 fn acceptance_scope_round_trips_every_variant() {
4477 for value in AcceptanceScope::ALL {
4478 assert_eq!(AcceptanceScope::parse(value.as_str()), Some(value));
4479 assert_eq!(serde_json::to_value(value).unwrap(), json!(value.as_str()));
4480 }
4481 assert_eq!(AcceptanceScope::parse("verified"), None);
4482 }
4483
4484 #[test]
4485 fn acceptance_scope_matches_shipped_schema() {
4486 let values: Vec<String> = schema()["$defs"]["acceptance_scope"]["enum"]
4487 .as_array()
4488 .unwrap()
4489 .iter()
4490 .map(|item| item.as_str().unwrap().to_string())
4491 .collect();
4492 assert_eq!(
4493 AcceptanceScope::ALL
4494 .iter()
4495 .map(|item| item.as_str().to_string())
4496 .collect::<Vec<_>>(),
4497 values
4498 );
4499 }
4500
4501 #[test]
4502 fn typed_read_views_remain_parse_only() {
4503 let receipt = json!({
4504 "lineage": {
4505 "parents": ["vrc_aaa"],
4506 "derived_from": ["arxiv:2406.00001"],
4507 "source_refs": ["https://example.org/run/1"],
4508 "producer_run_id": "run-17",
4509 "unknown_extra": {"kept": "loose"}
4510 },
4511 "acceptance": {"acceptance_scope": "machine_verified"},
4512 "environment": {"independence_basis": {
4513 "method_family": "sat",
4514 "known_couplings": ["model:test"]
4515 }}
4516 });
4517 let lineage = lineage_from_receipt(&receipt).unwrap();
4518 assert_eq!(lineage.parents, vec!["vrc_aaa"]);
4519 assert_eq!(lineage.producer_run_id.as_deref(), Some("run-17"));
4520 assert_eq!(
4521 acceptance_scope_from_receipt(&receipt),
4522 Some(AcceptanceScope::MachineVerified)
4523 );
4524 assert_eq!(
4525 independence_basis_from_environment(&receipt["environment"])
4526 .unwrap()
4527 .known_couplings,
4528 vec!["model:test"]
4529 );
4530 assert_eq!(lineage_from_receipt(&json!({})), None);
4531 }
4532}