Skip to main content

qualia_core_db/net/qdnf/session/handshake/
mod.rs

1//! QSession handshake binding. No 0-RTT application data.
2
3// Endpoint-v1 currently requires the native managed-key owner.
4#[cfg(not(target_arch = "wasm32"))]
5pub mod endpoint;
6mod fragmented;
7mod hello;
8
9use crate::crypto::network::transcript::Transcript;
10use crate::net::qdnf::authority::{
11    admit_service, ExecutionPermit, InstalledSessionKeys, PolicyOutcome,
12};
13use crate::net::qdnf::crypto::finished::finished_mac;
14use crate::net::qdnf::errors::QdnfError;
15use crate::net::qdnf::types::{OperationId, StrongDigest};
16
17pub use fragmented::{
18    handshake_over_fragments, hello_fragment_payload_mtu, send_hello_fragments, FragmentedHandshake,
19};
20pub use hello::{
21    encode_client_hello_with_certs, encode_server_hello_with_certs, CLIENT_HELLO_WIRE_LEN,
22    SERVER_HELLO_WIRE_LEN,
23};
24
25#[repr(u8)]
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum SessionState {
28    Idle = 0,
29    Resolving = 1,
30    RouteSelected = 2,
31    LinkAuthenticated = 3,
32    PersistentTargetVerified = 4,
33    CapabilityNegotiated = 5,
34    Active = 6,
35    Draining = 7,
36    Closed = 8,
37}
38
39/// Application session binding. Fields are private; Active requires a permit.
40///
41/// ```compile_fail
42/// let _ = qualia_core_db::net::qdnf::session::SessionBinding {
43///     operation: todo!(),
44///     target: todo!(),
45///     dni_digest: todo!(),
46///     purpose: todo!(),
47///     policy: todo!(),
48///     state: todo!(),
49/// };
50/// ```
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub struct SessionBinding {
53    operation: OperationId,
54    target: StrongDigest,
55    dni_digest: StrongDigest,
56    purpose: StrongDigest,
57    policy: PolicyOutcome,
58    state: SessionState,
59}
60
61impl SessionBinding {
62    /// Builds `SessionBinding` from `permit`.
63    pub fn from_permit(
64        permit: &ExecutionPermit,
65        keys: &InstalledSessionKeys,
66        now_unix: u64,
67    ) -> Result<Self, QdnfError> {
68        permit.current_at(now_unix)?;
69        permit.require_keys(keys)?;
70        if permit.operation().is_zero()
71            || permit.recipient().is_zero()
72            || permit.purpose().is_zero()
73        {
74            return Err(QdnfError::Unauthorized);
75        }
76        Ok(Self {
77            operation: permit.operation(),
78            target: permit.recipient(),
79            dni_digest: permit.instrument(),
80            purpose: permit.purpose(),
81            policy: PolicyOutcome::Allow,
82            state: SessionState::Active,
83        })
84    }
85
86    /// Component-test constructor. Rejects zero identity and forged Active+Allow
87    /// unless `policy` is not Allow or `state` is not Active.
88    #[cfg(test)]
89    pub(crate) fn recorded(
90        operation: OperationId,
91        target: StrongDigest,
92        dni_digest: StrongDigest,
93        purpose: StrongDigest,
94        policy: PolicyOutcome,
95        state: SessionState,
96    ) -> Result<Self, QdnfError> {
97        if state == SessionState::Active && policy == PolicyOutcome::Allow {
98            return Err(QdnfError::Unauthorized);
99        }
100        Ok(Self {
101            operation,
102            target,
103            dni_digest,
104            purpose,
105            policy,
106            state,
107        })
108    }
109
110    #[inline]
111    /// Bound operation.
112    pub const fn operation(self) -> OperationId {
113        self.operation
114    }
115
116    #[inline]
117    /// Target digest.
118    pub const fn target(self) -> StrongDigest {
119        self.target
120    }
121
122    #[inline]
123    /// DNI digest.
124    pub const fn dni_digest(self) -> StrongDigest {
125        self.dni_digest
126    }
127
128    #[inline]
129    /// Purpose digest.
130    pub const fn purpose(self) -> StrongDigest {
131        self.purpose
132    }
133
134    #[inline]
135    /// Policy outcome.
136    pub const fn policy(self) -> PolicyOutcome {
137        self.policy
138    }
139
140    #[inline]
141    /// Session state.
142    pub const fn state(self) -> SessionState {
143        self.state
144    }
145
146    /// `Ok(())` when the session admits an application.
147    pub fn admit_application(&self) -> Result<(), QdnfError> {
148        if self.state != SessionState::Active {
149            return Err(QdnfError::Unauthorized);
150        }
151        if self.operation.is_zero() || self.target.is_zero() || self.purpose.is_zero() {
152            return Err(QdnfError::Unauthorized);
153        }
154        admit_service(self.policy, true)
155    }
156
157    #[cfg(test)]
158    /// Test-only session binding fixture.
159    pub(crate) fn test_fixture(
160        operation: OperationId,
161        target: StrongDigest,
162        dni_digest: StrongDigest,
163        purpose: StrongDigest,
164        policy: PolicyOutcome,
165        state: SessionState,
166    ) -> Self {
167        Self {
168            operation,
169            target,
170            dni_digest,
171            purpose,
172            policy,
173            state,
174        }
175    }
176}
177
178/// Binds the session to the transcript.
179pub fn bind_session_transcript(
180    path_digest: &StrongDigest,
181    target: &StrongDigest,
182    purpose: &StrongDigest,
183) -> Result<StrongDigest, QdnfError> {
184    let mut t = Transcript::new();
185    t.append(b"path", &path_digest.0)?;
186    t.append(b"target", &target.0)?;
187    t.append(b"purpose", &purpose.0)?;
188    t.append(b"0rtt", &[0])?;
189    Ok(t.digest())
190}
191
192/// Confirms the Finished MAC.
193pub fn confirm_finished(
194    secret: &[u8; 32],
195    digest: &StrongDigest,
196    initiator_to_responder: bool,
197) -> Result<StrongDigest, QdnfError> {
198    finished_mac(secret, digest, initiator_to_responder)
199}
200
201pub const ZERO_RTT_APPLICATION: crate::net::qdnf::crypto::HandshakeState =
202    crate::net::qdnf::crypto::HandshakeState::Idle;
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn inactive_session_cannot_deliver() {
210        let s = SessionBinding::recorded(
211            OperationId([1u8; 16]),
212            StrongDigest([2u8; 48]),
213            StrongDigest([3u8; 48]),
214            StrongDigest([4u8; 48]),
215            PolicyOutcome::Allow,
216            SessionState::LinkAuthenticated,
217        )
218        .unwrap();
219        assert_eq!(s.admit_application(), Err(QdnfError::Unauthorized));
220    }
221
222    #[test]
223    fn recorded_cannot_mint_active_allow() {
224        assert_eq!(
225            SessionBinding::recorded(
226                OperationId([1u8; 16]),
227                StrongDigest([2u8; 48]),
228                StrongDigest([3u8; 48]),
229                StrongDigest([4u8; 48]),
230                PolicyOutcome::Allow,
231                SessionState::Active,
232            ),
233            Err(QdnfError::Unauthorized)
234        );
235    }
236}