logicaffeine_compile/concurrency/channel.rs
1//! `SecureChannel` envelope — the end-to-end crypto seam that wraps the opaque
2//! wire blob `marshal` produces, between the codec and the transport.
3//!
4//! Layering: the channel owns its *own* versioned envelope
5//! and never inspects or mutates the payload, exactly as the FEC layer in [`super::fec`]
6//! does. `seal` frames an opaque blob under a suite id; `open` reverses it, returning
7//! `None` on any malformed input — the same `None`-on-malformed contract
8//! [`super::marshal::message_from_wire`] honours, so a corrupt or truncated envelope is
9//! dropped, never decoded.
10//!
11//! ```text
12//! [ CHAN_MAGIC | CHAN_VER | suite_id (LE u16) | body ]
13//! ```
14//!
15//! The `null` suite (`SUITE_NULL`) is identity framing — no cryptography — and exists to
16//! prove the embedding seam end-to-end before any primitive lands. Real suites replace
17//! `body` with `handshake/sequence ‖ AEAD(blob)+tag` under their own suite id; because the
18//! suite id is bound in the envelope, swapping a suite is a registry change, never a wire
19//! break.
20
21/// Envelope magic byte — distinct from [`super::fec`]'s `0xFE` so a framed blob is
22/// self-identifying.
23pub(crate) const CHAN_MAGIC: u8 = 0xC0;
24
25/// Envelope format version.
26pub(crate) const CHAN_VER: u8 = 1;
27
28/// Fixed header: magic (1) + version (1) + suite id (2, little-endian).
29pub(crate) const CHAN_HEADER_LEN: usize = 4;
30
31/// The suite id of the identity suite.
32pub const SUITE_NULL: u16 = 0;
33
34/// The suite id of the post-quantum suite: an ML-KEM-768 handshake establishes the shared secret,
35/// SHAKE256 derives the key, and every body is ChaCha20-Poly1305 AEAD-sealed.
36pub const SUITE_PQ: u16 = 1;
37
38/// The suite id of the `PNP` tier — the information-theoretic true one-time pad (see [`super::pnp`]).
39/// It is the last resort should computational cryptography fall (the `P = NP` scenario): its secrecy
40/// rests on Shannon, not on any hardness assumption. Like [`SUITE_PQ`] it is keyed and stateful, so
41/// it lives outside the stateless [`suite_for`] registry and is used through [`super::pnp::PnpSuite`]
42/// rather than [`seal`] / [`open`].
43pub const SUITE_PNP: u16 = 2;
44
45/// A pluggable crypto suite. Each posture level — `null`, `Classic`, `Hybrid`, `PQ`,
46/// `PQ-Max` — is one `Suite` registered in [`suite_for`], so adding a primitive is a
47/// registration, not a change to [`seal`] / [`open`]. The seam stays suite-agnostic; all
48/// cryptography lives behind this trait (crypto-agility).
49pub trait Suite: Sync {
50 /// The wire suite id bound into the envelope header.
51 fn id(&self) -> u16;
52 /// Transform an opaque blob into the envelope body — identity for `null`; for a real
53 /// suite, `handshake/sequence ‖ AEAD(blob)+tag`.
54 fn seal_body(&self, blob: &[u8]) -> Vec<u8>;
55 /// Reverse [`Suite::seal_body`], or `None` on a tampered / malformed body.
56 fn open_body(&self, body: &[u8]) -> Option<Vec<u8>>;
57}
58
59/// The identity suite: no cryptography, `body == blob`. Proves the seam; never the shipped
60/// default once a real suite exists.
61pub struct NullSuite;
62
63impl Suite for NullSuite {
64 fn id(&self) -> u16 {
65 SUITE_NULL
66 }
67 fn seal_body(&self, blob: &[u8]) -> Vec<u8> {
68 blob.to_vec()
69 }
70 fn open_body(&self, body: &[u8]) -> Option<Vec<u8>> {
71 Some(body.to_vec())
72 }
73}
74
75/// Resolve a registered STATELESS suite by its wire id, or `None` for an unknown suite (so
76/// [`open`] returns `None` rather than decoding under the wrong primitive). The keyed [`PqSuite`]
77/// is not here — it carries a per-session key and is used via [`seal_with`] / [`open_with`].
78pub fn suite_for(id: u16) -> Option<&'static dyn Suite> {
79 static NULL: NullSuite = NullSuite;
80 match id {
81 SUITE_NULL => Some(&NULL),
82 _ => None,
83 }
84}
85
86/// How many sequence numbers behind the newest it has opened a [`PqSuite`] still opens a frame at: a
87/// frame further back can no longer be told from a replay, and is refused.
88pub const PQ_REPLAY_WINDOW: u64 = 1024;
89
90/// The sequence numbers a receiver has opened, over a window of `span` numbers ending at the newest
91/// (the anti-replay window of RFC 4303 §3.4.3): each number opens once, and a number `span` or more
92/// behind the newest is refused, since the window no longer remembers whether it opened.
93pub(crate) struct ReplayWindow {
94 span: u64,
95 newest: Option<u64>,
96 seen: Vec<u64>,
97}
98
99impl ReplayWindow {
100 pub(crate) fn new(span: u64) -> Self {
101 assert!(span >= 1, "a replay window spans at least one number");
102 Self {
103 span,
104 newest: None,
105 seen: vec![0; span.div_ceil(64) as usize],
106 }
107 }
108
109 /// A window that has opened every number below `opened_through` and none from it on: where a
110 /// receiver that remembers only its high-water mark resumes, refusing all it may have opened.
111 pub(crate) fn resumed_at(span: u64, opened_through: u64) -> Self {
112 let mut window = Self::new(span);
113 if let Some(newest) = opened_through.checked_sub(1) {
114 window.newest = Some(newest);
115 window.seen.fill(u64::MAX);
116 }
117 window
118 }
119
120 fn slot(&self, seq: u64) -> (usize, u64) {
121 let at = seq % self.span;
122 ((at / 64) as usize, 1u64 << (at % 64))
123 }
124
125 /// Whether `seq` would open: not opened before, and not too far behind the newest to tell.
126 pub(crate) fn admits(&self, seq: u64) -> bool {
127 match self.newest {
128 Some(newest) if seq <= newest => {
129 let (word, bit) = self.slot(seq);
130 newest - seq < self.span && self.seen[word] & bit == 0
131 }
132 _ => true,
133 }
134 }
135
136 /// Record `seq` as opened: `false`, recording nothing, when the window does not admit it.
137 pub(crate) fn accept(&mut self, seq: u64) -> bool {
138 if !self.admits(seq) {
139 return false;
140 }
141 match self.newest {
142 Some(newest) if seq <= newest => {}
143 Some(newest) if seq - newest < self.span => {
144 for skipped in newest + 1..seq {
145 let (word, bit) = self.slot(skipped);
146 self.seen[word] &= !bit;
147 }
148 self.newest = Some(seq);
149 }
150 _ => {
151 self.seen.fill(0);
152 self.newest = Some(seq);
153 }
154 }
155 let (word, bit) = self.slot(seq);
156 self.seen[word] |= bit;
157 true
158 }
159}
160
161/// The post-quantum suite: a per-session ChaCha20-Poly1305 key (from an ML-KEM-768 handshake,
162/// see [`pq_handshake_initiator`] / [`pq_handshake_responder`]). Each `seal_body` draws the next
163/// sequence number as its nonce, so no two frames share one, and the nonce rides in the body. The
164/// opening side opens each sequence number once, in any order within [`PQ_REPLAY_WINDOW`] of the
165/// newest, so a captured frame cannot be delivered twice. The suite id is bound as the AEAD
166/// associated data, so a frame can't be replayed under a different suite. (Bidirectional use derives a
167/// key per direction — see the handshake.)
168pub struct PqSuite {
169 key: [u8; 32],
170 seq: std::sync::atomic::AtomicU64,
171 opened: std::sync::Mutex<ReplayWindow>,
172}
173
174impl PqSuite {
175 /// A PQ suite over an already-derived 32-byte AEAD key.
176 pub fn new(key: [u8; 32]) -> Self {
177 Self {
178 key,
179 seq: std::sync::atomic::AtomicU64::new(0),
180 opened: std::sync::Mutex::new(ReplayWindow::new(PQ_REPLAY_WINDOW)),
181 }
182 }
183}
184
185impl Suite for PqSuite {
186 fn id(&self) -> u16 {
187 SUITE_PQ
188 }
189 fn seal_body(&self, blob: &[u8]) -> Vec<u8> {
190 let seq = self
191 .seq
192 .fetch_update(
193 std::sync::atomic::Ordering::Relaxed,
194 std::sync::atomic::Ordering::Relaxed,
195 |seq| seq.checked_add(1),
196 )
197 .expect("a PQ session seals at most 2^64 - 1 frames: another would reuse a nonce");
198 let mut nonce = [0u8; 12];
199 nonce[..8].copy_from_slice(&seq.to_le_bytes());
200 let sealed = logicaffeine_system::aead::chacha20poly1305_seal(
201 &self.key,
202 &nonce,
203 &SUITE_PQ.to_le_bytes(),
204 blob,
205 );
206 let mut body = Vec::with_capacity(12 + sealed.len());
207 body.extend_from_slice(&nonce);
208 body.extend_from_slice(&sealed);
209 body
210 }
211 fn open_body(&self, body: &[u8]) -> Option<Vec<u8>> {
212 if body.len() < 12 {
213 return None;
214 }
215 let nonce: [u8; 12] = body[..12].try_into().ok()?;
216 let blob = logicaffeine_system::aead::chacha20poly1305_open(
217 &self.key,
218 &nonce,
219 &SUITE_PQ.to_le_bytes(),
220 &body[12..],
221 )?;
222 let seq = u64::from_le_bytes(nonce[..8].try_into().ok()?);
223 let first = self
224 .opened
225 .lock()
226 .unwrap_or_else(std::sync::PoisonError::into_inner)
227 .accept(seq);
228 first.then_some(blob)
229 }
230}
231
232/// Derive a directional 32-byte AEAD key from an ML-KEM shared secret via SHAKE256, domain-separated
233/// by `label` (e.g. `b"i2r"` / `b"r2i"`) so each direction has an independent key — no nonce reuse
234/// across the two streams that share the handshake secret.
235pub fn derive_aead_key(shared_secret: &[u8], label: &[u8]) -> [u8; 32] {
236 let mut input = Vec::with_capacity(shared_secret.len() + label.len() + 24);
237 input.extend_from_slice(b"logos-pq-channel-v1\x00");
238 input.extend_from_slice(label);
239 input.extend_from_slice(shared_secret);
240 let mut k = [0u8; 32];
241 k.copy_from_slice(&logicaffeine_system::keccak::shake256_bytes(&input, 32));
242 k
243}
244
245/// The freshly generated handshake material an initiator publishes + retains.
246pub struct PqHandshake {
247 /// ML-KEM-768 encapsulation key, sent to the responder.
248 pub ek: Vec<u8>,
249 /// ML-KEM-768 decapsulation key, kept secret.
250 dk: Vec<u8>,
251}
252
253/// Initiator step 1: generate an ML-KEM-768 keypair. Publish [`PqHandshake::ek`] to the responder.
254pub fn pq_handshake_initiator(seed_d: &[u8; 32], seed_z: &[u8; 32]) -> PqHandshake {
255 let (ek, dk) = logicaffeine_system::mlkem::keygen(seed_d, seed_z);
256 PqHandshake { ek, dk }
257}
258
259/// Responder: encapsulate to the initiator's `ek`, returning the ciphertext to send back and the
260/// two directional suites (`initiator→responder`, `responder→initiator`). An `ek` that fails the
261/// FIPS 203 encapsulation-key checks is refused, never encapsulated to.
262pub fn pq_handshake_responder(
263 ek: &[u8],
264 msg: &[u8; 32],
265) -> Result<(Vec<u8>, PqSuite, PqSuite), logicaffeine_system::mlkem::KemError> {
266 let (ct, ss) = logicaffeine_system::mlkem::encaps(ek, msg)?;
267 Ok((
268 ct,
269 PqSuite::new(derive_aead_key(&ss, b"i2r")),
270 PqSuite::new(derive_aead_key(&ss, b"r2i")),
271 ))
272}
273
274/// Initiator step 2: decapsulate the responder's ciphertext, yielding the matching directional
275/// suites (`initiator→responder`, `responder→initiator`). A ciphertext of the wrong length is
276/// refused; a well-formed but forged one implicit-rejects into suites that open nothing.
277pub fn pq_handshake_finish(
278 hs: &PqHandshake,
279 ct: &[u8],
280) -> Result<(PqSuite, PqSuite), logicaffeine_system::mlkem::KemError> {
281 let ss = logicaffeine_system::mlkem::decaps(&hs.dk, ct)?;
282 Ok((
283 PqSuite::new(derive_aead_key(&ss, b"i2r")),
284 PqSuite::new(derive_aead_key(&ss, b"r2i")),
285 ))
286}
287
288/// Frame a blob under a keyed [`Suite`] instance (the [`PqSuite`] path), binding the suite id in the
289/// header exactly like [`seal`]. The instance carries the per-session key the static registry can't.
290pub fn seal_with(suite: &dyn Suite, blob: &[u8]) -> Vec<u8> {
291 let body = suite.seal_body(blob);
292 let mut out = Vec::with_capacity(CHAN_HEADER_LEN + body.len());
293 out.push(CHAN_MAGIC);
294 out.push(CHAN_VER);
295 out.extend_from_slice(&suite.id().to_le_bytes());
296 out.extend_from_slice(&body);
297 out
298}
299
300/// Reverse [`seal_with`] under a keyed [`Suite`] instance, or `None` on a bad header, a suite-id
301/// mismatch, or a body the suite rejects (a tampered AEAD tag).
302pub fn open_with(suite: &dyn Suite, bytes: &[u8]) -> Option<Vec<u8>> {
303 if bytes.len() < CHAN_HEADER_LEN || bytes[0] != CHAN_MAGIC || bytes[1] != CHAN_VER {
304 return None;
305 }
306 if u16::from_le_bytes([bytes[2], bytes[3]]) != suite.id() {
307 return None;
308 }
309 suite.open_body(&bytes[CHAN_HEADER_LEN..])
310}
311
312/// Frame an opaque blob under `suite_id`, dispatching the body through the registered
313/// [`Suite`]. Panics only if sealed with an unregistered suite — a programmer error, since
314/// callers select from the registry.
315pub fn seal(suite_id: u16, blob: &[u8]) -> Vec<u8> {
316 let suite = suite_for(suite_id).expect("seal with a registered suite");
317 let body = suite.seal_body(blob);
318 let mut out = Vec::with_capacity(CHAN_HEADER_LEN + body.len());
319 out.push(CHAN_MAGIC);
320 out.push(CHAN_VER);
321 out.extend_from_slice(&suite_id.to_le_bytes());
322 out.extend_from_slice(&body);
323 out
324}
325
326/// Reverse [`seal`], returning the inner blob. `None` on a too-short header, a bad
327/// magic/version, an unknown suite id, or a body the suite rejects — never a panic, never
328/// a partial decode (mirrors [`super::marshal::message_from_wire`]).
329pub fn open(bytes: &[u8]) -> Option<Vec<u8>> {
330 if bytes.len() < CHAN_HEADER_LEN || bytes[0] != CHAN_MAGIC || bytes[1] != CHAN_VER {
331 return None;
332 }
333 let suite_id = u16::from_le_bytes([bytes[2], bytes[3]]);
334 let suite = suite_for(suite_id)?;
335 suite.open_body(&bytes[CHAN_HEADER_LEN..])
336}
337
338thread_local! {
339 /// The suite sealing outbound / opening inbound frames on this thread. `None` (the
340 /// default) means the channel is disengaged: [`seal_active`] / [`open_active`] are pure
341 /// pass-throughs, so a program that never activates a suite is byte-identical on the wire.
342 static ACTIVE_SUITE: std::cell::Cell<Option<u16>> = const { std::cell::Cell::new(None) };
343}
344
345/// The suite active for seal/open on this thread, if any.
346pub fn active_suite() -> Option<u16> {
347 ACTIVE_SUITE.with(|s| s.get())
348}
349
350/// Run `f` with `suite` active for seal/open on this thread, restoring the prior suite after
351/// (mirrors `marshal`'s scoped wire-knob setters).
352pub fn with_suite<T>(suite: Option<u16>, f: impl FnOnce() -> T) -> T {
353 let prev = ACTIVE_SUITE.with(|s| s.replace(suite));
354 let out = f();
355 ACTIVE_SUITE.with(|s| s.set(prev));
356 out
357}
358
359/// A keyed, stateful crypto session installed for the live send/receive path. Unlike the stateless
360/// [`Suite`] registry, a session carries per-direction key/pad material and may **fail closed** on
361/// seal — a one-time pad can run out. Both the keyed [`PqSuite`] and the [`super::pnp`] one-time pad
362/// plug in here, so [`seal_active_checked`] / [`open_active`] stay suite-agnostic.
363pub trait ActiveSession {
364 /// Seal outbound bytes, or `None` to fail closed — the caller must then refuse to send, never
365 /// transmit the plaintext instead.
366 fn seal(&self, bytes: &[u8]) -> Option<Vec<u8>>;
367 /// Open inbound bytes, or `None` on a tampered / foreign / replayed frame.
368 fn open(&self, bytes: &[u8]) -> Option<Vec<u8>>;
369}
370
371thread_local! {
372 /// The keyed session sealing outbound / opening inbound frames on this thread, if installed. It
373 /// takes precedence over [`ACTIVE_SUITE`]; `None` (the default) leaves the stateless path — and
374 /// so the wire — unchanged for programs that never engage a session.
375 static ACTIVE_SESSION: std::cell::RefCell<Option<std::rc::Rc<dyn ActiveSession>>> =
376 const { std::cell::RefCell::new(None) };
377}
378
379/// The keyed session active for seal/open on this thread, if any.
380pub fn active_session() -> Option<std::rc::Rc<dyn ActiveSession>> {
381 ACTIVE_SESSION.with(|s| s.borrow().clone())
382}
383
384/// Install `session` as the active keyed session on this thread, returning the prior one. The live
385/// [`seal_active_checked`] / [`open_active`] path then routes through it until it is replaced/cleared.
386pub fn install_session(
387 session: Option<std::rc::Rc<dyn ActiveSession>>,
388) -> Option<std::rc::Rc<dyn ActiveSession>> {
389 ACTIVE_SESSION.with(|s| std::mem::replace(&mut *s.borrow_mut(), session))
390}
391
392/// Run `f` with `session` active for seal/open on this thread, restoring the prior session after
393/// (mirrors [`with_suite`]).
394pub fn with_session<T>(
395 session: Option<std::rc::Rc<dyn ActiveSession>>,
396 f: impl FnOnce() -> T,
397) -> T {
398 let prev = install_session(session);
399 let out = f();
400 install_session(prev);
401 out
402}
403
404/// Seal `bytes` under the active suite; with no active suite, return them unchanged so the
405/// wire stays byte-identical for non-secure programs. (Stateless path only — the keyed, possibly
406/// fail-closing session path is [`seal_active_checked`].)
407pub fn seal_active(bytes: Vec<u8>) -> Vec<u8> {
408 match active_suite() {
409 Some(id) => seal(id, &bytes),
410 None => bytes,
411 }
412}
413
414/// Seal `bytes` for the live send path: through the active keyed [`ActiveSession`] if installed
415/// (which may **fail closed**, returning `None` — e.g. a one-time pad is exhausted), else through the
416/// active stateless suite, else pass-through. A `None` result is the fail-closed signal the caller
417/// MUST surface as a send error — never transmit the plaintext instead.
418pub fn seal_active_checked(bytes: Vec<u8>) -> Option<Vec<u8>> {
419 match active_session() {
420 Some(session) => session.seal(&bytes),
421 None => Some(seal_active(bytes)),
422 }
423}
424
425/// Open an inbound frame under the active keyed session if installed, else the active suite;
426/// `None` on a tampered/foreign frame (the caller drops it). With neither engaged, pass `bytes`
427/// through so the wire stays byte-identical for non-secure programs.
428pub fn open_active(bytes: Vec<u8>) -> Option<Vec<u8>> {
429 if let Some(session) = active_session() {
430 return session.open(&bytes);
431 }
432 match active_suite() {
433 Some(_) => open(&bytes),
434 None => Some(bytes),
435 }
436}
437
438#[cfg(test)]
439#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/concurrency/channel/tests.rs"]
440mod tests;