Skip to main content

qualia_core_db/container_10d/
manifold_identity_container.rs

1//! Caller-buffered integration between the `.10d` v2 identity manifest and section envelope.
2//!
3//! In this envelope binding, `TypedFieldRecord::payload_section_id` is the stable
4//! `SectionType` discriminant. This keeps references portable across deterministic section
5//! reordering. Ranges are checked against the referenced payload's byte length on read.
6
7use super::header::Container10dHeader;
8use super::manifold_identity_v2::{
9    decode_manifold_identity_v2, encode_manifold_identity_v2_with_extensions, ManifestV2Error,
10    ManifoldIdentityV2, TypedFieldRecord,
11};
12use super::section::{
13    encode_container, parse_section_table, AlignmentTier, SectionDescriptor, SectionInput,
14    SectionTableError, SectionType,
15};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum ManifoldContainerError {
19    Manifest(ManifestV2Error),
20    Sections(SectionTableError),
21    MissingIdentityManifest,
22    HeaderMismatch,
23    ScratchCapacity {
24        needed: usize,
25        capacity: usize,
26    },
27    UnknownPayloadSection {
28        field_index: usize,
29        section_id: u32,
30    },
31    PayloadRangeOutOfBounds {
32        field_index: usize,
33        end: u64,
34        length: u32,
35    },
36}
37
38impl From<ManifestV2Error> for ManifoldContainerError {
39    fn from(value: ManifestV2Error) -> Self {
40        Self::Manifest(value)
41    }
42}
43
44impl From<SectionTableError> for ManifoldContainerError {
45    fn from(value: SectionTableError) -> Self {
46        Self::Sections(value)
47    }
48}
49
50/// Encode a full `.10d` v2 section envelope containing the identity manifest.
51///
52/// `manifest_scratch` and `section_scratch` are caller-owned bounded workspace. Every non-manifest
53/// section is copied by reference into the temporary section table; the generic envelope writer
54/// handles canonical ordering, alignment, CRCs, and final output capacity before returning.
55pub fn encode_container_with_manifold_identity<'a>(
56    header: &Container10dHeader,
57    other_sections: &[SectionInput<'a>],
58    identity: &ManifoldIdentityV2,
59    fields: &[TypedFieldRecord],
60    manifest_scratch: &'a mut [u8],
61    section_scratch: &mut [SectionInput<'a>],
62    out: &mut [u8],
63) -> Result<usize, ManifoldContainerError> {
64    encode_container_with_manifold_identity_extensions(
65        header,
66        other_sections,
67        identity,
68        fields,
69        &[],
70        manifest_scratch,
71        section_scratch,
72        out,
73    )
74}
75
76/// Encode the manifest with explicitly registered extension kinds.
77pub fn encode_container_with_manifold_identity_extensions<'a>(
78    header: &Container10dHeader,
79    other_sections: &[SectionInput<'a>],
80    identity: &ManifoldIdentityV2,
81    fields: &[TypedFieldRecord],
82    supported_extension_kinds: &[u16],
83    manifest_scratch: &'a mut [u8],
84    section_scratch: &mut [SectionInput<'a>],
85    out: &mut [u8],
86) -> Result<usize, ManifoldContainerError> {
87    if other_sections
88        .iter()
89        .any(|section| section.section_type == SectionType::ManifoldIdentityV2)
90    {
91        return Err(ManifoldContainerError::Sections(
92            SectionTableError::DuplicateSectionType {
93                section_type: SectionType::ManifoldIdentityV2 as u8,
94            },
95        ));
96    }
97    let needed_sections =
98        other_sections
99            .len()
100            .checked_add(1)
101            .ok_or(ManifoldContainerError::ScratchCapacity {
102                needed: usize::MAX,
103                capacity: section_scratch.len(),
104            })?;
105    if section_scratch.len() < needed_sections {
106        return Err(ManifoldContainerError::ScratchCapacity {
107            needed: needed_sections,
108            capacity: section_scratch.len(),
109        });
110    }
111    let manifest_len = encode_manifold_identity_v2_with_extensions(
112        identity,
113        fields,
114        supported_extension_kinds,
115        manifest_scratch,
116    )?;
117    validate_input_ranges(fields, other_sections)?;
118    section_scratch[..other_sections.len()].copy_from_slice(other_sections);
119    section_scratch[other_sections.len()] = SectionInput {
120        section_type: SectionType::ManifoldIdentityV2,
121        alignment_tier: AlignmentTier::Page,
122        stride: 0,
123        element_count: 0,
124        payload: &manifest_scratch[..manifest_len],
125    };
126    Ok(encode_container(
127        header,
128        &section_scratch[..needed_sections],
129        out,
130    )?)
131}
132
133/// Read the manifest and validate every typed payload reference before publishing decoded fields.
134///
135/// The function uses `field_scratch` for transactional decode: on any malformed section, unknown
136/// target, range error, or insufficient output capacity, `out_fields` remains unchanged.
137pub fn decode_container_manifold_identity(
138    data: &[u8],
139    header: &Container10dHeader,
140    supported_extension_kinds: &[u16],
141    field_scratch: &mut [TypedFieldRecord],
142    out_fields: &mut [TypedFieldRecord],
143) -> Result<(ManifoldIdentityV2, usize), ManifoldContainerError> {
144    let parsed_header =
145        Container10dHeader::parse(data).map_err(|_| ManifoldContainerError::HeaderMismatch)?;
146    if &parsed_header != header {
147        return Err(ManifoldContainerError::HeaderMismatch);
148    }
149    let descriptors = parse_section_table(data, &parsed_header)?;
150    let descriptor = descriptors
151        .iter()
152        .find(|item| item.typ() == Some(SectionType::ManifoldIdentityV2))
153        .ok_or(ManifoldContainerError::MissingIdentityManifest)?;
154    let offset = descriptor.byte_offset as usize;
155    let end = offset
156        .checked_add(descriptor.byte_length as usize)
157        .ok_or(ManifoldContainerError::MissingIdentityManifest)?;
158    let manifest = data
159        .get(offset..end)
160        .ok_or(ManifoldContainerError::MissingIdentityManifest)?;
161    let (identity, field_count) =
162        decode_manifold_identity_v2(manifest, supported_extension_kinds, field_scratch)?;
163    if out_fields.len() < field_count {
164        return Err(ManifoldContainerError::ScratchCapacity {
165            needed: field_count,
166            capacity: out_fields.len(),
167        });
168    }
169    validate_payload_ranges(&field_scratch[..field_count], descriptors)?;
170    out_fields[..field_count].copy_from_slice(&field_scratch[..field_count]);
171    Ok((identity, field_count))
172}
173
174fn validate_payload_ranges(
175    fields: &[TypedFieldRecord],
176    sections: &[SectionDescriptor],
177) -> Result<(), ManifoldContainerError> {
178    for (field_index, field) in fields.iter().enumerate() {
179        if field.payload_section_id == 0 {
180            continue;
181        }
182        let section_type = u8::try_from(field.payload_section_id).ok();
183        let section = section_type
184            .and_then(SectionType::from_u8)
185            .and_then(|kind| {
186                (kind != SectionType::ManifoldIdentityV2)
187                    .then(|| sections.iter().find(|item| item.typ() == Some(kind)))
188                    .flatten()
189            })
190            .ok_or(ManifoldContainerError::UnknownPayloadSection {
191                field_index,
192                section_id: field.payload_section_id,
193            })?;
194        let range_end = field
195            .payload_offset
196            .checked_add(field.payload_length)
197            .ok_or(ManifoldContainerError::PayloadRangeOutOfBounds {
198                field_index,
199                end: u64::MAX,
200                length: section.byte_length,
201            })?;
202        if range_end > u64::from(section.byte_length) {
203            return Err(ManifoldContainerError::PayloadRangeOutOfBounds {
204                field_index,
205                end: range_end,
206                length: section.byte_length,
207            });
208        }
209    }
210    Ok(())
211}
212
213fn validate_input_ranges(
214    fields: &[TypedFieldRecord],
215    sections: &[SectionInput<'_>],
216) -> Result<(), ManifoldContainerError> {
217    for (field_index, field) in fields.iter().enumerate() {
218        if field.payload_section_id == 0 {
219            continue;
220        }
221        let section_type = u8::try_from(field.payload_section_id).ok();
222        let section = section_type
223            .and_then(SectionType::from_u8)
224            .and_then(|kind| sections.iter().find(|item| item.section_type == kind))
225            .ok_or(ManifoldContainerError::UnknownPayloadSection {
226                field_index,
227                section_id: field.payload_section_id,
228            })?;
229        let range_end = field
230            .payload_offset
231            .checked_add(field.payload_length)
232            .ok_or(ManifoldContainerError::PayloadRangeOutOfBounds {
233                field_index,
234                end: u64::MAX,
235                length: u32::try_from(section.payload.len()).unwrap_or(u32::MAX),
236            })?;
237        if range_end > section.payload.len() as u64 {
238            return Err(ManifoldContainerError::PayloadRangeOutOfBounds {
239                field_index,
240                end: range_end,
241                length: u32::try_from(section.payload.len()).unwrap_or(u32::MAX),
242            });
243        }
244    }
245    Ok(())
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use crate::container_10d::{IntegrityIndexDigest, StableEntityId};
252
253    fn identity() -> ManifoldIdentityV2 {
254        ManifoldIdentityV2 {
255            entity_id: StableEntityId([7; 16]),
256            profile_id: 1,
257            domain_id: 2,
258            coordinate_convention_id: 3,
259            coordinates: [0.0; 10],
260            external_digest: Some(IntegrityIndexDigest([9; 16])),
261        }
262    }
263
264    #[test]
265    fn envelope_round_trip_validates_stable_section_references() {
266        let payload = [1u8, 2, 3, 4];
267        let other = [SectionInput {
268            section_type: SectionType::FieldSidecar,
269            alignment_tier: AlignmentTier::Word,
270            stride: 0,
271            element_count: 0,
272            payload: &payload,
273        }];
274        let fields = [TypedFieldRecord {
275            field_id: 1,
276            kind: super::super::manifold_identity_v2::FIELD_KIND_ELECTROMAGNETIC,
277            flags: 0,
278            unit_id: 10,
279            payload_section_id: SectionType::FieldSidecar as u32,
280            payload_offset: 1,
281            payload_length: 3,
282        }];
283        let header = Container10dHeader::proposed();
284        let mut manifest =
285            [0u8; super::super::manifold_identity_v2::MANIFOLD_IDENTITY_V2_MAX_BYTES];
286        let mut section_scratch = [other[0]; 2];
287        let mut bytes = [0u8; 8192];
288        let used = encode_container_with_manifold_identity(
289            &header,
290            &other,
291            &identity(),
292            &fields,
293            &mut manifest,
294            &mut section_scratch,
295            &mut bytes,
296        )
297        .unwrap();
298        let parsed_header = Container10dHeader::parse(&bytes[..used]).unwrap();
299        let mut field_scratch = [TypedFieldRecord::default(); 1];
300        let mut out_fields = [TypedFieldRecord::default(); 1];
301        let (decoded, count) = decode_container_manifold_identity(
302            &bytes[..used],
303            &parsed_header,
304            &[],
305            &mut field_scratch,
306            &mut out_fields,
307        )
308        .unwrap();
309        assert_eq!(decoded, identity());
310        assert_eq!(count, 1);
311        assert_eq!(out_fields[0], fields[0]);
312
313        assert_eq!(
314            decode_container_manifold_identity(
315                &bytes[..used],
316                &Container10dHeader::legacy_v1(),
317                &[],
318                &mut field_scratch,
319                &mut out_fields,
320            ),
321            Err(ManifoldContainerError::HeaderMismatch)
322        );
323    }
324
325    #[test]
326    fn invalid_payload_range_is_rejected_before_envelope_write() {
327        let payload = [1u8, 2, 3, 4];
328        let other = [SectionInput {
329            section_type: SectionType::FieldSidecar,
330            alignment_tier: AlignmentTier::Word,
331            stride: 0,
332            element_count: 0,
333            payload: &payload,
334        }];
335        let fields = [TypedFieldRecord {
336            field_id: 1,
337            kind: super::super::manifold_identity_v2::FIELD_KIND_ELECTROMAGNETIC,
338            flags: 0,
339            unit_id: 10,
340            payload_section_id: SectionType::FieldSidecar as u32,
341            payload_offset: 3,
342            payload_length: 2,
343        }];
344        let header = Container10dHeader::proposed();
345        let mut manifest =
346            [0u8; super::super::manifold_identity_v2::MANIFOLD_IDENTITY_V2_MAX_BYTES];
347        let mut section_scratch = [other[0]; 2];
348        let mut bytes = [0xa5u8; 8192];
349        assert!(matches!(
350            encode_container_with_manifold_identity(
351                &header,
352                &other,
353                &identity(),
354                &fields,
355                &mut manifest,
356                &mut section_scratch,
357                &mut bytes,
358            ),
359            Err(ManifoldContainerError::PayloadRangeOutOfBounds { .. })
360        ));
361        assert!(bytes.iter().all(|byte| *byte == 0xa5));
362    }
363}