Skip to main content

qualia_core_db/sensing/local_custody/
mod.rs

1//! Cold, caller-budgeted local custody bundle publication and reading.
2//!
3//! The host must enforce locality, directory ownership, exclusive chain
4//! coordination, current authorization and aggregate quotas. Atomic publication
5//! is one non-replacing bundle link, not a transactional chain-head update. A successful
6//! link does not prove directory durability or prevent rollback. Mounts, mapped
7//! drives, reparse points and filesystem behavior require platform qualification.
8//! Reads reject final-component links/reparse points on Unix and Windows; this
9//! does not guard root ancestors or establish that a volume is local. Unix
10//! nonblocking open avoids FIFO hangs but cannot prevent device-node effects.
11
12pub mod chain;
13pub mod local_head;
14pub mod local_head_adapter;
15pub mod local_recovery;
16mod open_checked;
17pub(crate) use open_checked::open_regular_exclusive;
18mod publish;
19pub mod quota;
20mod read;
21pub mod recovery;
22
23pub use publish::{publish_bundle, PublishedBundle};
24pub use read::{read_bundle, ReadBundle};
25
26use super::sidecar_attestation::{
27    SidecarReceipt, SidecarReceiptAuthority, SidecarReceiptError, SIDECAR_BYTES,
28    SIDECAR_RECEIPT_BYTES,
29};
30use std::path::Path;
31
32const HEADER_BYTES: usize = 16;
33const FIXED_BYTES: usize = HEADER_BYTES + SIDECAR_BYTES + SIDECAR_RECEIPT_BYTES;
34const MAGIC: &[u8; 4] = b"QCB1";
35
36/// Host checks are trust boundaries, not OS-enforced locality or locks. The
37/// caller must hold an exclusive chain lease across the complete operation.
38pub trait CustodyAuthority: SidecarReceiptAuthority {
39    /// Admit the root and budget, enforce locality, directory ownership and
40    /// restrictive traversal/read ACLs (including Windows file inheritance),
41    /// and verify the exclusive chain lease and current Store policy.
42    fn permit_publish(
43        &mut self,
44        root: &Path,
45        receipt: &SidecarReceipt,
46        sidecar: &[u8; SIDECAR_BYTES],
47        payload: &[u8],
48        total_bytes: usize,
49    ) -> bool;
50
51    /// Admit reading this exact checkpoint under current policy before any I/O.
52    fn permit_read(&mut self, root: &Path, checkpoint: &[u8; 32], max_bytes: usize) -> bool;
53}
54
55#[derive(Debug)]
56pub enum CustodyError {
57    InvalidRoot,
58    InvalidBudget,
59    TooLarge,
60    PermissionDenied,
61    InvalidEncoding,
62    CheckpointMismatch,
63    Receipt(SidecarReceiptError),
64    Io(std::io::Error),
65}
66
67impl From<std::io::Error> for CustodyError {
68    fn from(error: std::io::Error) -> Self {
69        Self::Io(error)
70    }
71}
72
73fn entry_size(payload_len: usize, budget: usize) -> Result<usize, CustodyError> {
74    if budget < FIXED_BYTES {
75        return Err(CustodyError::InvalidBudget);
76    }
77    let total = FIXED_BYTES
78        .checked_add(payload_len)
79        .ok_or(CustodyError::TooLarge)?;
80    if total > budget {
81        return Err(CustodyError::TooLarge);
82    }
83    Ok(total)
84}
85
86pub(crate) fn validate_root(root: &Path) -> Result<(), CustodyError> {
87    if !root.is_absolute() || root.as_os_str().len() > 4096 {
88        return Err(CustodyError::InvalidRoot);
89    }
90    if root
91        .components()
92        .any(|part| matches!(part, std::path::Component::ParentDir))
93    {
94        return Err(CustodyError::InvalidRoot);
95    }
96    #[cfg(windows)]
97    {
98        use std::path::{Component, Prefix};
99        if !matches!(root.components().next(),
100            Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)))
101        {
102            return Err(CustodyError::InvalidRoot);
103        }
104    }
105    Ok(())
106}
107
108fn filename(checkpoint: &[u8; 32]) -> [u8; 68] {
109    const HEX: &[u8; 16] = b"0123456789abcdef";
110    let mut name = [0; 68];
111    for (i, value) in checkpoint.iter().enumerate() {
112        name[2 * i] = HEX[(value >> 4) as usize];
113        name[2 * i + 1] = HEX[(value & 15) as usize];
114    }
115    name[64..].copy_from_slice(b".qcb");
116    name
117}
118
119#[cfg(test)]
120mod tests;