Skip to main content

qualia_core_db/sensing/local_custody/
recovery.rs

1//! Bounded, non-mutating admission of one published bundle during recovery.
2//!
3//! No directory scan, head update, deletion or repair is performed. The host
4//! must hold a read/policy lease and supply current rollback-resistant head
5//! state. Equal snapshots alone cannot prove a head was never rolled back.
6use super::{
7    chain::{ChainAuthorityError, ChainHead},
8    entry_size, read_bundle, validate_root, CustodyAuthority, CustodyError, SidecarReceipt,
9    SIDECAR_BYTES,
10};
11use std::path::Path;
12
13/// A host-verified membership assertion relative to the exact supplied head.
14/// The implementation must validate authenticated ancestry or exclusion proof;
15/// missing proof is `Unknown`, not evidence of an orphan or committed member.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum MembershipAssertion {
18    CommittedAncestor,
19    Excluded,
20    Unknown,
21}
22
23pub trait RecoveryAuthority: CustodyAuthority {
24    /// Authorize the exact checkpoint, chain metadata lookup and recovery read.
25    /// Maintain root protection, chain snapshot and current policy through return.
26    fn permit_recovery(
27        &mut self,
28        root: &Path,
29        chain: &[u8; 32],
30        checkpoint: &[u8; 32],
31        byte_budget: usize,
32    ) -> bool;
33    fn recovery_head(
34        &mut self,
35        root: &Path,
36        chain: &[u8; 32],
37    ) -> Result<ChainHead, ChainAuthorityError>;
38    fn membership(
39        &mut self,
40        root: &Path,
41        head: ChainHead,
42        receipt: &SidecarReceipt,
43    ) -> Result<MembershipAssertion, ChainAuthorityError>;
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum RecoveryDisposition {
48    /// Checkpoint and sequence equal the authenticated current head.
49    CommittedAtHead,
50    /// Host has validated authenticated ancestry under this exact head.
51    CommittedAncestor,
52    /// Host has validated exclusion; this does not authorize deletion or repair.
53    PublishedUncommitted,
54    /// A valid signed bundle without sufficient membership evidence.
55    Uncertain,
56}
57
58pub struct RecoveryReport {
59    pub receipt: SidecarReceipt,
60    pub payload_bytes: usize,
61    pub head: ChainHead,
62    pub disposition: RecoveryDisposition,
63}
64
65#[derive(Debug)]
66pub enum RecoveryError {
67    Custody(CustodyError),
68    Authority(ChainAuthorityError),
69    WrongChain,
70    InvalidHead,
71    InvalidMembership,
72    HeadChanged,
73}
74
75/// Read one exact checkpoint with caller-owned bounded buffers. Errors and
76/// unwind clear both buffers, including errors after a successful bundle read.
77/// A report is admission under the host's current snapshot, not a reusable
78/// permission, proof of directory durability, or independent rollback defence.
79pub fn inspect_recovery_bundle(
80    root: &Path,
81    chain: &[u8; 32],
82    checkpoint: &[u8; 32],
83    byte_budget: usize,
84    sidecar: &mut [u8; SIDECAR_BYTES],
85    payload: &mut [u8],
86    authority: &mut impl RecoveryAuthority,
87) -> Result<RecoveryReport, RecoveryError> {
88    sidecar.fill(0);
89    payload.fill(0);
90    let mut buffers = RecoveryBuffers {
91        sidecar,
92        payload,
93        keep: false,
94    };
95    let result = inspect_inner(
96        root,
97        chain,
98        checkpoint,
99        byte_budget,
100        buffers.sidecar,
101        buffers.payload,
102        authority,
103    );
104    if result.is_ok() {
105        buffers.keep = true;
106    }
107    result
108}
109
110fn inspect_inner(
111    root: &Path,
112    chain: &[u8; 32],
113    checkpoint: &[u8; 32],
114    byte_budget: usize,
115    sidecar: &mut [u8; SIDECAR_BYTES],
116    payload: &mut [u8],
117    authority: &mut impl RecoveryAuthority,
118) -> Result<RecoveryReport, RecoveryError> {
119    validate_root(root).map_err(RecoveryError::Custody)?;
120    entry_size(0, byte_budget).map_err(RecoveryError::Custody)?;
121    if chain.iter().all(|v| *v == 0) || checkpoint.iter().all(|v| *v == 0) {
122        return Err(RecoveryError::InvalidHead);
123    }
124    if !authority.permit_recovery(root, chain, checkpoint, byte_budget)
125        || !authority.permit_read(root, checkpoint, byte_budget)
126    {
127        return Err(RecoveryError::Custody(CustodyError::PermissionDenied));
128    }
129    let head = authority
130        .recovery_head(root, chain)
131        .map_err(RecoveryError::Authority)?;
132    validate_head(head)?;
133    let read = read_bundle(root, checkpoint, byte_budget, sidecar, payload, authority)
134        .map_err(RecoveryError::Custody)?;
135    if read.receipt.chain_id() != chain {
136        return Err(RecoveryError::WrongChain);
137    }
138    let assertion = if head
139        == (ChainHead::Present {
140            sequence: read.receipt.sequence(),
141            checkpoint: *checkpoint,
142        }) {
143        MembershipAssertion::Unknown
144    } else {
145        authority
146            .membership(root, head, &read.receipt)
147            .map_err(RecoveryError::Authority)?
148    };
149    let disposition = classify(head, &read.receipt, assertion)?;
150    let final_head = authority
151        .recovery_head(root, chain)
152        .map_err(RecoveryError::Authority)?;
153    if final_head != head {
154        return Err(RecoveryError::HeadChanged);
155    }
156    read.receipt
157        .verify_with_authority(
158            sidecar,
159            &payload[..read.payload_bytes],
160            read.payload_bytes,
161            authority,
162        )
163        .map_err(|e| RecoveryError::Custody(CustodyError::Receipt(e)))?;
164    if !authority.permit_recovery(root, chain, checkpoint, byte_budget)
165        || !authority.permit_read(root, checkpoint, byte_budget)
166    {
167        return Err(RecoveryError::Custody(CustodyError::PermissionDenied));
168    }
169    Ok(RecoveryReport {
170        receipt: read.receipt,
171        payload_bytes: read.payload_bytes,
172        head,
173        disposition,
174    })
175}
176
177fn validate_head(head: ChainHead) -> Result<(), RecoveryError> {
178    if matches!(head, ChainHead::Present { checkpoint, .. } if checkpoint.iter().all(|v| *v == 0)) {
179        return Err(RecoveryError::InvalidHead);
180    }
181    Ok(())
182}
183
184fn classify(
185    head: ChainHead,
186    receipt: &SidecarReceipt,
187    assertion: MembershipAssertion,
188) -> Result<RecoveryDisposition, RecoveryError> {
189    validate_head(head)?;
190    if head
191        == (ChainHead::Present {
192            sequence: receipt.sequence(),
193            checkpoint: receipt.checkpoint(),
194        })
195    {
196        return Ok(RecoveryDisposition::CommittedAtHead);
197    }
198    match assertion {
199        MembershipAssertion::CommittedAncestor => match head {
200            ChainHead::Present { sequence, .. } if receipt.sequence() < sequence => {
201                Ok(RecoveryDisposition::CommittedAncestor)
202            }
203            _ => Err(RecoveryError::InvalidMembership),
204        },
205        MembershipAssertion::Excluded => Ok(RecoveryDisposition::PublishedUncommitted),
206        MembershipAssertion::Unknown => Ok(RecoveryDisposition::Uncertain),
207    }
208}
209
210struct RecoveryBuffers<'a> {
211    sidecar: &'a mut [u8; SIDECAR_BYTES],
212    payload: &'a mut [u8],
213    keep: bool,
214}
215impl Drop for RecoveryBuffers<'_> {
216    fn drop(&mut self) {
217        if !self.keep {
218            self.sidecar.fill(0);
219            self.payload.fill(0);
220        }
221    }
222}
223
224#[cfg(test)]
225#[path = "recovery_tests.rs"]
226mod tests;