ccache-io 0.1.0

Pure-Rust MIT Kerberos credential-cache (ccache v4) reader + writer — round-trip a `krb5cc_*` file, walk its principals + tickets, or emit one from your own auth code. No FFI, no `libkrb5`, no MIT runtime dependency.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! # ccache-io — MIT Kerberos credential-cache (v4) read + write, pure Rust.
//!
//! Consumers of a Kerberos ticket rarely acquire it themselves — an operator drops in a
//! `krb5cc_*` file from MIT `kinit`, from a pentest toolkit, or from Windows via `.kirbi`
//! export. To interop with any of it, you need to parse the on-disk format. `ccache-io`
//! is a **pure-Rust MIT ccache v4 codec** with no dependency on `libkrb5`, `krb5-config`,
//! or any FFI — one crate, one file, one `thiserror` dep.
//!
//! ## Wire format
//!
//! v0.1 targets the v4 format only (MIT `krb5` ≥ 1.4, ubiquitous since 2005):
//!
//! ```text
//!   file  = header : primary : cred*
//!   header= u16 version(=0x0504) : u16 header_len : header_len bytes of tagged fields
//!   principal = u32 name_type : u32 num_components : counted-str realm : counted-str * num_components
//!   cred    = principal client : principal server : keyblock :
//!             u32 authtime : u32 starttime : u32 endtime : u32 renew_till :
//!             u8  is_skey : u32 tktflags :
//!             u32 num_addresses  : address*
//!             u32 num_authdata   : authdata*
//!             counted-bytes ticket : counted-bytes second_ticket
//!   keyblock = u16 keytype : u16 etype(=0) : counted-bytes key
//!   counted-str/bytes = u32 len : len bytes
//! ```
//!
//! Multi-byte integers are big-endian (network order), matching MIT convention. This
//! implementation is intentionally strict: an unrecognized version, a length that overflows
//! the buffer, or a truncated field is a decoded [`CcacheError`], never a panic — safe to
//! feed attacker-controlled bytes at the boundary.
//!
//! ## Example
//!
//! ```
//! use ccache_io::Ccache;
//! # let bytes: Vec<u8> = ccache_io::tests_only::sample_ccache_bytes();
//! let cc = Ccache::parse(&bytes).unwrap();
//! for c in &cc.credentials {
//!     println!(
//!         "{} → {}  (endtime={})",
//!         c.client.canonical(),
//!         c.server.canonical(),
//!         c.endtime,
//!     );
//! }
//! let round = cc.to_bytes();
//! assert_eq!(round, bytes);
//! ```

#![deny(unsafe_code)]
#![warn(missing_docs)]
#![doc(html_root_url = "https://docs.rs/ccache-io/0.1.0")]

use thiserror::Error;

/// v4 file magic (`0x0504`). v3 (`0x0503`) is little-endian and predates 2005; v0.1 does
/// not accept it — a wider `Version` enum can be added in v0.2 without a break because of
/// [`CcacheError`]'s `#[non_exhaustive]`.
pub const V4_MAGIC: u16 = 0x0504;

/// MIT `KRB5_NT_PRINCIPAL` (1) — a client account principal.
pub const NT_PRINCIPAL: u32 = 1;
/// MIT `KRB5_NT_SRV_INST` (2) — the standard shape for `krbtgt`, `HOST/…`, service SPNs.
pub const NT_SRV_INST: u32 = 2;

/// Every fatal shape/length problem this crate produces. Marked `#[non_exhaustive]` so new
/// diagnostics land as patch bumps rather than breaking downstream `match` blocks.
#[non_exhaustive]
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CcacheError {
    /// The file header did not start with a supported version tag.
    #[error("unsupported ccache version {found:#06x} (expected {expected:#06x})")]
    UnsupportedVersion {
        /// The u16 we actually read.
        found: u16,
        /// The version this build accepts (currently `0x0504`).
        expected: u16,
    },
    /// A length field would run past the end of the buffer — the file is truncated or the
    /// declared count is hostile.
    #[error("truncated input: need {need} bytes at offset {at}, have {remaining}")]
    Truncated {
        /// Bytes the field claimed to need.
        need: usize,
        /// Byte offset the field started at.
        at: usize,
        /// Bytes actually left in the buffer at that offset.
        remaining: usize,
    },
    /// A component count on a principal exceeded the sane cap. MIT's own `krb5.h` limits
    /// this in practice; hostile input tries to force a giant `Vec::with_capacity`.
    #[error("component count {count} at offset {at} exceeds sane cap ({cap})")]
    TooManyComponents {
        /// Declared count.
        count: u32,
        /// Byte offset it was read at.
        at: usize,
        /// The refuse-above threshold.
        cap: u32,
    },
    /// The variable-length field decoded as valid UTF-16 or ASCII but not as UTF-8 — MIT
    /// ccache stores principal component names as bytes without an encoding tag, so a
    /// non-UTF-8 realm typically means a corrupt file (or a file from a locale we don't
    /// yet handle).
    #[error("non-UTF-8 principal string at offset {at}: {source}")]
    Utf8 {
        /// Byte offset the string started at.
        at: usize,
        /// Underlying UTF-8 error.
        #[source]
        source: std::str::Utf8Error,
    },
}

/// A Kerberos principal — realm + one or more name components (`user`, `host/dc01`,
/// `krbtgt/REALM`). The `name_type` distinguishes user principals from services.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Principal {
    /// The realm (e.g. `TESTLAB.LOCAL`). Case-sensitive; MIT convention is uppercase.
    pub realm: String,
    /// `NT_PRINCIPAL` (1), `NT_SRV_INST` (2), or another `KRB5_NT_*` constant.
    pub name_type: u32,
    /// Name components — one for a user (`["alice"]`), two for a service (`["HOST","dc01"]`),
    /// two for `krbtgt` (`["krbtgt","REALM"]`).
    pub components: Vec<String>,
}

impl Principal {
    /// Render as MIT canonical form: `comp1/comp2/…@REALM` — the shape `klist` prints.
    pub fn canonical(&self) -> String {
        format!("{}@{}", self.components.join("/"), self.realm)
    }
}

/// Symmetric key material for the credential — session key for a TGT, service key for a
/// ticket. MIT stores an `etype` alongside the keytype for historical reasons; it is
/// always zero in v4 files and mirrored back on write.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyBlock {
    /// Kerberos encryption type — 17 (`AES128-CTS-HMAC-SHA1-96`), 18 (`AES256-CTS-HMAC-SHA1-96`),
    /// 23 (`RC4-HMAC`), … — one of the `ETYPE_*` constants in `krb5.h`.
    pub keytype: u16,
    /// Raw key bytes, length determined by `keytype` (16 for AES128 / RC4, 32 for AES256).
    pub key: Vec<u8>,
}

/// A network address the ticket is bound to (rarely populated in modern deployments).
/// v0.1 keeps the raw wire triple so a round-trip is byte-exact even for exotic values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Address {
    /// MIT `ADDRTYPE_*` — 2 for IPv4, 24 for IPv6, etc.
    pub addr_type: u16,
    /// Raw address bytes as stored in the file.
    pub data: Vec<u8>,
}

/// An `AuthorizationData` entry (RFC 4120 §5.2.6) — the shape the KDC uses to attach a
/// Windows PAC to a ticket. v0.1 exposes the raw ASN.1 blob for byte-exact round-trip.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuthData {
    /// MIT `KRB5_AUTHDATA_*` — 1 for `IF-RELEVANT`, 128 for `WIN2K-PAC`.
    pub ad_type: u16,
    /// The DER-encoded AuthorizationData contents.
    pub data: Vec<u8>,
}

/// One cached credential — client, server, key, times, and the encrypted ticket blob.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Credential {
    /// The principal the credential is issued for.
    pub client: Principal,
    /// The service the ticket authenticates to (`krbtgt/REALM@REALM` for a TGT).
    pub server: Principal,
    /// Session or service key.
    pub key: KeyBlock,
    /// Seconds since Unix epoch when the KDC issued the ticket.
    pub authtime: u32,
    /// Earliest use time (usually equal to `authtime`).
    pub starttime: u32,
    /// Ticket expiry.
    pub endtime: u32,
    /// Absolute renewal deadline (0 if non-renewable).
    pub renew_till: u32,
    /// `true` when this record stores a raw session key rather than a ticket — set for
    /// TGT-holding cache entries; false for service tickets.
    pub is_skey: bool,
    /// The 32-bit MIT `TicketFlags` bitmask.
    pub tktflags: u32,
    /// Address restrictions on the ticket (empty in modern deployments).
    pub addresses: Vec<Address>,
    /// Authorization data attached to the ticket (Windows PAC lives here).
    pub authdata: Vec<AuthData>,
    /// The encrypted ticket, opaque as far as ccache is concerned — DER-encoded MIT
    /// `Ticket` (RFC 4120 §5.3), the exact bytes handed to `AP-REQ`.
    pub ticket: Vec<u8>,
    /// The "second ticket" slot, used by `U2U` and `enc-tkt-in-skey`; empty for a plain TGT.
    pub second_ticket: Vec<u8>,
}

/// A parsed ccache file — a default principal and every credential the KDC issued it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ccache {
    /// File-header tagged fields, exactly as read — v0.1 preserves them opaquely so
    /// round-tripping doesn't disturb DConf / DeltaTime tags callers may not understand.
    pub header: Vec<u8>,
    /// The default principal — the identity `klist` labels the cache with.
    pub primary: Principal,
    /// Every credential in the cache, in file order (the order MIT tools rely on for
    /// "most recently added" selection).
    pub credentials: Vec<Credential>,
}

/// Refuse a principal that claims more than this many components — MIT's own tools
/// tighten to 100-ish, we allow a generous cap that still stops a `u32::MAX` allocation.
const MAX_COMPONENTS: u32 = 1024;
/// The default header block emitted by MIT `krb5` ≥ 1.4 — one 12-byte `DeltaTime` tag
/// with all zeros, matching every current-generation `kinit`.
const DEFAULT_HEADER: &[u8] = &[
    0x00, 0x01, // tag = DeltaTime
    0x00, 0x08, // len = 8
    0, 0, 0, 0, 0, 0, 0, 0, // 8 bytes of zeroed DeltaTime data
];

impl Ccache {
    /// Parse the on-disk v4 format. Returns [`CcacheError::UnsupportedVersion`] on any
    /// magic other than `0x0504` and [`CcacheError::Truncated`] on any length that would
    /// run past the buffer.
    pub fn parse(bytes: &[u8]) -> Result<Self, CcacheError> {
        let mut r = Reader::new(bytes);
        let version = r.u16()?;
        if version != V4_MAGIC {
            return Err(CcacheError::UnsupportedVersion {
                found: version,
                expected: V4_MAGIC,
            });
        }
        let header_len = r.u16()? as usize;
        let header = r.take(header_len)?.to_vec();
        let primary = read_principal(&mut r)?;
        let mut credentials = Vec::new();
        while r.remaining() > 0 {
            credentials.push(read_credential(&mut r)?);
        }
        Ok(Ccache {
            header,
            primary,
            credentials,
        })
    }

    /// Emit the on-disk v4 format. `parse(&cc.to_bytes()) == Ok(cc)` for every legal cache.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut w = Writer::new();
        w.u16(V4_MAGIC);
        w.u16(self.header.len() as u16);
        w.bytes(&self.header);
        write_principal(&mut w, &self.primary);
        for c in &self.credentials {
            write_credential(&mut w, c);
        }
        w.take()
    }

    /// Build an empty cache with the standard MIT header block — the shape `kinit`
    /// produces on a brand-new file. Callers push credentials, then `to_bytes()`.
    pub fn new(primary: Principal) -> Self {
        Ccache {
            header: DEFAULT_HEADER.to_vec(),
            primary,
            credentials: Vec::new(),
        }
    }
}

// ─── wire helpers ───────────────────────────────────────────────────────────

struct Reader<'a> {
    b: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(b: &'a [u8]) -> Self {
        Reader { b, pos: 0 }
    }
    fn remaining(&self) -> usize {
        self.b.len() - self.pos
    }
    fn take(&mut self, n: usize) -> Result<&'a [u8], CcacheError> {
        if n > self.remaining() {
            return Err(CcacheError::Truncated {
                need: n,
                at: self.pos,
                remaining: self.remaining(),
            });
        }
        let slice = &self.b[self.pos..self.pos + n];
        self.pos += n;
        Ok(slice)
    }
    fn u16(&mut self) -> Result<u16, CcacheError> {
        let b = self.take(2)?;
        Ok(u16::from_be_bytes([b[0], b[1]]))
    }
    fn u32(&mut self) -> Result<u32, CcacheError> {
        let b = self.take(4)?;
        Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
    }
    fn u8(&mut self) -> Result<u8, CcacheError> {
        Ok(self.take(1)?[0])
    }
    fn counted(&mut self) -> Result<&'a [u8], CcacheError> {
        let n = self.u32()? as usize;
        self.take(n)
    }
    fn counted_str(&mut self) -> Result<String, CcacheError> {
        let at = self.pos;
        let bytes = self.counted()?;
        std::str::from_utf8(bytes)
            .map(str::to_string)
            .map_err(|source| CcacheError::Utf8 { at, source })
    }
}

struct Writer(Vec<u8>);

impl Writer {
    fn new() -> Self {
        Writer(Vec::with_capacity(512))
    }
    fn take(self) -> Vec<u8> {
        self.0
    }
    fn u16(&mut self, v: u16) {
        self.0.extend_from_slice(&v.to_be_bytes());
    }
    fn u32(&mut self, v: u32) {
        self.0.extend_from_slice(&v.to_be_bytes());
    }
    fn u8(&mut self, v: u8) {
        self.0.push(v);
    }
    fn bytes(&mut self, b: &[u8]) {
        self.0.extend_from_slice(b);
    }
    fn counted(&mut self, b: &[u8]) {
        self.u32(b.len() as u32);
        self.bytes(b);
    }
}

fn read_principal(r: &mut Reader) -> Result<Principal, CcacheError> {
    let at = r.pos;
    let name_type = r.u32()?;
    let num = r.u32()?;
    if num > MAX_COMPONENTS {
        return Err(CcacheError::TooManyComponents {
            count: num,
            at,
            cap: MAX_COMPONENTS,
        });
    }
    let realm = r.counted_str()?;
    let mut components = Vec::with_capacity(num as usize);
    for _ in 0..num {
        components.push(r.counted_str()?);
    }
    Ok(Principal {
        realm,
        name_type,
        components,
    })
}

fn write_principal(w: &mut Writer, p: &Principal) {
    w.u32(p.name_type);
    w.u32(p.components.len() as u32);
    w.counted(p.realm.as_bytes());
    for c in &p.components {
        w.counted(c.as_bytes());
    }
}

fn read_credential(r: &mut Reader) -> Result<Credential, CcacheError> {
    let client = read_principal(r)?;
    let server = read_principal(r)?;
    let keytype = r.u16()?;
    let _etype_unused = r.u16()?;
    let key_bytes = r.counted()?.to_vec();
    let authtime = r.u32()?;
    let starttime = r.u32()?;
    let endtime = r.u32()?;
    let renew_till = r.u32()?;
    let is_skey = r.u8()? != 0;
    let tktflags = r.u32()?;
    let num_addr = r.u32()? as usize;
    if num_addr > MAX_COMPONENTS as usize {
        return Err(CcacheError::TooManyComponents {
            count: num_addr as u32,
            at: r.pos,
            cap: MAX_COMPONENTS,
        });
    }
    let mut addresses = Vec::with_capacity(num_addr);
    for _ in 0..num_addr {
        let addr_type = r.u16()?;
        let data = r.counted()?.to_vec();
        addresses.push(Address { addr_type, data });
    }
    let num_ad = r.u32()? as usize;
    if num_ad > MAX_COMPONENTS as usize {
        return Err(CcacheError::TooManyComponents {
            count: num_ad as u32,
            at: r.pos,
            cap: MAX_COMPONENTS,
        });
    }
    let mut authdata = Vec::with_capacity(num_ad);
    for _ in 0..num_ad {
        let ad_type = r.u16()?;
        let data = r.counted()?.to_vec();
        authdata.push(AuthData { ad_type, data });
    }
    let ticket = r.counted()?.to_vec();
    let second_ticket = r.counted()?.to_vec();
    Ok(Credential {
        client,
        server,
        key: KeyBlock {
            keytype,
            key: key_bytes,
        },
        authtime,
        starttime,
        endtime,
        renew_till,
        is_skey,
        tktflags,
        addresses,
        authdata,
        ticket,
        second_ticket,
    })
}

fn write_credential(w: &mut Writer, c: &Credential) {
    write_principal(w, &c.client);
    write_principal(w, &c.server);
    w.u16(c.key.keytype);
    w.u16(0); // etype field, always zero in v4
    w.counted(&c.key.key);
    w.u32(c.authtime);
    w.u32(c.starttime);
    w.u32(c.endtime);
    w.u32(c.renew_till);
    w.u8(if c.is_skey { 1 } else { 0 });
    w.u32(c.tktflags);
    w.u32(c.addresses.len() as u32);
    for a in &c.addresses {
        w.u16(a.addr_type);
        w.counted(&a.data);
    }
    w.u32(c.authdata.len() as u32);
    for a in &c.authdata {
        w.u16(a.ad_type);
        w.counted(&a.data);
    }
    w.counted(&c.ticket);
    w.counted(&c.second_ticket);
}

/// Test-only helpers reachable from doctests. Not part of the stable public API.
#[doc(hidden)]
pub mod tests_only {
    use super::*;

    /// A hand-crafted minimal ccache — one principal `alice@TESTLAB.LOCAL`, one TGT for
    /// `krbtgt/TESTLAB.LOCAL@TESTLAB.LOCAL` with an AES256 session key and an opaque
    /// ticket blob. Sufficient for the doctest and the round-trip test.
    pub fn sample_ccache_bytes() -> Vec<u8> {
        let cc = Ccache {
            header: DEFAULT_HEADER.to_vec(),
            primary: Principal {
                realm: "TESTLAB.LOCAL".into(),
                name_type: NT_PRINCIPAL,
                components: vec!["alice".into()],
            },
            credentials: vec![Credential {
                client: Principal {
                    realm: "TESTLAB.LOCAL".into(),
                    name_type: NT_PRINCIPAL,
                    components: vec!["alice".into()],
                },
                server: Principal {
                    realm: "TESTLAB.LOCAL".into(),
                    name_type: NT_SRV_INST,
                    components: vec!["krbtgt".into(), "TESTLAB.LOCAL".into()],
                },
                key: KeyBlock {
                    keytype: 18, // AES256-CTS-HMAC-SHA1-96
                    key: vec![0x11u8; 32],
                },
                authtime: 0x6600_0000,
                starttime: 0x6600_0000,
                endtime: 0x6600_A000,
                renew_till: 0x6601_0000,
                is_skey: false,
                tktflags: 0x5010_0000, // FORWARDABLE | RENEWABLE | INITIAL
                addresses: Vec::new(),
                authdata: Vec::new(),
                ticket: b"OPAQUE-DER-TICKET-BYTES".to_vec(),
                second_ticket: Vec::new(),
            }],
        };
        cc.to_bytes()
    }
}

// ─── tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn header_magic_is_be_0504() {
        let bytes = tests_only::sample_ccache_bytes();
        assert_eq!(&bytes[..2], &[0x05, 0x04]);
    }

    #[test]
    fn roundtrip_byte_exact() {
        let bytes = tests_only::sample_ccache_bytes();
        let parsed = Ccache::parse(&bytes).expect("parse");
        assert_eq!(parsed.primary.canonical(), "alice@TESTLAB.LOCAL");
        assert_eq!(parsed.credentials.len(), 1);
        let cred = &parsed.credentials[0];
        assert_eq!(
            cred.server.canonical(),
            "krbtgt/TESTLAB.LOCAL@TESTLAB.LOCAL"
        );
        assert_eq!(cred.key.keytype, 18);
        assert_eq!(cred.key.key.len(), 32);
        assert_eq!(cred.tktflags, 0x5010_0000);
        assert_eq!(&cred.ticket, b"OPAQUE-DER-TICKET-BYTES");
        let re = parsed.to_bytes();
        assert_eq!(re, bytes, "round-trip must be byte-identical");
    }

    #[test]
    fn rejects_wrong_magic() {
        let mut bytes = tests_only::sample_ccache_bytes();
        bytes[0] = 0x05;
        bytes[1] = 0x03; // v3 magic — unsupported in v0.1
        let err = Ccache::parse(&bytes).unwrap_err();
        assert_eq!(
            err,
            CcacheError::UnsupportedVersion {
                found: 0x0503,
                expected: V4_MAGIC
            }
        );
    }

    #[test]
    fn rejects_truncated_body() {
        let bytes = tests_only::sample_ccache_bytes();
        let short = &bytes[..bytes.len() - 5];
        let err = Ccache::parse(short).unwrap_err();
        assert!(matches!(err, CcacheError::Truncated { .. }));
    }

    #[test]
    fn rejects_hostile_component_count() {
        // Craft: valid header + principal with num_components = u32::MAX. Must not
        // allocate `Vec::with_capacity(u32::MAX)` — must reject bounded-alloc-style.
        let mut w = Writer::new();
        w.u16(V4_MAGIC);
        w.u16(DEFAULT_HEADER.len() as u16);
        w.bytes(DEFAULT_HEADER);
        w.u32(NT_PRINCIPAL); // name_type
        w.u32(u32::MAX); // hostile num_components
        w.counted(b"REALM");
        let err = Ccache::parse(&w.take()).unwrap_err();
        assert!(matches!(
            err,
            CcacheError::TooManyComponents {
                count: u32::MAX,
                ..
            }
        ));
    }

    #[test]
    fn multi_credential_cache_roundtrips() {
        let mut cc = Ccache::new(Principal {
            realm: "CORP.LOCAL".into(),
            name_type: NT_PRINCIPAL,
            components: vec!["bob".into()],
        });
        for i in 0..5u32 {
            cc.credentials.push(Credential {
                client: cc.primary.clone(),
                server: Principal {
                    realm: "CORP.LOCAL".into(),
                    name_type: NT_SRV_INST,
                    components: vec!["HOST".into(), format!("srv{i}.corp.local")],
                },
                key: KeyBlock {
                    keytype: 17,
                    key: vec![i as u8; 16],
                },
                authtime: 100 + i,
                starttime: 100 + i,
                endtime: 200 + i,
                renew_till: 0,
                is_skey: i.is_multiple_of(2),
                tktflags: 0x40000000,
                addresses: Vec::new(),
                authdata: Vec::new(),
                ticket: vec![i as u8; 32],
                second_ticket: Vec::new(),
            });
        }
        let bytes = cc.to_bytes();
        let parsed = Ccache::parse(&bytes).unwrap();
        assert_eq!(parsed.credentials.len(), 5);
        assert_eq!(parsed.to_bytes(), bytes);
    }

    #[test]
    fn utf8_realm_error_carries_offset() {
        // Craft a principal whose realm is bytes 0xFF 0xFE (invalid UTF-8 — a UTF-16 BOM).
        let mut w = Writer::new();
        w.u16(V4_MAGIC);
        w.u16(0);
        w.u32(NT_PRINCIPAL);
        w.u32(0); // no components
        w.counted(&[0xFF, 0xFE]); // realm bytes
        let err = Ccache::parse(&w.take()).unwrap_err();
        assert!(matches!(err, CcacheError::Utf8 { .. }));
    }
}