Skip to main content

kizz_store/
identity.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The cache identity: the stamp of the machine and the user that a cache belongs to.
6//!
7//! The cache is not portable. When the store creates the database it stamps it with
8//! the [`CacheIdentity`] of the process that creates it: the host name, the effective
9//! user and group, the supplementary groups, the umask, the machine architecture, and
10//! the CPU model. Every later [`Store::open`](crate::Store::open) gathers the current
11//! identity and compares it with the stamp, value by value, and refuses a cache whose
12//! stamp differs, naming each [`IdentityDifference`].
13
14use std::{collections::BTreeSet, ffi::CStr, fmt, fs, mem::MaybeUninit};
15
16use minicbor::{Decode, Encode};
17
18use crate::{
19    lock::host_name,
20    records::{Family, Record, RecordKey},
21};
22
23/// The file whose `Umask` line holds the umask of this process.
24const STATUS_FILE: &str = "/proc/self/status";
25
26/// The file whose `model name` lines name the CPUs of the machine.
27const CPU_INFO_FILE: &str = "/proc/cpuinfo";
28
29/// The key of the cache identity, the stamp of the database, in the `meta/` family.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct IdentityKey;
32
33impl IdentityKey {
34    /// The bytes of the key after the family prefix.
35    const BYTES: &'static [u8] = b"identity";
36}
37
38impl RecordKey for IdentityKey {
39    fn encode_key(
40        &self,
41        out: &mut Vec<u8>,
42    ) {
43        out.extend_from_slice(Self::BYTES);
44    }
45
46    fn decode_key(bytes: &[u8]) -> Option<Self> {
47        (bytes == Self::BYTES).then_some(Self)
48    }
49}
50
51/// The identity of the machine and the user that a cache belongs to, which the store
52/// writes when it creates the database and compares on every later open.
53#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
54pub struct CacheIdentity {
55    /// The host name of the machine.
56    #[n(0)]
57    pub host: String,
58    /// The effective user ID.
59    #[n(1)]
60    pub user: u32,
61    /// The effective group ID.
62    #[n(2)]
63    pub group: u32,
64    /// The supplementary group IDs, sorted and distinct.
65    #[n(3)]
66    pub groups: Vec<u32>,
67    /// The umask, from the `Umask` line of `/proc/self/status`, or `None` when the
68    /// file has no such line.
69    #[n(4)]
70    pub umask: Option<u32>,
71    /// The machine architecture, the `machine` field of `uname`.
72    #[n(5)]
73    pub machine: String,
74    /// The distinct `model name` values of `/proc/cpuinfo`, sorted; empty when it has
75    /// none.
76    #[n(6)]
77    pub cpu_models: Vec<String>,
78}
79
80impl Record for CacheIdentity {
81    type Key = IdentityKey;
82
83    const FAMILY: Family = Family::Meta;
84}
85
86impl CacheIdentity {
87    /// The identity of this process on this machine.
88    #[must_use]
89    pub fn current() -> Self {
90        Self {
91            host: host_name(),
92            // SAFETY: `geteuid` has no preconditions and cannot fail.
93            user: unsafe { libc::geteuid() },
94            // SAFETY: `getegid` has no preconditions and cannot fail.
95            group: unsafe { libc::getegid() },
96            groups: supplementary_groups(),
97            umask: fs::read_to_string(STATUS_FILE)
98                .ok()
99                .and_then(|status| umask_of_status(&status)),
100            machine: machine(),
101            cpu_models: fs::read_to_string(CPU_INFO_FILE)
102                .map_or_default(|info| cpu_models_of_info(&info)),
103        }
104    }
105
106    /// Each value of this identity, the stored one, that differs from `current`, in
107    /// the order of [`IdentityPart::ALL`]; empty when the two are the same.
108    ///
109    /// The values are compared as the record holds them, field by field, never by
110    /// the text that messages show: two lists of CPU models can show the same text
111    /// and still differ.
112    #[must_use]
113    pub fn differences(
114        &self,
115        current: &Self,
116    ) -> Vec<IdentityDifference> {
117        IdentityPart::ALL
118            .into_iter()
119            .filter(|part| part.differs(self, current))
120            .map(|part| {
121                IdentityDifference {
122                    part,
123                    stored: part.value(self),
124                    current: part.value(current),
125                }
126            })
127            .collect()
128    }
129}
130
131/// One value of a [`CacheIdentity`].
132#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
133pub enum IdentityPart {
134    /// The host name.
135    Host,
136    /// The effective user ID.
137    User,
138    /// The effective group ID.
139    Group,
140    /// The supplementary groups.
141    Groups,
142    /// The umask.
143    Umask,
144    /// The machine architecture.
145    Machine,
146    /// The CPU model.
147    CpuModel,
148}
149
150impl IdentityPart {
151    /// Every value, in the order of the fields of [`CacheIdentity`].
152    pub const ALL: [Self; 7] = [
153        Self::Host,
154        Self::User,
155        Self::Group,
156        Self::Groups,
157        Self::Umask,
158        Self::Machine,
159        Self::CpuModel,
160    ];
161
162    /// The name of the value in messages.
163    #[must_use]
164    pub const fn name(self) -> &'static str {
165        match self {
166            Self::Host => "host name",
167            Self::User => "effective user ID",
168            Self::Group => "effective group ID",
169            Self::Groups => "supplementary groups",
170            Self::Umask => "umask",
171            Self::Machine => "machine architecture",
172            Self::CpuModel => "CPU model",
173        }
174    }
175
176    /// Whether this value of `stored` differs from the same value of `current`,
177    /// compared as the fields hold them, not as messages show them.
178    #[must_use]
179    pub fn differs(
180        self,
181        stored: &CacheIdentity,
182        current: &CacheIdentity,
183    ) -> bool {
184        match self {
185            Self::Host => stored.host != current.host,
186            Self::User => stored.user != current.user,
187            Self::Group => stored.group != current.group,
188            Self::Groups => stored.groups != current.groups,
189            Self::Umask => stored.umask != current.umask,
190            Self::Machine => stored.machine != current.machine,
191            Self::CpuModel => stored.cpu_models != current.cpu_models,
192        }
193    }
194
195    /// This value of `identity`, as messages show it.
196    ///
197    /// Different values always show different text: names are quoted, with every
198    /// quote, backslash and control character escaped; group IDs and CPU models are
199    /// bracketed lists, so an empty list, a list of one empty name, and a list of one
200    /// name that holds a separator all show apart; and the umask is four octal digits,
201    /// or `unknown` when the status file had no `Umask` line.
202    #[must_use]
203    pub fn value(
204        self,
205        identity: &CacheIdentity,
206    ) -> String {
207        match self {
208            Self::Host => quoted(&identity.host),
209            Self::User => identity.user.to_string(),
210            Self::Group => identity.group.to_string(),
211            Self::Groups => bracketed(identity.groups.iter().map(u32::to_string)),
212            Self::Umask => {
213                identity
214                    .umask
215                    .map_or_else(|| String::from("unknown"), |umask| format!("{umask:04o}"))
216            },
217            Self::Machine => quoted(&identity.machine),
218            Self::CpuModel => bracketed(identity.cpu_models.iter().map(String::as_str).map(quoted)),
219        }
220    }
221}
222
223/// `text` between double quotes, with each double quote and backslash escaped by a
224/// backslash, and each control character written as `\u{…}` with its hexadecimal
225/// code, so that two different texts never show the same.
226fn quoted(text: &str) -> String {
227    let mut shown = String::from('"');
228    for character in text.chars() {
229        match character {
230            '"' | '\\' => {
231                shown.push('\\');
232                shown.push(character);
233            },
234            control if control.is_control() => shown.extend(control.escape_unicode()),
235            other => shown.push(other),
236        }
237    }
238    shown.push('"');
239    shown
240}
241
242/// `items` separated by commas between square brackets, `[]` when there are none.
243fn bracketed(items: impl Iterator<Item = String>) -> String {
244    format!("[{}]", items.collect::<Vec<_>>().join(", "))
245}
246
247impl fmt::Display for IdentityPart {
248    fn fmt(
249        &self,
250        f: &mut fmt::Formatter<'_>,
251    ) -> fmt::Result {
252        f.write_str(self.name())
253    }
254}
255
256/// A value of the cache identity that differs: as the cache stores it, and as this
257/// process has it.
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct IdentityDifference {
260    /// The value that differs.
261    pub part: IdentityPart,
262    /// The value that the cache stores, as [`IdentityPart::value`] shows it.
263    pub stored: String,
264    /// The current value, as [`IdentityPart::value`] shows it.
265    pub current: String,
266}
267
268impl fmt::Display for IdentityDifference {
269    fn fmt(
270        &self,
271        f: &mut fmt::Formatter<'_>,
272    ) -> fmt::Result {
273        write!(
274            f,
275            "{}: {} in the cache, {} now",
276            self.part, self.stored, self.current
277        )
278    }
279}
280
281/// Every difference of `differences`, separated by semicolons.
282#[must_use]
283pub fn identity_differences_text(differences: &[IdentityDifference]) -> String {
284    differences
285        .iter()
286        .map(ToString::to_string)
287        .collect::<Vec<_>>()
288        .join("; ")
289}
290
291/// The supplementary group IDs of this process, sorted and distinct; empty when they
292/// cannot be read, or when the buffer for them cannot be allocated: it is reserved
293/// with `Vec::try_reserve_exact`, where `vec![0; len]` panics on a length that
294/// overflows ("Kizz never panics").
295fn supplementary_groups() -> Vec<u32> {
296    // SAFETY: a size of zero asks only for the number of groups, and writes nothing.
297    let count = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
298    let Ok(len) = usize::try_from(count) else {
299        return Vec::new();
300    };
301    let mut groups: Vec<libc::gid_t> = Vec::new();
302    if groups.try_reserve_exact(len).is_err() {
303        return Vec::new();
304    }
305    groups.resize(len, 0);
306    // SAFETY: the buffer holds `count` group IDs, the size passed.
307    let filled = unsafe { libc::getgroups(count, groups.as_mut_ptr()) };
308    let Ok(filled) = usize::try_from(filled) else {
309        return Vec::new();
310    };
311    groups.truncate(filled);
312    groups.sort_unstable();
313    groups.dedup();
314    groups
315}
316
317/// The machine architecture from `uname`, or `(unknown)` when it cannot be read.
318fn machine() -> String {
319    let mut names = MaybeUninit::<libc::utsname>::uninit();
320    // SAFETY: the pointer is valid for writing a `utsname`.
321    if unsafe { libc::uname(names.as_mut_ptr()) } != 0 {
322        return String::from("(unknown)");
323    }
324    // SAFETY: `uname` succeeded, so it initialized `names`.
325    let names = unsafe { names.assume_init() };
326    // SAFETY: `uname` ends every field with a zero byte within the field.
327    unsafe { CStr::from_ptr(names.machine.as_ptr()) }
328        .to_string_lossy()
329        .into_owned()
330}
331
332/// The umask of the `Umask` line of `status`, the text of `/proc/self/status`, or
333/// `None` when it has no such line or its value is not octal.
334fn umask_of_status(status: &str) -> Option<u32> {
335    status.lines().find_map(|line| {
336        let value = line.strip_prefix("Umask:")?;
337        u32::from_str_radix(value.trim(), 8).ok()
338    })
339}
340
341/// The distinct `model name` values of `info`, the text of `/proc/cpuinfo`, sorted.
342fn cpu_models_of_info(info: &str) -> Vec<String> {
343    info.lines()
344        .filter_map(|line| {
345            let (key, value) = line.split_once(':')?;
346            (key.trim() == "model name").then(|| value.trim().to_owned())
347        })
348        .collect::<BTreeSet<_>>()
349        .into_iter()
350        .collect()
351}
352
353/// Two lists of CPU models that the joined text of earlier versions showed alike, with
354/// the text that messages show for each now.
355#[cfg(test)]
356pub(crate) struct CpuModelCollision {
357    /// The list that the cache stores.
358    pub(crate) stored: Vec<String>,
359    /// The text that messages show for `stored`.
360    pub(crate) stored_text: &'static str,
361    /// The current list.
362    pub(crate) current: Vec<String>,
363    /// The text that messages show for `current`.
364    pub(crate) current_text: &'static str,
365}
366
367/// The CPU-model lists that the joined text of earlier versions showed alike: an
368/// empty list, a list of one empty name and a list of the name `none`, which all
369/// showed `none`; a name that holds the separator `; `, which showed as two names; and
370/// a name that holds quotes and a comma, which a list without escapes would show as
371/// two names.
372#[cfg(test)]
373pub(crate) fn colliding_cpu_models() -> Vec<CpuModelCollision> {
374    let collision = |stored: &[&str],
375                     stored_text: &'static str,
376                     current: &[&str],
377                     current_text: &'static str| {
378        CpuModelCollision {
379            stored: stored.iter().copied().map(String::from).collect(),
380            stored_text,
381            current: current.iter().copied().map(String::from).collect(),
382            current_text,
383        }
384    };
385    vec![
386        collision(&[], "[]", &["none"], r#"["none"]"#),
387        collision(&[], "[]", &[""], r#"[""]"#),
388        collision(&[""], r#"[""]"#, &["none"], r#"["none"]"#),
389        collision(&["A; B"], r#"["A; B"]"#, &["A", "B"], r#"["A", "B"]"#),
390        collision(
391            &[r#"A", "B"#],
392            r#"["A\", \"B"]"#,
393            &["A", "B"],
394            r#"["A", "B"]"#,
395        ),
396    ]
397}
398
399/// Unit tests for parsing the identity and describing its differences.
400#[cfg(test)]
401#[allow(
402    clippy::disallowed_macros,
403    clippy::disallowed_methods,
404    reason = "test code: the tests assert and lock"
405)]
406mod tests {
407    use super::*;
408
409    /// An identity whose values are all made up.
410    fn identity() -> CacheIdentity {
411        CacheIdentity {
412            host: String::from("builder"),
413            user: 1000,
414            group: 100,
415            groups: vec![10, 100],
416            umask: Some(0o022),
417            machine: String::from("x86_64"),
418            cpu_models: vec![String::from("Example CPU")],
419        }
420    }
421
422    /// The umask is the octal value of the `Umask` line of `/proc/self/status`, and
423    /// unknown when the line is missing or its value is not octal.
424    #[test]
425    fn the_umask_is_the_octal_value_of_its_status_line() {
426        let status = "Name:\tkizz\nUmask:\t0027\nState:\tR (running)\n";
427        assert_eq!(umask_of_status(status), Some(0o027));
428        assert_eq!(umask_of_status("Name:\tkizz\n"), None);
429        assert_eq!(umask_of_status("Umask:\t0089\n"), None);
430    }
431
432    /// The CPU models are the `model name` values of `/proc/cpuinfo`, sorted and
433    /// distinct, and none when it has no such line.
434    #[test]
435    fn cpu_models_are_the_sorted_distinct_model_names() {
436        let info = "processor\t: 0\nmodel name\t: Fast Core\nflags\t\t: fpu\n\nprocessor\t: \
437                    1\nmodel name\t: Efficient Core\n\nprocessor\t: 2\nmodel name\t: Fast Core\n";
438        assert_eq!(cpu_models_of_info(info), vec![
439            String::from("Efficient Core"),
440            String::from("Fast Core"),
441        ]);
442        assert_eq!(
443            cpu_models_of_info("processor\t: 0\nCPU part\t: 0xd0c\n"),
444            Vec::<String>::new()
445        );
446    }
447
448    /// An identity compared with itself has no differences.
449    #[test]
450    fn the_same_identity_has_no_differences() {
451        assert_eq!(identity().differences(&identity()), Vec::new());
452    }
453
454    /// Values that differ are compared field by field, not by the text that messages
455    /// show, and CPU-model lists that the old joined text showed alike differ in the
456    /// CPU model alone and now show different text, in the value and in the message;
457    /// each other field that changes alone differs alone as well.
458    #[test]
459    fn differences_compare_the_fields_not_their_text() {
460        for CpuModelCollision {
461            stored: stored_models,
462            stored_text,
463            current: current_models,
464            current_text,
465        } in colliding_cpu_models()
466        {
467            let stored = CacheIdentity {
468                cpu_models: stored_models,
469                ..identity()
470            };
471            let current = CacheIdentity {
472                cpu_models: current_models,
473                ..identity()
474            };
475            assert_eq!(IdentityPart::CpuModel.value(&stored), stored_text);
476            assert_eq!(IdentityPart::CpuModel.value(&current), current_text);
477            assert_ne!(stored_text, current_text);
478            let differences = stored.differences(&current);
479            assert_eq!(
480                differences,
481                vec![IdentityDifference {
482                    part: IdentityPart::CpuModel,
483                    stored: String::from(stored_text),
484                    current: String::from(current_text),
485                }],
486                "{stored:?} and {current:?}"
487            );
488            assert_eq!(
489                identity_differences_text(&differences),
490                format!("CPU model: {stored_text} in the cache, {current_text} now")
491            );
492            assert!(IdentityPart::CpuModel.differs(&stored, &current));
493            assert!(!IdentityPart::CpuModel.differs(&stored, &stored));
494        }
495        let changed = [
496            (IdentityPart::Host, CacheIdentity {
497                host: String::from("other-builder"),
498                ..identity()
499            }),
500            (IdentityPart::User, CacheIdentity {
501                user: 1001,
502                ..identity()
503            }),
504            (IdentityPart::Group, CacheIdentity {
505                group: 101,
506                ..identity()
507            }),
508            (IdentityPart::Groups, CacheIdentity {
509                groups: vec![10],
510                ..identity()
511            }),
512            (IdentityPart::Umask, CacheIdentity {
513                umask: None,
514                ..identity()
515            }),
516            (IdentityPart::Machine, CacheIdentity {
517                machine: String::from("other-architecture"),
518                ..identity()
519            }),
520            (IdentityPart::CpuModel, CacheIdentity {
521                cpu_models: Vec::new(),
522                ..identity()
523            }),
524        ];
525        for (part, other) in changed {
526            for candidate in IdentityPart::ALL {
527                assert_eq!(
528                    candidate.differs(&identity(), &other),
529                    candidate == part,
530                    "{candidate} when {part} changed"
531                );
532            }
533        }
534    }
535
536    /// Messages show each kind of value: names quoted, with quotes, backslashes and
537    /// control characters escaped; group IDs and CPU models as bracketed lists, `[]`
538    /// when empty; and the umask in octal, or unknown.
539    #[test]
540    fn values_show_every_case() {
541        let mut other = identity();
542        other.host = String::from("say \"hi\"\\\tthere\n");
543        other.groups.clear();
544        other.umask = None;
545        other.cpu_models = vec![String::from("A"), String::from("B")];
546        let differences = identity().differences(&other);
547        assert_eq!(
548            identity_differences_text(&differences),
549            concat!(
550                r#"host name: "builder" in the cache, "say \"hi\"\\\u{9}there\u{a}" now; "#,
551                "supplementary groups: [10, 100] in the cache, [] now; ",
552                "umask: 0022 in the cache, unknown now; ",
553                r#"CPU model: ["Example CPU"] in the cache, ["A", "B"] now"#,
554            )
555        );
556        assert_eq!(IdentityPart::User.value(&identity()), "1000");
557        assert_eq!(IdentityPart::Group.value(&identity()), "100");
558        assert_eq!(IdentityPart::Machine.value(&identity()), r#""x86_64""#);
559        assert_eq!(IdentityPart::Groups.value(&other), "[]");
560        other.groups = vec![0];
561        assert_eq!(IdentityPart::Groups.value(&other), "[0]");
562        other.umask = Some(0);
563        assert_eq!(IdentityPart::Umask.value(&other), "0000");
564        other.cpu_models.clear();
565        assert_eq!(IdentityPart::CpuModel.value(&other), "[]");
566    }
567
568    /// The identity record encodes the same bytes each time, as a definite-length
569    /// array of seven fields, and decodes back to itself, with or without values.
570    #[test]
571    fn the_identity_encodes_deterministically_and_round_trips() {
572        let mut unknown = identity();
573        unknown.groups.clear();
574        unknown.umask = None;
575        unknown.cpu_models.clear();
576        for record in [identity(), unknown] {
577            let first = minicbor::to_vec(&record).unwrap();
578            assert_eq!(minicbor::to_vec(&record).unwrap(), first);
579            assert_eq!(minicbor::decode::<CacheIdentity>(&first).unwrap(), record);
580            // A definite-length array of seven items, then the host name, `builder`,
581            // a text string of seven bytes.
582            assert_eq!(first.get(..2), Some(&[0x87, 0x67][..]));
583        }
584    }
585
586    /// The identity key is `identity` in the `meta/` family, and decodes only from
587    /// its own bytes.
588    #[test]
589    fn identity_keys_round_trip() {
590        let mut bytes = Vec::new();
591        IdentityKey.encode_key(&mut bytes);
592        assert_eq!(bytes, b"identity");
593        assert_eq!(IdentityKey::decode_key(&bytes), Some(IdentityKey));
594        assert_eq!(IdentityKey::decode_key(b"schema-version"), None);
595        assert_eq!(
596            crate::records::database_key::<CacheIdentity>(&IdentityKey),
597            b"meta/identity"
598        );
599    }
600}