Skip to main content

teter_core/
e2e.rs

1//! End-to-end encryption between backend and frontend: the relay forwards
2//! terminal data it cannot read. See `docs/architecture.md`, "End-to-end
3//! encryption", for the design.
4//!
5//! The backend makes a [`Secret`] and prints it; the user gives it to the
6//! frontend, and it never goes to the relay. Both derive [`Keys`] from it and
7//! the session ID, one key per direction. A [`Sealer`] seals what one side
8//! sends, an [`Opener`] opens what the other side sent and refuses anything
9//! forged, altered, or seen before.
10
11use std::collections::HashMap;
12use std::fmt;
13
14use chacha20poly1305::aead::{Aead, KeyInit, Payload};
15use chacha20poly1305::{XChaCha20Poly1305, XNonce};
16use hkdf::Hkdf;
17use sha2::Sha256;
18use teter_common::SessionId;
19use zeroize::Zeroizing;
20
21/// The version byte that starts every sealed message.
22const VERSION: u8 = 1;
23/// Bound into every message, so nothing sealed here passes for anything else.
24const CONTEXT: &[u8] = b"teter-e2e-v1";
25const SENDER_LEN: usize = 16;
26const SEQ_LEN: usize = 8;
27const HEADER_LEN: usize = 1 + SENDER_LEN + SEQ_LEN;
28const TAG_LEN: usize = 16;
29/// Senders an [`Opener`] takes; past that, a new sender is refused. A sender
30/// is never forgotten, or the relay could replay what it had sent: a
31/// session's frontends, every run of each, must stay under this.
32const MAX_SENDERS: usize = 4096;
33
34/// The session's shared secret: 32 random bytes, printed by the backend as
35/// 64 hex digits. Never logged: its `Debug` hides it.
36#[derive(Clone, PartialEq, Eq)]
37pub struct Secret(Zeroizing<[u8; 32]>);
38
39impl Secret {
40    /// A new random secret.
41    pub fn generate() -> std::io::Result<Self> {
42        let mut bytes = Zeroizing::new([0u8; 32]);
43        getrandom::fill(bytes.as_mut()).map_err(std::io::Error::other)?;
44        Ok(Self(bytes))
45    }
46
47    /// The secret from its 64 hex digits (either case; whitespace and
48    /// dashes are ignored, so a secret copied in groups, or read as a line,
49    /// still reads).
50    #[expect(
51        clippy::indexing_slicing,
52        reason = "fixed-size buffers: the header's length is checked before it is cut, and hex digits come in pairs of a 64-digit secret"
53    )]
54    pub fn parse(text: &str) -> Result<Self, InvalidSecret> {
55        // Its room reserved at once: growing would leave copies behind.
56        let mut digits = Zeroizing::new(Vec::with_capacity(text.len()));
57        digits.extend(
58            text.bytes()
59                .filter(|b| !b.is_ascii_whitespace() && *b != b'-'),
60        );
61        if digits.len() != 64 {
62            return Err(InvalidSecret);
63        }
64        let mut bytes = Zeroizing::new([0u8; 32]);
65        for (byte, pair) in bytes.iter_mut().zip(digits.chunks(2)) {
66            // `* 16 +` rather than `<< 4 |`: the same byte, but `|` mutated
67            // to `^` gives the same byte too, so no test could catch it.
68            *byte = hex_value(pair[0])? * 16 + hex_value(pair[1])?;
69        }
70        Ok(Self(bytes))
71    }
72
73    /// The secret as 64 lowercase hex digits, to print for the user. Named
74    /// so that showing it is never an accident.
75    #[expect(
76        clippy::indexing_slicing,
77        reason = "fixed-size buffers: the header's length is checked before it is cut, and hex digits come in pairs of a 64-digit secret"
78    )]
79    pub fn reveal(&self) -> Zeroizing<String> {
80        let mut text = Zeroizing::new(String::with_capacity(64));
81        for byte in self.0.iter() {
82            text.push(char::from(HEX[usize::from(byte >> 4)]));
83            text.push(char::from(HEX[usize::from(byte & 0xf)]));
84        }
85        text
86    }
87}
88
89impl fmt::Debug for Secret {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str("Secret(..)")
92    }
93}
94
95const HEX: &[u8; 16] = b"0123456789abcdef";
96
97fn hex_value(digit: u8) -> Result<u8, InvalidSecret> {
98    match digit {
99        b'0'..=b'9' => Ok(digit - b'0'),
100        b'a'..=b'f' => Ok(digit - b'a' + 10),
101        b'A'..=b'F' => Ok(digit - b'A' + 10),
102        _ => Err(InvalidSecret),
103    }
104}
105
106/// A secret that is not 64 hex digits.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct InvalidSecret;
109
110impl fmt::Display for InvalidSecret {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.write_str("the secret is not 64 hex digits")
113    }
114}
115
116impl std::error::Error for InvalidSecret {}
117
118/// Which way a message goes: each way has its own key.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum Direction {
121    /// Frontend to backend: `input` and `resize`.
122    ToBackend,
123    /// Backend to frontend: `output`, and `replay`, which reaches the
124    /// frontend as `output`.
125    ToFrontend,
126}
127
128/// What a sealed message holds, bound into it: a relay cannot pass one kind
129/// off as another.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum Kind {
132    /// Keyboard and mouse input.
133    Input,
134    /// A terminal size.
135    Resize,
136    /// Terminal output.
137    Output,
138    /// Input inside a bracketed paste.
139    Paste,
140}
141
142impl Kind {
143    fn byte(self) -> u8 {
144        match self {
145            Self::Input => 1,
146            Self::Resize => 2,
147            Self::Output => 3,
148            Self::Paste => 4,
149        }
150    }
151}
152
153/// The session's two keys, derived from the secret and the session ID.
154pub struct Keys {
155    session: SessionId,
156    to_backend: Zeroizing<[u8; 32]>,
157    to_frontend: Zeroizing<[u8; 32]>,
158}
159
160impl Keys {
161    /// HKDF-SHA256 over the secret, salted with the session ID, one key per
162    /// direction: the keys of a session carried alone in its relay session.
163    pub fn derive(secret: &Secret, session: SessionId) -> Self {
164        Self::derive_with(secret, session, None)
165    }
166
167    /// [`Keys::derive`], for one channel of a relay session that carries
168    /// several (`channel`, the session's opaque channel ID): the channel is
169    /// in the HKDF info, so a message moved to another channel, or to the
170    /// session as a whole, does not open, even under the same secret.
171    pub fn derive_on(secret: &Secret, session: SessionId, channel: &str) -> Self {
172        Self::derive_with(secret, session, Some(channel))
173    }
174
175    #[expect(
176        clippy::expect_used,
177        reason = "fixed-size slices of a header whose length was checked, and an AEAD key of the length the cipher takes"
178    )]
179    fn derive_with(secret: &Secret, session: SessionId, channel: Option<&str>) -> Self {
180        let hkdf = Hkdf::<Sha256>::new(Some(session.as_bytes()), secret.0.as_ref());
181        let key = |direction: &[u8]| {
182            let mut info = direction.to_vec();
183            if let Some(channel) = channel {
184                info.extend_from_slice(b" on channel ");
185                info.extend_from_slice(channel.as_bytes());
186            }
187            let mut key = Zeroizing::new([0u8; 32]);
188            hkdf.expand(&info, key.as_mut())
189                .expect("32 bytes is a valid HKDF-SHA256 length");
190            key
191        };
192        Self {
193            session,
194            to_backend: key(b"teter-e2e-v1 frontend to backend"),
195            to_frontend: key(b"teter-e2e-v1 backend to frontend"),
196        }
197    }
198
199    fn cipher(&self, direction: Direction) -> XChaCha20Poly1305 {
200        let key = match direction {
201            Direction::ToBackend => &self.to_backend,
202            Direction::ToFrontend => &self.to_frontend,
203        };
204        XChaCha20Poly1305::new(key.as_ref().into())
205    }
206
207    /// A sealer for what this side sends `direction`.
208    pub fn sealer(&self, direction: Direction) -> std::io::Result<Sealer> {
209        let mut sender = [0u8; SENDER_LEN];
210        getrandom::fill(&mut sender).map_err(std::io::Error::other)?;
211        Ok(Sealer {
212            cipher: self.cipher(direction),
213            session: self.session,
214            sender,
215            next: 0,
216        })
217    }
218
219    /// An opener for what the other side sends `direction`.
220    pub fn opener(&self, direction: Direction) -> Opener {
221        Opener {
222            cipher: self.cipher(direction),
223            session: self.session,
224            last: HashMap::new(),
225            refused: std::collections::HashSet::new(),
226            newly_refused: false,
227        }
228    }
229}
230
231impl fmt::Debug for Keys {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.debug_struct("Keys")
234            .field("session", &self.session)
235            .finish_non_exhaustive()
236    }
237}
238
239/// The associated data of a message: what it is bound to besides its
240/// header.
241fn associated(session: SessionId, kind: Kind, header: &[u8]) -> Vec<u8> {
242    let mut aad = Vec::with_capacity(CONTEXT.len() + 16 + 1 + header.len());
243    aad.extend_from_slice(CONTEXT);
244    aad.extend_from_slice(session.as_bytes());
245    aad.push(kind.byte());
246    aad.extend_from_slice(header);
247    aad
248}
249
250/// Who sealed a message: the random ID of one sealer.
251pub type SenderId = [u8; SENDER_LEN];
252
253/// Seals what one side sends one way. Each message gets the next number;
254/// with the sender's random ID, it makes the nonce, which is so never used
255/// twice with the key.
256pub struct Sealer {
257    cipher: XChaCha20Poly1305,
258    session: SessionId,
259    sender: [u8; SENDER_LEN],
260    next: u64,
261}
262
263impl Sealer {
264    /// `plaintext` sealed as `kind`: version, sender, number, then the
265    /// ciphertext with its tag.
266    #[expect(
267        clippy::expect_used,
268        reason = "fixed-size slices of a header whose length was checked, and an AEAD key of the length the cipher takes"
269    )]
270    pub fn seal(&mut self, kind: Kind, plaintext: &[u8]) -> Vec<u8> {
271        let seq = self.next;
272        self.next = seq.checked_add(1).expect("2^64 messages from one sender");
273        let mut header = [0u8; HEADER_LEN];
274        header[0] = VERSION;
275        header[1..1 + SENDER_LEN].copy_from_slice(&self.sender);
276        header[1 + SENDER_LEN..].copy_from_slice(&seq.to_be_bytes());
277        let nonce = XNonce::from_slice(&header[1..]);
278        let aad = associated(self.session, kind, &header);
279        let sealed = self
280            .cipher
281            .encrypt(
282                nonce,
283                Payload {
284                    msg: plaintext,
285                    aad: &aad,
286                },
287            )
288            .expect("XChaCha20-Poly1305 seals any length a message can have");
289        let mut out = Vec::with_capacity(HEADER_LEN + sealed.len());
290        out.extend_from_slice(&header);
291        out.extend_from_slice(&sealed);
292        out
293    }
294}
295
296impl fmt::Debug for Sealer {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        f.debug_struct("Sealer")
299            .field("session", &self.session)
300            .finish_non_exhaustive()
301    }
302}
303
304/// Why a sealed message was refused.
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306pub enum OpenError {
307    /// Too short, or of an unknown version.
308    Malformed,
309    /// It does not open with the key: sealed with another secret or for
310    /// another session, altered, or of another kind.
311    Forged,
312    /// Its number is not past the last one from its sender: seen before, or
313    /// older than one already opened.
314    Replayed,
315    /// From a new sender, past the senders an opener takes.
316    TooManySenders,
317}
318
319impl fmt::Display for OpenError {
320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321        f.write_str(match self {
322            Self::Malformed => "a sealed message is malformed",
323            Self::Forged => "a sealed message does not open: another secret, or altered",
324            Self::Replayed => "a sealed message was seen before",
325            Self::TooManySenders => "too many senders in this session",
326        })
327    }
328}
329
330impl std::error::Error for OpenError {}
331
332/// Opens what the other side sends one way. It keeps the last number from
333/// each sender and takes only later ones: the relay can drop or delay
334/// messages, never replay or reorder them unnoticed.
335pub struct Opener {
336    cipher: XChaCha20Poly1305,
337    session: SessionId,
338    last: HashMap<[u8; SENDER_LEN], u64>,
339    /// New senders refused, past the senders it takes, up to a bound.
340    refused: std::collections::HashSet<[u8; SENDER_LEN]>,
341    /// Whether a sender was refused for the first time since last asked.
342    newly_refused: bool,
343}
344
345impl Opener {
346    /// The plaintext of `sealed`, a message of `kind`.
347    pub fn open(&mut self, kind: Kind, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, OpenError> {
348        self.open_from(kind, sealed).map(|(plaintext, _)| plaintext)
349    }
350
351    /// The plaintext of `sealed`, a message of `kind`, and who sent it.
352    #[expect(
353        clippy::indexing_slicing,
354        clippy::expect_used,
355        clippy::map_err_ignore,
356        reason = "fixed-size buffers: the header's length is checked before it is cut, and hex digits come in pairs of a 64-digit secret; fixed-size slices of a header whose length was checked, and an AEAD key of the length the cipher takes; AEAD failure carries no cause on purpose: a forgery and a corruption must look alike"
357    )]
358    pub fn open_from(
359        &mut self,
360        kind: Kind,
361        sealed: &[u8],
362    ) -> Result<(Zeroizing<Vec<u8>>, SenderId), OpenError> {
363        if sealed.len() < HEADER_LEN + TAG_LEN || sealed[0] != VERSION {
364            return Err(OpenError::Malformed);
365        }
366        let (header, body) = sealed.split_at(HEADER_LEN);
367        let sender: [u8; SENDER_LEN] = header[1..1 + SENDER_LEN].try_into().expect("16 bytes");
368        let seq = u64::from_be_bytes(header[1 + SENDER_LEN..].try_into().expect("8 bytes"));
369        if self.last.get(&sender).is_some_and(|&last| seq <= last) {
370            return Err(OpenError::Replayed);
371        }
372        let aad = associated(self.session, kind, header);
373        let plaintext = self
374            .cipher
375            .decrypt(
376                XNonce::from_slice(&header[1..]),
377                Payload {
378                    msg: body,
379                    aad: &aad,
380                },
381            )
382            .map_err(|_| OpenError::Forged)?;
383        // Only once it opened: a forgery moves nothing.
384        if !self.last.contains_key(&sender) && self.last.len() >= MAX_SENDERS {
385            if self.refused.len() < MAX_SENDERS && self.refused.insert(sender) {
386                self.newly_refused = true;
387            }
388            return Err(OpenError::TooManySenders);
389        }
390        self.last.insert(sender, seq);
391        Ok((Zeroizing::new(plaintext), sender))
392    }
393}
394
395impl Opener {
396    /// Whether a sender has been refused for the first time since this was
397    /// last asked: each refused sender counts once.
398    pub fn take_newly_refused(&mut self) -> bool {
399        std::mem::take(&mut self.newly_refused)
400    }
401}
402
403impl fmt::Debug for Opener {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        f.debug_struct("Opener")
406            .field("session", &self.session)
407            .finish_non_exhaustive()
408    }
409}
410
411/// A terminal size as the plaintext of a sealed `resize`: columns, then
412/// rows, big-endian.
413pub fn encode_size(columns: u16, rows: u16) -> [u8; 4] {
414    let [c0, c1] = columns.to_be_bytes();
415    let [r0, r1] = rows.to_be_bytes();
416    [c0, c1, r0, r1]
417}
418
419/// The size in a sealed `resize`'s plaintext, if it is one.
420pub fn decode_size(plaintext: &[u8]) -> Option<(u16, u16)> {
421    let [c0, c1, r0, r1] = plaintext.try_into().ok()?;
422    Some((u16::from_be_bytes([c0, c1]), u16::from_be_bytes([r0, r1])))
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    fn pair() -> (Keys, Keys) {
430        let secret = Secret::generate().unwrap();
431        let session = SessionId::new_v4();
432        let backend = Keys::derive(&secret, session);
433        let frontend = Keys::derive(&Secret::parse(&secret.reveal()).unwrap(), session);
434        (backend, frontend)
435    }
436
437    #[test]
438    fn a_secret_round_trips_through_its_text() {
439        let secret = Secret::generate().unwrap();
440        let text = secret.reveal();
441        assert_eq!(text.len(), 64);
442        assert!(text.bytes().all(|b| HEX.contains(&b)));
443        assert_eq!(Secret::parse(&text).unwrap(), secret);
444        // Upper case, and grouped with spaces or dashes.
445        assert_eq!(Secret::parse(&text.to_uppercase()).unwrap(), secret);
446        let grouped: String = text
447            .as_bytes()
448            .chunks(8)
449            .map(|c| std::str::from_utf8(c).unwrap())
450            .collect::<Vec<_>>()
451            .join("-");
452        assert_eq!(Secret::parse(&grouped).unwrap(), secret);
453        // Read as a line, with its end.
454        assert_eq!(Secret::parse(&format!(" {}\r\n", *text)).unwrap(), secret);
455        assert_eq!(Secret::parse(&format!("{}\t", *text)).unwrap(), secret);
456        assert_ne!(Secret::generate().unwrap(), secret);
457    }
458
459    #[test]
460    fn a_secret_that_is_not_64_hex_digits_is_refused() {
461        assert_eq!(Secret::parse(""), Err(InvalidSecret));
462        assert_eq!(Secret::parse(&"a".repeat(63)), Err(InvalidSecret));
463        assert_eq!(Secret::parse(&"a".repeat(65)), Err(InvalidSecret));
464        assert_eq!(Secret::parse(&"g".repeat(64)), Err(InvalidSecret));
465        assert_eq!(
466            Secret::parse(&format!("{}G", "a".repeat(63))),
467            Err(InvalidSecret)
468        );
469        // Each digit's value counts.
470        let secret = Secret::parse(&format!("0f{}", "0".repeat(62))).unwrap();
471        assert!(secret.reveal().starts_with("0f00"));
472        let secret = Secret::parse(&format!("A9{}", "0".repeat(62))).unwrap();
473        assert!(secret.reveal().starts_with("a900"));
474    }
475
476    #[test]
477    fn nothing_secret_shows_in_debug() {
478        let secret = Secret::parse(&"ab".repeat(32)).unwrap();
479        assert_eq!(format!("{secret:?}"), "Secret(..)");
480        let keys = Keys::derive(&secret, SessionId::nil());
481        let shown = format!(
482            "{keys:?} {:?} {:?}",
483            keys.sealer(Direction::ToBackend).unwrap(),
484            keys.opener(Direction::ToBackend)
485        );
486        assert!(!shown.contains("ab"), "{shown}");
487        assert!(!shown.contains("171"), "{shown}");
488        for name in ["Keys", "Sealer", "Opener"] {
489            assert!(shown.contains(name), "{shown}");
490        }
491        // The errors say what went wrong.
492        assert!(InvalidSecret.to_string().contains("64 hex digits"));
493        assert!(OpenError::Forged.to_string().contains("another secret"));
494        assert!(OpenError::Replayed.to_string().contains("seen before"));
495        assert!(OpenError::Malformed.to_string().contains("malformed"));
496        assert!(
497            OpenError::TooManySenders
498                .to_string()
499                .contains("too many senders")
500        );
501    }
502
503    #[test]
504    fn what_one_side_seals_the_other_opens() {
505        let (backend, frontend) = pair();
506        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
507        let mut opener = backend.opener(Direction::ToBackend);
508        let sealed = sealer.seal(Kind::Input, b"hunter2\r");
509        assert_eq!(sealed.len(), HEADER_LEN + 8 + TAG_LEN);
510        assert!(!sealed.windows(7).any(|w| w == b"hunter2"));
511        assert_eq!(
512            &opener.open(Kind::Input, &sealed).unwrap()[..],
513            b"hunter2\r"
514        );
515        // And the other way, with the other key.
516        let mut sealer = backend.sealer(Direction::ToFrontend).unwrap();
517        let mut opener = frontend.opener(Direction::ToFrontend);
518        let sealed = sealer.seal(Kind::Output, b"$ ");
519        assert_eq!(&opener.open(Kind::Output, &sealed).unwrap()[..], b"$ ");
520        // Empty plaintext seals too.
521        let sealed = sealer.seal(Kind::Output, b"");
522        assert_eq!(&opener.open(Kind::Output, &sealed).unwrap()[..], b"");
523    }
524
525    #[test]
526    fn the_same_plaintext_never_seals_the_same() {
527        let (backend, _) = pair();
528        let mut sealer = backend.sealer(Direction::ToFrontend).unwrap();
529        let a = sealer.seal(Kind::Output, b"same");
530        let b = sealer.seal(Kind::Output, b"same");
531        assert_ne!(a[HEADER_LEN..], b[HEADER_LEN..]);
532        let mut other = backend.sealer(Direction::ToFrontend).unwrap();
533        assert_ne!(
534            a[1..1 + SENDER_LEN],
535            other.seal(Kind::Output, b"same")[1..1 + SENDER_LEN]
536        );
537    }
538
539    #[test]
540    fn a_wrong_secret_another_session_or_direction_does_not_open() {
541        let (backend, _) = pair();
542        let mut sealer = backend.sealer(Direction::ToFrontend).unwrap();
543        let sealed = sealer.seal(Kind::Output, b"screen");
544        let other = Keys::derive(&Secret::generate().unwrap(), backend.session);
545        assert_eq!(
546            other
547                .opener(Direction::ToFrontend)
548                .open(Kind::Output, &sealed),
549            Err(OpenError::Forged)
550        );
551        let secret = Secret::parse(&"11".repeat(32)).unwrap();
552        let here = Keys::derive(&secret, SessionId::new_v4());
553        let elsewhere = Keys::derive(&secret, SessionId::new_v4());
554        let sealed = here
555            .sealer(Direction::ToFrontend)
556            .unwrap()
557            .seal(Kind::Output, b"x");
558        assert_eq!(
559            elsewhere
560                .opener(Direction::ToFrontend)
561                .open(Kind::Output, &sealed),
562            Err(OpenError::Forged)
563        );
564        // Sealed one way, opened as the other.
565        assert_eq!(
566            here.opener(Direction::ToBackend)
567                .open(Kind::Output, &sealed),
568            Err(OpenError::Forged)
569        );
570    }
571
572    #[test]
573    fn an_altered_message_or_one_of_another_kind_does_not_open() {
574        let (backend, frontend) = pair();
575        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
576        let mut opener = backend.opener(Direction::ToBackend);
577        let sealed = sealer.seal(Kind::Input, b"ls\r");
578        for at in 1..sealed.len() {
579            let mut altered = sealed.clone();
580            altered[at] ^= 1;
581            assert!(opener.open(Kind::Input, &altered).is_err(), "byte {at}");
582        }
583        assert_eq!(opener.open(Kind::Resize, &sealed), Err(OpenError::Forged));
584        // The original still opens: refusals moved nothing.
585        assert!(opener.open(Kind::Input, &sealed).is_ok());
586    }
587
588    #[test]
589    fn a_malformed_message_is_refused() {
590        let (backend, _) = pair();
591        let mut opener = backend.opener(Direction::ToBackend);
592        assert_eq!(opener.open(Kind::Input, b""), Err(OpenError::Malformed));
593        assert_eq!(
594            opener.open(Kind::Input, &[VERSION; HEADER_LEN + TAG_LEN - 1]),
595            Err(OpenError::Malformed)
596        );
597        let mut sealed = backend
598            .sealer(Direction::ToBackend)
599            .unwrap()
600            .seal(Kind::Input, b"");
601        assert_eq!(sealed.len(), HEADER_LEN + TAG_LEN);
602        assert!(
603            backend
604                .opener(Direction::ToBackend)
605                .open(Kind::Input, &sealed)
606                .is_ok()
607        );
608        sealed[0] = 2;
609        assert_eq!(opener.open(Kind::Input, &sealed), Err(OpenError::Malformed));
610    }
611
612    #[test]
613    fn a_replayed_or_older_message_is_refused() {
614        let (backend, frontend) = pair();
615        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
616        let mut opener = backend.opener(Direction::ToBackend);
617        let first = sealer.seal(Kind::Input, b"a");
618        let second = sealer.seal(Kind::Input, b"b");
619        let third = sealer.seal(Kind::Input, b"c");
620        assert!(opener.open(Kind::Input, &second).is_ok());
621        assert_eq!(opener.open(Kind::Input, &second), Err(OpenError::Replayed));
622        // Older than one opened: refused; a gap is fine (dropped messages).
623        assert_eq!(opener.open(Kind::Input, &first), Err(OpenError::Replayed));
624        assert!(opener.open(Kind::Input, &third).is_ok());
625        // Each sender has its own numbers.
626        let mut another = frontend.sealer(Direction::ToBackend).unwrap();
627        assert!(
628            opener
629                .open(Kind::Input, &another.seal(Kind::Input, b"d"))
630                .is_ok()
631        );
632        assert!(
633            opener
634                .open(Kind::Resize, &sealer.seal(Kind::Resize, &encode_size(1, 2)))
635                .is_ok()
636        );
637    }
638
639    #[test]
640    #[expect(
641        clippy::let_underscore_must_use,
642        reason = "the test checks what the opener records, not what open returns"
643    )]
644    fn a_new_sender_past_the_limit_is_refused_and_none_is_forgotten() {
645        let (backend, frontend) = pair();
646        let mut opener = backend.opener(Direction::ToBackend);
647        let mut first = frontend.sealer(Direction::ToBackend).unwrap();
648        let old = first.seal(Kind::Input, b"old");
649        assert!(opener.open(Kind::Input, &old).is_ok());
650        for _ in 1..MAX_SENDERS {
651            let mut sender = frontend.sealer(Direction::ToBackend).unwrap();
652            assert!(
653                opener
654                    .open(Kind::Input, &sender.seal(Kind::Input, b"x"))
655                    .is_ok()
656            );
657        }
658        assert_eq!(opener.last.len(), MAX_SENDERS);
659        let mut newest = frontend.sealer(Direction::ToBackend).unwrap();
660        assert!(!opener.take_newly_refused());
661        assert_eq!(
662            opener.open(Kind::Input, &newest.seal(Kind::Input, b"y")),
663            Err(OpenError::TooManySenders)
664        );
665        assert!(opener.take_newly_refused());
666        assert!(!opener.take_newly_refused(), "told once per ask");
667        // The same sender again: not new.
668        let _ = opener.open(Kind::Input, &newest.seal(Kind::Input, b"y2"));
669        assert!(!opener.take_newly_refused());
670        // Another new sender: new.
671        let mut other = frontend.sealer(Direction::ToBackend).unwrap();
672        let _ = opener.open(Kind::Input, &other.seal(Kind::Input, b"o"));
673        assert!(opener.take_newly_refused());
674        // The first sender is still known: its replay is refused, and its
675        // next message opens.
676        assert_eq!(opener.open(Kind::Input, &old), Err(OpenError::Replayed));
677        assert!(
678            opener
679                .open(Kind::Input, &first.seal(Kind::Input, b"z"))
680                .is_ok()
681        );
682        // A forgery from a new sender is a forgery, limit or not.
683        let mut forged = newest.seal(Kind::Input, b"f");
684        let last = forged.len() - 1;
685        forged[last] ^= 1;
686        assert_eq!(opener.open(Kind::Input, &forged), Err(OpenError::Forged));
687        // Refused senders are told up to the bound, and none past it.
688        while opener.refused.len() < MAX_SENDERS {
689            let mut sender = frontend.sealer(Direction::ToBackend).unwrap();
690            let _ = opener.open(Kind::Input, &sender.seal(Kind::Input, b"r"));
691            assert!(opener.take_newly_refused());
692        }
693        let mut past = frontend.sealer(Direction::ToBackend).unwrap();
694        assert_eq!(
695            opener.open(Kind::Input, &past.seal(Kind::Input, b"p")),
696            Err(OpenError::TooManySenders)
697        );
698        assert!(!opener.take_newly_refused(), "told past the bound");
699        assert_eq!(opener.refused.len(), MAX_SENDERS);
700    }
701
702    #[test]
703    fn paste_is_a_kind_of_its_own_and_the_sender_is_told() {
704        let (backend, frontend) = pair();
705        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
706        let mut opener = backend.opener(Direction::ToBackend);
707        let pasted = sealer.seal(Kind::Paste, b"p");
708        // Not input: a relay cannot pass typed input off as paste, or back.
709        assert_eq!(opener.open(Kind::Input, &pasted), Err(OpenError::Forged));
710        let (plaintext, sender) = opener.open_from(Kind::Paste, &pasted).unwrap();
711        assert_eq!(&plaintext[..], b"p");
712        assert_eq!(sender, sealer.sender);
713        let typed = sealer.seal(Kind::Input, b"t");
714        assert_eq!(opener.open(Kind::Paste, &typed), Err(OpenError::Forged));
715        let (_, again) = opener.open_from(Kind::Input, &typed).unwrap();
716        assert_eq!(again, sender);
717    }
718
719    #[test]
720    fn a_size_round_trips() {
721        assert_eq!(decode_size(&encode_size(80, 24)), Some((80, 24)));
722        assert_eq!(
723            decode_size(&encode_size(0x1234, 0xabcd)),
724            Some((0x1234, 0xabcd))
725        );
726        assert_eq!(encode_size(0x1234, 0xabcd), [0x12, 0x34, 0xab, 0xcd]);
727        assert_eq!(decode_size(&[1, 2, 3]), None);
728        assert_eq!(decode_size(&[1, 2, 3, 4, 5]), None);
729    }
730
731    #[test]
732    fn the_keys_follow_a_known_derivation() {
733        // A fixed secret and session give fixed keys: the derivation is
734        // part of the protocol, and must not change by accident. The values
735        // come from an independent HKDF-SHA256 (Python's hmac and hashlib).
736        let secret = Secret::parse(&"00".repeat(32)).unwrap();
737        let keys = Keys::derive(&secret, SessionId::nil());
738        let hex = |k: &[u8; 32]| k.iter().map(|b| format!("{b:02x}")).collect::<String>();
739        let pinned = (hex(&keys.to_backend), hex(&keys.to_frontend));
740        assert_ne!(pinned.0, pinned.1);
741        assert_eq!(
742            pinned,
743            (
744                String::from("026099e9d850ab7ef27762ea7e6c8590bb153abae1261881b66d32b2a24e9b42"),
745                String::from("7b11817c258cfdc9b023206880109ea790e6ec441440e0dc413f9307d02dc870")
746            )
747        );
748    }
749
750    #[test]
751    fn a_message_moved_to_another_channel_does_not_open() {
752        let secret = Secret::generate().unwrap();
753        let session = SessionId::new_v4();
754        let on_a = Keys::derive_on(&secret, session, "aaaa");
755        let mut sealer = on_a.sealer(Direction::ToFrontend).unwrap();
756        let sealed = sealer.seal(Kind::Output, b"for channel a");
757        // Its own channel opens it.
758        let mut opener = on_a.opener(Direction::ToFrontend);
759        assert_eq!(
760            opener.open(Kind::Output, &sealed).unwrap().as_slice(),
761            b"for channel a"
762        );
763        // Another channel, or the session as a whole, under the same secret,
764        // does not.
765        for keys in [
766            Keys::derive_on(&secret, session, "bbbb"),
767            Keys::derive(&secret, session),
768        ] {
769            assert!(
770                keys.opener(Direction::ToFrontend)
771                    .open(Kind::Output, &sealed)
772                    .is_err()
773            );
774        }
775        // And a channel-less message does not open on a channel.
776        let plain = Keys::derive(&secret, session)
777            .sealer(Direction::ToFrontend)
778            .unwrap()
779            .seal(Kind::Output, b"whole session");
780        assert!(
781            on_a.opener(Direction::ToFrontend)
782                .open(Kind::Output, &plain)
783                .is_err()
784        );
785    }
786}