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