Skip to main content

matter_kit/icd/
checkin.rs

1//! The Check-In Protocol (Core §4.22).
2//!
3//! An Intermittently Connected Device sleeps. While it sleeps it has no session, no
4//! subscription that can reach it, and — being asleep — no way to be told any of that. The
5//! Check-In message is how it says "I am awake now" to a client that has been waiting.
6//!
7//! > The goal of the Check-In Protocol is to provide a way for a server to notify a client of
8//! > an event or state outside of a secure session in a private and secure fashion.
9//!
10//! # Why it is encrypted the way it is
11//!
12//! The message is **sessionless**, "since one of the goals of the protocol is to provide a
13//! means to recover a secure session that was lost". So there are no session keys, and the
14//! only shared secret is the key the client handed over when it registered. That leaves one
15//! problem — an AEAD needs a nonce, and there is nowhere to negotiate one — and §4.22.3.1
16//! solves it by deriving the nonce from the key and a counter:
17//!
18//! ```text
19//! nonce      = HMAC-SHA256(key, counter)[0..13]
20//! ciphertext = AES-128-CCM(key, nonce, plaintext = counter ‖ application data)
21//! payload    = nonce ‖ ciphertext ‖ MIC
22//! ```
23//!
24//! The counter appears twice, and that is the point rather than redundancy. It is *outside*
25//! the encryption only as the nonce it generated, and *inside* it as a value the MIC covers.
26//! A client that decrypted successfully and then trusted the plaintext counter without
27//! re-deriving the nonce from it would accept a message whose two copies disagree —
28//! §4.22.4.2 step 4 is that check, and the specification's own Test 6 is a message that
29//! decrypts cleanly and fails it.
30//!
31//! # Who counts
32//!
33//! The server counts up. The client does **not** store the server's counter — it stores the
34//! value the counter had when it registered, plus the largest offset it has seen since
35//! (§4.22.1.2). A counter at or below that offset has been used before, and the message is a
36//! replay.
37//!
38//! That arithmetic is deliberately modular: "The subtraction SHALL be done as unsigned
39//! integers mod 2³². This ensures that even if the subtraction rolls over, it will still
40//! produce the correct offset." A client comparing counters directly instead is one that
41//! stops accepting check-ins the first time the server's counter wraps.
42//!
43//! # Keys wear out
44//!
45//! A key is good for one pass through the counter space, because reusing a counter reuses a
46//! nonce. §4.22.3.4 makes the client responsible for noticing: at an offset of 2³¹ — half way
47//! — [`Registration::needs_key_refresh`] is true and the client must re-register with a new
48//! key before the other half is spent.
49
50use crate::crypto::{
51    AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, SymmetricKey, aead_decrypt_in_place,
52    aead_encrypt_in_place, ct_eq, hmac,
53};
54use crate::error::{Result, bail};
55
56/// How many octets a Check-In message occupies beyond its application data: the plaintext
57/// nonce, the encrypted counter, and the MIC.
58pub const OVERHEAD: usize = AEAD_NONCE_LENGTH_BYTES + 4 + AEAD_MIC_LENGTH_BYTES;
59
60/// The offset at which §4.22.3.4 requires a client to re-register with a fresh key.
61///
62/// Half the counter space. Not a limit that can be run to the end: the key must be replaced
63/// while counter values remain, because the failure at the end is a *reused nonce*, which
64/// costs the confidentiality of both messages that share it.
65pub const KEY_REFRESH_OFFSET: u32 = 1 << 31;
66
67/// Derives the nonce for one Check-In message (§4.22.3.1).
68///
69/// > nonce = Crypto_HMAC(key = key, message = counter)[0..(CRYPTO_AEAD_NONCE_LENGTH_BYTES-1)]
70///
71/// The counter is hashed in its wire form — 4 octets, little-endian — not as an integer, so
72/// there is one answer rather than one per architecture.
73pub fn nonce(key: &SymmetricKey, counter: u32) -> Result<[u8; AEAD_NONCE_LENGTH_BYTES]> {
74    let digest = hmac(key.as_bytes(), &counter.to_le_bytes())?;
75    let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
76    let Some(head) = digest.get(..AEAD_NONCE_LENGTH_BYTES) else {
77        bail!(BufferTooSmall)
78    };
79    out.copy_from_slice(head);
80    Ok(out)
81}
82
83/// Builds one Check-In message (§4.22.4.1).
84///
85/// Writes `nonce ‖ ciphertext ‖ MIC` into `out` and returns its length. `application_data` is
86/// whatever the use case defines; the ICD use case sends none, and "if application data is not
87/// used for a specific use-case, creation of a Check-In message SHALL use a zero-length byte
88/// array".
89///
90/// The specification is emphatic about the failure path: "If the encryption procedure fails to
91/// generate the Check-In message, the server SHALL NOT send the associated Check-In message."
92/// An `Err` here is not a partial result to salvage — `out` holds nothing meaningful.
93pub fn encrypt(
94    key: &SymmetricKey,
95    counter: u32,
96    application_data: &[u8],
97    out: &mut [u8],
98) -> Result<usize> {
99    let nonce = nonce(key, counter)?;
100    let plaintext_len = application_data.len().saturating_add(4);
101    let total = plaintext_len
102        .saturating_add(AEAD_NONCE_LENGTH_BYTES)
103        .saturating_add(AEAD_MIC_LENGTH_BYTES);
104    if out.len() < total {
105        bail!(BufferTooSmall)
106    }
107
108    // The nonce goes out in plaintext, ahead of everything it protects.
109    let Some(head) = out.get_mut(..AEAD_NONCE_LENGTH_BYTES) else {
110        bail!(BufferTooSmall)
111    };
112    head.copy_from_slice(&nonce);
113
114    // "The plaintext SHALL be a concatenation of … the Check-In Counter value used in the
115    // encryption process and the Application Data, if used by the use case."
116    let body_end = AEAD_NONCE_LENGTH_BYTES.saturating_add(plaintext_len);
117    let Some(body) = out.get_mut(AEAD_NONCE_LENGTH_BYTES..body_end) else {
118        bail!(BufferTooSmall)
119    };
120    if body.len() < 4 {
121        bail!(BufferTooSmall)
122    }
123    let (counter_slot, data_slot) = body.split_at_mut(4);
124    counter_slot.copy_from_slice(&counter.to_le_bytes());
125    data_slot.copy_from_slice(application_data);
126
127    // "The additional data field SHALL NOT be used."
128    let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
129    aead_encrypt_in_place(key, &nonce, &[], body, &mut tag)?;
130
131    let Some(tail) = out.get_mut(body_end..total) else {
132        bail!(BufferTooSmall)
133    };
134    tail.copy_from_slice(&tag);
135    Ok(total)
136}
137
138/// What a successfully opened Check-In message carried.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct CheckIn<'a> {
141    /// The counter the server sent, already confirmed to match the nonce.
142    pub counter: u32,
143    /// The application data, empty for the ICD use case.
144    pub application_data: &'a [u8],
145}
146
147/// Opens one Check-In message with a candidate key (§4.22.4.2, steps 1–4).
148///
149/// `buf` is decrypted in place, so the returned application data borrows it. This is the step
150/// that also *identifies the sender*: "If the decryption succeeds, the device associated with
151/// the key is identified as the server checking in", so a client holding several registrations
152/// tries each key until one works. [`IntegrityCheckFailed`](crate::ErrorCode::IntegrityCheckFailed) means "not this key",
153/// not "bad message" — keep going.
154///
155/// Replay is **not** checked here, because this function does not know which registration the
156/// key came from. [`Registration::accept`] is that half.
157pub fn decrypt<'a>(key: &SymmetricKey, buf: &'a mut [u8]) -> Result<CheckIn<'a>> {
158    if buf.len() < OVERHEAD {
159        bail!(BtpMalformed)
160    }
161    let (head, rest) = buf.split_at_mut(AEAD_NONCE_LENGTH_BYTES);
162    let mut received_nonce = [0u8; AEAD_NONCE_LENGTH_BYTES];
163    received_nonce.copy_from_slice(head);
164
165    let body_len = rest.len().saturating_sub(AEAD_MIC_LENGTH_BYTES);
166    let (body, tag_bytes) = rest.split_at_mut(body_len);
167    let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
168    let Some(tag_slice) = tag_bytes.get(..AEAD_MIC_LENGTH_BYTES) else {
169        bail!(BtpMalformed)
170    };
171    tag.copy_from_slice(tag_slice);
172
173    aead_decrypt_in_place(key, &received_nonce, &[], body, &tag)?;
174
175    let (Some(counter_bytes), Some(application_data)) = (body.get(..4), body.get(4..)) else {
176        bail!(BtpMalformed)
177    };
178    let mut counter_le = [0u8; 4];
179    counter_le.copy_from_slice(counter_bytes);
180    let counter = u32::from_le_bytes(counter_le);
181
182    // §4.22.4.2 step 4. The counter is both the nonce's input and part of the MIC'd plaintext,
183    // and a message where the two disagree is one the sender did not construct: the tag proves
184    // only that *this* nonce and *this* plaintext go together, not that the plaintext's own
185    // counter is the one the nonce came from. The specification's Test 6 is exactly that
186    // message, and it decrypts cleanly.
187    let derived = nonce(key, counter)?;
188    if !ct_eq(&derived, &received_nonce) {
189        bail!(IntegrityCheckFailed)
190    }
191
192    Ok(CheckIn {
193        counter,
194        application_data,
195    })
196}
197
198/// One server a client has registered with, and what it remembers about that server's counter
199/// (§4.22.1.2).
200///
201/// Three values, and the reason there are three rather than one is that the client never
202/// learns the server's counter: it learns where the counter *was* when it registered, and
203/// tracks how far past that it has seen.
204#[derive(Debug, Clone)]
205pub struct Registration {
206    key: SymmetricKey,
207    /// "the starting value of Check-In Counter" — what the server reported at registration.
208    start: u32,
209    /// "the last known valid offset from the starting value of the Check-In Counter".
210    offset: u32,
211}
212
213impl Registration {
214    /// Records a registration.
215    #[must_use]
216    pub const fn new(key: SymmetricKey, start_counter: u32) -> Self {
217        Self {
218            key,
219            start: start_counter,
220            offset: 0,
221        }
222    }
223
224    /// The key this registration decrypts with.
225    #[must_use]
226    pub const fn key(&self) -> &SymmetricKey {
227        &self.key
228    }
229
230    /// The counter value the server reported when the client registered.
231    #[must_use]
232    pub const fn start_counter(&self) -> u32 {
233        self.start
234    }
235
236    /// The largest offset past [`Registration::start_counter`] that has been accepted.
237    #[must_use]
238    pub const fn offset(&self) -> u32 {
239        self.offset
240    }
241
242    /// Whether a counter is one this registration has not already seen (§4.22.3.3).
243    ///
244    /// > Subtract the stored starting value of the counter from the value provided in the
245    /// > Check-In message. The subtraction SHALL be done as unsigned integers mod 2³². This
246    /// > ensures that even if the subtraction rolls over, it will still produce the correct
247    /// > offset.
248    ///
249    /// Wrapping is the whole subtlety. A client that compared the two counters as ordinary
250    /// integers would work for months and then, the first time the server's counter passed
251    /// 2³²−1, reject every check-in from a perfectly healthy device — and the device would
252    /// keep sending them.
253    #[must_use]
254    pub const fn is_fresh(&self, counter: u32) -> bool {
255        self.offset < counter.wrapping_sub(self.start)
256    }
257
258    /// Whether §4.22.3.4 requires the client to re-register with a new key.
259    ///
260    /// "When a client receives a Check-In message with a Check-In Counter value indicating
261    /// that 2³¹ counter values have been used, the client SHALL refresh its entry with a new
262    /// key."
263    #[must_use]
264    pub const fn needs_key_refresh(&self) -> bool {
265        self.offset >= KEY_REFRESH_OFFSET
266    }
267
268    /// Opens a Check-In message from this server and records its counter.
269    ///
270    /// The two halves are here rather than in [`decrypt`] because only a registration knows
271    /// what has been seen before. A replayed message decrypts perfectly — the attacker is
272    /// replaying a message the server really sent — so freshness is the only thing that
273    /// separates it from the original.
274    ///
275    /// The offset moves **only on success**, which is what stops a replayed message from
276    /// advancing the window past check-ins that have not arrived yet.
277    pub fn accept<'a>(&mut self, buf: &'a mut [u8]) -> Result<CheckIn<'a>> {
278        let message = decrypt(&self.key, buf)?;
279        if !self.is_fresh(message.counter) {
280            bail!(DuplicateMessage)
281        }
282        self.offset = message.counter.wrapping_sub(self.start);
283        Ok(message)
284    }
285
286    /// Replaces the key and resets the window, as a re-registration does.
287    pub fn refresh(&mut self, key: SymmetricKey, start_counter: u32) {
288        self.key = key;
289        self.start = start_counter;
290        self.offset = 0;
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    /// Parses the specification's `aa:bb:cc` notation, so a vector can be pasted as printed.
299    fn hex(text: &str) -> heapless::Vec<u8, 128> {
300        text.split(':')
301            .filter(|s| !s.is_empty())
302            .map(|byte| u8::from_str_radix(byte.trim(), 16).expect("hex"))
303            .collect()
304    }
305
306    fn key(text: &str) -> SymmetricKey {
307        SymmetricKey::from_slice(&hex(text)).expect("16 octets")
308    }
309
310    /// Appendix F.4, Test 1: no application data.
311    #[test]
312    fn appendix_f4_test_1() {
313        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
314        assert_eq!(
315            nonce(&k, 0x0C).expect("nonce").as_slice(),
316            hex("45:80:d2:c6:f1:31:0d:c4:eb:64:f1:f8:e8").as_slice()
317        );
318
319        let expected = hex(
320            "45:80:d2:c6:f1:31:0d:c4:eb:64:f1:f8:e8:bd:c2:1f:b5:19:5d:74:7d:d2:87:9b:2b:0d:\
321             43:ce:5b:1c:56:50:78",
322        );
323        let mut out = [0u8; 64];
324        let n = encrypt(&k, 0x0C, b"", &mut out).expect("encrypt");
325        assert_eq!(&out[..n], expected.as_slice());
326
327        // The client registered when the counter was 0x0B, so 0x0C is one past it.
328        let mut registration = Registration::new(k, 0x0B);
329        let mut buf = expected.clone();
330        let message = registration.accept(&mut buf).expect("valid");
331        assert_eq!(message.counter, 0x0C);
332        assert!(message.application_data.is_empty());
333        assert_eq!(registration.offset(), 1);
334    }
335
336    /// Appendix F.4, Test 2: four octets of application data, and a gap in the counter.
337    #[test]
338    fn appendix_f4_test_2() {
339        let k = key("18:fd:bc:ea:ef:01:95:5b:0e:c8:75:ed:a3:ae:6e:e8");
340        assert_eq!(
341            nonce(&k, 0x0F).expect("nonce").as_slice(),
342            hex("9b:02:ed:21:ee:0c:7b:49:19:85:50:2e:37").as_slice()
343        );
344
345        let expected = hex(
346            "9b:02:ed:21:ee:0c:7b:49:19:85:50:2e:37:2d:bd:7b:3f:8b:4f:8e:3c:5a:d9:94:19:38:\
347             9f:41:a8:d6:09:93:8c:67:a8:6d:65",
348        );
349        let mut out = [0u8; 64];
350        let n = encrypt(&k, 0x0F, b"This", &mut out).expect("encrypt");
351        assert_eq!(&out[..n], expected.as_slice());
352
353        // Counters 0x0C..0x0F were never seen; skipping them is normal, because a sleeping
354        // device's check-ins are lost routinely.
355        let mut registration = Registration::new(k, 0x0B);
356        let mut buf = expected;
357        let message = registration.accept(&mut buf).expect("valid");
358        assert_eq!(message.counter, 0x0F);
359        assert_eq!(message.application_data, b"This");
360        assert_eq!(registration.offset(), 4);
361    }
362
363    /// Appendix F.4, Test 3: "Invalid Check-In message - Received counter has already been
364    /// used." The counter equals the starting value, so its offset is zero and nothing about
365    /// it is new.
366    #[test]
367    fn appendix_f4_test_3_a_counter_at_the_starting_value_is_a_replay() {
368        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
369        let expected = hex(
370            "aa:84:bc:60:88:6a:63:a8:47:5d:5d:be:b5:6d:63:5f:a9:52:85:ae:33:62:66:13:c7:63:\
371             6c:e3:e3:b2:a8:b1:3a:8c:89:be:f7:68:91:e8:e2:96",
372        );
373        let mut out = [0u8; 64];
374        let n = encrypt(&k, 0x0B, b"This is a", &mut out).expect("encrypt");
375        assert_eq!(&out[..n], expected.as_slice());
376
377        // It decrypts perfectly — that is the point. Only the window rejects it.
378        let mut buf = expected.clone();
379        let opened = decrypt(&k, &mut buf).expect("the cryptography is sound");
380        assert_eq!(opened.counter, 0x0B);
381        assert_eq!(opened.application_data, b"This is a");
382
383        let mut registration = Registration::new(k, 0x0B);
384        let mut buf = expected;
385        assert_eq!(
386            registration
387                .accept(&mut buf)
388                .map(|_| ())
389                .map_err(|e| e.code()),
390            Err(crate::ErrorCode::DuplicateMessage)
391        );
392        assert_eq!(
393            registration.offset(),
394            0,
395            "a replay does not move the window"
396        );
397    }
398
399    /// Appendix F.4, Test 4: the counter is *behind* what the client has already accepted.
400    #[test]
401    fn appendix_f4_test_4_a_counter_behind_the_window_is_a_replay() {
402        let k = key("ca:67:d4:1f:f7:11:29:10:fd:d1:8a:1b:f9:9e:a9:74");
403        let expected = hex(
404            "7a:97:72:24:3c:97:c8:7d:5f:3a:31:c4:e6:db:bc:1a:a5:66:c4:43:c2:05:86:06:6b:42:\
405             7b:fc:aa:ad:78:da:4a:10:5a:13:42:ad:bf:3f:47:98:cd:81:b9:ef:97:bb:b7",
406        );
407        let mut out = [0u8; 80];
408        let n = encrypt(&k, 0x0B, b"This is a longer", &mut out).expect("encrypt");
409        assert_eq!(&out[..n], expected.as_slice());
410
411        // The vector prints "Client counter: 0f" for this test, and the number is the *last
412        // accepted* counter rather than the registration start — §4.22.1.2 stores the start
413        // and an offset, and here they are 0x0B and 4. Reading it as a start with a zero
414        // offset gives the opposite answer, because 0x0B − 0x0F mod 2³² is 0xFFFF_FFFC and
415        // that is "almost a whole cycle ahead" rather than "four behind".
416        let mut registration = Registration::new(k.clone(), 0x0B);
417        let mut ahead = [0u8; 80];
418        let n = encrypt(&k, 0x0F, b"", &mut ahead).expect("encrypt");
419        registration
420            .accept(&mut ahead[..n])
421            .expect("0x0F arrives first");
422        assert_eq!(registration.offset(), 4);
423
424        let mut buf = expected;
425        assert_eq!(
426            registration
427                .accept(&mut buf)
428                .map(|_| ())
429                .map_err(|e| e.code()),
430            Err(crate::ErrorCode::DuplicateMessage),
431            "§4.22.3.3 rejects it because the window has already passed it"
432        );
433        assert_eq!(registration.offset(), 4, "and the window did not move");
434    }
435
436    #[test]
437    fn a_counter_far_ahead_is_accepted_and_demands_a_new_key() {
438        // The counterpart to Test 4, and the reason that test has to be read carefully. A
439        // counter 0xFFFF_FFFC past the *start* is arithmetically fresh — §4.22.3.3's three
440        // steps say so, and the CHIP reference implementation agrees — so it is accepted. What
441        // makes it harmless is §4.22.3.4: an offset that large means more than 2³¹ counter
442        // values have gone, and the key must be replaced before the nonces repeat.
443        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
444        let mut registration = Registration::new(k.clone(), 0x0F);
445        let mut out = [0u8; 64];
446        let n = encrypt(&k, 0x0B, b"", &mut out).expect("encrypt");
447        registration
448            .accept(&mut out[..n])
449            .expect("arithmetically fresh");
450        assert_eq!(registration.offset(), 0xFFFF_FFFC);
451        assert!(registration.needs_key_refresh());
452    }
453
454    /// Appendix F.4, Test 5: "Failed to decrypt Check-In message."
455    #[test]
456    fn appendix_f4_test_5_a_tampered_message_does_not_decrypt() {
457        let k = key("ca:67:d4:1f:f7:11:29:10:fd:d1:8a:1b:f9:9e:a9:74");
458        let mut buf = hex(
459            "f9:34:67:6e:a6:e0:70:7b:7a:d7:81:4f:f8:2e:5b:18:d1:9a:23:b2:e4:fa:df:82:92:53:\
460             51:7f:f3:c9:1d:8d:47:84:31:5a:1e:32:08:b8:ec:f6:11:8b:02:1a:5a:4c:d4:e9:d4:13:\
461             8d:ff:29:71",
462        );
463        assert_eq!(
464            decrypt(&k, &mut buf).map(|_| ()).map_err(|e| e.code()),
465            Err(crate::ErrorCode::IntegrityCheckFailed)
466        );
467    }
468
469    /// Appendix F.4, Test 6: "Invalid Check-In message - Nonce and received counter do not
470    /// match."
471    ///
472    /// This is the vector that justifies §4.22.4.2's step 4 existing at all. The message
473    /// decrypts cleanly and its MIC verifies — the tag proves this nonce and this plaintext go
474    /// together, and they do. What it does not prove is that the plaintext's own counter is
475    /// the one the nonce was derived from, and here it is not.
476    #[test]
477    fn appendix_f4_test_6_a_nonce_that_does_not_match_its_counter_is_refused() {
478        let k = key("ca:67:d4:1f:f7:11:29:10:fd:d1:8a:1b:f9:9e:a9:74");
479        let mut buf = hex(
480            "06:34:67:6e:a6:e0:70:7b:7a:d7:81:4f:f8:29:5b:18:d1:9a:23:b2:e4:fa:df:82:92:53:\
481             51:7f:f3:c9:1d:8d:47:84:2e:41:02:3c:03:ad:66:ac:4d:ca:72:47:e0:e4:c6:6b:d9:d3:\
482             99:13:e2:3d:82:32:b9:61:fa:92:26",
483        );
484        assert_eq!(
485            decrypt(&k, &mut buf).map(|_| ()).map_err(|e| e.code()),
486            Err(crate::ErrorCode::IntegrityCheckFailed),
487            "the AEAD succeeded; the nonce check is what refused it"
488        );
489    }
490
491    #[test]
492    fn the_window_survives_the_counter_wrapping() {
493        // "The subtraction SHALL be done as unsigned integers mod 2³². This ensures that even
494        // if the subtraction rolls over, it will still produce the correct offset." A client
495        // comparing counters directly works for months and then rejects every check-in from a
496        // healthy device the first time the server passes 2³² − 1.
497        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
498        let start = u32::MAX.saturating_sub(2);
499        let mut registration = Registration::new(k.clone(), start);
500
501        let mut out = [0u8; 64];
502        for counter in [u32::MAX - 1, u32::MAX, 0, 1, 2] {
503            let n = encrypt(&k, counter, b"", &mut out).expect("encrypt");
504            let mut buf = out;
505            let message = registration
506                .accept(&mut buf[..n])
507                .expect("a wrapped counter is still moving forwards");
508            assert_eq!(message.counter, counter);
509        }
510        assert_eq!(registration.offset(), 5);
511
512        // And the one before the wrap is still a replay afterwards.
513        let n = encrypt(&k, u32::MAX, b"", &mut out).expect("encrypt");
514        let mut buf = out;
515        assert_eq!(
516            registration
517                .accept(&mut buf[..n])
518                .map(|_| ())
519                .map_err(|e| e.code()),
520            Err(crate::ErrorCode::DuplicateMessage)
521        );
522    }
523
524    #[test]
525    fn a_key_must_be_refreshed_at_half_the_counter_space() {
526        // §4.22.3.4: the key has to go *before* the counters run out, because what waits at
527        // the end is a reused nonce — and that costs the confidentiality of both messages that
528        // share it, not merely the freshness of one.
529        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
530        let mut registration = Registration::new(k.clone(), 0);
531        assert!(!registration.needs_key_refresh());
532
533        let mut out = [0u8; 64];
534        let n = encrypt(&k, KEY_REFRESH_OFFSET, b"", &mut out).expect("encrypt");
535        let mut buf = out;
536        registration.accept(&mut buf[..n]).expect("still valid");
537        assert!(
538            registration.needs_key_refresh(),
539            "2³¹ counter values have been used"
540        );
541
542        // Re-registering resets the window.
543        let fresh = key("18:fd:bc:ea:ef:01:95:5b:0e:c8:75:ed:a3:ae:6e:e8");
544        registration.refresh(fresh, 7);
545        assert!(!registration.needs_key_refresh());
546        assert_eq!(registration.offset(), 0);
547        assert_eq!(registration.start_counter(), 7);
548    }
549
550    #[test]
551    fn a_client_identifies_the_server_by_which_key_opens_the_message() {
552        // §4.22.4.2 step 2: "When a client has multiple associated servers, the client iterates
553        // through this process for the keys associated to each potential server until the keys
554        // associated to all possible servers fail or a successful key is found." There is no
555        // sender field in the message — the key that works *is* the identification.
556        let a = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
557        let b = key("18:fd:bc:ea:ef:01:95:5b:0e:c8:75:ed:a3:ae:6e:e8");
558        let mut out = [0u8; 64];
559        let n = encrypt(&b, 3, b"", &mut out).expect("encrypt");
560
561        let mut buf = out;
562        assert_eq!(
563            decrypt(&a, &mut buf[..n]).map(|_| ()).map_err(|e| e.code()),
564            Err(crate::ErrorCode::IntegrityCheckFailed),
565            "the wrong key is a failure to try the next one with, not a bad message"
566        );
567        let mut buf = out;
568        assert_eq!(decrypt(&b, &mut buf[..n]).expect("right key").counter, 3);
569    }
570
571    #[test]
572    fn a_message_shorter_than_its_own_overhead_is_refused() {
573        // It arrives from an unauthenticated sender on a sleeping device, so the length check
574        // comes before anything else touches it.
575        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
576        for len in 0..OVERHEAD {
577            let mut buf = [0u8; OVERHEAD];
578            assert!(decrypt(&k, &mut buf[..len]).is_err(), "length {len}");
579        }
580    }
581
582    #[test]
583    fn a_buffer_too_small_for_the_message_is_refused_rather_than_truncated() {
584        let k = key("d9:0e:13:18:0d:00:ba:ad:d2:0c:f5:ed:49:13:d3:ff");
585        let mut out = [0u8; OVERHEAD];
586        encrypt(&k, 1, b"", &mut out).expect("exactly enough for no application data");
587        assert_eq!(
588            encrypt(&k, 1, b"x", &mut out).map_err(|e| e.code()),
589            Err(crate::ErrorCode::BufferTooSmall)
590        );
591    }
592}