Skip to main content

qualia_core_db/net/peer/host/
exchange.rs

1//! Authorised protected IPC exchange. Public QPR must not copy plaintext.
2
3use super::{ControllerIdentity, NativePeer, PeerBuilder, CELL_BYTES_DEFAULT};
4use crate::net::peer::cells::host_owner::HostAdmission;
5use crate::net::qdnf::authority::{
6    binding_for_controllers, AuthorityOwner, ContactState, ExecutionPermit, InstalledSessionKeys,
7};
8use crate::net::qdnf::bearer::ipc::{ipc_pair, FRAME_CAP};
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::harness::oracles::wire::{require_protected, ProtectedView};
11use crate::net::qdnf::session::handshake::handshake_over_fragments;
12use crate::net::qdnf::types::{Generation, LinkId, ScopeEpoch};
13
14/// Authorised application payload ceiling (E04.5 / P2).
15pub const AUTHORISED_PAYLOAD_CAP: usize = 4096;
16
17/// Protected round-trip size. Equals [`AUTHORISED_PAYLOAD_CAP`] on local-ipc.
18pub const AUTHORISED_ROUNDTRIP_CAP: usize = AUTHORISED_PAYLOAD_CAP;
19
20/// Local-ipc MTU that fits 4096 + AEAD overhead + QFrame header.
21pub const AUTHORISED_IPC_MTU: u16 = FRAME_CAP as u16;
22
23/// Two native peers over `local-ipc-v1`, admitted from one [`HostAdmission`].
24///
25/// Each peer needs `cell_bytes`. If remaining host bytes cannot cover the
26/// second cell, this returns [`QdnfError::Capacity`].
27pub fn pair_ipc_cells(
28    host: &mut HostAdmission,
29    a_controller: &[u8],
30    b_controller: &[u8],
31    scope: ScopeEpoch,
32    mtu: u16,
33    cell_bytes: u64,
34) -> Result<(NativePeer, NativePeer), QdnfError> {
35    let a_id = ControllerIdentity::from_controller(a_controller)?;
36    let b_id = ControllerIdentity::from_controller(b_controller)?;
37    if a_id == b_id {
38        return Err(QdnfError::Conflict);
39    }
40    let need = cell_bytes.checked_mul(2).ok_or(QdnfError::Capacity)?;
41    if cell_bytes == 0 || host.remaining_host_bytes() < need {
42        return Err(QdnfError::Capacity);
43    }
44    let profile = HostAdmission::profile_for_bytes(cell_bytes)?;
45    let slot_a = host.admit_cell(profile, cell_bytes)?;
46    let slot_b = match host.admit_cell(profile, cell_bytes) {
47        Ok(s) => s,
48        Err(_) => {
49            let _ = host.release_cell(slot_a);
50            return Err(QdnfError::Capacity);
51        }
52    };
53    let (a_bearer, b_bearer) = match ipc_pair(scope, mtu) {
54        Ok(p) => p,
55        Err(e) => {
56            let _ = host.release_cell(slot_b);
57            let _ = host.release_cell(slot_a);
58            return Err(e);
59        }
60    };
61    let mut a_link = LinkId::ZERO;
62    a_link.0[0] = 1;
63    let mut b_link = LinkId::ZERO;
64    b_link.0[0] = 2;
65    let a = match PeerBuilder::new(a_controller, a_link, cell_bytes)
66        .and_then(|b| b.with_bearer_cell(a_bearer, Some(slot_a)))
67    {
68        Ok(p) => p,
69        Err(e) => {
70            let _ = host.release_cell(slot_b);
71            let _ = host.release_cell(slot_a);
72            return Err(e);
73        }
74    };
75    let b = match PeerBuilder::new(b_controller, b_link, cell_bytes)
76        .and_then(|b| b.with_bearer_cell(b_bearer, Some(slot_b)))
77    {
78        Ok(p) => p,
79        Err(e) => {
80            let mut a = a;
81            let _ = a.release_into_host(host);
82            let _ = host.release_cell(slot_b);
83            return Err(e);
84        }
85    };
86    Ok((a, b))
87}
88
89fn handshake_on_bearer(
90    a: &mut NativePeer,
91    b: &mut NativePeer,
92) -> Result<(InstalledSessionKeys, InstalledSessionKeys), QdnfError> {
93    let dest_b = b.locator();
94    let dest_a = a.locator();
95    let id_a = a.identity().digest();
96    let id_b = b.identity().digest();
97    let hs =
98        handshake_over_fragments(&mut a.bearer, &mut b.bearer, &dest_b, &dest_a, &id_a, &id_b)?;
99    if hs.keys.transcript_digest.is_zero() {
100        return Err(QdnfError::CryptoFailure);
101    }
102    if hs.client_fragments < 2 || hs.server_fragments < 2 {
103        return Err(QdnfError::Capacity);
104    }
105    let a_keys = InstalledSessionKeys::new(
106        Generation(1),
107        hs.keys.initiator_to_responder,
108        hs.keys.responder_to_initiator,
109        true,
110    )?;
111    let b_keys = InstalledSessionKeys::new(
112        Generation(1),
113        hs.keys.responder_to_initiator,
114        hs.keys.initiator_to_responder,
115        true,
116    )?;
117    Ok((a_keys, b_keys))
118}
119
120fn issue_permit(
121    owner: &mut AuthorityOwner,
122    local: &[u8],
123    remote: &[u8],
124    purpose: &[u8],
125    op: &[u8],
126    now: u64,
127) -> Result<ExecutionPermit, QdnfError> {
128    let binding = binding_for_controllers(local, remote, purpose, op)?;
129    let (_cred, _contact, handle) =
130        owner.install_grant(binding, now, now.saturating_add(3600), ContactState::Active)?;
131    owner.issue_permit(handle, binding, now, 4096)
132}
133
134/// Two peers constructed through one host owner exchange authorised protected data.
135pub fn authorised_ipc_stream_exchange(payload: &[u8]) -> Result<usize, QdnfError> {
136    authorised_ipc_stream_exchange_in(payload, CELL_BYTES_DEFAULT, AUTHORISED_IPC_MTU)
137}
138
139/// Same protected path, with the caller’s cell budget and bearer MTU.
140pub fn authorised_ipc_stream_exchange_in(
141    payload: &[u8],
142    cell_bytes: u64,
143    mtu: u16,
144) -> Result<usize, QdnfError> {
145    if payload.is_empty() || payload.len() > AUTHORISED_PAYLOAD_CAP {
146        return Err(QdnfError::Capacity);
147    }
148    let host_bytes = cell_bytes.checked_mul(2).ok_or(QdnfError::Capacity)?;
149    let mut host = HostAdmission::new(host_bytes)?;
150    let now = 1_700_000_000u64;
151    let scope = ScopeEpoch { scope: 1, epoch: 1 };
152    let a_did = b"did:q42:a";
153    let b_did = b"did:q42:b";
154    let purpose = b"q42:QSync/1";
155    let (mut a, mut b) = pair_ipc_cells(&mut host, a_did, b_did, scope, mtu, cell_bytes)?;
156    let result = authorised_exchange_peers(&mut a, &mut b, payload, purpose, now);
157    let _ = a.release_into_host(&mut host);
158    let _ = b.release_into_host(&mut host);
159    result
160}
161
162fn authorised_exchange_peers(
163    a: &mut NativePeer,
164    b: &mut NativePeer,
165    payload: &[u8],
166    purpose: &[u8],
167    now: u64,
168) -> Result<usize, QdnfError> {
169    let a_did = b"did:q42:a";
170    let b_did = b"did:q42:b";
171    a.announce(&b.locator(), now)?;
172    let _ = b.accept_announce_at(now)?;
173    b.announce(&a.locator(), now)?;
174    let _ = a.accept_announce_at(now)?;
175
176    let mut owner_a = AuthorityOwner::new();
177    let mut owner_b = AuthorityOwner::new();
178    let permit_a = issue_permit(&mut owner_a, a_did, b_did, purpose, b"op-a", now)?;
179    let permit_b = issue_permit(&mut owner_b, b_did, a_did, purpose, b"op-b", now)?;
180    let (keys_a, keys_b) = handshake_on_bearer(a, b)?;
181
182    a.activate_protected(permit_a, keys_a, now)?;
183    b.activate_protected(permit_b, keys_b, now)?;
184
185    let sealed = a.send_protected(&b.locator(), payload)?;
186    require_protected(ProtectedView {
187        wire_payload: sealed.as_slice(),
188        application: payload,
189    })?;
190    let mut out = [0u8; AUTHORISED_PAYLOAD_CAP];
191    let n = b.recv_protected(&mut out)?;
192    if &out[..n] != payload {
193        return Err(QdnfError::Malformed);
194    }
195    Ok(n)
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use crate::net::peer::cells::host_owner::extra_identity_multiplies_host_budget;
202
203    fn host_for_pair(cell_bytes: u64) -> HostAdmission {
204        let host_bytes = cell_bytes.saturating_mul(2).max(1);
205        HostAdmission::new(host_bytes).unwrap()
206    }
207
208    #[test]
209    fn builder_cell_bytes_zero_is_capacity() {
210        let link = LinkId::ZERO;
211        assert_eq!(
212            PeerBuilder::new(b"did:q42:a", link, 0).unwrap_err(),
213            QdnfError::Capacity
214        );
215    }
216
217    #[test]
218    fn pair_ipc_cells_uses_caller_cell_bytes() {
219        let scope = ScopeEpoch { scope: 1, epoch: 1 };
220        let mut host = host_for_pair(2048);
221        let (a, _b) =
222            pair_ipc_cells(&mut host, b"did:q42:a", b"did:q42:b", scope, 1280, 2048).unwrap();
223        assert_eq!(a.remaining_host_bytes(), 2048);
224        assert_eq!(host.occupied_cells(), 2);
225        let mut zero = HostAdmission::new(4096).unwrap();
226        assert_eq!(
227            pair_ipc_cells(&mut zero, b"did:q42:a", b"did:q42:b", scope, 1280, 0).unwrap_err(),
228            QdnfError::Capacity
229        );
230    }
231
232    #[test]
233    fn native_peer_pair_shares_one_host_admission() {
234        let scope = ScopeEpoch { scope: 1, epoch: 1 };
235        let cell = 2048u64;
236        let mut one = HostAdmission::new(cell).unwrap();
237        assert_eq!(
238            pair_ipc_cells(&mut one, b"did:q42:a", b"did:q42:b", scope, 1280, cell).unwrap_err(),
239            QdnfError::Capacity
240        );
241        assert_eq!(one.occupied_cells(), 0);
242        let mut two = HostAdmission::new(cell.saturating_mul(2)).unwrap();
243        let (a, b) =
244            pair_ipc_cells(&mut two, b"did:q42:a", b"did:q42:b", scope, 1280, cell).unwrap();
245        assert_eq!(two.occupied_cells(), 2);
246        assert_eq!(a.remaining_host_bytes(), cell);
247        assert_eq!(b.remaining_host_bytes(), cell);
248        assert!(!extra_identity_multiplies_host_budget());
249    }
250
251    #[test]
252    fn authorised_path_exchanges_full_payload_cap() {
253        // Packet-protection `open` body must be 4096 for this round-trip.
254        let mut app = [0u8; AUTHORISED_PAYLOAD_CAP];
255        let mut i = 0usize;
256        while i < app.len() {
257            app[i] = (i as u8).wrapping_add(0xA5);
258            i = i.saturating_add(1);
259        }
260        let n = authorised_ipc_stream_exchange(&app).unwrap();
261        assert_eq!(n, AUTHORISED_PAYLOAD_CAP);
262    }
263
264    #[test]
265    fn authorised_path_rejects_over_payload_cap() {
266        let app = [7u8; AUTHORISED_PAYLOAD_CAP + 1];
267        assert_eq!(
268            authorised_ipc_stream_exchange(&app).unwrap_err(),
269            QdnfError::Capacity
270        );
271    }
272
273    fn install_session(peer: &mut NativePeer, local: &[u8], remote: &[u8], tag: u8, now: u64) {
274        let mut owner = AuthorityOwner::new();
275        let binding = binding_for_controllers(local, remote, b"q42:QSync/1", &[b'o', tag]).unwrap();
276        let (_cred, _contact, handle) = owner
277            .install_grant(binding, now, now.saturating_add(3600), ContactState::Active)
278            .unwrap();
279        let permit = owner.issue_permit(handle, binding, now, 4096).unwrap();
280        let mut send = [tag.saturating_add(1); 32];
281        let mut recv = [tag.saturating_add(80); 32];
282        send[31] = 1;
283        recv[31] = 2;
284        let keys = InstalledSessionKeys::new(Generation(1), send, recv, true).unwrap();
285        peer.activate_protected(permit, keys, now).unwrap();
286    }
287
288    #[test]
289    fn send_without_announce_is_no_route() {
290        let scope = ScopeEpoch { scope: 1, epoch: 1 };
291        let mut host = host_for_pair(CELL_BYTES_DEFAULT);
292        let (mut a, b) = pair_ipc_cells(
293            &mut host,
294            b"did:q42:a",
295            b"did:q42:b",
296            scope,
297            1280,
298            CELL_BYTES_DEFAULT,
299        )
300        .unwrap();
301        let now = 1_700_000_000u64;
302        install_session(&mut a, b"did:q42:a", b"did:q42:b", 1, now);
303        assert_eq!(a.send_stream(&b.locator(), b"x"), Err(QdnfError::NoRoute));
304    }
305
306    #[test]
307    fn wrong_recipient_is_unauthorized() {
308        let scope = ScopeEpoch { scope: 1, epoch: 1 };
309        let mut host = host_for_pair(CELL_BYTES_DEFAULT);
310        let (mut a, mut b) = pair_ipc_cells(
311            &mut host,
312            b"did:q42:a",
313            b"did:q42:b",
314            scope,
315            1280,
316            CELL_BYTES_DEFAULT,
317        )
318        .unwrap();
319        let now = 1_700_000_000u64;
320        a.announce(&b.locator(), now).unwrap();
321        let _ = b.accept_announce_at(now).unwrap();
322        b.announce(&a.locator(), now).unwrap();
323        let _ = a.accept_announce_at(now).unwrap();
324        install_session(&mut a, b"did:q42:a", b"did:q42:b", 1, now);
325        let wrong = crate::net::qdnf::types::ObservedLocator::from_slice(&[0x99]).unwrap();
326        assert_eq!(
327            a.send_protected(&wrong, b"x").unwrap_err(),
328            QdnfError::Unauthorized
329        );
330    }
331
332    #[test]
333    fn stale_permit_does_not_activate() {
334        let scope = ScopeEpoch { scope: 1, epoch: 1 };
335        let mut host = host_for_pair(CELL_BYTES_DEFAULT);
336        let (mut a, _b) = pair_ipc_cells(
337            &mut host,
338            b"did:q42:a",
339            b"did:q42:b",
340            scope,
341            1280,
342            CELL_BYTES_DEFAULT,
343        )
344        .unwrap();
345        let now = 1_700_000_000u64;
346        let mut owner = AuthorityOwner::new();
347        let binding =
348            binding_for_controllers(b"did:q42:a", b"did:q42:b", b"q42:QSync/1", b"op-s").unwrap();
349        let (_cred, _contact, handle) = owner
350            .install_grant(binding, now, now.saturating_add(3600), ContactState::Active)
351            .unwrap();
352        let permit = owner.issue_permit(handle, binding, now, 4096).unwrap();
353        let keys = InstalledSessionKeys::new(Generation(1), [1u8; 32], [2u8; 32], true).unwrap();
354        let err = a
355            .activate_protected(permit, keys, now.saturating_add(3600))
356            .unwrap_err();
357        assert!(err == QdnfError::Expired || err == QdnfError::Unauthorized);
358    }
359}