1use bytemuck::{bytes_of, pod_read_unaligned, Pod, Zeroable};
31
32use crate::container_10d::crc32c::crc32c;
33
34pub const PROVENANCE_MINI_HEADER_SIZE: usize = 80;
36
37pub const PROVENANCE_MAGIC: u32 = u32::from_le_bytes(*b"PRV1");
39
40pub const PROVENANCE_SECTION_VERSION: u16 = 2;
42
43pub const FLAG_HAS_VC: u16 = 0x0001;
45
46pub const MAX_PROVENANCE_FIELD: usize = 16 * 1024 * 1024;
50
51#[repr(C)]
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
72pub struct ProvenanceMiniHeader {
73 pub magic: u32,
74 pub version: u16,
75 pub flags: u16,
76 pub source_digest: u32,
77 pub reserved_u32: u32,
78 pub timestamp_epoch_s: u64,
79 pub version_hash: [u8; 32],
80 pub source_len: u32,
81 pub media_len: u32,
82 pub licence_len: u32,
83 pub vc_len: u32,
84 pub metadata_len: u32,
85 pub reserved_pad: u32,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Default)]
92pub struct ProvenanceSidecar {
93 pub source_bytes: Vec<u8>,
95 pub source_media_type: String,
97 pub licence: String,
100 pub vc: Vec<u8>,
103 pub semantic_metadata: Vec<u8>,
105 pub timestamp_epoch_s: u64,
107 pub version_hash: [u8; 32],
109}
110
111impl ProvenanceSidecar {
112 pub fn new(
116 source_bytes: impl Into<Vec<u8>>,
117 source_media_type: impl Into<String>,
118 licence: impl Into<String>,
119 ) -> Self {
120 Self {
121 source_bytes: source_bytes.into(),
122 source_media_type: source_media_type.into(),
123 licence: licence.into(),
124 vc: Vec::new(),
125 semantic_metadata: Vec::new(),
126 timestamp_epoch_s: 0,
127 version_hash: [0; 32],
128 }
129 }
130
131 pub fn with_vc(mut self, vc: impl Into<Vec<u8>>) -> Self {
134 self.vc = vc.into();
135 self
136 }
137
138 pub fn with_metadata(
142 mut self,
143 metadata: impl Into<Vec<u8>>,
144 timestamp: u64,
145 hash: [u8; 32],
146 ) -> Self {
147 self.semantic_metadata = metadata.into();
148 self.timestamp_epoch_s = timestamp;
149 self.version_hash = hash;
150 self
151 }
152
153 #[inline]
156 pub fn source_digest(&self) -> u32 {
157 crc32c(&self.source_bytes)
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum ProvenanceSectionError {
164 PayloadTooShort { got: usize, need: usize },
166 BadMagic { got: u32 },
168 UnsupportedVersion { got: u16 },
170 NonZeroReserved,
172 UnknownFlags { got: u16 },
174 FieldTooLarge {
176 field: &'static str,
177 got: usize,
178 max: usize,
179 },
180 PayloadTruncated { expected: usize, got: usize },
182 OutputBufferTooSmall { needed: usize, have: usize },
184 VcFlagInconsistent { has_vc: bool, vc_len: u32 },
186 NonUtf8 { field: &'static str },
188 SourceDigestMismatch { expected: u32, got: u32 },
191 MissingLicence,
193}
194
195impl std::fmt::Display for ProvenanceSectionError {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 match self {
198 Self::PayloadTooShort { got, need } => {
199 write!(f, "10d PRV payload too short: got {got}, need {need}")
200 }
201 Self::BadMagic { got } => write!(
202 f,
203 "10d PRV bad magic {got:#010x} (expected {PROVENANCE_MAGIC:#010x})"
204 ),
205 Self::UnsupportedVersion { got } => write!(f, "10d PRV unsupported version {got}"),
206 Self::NonZeroReserved => write!(f, "10d PRV non-zero reserved_u32"),
207 Self::UnknownFlags { got } => write!(
208 f,
209 "10d PRV unknown flags bits {got:#06x} (only bit 0 defined in v1)"
210 ),
211 Self::FieldTooLarge { field, got, max } => {
212 write!(f, "10d PRV field {field:?} too large: {got} > {max}")
213 }
214 Self::PayloadTruncated { expected, got } => write!(
215 f,
216 "10d PRV payload truncated: expected {expected}, got {got}"
217 ),
218 Self::OutputBufferTooSmall { needed, have } => write!(
219 f,
220 "10d PRV output buffer too small: need {needed}, have {have}"
221 ),
222 Self::VcFlagInconsistent { has_vc, vc_len } => write!(
223 f,
224 "10d PRV vc flag inconsistent: has_vc={has_vc}, vc_len={vc_len}"
225 ),
226 Self::NonUtf8 { field } => write!(f, "10d PRV field {field:?} is not valid utf8"),
227 Self::SourceDigestMismatch { expected, got } => write!(
228 f,
229 "10d PRV source-digest mismatch: expected {expected:#010x}, got {got:#010x}"
230 ),
231 Self::MissingLicence => write!(f, "10d PRV missing licence (context stripped)"),
232 }
233 }
234}
235
236impl std::error::Error for ProvenanceSectionError {}
237
238#[inline]
240pub fn encoded_len(s: &ProvenanceSidecar) -> usize {
241 PROVENANCE_MINI_HEADER_SIZE
242 + s.source_bytes.len()
243 + s.source_media_type.len()
244 + s.licence.len()
245 + s.vc.len()
246 + s.semantic_metadata.len()
247}
248
249pub fn encode_provenance_section(
252 s: &ProvenanceSidecar,
253 out: &mut [u8],
254) -> Result<usize, ProvenanceSectionError> {
255 let check = |field, len: usize| -> Result<(), ProvenanceSectionError> {
256 if len > MAX_PROVENANCE_FIELD {
257 Err(ProvenanceSectionError::FieldTooLarge {
258 field,
259 got: len,
260 max: MAX_PROVENANCE_FIELD,
261 })
262 } else {
263 Ok(())
264 }
265 };
266 check("source", s.source_bytes.len())?;
267 check("media_type", s.source_media_type.len())?;
268 check("licence", s.licence.len())?;
269 check("vc", s.vc.len())?;
270 check("semantic_metadata", s.semantic_metadata.len())?;
271
272 let total = encoded_len(s);
273 if out.len() < total {
274 return Err(ProvenanceSectionError::OutputBufferTooSmall {
275 needed: total,
276 have: out.len(),
277 });
278 }
279
280 let flags = if s.vc.is_empty() { 0 } else { FLAG_HAS_VC };
281 let header = ProvenanceMiniHeader {
282 magic: PROVENANCE_MAGIC,
283 version: PROVENANCE_SECTION_VERSION,
284 flags,
285 source_digest: s.source_digest(),
286 reserved_u32: 0,
287 timestamp_epoch_s: s.timestamp_epoch_s,
288 version_hash: s.version_hash,
289 source_len: s.source_bytes.len() as u32,
290 media_len: s.source_media_type.len() as u32,
291 licence_len: s.licence.len() as u32,
292 vc_len: s.vc.len() as u32,
293 metadata_len: s.semantic_metadata.len() as u32,
294 reserved_pad: 0,
295 };
296
297 let mut cursor = 0;
298 out[cursor..cursor + PROVENANCE_MINI_HEADER_SIZE].copy_from_slice(bytes_of(&header));
299 cursor += PROVENANCE_MINI_HEADER_SIZE;
300 out[cursor..cursor + s.source_bytes.len()].copy_from_slice(&s.source_bytes);
301 cursor += s.source_bytes.len();
302 out[cursor..cursor + s.source_media_type.len()].copy_from_slice(s.source_media_type.as_bytes());
303 cursor += s.source_media_type.len();
304 out[cursor..cursor + s.licence.len()].copy_from_slice(s.licence.as_bytes());
305 cursor += s.licence.len();
306 out[cursor..cursor + s.vc.len()].copy_from_slice(&s.vc);
307 cursor += s.vc.len();
308 out[cursor..cursor + s.semantic_metadata.len()].copy_from_slice(&s.semantic_metadata);
309 cursor += s.semantic_metadata.len();
310
311 debug_assert_eq!(cursor, total);
312 Ok(total)
313}
314
315#[derive(Debug, Clone, Copy)]
317pub struct ProvenanceSidecarView<'a> {
318 header: ProvenanceMiniHeader,
319 source_bytes: &'a [u8],
320 source_media_type: &'a str,
321 licence: &'a str,
322 vc: &'a [u8],
323 semantic_metadata: &'a [u8],
324}
325
326impl<'a> ProvenanceSidecarView<'a> {
327 #[inline]
329 pub fn source_bytes(&self) -> &'a [u8] {
330 self.source_bytes
331 }
332 #[inline]
334 pub fn source_media_type(&self) -> &'a str {
335 self.source_media_type
336 }
337 #[inline]
339 pub fn licence(&self) -> &'a str {
340 self.licence
341 }
342 #[inline]
344 pub fn vc(&self) -> Option<&'a [u8]> {
345 if self.vc.is_empty() {
346 None
347 } else {
348 Some(self.vc)
349 }
350 }
351 #[inline]
353 pub fn semantic_metadata(&self) -> &'a [u8] {
354 self.semantic_metadata
355 }
356 #[inline]
358 pub fn timestamp_epoch_s(&self) -> u64 {
359 self.header.timestamp_epoch_s
360 }
361 #[inline]
363 pub fn version_hash(&self) -> &[u8; 32] {
364 &self.header.version_hash
365 }
366 #[inline]
368 pub fn source_digest(&self) -> u32 {
369 self.header.source_digest
370 }
371}
372
373pub fn decode_provenance_section(
378 payload: &[u8],
379) -> Result<ProvenanceSidecarView<'_>, ProvenanceSectionError> {
380 if payload.len() < PROVENANCE_MINI_HEADER_SIZE {
381 return Err(ProvenanceSectionError::PayloadTooShort {
382 got: payload.len(),
383 need: PROVENANCE_MINI_HEADER_SIZE,
384 });
385 }
386 let header: ProvenanceMiniHeader = pod_read_unaligned(&payload[..PROVENANCE_MINI_HEADER_SIZE]);
391 if header.magic != PROVENANCE_MAGIC {
392 return Err(ProvenanceSectionError::BadMagic { got: header.magic });
393 }
394 if header.version != PROVENANCE_SECTION_VERSION {
395 return Err(ProvenanceSectionError::UnsupportedVersion {
396 got: header.version,
397 });
398 }
399 if header.reserved_u32 != 0 {
400 return Err(ProvenanceSectionError::NonZeroReserved);
401 }
402 if header.flags & !FLAG_HAS_VC != 0 {
403 return Err(ProvenanceSectionError::UnknownFlags { got: header.flags });
404 }
405 let has_vc = header.flags & FLAG_HAS_VC != 0;
406 if has_vc != (header.vc_len > 0) {
407 return Err(ProvenanceSectionError::VcFlagInconsistent {
408 has_vc,
409 vc_len: header.vc_len,
410 });
411 }
412
413 let source_len = header.source_len as usize;
414 let media_len = header.media_len as usize;
415 let licence_len = header.licence_len as usize;
416 let vc_len = header.vc_len as usize;
417 let metadata_len = header.metadata_len as usize;
418 for (field, len) in [
419 ("source", source_len),
420 ("media_type", media_len),
421 ("licence", licence_len),
422 ("vc", vc_len),
423 ("semantic_metadata", metadata_len),
424 ] {
425 if len > MAX_PROVENANCE_FIELD {
426 return Err(ProvenanceSectionError::FieldTooLarge {
427 field,
428 got: len,
429 max: MAX_PROVENANCE_FIELD,
430 });
431 }
432 }
433
434 let expected =
435 PROVENANCE_MINI_HEADER_SIZE + source_len + media_len + licence_len + vc_len + metadata_len;
436 if payload.len() < expected {
437 return Err(ProvenanceSectionError::PayloadTruncated {
438 expected,
439 got: payload.len(),
440 });
441 }
442
443 let mut cursor = PROVENANCE_MINI_HEADER_SIZE;
444 let source_bytes = &payload[cursor..cursor + source_len];
445 cursor += source_len;
446 let media_raw = &payload[cursor..cursor + media_len];
447 cursor += media_len;
448 let licence_raw = &payload[cursor..cursor + licence_len];
449 cursor += licence_len;
450 let vc = &payload[cursor..cursor + vc_len];
451 cursor += vc_len;
452 let metadata_raw = &payload[cursor..cursor + metadata_len];
453
454 let source_media_type =
455 std::str::from_utf8(media_raw).map_err(|_| ProvenanceSectionError::NonUtf8 {
456 field: "media_type",
457 })?;
458 let licence = std::str::from_utf8(licence_raw)
459 .map_err(|_| ProvenanceSectionError::NonUtf8 { field: "licence" })?;
460 let semantic_metadata = metadata_raw;
461
462 Ok(ProvenanceSidecarView {
463 header,
464 source_bytes,
465 source_media_type,
466 licence,
467 vc,
468 semantic_metadata,
469 })
470}
471
472pub fn validate_provenance(view: &ProvenanceSidecarView<'_>) -> Result<(), ProvenanceSectionError> {
484 let got = crc32c(view.source_bytes);
485 if got != view.header.source_digest {
486 return Err(ProvenanceSectionError::SourceDigestMismatch {
487 expected: view.header.source_digest,
488 got,
489 });
490 }
491 if view.licence.trim().is_empty() {
492 return Err(ProvenanceSectionError::MissingLicence);
493 }
494 Ok(())
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 fn sample() -> ProvenanceSidecar {
502 ProvenanceSidecar::new(
503 b"<the original source GLB bytes>".to_vec(),
504 "model/gltf-binary",
505 "CC-BY-4.0",
506 )
507 .with_vc(b"{\"vc\":\"attested\"}".to_vec())
508 .with_metadata(
509 b"\xA2\x68@context\x78\x1Dhttps://schema.org/\x65@type\x67Dataset".to_vec(),
510 1690000000,
511 [0xAA; 32],
512 )
513 }
514
515 #[test]
516 fn round_trips_and_validates() {
517 let s = sample();
518 let mut buf = vec![0u8; encoded_len(&s)];
519 let n = encode_provenance_section(&s, &mut buf).unwrap();
520 assert_eq!(n, buf.len());
521
522 let view = decode_provenance_section(&buf).unwrap();
523 assert_eq!(view.source_bytes(), s.source_bytes.as_slice());
524 assert_eq!(view.source_media_type(), "model/gltf-binary");
525 assert_eq!(view.licence(), "CC-BY-4.0");
526 assert_eq!(view.vc(), Some(s.vc.as_slice()));
527 assert_eq!(
528 view.semantic_metadata(),
529 b"\xA2\x68@context\x78\x1Dhttps://schema.org/\x65@type\x67Dataset"
530 );
531 assert_eq!(view.timestamp_epoch_s(), 1690000000);
532 assert_eq!(view.version_hash(), &[0xAA; 32]);
533 assert_eq!(view.source_digest(), crc32c(&s.source_bytes));
534 validate_provenance(&view).unwrap();
536 }
537
538 #[test]
539 fn deterministic_encoding() {
540 let s = sample();
541 let mut a = vec![0u8; encoded_len(&s)];
542 let mut b = vec![0u8; encoded_len(&s)];
543 encode_provenance_section(&s, &mut a).unwrap();
544 encode_provenance_section(&s, &mut b).unwrap();
545 assert_eq!(a, b, "two encodes of the same sidecar are byte-identical");
546 }
547
548 #[test]
549 fn no_vc_clears_the_flag() {
550 let s = ProvenanceSidecar::new(b"src".to_vec(), "text/plain", "CC0");
551 let mut buf = vec![0u8; encoded_len(&s)];
552 encode_provenance_section(&s, &mut buf).unwrap();
553 let view = decode_provenance_section(&buf).unwrap();
554 assert_eq!(view.vc(), None);
555 validate_provenance(&view).unwrap();
556 }
557
558 #[test]
559 fn tampered_source_bytes_fail_the_gate() {
560 let s = sample();
561 let mut buf = vec![0u8; encoded_len(&s)];
562 encode_provenance_section(&s, &mut buf).unwrap();
563 buf[PROVENANCE_MINI_HEADER_SIZE] ^= 0xFF;
565 let view = decode_provenance_section(&buf).unwrap();
566 assert!(matches!(
567 validate_provenance(&view),
568 Err(ProvenanceSectionError::SourceDigestMismatch { .. })
569 ));
570 }
571
572 #[test]
573 fn a_stripped_licence_fails_the_gate() {
574 let s = ProvenanceSidecar::new(b"src".to_vec(), "text/plain", "");
575 let mut buf = vec![0u8; encoded_len(&s)];
576 encode_provenance_section(&s, &mut buf).unwrap();
577 let view = decode_provenance_section(&buf).unwrap();
578 assert_eq!(
579 validate_provenance(&view),
580 Err(ProvenanceSectionError::MissingLicence)
581 );
582 }
583
584 #[test]
585 fn round_trips_through_the_real_container_section_table() {
586 use crate::container_10d::header::Container10dHeader;
587 use crate::container_10d::section::{
588 encode_container, parse_section_table, AlignmentTier, SectionInput, SectionType,
589 };
590
591 let sidecar = sample();
593 let mut prov_payload = vec![0u8; encoded_len(&sidecar)];
594 encode_provenance_section(&sidecar, &mut prov_payload).unwrap();
595 let mesh_payload = [0xAAu8; 64];
596
597 let inputs = [
598 SectionInput {
599 section_type: SectionType::QuantizedMesh,
600 alignment_tier: AlignmentTier::Word,
601 stride: 0,
602 element_count: 0,
603 payload: &mesh_payload,
604 },
605 SectionInput {
606 section_type: SectionType::ProvenanceSidecar,
608 alignment_tier: AlignmentTier::Word,
609 stride: 0,
610 element_count: 0,
611 payload: &prov_payload,
612 },
613 ];
614
615 let h = Container10dHeader::proposed();
616 let mut out = vec![0u8; 4096];
617 let n = encode_container(&h, &inputs, &mut out).expect("encode container w/ provenance");
618 let parsed = Container10dHeader::parse(&out[..n]).expect("header parse");
619 let descs = parse_section_table(&out[..n], &parsed).expect("table parse (CRC-checked)");
620
621 let prov = descs
623 .iter()
624 .find(|d| d.section_type == SectionType::ProvenanceSidecar as u8)
625 .expect("provenance section in table");
626 let payload = &out[prov.byte_offset as usize..][..prov.byte_length as usize];
627 let view = decode_provenance_section(payload).expect("decode from container");
628 validate_provenance(&view).expect("validate-before-use passes for the bundled sidecar");
629 assert_eq!(view.licence(), "CC-BY-4.0");
630 assert_eq!(view.source_bytes(), sidecar.source_bytes.as_slice());
631 }
632
633 #[test]
634 fn bad_magic_and_short_payload_are_rejected() {
635 assert!(matches!(
636 decode_provenance_section(&[0u8; 8]),
637 Err(ProvenanceSectionError::PayloadTooShort { .. })
638 ));
639 let mut buf = [0u8; PROVENANCE_MINI_HEADER_SIZE];
640 assert!(matches!(
642 decode_provenance_section(&buf),
643 Err(ProvenanceSectionError::BadMagic { .. })
644 ));
645 let bad = ProvenanceMiniHeader {
647 magic: PROVENANCE_MAGIC,
648 version: PROVENANCE_SECTION_VERSION,
649 flags: 0,
650 source_digest: 0,
651 reserved_u32: 0,
652 timestamp_epoch_s: 0,
653 version_hash: [0; 32],
654 source_len: 100,
655 media_len: 0,
656 licence_len: 0,
657 vc_len: 0,
658 metadata_len: 0,
659 reserved_pad: 0,
660 };
661 buf.copy_from_slice(bytes_of(&bad));
662 assert!(matches!(
663 decode_provenance_section(&buf),
664 Err(ProvenanceSectionError::PayloadTruncated { .. })
665 ));
666 }
667}