Skip to main content

qualia_core_db/crypto/network/
minima.rs

1//! CRY-02.08 **PARTIAL** — bind negotiation to cached authorized peer/realm minima.
2//!
3//! Only `qpr-pq-1` ([`PROFILE_QPR_PQ_1`]) is admitted as the initial profile.
4//! Stripped/missing offers, classical offers, unknown profiles, revoked cache
5//! entries, and any offered profile below the cached minimum fail closed.
6//! [`automatic_classical_retry`] is false; there is no classical fallback.
7//!
8//! Domain labels for the admitted profile live in
9//! [`crate::crypto::network::pq_handshake::{qlink_domain, qsession_domain}`].
10//! Classical-only authority is never enough
11//! ([`crate::crypto::network::pq_handshake::classical_only_authority_is_enough`]).
12//!
13//! Draft until FND-03 freeze. Alternate proof pairs, cookie admission chunks,
14//! and independent vectors remain open. No security proof is claimed.
15
16use crate::crypto::network::errors::CryptoError;
17
18/// Occupied minima slots. An 9th distinct `(peer, realm)` is [`CryptoError::Capacity`].
19pub const MAX_CACHED_MINIMA: usize = 8;
20
21/// Native PQ initial profile `qpr-pq-1`. The only admitted selected result.
22pub const PROFILE_QPR_PQ_1: u16 = 1;
23
24/// Classical-only profile. Forbidden as a selected result (maps to Downgrade).
25pub const PROFILE_CLASSICAL: u16 = 0;
26
27/// Cached authorized peer/realm minimum. `min_profile` must be
28/// [`PROFILE_QPR_PQ_1`] for [`select_profile`] to admit.
29#[repr(C)]
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct PeerMinima {
32    /// Cached authorized peer id (opaque).
33    pub peer: u64,
34    /// Realm id.
35    pub realm: u64,
36    /// Minimum admitted profile. Must be [`PROFILE_QPR_PQ_1`] to admit.
37    pub min_profile: u16,
38    /// Revoked cache entry. [`select_profile`] returns [`CryptoError::Revoked`].
39    pub revoked: bool,
40}
41
42/// Fixed 8-slot cache of authorized peer/realm minima. No heap.
43pub struct MinimaCache {
44    slots: [Option<PeerMinima>; MAX_CACHED_MINIMA],
45}
46
47impl MinimaCache {
48    /// Creates a default `MinimaCache`.
49    pub const fn new() -> Self {
50        Self {
51            slots: [None; MAX_CACHED_MINIMA],
52        }
53    }
54
55    /// Insert or replace by `(peer, realm)`. A 9th distinct pair is Capacity.
56    pub fn insert(&mut self, m: PeerMinima) -> Result<(), CryptoError> {
57        let mut i = 0usize;
58        while i < MAX_CACHED_MINIMA {
59            if let Some(existing) = &mut self.slots[i] {
60                if existing.peer == m.peer && existing.realm == m.realm {
61                    *existing = m;
62                    return Ok(());
63                }
64            }
65            i += 1;
66        }
67        let mut i = 0usize;
68        while i < MAX_CACHED_MINIMA {
69            if self.slots[i].is_none() {
70                self.slots[i] = Some(m);
71                return Ok(());
72            }
73            i += 1;
74        }
75        Err(CryptoError::Capacity)
76    }
77
78    /// Lookup by authorized `(peer, realm)`. Missing → Unauthorized.
79    pub fn lookup(&self, peer: u64, realm: u64) -> Result<PeerMinima, CryptoError> {
80        let mut i = 0usize;
81        while i < MAX_CACHED_MINIMA {
82            if let Some(m) = self.slots[i] {
83                if m.peer == peer && m.realm == realm {
84                    return Ok(m);
85                }
86            }
87            i += 1;
88        }
89        Err(CryptoError::Unauthorized)
90    }
91}
92
93/// Select a profile given cached minima and an offered profile.
94///
95/// Stripped / missing offer → [`CryptoError::Malformed`].
96/// Offered classical ([`PROFILE_CLASSICAL`]) → [`CryptoError::Downgrade`]
97/// (no automatic classical retry).
98/// Cached revoked → [`CryptoError::Revoked`].
99/// Offered profile &lt; cached `min_profile` → [`CryptoError::Downgrade`].
100/// Unknown profile (not 0 or 1) → [`CryptoError::UnknownProfile`].
101/// Success only if offered == [`PROFILE_QPR_PQ_1`] and
102/// `minima.min_profile` == [`PROFILE_QPR_PQ_1`] and `!revoked`.
103pub fn select_profile(cached: &PeerMinima, offered: Option<u16>) -> Result<u16, CryptoError> {
104    let offered = match offered {
105        Some(profile) => profile,
106        None => return Err(CryptoError::Malformed),
107    };
108    if offered != PROFILE_CLASSICAL && offered != PROFILE_QPR_PQ_1 {
109        return Err(CryptoError::UnknownProfile);
110    }
111    if cached.revoked {
112        return Err(CryptoError::Revoked);
113    }
114    if offered == PROFILE_CLASSICAL {
115        return Err(CryptoError::Downgrade);
116    }
117    if offered < cached.min_profile {
118        return Err(CryptoError::Downgrade);
119    }
120    if offered != PROFILE_QPR_PQ_1 || cached.min_profile != PROFILE_QPR_PQ_1 {
121        return Err(CryptoError::Downgrade);
122    }
123    Ok(PROFILE_QPR_PQ_1)
124}
125
126/// Negotiation never retries a classical-only profile automatically.
127pub fn automatic_classical_retry() -> bool {
128    false
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::crypto::network::pq_handshake::classical_only_authority_is_enough;
135
136    fn pq_minima(peer: u64, realm: u64) -> PeerMinima {
137        PeerMinima {
138            peer,
139            realm,
140            min_profile: PROFILE_QPR_PQ_1,
141            revoked: false,
142        }
143    }
144
145    #[test]
146    fn insert_eight_ok_ninth_capacity() {
147        let mut cache = MinimaCache::new();
148        let mut i = 0u64;
149        while i < MAX_CACHED_MINIMA as u64 {
150            assert_eq!(cache.insert(pq_minima(i + 1, 1)), Ok(()));
151            i += 1;
152        }
153        assert_eq!(cache.insert(pq_minima(99, 1)), Err(CryptoError::Capacity));
154        assert_eq!(cache.lookup(1, 1).unwrap().peer, 1);
155        assert_eq!(
156            cache.insert(PeerMinima {
157                peer: 1,
158                realm: 1,
159                min_profile: PROFILE_QPR_PQ_1,
160                revoked: true,
161            }),
162            Ok(())
163        );
164        assert!(cache.lookup(1, 1).unwrap().revoked);
165    }
166
167    #[test]
168    fn lookup_missing_is_unauthorized() {
169        let cache = MinimaCache::new();
170        assert_eq!(cache.lookup(1, 1), Err(CryptoError::Unauthorized));
171        let mut cache = MinimaCache::new();
172        assert_eq!(cache.insert(pq_minima(2, 3)), Ok(()));
173        assert_eq!(cache.lookup(2, 4), Err(CryptoError::Unauthorized));
174        assert_eq!(cache.lookup(1, 3), Err(CryptoError::Unauthorized));
175    }
176
177    #[test]
178    fn select_profile_none_is_malformed() {
179        let cached = pq_minima(1, 1);
180        assert_eq!(select_profile(&cached, None), Err(CryptoError::Malformed));
181    }
182
183    #[test]
184    fn select_profile_classical_is_downgrade() {
185        let cached = pq_minima(1, 1);
186        assert_eq!(
187            select_profile(&cached, Some(PROFILE_CLASSICAL)),
188            Err(CryptoError::Downgrade)
189        );
190    }
191
192    #[test]
193    fn select_profile_unknown_is_unknown_profile() {
194        let cached = pq_minima(1, 1);
195        assert_eq!(
196            select_profile(&cached, Some(99)),
197            Err(CryptoError::UnknownProfile)
198        );
199    }
200
201    #[test]
202    fn select_profile_revoked_even_if_offered_pq() {
203        let cached = PeerMinima {
204            peer: 7,
205            realm: 8,
206            min_profile: PROFILE_QPR_PQ_1,
207            revoked: true,
208        };
209        assert_eq!(
210            select_profile(&cached, Some(PROFILE_QPR_PQ_1)),
211            Err(CryptoError::Revoked)
212        );
213    }
214
215    #[test]
216    fn no_automatic_classical_retry_and_classical_authority_never_enough() {
217        assert!(!automatic_classical_retry());
218        assert!(!classical_only_authority_is_enough());
219    }
220
221    #[test]
222    fn select_profile_pq_against_min_pq_is_ok() {
223        let cached = pq_minima(4, 5);
224        assert_eq!(
225            select_profile(&cached, Some(PROFILE_QPR_PQ_1)),
226            Ok(PROFILE_QPR_PQ_1)
227        );
228    }
229}