Skip to main content

qualia_core_db/net/qdnf/clinical/mailbox/
lifecycle.rs

1//! Mailbox store, deliver, review and application-ack transitions.
2
3use super::super::{first_empty, MAX_SLOTS};
4use super::slot::{network_asserts_clinical_review, MailboxSlot, MailboxState};
5#[cfg(test)]
6use crate::net::peer::replication::custody::CustodyState;
7use crate::net::peer::replication::custody::{mark_application_acked, mark_delivered, mark_stored};
8use crate::net::qdnf::contracts::{recheck_permit, BoundGenerations, LiveGenerations};
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::types::StrongDigest;
11
12/// Eight-slot pending encrypted mailbox.
13#[derive(Clone, Copy, Debug)]
14pub struct Mailbox {
15    slots: [Option<MailboxSlot>; MAX_SLOTS],
16}
17
18impl Mailbox {
19    /// Creates a default `Mailbox`.
20    pub const fn new() -> Self {
21        Self {
22            slots: [None; MAX_SLOTS],
23        }
24    }
25
26    /// Fetches an entry by key; `None` when absent.
27    pub fn get(&self, slot: usize) -> Result<MailboxSlot, QdnfError> {
28        let err = if slot >= MAX_SLOTS {
29            QdnfError::Range
30        } else {
31            QdnfError::Closed
32        };
33        self.slots.get(slot).copied().flatten().ok_or(err)
34    }
35
36    /// Copy ciphertext bytes into a Stored slot. Length/digest without bytes is rejected.
37    pub fn store(
38        &mut self,
39        ct: &[u8],
40        recipient: StrongDigest,
41        key_generation: u64,
42    ) -> Result<usize, QdnfError> {
43        let slot = MailboxSlot::from_ciphertext(ct, recipient, key_generation)?;
44        let i = first_empty(&self.slots).ok_or(QdnfError::Capacity)?;
45        self.slots[i] = Some(slot);
46        Ok(i)
47    }
48
49    /// Length + digest is not content. Never becomes Stored.
50    pub fn store_len_digest(
51        &mut self,
52        ciphertext_len: u32,
53        ciphertext_digest: StrongDigest,
54        recipient: StrongDigest,
55        key_generation: u64,
56    ) -> Result<usize, QdnfError> {
57        let _ = (ciphertext_len, ciphertext_digest, recipient, key_generation);
58        match mark_stored(true, false) {
59            Ok(_) => Err(QdnfError::Incomplete),
60            Err(e) => Err(e),
61        }
62    }
63
64    /// Revoke clinician grants. Pending slots stay Stored.
65    pub fn revoke_clinician(&mut self, clinician: StrongDigest) -> Result<(), QdnfError> {
66        if clinician == StrongDigest::ZERO {
67            return Err(QdnfError::Malformed);
68        }
69        let mut i = 0usize;
70        while i < MAX_SLOTS {
71            if let Some(s) = self.slots[i].as_mut() {
72                if s.recipient == clinician {
73                    s.grant_revoked = true;
74                }
75            }
76            i += 1;
77        }
78        Ok(())
79    }
80
81    /// Deliver Stored material to the recorded recipient. No substitution.
82    /// Transport delivery does not mark ClinicianReviewed or ApplicationAcked.
83    pub fn deliver(
84        &mut self,
85        slot: usize,
86        recipient: StrongDigest,
87        key_generation: u64,
88    ) -> Result<(), QdnfError> {
89        debug_assert!(!network_asserts_clinical_review());
90        let mut s = self.get(slot)?;
91        if recipient != s.recipient {
92            return Err(QdnfError::Unauthorized);
93        }
94        if s.grant_revoked {
95            return Err(QdnfError::Revoked);
96        }
97        if key_generation != s.key_generation {
98            return Err(QdnfError::StaleGeneration);
99        }
100        recheck_permit(
101            s.bound,
102            LiveGenerations {
103                source: crate::net::qdnf::types::Generation(key_generation),
104                policy: crate::net::qdnf::types::Generation(key_generation),
105                identity: crate::net::qdnf::types::Generation(key_generation),
106            },
107        )?;
108        match s.state {
109            MailboxState::Stored => {
110                s.custody = mark_delivered(s.custody)?;
111                s.state = MailboxState::Delivered;
112                self.slots[slot] = Some(s);
113                Ok(())
114            }
115            MailboxState::Delivered => Ok(()),
116            MailboxState::ClinicianReviewed => Err(QdnfError::Conflict),
117        }
118    }
119
120    /// Commit/release recheck using live source/policy/identity generations (E12.5).
121    pub fn deliver_live(
122        &mut self,
123        slot: usize,
124        recipient: StrongDigest,
125        live: LiveGenerations,
126    ) -> Result<(), QdnfError> {
127        let s = self.get(slot)?;
128        recheck_permit(s.bound, live)?;
129        self.deliver(slot, recipient, s.key_generation)
130    }
131
132    /// Store ciphertext bound to compiled source/policy/identity generations.
133    pub fn store_bound(
134        &mut self,
135        ct: &[u8],
136        recipient: StrongDigest,
137        bound: BoundGenerations,
138    ) -> Result<usize, QdnfError> {
139        let i = self.store(ct, recipient, bound.source.0)?;
140        if let Some(slot) = self.slots[i].as_mut() {
141            slot.bound = bound;
142        }
143        Ok(i)
144    }
145
146    /// Application acknowledgement. Requires transport Delivered.
147    /// Distinct from ClinicianReviewed.
148    pub fn mark_application_acked(&mut self, slot: usize) -> Result<(), QdnfError> {
149        let mut s = self.get(slot)?;
150        s.custody = mark_application_acked(s.custody)?;
151        self.slots[slot] = Some(s);
152        Ok(())
153    }
154
155    /// ClinicianReviewed requires Delivered. Stored cannot skip.
156    /// Network delivery never calls this.
157    pub fn mark_reviewed(&mut self, slot: usize) -> Result<(), QdnfError> {
158        let mut s = self.get(slot)?;
159        match s.state {
160            MailboxState::Stored => Err(QdnfError::Denied),
161            MailboxState::Delivered => {
162                s.state = MailboxState::ClinicianReviewed;
163                self.slots[slot] = Some(s);
164                Ok(())
165            }
166            MailboxState::ClinicianReviewed => Ok(()),
167        }
168    }
169
170    /// Unapproved recipient substitution is always Unauthorized.
171    pub fn substitute_recipient(
172        &mut self,
173        slot: usize,
174        new_recipient: StrongDigest,
175    ) -> Result<(), QdnfError> {
176        let _ = (self.get(slot)?, new_recipient);
177        Err(QdnfError::Unauthorized)
178    }
179
180    /// Retained ciphertext for `slot`.
181    pub fn ciphertext(&self, slot: usize) -> Result<&[u8], QdnfError> {
182        match self.slots.get(slot) {
183            None => Err(QdnfError::Range),
184            Some(None) => Err(QdnfError::Closed),
185            Some(Some(s)) => Ok(s.ciphertext_bytes()),
186        }
187    }
188}
189
190impl Default for Mailbox {
191    fn default() -> Self {
192        Self::new()
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::crypto::network::digest::sha384;
200
201    fn d(tag: u8) -> StrongDigest {
202        let mut x = StrongDigest::ZERO;
203        x.0[0] = tag;
204        x
205    }
206
207    #[test]
208    fn mailbox_stored_requires_ciphertext_bytes() {
209        let mut ct = *b"pending-encrypted";
210        let original = ct;
211        let clinician = d(2);
212        let mut mb = Mailbox::new();
213        let slot = mb.store(&ct, clinician, 1).expect("store");
214        ct[0] ^= 0xff;
215        let s = mb.get(slot).unwrap();
216        assert_eq!(s.state, MailboxState::Stored);
217        assert_eq!(s.custody, CustodyState::Stored);
218        assert!(s.bytes_present());
219        assert_eq!(s.ciphertext_bytes(), original.as_slice());
220        assert_eq!(mb.ciphertext(slot).unwrap(), original.as_slice());
221        assert_eq!(s.ciphertext_digest, sha384(&original));
222        assert_eq!(s.ciphertext_len as usize, original.len());
223        assert_ne!(s.ciphertext_bytes(), ct.as_slice());
224        assert!(!s.is_application_acked());
225        assert!(!network_asserts_clinical_review());
226    }
227
228    #[test]
229    fn length_digest_only_is_incomplete() {
230        let clinician = d(2);
231        let ct = b"not-copied";
232        let mut mb = Mailbox::new();
233        assert_eq!(
234            mb.store_len_digest(ct.len() as u32, sha384(ct), clinician, 1),
235            Err(QdnfError::Incomplete)
236        );
237        assert_eq!(mb.get(0), Err(QdnfError::Closed));
238        assert_eq!(mb.ciphertext(0), Err(QdnfError::Closed));
239        assert_eq!(mark_stored(true, false), Err(QdnfError::Incomplete));
240    }
241
242    #[test]
243    fn delivered_is_not_application_acked() {
244        let ct = b"pending-encrypted";
245        let clinician = d(2);
246        let mut mb = Mailbox::new();
247        let slot = mb.store(ct, clinician, 1).expect("store");
248        assert_eq!(mb.mark_application_acked(slot), Err(QdnfError::Incomplete));
249        assert!(mb.deliver(slot, clinician, 1).is_ok());
250        let s = mb.get(slot).unwrap();
251        assert_eq!(s.state, MailboxState::Delivered);
252        assert_eq!(s.custody, CustodyState::Delivered);
253        assert_ne!(s.custody, CustodyState::ApplicationAcked);
254        assert!(!s.is_application_acked());
255        assert_ne!(s.state, MailboxState::ClinicianReviewed);
256        assert!(!network_asserts_clinical_review());
257        assert_eq!(mb.ciphertext(slot).unwrap(), ct);
258        assert!(mb.mark_application_acked(slot).is_ok());
259        let acked = mb.get(slot).unwrap();
260        assert!(acked.is_application_acked());
261        assert_eq!(acked.custody, CustodyState::ApplicationAcked);
262        assert_eq!(acked.state, MailboxState::Delivered);
263        assert_ne!(acked.state, MailboxState::ClinicianReviewed);
264        assert!(mb.mark_reviewed(slot).is_ok());
265        let reviewed = mb.get(slot).unwrap();
266        assert_eq!(reviewed.state, MailboxState::ClinicianReviewed);
267        assert!(reviewed.is_application_acked());
268        assert_eq!(reviewed.ciphertext_bytes(), ct);
269    }
270
271    #[test]
272    fn mailbox_revoke_substitute_generation_states() {
273        let ct = b"pending-encrypted";
274        let clinician = d(2);
275        let other = d(3);
276        let mut mb = Mailbox::new();
277        let slot = mb.store(ct, clinician, 1).expect("store");
278        assert_eq!(mb.get(slot).unwrap().state, MailboxState::Stored);
279        assert_eq!(mb.mark_reviewed(slot), Err(QdnfError::Denied));
280        assert_eq!(
281            mb.substitute_recipient(slot, other),
282            Err(QdnfError::Unauthorized)
283        );
284        assert_eq!(mb.deliver(slot, other, 1), Err(QdnfError::Unauthorized));
285        assert_eq!(
286            mb.deliver(slot, clinician, 2),
287            Err(QdnfError::StaleGeneration)
288        );
289        assert!(mb.deliver(slot, clinician, 1).is_ok());
290        assert_eq!(mb.get(slot).unwrap().state, MailboxState::Delivered);
291        assert!(!mb.get(slot).unwrap().is_application_acked());
292        assert!(!network_asserts_clinical_review());
293        assert!(mb.mark_reviewed(slot).is_ok());
294        assert_eq!(mb.get(slot).unwrap().state, MailboxState::ClinicianReviewed);
295        let mut pending = Mailbox::new();
296        let s = pending.store(ct, clinician, 1).expect("pending");
297        assert!(pending.revoke_clinician(clinician).is_ok());
298        assert_eq!(pending.get(s).unwrap().state, MailboxState::Stored);
299        assert_eq!(pending.deliver(s, clinician, 1), Err(QdnfError::Revoked));
300        assert_eq!(pending.get(s).unwrap().ciphertext_digest, sha384(ct));
301        assert_eq!(pending.get(s).unwrap().ciphertext_len as usize, ct.len());
302        assert_eq!(pending.get(s).unwrap().ciphertext_bytes(), ct);
303    }
304
305    #[test]
306    fn live_policy_generation_advance_is_stale() {
307        use crate::net::qdnf::types::Generation;
308        let clinician = d(2);
309        let mut mb = Mailbox::new();
310        let bound = BoundGenerations::new(Generation(1), Generation(1), Generation(1));
311        let slot = mb.store_bound(b"ct", clinician, bound).expect("store");
312        let mut live = bound.as_live();
313        live.policy = Generation(2);
314        assert_eq!(
315            mb.deliver_live(slot, clinician, live),
316            Err(QdnfError::StaleGeneration)
317        );
318        assert_eq!(mb.get(slot).unwrap().state, MailboxState::Stored);
319        assert!(mb.deliver_live(slot, clinician, bound.as_live()).is_ok());
320    }
321}