Skip to main content

ccache_io/
lib.rs

1//! # ccache-io — MIT Kerberos credential-cache (v4) read + write, pure Rust.
2//!
3//! Consumers of a Kerberos ticket rarely acquire it themselves — an operator drops in a
4//! `krb5cc_*` file from MIT `kinit`, from a pentest toolkit, or from Windows via `.kirbi`
5//! export. To interop with any of it, you need to parse the on-disk format. `ccache-io`
6//! is a **pure-Rust MIT ccache v4 codec** with no dependency on `libkrb5`, `krb5-config`,
7//! or any FFI — one crate, one file, one `thiserror` dep.
8//!
9//! ## Wire format
10//!
11//! v0.1 targets the v4 format only (MIT `krb5` ≥ 1.4, ubiquitous since 2005):
12//!
13//! ```text
14//!   file  = header : primary : cred*
15//!   header= u16 version(=0x0504) : u16 header_len : header_len bytes of tagged fields
16//!   principal = u32 name_type : u32 num_components : counted-str realm : counted-str * num_components
17//!   cred    = principal client : principal server : keyblock :
18//!             u32 authtime : u32 starttime : u32 endtime : u32 renew_till :
19//!             u8  is_skey : u32 tktflags :
20//!             u32 num_addresses  : address*
21//!             u32 num_authdata   : authdata*
22//!             counted-bytes ticket : counted-bytes second_ticket
23//!   keyblock = u16 keytype : u16 etype(=0) : counted-bytes key
24//!   counted-str/bytes = u32 len : len bytes
25//! ```
26//!
27//! Multi-byte integers are big-endian (network order), matching MIT convention. This
28//! implementation is intentionally strict: an unrecognized version, a length that overflows
29//! the buffer, or a truncated field is a decoded [`CcacheError`], never a panic — safe to
30//! feed attacker-controlled bytes at the boundary.
31//!
32//! ## Example
33//!
34//! ```
35//! use ccache_io::Ccache;
36//! # let bytes: Vec<u8> = ccache_io::tests_only::sample_ccache_bytes();
37//! let cc = Ccache::parse(&bytes).unwrap();
38//! for c in &cc.credentials {
39//!     println!(
40//!         "{} → {}  (endtime={})",
41//!         c.client.canonical(),
42//!         c.server.canonical(),
43//!         c.endtime,
44//!     );
45//! }
46//! let round = cc.to_bytes();
47//! assert_eq!(round, bytes);
48//! ```
49
50#![deny(unsafe_code)]
51#![warn(missing_docs)]
52#![doc(html_root_url = "https://docs.rs/ccache-io/0.1.0")]
53
54use thiserror::Error;
55
56/// v4 file magic (`0x0504`). v3 (`0x0503`) is little-endian and predates 2005; v0.1 does
57/// not accept it — a wider `Version` enum can be added in v0.2 without a break because of
58/// [`CcacheError`]'s `#[non_exhaustive]`.
59pub const V4_MAGIC: u16 = 0x0504;
60
61/// MIT `KRB5_NT_PRINCIPAL` (1) — a client account principal.
62pub const NT_PRINCIPAL: u32 = 1;
63/// MIT `KRB5_NT_SRV_INST` (2) — the standard shape for `krbtgt`, `HOST/…`, service SPNs.
64pub const NT_SRV_INST: u32 = 2;
65
66/// Every fatal shape/length problem this crate produces. Marked `#[non_exhaustive]` so new
67/// diagnostics land as patch bumps rather than breaking downstream `match` blocks.
68#[non_exhaustive]
69#[derive(Debug, Error, PartialEq, Eq)]
70pub enum CcacheError {
71    /// The file header did not start with a supported version tag.
72    #[error("unsupported ccache version {found:#06x} (expected {expected:#06x})")]
73    UnsupportedVersion {
74        /// The u16 we actually read.
75        found: u16,
76        /// The version this build accepts (currently `0x0504`).
77        expected: u16,
78    },
79    /// A length field would run past the end of the buffer — the file is truncated or the
80    /// declared count is hostile.
81    #[error("truncated input: need {need} bytes at offset {at}, have {remaining}")]
82    Truncated {
83        /// Bytes the field claimed to need.
84        need: usize,
85        /// Byte offset the field started at.
86        at: usize,
87        /// Bytes actually left in the buffer at that offset.
88        remaining: usize,
89    },
90    /// A component count on a principal exceeded the sane cap. MIT's own `krb5.h` limits
91    /// this in practice; hostile input tries to force a giant `Vec::with_capacity`.
92    #[error("component count {count} at offset {at} exceeds sane cap ({cap})")]
93    TooManyComponents {
94        /// Declared count.
95        count: u32,
96        /// Byte offset it was read at.
97        at: usize,
98        /// The refuse-above threshold.
99        cap: u32,
100    },
101    /// The variable-length field decoded as valid UTF-16 or ASCII but not as UTF-8 — MIT
102    /// ccache stores principal component names as bytes without an encoding tag, so a
103    /// non-UTF-8 realm typically means a corrupt file (or a file from a locale we don't
104    /// yet handle).
105    #[error("non-UTF-8 principal string at offset {at}: {source}")]
106    Utf8 {
107        /// Byte offset the string started at.
108        at: usize,
109        /// Underlying UTF-8 error.
110        #[source]
111        source: std::str::Utf8Error,
112    },
113}
114
115/// A Kerberos principal — realm + one or more name components (`user`, `host/dc01`,
116/// `krbtgt/REALM`). The `name_type` distinguishes user principals from services.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct Principal {
119    /// The realm (e.g. `TESTLAB.LOCAL`). Case-sensitive; MIT convention is uppercase.
120    pub realm: String,
121    /// `NT_PRINCIPAL` (1), `NT_SRV_INST` (2), or another `KRB5_NT_*` constant.
122    pub name_type: u32,
123    /// Name components — one for a user (`["alice"]`), two for a service (`["HOST","dc01"]`),
124    /// two for `krbtgt` (`["krbtgt","REALM"]`).
125    pub components: Vec<String>,
126}
127
128impl Principal {
129    /// Render as MIT canonical form: `comp1/comp2/…@REALM` — the shape `klist` prints.
130    pub fn canonical(&self) -> String {
131        format!("{}@{}", self.components.join("/"), self.realm)
132    }
133}
134
135/// Symmetric key material for the credential — session key for a TGT, service key for a
136/// ticket. MIT stores an `etype` alongside the keytype for historical reasons; it is
137/// always zero in v4 files and mirrored back on write.
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct KeyBlock {
140    /// Kerberos encryption type — 17 (`AES128-CTS-HMAC-SHA1-96`), 18 (`AES256-CTS-HMAC-SHA1-96`),
141    /// 23 (`RC4-HMAC`), … — one of the `ETYPE_*` constants in `krb5.h`.
142    pub keytype: u16,
143    /// Raw key bytes, length determined by `keytype` (16 for AES128 / RC4, 32 for AES256).
144    pub key: Vec<u8>,
145}
146
147/// A network address the ticket is bound to (rarely populated in modern deployments).
148/// v0.1 keeps the raw wire triple so a round-trip is byte-exact even for exotic values.
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub struct Address {
151    /// MIT `ADDRTYPE_*` — 2 for IPv4, 24 for IPv6, etc.
152    pub addr_type: u16,
153    /// Raw address bytes as stored in the file.
154    pub data: Vec<u8>,
155}
156
157/// An `AuthorizationData` entry (RFC 4120 §5.2.6) — the shape the KDC uses to attach a
158/// Windows PAC to a ticket. v0.1 exposes the raw ASN.1 blob for byte-exact round-trip.
159#[derive(Clone, Debug, PartialEq, Eq)]
160pub struct AuthData {
161    /// MIT `KRB5_AUTHDATA_*` — 1 for `IF-RELEVANT`, 128 for `WIN2K-PAC`.
162    pub ad_type: u16,
163    /// The DER-encoded AuthorizationData contents.
164    pub data: Vec<u8>,
165}
166
167/// One cached credential — client, server, key, times, and the encrypted ticket blob.
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub struct Credential {
170    /// The principal the credential is issued for.
171    pub client: Principal,
172    /// The service the ticket authenticates to (`krbtgt/REALM@REALM` for a TGT).
173    pub server: Principal,
174    /// Session or service key.
175    pub key: KeyBlock,
176    /// Seconds since Unix epoch when the KDC issued the ticket.
177    pub authtime: u32,
178    /// Earliest use time (usually equal to `authtime`).
179    pub starttime: u32,
180    /// Ticket expiry.
181    pub endtime: u32,
182    /// Absolute renewal deadline (0 if non-renewable).
183    pub renew_till: u32,
184    /// `true` when this record stores a raw session key rather than a ticket — set for
185    /// TGT-holding cache entries; false for service tickets.
186    pub is_skey: bool,
187    /// The 32-bit MIT `TicketFlags` bitmask.
188    pub tktflags: u32,
189    /// Address restrictions on the ticket (empty in modern deployments).
190    pub addresses: Vec<Address>,
191    /// Authorization data attached to the ticket (Windows PAC lives here).
192    pub authdata: Vec<AuthData>,
193    /// The encrypted ticket, opaque as far as ccache is concerned — DER-encoded MIT
194    /// `Ticket` (RFC 4120 §5.3), the exact bytes handed to `AP-REQ`.
195    pub ticket: Vec<u8>,
196    /// The "second ticket" slot, used by `U2U` and `enc-tkt-in-skey`; empty for a plain TGT.
197    pub second_ticket: Vec<u8>,
198}
199
200/// A parsed ccache file — a default principal and every credential the KDC issued it.
201#[derive(Clone, Debug, PartialEq, Eq)]
202pub struct Ccache {
203    /// File-header tagged fields, exactly as read — v0.1 preserves them opaquely so
204    /// round-tripping doesn't disturb DConf / DeltaTime tags callers may not understand.
205    pub header: Vec<u8>,
206    /// The default principal — the identity `klist` labels the cache with.
207    pub primary: Principal,
208    /// Every credential in the cache, in file order (the order MIT tools rely on for
209    /// "most recently added" selection).
210    pub credentials: Vec<Credential>,
211}
212
213/// Refuse a principal that claims more than this many components — MIT's own tools
214/// tighten to 100-ish, we allow a generous cap that still stops a `u32::MAX` allocation.
215const MAX_COMPONENTS: u32 = 1024;
216/// The default header block emitted by MIT `krb5` ≥ 1.4 — one 12-byte `DeltaTime` tag
217/// with all zeros, matching every current-generation `kinit`.
218const DEFAULT_HEADER: &[u8] = &[
219    0x00, 0x01, // tag = DeltaTime
220    0x00, 0x08, // len = 8
221    0, 0, 0, 0, 0, 0, 0, 0, // 8 bytes of zeroed DeltaTime data
222];
223
224impl Ccache {
225    /// Parse the on-disk v4 format. Returns [`CcacheError::UnsupportedVersion`] on any
226    /// magic other than `0x0504` and [`CcacheError::Truncated`] on any length that would
227    /// run past the buffer.
228    pub fn parse(bytes: &[u8]) -> Result<Self, CcacheError> {
229        let mut r = Reader::new(bytes);
230        let version = r.u16()?;
231        if version != V4_MAGIC {
232            return Err(CcacheError::UnsupportedVersion {
233                found: version,
234                expected: V4_MAGIC,
235            });
236        }
237        let header_len = r.u16()? as usize;
238        let header = r.take(header_len)?.to_vec();
239        let primary = read_principal(&mut r)?;
240        let mut credentials = Vec::new();
241        while r.remaining() > 0 {
242            credentials.push(read_credential(&mut r)?);
243        }
244        Ok(Ccache {
245            header,
246            primary,
247            credentials,
248        })
249    }
250
251    /// Emit the on-disk v4 format. `parse(&cc.to_bytes()) == Ok(cc)` for every legal cache.
252    pub fn to_bytes(&self) -> Vec<u8> {
253        let mut w = Writer::new();
254        w.u16(V4_MAGIC);
255        w.u16(self.header.len() as u16);
256        w.bytes(&self.header);
257        write_principal(&mut w, &self.primary);
258        for c in &self.credentials {
259            write_credential(&mut w, c);
260        }
261        w.take()
262    }
263
264    /// Build an empty cache with the standard MIT header block — the shape `kinit`
265    /// produces on a brand-new file. Callers push credentials, then `to_bytes()`.
266    pub fn new(primary: Principal) -> Self {
267        Ccache {
268            header: DEFAULT_HEADER.to_vec(),
269            primary,
270            credentials: Vec::new(),
271        }
272    }
273}
274
275// ─── wire helpers ───────────────────────────────────────────────────────────
276
277struct Reader<'a> {
278    b: &'a [u8],
279    pos: usize,
280}
281
282impl<'a> Reader<'a> {
283    fn new(b: &'a [u8]) -> Self {
284        Reader { b, pos: 0 }
285    }
286    fn remaining(&self) -> usize {
287        self.b.len() - self.pos
288    }
289    fn take(&mut self, n: usize) -> Result<&'a [u8], CcacheError> {
290        if n > self.remaining() {
291            return Err(CcacheError::Truncated {
292                need: n,
293                at: self.pos,
294                remaining: self.remaining(),
295            });
296        }
297        let slice = &self.b[self.pos..self.pos + n];
298        self.pos += n;
299        Ok(slice)
300    }
301    fn u16(&mut self) -> Result<u16, CcacheError> {
302        let b = self.take(2)?;
303        Ok(u16::from_be_bytes([b[0], b[1]]))
304    }
305    fn u32(&mut self) -> Result<u32, CcacheError> {
306        let b = self.take(4)?;
307        Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
308    }
309    fn u8(&mut self) -> Result<u8, CcacheError> {
310        Ok(self.take(1)?[0])
311    }
312    fn counted(&mut self) -> Result<&'a [u8], CcacheError> {
313        let n = self.u32()? as usize;
314        self.take(n)
315    }
316    fn counted_str(&mut self) -> Result<String, CcacheError> {
317        let at = self.pos;
318        let bytes = self.counted()?;
319        std::str::from_utf8(bytes)
320            .map(str::to_string)
321            .map_err(|source| CcacheError::Utf8 { at, source })
322    }
323}
324
325struct Writer(Vec<u8>);
326
327impl Writer {
328    fn new() -> Self {
329        Writer(Vec::with_capacity(512))
330    }
331    fn take(self) -> Vec<u8> {
332        self.0
333    }
334    fn u16(&mut self, v: u16) {
335        self.0.extend_from_slice(&v.to_be_bytes());
336    }
337    fn u32(&mut self, v: u32) {
338        self.0.extend_from_slice(&v.to_be_bytes());
339    }
340    fn u8(&mut self, v: u8) {
341        self.0.push(v);
342    }
343    fn bytes(&mut self, b: &[u8]) {
344        self.0.extend_from_slice(b);
345    }
346    fn counted(&mut self, b: &[u8]) {
347        self.u32(b.len() as u32);
348        self.bytes(b);
349    }
350}
351
352fn read_principal(r: &mut Reader) -> Result<Principal, CcacheError> {
353    let at = r.pos;
354    let name_type = r.u32()?;
355    let num = r.u32()?;
356    if num > MAX_COMPONENTS {
357        return Err(CcacheError::TooManyComponents {
358            count: num,
359            at,
360            cap: MAX_COMPONENTS,
361        });
362    }
363    let realm = r.counted_str()?;
364    let mut components = Vec::with_capacity(num as usize);
365    for _ in 0..num {
366        components.push(r.counted_str()?);
367    }
368    Ok(Principal {
369        realm,
370        name_type,
371        components,
372    })
373}
374
375fn write_principal(w: &mut Writer, p: &Principal) {
376    w.u32(p.name_type);
377    w.u32(p.components.len() as u32);
378    w.counted(p.realm.as_bytes());
379    for c in &p.components {
380        w.counted(c.as_bytes());
381    }
382}
383
384fn read_credential(r: &mut Reader) -> Result<Credential, CcacheError> {
385    let client = read_principal(r)?;
386    let server = read_principal(r)?;
387    let keytype = r.u16()?;
388    let _etype_unused = r.u16()?;
389    let key_bytes = r.counted()?.to_vec();
390    let authtime = r.u32()?;
391    let starttime = r.u32()?;
392    let endtime = r.u32()?;
393    let renew_till = r.u32()?;
394    let is_skey = r.u8()? != 0;
395    let tktflags = r.u32()?;
396    let num_addr = r.u32()? as usize;
397    if num_addr > MAX_COMPONENTS as usize {
398        return Err(CcacheError::TooManyComponents {
399            count: num_addr as u32,
400            at: r.pos,
401            cap: MAX_COMPONENTS,
402        });
403    }
404    let mut addresses = Vec::with_capacity(num_addr);
405    for _ in 0..num_addr {
406        let addr_type = r.u16()?;
407        let data = r.counted()?.to_vec();
408        addresses.push(Address { addr_type, data });
409    }
410    let num_ad = r.u32()? as usize;
411    if num_ad > MAX_COMPONENTS as usize {
412        return Err(CcacheError::TooManyComponents {
413            count: num_ad as u32,
414            at: r.pos,
415            cap: MAX_COMPONENTS,
416        });
417    }
418    let mut authdata = Vec::with_capacity(num_ad);
419    for _ in 0..num_ad {
420        let ad_type = r.u16()?;
421        let data = r.counted()?.to_vec();
422        authdata.push(AuthData { ad_type, data });
423    }
424    let ticket = r.counted()?.to_vec();
425    let second_ticket = r.counted()?.to_vec();
426    Ok(Credential {
427        client,
428        server,
429        key: KeyBlock {
430            keytype,
431            key: key_bytes,
432        },
433        authtime,
434        starttime,
435        endtime,
436        renew_till,
437        is_skey,
438        tktflags,
439        addresses,
440        authdata,
441        ticket,
442        second_ticket,
443    })
444}
445
446fn write_credential(w: &mut Writer, c: &Credential) {
447    write_principal(w, &c.client);
448    write_principal(w, &c.server);
449    w.u16(c.key.keytype);
450    w.u16(0); // etype field, always zero in v4
451    w.counted(&c.key.key);
452    w.u32(c.authtime);
453    w.u32(c.starttime);
454    w.u32(c.endtime);
455    w.u32(c.renew_till);
456    w.u8(if c.is_skey { 1 } else { 0 });
457    w.u32(c.tktflags);
458    w.u32(c.addresses.len() as u32);
459    for a in &c.addresses {
460        w.u16(a.addr_type);
461        w.counted(&a.data);
462    }
463    w.u32(c.authdata.len() as u32);
464    for a in &c.authdata {
465        w.u16(a.ad_type);
466        w.counted(&a.data);
467    }
468    w.counted(&c.ticket);
469    w.counted(&c.second_ticket);
470}
471
472/// Test-only helpers reachable from doctests. Not part of the stable public API.
473#[doc(hidden)]
474pub mod tests_only {
475    use super::*;
476
477    /// A hand-crafted minimal ccache — one principal `alice@TESTLAB.LOCAL`, one TGT for
478    /// `krbtgt/TESTLAB.LOCAL@TESTLAB.LOCAL` with an AES256 session key and an opaque
479    /// ticket blob. Sufficient for the doctest and the round-trip test.
480    pub fn sample_ccache_bytes() -> Vec<u8> {
481        let cc = Ccache {
482            header: DEFAULT_HEADER.to_vec(),
483            primary: Principal {
484                realm: "TESTLAB.LOCAL".into(),
485                name_type: NT_PRINCIPAL,
486                components: vec!["alice".into()],
487            },
488            credentials: vec![Credential {
489                client: Principal {
490                    realm: "TESTLAB.LOCAL".into(),
491                    name_type: NT_PRINCIPAL,
492                    components: vec!["alice".into()],
493                },
494                server: Principal {
495                    realm: "TESTLAB.LOCAL".into(),
496                    name_type: NT_SRV_INST,
497                    components: vec!["krbtgt".into(), "TESTLAB.LOCAL".into()],
498                },
499                key: KeyBlock {
500                    keytype: 18, // AES256-CTS-HMAC-SHA1-96
501                    key: vec![0x11u8; 32],
502                },
503                authtime: 0x6600_0000,
504                starttime: 0x6600_0000,
505                endtime: 0x6600_A000,
506                renew_till: 0x6601_0000,
507                is_skey: false,
508                tktflags: 0x5010_0000, // FORWARDABLE | RENEWABLE | INITIAL
509                addresses: Vec::new(),
510                authdata: Vec::new(),
511                ticket: b"OPAQUE-DER-TICKET-BYTES".to_vec(),
512                second_ticket: Vec::new(),
513            }],
514        };
515        cc.to_bytes()
516    }
517}
518
519// ─── tests ──────────────────────────────────────────────────────────────────
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    #[test]
526    fn header_magic_is_be_0504() {
527        let bytes = tests_only::sample_ccache_bytes();
528        assert_eq!(&bytes[..2], &[0x05, 0x04]);
529    }
530
531    #[test]
532    fn roundtrip_byte_exact() {
533        let bytes = tests_only::sample_ccache_bytes();
534        let parsed = Ccache::parse(&bytes).expect("parse");
535        assert_eq!(parsed.primary.canonical(), "alice@TESTLAB.LOCAL");
536        assert_eq!(parsed.credentials.len(), 1);
537        let cred = &parsed.credentials[0];
538        assert_eq!(
539            cred.server.canonical(),
540            "krbtgt/TESTLAB.LOCAL@TESTLAB.LOCAL"
541        );
542        assert_eq!(cred.key.keytype, 18);
543        assert_eq!(cred.key.key.len(), 32);
544        assert_eq!(cred.tktflags, 0x5010_0000);
545        assert_eq!(&cred.ticket, b"OPAQUE-DER-TICKET-BYTES");
546        let re = parsed.to_bytes();
547        assert_eq!(re, bytes, "round-trip must be byte-identical");
548    }
549
550    #[test]
551    fn rejects_wrong_magic() {
552        let mut bytes = tests_only::sample_ccache_bytes();
553        bytes[0] = 0x05;
554        bytes[1] = 0x03; // v3 magic — unsupported in v0.1
555        let err = Ccache::parse(&bytes).unwrap_err();
556        assert_eq!(
557            err,
558            CcacheError::UnsupportedVersion {
559                found: 0x0503,
560                expected: V4_MAGIC
561            }
562        );
563    }
564
565    #[test]
566    fn rejects_truncated_body() {
567        let bytes = tests_only::sample_ccache_bytes();
568        let short = &bytes[..bytes.len() - 5];
569        let err = Ccache::parse(short).unwrap_err();
570        assert!(matches!(err, CcacheError::Truncated { .. }));
571    }
572
573    #[test]
574    fn rejects_hostile_component_count() {
575        // Craft: valid header + principal with num_components = u32::MAX. Must not
576        // allocate `Vec::with_capacity(u32::MAX)` — must reject bounded-alloc-style.
577        let mut w = Writer::new();
578        w.u16(V4_MAGIC);
579        w.u16(DEFAULT_HEADER.len() as u16);
580        w.bytes(DEFAULT_HEADER);
581        w.u32(NT_PRINCIPAL); // name_type
582        w.u32(u32::MAX); // hostile num_components
583        w.counted(b"REALM");
584        let err = Ccache::parse(&w.take()).unwrap_err();
585        assert!(matches!(
586            err,
587            CcacheError::TooManyComponents {
588                count: u32::MAX,
589                ..
590            }
591        ));
592    }
593
594    #[test]
595    fn multi_credential_cache_roundtrips() {
596        let mut cc = Ccache::new(Principal {
597            realm: "CORP.LOCAL".into(),
598            name_type: NT_PRINCIPAL,
599            components: vec!["bob".into()],
600        });
601        for i in 0..5u32 {
602            cc.credentials.push(Credential {
603                client: cc.primary.clone(),
604                server: Principal {
605                    realm: "CORP.LOCAL".into(),
606                    name_type: NT_SRV_INST,
607                    components: vec!["HOST".into(), format!("srv{i}.corp.local")],
608                },
609                key: KeyBlock {
610                    keytype: 17,
611                    key: vec![i as u8; 16],
612                },
613                authtime: 100 + i,
614                starttime: 100 + i,
615                endtime: 200 + i,
616                renew_till: 0,
617                is_skey: i.is_multiple_of(2),
618                tktflags: 0x40000000,
619                addresses: Vec::new(),
620                authdata: Vec::new(),
621                ticket: vec![i as u8; 32],
622                second_ticket: Vec::new(),
623            });
624        }
625        let bytes = cc.to_bytes();
626        let parsed = Ccache::parse(&bytes).unwrap();
627        assert_eq!(parsed.credentials.len(), 5);
628        assert_eq!(parsed.to_bytes(), bytes);
629    }
630
631    #[test]
632    fn utf8_realm_error_carries_offset() {
633        // Craft a principal whose realm is bytes 0xFF 0xFE (invalid UTF-8 — a UTF-16 BOM).
634        let mut w = Writer::new();
635        w.u16(V4_MAGIC);
636        w.u16(0);
637        w.u32(NT_PRINCIPAL);
638        w.u32(0); // no components
639        w.counted(&[0xFF, 0xFE]); // realm bytes
640        let err = Ccache::parse(&w.take()).unwrap_err();
641        assert!(matches!(err, CcacheError::Utf8 { .. }));
642    }
643}