Skip to main content

ntpsec_rs_core/
nts.rs

1// ──── nts.rs ────────────────────────────────────────────────────────────────
2// Forensic reconstruction of ntpd/nts.c, include/nts.h (8K), include/nts2.h
3//
4// Network Time Security (NTS) core implementation.  NTS (RFC 8915) provides
5// cryptographic authentication for NTPv4 using TLS-encrypted key
6// establishment and AEAD-protected extension fields.
7//
8// ## NTS Architecture
9//
10// NTS has two phases:
11//
12//   1. **NTS-KE** (Key Establishment): A TLS handshake on port 4460 between
13//      client and server that negotiates algorithms and exchanges NTS cookies.
14//      Implemented in nts_client.rs / nts_server.rs.
15//
16//   2. **NTP Extension Fields**: AEAD-protected extension fields added to
17//      normal NTP packets.  The cookie encodes the server's state (keys,
18//      algorithm, etc.) encrypted with AES-SIV-CMAC-256.  Implemented in
19//      nts_cookie.rs / nts_extens.rs.
20//
21// This module provides the shared NTS state structures, protocol constants,
22// and unique identifier key management.
23//
24// ## Oracle
25//   - ntpsec ntpd/nts.c (14K)
26//   - ntpsec include/nts.h
27//   - ntpsec include/nts2.h
28//   - RFC 8915 — Network Time Security for NTP
29//   - RFC 5297 — Synthetic Initialization Vector (SIV) Authenticated Encryption
30//
31// ## Court
32//   - docs/courts/nts.md
33// =============================================================================
34
35/// NTS-KE default port (RFC 8915 §4).
36pub const NTS_KE_PORT: u16 = 4460;
37
38/// NTS protocol version.
39pub const NTS_VERSION: u8 = 1;
40
41/// Maximum number of cookies per NTS-KE response (ntpsec default).
42pub const NTS_MAX_COOKIES: usize = 8;
43
44/// Maximum cookie size in bytes.
45pub const NTS_MAX_COOKIE_SIZE: usize = 256;
46
47/// AEAD algorithm IDs used in NTS (RFC 8915 §4.1.3).
48pub mod aead_algorithms {
49    /// AEAD_AES_SIV_CMAC_256 (REQUIRED by RFC 8915).
50    pub const AEAD_AES_SIV_CMAC_256: u16 = 15;
51    /// AEAD_AES_SIV_CMAC_512.
52    pub const AEAD_AES_SIV_CMAC_512: u16 = 16;
53    /// AEAD_AES_GCM_128.
54    pub const AEAD_AES_GCM_128: u16 = 18;
55
56    /// Old alias kept for compatibility.
57    pub const AES_SIV_CMAC_256: u16 = AEAD_AES_SIV_CMAC_256;
58    /// Old alias kept for compatibility.
59    pub const AES_128_GCM: u16 = 2;
60    /// Old alias kept for compatibility.
61    pub const AES_256_GCM: u16 = 3;
62
63    /// All supported AEAD algorithms.
64    pub const SUPPORTED: &[u16] = &[AEAD_AES_SIV_CMAC_256];
65}
66
67/// Strongly-typed AEAD algorithm identifiers (RFC 8915 §4.1.3).
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum AeadAlgorithm {
70    AeadAesSivCmac256 = 15, // 32-byte key
71    AeadAesSivCmac512 = 16, // 64-byte key
72    AeadAesGcm128 = 18,     // 16-byte key
73}
74
75impl AeadAlgorithm {
76    /// Return the key length in bytes required by this AEAD algorithm (RFC 8915 §4.1.3).
77    pub fn key_length(&self) -> usize {
78        match self {
79            AeadAlgorithm::AeadAesSivCmac256 => 32,
80            AeadAlgorithm::AeadAesSivCmac512 => 64,
81            AeadAlgorithm::AeadAesGcm128 => 16,
82        }
83    }
84
85    /// Convert from the u16 wire-encoding used in NTS-KE records (RFC 8915 §4.1.3).
86    pub fn from_u16(v: u16) -> Option<Self> {
87        match v {
88            15 => Some(AeadAlgorithm::AeadAesSivCmac256),
89            16 => Some(AeadAlgorithm::AeadAesSivCmac512),
90            18 => Some(AeadAlgorithm::AeadAesGcm128),
91            _ => None,
92        }
93    }
94
95    /// Convert to the u16 wire-encoding used in NTS-KE records.
96    pub fn to_u16(self) -> u16 {
97        self as u16
98    }
99}
100
101/// NTS-KE session state.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum NtsKeState {
104    Idle,
105    Connecting,
106    Negotiating,
107    Established,
108    Error(String),
109}
110
111impl NtsKeState {
112    pub fn is_terminal(&self) -> bool {
113        matches!(self, NtsKeState::Established | NtsKeState::Error(_))
114    }
115
116    pub fn is_established(&self) -> bool {
117        matches!(self, NtsKeState::Established)
118    }
119
120    pub fn error_message(&self) -> Option<&str> {
121        match self {
122            NtsKeState::Error(msg) => Some(msg.as_str()),
123            _ => None,
124        }
125    }
126}
127
128/// NTS-KE negotiated parameters.
129#[derive(Debug, Clone)]
130pub struct NtsKeNegotiation {
131    pub aead_algorithm: AeadAlgorithm,
132    pub cookies: Vec<Vec<u8>>,          // raw cookie bodies
133    pub c2s_key: [u8; 32],              // client-to-server key (derived via TLS exporter)
134    pub s2c_key: [u8; 32],              // server-to-client key (derived via TLS exporter)
135    pub server_offer: Vec<NtsKeRecord>, // additional server offers
136}
137
138impl NtsKeNegotiation {
139    pub fn new(aead_algorithm: AeadAlgorithm, cookies: Vec<Vec<u8>>) -> Self {
140        Self {
141            aead_algorithm,
142            cookies,
143            c2s_key: [0u8; 32],
144            s2c_key: [0u8; 32],
145            server_offer: Vec::new(),
146        }
147    }
148
149    pub fn cookie_count(&self) -> usize {
150        self.cookies.len()
151    }
152
153    pub fn take_cookie(&mut self) -> Option<Vec<u8>> {
154        if self.cookies.is_empty() {
155            None
156        } else {
157            Some(self.cookies.remove(0))
158        }
159    }
160}
161
162// ──── NTS-KE Record Protocol ────────────────────────────────────────────
163//
164// RFC 8915 §4.1 defines the NTS-KE record wire format:
165//
166//   0                   1                   2                   3
167//   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
168//  ┌─────────────────────────────────────────────────────────────────┐
169//  │         Record Type (16)       │         Body Length (16)       │
170//  ├─────────────────────────────────────────────────────────────────┤
171//  │                          Body (variable)                        │
172//  └─────────────────────────────────────────────────────────────────┘
173//
174// Record types are defined in the `nts_record` module above.
175
176/// NTS-KE message record.
177#[derive(Debug, Clone)]
178pub struct NtsKeRecord {
179    pub record_type: u16,
180    pub body: Vec<u8>,
181}
182
183impl NtsKeRecord {
184    pub fn new(record_type: u16, body: Vec<u8>) -> Self {
185        Self { record_type, body }
186    }
187
188    /// Create a new NTS-KE record with the critical bit set (RFC 8915 §4.1.1).
189    /// When the critical bit is set, the receiver MUST understand this record
190    /// type or abort the handshake.
191    pub fn new_critical(record_type: u16, body: Vec<u8>) -> Self {
192        Self {
193            record_type: record_type | NTS_KE_RECORD_CRITICAL_BIT,
194            body,
195        }
196    }
197
198    /// Encode to wire format (4-byte header + body).
199    pub fn encode(&self) -> Vec<u8> {
200        let mut buf = Vec::with_capacity(4 + self.body.len());
201        buf.extend_from_slice(&self.record_type.to_be_bytes());
202        buf.extend_from_slice(&(self.body.len() as u16).to_be_bytes());
203        buf.extend_from_slice(&self.body);
204        buf
205    }
206
207    /// Decode from wire format.
208    /// Returns `(record, remaining_bytes)` on success.
209    pub fn decode(data: &[u8]) -> Option<(Self, &[u8])> {
210        if data.len() < 4 {
211            return None;
212        }
213        let record_type = u16::from_be_bytes([data[0], data[1]]);
214        let length = u16::from_be_bytes([data[2], data[3]]) as usize;
215        if data.len() < 4 + length {
216            return None;
217        }
218        let body = data[4..4 + length].to_vec();
219        let remaining = &data[4 + length..];
220        Some((Self { record_type, body }, remaining))
221    }
222
223    /// Decode a sequence of records from a byte buffer.
224    ///
225    /// Parses ALL decodable records without stopping at EOM.
226    /// Returns the records and any trailing undecodable bytes.
227    /// The critical bit (0x8000) is masked out for record type
228    /// identification but PRESERVED in the returned record so that
229    /// callers can validate critical vs. non-critical records.
230    pub fn decode_all(data: &[u8]) -> (Vec<Self>, &[u8]) {
231        let mut records = Vec::new();
232        let mut remain = data;
233        loop {
234            if remain.is_empty() {
235                break;
236            }
237            match Self::decode(remain) {
238                Some((rec, rest)) => {
239                    remain = rest;
240                    records.push(rec);
241                }
242                None => break,
243            }
244        }
245        (records, remain)
246    }
247}
248
249/// NTS-KE client — manages the NTS-KE state machine and record exchange.
250///
251/// In a deployed system this struct would drive the actual TLS connection
252/// to the NTS-KE server.  The handshake() method here demonstrates the
253/// protocol flow by constructing the negotiation request, processing the
254/// server's response, and extracting cookies and negotiated algorithms.
255///
256/// The actual TLS transport layer lives in nts_client.rs; this struct
257/// provides the protocol-aware framing layer.
258pub struct NtsKeProtocolClient {
259    state: NtsKeState,
260    host: String,
261    port: u16,
262    cookies: Vec<Vec<u8>>,
263    aead: Option<AeadAlgorithm>,
264}
265
266impl NtsKeProtocolClient {
267    pub fn new(host: &str, port: u16) -> Self {
268        Self {
269            state: NtsKeState::Idle,
270            host: host.to_string(),
271            port,
272            cookies: Vec::new(),
273            aead: None,
274        }
275    }
276
277    /// Perform the NTS-KE handshake.
278    ///
279    /// The full handshake (RFC 8915 §4) proceeds as follows:
280    ///
281    ///   1. Open a TLS connection to the NTS-KE server on the configured
282    ///      host:port (typically port 4460).
283    ///   2. Send a Negotiation Request record listing the client's supported
284    ///      AEAD algorithms.
285    ///   3. Optionally send NTPv4 Server Negotiation and/or NTPv4 Port
286    ///      Negotiation records.
287    ///   4. Send an End-of-Message record.
288    ///   5. Read and process the server's response records:
289    ///        - AEAD Algorithm Offer: the server's chosen algorithm.
290    ///        - NTS Cookie: one or more encrypted cookies.
291    ///        - NTPv4 Server Negotiation / Port Negotiation: server's
292    ///          NTP endpoint information.
293    ///        - End-of-Message: signals the end of the response.
294    ///   6. Close the TLS session.
295    ///
296    /// This implementation performs the protocol framing (record construction
297    /// and parsing) but requires the TLS transport to be wired in from the
298    /// nts_client module.  For the oracle-free / offline development path,
299    /// the method returns an error indicating that TLS is not yet connected.
300    pub fn handshake(&mut self) -> Result<NtsKeNegotiation, String> {
301        self.state = NtsKeState::Connecting;
302
303        // ── Build the negotiation request ──────────────────────────────
304        let mut request_records: Vec<NtsKeRecord> = Vec::new();
305
306        // Mandatory: Next Protocol Negotiation selecting NTPv4 (protocol ID 0).
307        // Body is a 16-bit protocol ID in network byte order. Critical bit MUST be set.
308        let next_proto_body = 0u16.to_be_bytes().to_vec();
309        request_records.push(NtsKeRecord::new_critical(
310            NTS_KE_RECORD_NEXT_PROTOCOL,
311            next_proto_body,
312        ));
313
314        // Advertise AES-SIV-CMAC-256 as the preferred AEAD algorithm.
315        let aead_body = AeadAlgorithm::AeadAesSivCmac256
316            .to_u16()
317            .to_be_bytes()
318            .to_vec();
319        request_records.push(NtsKeRecord::new_critical(
320            NTS_KE_RECORD_AEAD_ALGORITHM,
321            aead_body,
322        ));
323
324        // End-of-message: critical bit MUST be set (RFC 8915 §4.1.8).
325        request_records.push(NtsKeRecord::new_critical(
326            NTS_KE_RECORD_END_OF_MESSAGE,
327            vec![],
328        ));
329
330        // ── Serialize the request ──────────────────────────────────────
331        let _request_wire: Vec<u8> = request_records.iter().flat_map(|r| r.encode()).collect();
332
333        // ── TLS transport stub ─────────────────────────────────────────
334        // The actual TLS send/recv would happen here, driven by the
335        // nts_client module.  Since that module is a stub during the
336        // oracle-free development path, we record that we *would* send
337        // `request_wire` and then receive a response.
338        //
339        // When TLS is wired, replace this entire block with:
340        //
341        //   let tls = NtsTlsTransport::connect(&self.host, self.port)?;
342        //   tls.send_all(&request_wire).map_err(|e| ...)?;
343        //   let response_wire = tls.receive_all().map_err(|e| ...)?;
344        //
345        // For offline testing, return a clear error so callers know the
346        // transport layer is not yet available.
347
348        self.state = NtsKeState::Negotiating;
349
350        // Stub: handshake not yet wired through TLS transport.
351        self.state =
352            NtsKeState::Error("NTS-KE TLS transport not wired: nts_client is a stub".to_string());
353        Err("NTS-KE handshake requires TLS transport (nts_client not yet implemented)".to_string())
354    }
355
356    /// Start a handshake with pre-built wire-format request data.
357    ///
358    /// Used for testing / offline development paths where the caller
359    /// supplies both request and response bytes directly.
360    ///
361    /// When `cookie_cipher` is provided, the cookies in the server response
362    /// are decrypted to extract the real C2S and S2C keys (matching what
363    /// the full TLS path would derive via exporter). Without a cookie cipher,
364    /// the offline path returns zeroed keys — these MUST NOT be used for
365    /// actual encryption; the offline path is record-validation-only.
366    pub fn handshake_with_data(
367        &mut self,
368        request: &[u8],
369        response: &[u8],
370        cookie_cipher: Option<&crate::nts_cookie::CookieCipher>,
371    ) -> Result<NtsKeNegotiation, String> {
372        self.state = NtsKeState::Connecting;
373
374        // Verify the request encodes (round-trip check for tests).
375        let (req_records, _) = NtsKeRecord::decode_all(request);
376        if req_records.is_empty() {
377            self.state = NtsKeState::Error("empty request".to_string());
378            return Err("empty NTS-KE request".to_string());
379        }
380
381        self.state = NtsKeState::Negotiating;
382
383        // Parse the server's response records (decode_all parses the full buffer).
384        let (resp_records, trailing) = NtsKeRecord::decode_all(response);
385
386        // No trailing data allowed after EOM (RFC 8915 §4.1.8).
387        if !trailing.is_empty() {
388            self.state = NtsKeState::Error(format!(
389                "trailing data after NTS-KE records: {} bytes",
390                trailing.len()
391            ));
392            return Err(format!(
393                "trailing data after last NTS-KE record ({} bytes)",
394                trailing.len()
395            ));
396        }
397
398        let mut aead_algorithm: Option<AeadAlgorithm> = None;
399        let mut aead_count: usize = 0;
400        let mut cookies: Vec<Vec<u8>> = Vec::new();
401        let mut server_offer: Vec<NtsKeRecord> = Vec::new();
402        let mut next_proto_count: usize = 0;
403        let mut selected_ntpv4 = false;
404        let mut has_eom = false;
405        let mut eom_position = usize::MAX;
406
407        for (pos, rec) in resp_records.iter().enumerate() {
408            // Check for Error or Warning records (RFC 8915 §4.1.5, §4.1.6).
409            if rec.record_type & !NTS_KE_RECORD_CRITICAL_BIT == NTS_KE_RECORD_ERROR {
410                let msg = String::from_utf8_lossy(&rec.body);
411                self.state = NtsKeState::Error(format!("server error: {}", msg));
412                return Err(format!("NTS-KE server returned Error: {}", msg));
413            }
414
415            if rec.record_type & !NTS_KE_RECORD_CRITICAL_BIT == NTS_KE_RECORD_WARNING {
416                // RFC 8915 §4.1.6: Warning records are informational; log and continue
417                continue;
418            }
419
420            // Reject unknown critical records (RFC 8915 §4.1.1).
421            if rec.record_type & NTS_KE_RECORD_CRITICAL_BIT != 0 {
422                let raw_type = rec.record_type & !NTS_KE_RECORD_CRITICAL_BIT;
423                match raw_type {
424                    t if t == NTS_KE_RECORD_AEAD_ALGORITHM => {}
425                    t if t == NTS_KE_RECORD_NEW_COOKIE => {}
426                    t if t == NTS_KE_RECORD_NEXT_PROTOCOL => {}
427                    t if t == NTS_KE_RECORD_END_OF_MESSAGE => {}
428                    _ => {
429                        self.state =
430                            NtsKeState::Error(format!("unsupported critical record: {}", raw_type));
431                        return Err(format!(
432                            "unsupported critical NTS-KE record type: {}",
433                            raw_type
434                        ));
435                    }
436                }
437            }
438
439            let raw_type = rec.record_type & !NTS_KE_RECORD_CRITICAL_BIT;
440            match raw_type {
441                t if t == NTS_KE_RECORD_NEXT_PROTOCOL => {
442                    next_proto_count += 1;
443                    if rec.record_type & NTS_KE_RECORD_CRITICAL_BIT == 0 {
444                        self.state =
445                            NtsKeState::Error("Next Protocol missing critical bit".to_string());
446                        return Err("Next Protocol record missing critical bit".to_string());
447                    }
448                    if next_proto_count > 1 {
449                        self.state = NtsKeState::Error("duplicate Next Protocol".to_string());
450                        return Err("duplicate Next Protocol record".to_string());
451                    }
452                    if rec.body.len() < 2 || rec.body.len() % 2 != 0 {
453                        self.state = NtsKeState::Error(format!(
454                            "Next Protocol invalid body length: {}",
455                            rec.body.len()
456                        ));
457                        return Err(format!(
458                            "Next Protocol has invalid body length: {} bytes",
459                            rec.body.len()
460                        ));
461                    }
462                    for chunk in rec.body.chunks_exact(2) {
463                        let protocol = u16::from_be_bytes([chunk[0], chunk[1]]);
464                        if protocol == 0 {
465                            selected_ntpv4 = true;
466                        }
467                    }
468                }
469                t if t == NTS_KE_RECORD_AEAD_ALGORITHM => {
470                    aead_count += 1;
471                    if aead_count > 1 {
472                        self.state = NtsKeState::Error("duplicate AEAD".to_string());
473                        return Err("duplicate AEAD Algorithm record".to_string());
474                    }
475                    if rec.body.len() != 2 {
476                        self.state =
477                            NtsKeState::Error(format!("AEAD body len {} != 2", rec.body.len()));
478                        return Err(format!(
479                            "AEAD Algorithm body must be exactly 2 bytes, got {}",
480                            rec.body.len()
481                        ));
482                    }
483                    let alg_id = u16::from_be_bytes([rec.body[0], rec.body[1]]);
484                    if alg_id != 15 {
485                        self.state =
486                            NtsKeState::Error(format!("server AEAD {} not offered", alg_id));
487                        return Err(format!(
488                            "server selected AEAD algorithm {}; client offered only 15",
489                            alg_id
490                        ));
491                    }
492                    aead_algorithm = AeadAlgorithm::from_u16(alg_id);
493                }
494                t if t == NTS_KE_RECORD_NEW_COOKIE => {
495                    cookies.push(rec.body.clone());
496                }
497                t if t == NTS_KE_RECORD_END_OF_MESSAGE => {
498                    if has_eom {
499                        self.state = NtsKeState::Error("duplicate EOM".to_string());
500                        return Err("duplicate End of Message record".to_string());
501                    }
502                    if rec.record_type & NTS_KE_RECORD_CRITICAL_BIT == 0 {
503                        self.state = NtsKeState::Error("EOM missing critical bit".to_string());
504                        return Err("End of Message record missing critical bit".to_string());
505                    }
506                    if !rec.body.is_empty() {
507                        self.state = NtsKeState::Error(format!(
508                            "EOM non-empty body: {} bytes",
509                            rec.body.len()
510                        ));
511                        return Err(format!(
512                            "End of Message record has non-empty body ({} bytes)",
513                            rec.body.len()
514                        ));
515                    }
516                    has_eom = true;
517                    eom_position = pos;
518                }
519                _ => {
520                    server_offer.push(rec.clone());
521                }
522            }
523        }
524
525        if has_eom && eom_position != resp_records.len() - 1 {
526            self.state = NtsKeState::Error("EOM not final record".to_string());
527            return Err("EOM record is not the final record".to_string());
528        }
529
530        if next_proto_count == 0 {
531            self.state = NtsKeState::Error("missing Next Protocol".to_string());
532            return Err("server did not include mandatory Next Protocol Negotiation".to_string());
533        }
534        if !selected_ntpv4 {
535            self.state = NtsKeState::Error("NTPv4 not selected".to_string());
536            return Err("server did not select NTPv4 protocol".to_string());
537        }
538        if !has_eom {
539            self.state = NtsKeState::Error("missing EOM".to_string());
540            return Err("server response missing End of Message record".to_string());
541        }
542
543        let aead = aead_algorithm.ok_or_else(|| {
544            self.state = NtsKeState::Error("no AEAD algorithm negotiated".to_string());
545            "no AEAD algorithm negotiated".to_string()
546        })?;
547
548        if cookies.is_empty() {
549            self.state = NtsKeState::Error("no cookies received".to_string());
550            return Err("no cookies received from NTS-KE server".to_string());
551        }
552
553        // ── Derive C2S and S2C keys from cookies ──────────────────
554        // In the offline path there is no TLS session, so we cannot
555        // use the TLS exporter. Instead, decrypt the first cookie using
556        // the provided CookieCipher to extract the embedded keys.
557        let (c2s_key, s2c_key) = match cookie_cipher {
558            Some(cipher) => {
559                // Decrypt the first cookie to get the embedded keys
560                let plaintext = cipher.decrypt(&cookies[0]).map_err(|e| {
561                    format!("failed to decrypt cookie during handshake_with_data: {e}")
562                })?;
563                // Cookie plaintext format: aead_alg(2) || c2s_key(32) || s2c_key(32)
564                if plaintext.len() < 66 {
565                    self.state = NtsKeState::Error("decrypted cookie too short".to_string());
566                    return Err(format!(
567                        "decrypted cookie plaintext too short: {} bytes",
568                        plaintext.len()
569                    ));
570                }
571                let mut c2s = [0u8; 32];
572                let mut s2c = [0u8; 32];
573                c2s.copy_from_slice(&plaintext[2..34]);
574                s2c.copy_from_slice(&plaintext[34..66]);
575                (c2s, s2c)
576            }
577            None => {
578                // OFFLINE/TEST-ONLY PATH: Without a CookieCipher we return
579                // zeroed keys. These MUST NOT be used for actual encryption —
580                // this path is record-validation-only. The real TLS path in
581                // NtsKeClient::handshake() derives keys from the TLS exporter.
582                ([0u8; 32], [0u8; 32])
583            }
584        };
585
586        self.aead = Some(aead);
587        self.cookies = cookies.clone();
588        self.state = NtsKeState::Established;
589
590        Ok(NtsKeNegotiation {
591            aead_algorithm: aead,
592            cookies,
593            c2s_key,
594            s2c_key,
595            server_offer,
596        })
597    }
598
599    pub fn state(&self) -> &NtsKeState {
600        &self.state
601    }
602
603    pub fn cookies(&self) -> &[Vec<u8>] {
604        &self.cookies
605    }
606
607    pub fn host(&self) -> &str {
608        &self.host
609    }
610
611    pub fn port(&self) -> u16 {
612        self.port
613    }
614
615    pub fn aead(&self) -> Option<AeadAlgorithm> {
616        self.aead
617    }
618
619    /// Reset the client to `Idle` state, keeping host/port configuration.
620    pub fn reset(&mut self) {
621        self.state = NtsKeState::Idle;
622        self.cookies.clear();
623        self.aead = None;
624    }
625}
626
627/// NTS warning/error codes (RFC 8915 §4.1.4).
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629pub enum NtsErrorCode {
630    /// No error
631    None = 0,
632    /// Internal error
633    Internal = 1,
634    /// Unknown record type
635    UnknownRecord = 2,
636    /// Bad request
637    BadRequest = 3,
638    /// Authentication failure
639    AuthFailure = 4,
640    /// No such algorithm
641    UnknownAlgorithm = 5,
642    /// Cookie too large
643    CookieTooLarge = 6,
644}
645
646impl NtsErrorCode {
647    pub fn from_u16(v: u16) -> Self {
648        match v {
649            0 => NtsErrorCode::None,
650            1 => NtsErrorCode::Internal,
651            2 => NtsErrorCode::UnknownRecord,
652            3 => NtsErrorCode::BadRequest,
653            4 => NtsErrorCode::AuthFailure,
654            5 => NtsErrorCode::UnknownAlgorithm,
655            6 => NtsErrorCode::CookieTooLarge,
656            _ => NtsErrorCode::Internal,
657        }
658    }
659
660    pub fn to_u16(self) -> u16 {
661        self as u16
662    }
663}
664
665/// NTS unique identifier key (UIK) — used to derive cookie encryption keys.
666#[derive(Debug, Clone)]
667pub struct NtsUniqueKey {
668    /// The raw key material (64 bytes for AES-SIV-CMAC-256).
669    pub key_data: [u8; 64],
670    /// The UIK identifier (opaque, used in references).
671    pub id: Vec<u8>,
672}
673
674impl Default for NtsUniqueKey {
675    fn default() -> Self {
676        Self {
677            key_data: [0u8; 64],
678            id: Vec::new(),
679        }
680    }
681}
682
683impl NtsUniqueKey {
684    pub fn new(key_data: [u8; 64], id: Vec<u8>) -> Self {
685        Self { key_data, id }
686    }
687
688    /// Generate a random NTS unique key.
689    pub fn generate() -> Self {
690        let mut key = [0u8; 64];
691        let mut id = vec![0u8; 8];
692        getrandom::getrandom(&mut key).expect("RNG failure for NTS unique key");
693        getrandom::getrandom(&mut id).expect("RNG failure for NTS unique key ID");
694        Self { key_data: key, id }
695    }
696
697    /// Get the key as a reference.
698    pub fn as_bytes(&self) -> &[u8] {
699        &self.key_data
700    }
701
702    /// Get the key identifier as a string.
703    pub fn id_str(&self) -> String {
704        String::from_utf8_lossy(&self.id).to_string()
705    }
706}
707
708/// NTS failure reason — distinguishes failure modes for diagnostics (Gate 8.3).
709#[derive(Debug, Clone, PartialEq, Eq)]
710pub enum NtsFailureReason {
711    /// No failure; NTS is operational.
712    None,
713    /// TLS connection failed (TCP/TLS handshake).
714    TlsConnectionFailure,
715    /// Certificate validation failed (chain, expiry, hostname mismatch).
716    CertificateFailure,
717    /// ALPN negotiation failed — server did not negotiate ntske/1.
718    AlpnFailure,
719    /// Cookie exchange failed (zero cookies, invalid cookie format).
720    CookieFailure,
721    /// AEAD algorithm negotiation failure (unsupported or mismatched).
722    AeadFailure,
723    /// Packet authentication failure (AEAD verification failed).
724    PacketAuthFailure,
725    /// NTS-KE protocol error (malformed records, unexpected messages).
726    ProtocolError,
727    /// Server identity changed between handshakes.
728    ServerIdentityChanged,
729    /// Key rotation required — re-handshake needed.
730    KeyRotation,
731    /// Connection limit reached or timeout exceeded.
732    ConnectionTimeout,
733}
734
735impl NtsFailureReason {
736    pub fn description(&self) -> &'static str {
737        match self {
738            NtsFailureReason::None => "NTS operational",
739            NtsFailureReason::TlsConnectionFailure => "TLS connection failure",
740            NtsFailureReason::CertificateFailure => {
741                "certificate validation failure (chain, expiry, or hostname)"
742            }
743            NtsFailureReason::AlpnFailure => {
744                "ALPN negotiation failed — server did not negotiate ntske/1"
745            }
746            NtsFailureReason::CookieFailure => {
747                "cookie exchange failed (zero cookies or invalid format)"
748            }
749            NtsFailureReason::AeadFailure => {
750                "AEAD algorithm negotiation failure (unsupported or mismatched)"
751            }
752            NtsFailureReason::PacketAuthFailure => {
753                "packet authentication failed (AEAD verification)"
754            }
755            NtsFailureReason::ProtocolError => "NTS-KE protocol error",
756            NtsFailureReason::ServerIdentityChanged => "server identity changed",
757            NtsFailureReason::KeyRotation => "key rotation required",
758            NtsFailureReason::ConnectionTimeout => "connection timeout or rate-limited",
759        }
760    }
761}
762
763/// NTS state for a single association.
764#[derive(Debug, Clone)]
765pub struct NtsState {
766    /// Client-to-server key.
767    pub c2s_key: Option<Vec<u8>>,
768    /// Server-to-client key.
769    pub s2c_key: Option<Vec<u8>>,
770    /// NTS cookies for this association.
771    pub cookies: Vec<Vec<u8>>,
772    /// The server's cookie — used by the server to regenerate the key material.
773    pub server_cookie_data: Option<Vec<u8>>,
774    /// AEAD algorithm negotiated.
775    pub aead_algorithm: u16,
776    /// NTS-KE protocol version.
777    pub nts_version: u8,
778    /// Whether NTS-KE has completed.
779    pub nts_ke_done: bool,
780    /// NTP port negotiated via NTS (0 = default 123).
781    pub ntspe_port: u16,
782    /// NTS-KE hostname.
783    pub ke_hostname: Option<String>,
784    /// NTS-KE port.
785    pub ke_port: u16,
786    /// Current NTS failure reason (Gate 8.3 — no silent downgrade).
787    pub failure_reason: NtsFailureReason,
788    /// Whether to force NTS-KE re-handshake (Gate 8.6).
789    pub needs_rehandshake: bool,
790    /// Cookie replenish threshold: when cookie_count() drops below this,
791    /// a new NTS-KE handshake should be triggered (Gate 8.6).
792    pub cookie_replenish_threshold: usize,
793}
794
795impl Default for NtsState {
796    fn default() -> Self {
797        Self::new()
798    }
799}
800
801impl NtsState {
802    pub fn new() -> Self {
803        Self {
804            c2s_key: None,
805            s2c_key: None,
806            cookies: Vec::new(),
807            server_cookie_data: None,
808            aead_algorithm: aead_algorithms::AES_SIV_CMAC_256,
809            nts_version: NTS_VERSION,
810            nts_ke_done: false,
811            ntspe_port: 0,
812            ke_hostname: None,
813            ke_port: NTS_KE_PORT,
814            failure_reason: NtsFailureReason::None,
815            needs_rehandshake: false,
816            cookie_replenish_threshold: NTS_MAX_COOKIES / 2,
817        }
818    }
819
820    /// Add an NTS cookie.
821    pub fn add_cookie(&mut self, cookie: Vec<u8>) {
822        if self.cookies.len() < NTS_MAX_COOKIES {
823            self.cookies.push(cookie);
824        }
825    }
826
827    /// Pop the first cookie (for use in an NTS request).
828    pub fn pop_cookie(&mut self) -> Option<Vec<u8>> {
829        if self.cookies.is_empty() {
830            None
831        } else {
832            Some(self.cookies.remove(0))
833        }
834    }
835
836    /// Number of cookies.
837    pub fn cookie_count(&self) -> usize {
838        self.cookies.len()
839    }
840
841    /// Whether we have keys for NTS.
842    pub fn is_nts_ready(&self) -> bool {
843        self.nts_ke_done && self.c2s_key.is_some() && self.s2c_key.is_some()
844    }
845
846    /// Whether cookie replenishment is needed (Gate 8.6).
847    pub fn needs_cookie_replenish(&self) -> bool {
848        self.cookies.len() <= self.cookie_replenish_threshold
849    }
850
851    /// Set the failure reason and mark that NTS is not operational (Gate 8.3).
852    pub fn set_failure(&mut self, reason: NtsFailureReason) {
853        self.failure_reason = reason;
854        self.nts_ke_done = false;
855    }
856
857    /// Clear the failure state.
858    pub fn clear_failure(&mut self) {
859        self.failure_reason = NtsFailureReason::None;
860    }
861
862    /// Get the failure description for Mode 6 variable reporting.
863    pub fn failure_description(&self) -> String {
864        if self.failure_reason == NtsFailureReason::None {
865            "OK".to_string()
866        } else {
867            format!(
868                "NTS_{}",
869                self.failure_reason
870                    .description()
871                    .to_uppercase()
872                    .replace(' ', "_")
873            )
874        }
875    }
876}
877
878// ──── NTS-KE record type constants (RFC 8915 §4.1, top-level aliases) ──
879
880// NTS-KE record type constants (RFC 8915 §4.1).
881pub const NTS_KE_RECORD_END_OF_MESSAGE: u16 = 0;
882pub const NTS_KE_RECORD_NEXT_PROTOCOL: u16 = 1;
883pub const NTS_KE_RECORD_ERROR: u16 = 2;
884pub const NTS_KE_RECORD_WARNING: u16 = 3;
885pub const NTS_KE_RECORD_AEAD_ALGORITHM: u16 = 4;
886pub const NTS_KE_RECORD_NEW_COOKIE: u16 = 5;
887pub const NTS_KE_RECORD_NTPV4_SERVER: u16 = 6;
888pub const NTS_KE_RECORD_NTPV4_PORT: u16 = 7;
889pub const NTS_KE_RECORD_CRITICAL_BIT: u16 = 0x8000;
890
891// AEAD algorithm identifiers (RFC 8915 §4.1.3).
892pub const AEAD_AES_SIV_CMAC_256: u16 = 15;
893pub const AEAD_AES_SIV_CMAC_512: u16 = 16;
894pub const AEAD_AES_GCM_128: u16 = 18;
895
896// NTS-KE TLS exporter label (RFC 8915 §4.5).
897pub const NTS_KE_EXPORTER_LABEL: &[u8] = b"EXPORTER-network-time-security";
898
899// Default NTS-KE server port.
900pub const NTS_KE_DEFAULT_PORT: u16 = 4460;
901
902// ──── Tests ───────────────────────────────────────────────────────────
903
904#[cfg(test)]
905mod tests {
906    use super::*;
907
908    #[test]
909    fn test_nts_state_new() {
910        let state = NtsState::new();
911        assert!(!state.is_nts_ready());
912        assert_eq!(state.cookie_count(), 0);
913        assert_eq!(state.nts_version, NTS_VERSION);
914        assert_eq!(state.ke_port, NTS_KE_PORT);
915        assert_eq!(state.failure_reason, NtsFailureReason::None);
916        assert!(!state.needs_rehandshake);
917        assert_eq!(state.cookie_replenish_threshold, NTS_MAX_COOKIES / 2);
918    }
919
920    #[test]
921    fn test_nts_state_cookies() {
922        let mut state = NtsState::new();
923        state.add_cookie(vec![1, 2, 3]);
924        state.add_cookie(vec![4, 5, 6]);
925        assert_eq!(state.cookie_count(), 2);
926        let cookie = state.pop_cookie().unwrap();
927        assert_eq!(cookie, vec![1, 2, 3]);
928        assert_eq!(state.cookie_count(), 1);
929    }
930
931    #[test]
932    fn test_nts_state_max_cookies() {
933        let mut state = NtsState::new();
934        for i in 0..NTS_MAX_COOKIES + 2 {
935            state.add_cookie(vec![i as u8]);
936        }
937        assert_eq!(state.cookie_count(), NTS_MAX_COOKIES);
938    }
939
940    #[test]
941    fn test_nts_state_failure_tracking() {
942        let mut state = NtsState::new();
943        assert_eq!(state.failure_reason, NtsFailureReason::None);
944        assert_eq!(state.failure_description(), "OK");
945
946        state.set_failure(NtsFailureReason::CertificateFailure);
947        assert_eq!(state.failure_reason, NtsFailureReason::CertificateFailure);
948        assert!(!state.nts_ke_done);
949        assert!(state.failure_description().contains("NTS_"));
950
951        state.clear_failure();
952        assert_eq!(state.failure_reason, NtsFailureReason::None);
953    }
954
955    #[test]
956    fn test_nts_state_cookie_replenish() {
957        let mut state = NtsState::new();
958        state.cookie_replenish_threshold = 4;
959        // With 0 cookies, needs replenish
960        assert!(state.needs_cookie_replenish());
961        // Add 3 cookies, still below threshold 4
962        for i in 0..3 {
963            state.add_cookie(vec![i]);
964        }
965        assert!(state.needs_cookie_replenish());
966        // Add one more = 4, threshold is 4, so needs_replenish (<= threshold)
967        state.add_cookie(vec![4]);
968        assert!(state.needs_cookie_replenish());
969        // Add one more = 5, above threshold 4
970        state.add_cookie(vec![5]);
971        assert!(!state.needs_cookie_replenish());
972    }
973
974    #[test]
975    fn test_nts_failure_reason_descriptions() {
976        assert_eq!(NtsFailureReason::None.description(), "NTS operational");
977        assert!(NtsFailureReason::CertificateFailure
978            .description()
979            .contains("certificate"));
980        assert!(NtsFailureReason::AlpnFailure.description().contains("ALPN"));
981        assert!(NtsFailureReason::PacketAuthFailure
982            .description()
983            .contains("authentication"));
984    }
985
986    #[test]
987    fn test_unique_key_generate() {
988        let key1 = NtsUniqueKey::generate();
989        let key2 = NtsUniqueKey::generate();
990        assert_ne!(key1.key_data, key2.key_data);
991        assert!(!key1.id.is_empty());
992        assert_eq!(key1.key_data.len(), 64);
993    }
994
995    #[test]
996    fn test_nts_ke_record_new() {
997        let rec = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![1, 2, 3, 4]);
998        assert_eq!(rec.record_type, NTS_KE_RECORD_NEW_COOKIE);
999        assert_eq!(rec.body, vec![1, 2, 3, 4]);
1000    }
1001
1002    #[test]
1003    fn test_record_encode_decode_roundtrip() {
1004        let rec = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![1, 2, 3, 4]);
1005        let encoded = rec.encode();
1006        let (decoded, remaining) = NtsKeRecord::decode(&encoded).unwrap();
1007        assert_eq!(decoded.record_type, NTS_KE_RECORD_NEW_COOKIE);
1008        assert_eq!(decoded.body, vec![1, 2, 3, 4]);
1009        assert!(remaining.is_empty());
1010    }
1011
1012    #[test]
1013    fn test_nts_ke_record_roundtrip() {
1014        let rec = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![1, 2, 3, 4]);
1015        let encoded = rec.encode();
1016        let (decoded, remaining) = NtsKeRecord::decode(&encoded).unwrap();
1017        assert_eq!(decoded.record_type, NTS_KE_RECORD_NEW_COOKIE);
1018        assert_eq!(decoded.body, vec![1, 2, 3, 4]);
1019        assert!(remaining.is_empty());
1020    }
1021
1022    #[test]
1023    fn test_nts_ke_record_decode_all() {
1024        let rec1 = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![1, 2, 3]);
1025        let rec2 = NtsKeRecord::new(NTS_KE_RECORD_NTPV4_SERVER, vec![1]);
1026        let eom = NtsKeRecord::new_critical(NTS_KE_RECORD_END_OF_MESSAGE, vec![]);
1027        let mut data = rec1.encode();
1028        data.extend_from_slice(&rec2.encode());
1029        data.extend_from_slice(&eom.encode());
1030        let (records, trailing) = NtsKeRecord::decode_all(&data);
1031        assert_eq!(records.len(), 3);
1032        assert_eq!(records[0].record_type, NTS_KE_RECORD_NEW_COOKIE);
1033        assert_eq!(records[1].record_type, NTS_KE_RECORD_NTPV4_SERVER);
1034        assert!(
1035            (records[2].record_type & !NTS_KE_RECORD_CRITICAL_BIT) == NTS_KE_RECORD_END_OF_MESSAGE
1036        );
1037        assert!(records[2].record_type & NTS_KE_RECORD_CRITICAL_BIT != 0);
1038        assert!(trailing.is_empty());
1039    }
1040
1041    #[test]
1042    fn test_decode_all() {
1043        // Extended decode_all test with multiple record types and trailing data.
1044        let rec1 = NtsKeRecord::new(NTS_KE_RECORD_AEAD_ALGORITHM, vec![0, 1]);
1045        let rec2 = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![10, 20, 30]);
1046        let eom = NtsKeRecord::new_critical(NTS_KE_RECORD_END_OF_MESSAGE, vec![]);
1047        let mut data = rec1.encode();
1048        data.extend_from_slice(&rec2.encode());
1049        data.extend_from_slice(&eom.encode());
1050        // Add trailing data — decode_all returns it as the second element.
1051        let trailing_rec = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![99]);
1052        data.extend_from_slice(&trailing_rec.encode());
1053
1054        let (records, trailing) = NtsKeRecord::decode_all(&data);
1055        // All 4 records are parsed (the trailing cookie is now a 4th record).
1056        assert_eq!(records.len(), 4);
1057        assert_eq!(records[0].record_type, NTS_KE_RECORD_AEAD_ALGORITHM);
1058        assert_eq!(records[1].record_type, NTS_KE_RECORD_NEW_COOKIE);
1059        assert!(
1060            (records[2].record_type & !NTS_KE_RECORD_CRITICAL_BIT) == NTS_KE_RECORD_END_OF_MESSAGE
1061        );
1062        assert_eq!(records[3].record_type, NTS_KE_RECORD_NEW_COOKIE);
1063        assert!(trailing.is_empty(), "decode_all parsed everything");
1064    }
1065
1066    #[test]
1067    fn test_aead_key_length() {
1068        assert_eq!(AeadAlgorithm::AeadAesSivCmac256.key_length(), 32);
1069        assert_eq!(AeadAlgorithm::AeadAesSivCmac512.key_length(), 64);
1070        assert_eq!(AeadAlgorithm::AeadAesGcm128.key_length(), 16);
1071    }
1072
1073    #[test]
1074    fn test_aead_algorithms() {
1075        assert!(aead_algorithms::SUPPORTED.contains(&aead_algorithms::AES_SIV_CMAC_256));
1076    }
1077
1078    #[test]
1079    fn test_aead_algorithm_from_to_u16() {
1080        for v in [15u16, 16, 18] {
1081            let alg = AeadAlgorithm::from_u16(v).unwrap();
1082            assert_eq!(alg.to_u16(), v);
1083        }
1084        assert!(AeadAlgorithm::from_u16(0).is_none());
1085        assert!(AeadAlgorithm::from_u16(99).is_none());
1086    }
1087
1088    #[test]
1089    fn test_nts_ke_state() {
1090        let state = NtsKeState::Idle;
1091        assert!(!state.is_terminal());
1092        assert!(!state.is_established());
1093
1094        let state = NtsKeState::Connecting;
1095        assert!(!state.is_terminal());
1096
1097        let state = NtsKeState::Negotiating;
1098        assert!(!state.is_terminal());
1099
1100        let state = NtsKeState::Established;
1101        assert!(state.is_terminal());
1102        assert!(state.is_established());
1103
1104        let state = NtsKeState::Error("something broke".to_string());
1105        assert!(state.is_terminal());
1106        assert!(!state.is_established());
1107        assert_eq!(state.error_message(), Some("something broke"));
1108    }
1109
1110    #[test]
1111    fn test_nts_ke_state_error_none() {
1112        let state = NtsKeState::Idle;
1113        assert_eq!(state.error_message(), None);
1114    }
1115
1116    #[test]
1117    fn test_nts_ke_client_new() {
1118        let client = NtsKeProtocolClient::new("ntp.example.com", NTS_KE_PORT);
1119        assert_eq!(client.host(), "ntp.example.com");
1120        assert_eq!(client.port(), NTS_KE_PORT);
1121        assert_eq!(*client.state(), NtsKeState::Idle);
1122        assert!(client.cookies().is_empty());
1123        assert!(client.aead().is_none());
1124    }
1125
1126    #[test]
1127    fn test_nts_ke_client_reset() {
1128        let mut client = NtsKeProtocolClient::new("ntp.example.com", NTS_KE_PORT);
1129        client.reset();
1130        assert_eq!(*client.state(), NtsKeState::Idle);
1131        assert!(client.cookies().is_empty());
1132        assert!(client.aead().is_none());
1133    }
1134
1135    #[test]
1136    fn test_nts_ke_client_handshake_with_data() {
1137        let mut client = NtsKeProtocolClient::new("ntp.example.com", NTS_KE_PORT);
1138
1139        // Build a mock server response: MUST include critical Next Protocol with u16 body, critical EOM.
1140        let next_proto =
1141            NtsKeRecord::new_critical(NTS_KE_RECORD_NEXT_PROTOCOL, 0u16.to_be_bytes().to_vec());
1142        let aead_rec = NtsKeRecord::new(
1143            NTS_KE_RECORD_AEAD_ALGORITHM,
1144            (15u16).to_be_bytes().to_vec(), // AEAD_AES_SIV_CMAC_256
1145        );
1146        let cookie1 = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![0xAA; 32]);
1147        let cookie2 = NtsKeRecord::new(NTS_KE_RECORD_NEW_COOKIE, vec![0xBB; 32]);
1148        let eom = NtsKeRecord::new_critical(NTS_KE_RECORD_END_OF_MESSAGE, vec![]);
1149
1150        let mut response = Vec::new();
1151        response.extend_from_slice(&next_proto.encode());
1152        response.extend_from_slice(&aead_rec.encode());
1153        response.extend_from_slice(&cookie1.encode());
1154        response.extend_from_slice(&cookie2.encode());
1155        response.extend_from_slice(&eom.encode());
1156
1157        // Build a minimal request with critical records throughout.
1158        let req_next_proto =
1159            NtsKeRecord::new_critical(NTS_KE_RECORD_NEXT_PROTOCOL, 0u16.to_be_bytes().to_vec());
1160        let req_aead =
1161            NtsKeRecord::new_critical(NTS_KE_RECORD_AEAD_ALGORITHM, (15u16).to_be_bytes().to_vec());
1162        let req_eom = NtsKeRecord::new_critical(NTS_KE_RECORD_END_OF_MESSAGE, vec![]);
1163        let mut request = Vec::new();
1164        request.extend_from_slice(&req_next_proto.encode());
1165        request.extend_from_slice(&req_aead.encode());
1166        request.extend_from_slice(&req_eom.encode());
1167
1168        let negotiation = client
1169            .handshake_with_data(&request, &response, None)
1170            .unwrap();
1171        assert_eq!(negotiation.aead_algorithm, AeadAlgorithm::AeadAesSivCmac256);
1172        assert_eq!(negotiation.cookie_count(), 2);
1173        assert_eq!(negotiation.cookies[0], vec![0xAA; 32]);
1174        assert_eq!(negotiation.cookies[1], vec![0xBB; 32]);
1175        assert_eq!(*client.state(), NtsKeState::Established);
1176        assert_eq!(client.aead(), Some(AeadAlgorithm::AeadAesSivCmac256));
1177    }
1178
1179    #[test]
1180    fn test_nts_ke_client_handshake_with_data_empty_response() {
1181        let mut client = NtsKeProtocolClient::new("ntp.example.com", NTS_KE_PORT);
1182        let request = NtsKeRecord::new_critical(NTS_KE_RECORD_END_OF_MESSAGE, vec![]).encode();
1183        let result = client.handshake_with_data(&request, &[], None);
1184        assert!(result.is_err());
1185        assert!(client.state().error_message().is_some());
1186    }
1187
1188    #[test]
1189    fn test_nts_ke_client_handshake_stub_returns_error() {
1190        let mut client = NtsKeProtocolClient::new("ntp.example.com", NTS_KE_PORT);
1191        let result = client.handshake();
1192        assert!(result.is_err());
1193        // The error should mention TLS transport being a stub.
1194        let err_msg = result.unwrap_err();
1195        assert!(
1196            err_msg.contains("TLS") || err_msg.contains("transport") || err_msg.contains("stub")
1197        );
1198    }
1199
1200    #[test]
1201    fn test_nts_ke_negotiation_new() {
1202        let mut neg = NtsKeNegotiation::new(
1203            AeadAlgorithm::AeadAesSivCmac256,
1204            vec![vec![1, 2, 3], vec![4, 5, 6]],
1205        );
1206        assert_eq!(neg.cookie_count(), 2);
1207        assert_eq!(neg.take_cookie(), Some(vec![1, 2, 3]));
1208        assert_eq!(neg.cookie_count(), 1);
1209    }
1210
1211    #[test]
1212    fn test_nts_error_code() {
1213        assert_eq!(NtsErrorCode::from_u16(0), NtsErrorCode::None);
1214        assert_eq!(NtsErrorCode::from_u16(1), NtsErrorCode::Internal);
1215        assert_eq!(NtsErrorCode::from_u16(2), NtsErrorCode::UnknownRecord);
1216        assert_eq!(NtsErrorCode::from_u16(3), NtsErrorCode::BadRequest);
1217        assert_eq!(NtsErrorCode::from_u16(4), NtsErrorCode::AuthFailure);
1218        assert_eq!(NtsErrorCode::from_u16(5), NtsErrorCode::UnknownAlgorithm);
1219        assert_eq!(NtsErrorCode::from_u16(6), NtsErrorCode::CookieTooLarge);
1220        assert_eq!(NtsErrorCode::from_u16(99), NtsErrorCode::Internal);
1221        assert_eq!(NtsErrorCode::None.to_u16(), 0);
1222        assert_eq!(NtsErrorCode::Internal.to_u16(), 1);
1223    }
1224
1225    #[test]
1226    fn test_record_encode_decode_minimal() {
1227        // Empty body
1228        let rec = NtsKeRecord::new(NTS_KE_RECORD_END_OF_MESSAGE, vec![]);
1229        let encoded = rec.encode();
1230        assert_eq!(encoded.len(), 4);
1231        let (decoded, remaining) = NtsKeRecord::decode(&encoded).unwrap();
1232        assert_eq!(decoded.record_type, NTS_KE_RECORD_END_OF_MESSAGE);
1233        assert!(decoded.body.is_empty());
1234        assert!(remaining.is_empty());
1235    }
1236
1237    #[test]
1238    fn test_record_decode_truncated() {
1239        // Only 2 bytes (need 4 for header)
1240        let result = NtsKeRecord::decode(&[0x00, 0x01]);
1241        assert!(result.is_none());
1242
1243        // Header says body is 10 bytes but only 2 available
1244        let result = NtsKeRecord::decode(&[0x00, 0x01, 0x00, 0x0A, 0xFF, 0xFF]);
1245        assert!(result.is_none());
1246    }
1247
1248    #[test]
1249    fn test_nts_ke_record_constants() {
1250        assert_eq!(NTS_KE_RECORD_END_OF_MESSAGE, 0);
1251        assert_eq!(NTS_KE_RECORD_NEXT_PROTOCOL, 1);
1252        assert_eq!(NTS_KE_RECORD_ERROR, 2);
1253        assert_eq!(NTS_KE_RECORD_WARNING, 3);
1254        assert_eq!(NTS_KE_RECORD_AEAD_ALGORITHM, 4);
1255        assert_eq!(NTS_KE_RECORD_NEW_COOKIE, 5);
1256        assert_eq!(NTS_KE_RECORD_NTPV4_SERVER, 6);
1257        assert_eq!(NTS_KE_RECORD_NTPV4_PORT, 7);
1258        assert_eq!(NTS_KE_RECORD_CRITICAL_BIT, 0x8000);
1259        assert_eq!(AEAD_AES_SIV_CMAC_256, 15);
1260        assert_eq!(AEAD_AES_SIV_CMAC_512, 16);
1261        assert_eq!(AEAD_AES_GCM_128, 18);
1262    }
1263}