brinkhaustools/licence/
hardware.rs

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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! Hardware profile: the identifiers a licence can be bound to.
//!
//! The operator chooses which identifiers a licence binds to; a licence names them
//! by type, label and a salted SHA-256, never by value (it travels by e-mail).
//!
//! **Containers — recommended: name each source.** A container sees neither the
//! host's machine-id nor its network cards. Mount exactly the files the licence
//! may bind to, read-only, and name them ([`ExplicitSource`],
//! [`HardwareProfile::collect_explicit`]), e.g.
//! `/etc/machine-id:/hw/machine-id:ro` and
//! `/sys/class/net/eth0/address:/hw/mac-eth0:ro` (a single file; Docker resolves
//! the symlink, and a wrong interface name stops the container from starting).
//! The container then sees these values and nothing else of the host.
//! `/proc/cpuinfo` is not namespaced and needs no mount.
//!
//! **Alternative: a host root** (default `/host`, [`HardwareSources`]): mount
//! `/etc/machine-id` and all of `/sys` under it — `/sys/class/net` alone dangles
//! ([`ProfileProblem::DanglingInterfaces`]). It discovers every physical network
//! card but exposes the whole of `/sys`; prefer named sources. Without either,
//! the collector refuses the container's own machine-id and veth MAC
//! ([`ProfileProblem::ContainerWithoutHostRoot`]): they identify the image, not
//! the hardware.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::codec::hex_encode;

/// Domain separator of the identifier hash; part of the wire format.
const HASH_DOMAIN: &str = "brinkhaus-licence-v1";

/// Default mount point of the host inside a container.
pub const DEFAULT_HOST_ROOT: &str = "/host";

/// Kind of a hardware identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IdentifierKind {
    /// Linux `/etc/machine-id`, Windows `MachineGuid` — the OS installation.
    MachineId,
    /// MAC address of one physical network interface (label = interface name).
    Mac,
    /// CPU serial from `/proc/cpuinfo` (ARM SoCs; x86 has none).
    CpuSerial,
    /// First line of a provisioned serial-number file (e.g. a Brinkhaus SN).
    SerialFile,
}

impl IdentifierKind {
    /// Wire name (`machineId`, `mac`, `cpuSerial`, `serialFile`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::MachineId => "machineId",
            Self::Mac => "mac",
            Self::CpuSerial => "cpuSerial",
            Self::SerialFile => "serialFile",
        }
    }

    /// Parse a wire name.
    pub fn parse(text: &str) -> Option<Self> {
        [
            Self::MachineId,
            Self::Mac,
            Self::CpuSerial,
            Self::SerialFile,
        ]
        .into_iter()
        .find(|k| k.as_str() == text)
    }

    /// Normalise a raw value; `None` if it is empty or a known placeholder.
    pub fn normalize(self, raw: &str) -> Option<String> {
        let raw = raw.trim();
        let value = match self {
            // Linux: 32 hex digits; Windows GUID with braces/dashes → same shape.
            Self::MachineId => raw
                .chars()
                .filter(|c| !matches!(c, '{' | '}' | '-'))
                .collect::<String>()
                .to_ascii_lowercase(),
            Self::Mac => {
                let octets: Vec<&str> = raw.split([':', '-']).collect();
                if octets.len() != 6
                    || octets
                        .iter()
                        .any(|o| o.len() != 2 || !o.chars().all(|c| c.is_ascii_hexdigit()))
                {
                    return None;
                }
                let mac = octets.join(":").to_ascii_lowercase();
                if mac == "00:00:00:00:00:00" || mac == "ff:ff:ff:ff:ff:ff" {
                    return None;
                }
                mac
            }
            Self::CpuSerial => raw.to_ascii_lowercase(),
            Self::SerialFile => raw.to_ascii_uppercase(),
        };
        if value.is_empty() || value.chars().all(|c| c == '0') {
            None
        } else {
            Some(value)
        }
    }
}

/// Salted hash of a normalised identifier value (lower-case hex).
pub fn identifier_hash(kind: IdentifierKind, normalized: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(HASH_DOMAIN.as_bytes());
    hasher.update([0]);
    hasher.update(kind.as_str().as_bytes());
    hasher.update([0]);
    hasher.update(normalized.as_bytes());
    hex_encode(&hasher.finalize())
}

/// One binding in a licence or request: kind, display label, hash.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
    #[serde(rename = "type")]
    pub kind: IdentifierKind,
    pub label: String,
    pub sha256: String,
}

/// One identifier found on this machine.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HardwareIdentifier {
    #[serde(rename = "type")]
    pub kind: IdentifierKind,
    /// Display label: interface name for MACs, the source path otherwise.
    pub label: String,
    /// Normalised value (shown to the operator, never sent to the FleetManager).
    pub value: String,
    pub sha256: String,
}

impl HardwareIdentifier {
    /// Build from a raw value; `None` if the value normalises to nothing.
    pub fn new(kind: IdentifierKind, label: impl Into<String>, raw: &str) -> Option<Self> {
        let value = kind.normalize(raw)?;
        Some(Self {
            kind,
            label: label.into(),
            sha256: identifier_hash(kind, &value),
            value,
        })
    }

    /// The binding a licence would carry for this identifier.
    pub fn binding(&self) -> Binding {
        Binding {
            kind: self.kind,
            label: self.label.clone(),
            sha256: self.sha256.clone(),
        }
    }
}

/// Why an identifier kind could not be collected.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "problem", rename_all = "camelCase")]
pub enum ProfileProblem {
    /// Running in a container without a host root: machine-id and MACs refused.
    ContainerWithoutHostRoot { expected: String },
    /// A source file or directory is missing or unreadable.
    #[serde(rename_all = "camelCase")]
    SourceUnreadable {
        kind: IdentifierKind,
        path: String,
        error: String,
    },
    /// Interface entries exist but point nowhere: only `class/net` was mounted.
    DanglingInterfaces { path: String },
    /// The interface directory is readable but holds no physical interface.
    NoPhysicalInterface { path: String },
    /// A platform query (registry, PowerShell) failed.
    #[serde(rename_all = "camelCase")]
    QueryFailed { kind: IdentifierKind, error: String },
    /// Running in a container, and no source is named
    /// ([`HardwareProfile::collect_explicit`] with an empty list).
    NoSourceConfigured,
}

/// One identifier read from a file the operator named (a container mounts each
/// one individually, read-only).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplicitSource {
    pub kind: IdentifierKind,
    /// Display label (interface name for MACs).
    pub label: String,
    pub path: PathBuf,
}

/// Parse a list of named sources of one kind: `label=path,label=path` or a
/// single bare `path` (label = file name). Whitespace around items is ignored,
/// empty items are skipped.
///
/// # Errors
///
/// Text naming the item, if a label or path is empty.
pub fn parse_source_spec(kind: IdentifierKind, spec: &str) -> Result<Vec<ExplicitSource>, String> {
    let mut out = Vec::new();
    for item in spec.split(',').map(str::trim).filter(|i| !i.is_empty()) {
        let (label, path) = match item.split_once('=') {
            Some((label, path)) => (label.trim().to_string(), path.trim()),
            None => {
                let label = Path::new(item)
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| item.to_string());
                (label, item)
            }
        };
        if label.is_empty() || path.is_empty() {
            return Err(format!(
                "{}: invalid source {item:?} (expected label=path)",
                kind.as_str()
            ));
        }
        out.push(ExplicitSource {
            kind,
            label,
            path: PathBuf::from(path),
        });
    }
    Ok(out)
}

/// Whether this process runs inside a container (Docker or Podman marker file).
#[must_use]
pub fn in_container() -> bool {
    Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists()
}

/// Where the collector looks.
#[derive(Debug, Clone)]
pub struct HardwareSources {
    /// Root of the host file system (`/` on bare metal, `/host` in a container).
    pub host_root: PathBuf,
    /// procfs root (`/proc`); not namespaced, read directly.
    pub proc_root: PathBuf,
    /// Optional provisioned serial-number file.
    pub serial_file: Option<PathBuf>,
    /// Whether this process runs inside a container.
    pub in_container: bool,
}

impl HardwareSources {
    /// Resolve the sources: an explicit host root wins; otherwise `/host` if it
    /// exists, else `/`.
    pub fn detect(host_root: Option<&Path>, serial_file: Option<&Path>) -> Self {
        let host_root = match host_root {
            Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
            _ if Path::new(DEFAULT_HOST_ROOT).is_dir() => PathBuf::from(DEFAULT_HOST_ROOT),
            _ => PathBuf::from("/"),
        };
        Self {
            host_root,
            proc_root: PathBuf::from("/proc"),
            serial_file: serial_file
                .filter(|p| !p.as_os_str().is_empty())
                .map(Path::to_path_buf),
            in_container: in_container(),
        }
    }
}

/// All identifiers found on this machine, plus why others are missing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct HardwareProfile {
    pub identifiers: Vec<HardwareIdentifier>,
    pub problems: Vec<ProfileProblem>,
}

impl HardwareProfile {
    /// Collect the profile of this machine.
    pub fn collect(sources: &HardwareSources) -> Self {
        let mut profile = Self::default();
        platform::collect(sources, &mut profile);
        collect_cpu_serial(&sources.proc_root, &mut profile);
        if let Some(path) = &sources.serial_file {
            collect_serial_file(path, &mut profile);
        }
        profile
    }

    /// Collect from named sources only: each file's first non-empty line is the
    /// value. Nothing else of the host is read except `/proc/cpuinfo` (under
    /// `proc_root`, if given), which is not namespaced. An empty list reports
    /// [`ProfileProblem::NoSourceConfigured`].
    pub fn collect_explicit(sources: &[ExplicitSource], proc_root: Option<&Path>) -> Self {
        let mut profile = Self::default();
        if sources.is_empty() {
            profile.problems.push(ProfileProblem::NoSourceConfigured);
        }
        for source in sources {
            match std::fs::read_to_string(&source.path) {
                Ok(text) => {
                    let first = text.lines().map(str::trim).find(|l| !l.is_empty());
                    match first
                        .and_then(|v| HardwareIdentifier::new(source.kind, source.label.clone(), v))
                    {
                        Some(id) => profile.push(Some(id)),
                        None => profile.problems.push(ProfileProblem::SourceUnreadable {
                            kind: source.kind,
                            path: source.path.display().to_string(),
                            error: "empty or placeholder value".to_string(),
                        }),
                    }
                }
                Err(e) => profile.problems.push(ProfileProblem::SourceUnreadable {
                    kind: source.kind,
                    path: source.path.display().to_string(),
                    error: e.to_string(),
                }),
            }
        }
        if let Some(proc_root) = proc_root {
            collect_cpu_serial(proc_root, &mut profile);
        }
        profile
    }

    /// Whether `binding` is present on this machine.
    pub fn matches(&self, binding: &Binding) -> bool {
        self.identifiers
            .iter()
            .any(|id| id.kind == binding.kind && id.sha256 == binding.sha256)
    }

    /// Stable digest over all identifier hashes (recorded with a trial).
    pub fn digest(&self) -> String {
        let mut hashes: Vec<String> = self
            .identifiers
            .iter()
            .map(|id| format!("{}:{}", id.kind.as_str(), id.sha256))
            .collect();
        hashes.sort();
        hex_encode(&Sha256::digest(hashes.join("\n").as_bytes()))
    }

    /// Bindings of the identifiers with the given hashes (operator selection).
    pub fn bindings_for(&self, hashes: &[String]) -> Vec<Binding> {
        self.identifiers
            .iter()
            .filter(|id| hashes.contains(&id.sha256))
            .map(HardwareIdentifier::binding)
            .collect()
    }

    fn push(&mut self, id: Option<HardwareIdentifier>) {
        if let Some(id) = id {
            if !self.identifiers.contains(&id) {
                self.identifiers.push(id);
            }
        }
    }
}

fn collect_cpu_serial(proc_root: &Path, profile: &mut HardwareProfile) {
    let path = proc_root.join("cpuinfo");
    if let Ok(text) = std::fs::read_to_string(&path) {
        if let Some(serial) = parse_cpuinfo_serial(&text) {
            profile.push(HardwareIdentifier::new(
                IdentifierKind::CpuSerial,
                path.display().to_string(),
                &serial,
            ));
        }
    }
}

/// The `Serial` line of `/proc/cpuinfo` (ARM), if present.
pub fn parse_cpuinfo_serial(cpuinfo: &str) -> Option<String> {
    cpuinfo.lines().find_map(|line| {
        let (key, value) = line.split_once(':')?;
        key.trim()
            .eq_ignore_ascii_case("serial")
            .then(|| value.trim().to_string())
    })
}

fn collect_serial_file(path: &Path, profile: &mut HardwareProfile) {
    match std::fs::read_to_string(path) {
        Ok(text) => {
            let first = text.lines().map(str::trim).find(|l| !l.is_empty());
            profile.push(first.and_then(|line| {
                HardwareIdentifier::new(
                    IdentifierKind::SerialFile,
                    path.display().to_string(),
                    line,
                )
            }));
        }
        Err(e) => profile.problems.push(ProfileProblem::SourceUnreadable {
            kind: IdentifierKind::SerialFile,
            path: path.display().to_string(),
            error: e.to_string(),
        }),
    }
}

#[cfg(not(windows))]
mod platform {
    use super::*;

    pub(super) fn collect(sources: &HardwareSources, profile: &mut HardwareProfile) {
        if sources.in_container && sources.host_root == Path::new("/") {
            profile
                .problems
                .push(ProfileProblem::ContainerWithoutHostRoot {
                    expected: DEFAULT_HOST_ROOT.to_string(),
                });
            return;
        }
        collect_machine_id(&sources.host_root, profile);
        collect_macs(&sources.host_root.join("sys/class/net"), profile);
    }

    fn collect_machine_id(root: &Path, profile: &mut HardwareProfile) {
        let primary = root.join("etc/machine-id");
        let fallback = root.join("var/lib/dbus/machine-id");
        for path in [&primary, &fallback] {
            if let Ok(text) = std::fs::read_to_string(path) {
                if let Some(id) =
                    HardwareIdentifier::new(IdentifierKind::MachineId, "machine-id", &text)
                {
                    profile.push(Some(id));
                    return;
                }
            }
        }
        let error = std::fs::read_to_string(&primary)
            .err()
            .map(|e| e.to_string())
            .unwrap_or_else(|| "empty".to_string());
        profile.problems.push(ProfileProblem::SourceUnreadable {
            kind: IdentifierKind::MachineId,
            path: primary.display().to_string(),
            error,
        });
    }

    /// Physical interfaces only: the sysfs link of a virtual one (bridge, veth,
    /// docker0, lo) resolves under `devices/virtual/`; Ethernet type 1; MACs the
    /// kernel randomised (`addr_assign_type` 1) are skipped.
    pub(super) fn collect_macs(net_dir: &Path, profile: &mut HardwareProfile) {
        let entries = match std::fs::read_dir(net_dir) {
            Ok(e) => e,
            Err(e) => {
                profile.problems.push(ProfileProblem::SourceUnreadable {
                    kind: IdentifierKind::Mac,
                    path: net_dir.display().to_string(),
                    error: e.to_string(),
                });
                return;
            }
        };
        let mut names: Vec<String> = entries
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        let (mut found, mut dangling) = (0usize, 0usize);
        for name in &names {
            let entry = net_dir.join(name);
            if let Ok(link) = std::fs::read_link(&entry) {
                if link.to_string_lossy().contains("devices/virtual/") {
                    continue;
                }
            } else if !entry.join("device").exists() {
                continue;
            }
            let read = |file: &str| std::fs::read_to_string(entry.join(file));
            let address = match read("address") {
                Ok(a) => a,
                Err(_) => {
                    dangling += 1;
                    continue;
                }
            };
            if read("type").map(|t| t.trim() != "1").unwrap_or(true) {
                continue;
            }
            if read("addr_assign_type")
                .map(|t| t.trim() == "1")
                .unwrap_or(false)
            {
                continue;
            }
            if let Some(id) = HardwareIdentifier::new(IdentifierKind::Mac, name.clone(), &address) {
                profile.push(Some(id));
                found += 1;
            }
        }
        if found == 0 {
            let path = net_dir.display().to_string();
            profile.problems.push(if dangling > 0 {
                ProfileProblem::DanglingInterfaces { path }
            } else {
                ProfileProblem::NoPhysicalInterface { path }
            });
        }
    }
}

#[cfg(windows)]
mod platform {
    use super::*;
    use std::os::windows::process::CommandExt;
    use std::process::Command;

    const CREATE_NO_WINDOW: u32 = 0x0800_0000;

    pub(super) fn collect(_sources: &HardwareSources, profile: &mut HardwareProfile) {
        match run(
            "reg",
            &[
                "query",
                r"HKLM\SOFTWARE\Microsoft\Cryptography",
                "/v",
                "MachineGuid",
            ],
        ) {
            Ok(out) => profile.push(parse_reg_query_value(&out, "MachineGuid").and_then(|guid| {
                HardwareIdentifier::new(IdentifierKind::MachineId, "MachineGuid", &guid)
            })),
            Err(error) => profile.problems.push(ProfileProblem::QueryFailed {
                kind: IdentifierKind::MachineId,
                error,
            }),
        }
        match run(
            "powershell.exe",
            &[
                "-NoProfile",
                "-NonInteractive",
                "-Command",
                "Get-NetAdapter -Physical | Select-Object Name,MacAddress | ConvertTo-Json -Compress",
            ],
        ) {
            Ok(out) => {
                let before = profile.identifiers.len();
                for (name, mac) in parse_netadapter_json(&out) {
                    profile.push(HardwareIdentifier::new(IdentifierKind::Mac, name, &mac));
                }
                if profile.identifiers.len() == before {
                    profile.problems.push(ProfileProblem::NoPhysicalInterface {
                        path: "Get-NetAdapter -Physical".to_string(),
                    });
                }
            }
            Err(error) => profile.problems.push(ProfileProblem::QueryFailed {
                kind: IdentifierKind::Mac,
                error,
            }),
        }
    }

    fn run(program: &str, args: &[&str]) -> Result<String, String> {
        let output = Command::new(program)
            .args(args)
            .creation_flags(CREATE_NO_WINDOW)
            .output()
            .map_err(|e| format!("{program}: {e}"))?;
        if !output.status.success() {
            return Err(format!("{program}: exit {}", output.status));
        }
        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    }
}

/// Value of `name` in the output of `reg query … /v name`.
pub fn parse_reg_query_value(output: &str, name: &str) -> Option<String> {
    output.lines().find_map(|line| {
        let mut parts = line.split_whitespace();
        if parts.next()? != name {
            return None;
        }
        let _kind = parts.next()?;
        parts.next().map(str::to_string)
    })
}

/// `(Name, MacAddress)` pairs from `Get-NetAdapter | ConvertTo-Json` (object or array).
pub fn parse_netadapter_json(output: &str) -> Vec<(String, String)> {
    let value: serde_json::Value = match serde_json::from_str(output.trim()) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    let items = match value {
        serde_json::Value::Array(items) => items,
        single => vec![single],
    };
    items
        .iter()
        .filter_map(|item| {
            Some((
                item.get("Name")?.as_str()?.to_string(),
                item.get("MacAddress")?.as_str()?.to_string(),
            ))
        })
        .collect()
}

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

    #[test]
    fn normalisation_per_kind() {
        let n = |k: IdentifierKind, v: &str| k.normalize(v);
        assert_eq!(
            n(
                IdentifierKind::MachineId,
                "{0CD9A1AB-E0B8-40BB-A8A4-E848C070DF47}\n"
            )
            .unwrap(),
            "0cd9a1abe0b840bba8a4e848c070df47"
        );
        assert_eq!(
            n(IdentifierKind::Mac, "E0-8F-4C-82-40-7E").unwrap(),
            "e0:8f:4c:82:40:7e"
        );
        assert_eq!(n(IdentifierKind::Mac, "00:00:00:00:00:00"), None);
        assert_eq!(n(IdentifierKind::Mac, "e0:8f:4c:82:40"), None);
        assert_eq!(n(IdentifierKind::CpuSerial, "0000000000000000"), None);
        assert_eq!(
            n(IdentifierKind::SerialFile, " sn00100 ").unwrap(),
            "SN00100"
        );
        assert_eq!(n(IdentifierKind::MachineId, "  "), None);
    }

    #[test]
    fn hash_is_domain_and_kind_separated() {
        let a = identifier_hash(IdentifierKind::CpuSerial, "abc");
        let b = identifier_hash(IdentifierKind::SerialFile, "abc");
        assert_ne!(a, b);
        assert_eq!(a.len(), 64);
    }

    #[test]
    fn cpuinfo_serial_only_on_arm() {
        let arm = "processor\t: 0\nHardware\t: BCM2835\nSerial\t\t: 10000000abcdef01\n";
        assert_eq!(parse_cpuinfo_serial(arm).unwrap(), "10000000abcdef01");
        assert_eq!(parse_cpuinfo_serial("model name\t: Intel(R)\n"), None);
    }

    #[test]
    fn windows_output_parsers() {
        let reg = "\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\r\n    MachineGuid    REG_SZ    0cd9a1ab-e0b8-40bb-a8a4-e848c070df47\r\n";
        assert_eq!(
            parse_reg_query_value(reg, "MachineGuid").unwrap(),
            "0cd9a1ab-e0b8-40bb-a8a4-e848c070df47"
        );
        let single = r#"{"Name":"Ethernet","MacAddress":"E0-8F-4C-82-40-7E"}"#;
        assert_eq!(parse_netadapter_json(single).len(), 1);
        let many = r#"[{"Name":"Ethernet","MacAddress":"E0-8F-4C-82-40-7E"},{"Name":"WLAN","MacAddress":"74-D4-DD-C7-65-A0"}]"#;
        assert_eq!(parse_netadapter_json(many)[1].0, "WLAN");
        assert!(parse_netadapter_json("").is_empty());
    }

    #[cfg(unix)]
    fn fake_sysfs(root: &Path, full_sys: bool) {
        use std::os::unix::fs::symlink;
        let net = root.join("sys/class/net");
        std::fs::create_dir_all(&net).unwrap();
        let mk = |rel: &str, name: &str, ty: &str, addr: &str, assign: &str| {
            let dev = root.join("sys/devices").join(rel).join(name);
            if full_sys {
                std::fs::create_dir_all(&dev).unwrap();
                std::fs::write(dev.join("address"), format!("{addr}\n")).unwrap();
                std::fs::write(dev.join("type"), format!("{ty}\n")).unwrap();
                std::fs::write(dev.join("addr_assign_type"), format!("{assign}\n")).unwrap();
            }
            symlink(format!("../../devices/{rel}/{name}"), net.join(name)).unwrap();
        };
        mk(
            "pci0000:00/0000:00:1f.6/net",
            "eth0",
            "1",
            "E0:8F:4C:82:40:7E",
            "0",
        );
        mk(
            "pci0000:00/0000:00:14.3/net",
            "wlan0",
            "1",
            "02:11:22:33:44:55",
            "1",
        );
        mk("virtual/net", "docker0", "1", "8e:37:58:94:aa:e2", "3");
        mk("virtual/net", "lo", "772", "00:00:00:00:00:00", "0");
    }

    #[cfg(unix)]
    #[test]
    fn collects_physical_interfaces_and_machine_id_from_host_root() {
        let dir = tempfile::tempdir().unwrap();
        fake_sysfs(dir.path(), true);
        std::fs::create_dir_all(dir.path().join("etc")).unwrap();
        std::fs::write(
            dir.path().join("etc/machine-id"),
            "0cd9a1abe0b840bba8a4e848c070df47\n",
        )
        .unwrap();
        let serial = dir.path().join("serial");
        std::fs::write(&serial, "\nSN00100\n").unwrap();
        let sources = HardwareSources {
            host_root: dir.path().to_path_buf(),
            proc_root: dir.path().join("no-proc"),
            serial_file: Some(serial),
            in_container: true,
        };
        let profile = HardwareProfile::collect(&sources);
        let kinds: Vec<(IdentifierKind, &str)> = profile
            .identifiers
            .iter()
            .map(|i| (i.kind, i.label.as_str()))
            .collect();
        assert!(kinds.contains(&(IdentifierKind::MachineId, "machine-id")));
        assert!(kinds.contains(&(IdentifierKind::Mac, "eth0")));
        assert!(!kinds
            .iter()
            .any(|(_, l)| *l == "docker0" || *l == "wlan0" || *l == "lo"));
        assert!(kinds.iter().any(|(k, _)| *k == IdentifierKind::SerialFile));
        assert!(profile.problems.is_empty(), "{:?}", profile.problems);

        let mac = profile
            .identifiers
            .iter()
            .find(|i| i.label == "eth0")
            .unwrap();
        assert!(profile.matches(&mac.binding()));
        assert_eq!(
            profile
                .bindings_for(std::slice::from_ref(&mac.sha256))
                .len(),
            1
        );
    }

    #[cfg(unix)]
    #[test]
    fn only_class_net_mounted_is_reported_as_dangling() {
        let dir = tempfile::tempdir().unwrap();
        fake_sysfs(dir.path(), false);
        let mut profile = HardwareProfile::default();
        platform::collect_macs(&dir.path().join("sys/class/net"), &mut profile);
        assert!(profile.identifiers.is_empty());
        assert!(matches!(
            profile.problems[0],
            ProfileProblem::DanglingInterfaces { .. }
        ));
    }

    #[cfg(unix)]
    #[test]
    fn container_without_host_root_refuses_image_identity() {
        let sources = HardwareSources {
            host_root: PathBuf::from("/"),
            proc_root: PathBuf::from("/nonexistent"),
            serial_file: None,
            in_container: true,
        };
        let profile = HardwareProfile::collect(&sources);
        assert!(profile.identifiers.is_empty());
        assert!(matches!(
            profile.problems[0],
            ProfileProblem::ContainerWithoutHostRoot { .. }
        ));
    }

    #[test]
    fn named_sources_are_read_and_nothing_else() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("machine-id"),
            "0cd9a1abe0b840bba8a4e848c070df47\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("mac-eth0"), "E0:8F:4C:82:40:7E\n").unwrap();
        std::fs::write(dir.path().join("leer"), "\n").unwrap();
        let d = dir.path().display();
        let mut sources =
            parse_source_spec(IdentifierKind::MachineId, &format!("{d}/machine-id")).unwrap();
        sources.extend(
            parse_source_spec(
                IdentifierKind::Mac,
                &format!(" eth0={d}/mac-eth0 , eth1={d}/fehlt ,"),
            )
            .unwrap(),
        );
        sources.extend(
            parse_source_spec(IdentifierKind::SerialFile, &format!("sn={d}/leer")).unwrap(),
        );
        assert_eq!(sources[0].label, "machine-id");
        assert_eq!(sources[1].label, "eth0");
        let profile = HardwareProfile::collect_explicit(&sources, None);
        let ids: Vec<(IdentifierKind, &str)> = profile
            .identifiers
            .iter()
            .map(|i| (i.kind, i.label.as_str()))
            .collect();
        assert_eq!(
            ids,
            vec![
                (IdentifierKind::MachineId, "machine-id"),
                (IdentifierKind::Mac, "eth0")
            ]
        );
        assert_eq!(
            profile.problems.len(),
            2,
            "missing file and empty value: {:?}",
            profile.problems
        );
        assert!(parse_source_spec(IdentifierKind::Mac, "eth0=").is_err());
        assert!(parse_source_spec(IdentifierKind::Mac, "=x").is_err());
        assert_eq!(
            HardwareProfile::collect_explicit(&[], None).problems,
            vec![ProfileProblem::NoSourceConfigured]
        );
    }

    #[test]
    fn digest_ignores_order() {
        let a = HardwareIdentifier::new(IdentifierKind::Mac, "eth0", "e0:8f:4c:82:40:7e").unwrap();
        let b = HardwareIdentifier::new(IdentifierKind::SerialFile, "sn", "SN1").unwrap();
        let p1 = HardwareProfile {
            identifiers: vec![a.clone(), b.clone()],
            problems: vec![],
        };
        let p2 = HardwareProfile {
            identifiers: vec![b, a],
            problems: vec![],
        };
        assert_eq!(p1.digest(), p2.digest());
    }
}