Skip to main content

qualia_core_db/net/qdnf/profiles/
offline.rs

1//! Prepared offline contact packages and short-lived capabilities (E16.4).
2//!
3//! Queue capacity is 8. Release checks [`Generation`] equality rather than a
4//! caller-asserted “authority is current” boolean. Expired packages stay
5//! sealed; clock rollback does not extend expiry.
6//!
7//! [`ScopedCapability`] cannot be refreshed by copying: a copy keeps the
8//! original deadline and [`activate_capability`] still expires after it.
9//!
10//! Offline permissions are never labelled “current” after freshness lapses.
11//! Remote wipe and attestation cannot guarantee safety after endpoint
12//! compromise or seizure (E16.7).
13
14use crate::net::qdnf::errors::QdnfError;
15use crate::net::qdnf::types::{Generation, StrongDigest};
16
17pub const MAX_OFFLINE: usize = 8;
18
19#[repr(C)]
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct OfflinePackage {
22    pub recipient: StrongDigest,
23    pub expiry_unix: u64,
24    pub ciphertext_len: u32,
25    pub digest: StrongDigest,
26}
27
28impl OfflinePackage {
29    pub const EMPTY: Self = Self {
30        recipient: StrongDigest::ZERO,
31        expiry_unix: 0,
32        ciphertext_len: 0,
33        digest: StrongDigest::ZERO,
34    };
35}
36
37/// Short-lived capability. Copying does not extend [`Self::expires_unix`].
38#[repr(C)]
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct ScopedCapability {
41    pub expires_unix: u64,
42    pub purpose: StrongDigest,
43    pub recipient: StrongDigest,
44}
45
46#[repr(C)]
47#[derive(Clone, Copy, Debug)]
48pub struct OfflineQueue {
49    packages: [OfflinePackage; MAX_OFFLINE],
50    occupied: [bool; MAX_OFFLINE],
51    last_seen_unix: u64,
52}
53
54impl OfflineQueue {
55    /// Creates a default `OfflineQueue`.
56    pub const fn new() -> Self {
57        Self {
58            packages: [OfflinePackage::EMPTY; MAX_OFFLINE],
59            occupied: [false; MAX_OFFLINE],
60            last_seen_unix: 0,
61        }
62    }
63
64    #[inline]
65    /// `OfflineQueue::last_seen_unix`.
66    pub const fn last_seen_unix(&self) -> u64 {
67        self.last_seen_unix
68    }
69
70    /// `OfflineQueue::get`.
71    pub fn get(&self, slot: u8) -> Result<OfflinePackage, QdnfError> {
72        let i = slot as usize;
73        if i >= MAX_OFFLINE || !self.occupied[i] {
74            return Err(QdnfError::Denied);
75        }
76        Ok(self.packages[i])
77    }
78}
79
80impl Default for OfflineQueue {
81    fn default() -> Self {
82        Self::new()
83    }
84}
85
86fn package_well_formed(pkg: &OfflinePackage) -> Result<(), QdnfError> {
87    if pkg.recipient.is_zero() {
88        return Err(QdnfError::Malformed);
89    }
90    if pkg.ciphertext_len == 0 && !pkg.digest.is_zero() {
91        return Err(QdnfError::Malformed);
92    }
93    Ok(())
94}
95
96/// Enqueue a sealed package. Capacity 8. Clock rollback is Conflict and
97/// does not rewrite stored expiry.
98pub fn queue_offline(
99    queue: &mut OfflineQueue,
100    pkg: OfflinePackage,
101    now: u64,
102) -> Result<u8, QdnfError> {
103    if now < queue.last_seen_unix {
104        return Err(QdnfError::Conflict);
105    }
106    package_well_formed(&pkg)?;
107    if pkg.ciphertext_len == 0 {
108        return Err(QdnfError::Malformed);
109    }
110    let mut i = 0usize;
111    while i < MAX_OFFLINE {
112        if !queue.occupied[i] {
113            queue.packages[i] = pkg;
114            queue.occupied[i] = true;
115            queue.last_seen_unix = now;
116            return Ok(i as u8);
117        }
118        i += 1;
119    }
120    Err(QdnfError::Capacity)
121}
122
123/// Release a queued package. Authority freshness is the live generation,
124/// not a boolean assertion from the caller.
125pub fn release_offline(
126    pkg: &OfflinePackage,
127    now: u64,
128    authority_generation: Generation,
129    live_generation: Generation,
130) -> Result<(), QdnfError> {
131    package_well_formed(pkg)?;
132    if pkg.ciphertext_len == 0 {
133        return Err(QdnfError::Malformed);
134    }
135    if now >= pkg.expiry_unix {
136        return Err(QdnfError::Expired);
137    }
138    if authority_generation != live_generation {
139        return Err(QdnfError::StaleGeneration);
140    }
141    Ok(())
142}
143
144/// Release from the queue, applying monotonic clock checks.
145pub fn release_queued(
146    queue: &mut OfflineQueue,
147    slot: u8,
148    now: u64,
149    authority_generation: Generation,
150    live_generation: Generation,
151) -> Result<(), QdnfError> {
152    if now < queue.last_seen_unix {
153        return Err(QdnfError::Conflict);
154    }
155    let pkg = queue.get(slot)?;
156    release_offline(&pkg, now, authority_generation, live_generation)?;
157    queue.last_seen_unix = now;
158    queue.occupied[slot as usize] = false;
159    queue.packages[slot as usize] = OfflinePackage::EMPTY;
160    Ok(())
161}
162
163/// Activates an offline capability.
164pub fn activate_capability(cap: &ScopedCapability, now: u64) -> Result<(), QdnfError> {
165    if cap.recipient.is_zero() || cap.purpose.is_zero() {
166        return Err(QdnfError::Malformed);
167    }
168    if now >= cap.expires_unix {
169        Err(QdnfError::Expired)
170    } else {
171        Ok(())
172    }
173}
174
175/// Copying is not a refresh: the deadline is unchanged and this call is denied.
176pub fn extend_capability_by_copy(
177    cap: &ScopedCapability,
178    _new_expiry: u64,
179) -> Result<ScopedCapability, QdnfError> {
180    let _ = cap;
181    Err(QdnfError::Denied)
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    fn digest(b: u8) -> StrongDigest {
189        let mut d = StrongDigest::ZERO;
190        d.0[0] = b;
191        d.0[47] = 3;
192        d
193    }
194
195    fn pkg(exp: u64) -> OfflinePackage {
196        OfflinePackage {
197            recipient: digest(1),
198            expiry_unix: exp,
199            ciphertext_len: 64,
200            digest: digest(2),
201        }
202    }
203
204    #[test]
205    fn queue_and_release_matching_generation() {
206        let mut q = OfflineQueue::new();
207        let slot = queue_offline(&mut q, pkg(100), 10).unwrap();
208        release_queued(&mut q, slot, 11, Generation(3), Generation(3)).unwrap();
209        assert_eq!(q.get(slot).unwrap_err(), QdnfError::Denied);
210    }
211
212    #[test]
213    fn stale_generation_is_not_a_boolean_ok() {
214        let p = pkg(100);
215        assert_eq!(
216            release_offline(&p, 10, Generation(1), Generation(2)),
217            Err(QdnfError::StaleGeneration)
218        );
219    }
220
221    #[test]
222    fn expired_stays_sealed() {
223        let p = pkg(10);
224        assert_eq!(
225            release_offline(&p, 10, Generation(1), Generation(1)),
226            Err(QdnfError::Expired)
227        );
228    }
229
230    #[test]
231    fn empty_ciphertext_with_digest_is_malformed() {
232        let p = OfflinePackage {
233            recipient: digest(1),
234            expiry_unix: 100,
235            ciphertext_len: 0,
236            digest: digest(9),
237        };
238        let mut q = OfflineQueue::new();
239        assert_eq!(
240            queue_offline(&mut q, p, 1).unwrap_err(),
241            QdnfError::Malformed
242        );
243        assert_eq!(
244            release_offline(&p, 1, Generation(1), Generation(1)),
245            Err(QdnfError::Malformed)
246        );
247    }
248
249    #[test]
250    fn clock_rollback_does_not_extend_expiry() {
251        let mut q = OfflineQueue::new();
252        let slot = queue_offline(&mut q, pkg(100), 50).unwrap();
253        let exp = q.get(slot).unwrap().expiry_unix;
254        assert_eq!(
255            queue_offline(&mut q, pkg(500), 40).unwrap_err(),
256            QdnfError::Conflict
257        );
258        assert_eq!(q.get(slot).unwrap().expiry_unix, exp);
259        assert_eq!(
260            release_queued(&mut q, slot, 40, Generation(1), Generation(1)).unwrap_err(),
261            QdnfError::Conflict
262        );
263        assert_eq!(q.get(slot).unwrap().expiry_unix, exp);
264    }
265
266    #[test]
267    fn capability_copy_does_not_refresh() {
268        let cap = ScopedCapability {
269            expires_unix: 20,
270            purpose: digest(4),
271            recipient: digest(5),
272        };
273        activate_capability(&cap, 10).unwrap();
274        let copied = cap;
275        assert_eq!(copied.expires_unix, cap.expires_unix);
276        assert_eq!(activate_capability(&copied, 20), Err(QdnfError::Expired));
277        assert_eq!(
278            extend_capability_by_copy(&copied, 9999).unwrap_err(),
279            QdnfError::Denied
280        );
281        assert_eq!(copied.expires_unix, 20);
282    }
283
284    #[test]
285    fn queue_capacity_eight() {
286        let mut q = OfflineQueue::new();
287        let mut i = 0u8;
288        while i < MAX_OFFLINE as u8 {
289            queue_offline(&mut q, pkg(100), 1).unwrap();
290            i += 1;
291        }
292        assert_eq!(
293            queue_offline(&mut q, pkg(100), 2).unwrap_err(),
294            QdnfError::Capacity
295        );
296    }
297}