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. Message 1 carries the PSK metadata
355    /// (`psk_id`, `psk_category`) for the session layer to validate; the handshake itself starts
356    /// with the Sentinel PSK, which [`Responder::set_psk`] can replace.
357    pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
358        read_handshake_payload(&mut self.handshake, msg)
359    }
360
361    /// Writes Noise handshake message 2 and returns it.
362    ///
363    /// The payload is the empty JSON object that Sendspin requires; it is not configurable.
364    pub fn write_message(&mut self) -> Result<Vec<u8>> {
365        write_handshake_payload(&mut self.handshake, HANDSHAKE_MESSAGE_2)
366    }
367
368    /// Returns whether both handshake messages have been processed.
369    pub fn handshake_finished(&self) -> bool {
370        self.handshake.is_handshake_finished()
371    }
372
373    /// Finishes the handshake and switches to transport mode.
374    ///
375    /// Fails if a handshake message is still outstanding, which
376    /// [`Responder::handshake_finished`] reports ahead of time.
377    pub fn into_transport(self) -> Result<TransportState> {
378        transport_from(self.handshake, self.suite)
379    }
380}
381
382/// Which key sealed the handshake message 2 the initiator just read.
383///
384/// [`Initiator::read_message_with_sentinel`] reports this so the session layer can tell a peer
385/// that holds the selected key from one that sealed with the published Sentinel key. It is a fact
386/// about the wire, not a verdict: what an unpaired peer may do is the caller's decision.
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388pub enum PskOutcome {
389    /// The key selected with [`Initiator::set_psk`], which for a server is the pairing record's
390    /// key.
391    SelectedKey,
392    /// The published [`SENTINEL_PSK`]: the selected key did not seal this handshake, so the peer
393    /// does not hold it.
394    SentinelFallback,
395}
396
397/// Noise initiator state for one connection: the server half.
398///
399/// The server always sends the first handshake message, so this type produces message 1 and
400/// consumes message 2. It starts with the published Sentinel PSK; [`Initiator::set_psk`] selects
401/// the key the session will actually use, which message 1 must announce.
402///
403/// The suite is the one the client announced in `client/init`: a server must run exactly that one,
404/// because the client builds its responder for it. There is no fallback - [`Initiator::new`]
405/// refuses a prologue that announces another suite, and [`Initiator::with_announced_suite`] takes
406/// the suite from the announcement so the two cannot disagree.
407pub struct Initiator {
408    handshake: snow::HandshakeState,
409    /// The suite this handshake runs, kept for the transport and for callers that report it.
410    suite: Suite,
411    /// Whether the last key selected through [`Initiator::set_psk`] is a key other than
412    /// [`SENTINEL_PSK`].
413    ///
414    /// The retry inside [`Initiator::read_message_with_sentinel`] installs the Sentinel key
415    /// directly on the handshake state, so it does not change this field: the field describes the
416    /// selection `set_psk` made, not the key the state currently holds.
417    ///
418    /// [`Initiator::read_message_with_sentinel`] has nothing to retry under when the selected key
419    /// is the Sentinel key itself.
420    selected_non_sentinel: bool,
421}
422
423impl Initiator {
424    /// Builds the initiator for an explicit peer key and suite.
425    ///
426    /// `prologue` reaches Noise unchanged, so both sides must mix in the same bytes: the exact
427    /// `client/init` and `server/init` of a first handshake, or the previous handshake hash on a
428    /// re-handshake. When the prologue carries a `client/init`, the suite it announces must be
429    /// `suite`; a prologue that carries no announcement - a re-handshake hash, which is not
430    /// JSON - leaves `suite` as the only source, and a suite this build does not have is always
431    /// refused.
432    pub fn new(
433        identity: &Identity,
434        peer_public: &[u8; 32],
435        suite: Suite,
436        prologue: &[u8],
437    ) -> Result<Initiator> {
438        if let Some(announced) = announced_suite_from_prologue(prologue)? {
439            if announced != suite {
440                bail!(
441                    "the `client/init` in the prologue announces the cipher suite `{announced}`, \
442                     so this handshake cannot run `{suite}`; the suite a peer announced is \
443                     refused when it differs, never substituted"
444                );
445            }
446        }
447        Initiator::build(identity, peer_public, suite, prologue)
448    }
449
450    /// Builds the initiator for the suite the prologue's `client/init` announces.
451    ///
452    /// This is the constructor for a first handshake: the announcement decides the suite, so the
453    /// two cannot disagree. A prologue that is not the init exchange, that carries no
454    /// `client/init`, that carries two of them, that announces no suite or that announces one
455    /// this build does not have is rejected; use [`Initiator::new`] on a re-handshake, where the
456    /// prologue is the previous handshake hash.
457    pub fn with_announced_suite(
458        identity: &Identity,
459        peer_public: &[u8; 32],
460        prologue: &[u8],
461    ) -> Result<Initiator> {
462        let suite = suite_from_prologue(prologue)?;
463        Initiator::build(identity, peer_public, suite, prologue)
464    }
465
466    /// Builds the handshake state every constructor ends in.
467    fn build(
468        identity: &Identity,
469        peer_public: &[u8; 32],
470        suite: Suite,
471        prologue: &[u8],
472    ) -> Result<Initiator> {
473        identity.validate()?;
474
475        // Keep the published constant honest even if someone edits it.
476        debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
477
478        let params = suite
479            .params()
480            .parse()
481            .context("failed to parse the Noise protocol parameters")?;
482        let handshake = snow::Builder::new(params)
483            .local_private_key(&identity.secret)
484            .context("failed to set the local static key")?
485            .remote_public_key(peer_public)
486            .context("failed to set the peer static key")?
487            .psk(2, &SENTINEL_PSK)
488            .context("failed to set the handshake PSK")?
489            .prologue(prologue)
490            .context("failed to set the Noise prologue")?
491            .build_initiator()
492            .context("failed to build the Noise initiator")?;
493        Ok(Initiator {
494            handshake,
495            suite,
496            selected_non_sentinel: false,
497        })
498    }
499
500    /// Returns the cipher suite this handshake runs.
501    pub fn suite(&self) -> Suite {
502        self.suite
503    }
504
505    /// Replaces the pre-shared key used by the rest of the handshake.
506    ///
507    /// The initiator starts with the published Sentinel PSK. Call this before writing message 1
508    /// when the handshake announces a private key, because message 1's payload names the key this
509    /// call selects; noise mixes the key into message 2 either way, so both sides must use the
510    /// same value or the peer's message 2 does not authenticate.
511    ///
512    /// That is the contract: before message 1, or once on the same state after a failed read, which
513    /// is what [`Initiator::read_message_with_sentinel`] does. Those are the only two call sites
514    /// this crate has; any other call replaces a key the handshake has already used.
515    pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
516        self.handshake
517            .set_psk(2, psk)
518            .context("failed to set the Noise handshake PSK")?;
519        self.selected_non_sentinel = psk != &SENTINEL_PSK;
520        Ok(())
521    }
522
523    /// Writes Noise handshake message 1 with `payload` and returns the message.
524    ///
525    /// The payload is the PSK metadata (`psk_id`, `psk_category`) the session layer builds; this
526    /// module does not interpret it. It travels encrypted, so it must fit into a Noise message.
527    pub fn write_message(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
528        write_handshake_payload(&mut self.handshake, payload)
529    }
530
531    /// Reads Noise handshake message 2 and returns its decrypted payload.
532    ///
533    /// The payload is returned verbatim; Sendspin requires it to be the empty JSON object, which
534    /// the session layer checks. Fails when the message does not authenticate, which covers a
535    /// message sealed with another PSK, a changed byte and a truncation.
536    pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
537        read_handshake_payload(&mut self.handshake, msg)
538    }
539
540    /// Reads Noise handshake message 2, retrying the same bytes under [`SENTINEL_PSK`] when they
541    /// do not authenticate.
542    ///
543    /// This is [`Initiator::read_message`] with the recovery a server needs after announcing a key
544    /// its peer does not hold: a message 2 sealed with the Sentinel key fails under the selected
545    /// key, and the same bytes then authenticate under the published one. `snow` restores its
546    /// symmetric state when a read fails, so the retry sees the handshake position the first
547    /// attempt left; the payload buffer is reused and returned verbatim, as
548    /// [`Initiator::read_message`] returns it.
549    ///
550    /// The outcome reports which key sealed the message. A message that authenticates is never
551    /// retried, whatever payload it carries, and a failure that is not an authentication failure is
552    /// returned as it comes. This is for the first handshake of a server that selected a key; a
553    /// re-handshake has no fallback and its caller keeps [`Initiator::read_message`].
554    ///
555    /// # Errors
556    /// Fails when the selected key is [`SENTINEL_PSK`] itself, because there is no second key to
557    /// retry under; when the message is shorter than the authentication tag; when it does not
558    /// authenticate under either key; and on everything else [`Initiator::read_message`] reports.
559    pub fn read_message_with_sentinel(&mut self, msg: &[u8]) -> Result<(PskOutcome, Vec<u8>)> {
560        if !self.selected_non_sentinel {
561            bail!(
562                "the selected PSK is the Sentinel key, so a failed read cannot be retried under \
563                 the Sentinel key"
564            );
565        }
566        ensure_message_len(msg.len(), "handshake message")?;
567        let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
568        match self.handshake.read_message(msg, &mut payload) {
569            Ok(len) => {
570                payload.truncate(len);
571                return Ok((PskOutcome::SelectedKey, payload));
572            }
573            // The failed read restored the symmetric state, so the same bytes can be read again
574            // under the key the peer sealed with.
575            Err(error) if should_retry_under_sentinel(&error) => {}
576            Err(error) => return Err(error).context("failed to read the Noise handshake message"),
577        }
578        self.handshake
579            .set_psk(2, &SENTINEL_PSK)
580            .context("failed to set the Noise handshake PSK")?;
581        let len = self
582            .handshake
583            .read_message(msg, &mut payload)
584            .context("failed to read the Noise handshake message under the Sentinel key")?;
585        payload.truncate(len);
586        Ok((PskOutcome::SentinelFallback, payload))
587    }
588
589    /// Returns whether both handshake messages have been processed.
590    pub fn handshake_finished(&self) -> bool {
591        self.handshake.is_handshake_finished()
592    }
593
594    /// Finishes the handshake and switches to transport mode.
595    ///
596    /// Returns what [`Responder::into_transport`] returns: the handshake hash a re-handshake
597    /// mixes in and the suite these keys were derived under. Fails if message 2 is still
598    /// outstanding, which [`Initiator::handshake_finished`] reports ahead of time.
599    pub fn into_transport(self) -> Result<TransportState> {
600        transport_from(self.handshake, self.suite)
601    }
602}
603
604/// Reads a handshake message and returns the payload it carries.
605fn read_handshake_payload(handshake: &mut snow::HandshakeState, msg: &[u8]) -> Result<Vec<u8>> {
606    ensure_message_len(msg.len(), "handshake message")?;
607    let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
608    let len = handshake
609        .read_message(msg, &mut payload)
610        .context("failed to read the Noise handshake message")?;
611    payload.truncate(len);
612    Ok(payload)
613}
614
615/// Returns whether a failed handshake read is worth retrying under [`SENTINEL_PSK`].
616///
617/// Only an authentication failure means "the peer sealed this with another key". Everything else -
618/// a malformed length, a wrong handshake position, a failed DH - would fail the same way under the
619/// Sentinel key, so a retry could only hide the real fault. `snow::Error` is `#[non_exhaustive]`,
620/// and a variant added later is not a decryption failure: every one of them means "no retry".
621fn should_retry_under_sentinel(error: &snow::Error) -> bool {
622    matches!(error, snow::Error::Decrypt)
623}
624
625/// Writes one handshake message carrying `payload`.
626fn write_handshake_payload(
627    handshake: &mut snow::HandshakeState,
628    payload: &[u8],
629) -> Result<Vec<u8>> {
630    let mut message = vec![0u8; MAX_MESSAGE_LEN];
631    let len = handshake
632        .write_message(payload, &mut message)
633        .context("failed to write the Noise handshake message")?;
634    message.truncate(len);
635    Ok(message)
636}
637
638/// Finishes a handshake and switches to transport mode.
639///
640/// `h` is final once the second message has been processed, and `into_transport_mode` consumes the
641/// handshake state that holds it.
642fn transport_from(handshake: snow::HandshakeState, suite: Suite) -> Result<TransportState> {
643    let handshake_hash: [u8; 32] = handshake
644        .get_handshake_hash()
645        .try_into()
646        .context("the Noise handshake hash is not 32 bytes")?;
647    let state = handshake
648        .into_transport_mode()
649        .context("failed to finish the Noise handshake")?;
650    Ok(TransportState {
651        state,
652        handshake_hash,
653        suite,
654    })
655}
656
657/// A Noise transport session: one ciphertext per message.
658///
659/// The nonce advances with every message in each direction; a repeated or reordered ciphertext
660/// fails authentication. Payloads are not fragmented at this layer, so a caller that needs to
661/// send more than a single Noise message can carry has to split the data itself.
662pub struct TransportState {
663    state: snow::TransportState,
664    /// The handshake hash `h` of the handshake that produced these keys.
665    handshake_hash: [u8; 32],
666    /// The cipher suite of the handshake that produced these keys.
667    suite: Suite,
668}
669
670impl TransportState {
671    /// Returns the cipher suite these keys were derived under.
672    ///
673    /// A re-handshake must use it again, and so must anything the specification seals with the
674    /// suite's AEAD, such as a pairing payload.
675    pub fn suite(&self) -> Suite {
676        self.suite
677    }
678
679    /// Returns the handshake hash `h` of the handshake these keys came from.
680    ///
681    /// Noise finalises `h` when the second handshake message is processed, and nothing after that
682    /// changes it. Sendspin uses it once: a [re-handshake](https://github.com/Sendspin/spec/blob/main/connection.md#re-handshake)
683    /// mixes the previous handshake's `h` in as its prologue, so a second handshake that reuses
684    /// these keys must be built with this value. It is a transcript hash, not key material, but it
685    /// must still never be logged.
686    pub fn handshake_hash(&self) -> &[u8; 32] {
687        &self.handshake_hash
688    }
689
690    /// Encrypts one plaintext into a Noise transport message.
691    ///
692    /// Fails if the plaintext does not fit into a single Noise message, that is if it is larger
693    /// than [`MAX_MESSAGE_LEN`] minus the 16-byte authentication tag.
694    pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
695        ensure_plaintext_len(plaintext.len())?;
696        let mut message = vec![0u8; plaintext.len() + TAG_LEN];
697        let len = self
698            .state
699            .write_message(plaintext, &mut message)
700            .context("failed to encrypt the Noise transport message")?;
701        message.truncate(len);
702        Ok(message)
703    }
704
705    /// Decrypts one Noise transport message.
706    ///
707    /// Fails if the ciphertext is longer than a Noise message, shorter than the authentication
708    /// tag, or does not authenticate under the current key and nonce.
709    pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
710        ensure_message_len(ciphertext.len(), "transport message")?;
711        let mut plaintext = vec![0u8; plaintext_capacity(ciphertext.len(), "transport message")?];
712        let len = self
713            .state
714            .read_message(ciphertext, &mut plaintext)
715            .context("failed to decrypt the Noise transport message")?;
716        plaintext.truncate(len);
717        Ok(plaintext)
718    }
719}
720
721/// Reads the initiator's static public key from a prologue of concatenated init messages.
722///
723/// The prologue is the exact `client/init` followed by `server/init` exchange, so it is parsed
724/// as a stream of top-level JSON documents and the caller passes the two documents without
725/// splitting them. Malformed JSON, a missing `server/init`, a non-canonical `server_id` and a
726/// second `server/init` are all errors: guessing a key here would mean handshaking with a static
727/// key the initiator may not hold.
728fn initiator_key_from_prologue(prologue: &[u8]) -> Result<[u8; 32]> {
729    let mut server_id = None;
730    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
731    {
732        let document = document.context("the prologue is not a sequence of JSON documents")?;
733        if document.get("type").and_then(serde_json::Value::as_str) != Some("server/init") {
734            continue;
735        }
736        if server_id.is_some() {
737            bail!("the prologue contains more than one `server/init` document");
738        }
739        let id = document
740            .pointer("/payload/server_id")
741            .and_then(serde_json::Value::as_str)
742            .ok_or_else(|| {
743                anyhow!("the `server/init` document carries no string `payload.server_id`")
744            })?;
745        server_id = Some(decode_key(id).ok_or_else(|| {
746            anyhow!("`server_id` is not a canonical 43-character unpadded base64url X25519 key")
747        })?);
748    }
749
750    server_id.ok_or_else(|| {
751        anyhow!(
752            "the prologue contains no `server/init` document with a `server_id`, so the \
753             initiator's static public key is unknown; pass it with `Responder::with_peer`"
754        )
755    })
756}
757
758/// Derives the X25519 public key that belongs to `secret`.
759fn public_key_for(secret: &[u8; 32]) -> [u8; 32] {
760    PublicKey::from(&StaticSecret::from(*secret)).to_bytes()
761}
762
763/// Reads the cipher suite the prologue's `client/init` announces.
764///
765/// The suite a handshake runs is the suite the client announced: it is not negotiated, and a
766/// name this build does not have is an error rather than a reason to use [`Suite::default`]. A
767/// prologue with no `client/init`, a missing or non-string `suite` and two `client/init`
768/// documents are errors too, for the same reason a missing `server_id` is: the handshake would
769/// otherwise guess what the peer meant.
770fn suite_from_prologue(prologue: &[u8]) -> Result<Suite> {
771    let mut announced = None;
772    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
773    {
774        let document = document.context("the prologue is not a sequence of JSON documents")?;
775        if let Some(suite) = client_init_suite(&document)? {
776            if announced.is_some() {
777                bail!("the prologue contains more than one `client/init` document");
778            }
779            announced = Some(suite);
780        }
781    }
782
783    announced.ok_or_else(|| {
784        anyhow!(
785            "the prologue contains no `client/init` document with a `suite`, so the cipher suite \
786             is unknown; a first handshake needs the init exchange, pass the suite with \
787             `Responder::with_peer_suite` on a re-handshake"
788        )
789    })
790}
791
792/// Reads the suite a prologue announces, if the prologue is the init exchange at all.
793///
794/// `None` means there is no `client/init` document to read: a re-handshake prologue is the
795/// previous handshake hash, which is not JSON, and carries no announcement. A `client/init` that
796/// carries no usable suite is still an error, so an announcement is never half-read.
797fn announced_suite_from_prologue(prologue: &[u8]) -> Result<Option<Suite>> {
798    let mut announced = None;
799    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
800    {
801        let Ok(document) = document else {
802            // Not a sequence of JSON documents: no announcement to check against.
803            return Ok(None);
804        };
805        if let Some(suite) = client_init_suite(&document)? {
806            if announced.is_some() {
807                bail!("the prologue contains more than one `client/init` document");
808            }
809            announced = Some(suite);
810        }
811    }
812    Ok(announced)
813}
814
815/// Returns the suite one init document announces, or `None` when it is not a `client/init`.
816fn client_init_suite(document: &serde_json::Value) -> Result<Option<Suite>> {
817    if document.get("type").and_then(serde_json::Value::as_str) != Some("client/init") {
818        return Ok(None);
819    }
820    let name = document
821        .pointer("/payload/suite")
822        .and_then(serde_json::Value::as_str)
823        .ok_or_else(|| {
824            anyhow!(
825                "the `client/init` document carries no string `payload.suite`; the cipher suite \
826                 is required and is not assumed to be `{}`",
827                Suite::default()
828            )
829        })?;
830    Ok(Some(Suite::from_wire_name(name).ok_or_else(|| {
831        anyhow!(
832            "the `client/init` document announces the cipher suite `{name}`, which this build \
833             does not have; it supports {}",
834            Suite::ALL
835                .map(Suite::wire_name)
836                .map(|name| format!("`{name}`"))
837                .join(", ")
838        )
839    })?))
840}
841
842/// Rejects a Noise message that exceeds the protocol maximum.
843fn ensure_message_len(len: usize, what: &str) -> Result<()> {
844    if len > MAX_MESSAGE_LEN {
845        bail!(
846            "Noise {what} is {len} bytes, exceeding the maximum Noise message size of \
847             {MAX_MESSAGE_LEN} bytes"
848        );
849    }
850    Ok(())
851}
852
853/// Rejects plaintext that cannot fit into one Noise message.
854fn ensure_plaintext_len(len: usize) -> Result<()> {
855    if len > MAX_PLAINTEXT_LEN {
856        bail!(
857            "plaintext is {len} bytes, exceeding the maximum Noise plaintext size of \
858             {MAX_PLAINTEXT_LEN} bytes (a {MAX_MESSAGE_LEN}-byte message including the \
859             {TAG_LEN}-byte tag); payloads are not fragmented at this layer"
860        );
861    }
862    Ok(())
863}
864
865/// Returns how much plaintext a message of `len` bytes can carry.
866fn plaintext_capacity(len: usize, what: &str) -> Result<usize> {
867    len.checked_sub(TAG_LEN).ok_or_else(|| {
868        anyhow!("Noise {what} is {len} bytes, shorter than the {TAG_LEN}-byte authentication tag")
869    })
870}
871
872/// Decodes a canonical 32-byte unpadded base64url key.
873fn decode_key(value: &str) -> Option<[u8; 32]> {
874    if value.len() != KEY_CHARS {
875        return None;
876    }
877    let bytes = URL_SAFE_NO_PAD.decode(value).ok()?;
878    if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
879        return None;
880    }
881    bytes.try_into().ok()
882}
883
884#[cfg(test)]
885mod tests {
886    use super::*;
887
888    const CLIENT_INIT: &[u8] =
889        br#"{"type":"client/init","payload":{"client_id":"test-client","version":1}}"#;
890
891    fn server_init(server_id: &str) -> Vec<u8> {
892        format!(r#"{{"type":"server/init","payload":{{"server_id":"{server_id}","version":1}}}}"#)
893            .into_bytes()
894    }
895
896    fn prologue(server_id: &str) -> Vec<u8> {
897        let mut bytes = CLIENT_INIT.to_vec();
898        bytes.extend_from_slice(&server_init(server_id));
899        bytes
900    }
901
902    /// The prologue the Sentinel tests mix in. It is not JSON, so `Initiator::new` sees no suite
903    /// announcement and takes the one it is passed - the same rule a re-handshake relies on.
904    const TEST_PROLOGUE: &[u8] = b"client/init{}server/init{}";
905
906    /// A pairing record's PSK, distinct from [`SENTINEL_PSK`] so the two outcomes cannot be
907    /// confused.
908    const RECORD_PSK: [u8; 32] = [0x11; 32];
909
910    /// The metadata message 1 carries. This layer never interprets it, so its content is arbitrary.
911    const MESSAGE_1_PAYLOAD: &[u8] = br#"{"psk_id":"test","psk_category":"sn"}"#;
912
913    /// Builds the client half of the handshake on `snow` directly, as `tests/noise_handshake.rs`
914    /// does, with `psk` in the message-2 slot.
915    fn peer_responder(
916        client: &Identity,
917        server: &Identity,
918        psk: &[u8; 32],
919    ) -> snow::HandshakeState {
920        snow::Builder::new(
921            Suite::ChaChaPoly
922                .params()
923                .parse()
924                .expect("valid Noise parameters"),
925        )
926        .local_private_key(&client.secret)
927        .expect("set the local static key")
928        .remote_public_key(&server.public)
929        .expect("set the peer static key")
930        .psk(2, psk)
931        .expect("set the handshake PSK")
932        .prologue(TEST_PROLOGUE)
933        .expect("set the Noise prologue")
934        .build_responder()
935        .expect("build the Noise responder")
936    }
937
938    fn peer_write(peer: &mut snow::HandshakeState, payload: &[u8]) -> Vec<u8> {
939        let mut message = vec![0u8; MAX_MESSAGE_LEN];
940        let len = peer
941            .write_message(payload, &mut message)
942            .expect("write a Noise handshake message");
943        message.truncate(len);
944        message
945    }
946
947    fn peer_read(peer: &mut snow::HandshakeState, message: &[u8]) -> Vec<u8> {
948        let mut payload = vec![0u8; MAX_MESSAGE_LEN];
949        let len = peer
950            .read_message(message, &mut payload)
951            .expect("read a Noise handshake message");
952        payload.truncate(len);
953        payload
954    }
955
956    /// Builds both halves with their own PSK and exchanges message 1, which no PSK seals.
957    fn handshake_after_message_1(
958        initiator_psk: &[u8; 32],
959        peer_psk: &[u8; 32],
960    ) -> (Initiator, snow::HandshakeState) {
961        let server = Identity::generate();
962        let client = Identity::generate();
963        let mut initiator =
964            Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
965                .expect("build the initiator");
966        initiator
967            .set_psk(initiator_psk)
968            .expect("select the initiator PSK");
969        let mut peer = peer_responder(&client, &server, peer_psk);
970
971        let message_1 = initiator
972            .write_message(MESSAGE_1_PAYLOAD)
973            .expect("write message 1");
974        assert_eq!(
975            peer_read(&mut peer, &message_1),
976            MESSAGE_1_PAYLOAD,
977            "message 1 must reach the peer whichever key each side selected"
978        );
979        (initiator, peer)
980    }
981
982    #[test]
983    fn the_prologue_carries_the_initiator_static_key() {
984        let identity = Identity::generate();
985        let key = initiator_key_from_prologue(&prologue(&identity.public_base64()))
986            .expect("server/init carries server_id");
987        assert_eq!(key, identity.public);
988    }
989
990    #[test]
991    fn a_prologue_without_a_server_init_is_rejected() {
992        let identity = Identity::generate();
993
994        for prologue in [&b""[..], CLIENT_INIT] {
995            let result = Responder::new(&identity, prologue);
996            assert!(
997                result.is_err(),
998                "a prologue without server/init must be rejected"
999            );
1000            let err = result.err().expect("the rejection was asserted");
1001            let message = format!("{err:#}");
1002            assert!(
1003                message.contains("server_id") && message.contains("with_peer"),
1004                "error should name the missing key and the way out, got: {message}"
1005            );
1006        }
1007
1008        // Malformed JSON is a parse error, not a silently skipped document.
1009        let result = Responder::new(&identity, b"not json at all");
1010        assert!(
1011            result.is_err(),
1012            "a prologue that is not JSON must be rejected"
1013        );
1014        let err = result.err().expect("the rejection was asserted");
1015        assert!(
1016            format!("{err:#}").contains("prologue is not a sequence of JSON documents"),
1017            "error should name the malformed prologue, got: {err:#}"
1018        );
1019    }
1020
1021    #[test]
1022    fn prologue_with_duplicate_server_id_is_rejected() {
1023        let identity = Identity::generate();
1024        let first = Identity::generate().public_base64();
1025        let second = Identity::generate().public_base64();
1026        let mut prologue = prologue(&first);
1027        prologue.extend_from_slice(&server_init(&second));
1028
1029        let result = Responder::new(&identity, &prologue);
1030        assert!(result.is_err(), "two server/init documents are ambiguous");
1031        let err = result.err().expect("the rejection was asserted");
1032        assert!(
1033            format!("{err:#}").contains("more than one `server/init`"),
1034            "error should name the duplicate, got: {err:#}"
1035        );
1036    }
1037
1038    #[test]
1039    fn an_identity_mismatch_is_rejected_before_the_handshake() {
1040        let mut identity = Identity::generate();
1041        identity.public = Identity::generate().public;
1042        let prologue = prologue(&Identity::generate().public_base64());
1043        let result = Responder::with_peer(&identity, &[0u8; 32], &prologue);
1044        assert!(result.is_err(), "a mismatched identity must be rejected");
1045        let err = result.err().expect("the rejection was asserted");
1046        assert!(
1047            format!("{err:#}").contains("does not match"),
1048            "error should name the mismatch, got: {err:#}"
1049        );
1050    }
1051
1052    #[test]
1053    fn a_server_init_without_a_usable_server_id_is_rejected() {
1054        let identity = Identity::generate();
1055
1056        let mut missing = CLIENT_INIT.to_vec();
1057        missing.extend_from_slice(br#"{"type":"server/init","payload":{"version":1}}"#);
1058        let result = Responder::new(&identity, &missing);
1059        assert!(result.is_err(), "a server/init without server_id must fail");
1060        assert!(
1061            format!("{:#}", result.err().expect("the rejection was asserted"))
1062                .contains("payload.server_id"),
1063            "the error must name the missing field"
1064        );
1065
1066        let mut wrong_type = CLIENT_INIT.to_vec();
1067        wrong_type.extend_from_slice(br#"{"type":"server/init","payload":{"server_id":42}}"#);
1068        let result = Responder::new(&identity, &wrong_type);
1069        assert!(result.is_err(), "a non-string server_id must fail");
1070        assert!(
1071            format!("{:#}", result.err().expect("the rejection was asserted"))
1072                .contains("payload.server_id")
1073        );
1074    }
1075
1076    #[test]
1077    fn a_server_id_that_is_not_a_canonical_key_is_rejected() {
1078        let identity = Identity::generate();
1079
1080        // Wrong length, an invalid base64url character, and 43 characters whose unused trailing
1081        // bits are not zero: only the canonical encoding of exactly 32 bytes may be accepted.
1082        for server_id in ["short", &"!".repeat(43), &"a".repeat(43)] {
1083            let result = Responder::new(&identity, &prologue(server_id));
1084            assert!(
1085                result.is_err(),
1086                "{server_id:?} must not be accepted as a key"
1087            );
1088            let message = format!("{:#}", result.err().expect("the rejection was asserted"));
1089            assert!(
1090                message.contains("canonical 43-character"),
1091                "the error must name the encoding, got: {message}"
1092            );
1093        }
1094
1095        // The canonical form of the same 32-byte secret is accepted and yields that key.
1096        let id = "A".repeat(43);
1097        assert_eq!(
1098            initiator_key_from_prologue(&prologue(&id)).expect("a canonical key is accepted"),
1099            {
1100                use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1101                use base64::Engine as _;
1102                let bytes = URL_SAFE_NO_PAD.decode(&id).expect("the id is base64url");
1103                let mut key = [0u8; 32];
1104                key.copy_from_slice(&bytes);
1105                key
1106            }
1107        );
1108    }
1109
1110    #[test]
1111    fn identity_debug_redacts_the_secret() {
1112        let identity = Identity::generate();
1113        let text = format!("{identity:?}");
1114        assert!(text.contains(&identity.public_base64()));
1115        assert!(!text.contains(&identity.secret_base64()));
1116        assert!(text.contains("<redacted>"));
1117    }
1118
1119    #[test]
1120    fn a_failed_read_can_be_retried_with_another_psk() {
1121        // The initiator announced the record's key, but the peer sealed message 2 with the
1122        // Sentinel key: the read fails under the record's key and succeeds on the same bytes under
1123        // the Sentinel key.
1124        let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &SENTINEL_PSK);
1125        let message_2 = peer_write(&mut peer, b"{}");
1126
1127        let error = initiator
1128            .read_message(&message_2)
1129            .expect_err("a message 2 sealed with the Sentinel key must not authenticate");
1130        assert_eq!(
1131            error.downcast_ref::<snow::Error>(),
1132            Some(&snow::Error::Decrypt),
1133            "a wrong PSK is an authentication failure, not a length or state failure"
1134        );
1135
1136        let (outcome, payload) = initiator
1137            .read_message_with_sentinel(&message_2)
1138            .expect("the same bytes authenticate under the Sentinel key");
1139        assert_eq!(outcome, PskOutcome::SentinelFallback);
1140        assert_eq!(payload, b"{}");
1141        assert!(initiator.handshake_finished());
1142
1143        // The retry must leave both sides on the same keys. The peer's `h` is captured before
1144        // `into_transport_mode` consumes the state that holds it.
1145        let peer_hash = peer.get_handshake_hash().to_vec();
1146        let mut ours = initiator.into_transport().expect("initiator transport");
1147        assert_eq!(
1148            ours.handshake_hash().to_vec(),
1149            peer_hash,
1150            "the retried handshake derived a hash the peer does not share"
1151        );
1152        let mut theirs = peer.into_transport_mode().expect("the peer's transport");
1153
1154        let ciphertext = ours.encrypt(b"from the initiator").expect("encrypt");
1155        let mut plaintext = vec![0u8; MAX_MESSAGE_LEN];
1156        let len = theirs
1157            .read_message(&ciphertext, &mut plaintext)
1158            .expect("the peer decrypts");
1159        assert_eq!(&plaintext[..len], b"from the initiator");
1160
1161        let mut ciphertext = vec![0u8; MAX_MESSAGE_LEN];
1162        let len = theirs
1163            .write_message(b"from the responder", &mut ciphertext)
1164            .expect("the peer encrypts");
1165        assert_eq!(
1166            ours.decrypt(&ciphertext[..len]).expect("decrypt"),
1167            b"from the responder"
1168        );
1169    }
1170
1171    #[test]
1172    fn a_successful_read_is_not_retried() {
1173        let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1174        let message_2 = peer_write(&mut peer, b"{}");
1175
1176        let (outcome, payload) = initiator
1177            .read_message_with_sentinel(&message_2)
1178            .expect("message 2 authenticates under the selected key");
1179        assert_eq!(outcome, PskOutcome::SelectedKey);
1180        assert_eq!(payload, b"{}");
1181        assert!(initiator.handshake_finished());
1182    }
1183
1184    #[test]
1185    fn a_successful_read_returns_a_foreign_payload() {
1186        // A message that authenticates is never a reason to retry, whatever it carries: this layer
1187        // returns the payload verbatim and the session layer rejects a non-`{}` one.
1188        let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1189        let message_2 = peer_write(&mut peer, b"not-empty");
1190
1191        let (outcome, payload) = initiator
1192            .read_message_with_sentinel(&message_2)
1193            .expect("message 2 authenticates under the selected key");
1194        assert_eq!(outcome, PskOutcome::SelectedKey);
1195        assert_eq!(payload, b"not-empty");
1196    }
1197
1198    #[test]
1199    fn the_sentinel_key_cannot_be_the_selected_key() {
1200        let server = Identity::generate();
1201        let client = Identity::generate();
1202        let mut initiator =
1203            Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
1204                .expect("build the initiator");
1205        initiator
1206            .set_psk(&SENTINEL_PSK)
1207            .expect("the Sentinel key is a valid PSK");
1208
1209        // Four bytes are too short even for a tag: the refusal must come from the key, which means
1210        // the guard runs before anything is read.
1211        let error = initiator
1212            .read_message_with_sentinel(&[0u8; 4])
1213            .expect_err("there is no second key to retry under");
1214        let text = format!("{error:#}");
1215        assert!(
1216            text.contains("Sentinel"),
1217            "the error must name the Sentinel key, got: {text}"
1218        );
1219        assert!(!initiator.handshake_finished());
1220    }
1221
1222    #[test]
1223    fn the_last_psk_write_wins() {
1224        let server = Identity::generate();
1225        let client = Identity::generate();
1226        let mut initiator =
1227            Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
1228                .expect("build the initiator");
1229        initiator
1230            .set_psk(&RECORD_PSK)
1231            .expect("select the record's key");
1232        initiator
1233            .set_psk(&SENTINEL_PSK)
1234            .expect("select the Sentinel key again");
1235
1236        let error = initiator
1237            .read_message_with_sentinel(&[0u8; 4])
1238            .expect_err("the Sentinel key was the last write, so there is nothing to retry under");
1239        assert!(
1240            format!("{error:#}").contains("Sentinel"),
1241            "the error must name the Sentinel key, got: {error:#}"
1242        );
1243    }
1244
1245    #[test]
1246    fn only_a_decrypt_failure_is_retried() {
1247        assert!(should_retry_under_sentinel(&snow::Error::Decrypt));
1248
1249        for error in [
1250            snow::Error::Input,
1251            snow::Error::Dh,
1252            snow::Error::Rng,
1253            snow::Error::State(snow::error::StateProblem::NotTurnToRead),
1254        ] {
1255            assert!(
1256                !should_retry_under_sentinel(&error),
1257                "{error:?} is not an authentication failure and must not be retried"
1258            );
1259        }
1260    }
1261
1262    #[test]
1263    fn a_frame_shorter_than_the_tag_is_not_retried() {
1264        let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1265
1266        let error = initiator
1267            .read_message_with_sentinel(&[0u8; 12])
1268            .expect_err("12 bytes cannot carry an authentication tag");
1269        assert!(
1270            error.downcast_ref::<snow::Error>().is_none(),
1271            "the capacity guard, not snow, must reject a frame below the tag length"
1272        );
1273        assert!(
1274            format!("{error:#}").contains("16-byte"),
1275            "the error must name the tag length, got: {error:#}"
1276        );
1277    }
1278
1279    #[test]
1280    fn a_frame_in_the_input_band_is_not_retried() {
1281        let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1282
1283        // 20 bytes leave no room for the 32-byte `e` token, so `snow` rejects the shape without
1284        // authenticating anything; retrying that under another key could only hide a malformed
1285        // frame.
1286        let error = initiator
1287            .read_message_with_sentinel(&[0u8; 20])
1288            .expect_err("20 bytes cannot carry a message-2 ephemeral key");
1289        assert_eq!(
1290            error.downcast_ref::<snow::Error>(),
1291            Some(&snow::Error::Input)
1292        );
1293        // `Input` is the same error whether the frame was retried or not, so only the context
1294        // separates the two paths: the retry wraps its failure with this phrase, the guard does
1295        // not. This assertion is what kills the mutant that retries unconditionally.
1296        assert!(
1297            !format!("{error:#}").contains("under the Sentinel key"),
1298            "a frame in the input band must not reach the retry, got: {error:#}"
1299        );
1300    }
1301
1302    #[test]
1303    fn a_truncated_tag_is_retried_and_still_fails() {
1304        let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1305
1306        // 40 bytes carry the 32-byte `e` token but only 8 bytes where a 16-byte tag belongs, so
1307        // both keys fail as `Decrypt`; the caller sees the retry's failure.
1308        let error = initiator
1309            .read_message_with_sentinel(&[0u8; 40])
1310            .expect_err("a truncated tag must not authenticate");
1311        assert_eq!(
1312            error.downcast_ref::<snow::Error>(),
1313            Some(&snow::Error::Decrypt)
1314        );
1315    }
1316}