Skip to main content

qualia_core_db/sensing/local_custody/
local_head.rs

1//! Signed local chain heads under a held, cooperative OS file lock.
2//!
3//! The host must protect the root and lock file from replacement, establish
4//! that storage is local, and authenticate freshness/absence with independent
5//! anti-rollback state. Filesystem locks coordinate only cooperating writers.
6//! This module does not establish durable chain membership on its own.
7use super::super::sidecar_attestation::{SidecarReceipt, SidecarReceiptAuthority, SIDECAR_BYTES};
8use super::{
9    chain::{ChainHead, HeadCommit},
10    open_checked::open_regular,
11    validate_root,
12};
13use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
14use std::{
15    fs::{File, OpenOptions},
16    io::{Read, Write},
17    path::{Path, PathBuf},
18};
19
20const SIZE: usize = 176;
21const MAGIC: &[u8; 4] = b"QCH1";
22const DOMAIN: &[u8] = b"qualia:sensing:local-chain-head:v1\0";
23
24/// External policy establishes local root/ACL and rollback-resistant head state.
25/// The host must hold a policy lease across final checks and file replacement;
26/// callback results alone cannot make external revocation atomic with I/O.
27/// `Empty` means authenticated genesis absence, not an unavailable lookup.
28pub trait LocalHeadPolicy: SidecarReceiptAuthority {
29    fn permit_open(&mut self, root: &Path, chain: &[u8; 32]) -> bool;
30    fn admit_current(&mut self, root: &Path, chain: &[u8; 32], head: ChainHead) -> bool;
31    /// Check current Store policy and confirm the exact referenced bundle is
32    /// published and admissible. This module does not perform that lookup.
33    fn permit_commit(
34        &mut self,
35        root: &Path,
36        chain: &[u8; 32],
37        expected: ChainHead,
38        next: ChainHead,
39        receipt: &SidecarReceipt,
40        sidecar: &[u8; SIDECAR_BYTES],
41        payload: &[u8],
42    ) -> bool;
43}
44
45#[derive(Debug)]
46pub enum LocalHeadError {
47    InvalidRoot,
48    InvalidChain,
49    InvalidBudget,
50    PermissionDenied,
51    InvalidEncoding,
52    InvalidSigner,
53    InvalidSignature,
54    Receipt,
55    Conflict,
56    Io(std::io::Error),
57}
58impl From<std::io::Error> for LocalHeadError {
59    fn from(value: std::io::Error) -> Self {
60        Self::Io(value)
61    }
62}
63
64/// Holds an exclusive advisory lock. Root protection and lock-file identity
65/// must be enforced by the host for the entire lifetime of the lease.
66pub struct LocalHeadLease<'a> {
67    root: PathBuf,
68    chain: [u8; 32],
69    head_path: PathBuf,
70    _lock: File,
71    signer: &'a SigningKey,
72}
73
74impl<'a> LocalHeadLease<'a> {
75    /// Exact lexical scope of this lease; the host protects root identity for
76    /// the whole lease and must not assume this checks filesystem aliases.
77    pub fn matches_scope(&self, root: &Path, chain: &[u8; 32]) -> bool {
78        self.root == root && &self.chain == chain
79    }
80    /// `byte_budget` bounds the single temporary head record, not aggregate
81    /// directory usage or runtime/OS allocation. No implicit directories are
82    /// created; the caller supplies an already protected root.
83    pub fn acquire(
84        root: &Path,
85        chain: [u8; 32],
86        signer: &'a SigningKey,
87        byte_budget: usize,
88        policy: &mut impl LocalHeadPolicy,
89    ) -> Result<Self, LocalHeadError> {
90        validate_root(root).map_err(|_| LocalHeadError::InvalidRoot)?;
91        if chain.iter().all(|b| *b == 0) {
92            return Err(LocalHeadError::InvalidChain);
93        }
94        if byte_budget < SIZE {
95            return Err(LocalHeadError::InvalidBudget);
96        }
97        if !policy.permit_open(root, &chain) {
98            return Err(LocalHeadError::PermissionDenied);
99        }
100        let mut name = [0u8; 69];
101        const HEX: &[u8; 16] = b"0123456789abcdef";
102        for (i, byte) in chain.iter().enumerate() {
103            name[i * 2] = HEX[(byte >> 4) as usize];
104            name[i * 2 + 1] = HEX[(byte & 15) as usize];
105        }
106        name[64..].copy_from_slice(b".lock");
107        let lock_path =
108            root.join(std::str::from_utf8(&name).map_err(|_| LocalHeadError::InvalidEncoding)?);
109        name[64..].copy_from_slice(b".head");
110        let head_path =
111            root.join(std::str::from_utf8(&name).map_err(|_| LocalHeadError::InvalidEncoding)?);
112        let mut options = OpenOptions::new();
113        options.read(true).write(true).create(true).truncate(false);
114        #[cfg(unix)]
115        {
116            use std::os::unix::fs::OpenOptionsExt;
117            options
118                .mode(0o600)
119                .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC);
120        }
121        #[cfg(windows)]
122        {
123            use std::os::windows::fs::OpenOptionsExt;
124            options.custom_flags(0x0020_0000);
125        }
126        #[cfg(not(any(unix, windows)))]
127        {
128            return Err(LocalHeadError::InvalidRoot);
129        }
130        let lock = options.open(lock_path)?;
131        let metadata = lock.metadata()?;
132        if !metadata.is_file() {
133            return Err(LocalHeadError::InvalidEncoding);
134        }
135        #[cfg(windows)]
136        {
137            use std::os::windows::fs::MetadataExt;
138            if metadata.file_attributes() & 0x400 != 0 {
139                return Err(LocalHeadError::InvalidEncoding);
140            }
141        }
142        lock.try_lock().map_err(|_| LocalHeadError::Conflict)?;
143        Ok(Self {
144            root: root.to_owned(),
145            chain,
146            head_path,
147            _lock: lock,
148            signer,
149        })
150    }
151
152    pub fn current(&self, policy: &mut impl LocalHeadPolicy) -> Result<ChainHead, LocalHeadError> {
153        if !policy.permit_open(&self.root, &self.chain) {
154            return Err(LocalHeadError::PermissionDenied);
155        }
156        let head = match open_regular(&self.head_path) {
157            Ok(mut file) => {
158                let mut bytes = [0u8; SIZE];
159                file.read_exact(&mut bytes)?;
160                let mut trailing = [0u8; 1];
161                if file.read(&mut trailing)? != 0 {
162                    return Err(LocalHeadError::InvalidEncoding);
163                }
164                self.decode(&bytes)?
165            }
166            Err(super::CustodyError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
167                ChainHead::Empty
168            }
169            Err(_) => return Err(LocalHeadError::InvalidEncoding),
170        };
171        if !policy.admit_current(&self.root, &self.chain, head) {
172            return Err(LocalHeadError::PermissionDenied);
173        }
174        Ok(head)
175    }
176
177    /// Compare, sign and atomically replace a local head while holding the
178    /// lease. A post-replacement failure yields `Indeterminate`, never success.
179    /// The caller must have published the corresponding bundle and must use
180    /// external rollback/freshness checks during recovery.
181    #[allow(clippy::too_many_arguments)]
182    pub fn compare_and_commit(
183        &mut self,
184        expected: ChainHead,
185        receipt: &SidecarReceipt,
186        sidecar: &[u8; SIDECAR_BYTES],
187        payload: &[u8],
188        payload_budget: usize,
189        policy: &mut impl LocalHeadPolicy,
190    ) -> Result<HeadCommit, LocalHeadError> {
191        if receipt.chain_id() != &self.chain {
192            return Err(LocalHeadError::InvalidChain);
193        }
194        receipt
195            .verify_with_authority(sidecar, payload, payload_budget, policy)
196            .map_err(|_| LocalHeadError::Receipt)?;
197        if self.current(policy)? != expected {
198            return Ok(HeadCommit::Conflict);
199        }
200        match expected {
201            ChainHead::Empty
202                if receipt.sequence() == 0 && receipt.previous().iter().all(|b| *b == 0) => {}
203            ChainHead::Present {
204                sequence,
205                checkpoint,
206            } if sequence.checked_add(1) == Some(receipt.sequence())
207                && receipt.previous() == &checkpoint => {}
208            _ => return Ok(HeadCommit::Conflict),
209        }
210        let next = ChainHead::Present {
211            sequence: receipt.sequence(),
212            checkpoint: receipt.checkpoint(),
213        };
214        if !policy.permit_commit(
215            &self.root,
216            &self.chain,
217            expected,
218            next,
219            receipt,
220            sidecar,
221            payload,
222        ) {
223            return Err(LocalHeadError::PermissionDenied);
224        }
225        let bytes = self.encode(next)?;
226        let mut temp = tempfile::Builder::new()
227            .prefix("qualia-head-")
228            .tempfile_in(&self.root)?;
229        temp.write_all(&bytes)?;
230        temp.as_file().sync_all()?;
231        // Check current policy and head again before the replacement.
232        if self.current(policy)? != expected {
233            return Ok(HeadCommit::Conflict);
234        }
235        if !policy.permit_commit(
236            &self.root,
237            &self.chain,
238            expected,
239            next,
240            receipt,
241            sidecar,
242            payload,
243        ) {
244            return Err(LocalHeadError::PermissionDenied);
245        }
246        // Recheck signer, grant and chain authority after staging, before rename.
247        // The host must hold its policy lease through the actual replacement.
248        receipt
249            .verify_with_authority(sidecar, payload, payload_budget, policy)
250            .map_err(|_| LocalHeadError::Receipt)?;
251        if temp.persist(&self.head_path).is_err() {
252            return Ok(HeadCommit::Indeterminate);
253        }
254        // The platform/filesystem must additionally be qualified by the host.
255        #[cfg(unix)]
256        {
257            return Ok(
258                if File::open(&self.root).and_then(|f| f.sync_all()).is_ok() {
259                    HeadCommit::Committed
260                } else {
261                    HeadCommit::Indeterminate
262                },
263            );
264        }
265        #[cfg(not(unix))]
266        {
267            Ok(HeadCommit::Indeterminate)
268        }
269    }
270
271    fn encode(&self, head: ChainHead) -> Result<[u8; SIZE], LocalHeadError> {
272        let ChainHead::Present {
273            sequence,
274            checkpoint,
275        } = head
276        else {
277            return Err(LocalHeadError::InvalidEncoding);
278        };
279        if checkpoint.iter().all(|b| *b == 0) {
280            return Err(LocalHeadError::InvalidEncoding);
281        }
282        let mut bytes = [0u8; SIZE];
283        bytes[..4].copy_from_slice(MAGIC);
284        bytes[4..6].copy_from_slice(&1u16.to_le_bytes());
285        bytes[6..8].copy_from_slice(&(SIZE as u16).to_le_bytes());
286        bytes[8..40].copy_from_slice(&self.chain);
287        bytes[40..48].copy_from_slice(&sequence.to_le_bytes());
288        bytes[48..80].copy_from_slice(&checkpoint);
289        bytes[80..112].copy_from_slice(&self.signer.verifying_key().to_bytes());
290        let mut message = [0u8; DOMAIN.len() + 112];
291        message[..DOMAIN.len()].copy_from_slice(DOMAIN);
292        message[DOMAIN.len()..DOMAIN.len() + 112].copy_from_slice(&bytes[..112]);
293        bytes[112..].copy_from_slice(&self.signer.sign(&message[..DOMAIN.len() + 112]).to_bytes());
294        Ok(bytes)
295    }
296
297    fn decode(&self, bytes: &[u8; SIZE]) -> Result<ChainHead, LocalHeadError> {
298        if &bytes[..4] != MAGIC
299            || bytes[4..6] != 1u16.to_le_bytes()
300            || bytes[6..8] != (SIZE as u16).to_le_bytes()
301            || bytes[8..40] != self.chain
302            || bytes[80..112] != self.signer.verifying_key().to_bytes()
303        {
304            return Err(LocalHeadError::InvalidEncoding);
305        }
306        let key = VerifyingKey::from_bytes(&self.signer.verifying_key().to_bytes())
307            .map_err(|_| LocalHeadError::InvalidSigner)?;
308        let signature = Signature::from_bytes(
309            bytes[112..176]
310                .try_into()
311                .map_err(|_| LocalHeadError::InvalidEncoding)?,
312        );
313        let mut message = [0u8; DOMAIN.len() + 112];
314        message[..DOMAIN.len()].copy_from_slice(DOMAIN);
315        message[DOMAIN.len()..DOMAIN.len() + 112].copy_from_slice(&bytes[..112]);
316        key.verify_strict(&message[..DOMAIN.len() + 112], &signature)
317            .map_err(|_| LocalHeadError::InvalidSignature)?;
318        let sequence = u64::from_le_bytes(
319            bytes[40..48]
320                .try_into()
321                .map_err(|_| LocalHeadError::InvalidEncoding)?,
322        );
323        let checkpoint: [u8; 32] = bytes[48..80]
324            .try_into()
325            .map_err(|_| LocalHeadError::InvalidEncoding)?;
326        if checkpoint.iter().all(|b| *b == 0) {
327            return Err(LocalHeadError::InvalidEncoding);
328        }
329        Ok(ChainHead::Present {
330            sequence,
331            checkpoint,
332        })
333    }
334}