Skip to main content

matter_kit/msg/
security.rs

1//! Encrypting and decrypting a Matter message (Core §4.8, §4.9).
2//!
3//! Everything above the message header travels encrypted, and the header itself travels
4//! *authenticated but in the clear* — a receiver has to read the Session ID before it can
5//! find the key. That is why the header is the AEAD's associated data rather than part of
6//! its payload: changing a single bit of it breaks the tag, but anyone can still read it.
7//!
8//! ```text
9//!  ┌──────────── associated data (authenticated, clear) ────────────┐┌ encrypted ┐┌ tag ┐
10//!  │ flags │ session │ sec │ counter │ [source] │ [dest] │ [ext]    ││  payload  ││ MIC │
11//!  └───────┴─────────┴─────┴─────────┴──────────┴────────┴──────────┘└───────────┘└─────┘
12//!           ╰──── never obfuscated ────╯╰─── obfuscated when P is set ───╯
13//! ```
14//!
15//! # Privacy
16//!
17//! With the **P** flag set, the counter and node ids are additionally obfuscated with
18//! AES-CTR under a key derived from the encryption key (§4.9). This does not add
19//! confidentiality — they are already authenticated, and an attacker who has the key can
20//! read them either way — it removes a *correlation handle*: without it, a passive observer
21//! can follow one node across a network by its monotonically increasing counter.
22//!
23//! The first four octets are deliberately outside the obfuscation, because a receiver must
24//! read the Session ID to know which key to try.
25//!
26//! # The nonce, and why it is an enum
27//!
28//! §4.8.1.1 gives three different answers for the nonce's Source Node ID depending on the
29//! session: a CASE session uses the peer's operational id from the session context, a PASE
30//! session uses the Unspecified Node ID, and a group message uses the id in the message.
31//! Passing a bare `NodeId` would make all three look the same at the call site and let a
32//! caller silently pick the wrong one — so [`NonceSource`] names them.
33
34use super::header::{Destination, MessageHeader, SessionType};
35use super::ids::NodeId;
36use crate::crypto::{
37    AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, SymmetricKey, aead_decrypt_in_place,
38    aead_encrypt_in_place, privacy_key, privacy_xor,
39};
40use crate::error::{Error, ErrorCode, Result, bail};
41
42/// The keys one session protects its messages with.
43///
44/// The privacy key is derived from the encryption key once, at session establishment,
45/// rather than per message: it is a KDF call, and doing it on every send would be visible
46/// on a microcontroller.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct SessionKeys {
49    /// The AEAD key for this direction (§4.8).
50    pub encryption: SymmetricKey,
51    /// The AES-CTR key for header obfuscation (§4.9.1).
52    pub privacy: SymmetricKey,
53}
54
55impl SessionKeys {
56    /// Derives the privacy key from an encryption key (§4.9.1).
57    pub fn from_encryption_key(encryption: SymmetricKey) -> Result<Self> {
58        let privacy = privacy_key(&encryption)?;
59        Ok(Self {
60            encryption,
61            privacy,
62        })
63    }
64}
65
66/// Where the Source Node ID in the AEAD nonce comes from (§4.8.1.1).
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum NonceSource {
69    /// A PASE session: "the Nonce Source Node ID SHALL be Unspecified Node ID".
70    ///
71    /// Safe despite being a constant, and the specification says why: "Because PASE
72    /// negotiates strong one-time keys per session and the I2RKey and R2IKey are distinct
73    /// for each direction of communication, the use of the Unspecified Node ID as the
74    /// Nonce Source Node ID remains semantically secure."
75    Pase,
76    /// A CASE session: "determined via the Secure Session Context associated with the
77    /// Session Identifier" — the operational Node ID of whoever protected the message.
78    Case(NodeId),
79    /// A group message: the Source Node ID carried in the message itself.
80    ///
81    /// "The S Flag of the message SHALL be 1 … If the S Flag of the message is 0 the
82    /// message SHALL be dropped."
83    Group,
84}
85
86impl NonceSource {
87    fn resolve(self, header: &MessageHeader) -> Result<NodeId> {
88        match self {
89            Self::Pase => Ok(NodeId::UNSPECIFIED),
90            Self::Case(id) => Ok(id),
91            Self::Group => header.source.ok_or(Error::new(ErrorCode::MessageReserved)),
92        }
93    }
94}
95
96/// Builds the AEAD nonce of Table 17: `Security Flags || Message Counter || Source Node ID`.
97///
98/// "The scalar fields in the nonce … SHALL be encoded in little-endian byte order … that
99/// is, in the same byte ordering as the segment of the message from which its data
100/// originates."
101fn nonce(
102    security_flags: u8,
103    message_counter: u32,
104    source: NodeId,
105) -> [u8; AEAD_NONCE_LENGTH_BYTES] {
106    let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
107    out[0] = security_flags;
108    // Indices are constant and within a 13-octet array.
109    if let Some(slot) = out.get_mut(1..5) {
110        slot.copy_from_slice(&message_counter.to_le_bytes());
111    }
112    if let Some(slot) = out.get_mut(5..13) {
113        slot.copy_from_slice(&source.0.to_le_bytes());
114    }
115    out
116}
117
118/// Builds the privacy nonce of §4.9.2: `Session ID (big-endian) || MIC[5..16]`.
119fn privacy_nonce(
120    session_id: u16,
121    mic: &[u8; AEAD_MIC_LENGTH_BYTES],
122) -> Result<[u8; AEAD_NONCE_LENGTH_BYTES]> {
123    let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
124    // "the 16-bit Session ID (in big-endian format)" — the one place in the message layer
125    // where a scalar is *not* little-endian.
126    let Some(slot) = out.get_mut(..2) else {
127        bail!(BufferTooSmall)
128    };
129    slot.copy_from_slice(&session_id.to_be_bytes());
130    let (Some(dst), Some(src)) = (out.get_mut(2..13), mic.get(5..16)) else {
131        bail!(BufferTooSmall)
132    };
133    dst.copy_from_slice(src);
134    Ok(out)
135}
136
137/// How many header octets the privacy step obfuscates.
138///
139/// "M = Message Counter || [Source ID] || [Destination ID]" — the counter and the node ids,
140/// and nothing before or after them. The four octets before (flags, session id, security
141/// flags) stay readable because a receiver needs them to find the key; the message
142/// extensions after are excluded by §4.4.1.7.
143const PRIVACY_OFFSET: usize = 4;
144
145fn privacy_len(header: &MessageHeader) -> usize {
146    let counter = 4usize;
147    let source = if header.source.is_some() { 8 } else { 0 };
148    let destination = match header.destination {
149        Destination::None => 0,
150        Destination::Node(_) => 8,
151        Destination::Group(_) => 2,
152    };
153    counter.saturating_add(source).saturating_add(destination)
154}
155
156/// Encrypts one message into `out`, returning how many octets it occupies.
157///
158/// `payload` is the protocol header and application payload — everything that travels
159/// encrypted. The header's `privacy` flag decides whether §4.9's obfuscation is applied.
160///
161/// The result is `header || ciphertext || MIC`.
162pub fn protect(
163    header: &MessageHeader,
164    nonce_source: NonceSource,
165    payload: &[u8],
166    keys: &SessionKeys,
167    out: &mut [u8],
168) -> Result<usize> {
169    if header.is_unsecured() {
170        // §4.4.2.1: "The Message Integrity Check field SHALL be present for all messages
171        // except those of Unsecured Session Type." Protecting one would be a
172        // contradiction, so it is refused rather than silently producing a message with a
173        // tag nobody will check.
174        bail!(InvalidState)
175    }
176    if matches!(header.session_type, SessionType::Group) && header.source.is_none() {
177        // §4.8.1.1: a group message without a Source Node ID has no nonce.
178        bail!(MessageReserved)
179    }
180
181    let header_len = header.encode(out)?;
182    let source = nonce_source.resolve(header)?;
183    let n = nonce(security_flags_of(header), header.message_counter, source);
184
185    // The associated data is the header exactly as encoded — no re-serialisation, so the
186    // bytes that are authenticated are provably the bytes that are sent.
187    let Some(aad) = out.get(..header_len) else {
188        bail!(BufferTooSmall)
189    };
190    let mut aad_copy = [0u8; MAX_HEADER];
191    let Some(aad_slot) = aad_copy.get_mut(..header_len) else {
192        bail!(BufferTooSmall)
193    };
194    aad_slot.copy_from_slice(aad);
195
196    let cipher_end = header_len
197        .checked_add(payload.len())
198        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
199    let total = cipher_end
200        .checked_add(AEAD_MIC_LENGTH_BYTES)
201        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
202    let Some(body) = out.get_mut(header_len..cipher_end) else {
203        bail!(BufferTooSmall)
204    };
205    body.copy_from_slice(payload);
206
207    let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
208    aead_encrypt_in_place(&keys.encryption, &n, aad_slot, body, &mut tag)?;
209
210    let Some(mic) = out.get_mut(cipher_end..total) else {
211        bail!(BufferTooSmall)
212    };
213    mic.copy_from_slice(&tag);
214
215    if header.privacy {
216        // §4.9.3, and note the order: obfuscation happens *after* encryption, because its
217        // nonce is built from the MIC that encryption produced.
218        let nonce = privacy_nonce(header.session_id.0, &tag)?;
219        let end = PRIVACY_OFFSET
220            .checked_add(privacy_len(header))
221            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
222        let Some(region) = out.get_mut(PRIVACY_OFFSET..end) else {
223            bail!(BufferTooSmall)
224        };
225        privacy_xor(&keys.privacy, &nonce, region)?;
226    }
227
228    Ok(total)
229}
230
231/// The largest message header: flags, session, security, counter, source and destination.
232const MAX_HEADER: usize = 1 + 2 + 1 + 4 + 8 + 8;
233
234/// Reconstructs the Security Flags octet a header encodes to.
235fn security_flags_of(header: &MessageHeader) -> u8 {
236    let mut bits = match header.session_type {
237        SessionType::Unicast => 0u8,
238        SessionType::Group => 1,
239    };
240    if header.privacy {
241        bits |= 0b1000_0000;
242    }
243    if header.control {
244        bits |= 0b0100_0000;
245    }
246    bits
247}
248
249/// What a receiver can read before it has found a key.
250///
251/// The first four octets are never obfuscated and never encrypted, which is what makes a
252/// session lookup possible at all.
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub struct Preview {
255    /// Which session's keys to try.
256    pub session_id: super::ids::SessionId,
257    /// Unicast or group — it decides which counter rule and which key set apply.
258    pub session_type: SessionType,
259    /// Whether the header is obfuscated.
260    pub privacy: bool,
261    /// Whether this is a control message, which counts on its own counter.
262    pub control: bool,
263}
264
265/// Reads the four octets of a message that are always in the clear.
266///
267/// This is the first thing a receiver does: it cannot parse the rest of the header until
268/// it has deobfuscated it, and it cannot deobfuscate it until it has found the session.
269pub fn preview(buf: &[u8]) -> Result<Preview> {
270    let (Some(&flags), Some(session), Some(&security)) = (buf.first(), buf.get(1..3), buf.get(3))
271    else {
272        bail!(MessageTruncated)
273    };
274    if (flags >> 4) != super::header::MESSAGE_FORMAT_VERSION {
275        bail!(UnsupportedVersion)
276    }
277    let Ok(id) = <[u8; 2]>::try_from(session) else {
278        bail!(MessageTruncated)
279    };
280    let session_type = match security & 0b11 {
281        0 => SessionType::Unicast,
282        1 => SessionType::Group,
283        _ => bail!(MessageReserved),
284    };
285    Ok(Preview {
286        session_id: super::ids::SessionId(u16::from_le_bytes(id)),
287        session_type,
288        privacy: security & 0b1000_0000 != 0,
289        control: security & 0b0100_0000 != 0,
290    })
291}
292
293/// Decrypts one message in place, returning its header and the range of `buf` holding the
294/// plaintext payload.
295///
296/// On success `buf[range]` is the protocol header and application payload. On failure the
297/// contents of `buf` are unspecified — §3.6.2 is explicit that a failed tag check leaves
298/// the payload undefined — so a caller must not look at it.
299pub fn unprotect(
300    buf: &mut [u8],
301    keys: &SessionKeys,
302    nonce_source: NonceSource,
303) -> Result<(MessageHeader, core::ops::Range<usize>)> {
304    let head = preview(buf)?;
305
306    if head.privacy {
307        // Deobfuscate before parsing: the counter and node ids are unreadable until now,
308        // and the header cannot be parsed without them.
309        let total = buf.len();
310        let mic_start = total
311            .checked_sub(AEAD_MIC_LENGTH_BYTES)
312            .ok_or(Error::new(ErrorCode::MessageTruncated))?;
313        let Some(mic) = buf.get(mic_start..total) else {
314            bail!(MessageTruncated)
315        };
316        let Ok(mic) = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic) else {
317            bail!(MessageTruncated)
318        };
319        let nonce = privacy_nonce(head.session_id.0, &mic)?;
320
321        // The obfuscated region's length depends on the Message Flags, which are in the
322        // clear — so it can be computed without decrypting anything.
323        let Some(&flags) = buf.first() else {
324            bail!(MessageTruncated)
325        };
326        let obfuscated = privacy_len_from_flags(flags)?;
327        let end = PRIVACY_OFFSET
328            .checked_add(obfuscated)
329            .ok_or(Error::new(ErrorCode::MessageTruncated))?;
330        let Some(region) = buf.get_mut(PRIVACY_OFFSET..end) else {
331            bail!(MessageTruncated)
332        };
333        privacy_xor(&keys.privacy, &nonce, region)?;
334    }
335
336    let (header, rest) = MessageHeader::decode(buf)?;
337    if header.is_unsecured() {
338        // Nothing to unprotect; a caller that reached here has a session key for a session
339        // that does not use one.
340        bail!(InvalidState)
341    }
342    // §4.7.2's validity checks that depend on the session type.
343    match header.session_type {
344        SessionType::Unicast => {
345            if matches!(header.destination, Destination::Group(_)) {
346                // "If the message is of Secure Unicast Session Type: The DSIZ field SHALL
347                // NOT indicate a Group ID is present."
348                bail!(MessageReserved)
349            }
350        }
351        SessionType::Group => {
352            if matches!(header.destination, Destination::None) || header.source.is_none() {
353                // "The DSIZ field SHALL NOT be 0. The S Flag field SHALL NOT be 0."
354                bail!(MessageReserved)
355            }
356        }
357    }
358
359    let header_len = buf.len().saturating_sub(rest.len());
360    let mut aad = [0u8; MAX_HEADER];
361    let (Some(aad_slot), Some(header_bytes)) = (aad.get_mut(..header_len), buf.get(..header_len))
362    else {
363        bail!(MessageTruncated)
364    };
365    aad_slot.copy_from_slice(header_bytes);
366
367    let total = buf.len();
368    let mic_start = total
369        .checked_sub(AEAD_MIC_LENGTH_BYTES)
370        .ok_or(Error::new(ErrorCode::MessageTruncated))?;
371    if mic_start < header_len {
372        bail!(MessageTruncated)
373    }
374    let Some(mic) = buf.get(mic_start..total) else {
375        bail!(MessageTruncated)
376    };
377    let Ok(tag) = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic) else {
378        bail!(MessageTruncated)
379    };
380
381    let source = nonce_source.resolve(&header)?;
382    let n = nonce(security_flags_of(&header), header.message_counter, source);
383
384    let Some(body) = buf.get_mut(header_len..mic_start) else {
385        bail!(MessageTruncated)
386    };
387    aead_decrypt_in_place(&keys.encryption, &n, aad_slot, body, &tag)?;
388
389    Ok((header, header_len..mic_start))
390}
391
392/// The obfuscated region's length, from the Message Flags octet alone.
393fn privacy_len_from_flags(flags: u8) -> Result<usize> {
394    let source = if flags & 0b0000_0100 != 0 { 8 } else { 0 };
395    let destination = match flags & 0b11 {
396        0 => 0usize,
397        1 => 8,
398        2 => 2,
399        _ => bail!(MessageReserved),
400    };
401    Ok(4usize.saturating_add(source).saturating_add(destination))
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407    use crate::msg::{ExchangeId, GroupId, ProtocolHeader, ProtocolId, SessionId};
408
409    fn keys() -> SessionKeys {
410        SessionKeys::from_encryption_key(SymmetricKey::new([0x5A; 16])).expect("derive")
411    }
412
413    fn case_header() -> MessageHeader {
414        MessageHeader {
415            session_id: SessionId(0x1234),
416            message_counter: 0x0102_0304,
417            ..MessageHeader::default()
418        }
419    }
420
421    #[test]
422    fn the_nonce_is_table_17() {
423        // Security Flags(1) || Message Counter(4, LE) || Source Node ID(8, LE).
424        let n = nonce(0x80, 0x0A0B_0C0D, NodeId(0x1122_3344_5566_7788));
425        assert_eq!(
426            n,
427            [
428                0x80, // security flags
429                0x0D, 0x0C, 0x0B, 0x0A, // counter, little-endian
430                0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, // source, little-endian
431            ]
432        );
433    }
434
435    #[test]
436    fn the_privacy_nonce_matches_the_specs_worked_example() {
437        // §4.9.2 prints this one in full: session 42, and a given MIC.
438        let mic = [
439            0xc5, 0xa0, 0x06, 0x3a, 0xd5, 0xd2, 0x51, 0x81, 0x91, 0x40, 0x0d, 0xd6, 0x8c, 0x5c,
440            0x16, 0x3b,
441        ];
442        let n = privacy_nonce(42, &mic).expect("nonce");
443        assert_eq!(
444            n,
445            [
446                0x00, 0x2a, // session id, big-endian
447                0xd2, 0x51, 0x81, 0x91, 0x40, 0x0d, 0xd6, 0x8c, 0x5c, 0x16,
448                0x3b, // MIC[5..16]
449            ]
450        );
451    }
452
453    #[test]
454    fn a_case_message_round_trips() {
455        let keys = keys();
456        let header = case_header();
457        let payload = b"protocol header and payload";
458
459        let mut buf = [0u8; 256];
460        let n = protect(
461            &header,
462            NonceSource::Case(NodeId(7)),
463            payload,
464            &keys,
465            &mut buf,
466        )
467        .expect("protect");
468
469        let (decoded, range) =
470            unprotect(&mut buf[..n], &keys, NonceSource::Case(NodeId(7))).expect("unprotect");
471        assert_eq!(decoded, header);
472        assert_eq!(&buf[range], payload);
473    }
474
475    #[test]
476    fn a_pase_message_round_trips() {
477        let keys = keys();
478        let header = case_header();
479        let payload = b"pake1";
480        let mut buf = [0u8; 128];
481        let n = protect(&header, NonceSource::Pase, payload, &keys, &mut buf).expect("protect");
482        let (_, range) = unprotect(&mut buf[..n], &keys, NonceSource::Pase).expect("unprotect");
483        assert_eq!(&buf[range], payload);
484    }
485
486    #[test]
487    fn the_wrong_nonce_source_does_not_decrypt() {
488        // The whole reason `NonceSource` is an enum: picking the wrong one is a silent
489        // interoperability failure, and this is what it looks like.
490        let keys = keys();
491        let header = case_header();
492        let mut buf = [0u8; 128];
493        let n =
494            protect(&header, NonceSource::Case(NodeId(7)), b"x", &keys, &mut buf).expect("protect");
495        assert_eq!(
496            unprotect(&mut buf[..n], &keys, NonceSource::Pase)
497                .unwrap_err()
498                .code(),
499            ErrorCode::IntegrityCheckFailed
500        );
501    }
502
503    #[test]
504    fn a_private_message_round_trips_and_hides_the_counter() {
505        let keys = keys();
506        let header = MessageHeader {
507            privacy: true,
508            source: Some(NodeId(0x1122_3344_5566_7788)),
509            destination: Destination::Node(NodeId(9)),
510            ..case_header()
511        };
512        let payload = b"obfuscated header, encrypted body";
513
514        let mut buf = [0u8; 256];
515        let n = protect(
516            &header,
517            NonceSource::Case(NodeId(0x1122_3344_5566_7788)),
518            payload,
519            &keys,
520            &mut buf,
521        )
522        .expect("protect");
523
524        // The counter is not readable on the wire…
525        assert_ne!(
526            &buf[4..8],
527            &header.message_counter.to_le_bytes(),
528            "the counter should be obfuscated"
529        );
530        // …but the first four octets are, because a receiver needs them.
531        let head = preview(&buf[..n]).expect("preview");
532        assert_eq!(head.session_id, header.session_id);
533        assert!(head.privacy);
534
535        let (decoded, range) = unprotect(
536            &mut buf[..n],
537            &keys,
538            NonceSource::Case(NodeId(0x1122_3344_5566_7788)),
539        )
540        .expect("unprotect");
541        assert_eq!(decoded, header);
542        assert_eq!(&buf[range], payload);
543    }
544
545    #[test]
546    fn a_group_message_round_trips() {
547        let keys = keys();
548        let header = MessageHeader {
549            session_type: SessionType::Group,
550            session_id: SessionId(5),
551            source: Some(NodeId(42)),
552            destination: Destination::Group(GroupId(7)),
553            ..MessageHeader::default()
554        };
555        let mut buf = [0u8; 128];
556        let n = protect(&header, NonceSource::Group, b"grouped", &keys, &mut buf).expect("protect");
557        let (decoded, range) =
558            unprotect(&mut buf[..n], &keys, NonceSource::Group).expect("unprotect");
559        assert_eq!(decoded.source, Some(NodeId(42)));
560        assert_eq!(&buf[range], b"grouped");
561    }
562
563    #[test]
564    fn a_group_message_without_a_source_is_refused() {
565        // §4.8.1.1: "If the S Flag of the message is 0 the message SHALL be dropped" —
566        // there is no nonce without it.
567        let keys = keys();
568        let header = MessageHeader {
569            session_type: SessionType::Group,
570            session_id: SessionId(5),
571            destination: Destination::Group(GroupId(7)),
572            ..MessageHeader::default()
573        };
574        let mut buf = [0u8; 128];
575        assert_eq!(
576            protect(&header, NonceSource::Group, b"x", &keys, &mut buf)
577                .unwrap_err()
578                .code(),
579            ErrorCode::MessageReserved
580        );
581    }
582
583    #[test]
584    fn an_unsecured_message_cannot_be_protected() {
585        let keys = keys();
586        let mut buf = [0u8; 64];
587        assert_eq!(
588            protect(
589                &MessageHeader::default(),
590                NonceSource::Pase,
591                b"x",
592                &keys,
593                &mut buf
594            )
595            .unwrap_err()
596            .code(),
597            ErrorCode::InvalidState
598        );
599    }
600
601    #[test]
602    fn every_single_bit_flip_is_caught() {
603        // The header is authenticated even though it is readable; the payload and MIC
604        // obviously are. Nothing in the message may be changed without detection.
605        let keys = keys();
606        let header = case_header();
607        let mut buf = [0u8; 128];
608        let n = protect(
609            &header,
610            NonceSource::Case(NodeId(7)),
611            b"payload",
612            &keys,
613            &mut buf,
614        )
615        .expect("protect");
616        let original = buf;
617
618        for byte in 0..n {
619            for bit in 0..8u32 {
620                let mut broken = original;
621                broken[byte] ^= 1u8 << bit;
622                let result = unprotect(&mut broken[..n], &keys, NonceSource::Case(NodeId(7)));
623                assert!(
624                    result.is_err(),
625                    "flipping bit {bit} of octet {byte} went undetected"
626                );
627            }
628        }
629    }
630
631    #[test]
632    fn the_wrong_key_does_not_decrypt() {
633        let keys = keys();
634        let other = SessionKeys::from_encryption_key(SymmetricKey::new([0xA5; 16])).expect("k");
635        let mut buf = [0u8; 128];
636        let n = protect(&case_header(), NonceSource::Pase, b"x", &keys, &mut buf).expect("protect");
637        assert!(unprotect(&mut buf[..n], &other, NonceSource::Pase).is_err());
638    }
639
640    #[test]
641    fn a_group_id_on_a_unicast_session_is_refused() {
642        // §4.7.2: "If the message is of Secure Unicast Session Type: The DSIZ field SHALL
643        // NOT indicate a Group ID is present."
644        let keys = keys();
645        let header = MessageHeader {
646            destination: Destination::Group(GroupId(1)),
647            ..case_header()
648        };
649        let mut buf = [0u8; 128];
650        let n =
651            protect(&header, NonceSource::Case(NodeId(1)), b"x", &keys, &mut buf).expect("protect");
652        assert_eq!(
653            unprotect(&mut buf[..n], &keys, NonceSource::Case(NodeId(1)))
654                .unwrap_err()
655                .code(),
656            ErrorCode::MessageReserved
657        );
658    }
659
660    #[test]
661    fn truncation_at_every_length_is_an_error_not_a_panic() {
662        let keys = keys();
663        let mut buf = [0u8; 128];
664        let n = protect(
665            &case_header(),
666            NonceSource::Pase,
667            b"payload",
668            &keys,
669            &mut buf,
670        )
671        .expect("protect");
672        for cut in 0..n {
673            let mut copy = buf;
674            let _ = unprotect(&mut copy[..cut], &keys, NonceSource::Pase);
675        }
676    }
677
678    #[test]
679    fn a_whole_message_round_trips_with_its_protocol_header() {
680        // What a real send path does: encode the protocol header, protect the result.
681        let keys = keys();
682        let protocol = ProtocolHeader {
683            initiator: true,
684            reliability: true,
685            exchange_id: ExchangeId(3),
686            protocol: ProtocolId::SECURE_CHANNEL,
687            opcode: 0x20,
688            ..ProtocolHeader::default()
689        };
690        let mut inner = [0u8; 64];
691        let inner_len = protocol.encode(&mut inner).expect("encode");
692
693        let mut buf = [0u8; 256];
694        let n = protect(
695            &case_header(),
696            NonceSource::Pase,
697            &inner[..inner_len],
698            &keys,
699            &mut buf,
700        )
701        .expect("protect");
702
703        let (_, range) = unprotect(&mut buf[..n], &keys, NonceSource::Pase).expect("unprotect");
704        let (decoded, app) = ProtocolHeader::decode(&buf[range]).expect("decode");
705        assert_eq!(decoded, protocol);
706        assert!(app.is_empty());
707    }
708
709    #[test]
710    fn the_preview_refuses_what_the_header_would() {
711        assert_eq!(
712            preview(&[]).unwrap_err().code(),
713            ErrorCode::MessageTruncated
714        );
715        assert_eq!(
716            preview(&[0x10, 0, 0, 0]).unwrap_err().code(),
717            ErrorCode::UnsupportedVersion
718        );
719        assert_eq!(
720            preview(&[0x00, 0, 0, 0x02]).unwrap_err().code(),
721            ErrorCode::MessageReserved
722        );
723    }
724}