Skip to main content

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 std::fmt::Display for HandshakeSequenceError {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        match self.error.as_ref() {
97            Frame::Error { code, message, .. } => {
98                write!(f, "handshake sequence rejected ({code}): {message}")
99            }
100            frame => write!(f, "handshake sequence rejected by {} frame", frame.kind()),
101        }
102    }
103}
104
105impl std::error::Error for HandshakeSequenceError {}
106
107/// Drives the per-connection handshake state machine.
108///
109/// Deliberately not `Clone`: the gate's entire guarantee is that its state
110/// only ever moves forward for one connection. A copy of a completed gate
111/// would admit requests on a connection that never handshook, and a copy of
112/// an earlier state could be restored after a violation closed the original.
113#[derive(Debug)]
114pub struct HandshakeGate {
115    state: State,
116    supported: SupportedVersions,
117}
118
119impl HandshakeGate {
120    /// A new gate for a connection that has not yet handshaken, accepting
121    /// [`SupportedVersions::current`].
122    pub fn new(supported: SupportedVersions) -> Self {
123        Self {
124            state: State::AwaitingHandshake,
125            supported,
126        }
127    }
128
129    /// True once a `handshake` has been accepted.
130    pub fn is_complete(&self) -> bool {
131        matches!(self.state, State::Completed(_))
132    }
133
134    /// The accepted protocol version, once the handshake has completed.
135    pub fn accepted_version(&self) -> Option<ProtocolVersion> {
136        match self.state {
137            State::Completed(v) => Some(v),
138            _ => None,
139        }
140    }
141
142    /// Feed one inbound frame to the gate.
143    ///
144    /// - Before completion, a [`Frame::Handshake`] is evaluated against the
145    ///   configured [`SupportedVersions`] and produces
146    ///   [`HandshakeOutcome::Accepted`] or [`HandshakeOutcome::Rejected`].
147    /// - Before completion, any other frame kind is a sequence violation
148    ///   (`Err(`[`HandshakeSequenceError`]`)`) — the caller must never have
149    ///   dispatched it to `request`/`subscribe`/etc. handling; this call is
150    ///   what makes that guarantee enforceable rather than conventional.
151    /// - After completion, client→server frames
152    ///   ([`crate::frame::CLIENT_TO_SERVER_KINDS`] minus `handshake`) are
153    ///   admitted ([`HandshakeOutcome::Admitted`]). A stray second
154    ///   `handshake` is a sequence violation (the ADR fixes the handshake
155    ///   to "the first application frame"), and a server→client-only kind
156    ///   (`response`, `handshake_ack`, `subscribe_ack`, `unsubscribe_ack`,
157    ///   `event`) is a direction violation — it can never be a legal
158    ///   inbound frame on this gate — and closes the gate like any other
159    ///   protocol violation.
160    pub fn admit(&mut self, frame: &Frame) -> Result<HandshakeOutcome, HandshakeSequenceError> {
161        match (&self.state, frame) {
162            (State::AwaitingHandshake, Frame::Handshake { version }) => {
163                if self.supported.contains(*version) {
164                    self.state = State::Completed(*version);
165                    Ok(HandshakeOutcome::Accepted {
166                        ack: Frame::HandshakeAck { version: *version },
167                        version: *version,
168                    })
169                } else {
170                    self.state = State::Closed(CloseReason::UnsupportedVersion);
171                    Ok(HandshakeOutcome::Rejected {
172                        error: Frame::Error {
173                            id: None,
174                            code: WireErrorCode::UnsupportedVersion,
175                            message: format!(
176                                "unsupported protocol version {version}; server supports [{}, {}]",
177                                self.supported.min(),
178                                self.supported.max()
179                            ),
180                            unrecognized_code: None,
181                        },
182                    })
183                }
184            }
185            (State::AwaitingHandshake, _) => {
186                self.state = State::Closed(CloseReason::NonHandshakeFirst);
187                Err(HandshakeSequenceError {
188                    error: Box::new(Frame::Error {
189                        id: None,
190                        code: WireErrorCode::MalformedFrame,
191                        message: format!(
192                            "expected \"handshake\" as the first frame, got {:?}",
193                            frame.kind()
194                        ),
195                        unrecognized_code: None,
196                    }),
197                })
198            }
199            (State::Completed(_), Frame::Handshake { .. }) => {
200                self.state = State::Closed(CloseReason::DuplicateHandshake);
201                Err(HandshakeSequenceError {
202                    error: Box::new(Frame::Error {
203                        id: None,
204                        code: WireErrorCode::MalformedFrame,
205                        message: "handshake already completed on this connection".to_string(),
206                        unrecognized_code: None,
207                    }),
208                })
209            }
210            (State::Completed(_), _) => {
211                // The gate is the server-side inbound admission point, so a
212                // frame whose kind is only ever sent server→client is a
213                // direction violation (frame grammar) no matter when it
214                // arrives: reject it like any other grammar violation.
215                if crate::frame::CLIENT_TO_SERVER_KINDS.contains(&frame.kind()) {
216                    Ok(HandshakeOutcome::Admitted)
217                } else {
218                    self.state = State::Closed(CloseReason::ServerOnlyKind);
219                    Err(HandshakeSequenceError {
220                        error: Box::new(Frame::Error {
221                            id: None,
222                            code: WireErrorCode::MalformedFrame,
223                            message: format!(
224                                "frame kind {:?} is server-to-client only; a server never accepts it as an inbound frame",
225                                frame.kind()
226                            ),
227                            unrecognized_code: None,
228                        }),
229                    })
230                }
231            }
232            (State::Closed(reason), _) => Err(HandshakeSequenceError {
233                error: Box::new(Frame::Error {
234                    id: None,
235                    code: WireErrorCode::MalformedFrame,
236                    message: format!("connection already closed by {}", reason.phrase()),
237                    unrecognized_code: None,
238                }),
239            }),
240        }
241    }
242}
243
244impl Default for HandshakeGate {
245    fn default() -> Self {
246        Self::new(SupportedVersions::current())
247    }
248}
249
250#[cfg(test)]
251#[path = "handshake_tests.rs"]
252mod tests;