Skip to main content

qualia_core_db/bundle/stream/protection/
source.rs

1//! Cold original-source admission; original bytes remain borrowed and unchanged.
2use super::{coverage, EntryRange, ProtectionError as Error, SourceObject};
3use crate::bundle::format::BUNDLE_HEADER_SIZE;
4use crate::bundle::stream::descriptor::MAX_ENTRIES;
5use crate::bundle::stream::index::{
6    admit_header, admit_index, AdmittedIndex, EntryScratch, ExtentLimit,
7};
8use crate::bundle::{BundleReadLimits, BundleReader};
9use crate::crypto::network::object_stream::{MAX_METADATA, MAX_OBJECT_BYTES};
10
11/// A private structural preparation, not an authenticated/encrypted publication.
12/// Deliberately no Debug: retained index bytes contain private names and metadata.
13pub struct PreparedSource<'a, 's> {
14    source: &'a [u8],
15    index: AdmittedIndex<'a>,
16    objects: &'s [SourceObject],
17    metadata_length: usize,
18}
19impl<'a, 's> PreparedSource<'a, 's> {
20    /// The host must retain immutable snapshot/writer exclusion for external or
21    /// mapped storage throughout this lifetime. Rust's slice borrow alone does
22    /// not exclude external writers. This does not generate IDs, keys or rights.
23    ///
24    /// All interval/order scratch is supplied by the caller and remains private.
25    /// Full BundleReader validation uses its existing bounded cold materialization,
26    /// then drops it before returning; this is not a zero-allocation hot API.
27    pub fn prepare(
28        source: &'a [u8],
29        limits: BundleReadLimits,
30        index_scratch: &mut [EntryScratch<'a>],
31        entries: &mut [EntryRange],
32        objects: &'s mut [SourceObject],
33        order: &mut [u32],
34    ) -> Result<Self, Error> {
35        let extent = u64::try_from(source.len()).map_err(|_| Error::Overflow)?;
36        if extent > MAX_OBJECT_BYTES || source.len() > limits.file_bytes {
37            return Err(Error::Limit);
38        }
39        let metadata_cap = usize::try_from(MAX_METADATA).map_err(|_| Error::Overflow)?;
40        let limits = BundleReadLimits {
41            entries: limits.entries.min(MAX_ENTRIES),
42            index_bytes: limits.index_bytes.min(metadata_cap),
43            decoded_index_bytes: limits.decoded_index_bytes.min(metadata_cap),
44            ..limits
45        };
46        let raw_header = source.get(..BUNDLE_HEADER_SIZE).ok_or(Error::Source)?;
47        let header = admit_header(
48            raw_header,
49            extent,
50            ExtentLimit {
51                max_logical_bytes: MAX_OBJECT_BYTES,
52            },
53            limits.into(),
54        )
55        .map_err(|_| Error::Source)?;
56        let count = usize::try_from(header.entry_count()).map_err(|_| Error::Overflow)?;
57        if index_scratch.len() < count {
58            return Err(Error::Capacity);
59        }
60        let start = usize::try_from(header.index_offset()).map_err(|_| Error::Overflow)?;
61        let raw_index = source.get(start..).ok_or(Error::Source)?;
62        let index = admit_index(&header, raw_index, limits.into(), index_scratch)
63            .map_err(|_| Error::Source)?;
64        let count = coverage::prepare(&index, entries, objects, order)?;
65        let metadata_length = coverage::metadata_length(count, header.index_length())?;
66        {
67            // Canonical full-format owner verifies whole CRC and every original
68            // SHA256 payload; no second QBDL/CBOR parser is introduced here.
69            let full =
70                BundleReader::parse_with_limits(source, limits).map_err(|_| Error::Source)?;
71            if full.entries().len() != index.sizing().entry_count() {
72                return Err(Error::Coverage);
73            }
74        }
75        Ok(Self {
76            source,
77            index,
78            objects: &objects[..count],
79            metadata_length,
80        })
81    }
82    pub(super) fn checked_header(&self) -> crate::bundle::stream::index::CheckedHeader {
83        self.index.header()
84    }
85    pub fn objects(&self) -> &[SourceObject] {
86        self.objects
87    }
88    pub fn entry_count(&self) -> usize {
89        self.index.sizing().entry_count()
90    }
91    pub const fn metadata_length(&self) -> usize {
92        self.metadata_length
93    }
94    pub fn header_bytes(&self) -> &'a [u8] {
95        &self.source[..BUNDLE_HEADER_SIZE]
96    }
97    pub fn index_bytes(&self) -> &'a [u8] {
98        self.index.encoded_bytes()
99    }
100    pub fn source_bytes(&self) -> &'a [u8] {
101        self.source
102    }
103    pub fn object_bytes(&self, ordinal: usize) -> Result<&'a [u8], Error> {
104        let row = self.objects.get(ordinal).ok_or(Error::Coverage)?;
105        let start = usize::try_from(row.offset()).map_err(|_| Error::Overflow)?;
106        let end = row
107            .offset()
108            .checked_add(row.length())
109            .ok_or(Error::Overflow)?;
110        let end = usize::try_from(end).map_err(|_| Error::Overflow)?;
111        self.source.get(start..end).ok_or(Error::Coverage)
112    }
113}