Skip to main content

syncspin_core/
noise.rs

1//! Sendspin's Noise layer: `Noise_KKpsk2_25519_<cipher>_SHA256`.
2//!
3//! Every Sendspin connection is wrapped in Noise. The handshake follows the cleartext init
4//! exchange and precedes all application traffic:
5//!
6//! ```text
7//! client -> server  client/init      cleartext JSON, carries the client_id and the suite
8//! server -> client  server/init      cleartext JSON, carries the server_id
9//! server -> client  noise/handshake  Noise message 1, payload {"psk_id": .., "psk_category": ..}
10//! client -> server  noise/handshake  Noise message 2, payload {}
11//! ```
12//!
13//! The server is always the Noise initiator and the client the responder, whichever side opened
14//! the WebSocket. Both static public keys are known before the handshake (`KK`), and the
15//! pre-shared key is mixed in at the end of the second message (`psk2`). The Noise prologue is
16//! the exact concatenation of the `client/init` and `server/init` bytes as sent on the wire, so
17//! tampering with the cleartext exchange fails the handshake.
18//!
19//! This module carries both halves of the handshake - [`Responder`] for the client, [`Initiator`]
20//! for the server - plus the transport that follows it. It does not interpret handshake payloads;
21//! the session layer validates the `psk_id`/`psk_category` metadata. A handshake starts with the
22//! published Sentinel PSK, which is what an unpaired client uses and which provides no
23//! authentication on its own; the session layer reads the PSK metadata from message 1 and selects
24//! the matching key through [`Responder::set_psk`] or [`Initiator::set_psk`] before it answers.
25//!
26//! # Cipher suites
27//!
28//! The specification defines two suites and requires a server to support both. [`Suite`] is the
29//! set this build has; a name outside it is refused. The client picks the suite and announces it
30//! in `client/init`, so there is no negotiation to fall back from: a responder built for another
31//! suite than the one announced is an error, not a downgrade.
32
33use std::fmt;
34
35use anyhow::{anyhow, bail, Context, Result};
36use base64::engine::general_purpose::URL_SAFE_NO_PAD;
37use base64::Engine as _;
38use sha2::{Digest, Sha256};
39use x25519_dalek::{PublicKey, StaticSecret};
40
41/// A Sendspin cipher suite: the `<DH>_<cipher>_<hash>` tail of a Noise protocol name.
42///
43/// The specification lists both of these and requires a server to have both; a client announces
44/// the one it uses in `client/init`. [`Suite::ChaChaPoly`] is the default because it is the suite
45/// this library has always spoken and the one its pairing wrapping was pinned against.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
47pub enum Suite {
48    /// `25519_ChaChaPoly_SHA256`, the software-friendly suite and the default.
49    #[default]
50    ChaChaPoly,
51    /// `25519_AESGCM_SHA256`, the hardware-accelerated suite.
52    AesGcm,
53}
54
55impl Suite {
56    /// Every suite this implementation has, in the order the specification lists them.
57    pub const ALL: [Suite; 2] = [Suite::ChaChaPoly, Suite::AesGcm];
58
59    /// The name `client/init` carries in `suite`, which is also the `<DH>_<cipher>_<hash>`
60    /// tail of the Noise protocol name.
61    pub const fn wire_name(self) -> &'static str {
62        match self {
63            Suite::ChaChaPoly => "25519_ChaChaPoly_SHA256",
64            Suite::AesGcm => "25519_AESGCM_SHA256",
65        }
66    }
67
68    /// The full Noise protocol name: `Noise_KKpsk2_` followed by [`Suite::wire_name`].
69    pub const fn params(self) -> &'static str {
70        match self {
71            Suite::ChaChaPoly => "Noise_KKpsk2_25519_ChaChaPoly_SHA256",
72            Suite::AesGcm => "Noise_KKpsk2_25519_AESGCM_SHA256",
73        }
74    }
75
76    /// Parses the suite name a `client/init` announces.
77    ///
78    /// `None` means this build does not have the suite. There is deliberately no fallback to
79    /// [`Suite::default`]: a caller that cannot honour the announced suite must refuse it.
80    pub fn from_wire_name(name: &str) -> Option<Suite> {
81        Suite::ALL
82            .into_iter()
83            .find(|suite| suite.wire_name() == name)
84    }
85}
86
87impl fmt::Display for Suite {
88    /// Writes the wire name, so an error names the suite the peer announced.
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str(self.wire_name())
91    }
92}
93
94/// Noise protocol parameters of the default suite, [`Suite::ChaChaPoly`].
95pub const NOISE_PARAMS: &str = Suite::ChaChaPoly.params();
96
97/// The published Sentinel PSK, used whenever no paired PSK applies.
98///
99/// Its value is public, so it authenticates nothing. It exists so an unpaired client can
100/// connect before pairing establishes a private PSK.
101pub const SENTINEL_PSK: [u8; 32] = [
102    0x1b, 0x5e, 0x24, 0xdb, 0xc1, 0xae, 0xd9, 0x5f, 0xc2, 0xa5, 0xa3, 0x38, 0xa9, 0x0c, 0x05, 0xdf,
103    0x44, 0xbd, 0x10, 0xf5, 0xec, 0x1f, 0x4c, 0xd6, 0x6c, 0xbf, 0x86, 0x27, 0x27, 0x67, 0xb9, 0xd3,
104];
105
106/// The Sentinel PSK's published id, `psk_id_for(SENTINEL_PSK)`.
107pub const SENTINEL_PSK_ID: &str = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo";
108
109/// Maximum size of one Noise message, handshake or transport, including the authentication tag.
110///
111/// This is the Noise specification's limit; `snow` does not re-export the constant, so it is
112/// repeated here.
113pub const MAX_MESSAGE_LEN: usize = 65_535;
114
115/// Length of the authentication tag appended to every Noise transport ciphertext.
116pub const TAG_LEN: usize = 16;
117
118/// Largest plaintext that fits into one Noise transport message, including the leading binary
119/// message id byte.
120pub const MAX_PLAINTEXT_LEN: usize = MAX_MESSAGE_LEN - TAG_LEN;
121
122/// Label that Sendspin hashes together with a PSK to derive its id.
123const PSK_ID_LABEL: &[u8] = b"sendspin-psk-id-v1";
124
125/// Payload of Noise handshake message 2: the literal empty JSON object, not zero bytes.
126const HANDSHAKE_MESSAGE_2: &[u8] = b"{}";
127
128/// Unpadded base64url length of a 32-byte key.
129const KEY_CHARS: usize = 43;
130
131/// Derives a PSK id: `base64url(SHA-256("sendspin-psk-id-v1" || psk))`, without padding.
132///
133/// The id is what a server announces in `noise/handshake` message 1 so the client can select
134/// the matching PSK; it is a hash of the key and reveals nothing about its value.
135pub fn psk_id_for(psk: &[u8]) -> String {
136    let mut hasher = Sha256::new();
137    hasher.update(PSK_ID_LABEL);
138    hasher.update(psk);
139    URL_SAFE_NO_PAD.encode(hasher.finalize())
140}
141
142/// A long-lived X25519 keypair that identifies one side of a connection.
143///
144/// Sendspin uses the public key as the `client_id` or `server_id` and the secret key as the
145/// static key of the Noise handshake. Both halves must match: [`Identity::generate`] and
146/// [`Identity::from_secret_base64`] derive the public key from the secret, so an identity built
147/// through them always does.
148#[derive(Clone, Copy)]
149pub struct Identity {
150    /// Public X25519 key as 32 raw bytes; 43 base64url characters once encoded.
151    pub public: [u8; 32],
152    /// Secret X25519 key as 32 raw bytes. Never log this value.
153    pub secret: [u8; 32],
154}
155
156impl Identity {
157    /// Generates a fresh keypair from the operating system's CSPRNG.
158    ///
159    /// # Panics
160    ///
161    /// Panics if the operating system's CSPRNG is unavailable. That is not a recoverable
162    /// condition: a silent fallback would be a weak key.
163    pub fn generate() -> Identity {
164        let params = NOISE_PARAMS
165            .parse()
166            .expect("NOISE_PARAMS is a valid Noise protocol name");
167        let keypair = snow::Builder::new(params)
168            .generate_keypair()
169            .expect("the operating system CSPRNG is available");
170        let secret: [u8; 32] = keypair
171            .private
172            .as_slice()
173            .try_into()
174            .expect("an X25519 secret key is 32 bytes");
175        Identity::from_secret(secret)
176    }
177
178    /// Decodes an identity from its 43-character unpadded base64url secret key.
179    ///
180    /// The public key is derived from the secret. The input must be the canonical encoding of
181    /// exactly 32 bytes; a truncated, padded or non-base64url string is an error. Every 32-byte
182    /// value is a valid secret, so this cannot tell a secret key from a public key: passing a
183    /// public key such as [`Identity::public_base64`] succeeds and silently yields a different
184    /// identity.
185    pub fn from_secret_base64(s: &str) -> Result<Identity> {
186        let secret = decode_key(s).ok_or_else(|| {
187            anyhow!("identity secret is not a canonical 43-character unpadded base64url X25519 key")
188        })?;
189        Ok(Identity::from_secret(secret))
190    }
191
192    /// Returns the public key as 43-character unpadded base64url text.
193    ///
194    /// This is the value to send as `client_id` or `server_id`.
195    pub fn public_base64(&self) -> String {
196        URL_SAFE_NO_PAD.encode(self.public)
197    }
198
199    /// Returns the secret key as 43-character unpadded base64url text.
200    ///
201    /// The value is key material: hand it to [`Identity::from_secret_base64`] to restore an
202    /// identity and treat the text like a password.
203    pub fn secret_base64(&self) -> String {
204        URL_SAFE_NO_PAD.encode(self.secret)
205    }
206
207    /// Builds an identity whose public key is derived from `secret`.
208    fn from_secret(secret: [u8; 32]) -> Identity {
209        Identity {
210            public: public_key_for(&secret),
211            secret,
212        }
213    }
214
215    /// Rejects a hand-built identity whose two halves do not belong together.
216    fn validate(&self) -> Result<()> {
217        if public_key_for(&self.secret) != self.public {
218            bail!("identity public key does not match its secret key");
219        }
220        Ok(())
221    }
222}
223
224impl fmt::Debug for Identity {
225    /// Formats the public key and redacts the secret, so `Debug` output is safe to log.
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        f.debug_struct("Identity")
228            .field("public", &self.public_base64())
229            .field("secret", &"<redacted>")
230            .finish()
231    }
232}
233
234/// Noise responder state for one connection.
235pub struct Responder {
236    handshake: snow::HandshakeState,
237    /// The suite this handshake runs, kept for the transport and for callers that report it.
238    suite: Suite,
239}
240
241impl Responder {
242    /// Builds the responder for the client side of a Sendspin handshake, using the suite the
243    /// prologue's `client/init` announces.
244    ///
245    /// `prologue` must be the exact concatenation of the `client/init` and `server/init` bytes
246    /// as transmitted, in that order. It is mixed into the handshake verbatim, the initiator's
247    /// static public key is read from the `server_id` field of the `server/init` document it
248    /// contains, and the cipher suite from the `suite` field of `client/init`. A prologue that
249    /// is not a sequence of JSON documents, that carries no `server/init`, that carries two of
250    /// them, that announces no suite or that announces one this build does not have is
251    /// rejected; use [`Responder::with_peer`] when the key is already known, as during a
252    /// re-handshake where the prologue is the previous handshake hash.
253    pub fn new(identity: &Identity, prologue: &[u8]) -> Result<Responder> {
254        let peer_public = initiator_key_from_prologue(prologue)?;
255        let suite = suite_from_prologue(prologue)?;
256        Responder::with_peer_suite(identity, &peer_public, suite, prologue)
257    }
258
259    /// Builds the responder for the suite the prologue announces, refusing any other.
260    ///
261    /// This is [`Responder::new`] with an explicit choice, for a caller that must pin the suite.
262    /// A prologue whose `client/init` announces a different suite is an error: honouring the
263    /// caller's suite would hand the peer a handshake it cannot follow, and switching to the
264    /// announced one would be a silent downgrade of what the caller asked for.
265    pub fn with_suite(identity: &Identity, suite: Suite, prologue: &[u8]) -> Result<Responder> {
266        let peer_public = initiator_key_from_prologue(prologue)?;
267        let announced = suite_from_prologue(prologue)?;
268        if announced != suite {
269            bail!(
270                "the `client/init` in the prologue announces the cipher suite `{announced}`, so \
271                 this handshake cannot run `{suite}`; a suite the peer did not announce is \
272                 refused, never substituted"
273            );
274        }
275        Responder::with_peer_suite(identity, &peer_public, suite, prologue)
276    }
277
278    /// Builds the responder with the initiator's static public key supplied explicitly, for the
279    /// default suite [`Suite::ChaChaPoly`].
280    ///
281    /// Use this when the prologue is not the init exchange, for example on a re-handshake whose
282    /// prologue is the previous handshake hash. `prologue` still reaches Noise unchanged; both
283    /// sides must mix in the same bytes. A re-handshake must keep the suite of the connection it
284    /// replaces, so a caller that can offer more than one suite must use
285    /// [`Responder::with_peer_suite`] and pass the suite the connection already runs.
286    pub fn with_peer(
287        identity: &Identity,
288        peer_public: &[u8; 32],
289        prologue: &[u8],
290    ) -> Result<Responder> {
291        Responder::with_peer_suite(identity, peer_public, Suite::default(), prologue)
292    }
293
294    /// Builds the responder for an explicit peer key and suite.
295    ///
296    /// This is the constructor every other one ends in. It does not read the prologue, so it is
297    /// the one to use on a re-handshake, where the prologue is the previous handshake hash and
298    /// carries no announcement.
299    pub fn with_peer_suite(
300        identity: &Identity,
301        peer_public: &[u8; 32],
302        suite: Suite,
303        prologue: &[u8],
304    ) -> Result<Responder> {
305        identity.validate()?;
306
307        // Keep the published constant honest even if someone edits it.
308        debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
309
310        let params = suite
311            .params()
312            .parse()
313            .context("failed to parse the Noise protocol parameters")?;
314        let handshake = snow::Builder::new(params)
315            .local_private_key(&identity.secret)
316            .context("failed to set the local static key")?
317            .remote_public_key(peer_public)
318            .context("failed to set the peer static key")?
319            .psk(2, &SENTINEL_PSK)
320            .context("failed to set the handshake PSK")?
321            .prologue(prologue)
322            .context("failed to set the Noise prologue")?
323            .build_responder()
324            .context("failed to build the Noise responder")?;
325        Ok(Responder { handshake, suite })
326    }
327
328    /// Returns the cipher suite this handshake runs.
329    pub fn suite(&self) -> Suite {
330        self.suite
331    }
332
333    /// Replaces the pre-shared key used by the rest of the handshake.
334    ///
335    /// The responder starts with the published Sentinel PSK because the key is selected from the
336    /// metadata that message 1 carries. Call this after [`Responder::read_message`] and before
337    /// [`Responder::write_message`]: Noise mixes the key into message 2, so both sides must use
338    /// the same value and the initiator rejects a message sealed with another one.
339    ///
340    /// # Errors
341    /// The call is forwarded to `snow`, which refuses only a key of the wrong length or an
342    /// out-of-range location; both are fixed here, so this does not fail in practice. `snow` does
343    /// not refuse a late call either: the key must be set before [`Responder::write_message`]
344    /// seals message 2, and a later call has no effect on the handshake or on the message already
345    /// sealed.
346    pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
347        self.handshake
348            .set_psk(2, psk)
349            .context("failed to set the Noise handshake PSK")
350    }
351
352    /// Reads one Noise handshake message and returns its decrypted payload.
353    ///
354    /// The payload is returned verbatim, and this method validates nothing. Message 1 carries the
355    /// PSK metadata (`psk_id`, `psk_category`) for the session layer to validate; the handshake
356    /// itself starts with the Sentinel PSK, which [`Responder::set_psk`] can replace.
357    ///
358    /// A caller that drives `Responder` directly has to do what the session does with that payload:
359    /// reject an unknown category and a non-canonical id, match the announced category and id
360    /// against the PSKs it holds, check that a stored record names the `server_id` from
361    /// `server/init`, and fall back to the Sentinel PSK only on the initial handshake. A caller
362    /// that ignores the payload completes a handshake against any announced `psk_id` /
363    /// `psk_category` pair.
364    pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
365        read_handshake_payload(&mut self.handshake, msg)
366    }
367
368    /// Writes Noise handshake message 2 and returns it.
369    ///
370    /// The payload is the empty JSON object that Sendspin requires; it is not configurable.
371    pub fn write_message(&mut self) -> Result<Vec<u8>> {
372        write_handshake_payload(&mut self.handshake, HANDSHAKE_MESSAGE_2)
373    }
374
375    /// Returns whether both handshake messages have been processed.
376    pub fn handshake_finished(&self) -> bool {
377        self.handshake.is_handshake_finished()
378    }
379
380    /// Finishes the handshake and switches to transport mode.
381    ///
382    /// Fails if a handshake message is still outstanding, which
383    /// [`Responder::handshake_finished`] reports ahead of time.
384    pub fn into_transport(self) -> Result<TransportState> {
385        transport_from(self.handshake, self.suite)
386    }
387}
388
389/// Which key sealed the handshake message 2 the initiator just read.
390///
391/// [`Initiator::read_message_with_sentinel`] reports this so the session layer can tell a peer
392/// that holds the selected key from one that sealed with the published Sentinel key. It is a fact
393/// about the wire, not a verdict: what an unpaired peer may do is the caller's decision.
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub enum PskOutcome {
396    /// The key selected with [`Initiator::set_psk`], which for a server is the pairing record's
397    /// key.
398    SelectedKey,
399    /// The published [`SENTINEL_PSK`]: the selected key did not seal this handshake, so the peer
400    /// does not hold it.
401    SentinelFallback,
402}
403
404/// Noise initiator state for one connection: the server half.
405///
406/// The server always sends the first handshake message, so this type produces message 1 and
407/// consumes message 2. It starts with the published Sentinel PSK; [`Initiator::set_psk`] selects
408/// the key the session will actually use, which message 1 must announce.
409///
410/// The suite is the one the client announced in `client/init`: a server must run exactly that one,
411/// because the client builds its responder for it. There is no fallback - [`Initiator::new`]
412/// refuses a prologue that announces another suite, and [`Initiator::with_announced_suite`] takes
413/// the suite from the announcement so the two cannot disagree.
414pub struct Initiator {
415    handshake: snow::HandshakeState,
416    /// The suite this handshake runs, kept for the transport and for callers that report it.
417    suite: Suite,
418    /// Whether the last key selected through [`Initiator::set_psk`] is a key other than
419    /// [`SENTINEL_PSK`].
420    ///
421    /// The retry inside [`Initiator::read_message_with_sentinel`] installs the Sentinel key
422    /// directly on the handshake state, so it does not change this field: the field describes the
423    /// selection `set_psk` made, not the key the state currently holds.
424    ///
425    /// [`Initiator::read_message_with_sentinel`] has nothing to retry under when the selected key
426    /// is the Sentinel key itself.
427    selected_non_sentinel: bool,
428}
429
430impl Initiator {
431    /// Builds the initiator for an explicit peer key and suite.
432    ///
433    /// `prologue` reaches Noise unchanged, so both sides must mix in the same bytes: the exact
434    /// `client/init` and `server/init` of a first handshake, or the previous handshake hash on a
435    /// re-handshake. When the prologue carries a `client/init`, the suite it announces must be
436    /// `suite`; a prologue that carries no announcement - a re-handshake hash, which is not
437    /// JSON - leaves `suite` as the only source, and a suite this build does not have is always
438    /// refused.
439    pub fn new(
440        identity: &Identity,
441        peer_public: &[u8; 32],
442        suite: Suite,
443        prologue: &[u8],
444    ) -> Result<Initiator> {
445        if let Some(announced) = announced_suite_from_prologue(prologue)? {
446            if announced != suite {
447                bail!(
448                    "the `client/init` in the prologue announces the cipher suite `{announced}`, \
449                     so this handshake cannot run `{suite}`; the suite a peer announced is \
450                     refused when it differs, never substituted"
451                );
452            }
453        }
454        Initiator::build(identity, peer_public, suite, prologue)
455    }
456
457    /// Builds the initiator for the suite the prologue's `client/init` announces.
458    ///
459    /// This is the constructor for a first handshake: the announcement decides the suite, so the
460    /// two cannot disagree. A prologue that is not the init exchange, that carries no
461    /// `client/init`, that carries two of them, that announces no suite or that announces one
462    /// this build does not have is rejected; use [`Initiator::new`] on a re-handshake, where the
463    /// prologue is the previous handshake hash.
464    pub fn with_announced_suite(
465        identity: &Identity,
466        peer_public: &[u8; 32],
467        prologue: &[u8],
468    ) -> Result<Initiator> {
469        let suite = suite_from_prologue(prologue)?;
470        Initiator::build(identity, peer_public, suite, prologue)
471    }
472
473    /// Builds the handshake state every constructor ends in.
474    fn build(
475        identity: &Identity,
476        peer_public: &[u8; 32],
477        suite: Suite,
478        prologue: &[u8],
479    ) -> Result<Initiator> {
480        identity.validate()?;
481
482        // Keep the published constant honest even if someone edits it.
483        debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
484
485        let params = suite
486            .params()
487            .parse()
488            .context("failed to parse the Noise protocol parameters")?;
489        let handshake = snow::Builder::new(params)
490            .local_private_key(&identity.secret)
491            .context("failed to set the local static key")?
492            .remote_public_key(peer_public)
493            .context("failed to set the peer static key")?
494            .psk(2, &SENTINEL_PSK)
495            .context("failed to set the handshake PSK")?
496            .prologue(prologue)
497            .context("failed to set the Noise prologue")?
498            .build_initiator()
499            .context("failed to build the Noise initiator")?;
500        Ok(Initiator {
501            handshake,
502            suite,
503            selected_non_sentinel: false,
504        })
505    }
506
507    /// Returns the cipher suite this handshake runs.
508    pub fn suite(&self) -> Suite {
509        self.suite
510    }
511
512    /// Replaces the pre-shared key used by the rest of the handshake.
513    ///
514    /// The initiator starts with the published Sentinel PSK. Call this before writing message 1
515    /// when the handshake announces a private key, because message 1's payload names the key this
516    /// call selects; noise mixes the key into message 2 either way, so both sides must use the
517    /// same value or the peer's message 2 does not authenticate.
518    ///
519    /// That is the contract: before message 1, or once on the same state after a failed read, which
520    /// is what [`Initiator::read_message_with_sentinel`] does. Those are the only two call sites
521    /// this crate has; any other call replaces a key the handshake has already used.
522    pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
523        self.handshake
524            .set_psk(2, psk)
525            .context("failed to set the Noise handshake PSK")?;
526        self.selected_non_sentinel = psk != &SENTINEL_PSK;
527        Ok(())
528    }
529
530    /// Writes Noise handshake message 1 with `payload` and returns the message.
531    ///
532    /// The payload is the PSK metadata (`psk_id`, `psk_category`) the session layer builds; this
533    /// module does not interpret it. It travels encrypted, so it must fit into a Noise message.
534    pub fn write_message(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
535        write_handshake_payload(&mut self.handshake, payload)
536    }
537
538    /// Reads Noise handshake message 2 and returns its decrypted payload.
539    ///
540    /// The payload is returned verbatim; Sendspin requires it to be the empty JSON object, which
541    /// the session layer checks. Fails when the message does not authenticate, which covers a
542    /// message sealed with another PSK, a changed byte and a truncation.
543    pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
544        read_handshake_payload(&mut self.handshake, msg)
545    }
546
547    /// Reads Noise handshake message 2, retrying the same bytes under [`SENTINEL_PSK`] when they
548    /// do not authenticate.
549    ///
550    /// This is [`Initiator::read_message`] with the recovery a server needs after announcing a key
551    /// its peer does not hold: a message 2 sealed with the Sentinel key fails under the selected
552    /// key, and the same bytes then authenticate under the published one. `snow` restores its
553    /// symmetric state when a read fails, so the retry sees the handshake position the first
554    /// attempt left; the payload buffer is reused and returned verbatim, as
555    /// [`Initiator::read_message`] returns it.
556    ///
557    /// The outcome reports which key sealed the message. A message that authenticates is never
558    /// retried, whatever payload it carries, and a failure that is not an authentication failure is
559    /// returned as it comes. This is for the first handshake of a server that selected a key; a
560    /// re-handshake has no fallback and its caller keeps [`Initiator::read_message`].
561    ///
562    /// # Errors
563    /// Fails when the selected key is [`SENTINEL_PSK`] itself, because there is no second key to
564    /// retry under; when the message is shorter than the authentication tag; when it does not
565    /// authenticate under either key; and on everything else [`Initiator::read_message`] reports.
566    pub fn read_message_with_sentinel(&mut self, msg: &[u8]) -> Result<(PskOutcome, Vec<u8>)> {
567        if !self.selected_non_sentinel {
568            bail!(
569                "the selected PSK is the Sentinel key, so a failed read cannot be retried under \
570                 the Sentinel key"
571            );
572        }
573        ensure_message_len(msg.len(), "handshake message")?;
574        let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
575        match self.handshake.read_message(msg, &mut payload) {
576            Ok(len) => {
577                payload.truncate(len);
578                return Ok((PskOutcome::SelectedKey, payload));
579            }
580            // The failed read restored the symmetric state, so the same bytes can be read again
581            // under the key the peer sealed with.
582            Err(error) if should_retry_under_sentinel(&error) => {}
583            Err(error) => return Err(error).context("failed to read the Noise handshake message"),
584        }
585        self.handshake
586            .set_psk(2, &SENTINEL_PSK)
587            .context("failed to set the Noise handshake PSK")?;
588        let len = self
589            .handshake
590            .read_message(msg, &mut payload)
591            .context("failed to read the Noise handshake message under the Sentinel key")?;
592        payload.truncate(len);
593        Ok((PskOutcome::SentinelFallback, payload))
594    }
595
596    /// Returns whether both handshake messages have been processed.
597    pub fn handshake_finished(&self) -> bool {
598        self.handshake.is_handshake_finished()
599    }
600
601    /// Finishes the handshake and switches to transport mode.
602    ///
603    /// Returns what [`Responder::into_transport`] returns: the handshake hash a re-handshake
604    /// mixes in and the suite these keys were derived under. Fails if message 2 is still
605    /// outstanding, which [`Initiator::handshake_finished`] reports ahead of time.
606    pub fn into_transport(self) -> Result<TransportState> {
607        transport_from(self.handshake, self.suite)
608    }
609}
610
611/// Reads a handshake message and returns the payload it carries.
612fn read_handshake_payload(handshake: &mut snow::HandshakeState, msg: &[u8]) -> Result<Vec<u8>> {
613    ensure_message_len(msg.len(), "handshake message")?;
614    let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
615    let len = handshake
616        .read_message(msg, &mut payload)
617        .context("failed to read the Noise handshake message")?;
618    payload.truncate(len);
619    Ok(payload)
620}
621
622/// Returns whether a failed handshake read is worth retrying under [`SENTINEL_PSK`].
623///
624/// Only an authentication failure means "the peer sealed this with another key". Everything else -
625/// a malformed length, a wrong handshake position, a failed DH - would fail the same way under the
626/// Sentinel key, so a retry could only hide the real fault. `snow::Error` is `#[non_exhaustive]`,
627/// and a variant added later is not a decryption failure: every one of them means "no retry".
628fn should_retry_under_sentinel(error: &snow::Error) -> bool {
629    matches!(error, snow::Error::Decrypt)
630}
631
632/// Writes one handshake message carrying `payload`.
633fn write_handshake_payload(
634    handshake: &mut snow::HandshakeState,
635    payload: &[u8],
636) -> Result<Vec<u8>> {
637    let mut message = vec![0u8; MAX_MESSAGE_LEN];
638    let len = handshake
639        .write_message(payload, &mut message)
640        .context("failed to write the Noise handshake message")?;
641    message.truncate(len);
642    Ok(message)
643}
644
645/// Finishes a handshake and switches to transport mode.
646///
647/// `h` is final once the second message has been processed, and `into_transport_mode` consumes the
648/// handshake state that holds it.
649fn transport_from(handshake: snow::HandshakeState, suite: Suite) -> Result<TransportState> {
650    let handshake_hash: [u8; 32] = handshake
651        .get_handshake_hash()
652        .try_into()
653        .context("the Noise handshake hash is not 32 bytes")?;
654    let state = handshake
655        .into_transport_mode()
656        .context("failed to finish the Noise handshake")?;
657    Ok(TransportState {
658        state,
659        handshake_hash,
660        suite,
661    })
662}
663
664/// A Noise transport session: one ciphertext per message.
665///
666/// The nonce advances with every message in each direction; a repeated or reordered ciphertext
667/// fails authentication. Payloads are not fragmented at this layer, so a caller that needs to
668/// send more than a single Noise message can carry has to split the data itself.
669pub struct TransportState {
670    state: snow::TransportState,
671    /// The handshake hash `h` of the handshake that produced these keys.
672    handshake_hash: [u8; 32],
673    /// The cipher suite of the handshake that produced these keys.
674    suite: Suite,
675}
676
677impl TransportState {
678    /// Returns the cipher suite these keys were derived under.
679    ///
680    /// A re-handshake must use it again, and so must anything the specification seals with the
681    /// suite's AEAD, such as a pairing payload.
682    pub fn suite(&self) -> Suite {
683        self.suite
684    }
685
686    /// Returns the handshake hash `h` of the handshake these keys came from.
687    ///
688    /// Noise finalises `h` when the second handshake message is processed, and nothing after that
689    /// changes it. Sendspin uses it once: a [re-handshake](https://github.com/Sendspin/spec/blob/main/connection.md#re-handshake)
690    /// mixes the previous handshake's `h` in as its prologue, so a second handshake that reuses
691    /// these keys must be built with this value. It is a transcript hash, not key material, but it
692    /// must still never be logged.
693    pub fn handshake_hash(&self) -> &[u8; 32] {
694        &self.handshake_hash
695    }
696
697    /// Encrypts one plaintext into a Noise transport message.
698    ///
699    /// Fails if the plaintext does not fit into a single Noise message, that is if it is larger
700    /// than [`MAX_MESSAGE_LEN`] minus the 16-byte authentication tag.
701    pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
702        ensure_plaintext_len(plaintext.len())?;
703        let mut message = vec![0u8; plaintext.len() + TAG_LEN];
704        let len = self
705            .state
706            .write_message(plaintext, &mut message)
707            .context("failed to encrypt the Noise transport message")?;
708        message.truncate(len);
709        Ok(message)
710    }
711
712    /// Decrypts one Noise transport message.
713    ///
714    /// Fails if the ciphertext is longer than a Noise message, shorter than the authentication
715    /// tag, or does not authenticate under the current key and nonce.
716    pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
717        ensure_message_len(ciphertext.len(), "transport message")?;
718        let mut plaintext = vec![0u8; plaintext_capacity(ciphertext.len(), "transport message")?];
719        let len = self
720            .state
721            .read_message(ciphertext, &mut plaintext)
722            .context("failed to decrypt the Noise transport message")?;
723        plaintext.truncate(len);
724        Ok(plaintext)
725    }
726}
727
728/// Reads the initiator's static public key from a prologue of concatenated init messages.
729///
730/// The prologue is the exact `client/init` followed by `server/init` exchange, so it is parsed
731/// as a stream of top-level JSON documents and the caller passes the two documents without
732/// splitting them. Malformed JSON, a missing `server/init`, a non-canonical `server_id` and a
733/// second `server/init` are all errors: guessing a key here would mean handshaking with a static
734/// key the initiator may not hold.
735fn initiator_key_from_prologue(prologue: &[u8]) -> Result<[u8; 32]> {
736    let mut server_id = None;
737    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
738    {
739        let document = document.context("the prologue is not a sequence of JSON documents")?;
740        if document.get("type").and_then(serde_json::Value::as_str) != Some("server/init") {
741            continue;
742        }
743        if server_id.is_some() {
744            bail!("the prologue contains more than one `server/init` document");
745        }
746        let id = document
747            .pointer("/payload/server_id")
748            .and_then(serde_json::Value::as_str)
749            .ok_or_else(|| {
750                anyhow!("the `server/init` document carries no string `payload.server_id`")
751            })?;
752        server_id = Some(decode_key(id).ok_or_else(|| {
753            anyhow!("`server_id` is not a canonical 43-character unpadded base64url X25519 key")
754        })?);
755    }
756
757    server_id.ok_or_else(|| {
758        anyhow!(
759            "the prologue contains no `server/init` document with a `server_id`, so the \
760             initiator's static public key is unknown; pass it with `Responder::with_peer`"
761        )
762    })
763}
764
765/// Derives the X25519 public key that belongs to `secret`.
766fn public_key_for(secret: &[u8; 32]) -> [u8; 32] {
767    PublicKey::from(&StaticSecret::from(*secret)).to_bytes()
768}
769
770/// Reads the cipher suite the prologue's `client/init` announces.
771///
772/// The suite a handshake runs is the suite the client announced: it is not negotiated, and a
773/// name this build does not have is an error rather than a reason to use [`Suite::default`]. A
774/// prologue with no `client/init`, a missing or non-string `suite` and two `client/init`
775/// documents are errors too, for the same reason a missing `server_id` is: the handshake would
776/// otherwise guess what the peer meant.
777fn suite_from_prologue(prologue: &[u8]) -> Result<Suite> {
778    let mut announced = None;
779    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
780    {
781        let document = document.context("the prologue is not a sequence of JSON documents")?;
782        if let Some(suite) = client_init_suite(&document)? {
783            if announced.is_some() {
784                bail!("the prologue contains more than one `client/init` document");
785            }
786            announced = Some(suite);
787        }
788    }
789
790    announced.ok_or_else(|| {
791        anyhow!(
792            "the prologue contains no `client/init` document with a `suite`, so the cipher suite \
793             is unknown; a first handshake needs the init exchange, pass the suite with \
794             `Responder::with_peer_suite` on a re-handshake"
795        )
796    })
797}
798
799/// Reads the suite a prologue announces, if the prologue is the init exchange at all.
800///
801/// `None` means there is no `client/init` document to read: a re-handshake prologue is the
802/// previous handshake hash, which is not JSON, and carries no announcement. A `client/init` that
803/// carries no usable suite is still an error, so an announcement is never half-read.
804fn announced_suite_from_prologue(prologue: &[u8]) -> Result<Option<Suite>> {
805    let mut announced = None;
806    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
807    {
808        let Ok(document) = document else {
809            // Not a sequence of JSON documents: no announcement to check against.
810            return Ok(None);
811        };
812        if let Some(suite) = client_init_suite(&document)? {
813            if announced.is_some() {
814                bail!("the prologue contains more than one `client/init` document");
815            }
816            announced = Some(suite);
817        }
818    }
819    Ok(announced)
820}
821
822/// Returns the suite one init document announces, or `None` when it is not a `client/init`.
823fn client_init_suite(document: &serde_json::Value) -> Result<Option<Suite>> {
824    if document.get("type").and_then(serde_json::Value::as_str) != Some("client/init") {
825        return Ok(None);
826    }
827    let name = document
828        .pointer("/payload/suite")
829        .and_then(serde_json::Value::as_str)
830        .ok_or_else(|| {
831            anyhow!(
832                "the `client/init` document carries no string `payload.suite`; the cipher suite \
833                 is required and is not assumed to be `{}`",
834                Suite::default()
835            )
836        })?;
837    Ok(Some(Suite::from_wire_name(name).ok_or_else(|| {
838        anyhow!(
839            "the `client/init` document announces the cipher suite `{name}`, which this build \
840             does not have; it supports {}",
841            Suite::ALL
842                .map(Suite::wire_name)
843                .map(|name| format!("`{name}`"))
844                .join(", ")
845        )
846    })?))
847}
848
849/// Rejects a Noise message that exceeds the protocol maximum.
850fn ensure_message_len(len: usize, what: &str) -> Result<()> {
851    if len > MAX_MESSAGE_LEN {
852        bail!(
853            "Noise {what} is {len} bytes, exceeding the maximum Noise message size of \
854             {MAX_MESSAGE_LEN} bytes"
855        );
856    }
857    Ok(())
858}
859
860/// Rejects plaintext that cannot fit into one Noise message.
861fn ensure_plaintext_len(len: usize) -> Result<()> {
862    if len > MAX_PLAINTEXT_LEN {
863        bail!(
864            "plaintext is {len} bytes, exceeding the maximum Noise plaintext size of \
865             {MAX_PLAINTEXT_LEN} bytes (a {MAX_MESSAGE_LEN}-byte message including the \
866             {TAG_LEN}-byte tag); payloads are not fragmented at this layer"
867        );
868    }
869    Ok(())
870}
871
872/// Returns how much plaintext a message of `len` bytes can carry.
873fn plaintext_capacity(len: usize, what: &str) -> Result<usize> {
874    len.checked_sub(TAG_LEN).ok_or_else(|| {
875        anyhow!("Noise {what} is {len} bytes, shorter than the {TAG_LEN}-byte authentication tag")
876    })
877}
878
879/// Decodes a canonical 32-byte unpadded base64url key.
880fn decode_key(value: &str) -> Option<[u8; 32]> {
881    if value.len() != KEY_CHARS {
882        return None;
883    }
884    let bytes = URL_SAFE_NO_PAD.decode(value).ok()?;
885    if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
886        return None;
887    }
888    bytes.try_into().ok()
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    const CLIENT_INIT: &[u8] =
896        br#"{"type":"client/init","payload":{"client_id":"test-client","version":1}}"#;
897
898    fn server_init(server_id: &str) -> Vec<u8> {
899        format!(r#"{{"type":"server/init","payload":{{"server_id":"{server_id}","version":1}}}}"#)
900            .into_bytes()
901    }
902
903    fn prologue(server_id: &str) -> Vec<u8> {
904        let mut bytes = CLIENT_INIT.to_vec();
905        bytes.extend_from_slice(&server_init(server_id));
906        bytes
907    }
908
909    /// The prologue the Sentinel tests mix in. It is not JSON, so `Initiator::new` sees no suite
910    /// announcement and takes the one it is passed - the same rule a re-handshake relies on.
911    const TEST_PROLOGUE: &[u8] = b"client/init{}server/init{}";
912
913    /// A pairing record's PSK, distinct from [`SENTINEL_PSK`] so the two outcomes cannot be
914    /// confused.
915    const RECORD_PSK: [u8; 32] = [0x11; 32];
916
917    /// The metadata message 1 carries. This layer never interprets it, so its content is arbitrary.
918    const MESSAGE_1_PAYLOAD: &[u8] = br#"{"psk_id":"test","psk_category":"sn"}"#;
919
920    /// Builds the client half of the handshake on `snow` directly, as `tests/noise_handshake.rs`
921    /// does, with `psk` in the message-2 slot.
922    fn peer_responder(
923        client: &Identity,
924        server: &Identity,
925        psk: &[u8; 32],
926    ) -> snow::HandshakeState {
927        snow::Builder::new(
928            Suite::ChaChaPoly
929                .params()
930                .parse()
931                .expect("valid Noise parameters"),
932        )
933        .local_private_key(&client.secret)
934        .expect("set the local static key")
935        .remote_public_key(&server.public)
936        .expect("set the peer static key")
937        .psk(2, psk)
938        .expect("set the handshake PSK")
939        .prologue(TEST_PROLOGUE)
940        .expect("set the Noise prologue")
941        .build_responder()
942        .expect("build the Noise responder")
943    }
944
945    fn peer_write(peer: &mut snow::HandshakeState, payload: &[u8]) -> Vec<u8> {
946        let mut message = vec![0u8; MAX_MESSAGE_LEN];
947        let len = peer
948            .write_message(payload, &mut message)
949            .expect("write a Noise handshake message");
950        message.truncate(len);
951        message
952    }
953
954    fn peer_read(peer: &mut snow::HandshakeState, message: &[u8]) -> Vec<u8> {
955        let mut payload = vec![0u8; MAX_MESSAGE_LEN];
956        let len = peer
957            .read_message(message, &mut payload)
958            .expect("read a Noise handshake message");
959        payload.truncate(len);
960        payload
961    }
962
963    /// Builds both halves with their own PSK and exchanges message 1, which no PSK seals.
964    fn handshake_after_message_1(
965        initiator_psk: &[u8; 32],
966        peer_psk: &[u8; 32],
967    ) -> (Initiator, snow::HandshakeState) {
968        let server = Identity::generate();
969        let client = Identity::generate();
970        let mut initiator =
971            Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
972                .expect("build the initiator");
973        initiator
974            .set_psk(initiator_psk)
975            .expect("select the initiator PSK");
976        let mut peer = peer_responder(&client, &server, peer_psk);
977
978        let message_1 = initiator
979            .write_message(MESSAGE_1_PAYLOAD)
980            .expect("write message 1");
981        assert_eq!(
982            peer_read(&mut peer, &message_1),
983            MESSAGE_1_PAYLOAD,
984            "message 1 must reach the peer whichever key each side selected"
985        );
986        (initiator, peer)
987    }
988
989    #[test]
990    fn the_prologue_carries_the_initiator_static_key() {
991        let identity = Identity::generate();
992        let key = initiator_key_from_prologue(&prologue(&identity.public_base64()))
993            .expect("server/init carries server_id");
994        assert_eq!(key, identity.public);
995    }
996
997    #[test]
998    fn a_prologue_without_a_server_init_is_rejected() {
999        let identity = Identity::generate();
1000
1001        for prologue in [&b""[..], CLIENT_INIT] {
1002            let result = Responder::new(&identity, prologue);
1003            assert!(
1004                result.is_err(),
1005                "a prologue without server/init must be rejected"
1006            );
1007            let err = result.err().expect("the rejection was asserted");
1008            let message = format!("{err:#}");
1009            assert!(
1010                message.contains("server_id") && message.contains("with_peer"),
1011                "error should name the missing key and the way out, got: {message}"
1012            );
1013        }
1014
1015        // Malformed JSON is a parse error, not a silently skipped document.
1016        let result = Responder::new(&identity, b"not json at all");
1017        assert!(
1018            result.is_err(),
1019            "a prologue that is not JSON must be rejected"
1020        );
1021        let err = result.err().expect("the rejection was asserted");
1022        assert!(
1023            format!("{err:#}").contains("prologue is not a sequence of JSON documents"),
1024            "error should name the malformed prologue, got: {err:#}"
1025        );
1026    }
1027
1028    #[test]
1029    fn prologue_with_duplicate_server_id_is_rejected() {
1030        let identity = Identity::generate();
1031        let first = Identity::generate().public_base64();
1032        let second = Identity::generate().public_base64();
1033        let mut prologue = prologue(&first);
1034        prologue.extend_from_slice(&server_init(&second));
1035
1036        let result = Responder::new(&identity, &prologue);
1037        assert!(result.is_err(), "two server/init documents are ambiguous");
1038        let err = result.err().expect("the rejection was asserted");
1039        assert!(
1040            format!("{err:#}").contains("more than one `server/init`"),
1041            "error should name the duplicate, got: {err:#}"
1042        );
1043    }
1044
1045    #[test]
1046    fn an_identity_mismatch_is_rejected_before_the_handshake() {
1047        let mut identity = Identity::generate();
1048        identity.public = Identity::generate().public;
1049        let prologue = prologue(&Identity::generate().public_base64());
1050        let result = Responder::with_peer(&identity, &[0u8; 32], &prologue);
1051        assert!(result.is_err(), "a mismatched identity must be rejected");
1052        let err = result.err().expect("the rejection was asserted");
1053        assert!(
1054            format!("{err:#}").contains("does not match"),
1055            "error should name the mismatch, got: {err:#}"
1056        );
1057    }
1058
1059    #[test]
1060    fn a_server_init_without_a_usable_server_id_is_rejected() {
1061        let identity = Identity::generate();
1062
1063        let mut missing = CLIENT_INIT.to_vec();
1064        missing.extend_from_slice(br#"{"type":"server/init","payload":{"version":1}}"#);
1065        let result = Responder::new(&identity, &missing);
1066        assert!(result.is_err(), "a server/init without server_id must fail");
1067        assert!(
1068            format!("{:#}", result.err().expect("the rejection was asserted"))
1069                .contains("payload.server_id"),
1070            "the error must name the missing field"
1071        );
1072
1073        let mut wrong_type = CLIENT_INIT.to_vec();
1074        wrong_type.extend_from_slice(br#"{"type":"server/init","payload":{"server_id":42}}"#);
1075        let result = Responder::new(&identity, &wrong_type);
1076        assert!(result.is_err(), "a non-string server_id must fail");
1077        assert!(
1078            format!("{:#}", result.err().expect("the rejection was asserted"))
1079                .contains("payload.server_id")
1080        );
1081    }
1082
1083    #[test]
1084    fn a_server_id_that_is_not_a_canonical_key_is_rejected() {
1085        let identity = Identity::generate();
1086
1087        // Wrong length, an invalid base64url character, and 43 characters whose unused trailing
1088        // bits are not zero: only the canonical encoding of exactly 32 bytes may be accepted.
1089        for server_id in ["short", &"!".repeat(43), &"a".repeat(43)] {
1090            let result = Responder::new(&identity, &prologue(server_id));
1091            assert!(
1092                result.is_err(),
1093                "{server_id:?} must not be accepted as a key"
1094            );
1095            let message = format!("{:#}", result.err().expect("the rejection was asserted"));
1096            assert!(
1097                message.contains("canonical 43-character"),
1098                "the error must name the encoding, got: {message}"
1099            );
1100        }
1101
1102        // The canonical form of the same 32-byte secret is accepted and yields that key.
1103        let id = "A".repeat(43);
1104        assert_eq!(
1105            initiator_key_from_prologue(&prologue(&id)).expect("a canonical key is accepted"),
1106            {
1107                use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1108                use base64::Engine as _;
1109                let bytes = URL_SAFE_NO_PAD.decode(&id).expect("the id is base64url");
1110                let mut key = [0u8; 32];
1111                key.copy_from_slice(&bytes);
1112                key
1113            }
1114        );
1115    }
1116
1117    #[test]
1118    fn identity_debug_redacts_the_secret() {
1119        let identity = Identity::generate();
1120        let text = format!("{identity:?}");
1121        assert!(text.contains(&identity.public_base64()));
1122        assert!(!text.contains(&identity.secret_base64()));
1123        assert!(text.contains("<redacted>"));
1124    }
1125
1126    #[test]
1127    fn a_failed_read_can_be_retried_with_another_psk() {
1128        // The initiator announced the record's key, but the peer sealed message 2 with the
1129        // Sentinel key: the read fails under the record's key and succeeds on the same bytes under
1130        // the Sentinel key.
1131        let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &SENTINEL_PSK);
1132        let message_2 = peer_write(&mut peer, b"{}");
1133
1134        let error = initiator
1135            .read_message(&message_2)
1136            .expect_err("a message 2 sealed with the Sentinel key must not authenticate");
1137        assert_eq!(
1138            error.downcast_ref::<snow::Error>(),
1139            Some(&snow::Error::Decrypt),
1140            "a wrong PSK is an authentication failure, not a length or state failure"
1141        );
1142
1143        let (outcome, payload) = initiator
1144            .read_message_with_sentinel(&message_2)
1145            .expect("the same bytes authenticate under the Sentinel key");
1146        assert_eq!(outcome, PskOutcome::SentinelFallback);
1147        assert_eq!(payload, b"{}");
1148        assert!(initiator.handshake_finished());
1149
1150        // The retry must leave both sides on the same keys. The peer's `h` is captured before
1151        // `into_transport_mode` consumes the state that holds it.
1152        let peer_hash = peer.get_handshake_hash().to_vec();
1153        let mut ours = initiator.into_transport().expect("initiator transport");
1154        assert_eq!(
1155            ours.handshake_hash().to_vec(),
1156            peer_hash,
1157            "the retried handshake derived a hash the peer does not share"
1158        );
1159        let mut theirs = peer.into_transport_mode().expect("the peer's transport");
1160
1161        let ciphertext = ours.encrypt(b"from the initiator").expect("encrypt");
1162        let mut plaintext = vec![0u8; MAX_MESSAGE_LEN];
1163        let len = theirs
1164            .read_message(&ciphertext, &mut plaintext)
1165            .expect("the peer decrypts");
1166        assert_eq!(&plaintext[..len], b"from the initiator");
1167
1168        let mut ciphertext = vec![0u8; MAX_MESSAGE_LEN];
1169        let len = theirs
1170            .write_message(b"from the responder", &mut ciphertext)
1171            .expect("the peer encrypts");
1172        assert_eq!(
1173            ours.decrypt(&ciphertext[..len]).expect("decrypt"),
1174            b"from the responder"
1175        );
1176    }
1177
1178    #[test]
1179    fn a_successful_read_is_not_retried() {
1180        let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1181        let message_2 = peer_write(&mut peer, b"{}");
1182
1183        let (outcome, payload) = initiator
1184            .read_message_with_sentinel(&message_2)
1185            .expect("message 2 authenticates under the selected key");
1186        assert_eq!(outcome, PskOutcome::SelectedKey);
1187        assert_eq!(payload, b"{}");
1188        assert!(initiator.handshake_finished());
1189    }
1190
1191    #[test]
1192    fn a_successful_read_returns_a_foreign_payload() {
1193        // A message that authenticates is never a reason to retry, whatever it carries: this layer
1194        // returns the payload verbatim and the session layer rejects a non-`{}` one.
1195        let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1196        let message_2 = peer_write(&mut peer, b"not-empty");
1197
1198        let (outcome, payload) = initiator
1199            .read_message_with_sentinel(&message_2)
1200            .expect("message 2 authenticates under the selected key");
1201        assert_eq!(outcome, PskOutcome::SelectedKey);
1202        assert_eq!(payload, b"not-empty");
1203    }
1204
1205    #[test]
1206    fn the_sentinel_key_cannot_be_the_selected_key() {
1207        let server = Identity::generate();
1208        let client = Identity::generate();
1209        let mut initiator =
1210            Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
1211                .expect("build the initiator");
1212        initiator
1213            .set_psk(&SENTINEL_PSK)
1214            .expect("the Sentinel key is a valid PSK");
1215
1216        // Four bytes are too short even for a tag: the refusal must come from the key, which means
1217        // the guard runs before anything is read.
1218        let error = initiator
1219            .read_message_with_sentinel(&[0u8; 4])
1220            .expect_err("there is no second key to retry under");
1221        let text = format!("{error:#}");
1222        assert!(
1223            text.contains("Sentinel"),
1224            "the error must name the Sentinel key, got: {text}"
1225        );
1226        assert!(!initiator.handshake_finished());
1227    }
1228
1229    #[test]
1230    fn the_last_psk_write_wins() {
1231        let server = Identity::generate();
1232        let client = Identity::generate();
1233        let mut initiator =
1234            Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
1235                .expect("build the initiator");
1236        initiator
1237            .set_psk(&RECORD_PSK)
1238            .expect("select the record's key");
1239        initiator
1240            .set_psk(&SENTINEL_PSK)
1241            .expect("select the Sentinel key again");
1242
1243        let error = initiator
1244            .read_message_with_sentinel(&[0u8; 4])
1245            .expect_err("the Sentinel key was the last write, so there is nothing to retry under");
1246        assert!(
1247            format!("{error:#}").contains("Sentinel"),
1248            "the error must name the Sentinel key, got: {error:#}"
1249        );
1250    }
1251
1252    #[test]
1253    fn only_a_decrypt_failure_is_retried() {
1254        assert!(should_retry_under_sentinel(&snow::Error::Decrypt));
1255
1256        for error in [
1257            snow::Error::Input,
1258            snow::Error::Dh,
1259            snow::Error::Rng,
1260            snow::Error::State(snow::error::StateProblem::NotTurnToRead),
1261        ] {
1262            assert!(
1263                !should_retry_under_sentinel(&error),
1264                "{error:?} is not an authentication failure and must not be retried"
1265            );
1266        }
1267    }
1268
1269    #[test]
1270    fn a_frame_shorter_than_the_tag_is_not_retried() {
1271        let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1272
1273        let error = initiator
1274            .read_message_with_sentinel(&[0u8; 12])
1275            .expect_err("12 bytes cannot carry an authentication tag");
1276        assert!(
1277            error.downcast_ref::<snow::Error>().is_none(),
1278            "the capacity guard, not snow, must reject a frame below the tag length"
1279        );
1280        assert!(
1281            format!("{error:#}").contains("16-byte"),
1282            "the error must name the tag length, got: {error:#}"
1283        );
1284    }
1285
1286    #[test]
1287    fn a_frame_in_the_input_band_is_not_retried() {
1288        let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1289
1290        // 20 bytes leave no room for the 32-byte `e` token, so `snow` rejects the shape without
1291        // authenticating anything; retrying that under another key could only hide a malformed
1292        // frame.
1293        let error = initiator
1294            .read_message_with_sentinel(&[0u8; 20])
1295            .expect_err("20 bytes cannot carry a message-2 ephemeral key");
1296        assert_eq!(
1297            error.downcast_ref::<snow::Error>(),
1298            Some(&snow::Error::Input)
1299        );
1300        // `Input` is the same error whether the frame was retried or not, so only the context
1301        // separates the two paths: the retry wraps its failure with this phrase, the guard does
1302        // not. This assertion is what kills the mutant that retries unconditionally.
1303        assert!(
1304            !format!("{error:#}").contains("under the Sentinel key"),
1305            "a frame in the input band must not reach the retry, got: {error:#}"
1306        );
1307    }
1308
1309    #[test]
1310    fn a_truncated_tag_is_retried_and_still_fails() {
1311        let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1312
1313        // 40 bytes carry the 32-byte `e` token but only 8 bytes where a 16-byte tag belongs, so
1314        // both keys fail as `Decrypt`; the caller sees the retry's failure.
1315        let error = initiator
1316            .read_message_with_sentinel(&[0u8; 40])
1317            .expect_err("a truncated tag must not authenticate");
1318        assert_eq!(
1319            error.downcast_ref::<snow::Error>(),
1320            Some(&snow::Error::Decrypt)
1321        );
1322    }
1323}