Skip to main content

qualia_core_db/container_10d/
provenance_section.rs

1//! `.10d` ProvenanceSidecar section (P1) — the provenance half of an asset,
2//! bundled **physically inside the container** so context is byte-inseparable
3//! from the data it attests.
4//!
5//! The hypermedia library records provenance *semantically* (an asset's
6//! `prov:wasDerivedFrom` / `hasProvenance` edges — see [`crate::hypermedia`]).
7//! That is queryable, but the source bytes / licence / verifiable-credential
8//! live *outside* the sealed `.10d`, so a `.10d` copied on its own loses them.
9//! This section carries them **in-envelope**: the immutable source bytes the
10//! asset was derived from, its media type, its **licence** (the never-strip-
11//! context field), and an optional **verifiable credential** attesting the
12//! chain — all under the `.10d`'s own section-table CRC-32C.
13//!
14//! **Validate-before-use.** [`validate_provenance`] is the gate a consumer runs
15//! before trusting the asset as citable: the carried source bytes must hash to
16//! the declared `source_digest` (self-authenticating — the bytes really are the
17//! attested source), and a licence must be present (context was not stripped).
18//! The renderer's governance path already keys "citable" off the presence of a
19//! provenance section (`render/portal/mod.rs` sets `has_attestation`); this
20//! section makes that attestation real and checkable rather than merely
21//! reserved.
22//!
23//! **Layout:** a 32-byte [`ProvenanceMiniHeader`] (magic + version + flags +
24//! `source_digest` + field lengths) followed by the concatenated fields —
25//! `[source_bytes][source_media_type utf8][licence utf8][vc bytes]`. The
26//! mini-header is `repr(C)`, naturally aligned, no implicit padding. Two
27//! encodes of the same sidecar are byte-identical; the section-table CRC-32C
28//! catches a flipped bit.
29
30use bytemuck::{bytes_of, pod_read_unaligned, Pod, Zeroable};
31
32use crate::container_10d::crc32c::crc32c;
33
34/// Section payload mini-header size in bytes.
35pub const PROVENANCE_MINI_HEADER_SIZE: usize = 80;
36
37/// Magic tag at the head of a provenance-section payload (`b"PRV1"`, LE).
38pub const PROVENANCE_MAGIC: u32 = u32::from_le_bytes(*b"PRV1");
39
40/// Provenance-section payload version.
41pub const PROVENANCE_SECTION_VERSION: u16 = 2;
42
43/// `flags` bit 0: a verifiable credential is present (`vc_len` must be > 0).
44pub const FLAG_HAS_VC: u16 = 0x0001;
45
46/// Upper bound per variable-length field — bounds a hostile/malformed file.
47/// 16 MiB comfortably holds a source document, its media-type label, a licence
48/// string, and a VC while staying well under the 42 MB Sentinel ceiling.
49pub const MAX_PROVENANCE_FIELD: usize = 16 * 1024 * 1024;
50
51/// The 80-byte ProvenanceSidecar-section mini-header. `repr(C)`, naturally
52/// aligned, no implicit padding.
53///
54/// ```text
55/// offset  size  field
56/// 0       4     magic:u32          (PROVENANCE_MAGIC)
57/// 4       2     version:u16        (PROVENANCE_SECTION_VERSION)
58/// 6       2     flags:u16          (bit 0 = a VC is present)
59/// 8       4     source_digest:u32  (CRC-32C over source_bytes — the gate anchor)
60/// 12      4     reserved_u32       (must be zero) - moves before u64 to align to 16
61/// 16      8     timestamp_epoch_s:u64 (Date of harvest/authoring)
62/// 24      32    version_hash:[u8; 32] (Cryptographic version control hash e.g., SHA256)
63/// 56      4     source_len:u32
64/// 60      4     media_len:u32      (source media-type utf8 length)
65/// 64      4     licence_len:u32
66/// 68      4     vc_len:u32
67/// 72      4     metadata_len:u32   (Schema.org / Dublin Core semantic JSON-LD length)
68/// 76      4     reserved_pad:u32   (padding for 80-byte alignment)
69/// ```
70#[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/// An owned provenance sidecar to bundle into a `.10d` — the source bytes an
89/// asset was derived from, their media type, the licence (required), and an
90/// optional verifiable credential.
91#[derive(Debug, Clone, PartialEq, Eq, Default)]
92pub struct ProvenanceSidecar {
93    /// The immutable original bytes the asset was derived from.
94    pub source_bytes: Vec<u8>,
95    /// The source's media type (e.g. `model/gltf-binary`, `text/markdown`).
96    pub source_media_type: String,
97    /// The licence the source is available under (e.g. `CC-BY-4.0`, `CC0`).
98    /// Required — a provenance record with no licence is a stripped context.
99    pub licence: String,
100    /// An optional verifiable credential (CBOR / JWT bytes) attesting the
101    /// derivation chain. Empty = none.
102    pub vc: Vec<u8>,
103    /// Schema.org / Dublin Core semantic CBOR-LD metadata payload.
104    pub semantic_metadata: Vec<u8>,
105    /// Creation or harvest timestamp (UNIX epoch seconds).
106    pub timestamp_epoch_s: u64,
107    /// Cryptographic version control hash (e.g., SHA256 of the git commit or asset).
108    pub version_hash: [u8; 32],
109}
110
111impl ProvenanceSidecar {
112    /// Create a sidecar recording the source payload, its media type, and
113    /// the licence it is available under (licence is required — a provenance
114    /// record with no licence is a stripped context).
115    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    /// Attach a verifiable credential (CBOR / JWT bytes) attesting the
132    /// derivation chain.
133    pub fn with_vc(mut self, vc: impl Into<Vec<u8>>) -> Self {
134        self.vc = vc.into();
135        self
136    }
137
138    /// Attach semantic CBOR-LD metadata, the creation/harvest timestamp
139    /// (epoch seconds), and a version-control hash (e.g. SHA256 of the
140    /// source commit or asset).
141    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    /// The CRC-32C digest of the source bytes — the value stored in the header
154    /// and re-checked by [`validate_provenance`].
155    #[inline]
156    pub fn source_digest(&self) -> u32 {
157        crc32c(&self.source_bytes)
158    }
159}
160
161/// Provenance-section read/write/validate error.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum ProvenanceSectionError {
164    /// The payload is too short for the mini-header.
165    PayloadTooShort { got: usize, need: usize },
166    /// The payload magic is not [`PROVENANCE_MAGIC`].
167    BadMagic { got: u32 },
168    /// The payload version is not [`PROVENANCE_SECTION_VERSION`].
169    UnsupportedVersion { got: u16 },
170    /// The mini-header `reserved_u32` is non-zero.
171    NonZeroReserved,
172    /// Unknown flags bit set (only bit 0 is defined in v1).
173    UnknownFlags { got: u16 },
174    /// A variable-length field exceeds [`MAX_PROVENANCE_FIELD`].
175    FieldTooLarge {
176        field: &'static str,
177        got: usize,
178        max: usize,
179    },
180    /// The payload is too short for the declared field lengths.
181    PayloadTruncated { expected: usize, got: usize },
182    /// The output buffer is too small.
183    OutputBufferTooSmall { needed: usize, have: usize },
184    /// The `FLAG_HAS_VC` bit and `vc_len` disagree.
185    VcFlagInconsistent { has_vc: bool, vc_len: u32 },
186    /// A field declared as utf8 (media type / licence) is not valid utf8.
187    NonUtf8 { field: &'static str },
188    /// Validate gate: the carried source bytes do not hash to the declared
189    /// `source_digest` — the sidecar's source is not authentic to its claim.
190    SourceDigestMismatch { expected: u32, got: u32 },
191    /// Validate gate: no licence is present (context was stripped).
192    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/// Encoded payload length in bytes for a sidecar (mini-header + fields).
239#[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
249/// Encode a provenance sidecar into a caller-supplied buffer. Returns the
250/// number of bytes written. Deterministic (two encodes are byte-identical).
251pub 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/// A zero-copy read view over a decoded provenance-section payload.
316#[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    /// The immutable source bytes the asset was derived from.
328    #[inline]
329    pub fn source_bytes(&self) -> &'a [u8] {
330        self.source_bytes
331    }
332    /// The source's media type.
333    #[inline]
334    pub fn source_media_type(&self) -> &'a str {
335        self.source_media_type
336    }
337    /// The licence the source is available under.
338    #[inline]
339    pub fn licence(&self) -> &'a str {
340        self.licence
341    }
342    /// The attached verifiable credential, if any.
343    #[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    /// Schema.org / Dublin Core semantic CBOR-LD metadata payload.
352    #[inline]
353    pub fn semantic_metadata(&self) -> &'a [u8] {
354        self.semantic_metadata
355    }
356    /// Harvest or creation timestamp.
357    #[inline]
358    pub fn timestamp_epoch_s(&self) -> u64 {
359        self.header.timestamp_epoch_s
360    }
361    /// Cryptographic version control hash.
362    #[inline]
363    pub fn version_hash(&self) -> &[u8; 32] {
364        &self.header.version_hash
365    }
366    /// The declared source digest (CRC-32C over the source bytes).
367    #[inline]
368    pub fn source_digest(&self) -> u32 {
369        self.header.source_digest
370    }
371}
372
373/// Parse the mini-header and slice the fields out of a provenance-section
374/// payload (zero-copy). Validates magic, version, reserved, flag consistency,
375/// field bounds, and utf8 — but does **not** run the trust gate; call
376/// [`validate_provenance`] before using the sidecar as an attestation.
377pub 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    // `pod_read_unaligned` (not `from_bytes`): a section payload — or a raw
387    // test buffer — is not guaranteed aligned to the header's 4-byte alignment,
388    // and `from_bytes` panics on misalignment. This copies the 32 header bytes
389    // into an aligned value.
390    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
472/// The **validate-before-use gate**: return `Ok` only if the sidecar can be
473/// trusted as the asset's provenance. Two independent checks:
474///
475/// 1. **Self-authenticating source** — the carried `source_bytes` hash to the
476///    declared `source_digest` (the bytes really are the attested source; a
477///    swapped source is rejected).
478/// 2. **Context present** — a non-empty licence (a provenance record with no
479///    licence is a stripped context, not an attestation).
480///
481/// A consumer runs this before treating an asset as citable/attested (mirroring
482/// the renderer's `has_attestation` governance gate).
483pub 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        // The gate passes for an authentic, licensed sidecar.
535        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        // Flip a byte in the source-bytes region (after the 32-byte header).
564        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        // A provenance sidecar bundled alongside a (stand-in) mesh section.
592        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                // type 7 — accepted by the encoder now that it is implemented.
607                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        // The provenance section is present and readable straight out of the .10d.
622        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        // zeroed header ⇒ magic 0 ⇒ BadMagic
641        assert!(matches!(
642            decode_provenance_section(&buf),
643            Err(ProvenanceSectionError::BadMagic { .. })
644        ));
645        // set a good magic but truncated declared source_len
646        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}