Skip to main content

khive_wire_protocol/
client_handshake.rs

1//! Client-side handshake admission, per ADR-137 Amendment 1, Decisions 5 and 6.
2//!
3//! A transport records the version it actually sent, then feeds every decoded
4//! inbound frame through this gate before handling it. This module performs no
5//! I/O, and it does not replace the codec's frame-field validation.
6
7use crate::error::{TerminalScope, WireErrorCode};
8use crate::frame::Frame;
9use crate::handshake::HandshakeSequenceError;
10use crate::version::ProtocolVersion;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13enum CloseReason {
14    UnsolicitedFrame,
15    MismatchedAcknowledgment,
16    UnexpectedDuringHandshake,
17    WrongDirectionOrRepeatedHandshake,
18    InvalidErrorEnvelope,
19    ServerTerminalError,
20}
21
22impl CloseReason {
23    const fn phrase(self) -> &'static str {
24        match self {
25            Self::UnsolicitedFrame => "an unsolicited frame before a handshake was sent",
26            Self::MismatchedAcknowledgment => "an acknowledgment of a version that was not offered",
27            Self::UnexpectedDuringHandshake => "an unexpected frame during the handshake",
28            Self::WrongDirectionOrRepeatedHandshake => {
29                "a direction or repeated-handshake violation"
30            }
31            Self::InvalidErrorEnvelope => "an invalid server error frame",
32            Self::ServerTerminalError => "a connection-terminal server error",
33        }
34    }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38enum State {
39    Fresh,
40    Outstanding(ProtocolVersion),
41    Completed(ProtocolVersion),
42    Closed(CloseReason),
43}
44
45/// A local misuse of [`ClientHandshakeGate::record_handshake_sent`].
46///
47/// These errors do not carry a wire error code or close a connection: no inbound
48/// frame caused them, and the gate's state is unchanged.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
50pub enum ClientHandshakeStartError {
51    /// A conforming encoder cannot emit a handshake naming version zero.
52    #[error("cannot record a sent handshake for protocol version zero")]
53    VersionZero,
54    /// This connection already has an outstanding or completed handshake.
55    #[error("a handshake has already been sent on this connection")]
56    AlreadyStarted,
57    /// A terminal outcome already closed this gate.
58    #[error("the client handshake gate is permanently closed")]
59    Closed,
60}
61
62/// The result of admitting one decoded server frame.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum ClientHandshakeOutcome {
65    /// The acknowledgment matches the exact version the client offered.
66    Completed { version: ProtocolVersion },
67    /// A server application frame was admitted after handshake completion.
68    Admitted,
69    /// A connection-terminal server error was admitted and closed the gate.
70    ///
71    /// The caller must surface the original inbound [`Frame::Error`] and close
72    /// the transport without fallback. The borrowed frame passed to `admit`
73    /// remains available, including its original code and message.
74    ServerTerminated,
75}
76
77/// Enforces the inbound handshake sequence and frame direction for one client
78/// connection.
79///
80/// Record the exact offered version only after the transport successfully sends
81/// its handshake. Before that, every inbound frame is unsolicited. An exact
82/// acknowledgment completes the handshake; a server connection-terminal error
83/// is surfaced without fallback. Every sequence or direction violation closes
84/// the gate permanently with an id-less `malformed_frame`.
85///
86/// Deliberately not `Clone`: copying an earlier state must not allow a terminal
87/// connection to resume. There is no reset or unchecked-completion operation.
88#[derive(Debug)]
89pub struct ClientHandshakeGate {
90    state: State,
91}
92
93impl ClientHandshakeGate {
94    /// A fresh connection on which no handshake has been sent.
95    pub fn new() -> Self {
96        Self {
97            state: State::Fresh,
98        }
99    }
100
101    /// Record the exact version in the handshake the transport just sent.
102    ///
103    /// The caller constructs, encodes and writes its existing [`Frame::Handshake`]
104    /// first, then records that version before reading inbound frames. This
105    /// method does no I/O. Preparation, encoding or write failure must not call
106    /// it; discard the failed connection instead. A local error leaves the state
107    /// unchanged. The caller selects a version whose grammar it implements,
108    /// normally [`crate::CURRENT_VERSION`]; this gate adds no range negotiation.
109    pub fn record_handshake_sent(
110        &mut self,
111        offered: ProtocolVersion,
112    ) -> Result<(), ClientHandshakeStartError> {
113        match self.state {
114            State::Fresh => {
115                if offered.get() == 0 {
116                    return Err(ClientHandshakeStartError::VersionZero);
117                }
118                self.state = State::Outstanding(offered);
119                Ok(())
120            }
121            State::Outstanding(_) | State::Completed(_) => {
122                Err(ClientHandshakeStartError::AlreadyStarted)
123            }
124            State::Closed(_) => Err(ClientHandshakeStartError::Closed),
125        }
126    }
127
128    /// Whether this connection currently has a completed handshake.
129    pub fn is_complete(&self) -> bool {
130        matches!(self.state, State::Completed(_))
131    }
132
133    /// The outstanding offer, before its matching acknowledgment arrives.
134    pub fn offered_version(&self) -> Option<ProtocolVersion> {
135        match self.state {
136            State::Outstanding(version) => Some(version),
137            _ => None,
138        }
139    }
140
141    /// The accepted version while the connection remains completed and usable.
142    pub fn accepted_version(&self) -> Option<ProtocolVersion> {
143        match self.state {
144            State::Completed(version) => Some(version),
145            _ => None,
146        }
147    }
148
149    /// Whether a protocol violation or admitted server error permanently closed
150    /// this gate.
151    pub fn is_closed(&self) -> bool {
152        matches!(self.state, State::Closed(_))
153    }
154
155    /// Admit one already-decoded inbound frame, before the caller handles it.
156    ///
157    /// A fresh gate rejects every kind. With an offer outstanding, only an exact
158    /// acknowledgment or a connection-terminal server error is admissible. After
159    /// completion, server application kinds are admitted; another acknowledgment
160    /// or any client-to-server kind is a violation. An admitted terminal error
161    /// yields [`ClientHandshakeOutcome::ServerTerminated`], leaving the original
162    /// frame available to surface before closing the transport.
163    ///
164    /// The codec remains role-agnostic and owns field/grammar validation. Every
165    /// sequence rejection here is id-less `malformed_frame` and permanently
166    /// closes the gate; even a later otherwise-valid frame cannot recover it.
167    pub fn admit(
168        &mut self,
169        frame: &Frame,
170    ) -> Result<ClientHandshakeOutcome, HandshakeSequenceError> {
171        match (self.state, frame) {
172            (State::Fresh, _) => self.reject(
173                CloseReason::UnsolicitedFrame,
174                format!("received {:?} before the client sent a handshake", frame.kind()),
175            ),
176            (State::Outstanding(offered), Frame::HandshakeAck { version }) => {
177                if *version == offered {
178                    self.state = State::Completed(offered);
179                    Ok(ClientHandshakeOutcome::Completed { version: offered })
180                } else {
181                    self.reject(
182                        CloseReason::MismatchedAcknowledgment,
183                        format!("handshake acknowledgment names version {version}, but the client offered {offered}"),
184                    )
185                }
186            }
187            (State::Completed(_), Frame::Error { id: None, unrecognized_code: Some(_), .. }) => self.reject(
188                CloseReason::InvalidErrorEnvelope,
189                "a server error with an unrecognized code must identify an operation".to_string(),
190            ),
191            (State::Completed(_), Frame::Error { id: Some(_), code, .. })
192                if code.terminal_scope() == TerminalScope::Connection =>
193            {
194                self.reject(
195                    CloseReason::InvalidErrorEnvelope,
196                    "a connection-terminal server error must not identify an operation".to_string(),
197                )
198            }
199            (State::Completed(_), Frame::Error { id: None, code, .. })
200                if code.terminal_scope() == TerminalScope::Request =>
201            {
202                self.reject(
203                    CloseReason::InvalidErrorEnvelope,
204                    "a request-terminal server error must identify an operation".to_string(),
205                )
206            }
207            (State::Outstanding(_) | State::Completed(_), Frame::Error { id: None, code, .. })
208                if code.terminal_scope() == TerminalScope::Connection =>
209            {
210                self.state = State::Closed(CloseReason::ServerTerminalError);
211                Ok(ClientHandshakeOutcome::ServerTerminated)
212            }
213            (State::Outstanding(_), _) => self.reject(
214                CloseReason::UnexpectedDuringHandshake,
215                format!("expected the offered-version acknowledgment or a connection-terminal error, got {:?}", frame.kind()),
216            ),
217            (State::Completed(_), Frame::Response { .. }
218                | Frame::Error { .. }
219                | Frame::SubscribeAck { .. }
220                | Frame::UnsubscribeAck { .. }
221                | Frame::Event { .. }) => Ok(ClientHandshakeOutcome::Admitted),
222            (State::Completed(_), _) => self.reject(
223                CloseReason::WrongDirectionOrRepeatedHandshake,
224                format!("frame kind {:?} is not admissible at a client after handshake completion", frame.kind()),
225            ),
226            (State::Closed(reason), _) => Err(sequence_error(format!(
227                "connection already closed by {}",
228                reason.phrase()
229            ))),
230        }
231    }
232
233    fn reject(
234        &mut self,
235        reason: CloseReason,
236        message: String,
237    ) -> Result<ClientHandshakeOutcome, HandshakeSequenceError> {
238        self.state = State::Closed(reason);
239        Err(sequence_error(message))
240    }
241}
242
243fn sequence_error(message: String) -> HandshakeSequenceError {
244    HandshakeSequenceError {
245        error: Box::new(Frame::Error {
246            id: None,
247            code: WireErrorCode::MalformedFrame,
248            message,
249            unrecognized_code: None,
250        }),
251    }
252}
253
254impl Default for ClientHandshakeGate {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260#[cfg(test)]
261#[path = "client_handshake_tests.rs"]
262mod tests;