khive_wire_protocol/handshake.rs
1//! The server-side handshake state machine (ADR-137, "Shared protocol crate
2//! and handshake").
3//!
4//! The ADR requires: *"the first application frame on every connection must
5//! be a `handshake` carrying a protocol version; the answer is
6//! `handshake_ack` naming the accepted version, or the wire error
7//! `unsupported_version` followed by connection close, before it accepts
8//! any request or subscription frame."* [`HandshakeGate`] is a type the
9//! server side feeds every inbound frame through: it is impossible to
10//! obtain a [`Frame::Request`]/`Subscribe`/etc. admission decision without
11//! having first driven a successful handshake through it, so "no request
12//! frame before handshake completes" is enforced by the gate's API shape
13//! rather than left to every call site to remember.
14
15use crate::error::WireErrorCode;
16use crate::frame::Frame;
17use crate::version::{ProtocolVersion, SupportedVersions};
18
19/// Why a gate moved to the terminal [`State::Closed`]. Stored at the
20/// moment of closure so the Closed-state rejection can report the ACTUAL
21/// cause instead of always blaming a handshake failure.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum CloseReason {
24 /// The handshake named no mutually supported version
25 /// ([`HandshakeOutcome::Rejected`]).
26 UnsupportedVersion,
27 /// A non-`handshake` frame arrived before the handshake completed.
28 NonHandshakeFirst,
29 /// A second `handshake` arrived after one already completed.
30 DuplicateHandshake,
31 /// A server→client-only frame kind arrived on this inbound gate.
32 ServerOnlyKind,
33}
34
35impl CloseReason {
36 /// The human-readable cause used in the Closed-state rejection message.
37 const fn phrase(self) -> &'static str {
38 match self {
39 CloseReason::UnsupportedVersion => "a rejected handshake (unsupported version)",
40 CloseReason::NonHandshakeFirst => "a frame before the handshake",
41 CloseReason::DuplicateHandshake => "a duplicate handshake",
42 CloseReason::ServerOnlyKind => "a server-to-client frame on an inbound gate",
43 }
44 }
45}
46
47/// The gate's current state.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49enum State {
50 /// No handshake has completed yet on this connection.
51 AwaitingHandshake,
52 /// A handshake completed; the connection speaks this version.
53 Completed(ProtocolVersion),
54 /// A connection-terminal outcome was already produced (rejected
55 /// handshake, or a protocol violation). The gate accepts no further
56 /// frames; the carried reason records what closed it.
57 Closed(CloseReason),
58}
59
60/// The outcome of feeding one frame to [`HandshakeGate::admit`].
61#[derive(Debug, Clone, PartialEq)]
62pub enum HandshakeOutcome {
63 /// The frame was a valid `handshake` naming a mutually supported
64 /// version. Send the returned `handshake_ack` frame; the connection may
65 /// now accept `request`/`subscribe`/`unsubscribe`/`cancel` frames.
66 Accepted {
67 ack: Frame,
68 version: ProtocolVersion,
69 },
70 /// The frame was a `handshake` naming no mutually supported version.
71 /// Send the returned `error` frame (`unsupported_version`), then close
72 /// the connection.
73 Rejected { error: Frame },
74 /// The connection already completed its handshake, this frame was not
75 /// a handshake attempt, and its kind is one a client may send to the
76 /// server; it is admitted for ordinary dispatch.
77 Admitted,
78}
79
80/// A protocol violation the gate detected outside the handshake itself:
81/// a non-`handshake` frame arriving before handshake completion, a second
82/// `handshake` frame arriving after completion, or a server→client-only
83/// frame kind arriving on the server's INBOUND gate after completion.
84///
85/// ADR-137 does not name a specific wire error code for either violation;
86/// this crate maps both to [`WireErrorCode::MalformedFrame`] (connection
87/// grammar violation) — see the crate documentation's "Contract choices the
88/// ADR did not fix" note.
89#[derive(Debug, Clone, PartialEq)]
90pub struct HandshakeSequenceError {
91 pub error: Box<Frame>,
92}
93
94impl HandshakeSequenceError {
95 fn malformed(message: String) -> Self {
96 Self {
97 error: Box::new(Frame::Error {
98 id: None,
99 code: WireErrorCode::MalformedFrame,
100 message,
101 unrecognized_code: None,
102 }),
103 }
104 }
105}
106
107impl std::fmt::Display for HandshakeSequenceError {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 match self.error.as_ref() {
110 Frame::Error { code, message, .. } => {
111 write!(f, "handshake sequence rejected ({code}): {message}")
112 }
113 frame => write!(f, "handshake sequence rejected by {} frame", frame.kind()),
114 }
115 }
116}
117
118impl std::error::Error for HandshakeSequenceError {}
119
120/// Drives the per-connection handshake state machine.
121///
122/// Deliberately not `Clone`: the gate's entire guarantee is that its state
123/// only ever moves forward for one connection. A copy of a completed gate
124/// would admit requests on a connection that never handshook, and a copy of
125/// an earlier state could be restored after a violation closed the original.
126#[derive(Debug)]
127pub struct HandshakeGate {
128 state: State,
129 supported: SupportedVersions,
130}
131
132impl HandshakeGate {
133 /// A new gate for a connection that has not yet handshaken, accepting
134 /// [`SupportedVersions::current`].
135 pub fn new(supported: SupportedVersions) -> Self {
136 Self {
137 state: State::AwaitingHandshake,
138 supported,
139 }
140 }
141
142 /// True once a `handshake` has been accepted.
143 pub fn is_complete(&self) -> bool {
144 matches!(self.state, State::Completed(_))
145 }
146
147 /// The accepted protocol version, once the handshake has completed.
148 pub fn accepted_version(&self) -> Option<ProtocolVersion> {
149 match self.state {
150 State::Completed(v) => Some(v),
151 _ => None,
152 }
153 }
154
155 /// Feed one inbound frame to the gate.
156 ///
157 /// - Before completion, a [`Frame::Handshake`] is evaluated against the
158 /// configured [`SupportedVersions`] and produces
159 /// [`HandshakeOutcome::Accepted`] or [`HandshakeOutcome::Rejected`].
160 /// - Before completion, any other frame kind is a sequence violation
161 /// (`Err(`[`HandshakeSequenceError`]`)`) — the caller must never have
162 /// dispatched it to `request`/`subscribe`/etc. handling; this call is
163 /// what makes that guarantee enforceable rather than conventional.
164 /// - After completion, client→server frames
165 /// ([`crate::frame::CLIENT_TO_SERVER_KINDS`] minus `handshake`) are
166 /// admitted ([`HandshakeOutcome::Admitted`]). A stray second
167 /// `handshake` is a sequence violation (the ADR fixes the handshake
168 /// to "the first application frame"), and a server→client-only kind
169 /// (`response`, `handshake_ack`, `subscribe_ack`, `unsubscribe_ack`,
170 /// `event`) is a direction violation — it can never be a legal
171 /// inbound frame on this gate — and closes the gate like any other
172 /// protocol violation.
173 pub fn admit(&mut self, frame: &Frame) -> Result<HandshakeOutcome, HandshakeSequenceError> {
174 match (&self.state, frame) {
175 (State::AwaitingHandshake, Frame::Handshake { version }) => {
176 if self.supported.contains(*version) {
177 self.state = State::Completed(*version);
178 Ok(HandshakeOutcome::Accepted {
179 ack: Frame::HandshakeAck { version: *version },
180 version: *version,
181 })
182 } else {
183 self.state = State::Closed(CloseReason::UnsupportedVersion);
184 Ok(HandshakeOutcome::Rejected {
185 error: Frame::Error {
186 id: None,
187 code: WireErrorCode::UnsupportedVersion,
188 message: format!(
189 "unsupported protocol version {version}; server supports [{}, {}]",
190 self.supported.min(),
191 self.supported.max()
192 ),
193 unrecognized_code: None,
194 },
195 })
196 }
197 }
198 (State::AwaitingHandshake, _) => {
199 self.state = State::Closed(CloseReason::NonHandshakeFirst);
200 Err(HandshakeSequenceError::malformed(format!(
201 "expected \"handshake\" as the first frame, got {:?}",
202 frame.kind()
203 )))
204 }
205 (State::Completed(_), Frame::Handshake { .. }) => {
206 self.state = State::Closed(CloseReason::DuplicateHandshake);
207 Err(HandshakeSequenceError::malformed(
208 "handshake already completed on this connection".to_string(),
209 ))
210 }
211 (State::Completed(_), _) => {
212 // The gate is the server-side inbound admission point, so a
213 // frame whose kind is only ever sent server→client is a
214 // direction violation (frame grammar) no matter when it
215 // arrives: reject it like any other grammar violation.
216 if crate::frame::CLIENT_TO_SERVER_KINDS.contains(&frame.kind()) {
217 Ok(HandshakeOutcome::Admitted)
218 } else {
219 self.state = State::Closed(CloseReason::ServerOnlyKind);
220 Err(HandshakeSequenceError::malformed(format!(
221 "frame kind {:?} is server-to-client only; a server never accepts it as an inbound frame",
222 frame.kind()
223 )))
224 }
225 }
226 (State::Closed(reason), _) => Err(HandshakeSequenceError::malformed(format!(
227 "connection already closed by {}",
228 reason.phrase()
229 ))),
230 }
231 }
232}
233
234impl Default for HandshakeGate {
235 fn default() -> Self {
236 Self::new(SupportedVersions::current())
237 }
238}
239
240#[cfg(test)]
241#[path = "handshake_tests.rs"]
242mod tests;