host-identity-cli 1.0.0

Command-line interface for host-identity: print a stable host UUID across platforms, clouds, and Kubernetes
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
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
//! `host-identity` — command-line interface for the `host-identity` crate.
//! Binary was renamed from `hostid` to avoid colliding with coreutils
//! `hostid(1)`; see `crates/host-identity-cli/Cargo.toml` for the
//! `[[bin]]` name and the rationale.
//!
//! This crate also exposes a small library surface so build tooling
//! (the workspace `xtask` that generates man pages) can reuse the
//! exact `clap::Command` definition the binary ships with. End users
//! should depend on the [`host-identity`] library directly.
//!
//! [`host-identity`]: https://crates.io/crates/host-identity

use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::{Context, Result, anyhow};
use clap::{Parser, Subcommand, ValueEnum};
use host_identity::ids::{resolver_from_ids, source_ids};
use host_identity::sources::FileOverride;
use host_identity::{HostId, ResolveOutcome, Resolver, SourceKind, UnknownSourceError, Wrap};
use serde::Serialize;

/// Environment variable that, when set to a non-empty path, causes the
/// CLI to prepend a [`FileOverride`] at the front of the resolver
/// chain. Takes precedence over `HOST_IDENTITY`.
const HOST_IDENTITY_FILE_ENV: &str = "HOST_IDENTITY_FILE";

#[cfg(feature = "network")]
mod transport;

/// Crate version, re-exported so the workspace `xtask` can stamp the
/// man page footer with the CLI crate's version rather than its own.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

const LONG_ABOUT: &str = "\
Resolve a stable, collision-resistant host UUID across platforms, container \
runtimes, cloud providers, and Kubernetes.

host-identity walks a platform-appropriate chain of identity sources (env override, \
/etc/machine-id, DMI, cloud metadata, Kubernetes pod UID, …) and returns the \
first one that produces a credible identifier. Cloned-VM sentinels, empty \
files, and systemd's literal `uninitialized` string are rejected rather than \
silently hashed into a shared ID.

Two environment variables pin identity explicitly when the automatic chain \
gets it wrong. HOST_IDENTITY_FILE names a file whose contents are used as \
the host identifier and takes precedence over every other source, including \
HOST_IDENTITY. HOST_IDENTITY supplies the identifier inline and is consulted \
next. Both work with the default chain and with explicit --sources.

By default the chain uses only local sources. Pass --network to pull in \
cloud-metadata and Kubernetes probes, which require an HTTP client and a \
binary built with the `network` feature.";

const EXAMPLES: &str = "\
EXAMPLES:
    Print the host UUID using the default local source chain:
        host-identity

    Include cloud-metadata and Kubernetes sources:
        host-identity resolve --network

    Build a custom chain from explicit source identifiers:
        host-identity resolve --sources env-override,machine-id,dmi

    Emit machine-readable output:
        host-identity resolve --format json
        host-identity audit --format json

    Pin identity via environment override:
        HOST_IDENTITY=11111111-2222-3333-4444-555555555555 host-identity

    Pin identity via a file (takes precedence over HOST_IDENTITY):
        HOST_IDENTITY_FILE=/etc/host-identity host-identity

    List every source identifier compiled into this binary:
        host-identity sources
";

/// Top-level command-line interface for the `host-identity` binary.
#[derive(Parser)]
#[command(
    name = "host-identity",
    version,
    author,
    about = "Resolve a stable host UUID across platforms, clouds, and Kubernetes",
    long_about = LONG_ABOUT,
    after_long_help = EXAMPLES,
    args_conflicts_with_subcommands = true,
)]
pub struct Cli {
    #[command(subcommand)]
    command: Option<Command>,

    /// Top-level flags apply only when no subcommand is given (they are
    /// shorthand for `host-identity resolve ...`).
    #[command(flatten)]
    resolve: ResolveArgs,
}

#[derive(Subcommand)]
enum Command {
    /// Resolve the host identity and print it (default).
    Resolve(ResolveArgs),
    /// Walk every source without short-circuiting and report each outcome.
    Audit(AuditArgs),
    /// List every source identifier compiled into this binary.
    Sources {
        /// Emit JSON instead of one identifier per line.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Parser, Clone, Default)]
struct ResolveArgs {
    /// Output format.
    #[arg(long, value_enum, default_value_t = Format::Plain)]
    format: Format,

    /// UUID wrap strategy.
    #[arg(long, value_enum, default_value_t = WrapArg::V5)]
    wrap: WrapArg,

    /// Comma-separated source identifiers to build a custom chain
    /// (see `host-identity sources`). Combine with `--network` to include
    /// cloud-metadata sources in the chain.
    #[arg(long, value_delimiter = ',')]
    sources: Vec<String>,

    /// Enable cloud-metadata and Kubernetes sources by supplying an HTTP
    /// transport. Without `--sources` this adds them to the default chain;
    /// with `--sources` it lets identifiers like `aws-imds` resolve.
    /// Requires the binary to be built with the `network` feature.
    #[arg(long)]
    network: bool,

    /// Per-request timeout, in milliseconds, for cloud-metadata and
    /// Kubernetes HTTP probes. Only meaningful with `--network`. Off-cloud
    /// hosts never answer these endpoints, so this directly bounds the
    /// time spent waiting before falling through to the next source.
    #[arg(long, value_name = "MS", value_parser = clap::value_parser!(u64).range(1..))]
    network_timeout_ms: Option<u64>,
}

#[derive(Parser, Clone, Default)]
struct AuditArgs {
    #[command(flatten)]
    resolve: ResolveArgs,
}

#[derive(ValueEnum, Clone, Copy, Default)]
enum Format {
    #[default]
    Plain,
    Summary,
    Json,
}

#[derive(ValueEnum, Clone, Copy, Default)]
enum WrapArg {
    #[default]
    V5,
    V3,
    Passthrough,
}

impl From<WrapArg> for Wrap {
    fn from(w: WrapArg) -> Self {
        match w {
            WrapArg::V5 => Wrap::UuidV5Namespaced,
            WrapArg::V3 => Wrap::UuidV3Nil,
            WrapArg::Passthrough => Wrap::Passthrough,
        }
    }
}

/// Exit codes surfaced by the CLI. Scripts can branch on
/// `Usage` (2) vs. `Runtime` (1) to distinguish a bad invocation
/// from a host where no source produced an identity.
const EXIT_USAGE: u8 = 2;

/// Errors that `build_resolver` converts into an `EXIT_USAGE` exit.
#[derive(Debug)]
enum CliError {
    Usage(anyhow::Error),
    Runtime(anyhow::Error),
}

impl CliError {
    fn exit_code(&self) -> ExitCode {
        match self {
            Self::Usage(_) => ExitCode::from(EXIT_USAGE),
            Self::Runtime(_) => ExitCode::FAILURE,
        }
    }
    fn into_inner(self) -> anyhow::Error {
        match self {
            Self::Usage(e) | Self::Runtime(e) => e,
        }
    }
}

fn usage<T>(msg: anyhow::Error) -> Result<T, CliError> {
    Err(CliError::Usage(msg))
}

fn runtime_err<E: Into<anyhow::Error>>(e: E) -> CliError {
    CliError::Runtime(e.into())
}

fn runtime<T>(msg: anyhow::Error) -> Result<T, CliError> {
    Err(CliError::Runtime(msg))
}

/// Parse argv and run the CLI, returning the process exit code.
#[must_use]
pub fn run() -> ExitCode {
    let cli = Cli::parse();
    let result = match cli.command {
        Some(Command::Resolve(args)) => run_resolve(&args),
        Some(Command::Audit(args)) => run_audit(&args.resolve),
        Some(Command::Sources { json }) => run_sources(json),
        None => run_resolve(&cli.resolve),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            let code = err.exit_code();
            eprintln!("host-identity: {:#}", err.into_inner());
            code
        }
    }
}

/// Write to stdout, collapsing `BrokenPipe` into a clean exit.
/// Without this, piping `host-identity audit | head` panics.
fn write_and_flush(bytes: &[u8]) -> io::Result<()> {
    let stdout = io::stdout();
    let mut lock = stdout.lock();
    match lock.write_all(bytes).and_then(|()| lock.flush()) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == io::ErrorKind::BrokenPipe => Ok(()),
        Err(err) => Err(err),
    }
}

fn build_resolver(args: &ResolveArgs) -> Result<Resolver, CliError> {
    if args.network_timeout_ms.is_some() && !args.network {
        return usage(anyhow!("`--network-timeout-ms` requires `--network`"));
    }
    let resolver = match (args.sources.is_empty(), args.network) {
        (true, false) => Resolver::with_defaults(),
        (true, true) => network_defaults(args.network_timeout_ms).map_err(CliError::Usage)?,
        (false, false) => {
            resolver_from_ids(&args.sources).map_err(|e| CliError::Usage(map_unknown(e)))?
        }
        (false, true) => resolver_from_ids_network(&args.sources, args.network_timeout_ms)
            .map_err(CliError::Usage)?,
    };

    let mut resolver = resolver.with_wrap(Wrap::from(args.wrap));
    if let Some(file_override) = host_identity_file_override() {
        resolver = resolver.prepend(file_override);
    }
    Ok(resolver)
}

/// Read `HOST_IDENTITY_FILE` from the process environment and, if set
/// to a non-empty path, return a [`FileOverride`] for it. The override
/// is prepended by [`build_resolver`] so it outranks every other source,
/// matching the documented precedence in `LONG_ABOUT`.
fn host_identity_file_override() -> Option<FileOverride> {
    file_override_from_env_value(std::env::var_os(HOST_IDENTITY_FILE_ENV).as_deref())
}

/// Pure helper: construct a [`FileOverride`] from a raw env-var value.
/// Returns `None` when the value is absent or empty. A set-but-empty
/// value is treated the same as unset so a script clearing the
/// variable (`HOST_IDENTITY_FILE=`) disables the override rather than
/// silently turning into `FileOverride::new("")` (which would probe a
/// relative empty path).
fn file_override_from_env_value(value: Option<&OsStr>) -> Option<FileOverride> {
    let raw = value?;
    if raw.is_empty() {
        return None;
    }
    Some(FileOverride::new(PathBuf::from(raw)))
}

#[cfg(feature = "network")]
#[allow(clippy::unnecessary_wraps)]
fn network_defaults(timeout_ms: Option<u64>) -> Result<Resolver> {
    Ok(Resolver::with_network_defaults(build_transport(timeout_ms)))
}

#[cfg(not(feature = "network"))]
fn network_defaults(_timeout_ms: Option<u64>) -> Result<Resolver> {
    Err(network_feature_disabled())
}

#[cfg(feature = "network")]
fn resolver_from_ids_network(ids: &[String], timeout_ms: Option<u64>) -> Result<Resolver> {
    host_identity::ids::resolver_from_ids_with_transport(ids, build_transport(timeout_ms))
        .map_err(map_unknown)
}

#[cfg(not(feature = "network"))]
fn resolver_from_ids_network(_ids: &[String], _timeout_ms: Option<u64>) -> Result<Resolver> {
    Err(network_feature_disabled())
}

#[cfg(feature = "network")]
fn build_transport(timeout_ms: Option<u64>) -> transport::UreqTransport {
    let timeout = timeout_ms.map_or(
        transport::DEFAULT_NETWORK_TIMEOUT,
        std::time::Duration::from_millis,
    );
    transport::UreqTransport::with_timeout(timeout)
}

#[cfg(not(feature = "network"))]
fn network_feature_disabled() -> anyhow::Error {
    anyhow!("this build has no `network` feature; rebuild with `--features network`")
}

fn map_unknown(err: UnknownSourceError) -> anyhow::Error {
    match err {
        UnknownSourceError::Unknown(id) => anyhow!("unknown source identifier: `{id}`"),
        UnknownSourceError::RequiresPath(id) => anyhow!(
            "source `{id}` requires a caller-supplied path and cannot be built from an identifier",
        ),
        UnknownSourceError::RequiresTransport(id) => {
            anyhow!("source `{id}` is a cloud source; pass `--network` to supply an HTTP transport")
        }
        UnknownSourceError::FeatureDisabled(id, feat) => anyhow!(
            "source `{id}` requires the `{feat}` feature, which isn't enabled in this build",
        ),
    }
}

fn run_resolve(args: &ResolveArgs) -> Result<(), CliError> {
    let resolver = build_resolver(args)?;
    let id = resolver
        .resolve()
        .context("no source produced a host identity")
        .map_err(CliError::Runtime)?;
    print_host_id(&id, args.format).map_err(CliError::Runtime)
}

fn run_audit(args: &ResolveArgs) -> Result<(), CliError> {
    let resolver = build_resolver(args)?;
    let outcomes = resolver.resolve_all();
    let mut buf = Vec::new();
    match args.format {
        Format::Json => {
            let report: Vec<AuditEntry> = outcomes.iter().map(AuditEntry::from).collect();
            serde_json::to_writer_pretty(&mut buf, &report).map_err(runtime_err)?;
            buf.push(b'\n');
        }
        Format::Plain | Format::Summary => {
            for (i, outcome) in outcomes.iter().enumerate() {
                let kind = outcome.source();
                let tail = match outcome {
                    ResolveOutcome::Found(id) => id.summary().to_string(),
                    ResolveOutcome::Skipped(_) => "(skipped)".to_owned(),
                    ResolveOutcome::Errored(_, err) => format!("ERROR {err}"),
                };
                writeln!(buf, "{i:>2}. {kind:<28} -> {tail}").map_err(runtime_err)?;
            }
        }
    }
    write_and_flush(&buf).map_err(runtime_err)?;

    // Exit non-zero (runtime) when every outcome errored or skipped —
    // nothing to show for the walk, matching `run_resolve`'s contract.
    if !outcomes
        .iter()
        .any(|o| matches!(o, ResolveOutcome::Found(_)))
    {
        return runtime(anyhow!("no source produced a host identity"));
    }
    Ok(())
}

fn run_sources(json: bool) -> Result<(), CliError> {
    let ids = available_source_ids();
    let mut buf = Vec::new();
    if json {
        let entries: Vec<SourceEntry> = ids
            .iter()
            .map(|id| SourceEntry {
                id,
                description: describe_id(id),
            })
            .collect();
        serde_json::to_writer_pretty(&mut buf, &entries).map_err(runtime_err)?;
        buf.push(b'\n');
    } else {
        // Source identifiers are ASCII; char count == byte count. Use
        // `chars().count()` anyway so a future non-ASCII label doesn't
        // silently desync the padding width.
        let width = ids
            .iter()
            .map(|id| id.chars().count())
            .max()
            .unwrap_or_default();
        for id in &ids {
            writeln!(buf, "{id:<width$}  {}", describe_id(id), width = width)
                .map_err(runtime_err)?;
        }
    }
    write_and_flush(&buf).map_err(runtime_err)
}

fn describe_id(id: &str) -> &'static str {
    SourceKind::from_id(id).map_or("", SourceKind::describe)
}

#[derive(Serialize)]
struct SourceEntry {
    id: &'static str,
    description: &'static str,
}

fn print_host_id(id: &HostId, format: Format) -> Result<()> {
    let mut buf = Vec::new();
    match format {
        Format::Plain => writeln!(buf, "{id}")?,
        Format::Summary => writeln!(buf, "{}", id.summary())?,
        Format::Json => {
            let out = HostIdJson {
                uuid: id.as_uuid().to_string(),
                source: id.source().as_str(),
                in_container: id.in_container(),
            };
            serde_json::to_writer_pretty(&mut buf, &out)?;
            buf.push(b'\n');
        }
    }
    write_and_flush(&buf)?;
    Ok(())
}

#[derive(Serialize)]
struct HostIdJson {
    uuid: String,
    source: &'static str,
    in_container: bool,
}

#[derive(Serialize, Clone, Copy)]
#[serde(rename_all = "lowercase")]
enum AuditStatus {
    Found,
    Skipped,
    Errored,
}

#[derive(Serialize)]
struct AuditEntry {
    source: &'static str,
    status: AuditStatus,
    uuid: Option<String>,
    error: Option<String>,
    in_container: Option<bool>,
}

impl From<&ResolveOutcome> for AuditEntry {
    fn from(o: &ResolveOutcome) -> Self {
        let source = o.source().as_str();
        match o {
            ResolveOutcome::Found(id) => Self {
                source,
                status: AuditStatus::Found,
                uuid: Some(id.as_uuid().to_string()),
                error: None,
                in_container: Some(id.in_container()),
            },
            ResolveOutcome::Skipped(_) => Self {
                source,
                status: AuditStatus::Skipped,
                uuid: None,
                error: None,
                in_container: None,
            },
            ResolveOutcome::Errored(_, err) => Self {
                source,
                status: AuditStatus::Errored,
                uuid: None,
                error: Some(err.to_string()),
                in_container: None,
            },
        }
    }
}

fn available_source_ids() -> Vec<&'static str> {
    let mut ids = vec![
        source_ids::ENV_OVERRIDE,
        source_ids::FILE_OVERRIDE,
        source_ids::MACHINE_ID,
        source_ids::DBUS_MACHINE_ID,
        source_ids::DMI,
        source_ids::IO_PLATFORM_UUID,
        source_ids::WINDOWS_MACHINE_GUID,
        source_ids::FREEBSD_HOSTID,
        source_ids::KENV_SMBIOS,
        source_ids::BSD_KERN_HOSTID,
        source_ids::ILLUMOS_HOSTID,
    ];
    #[cfg(feature = "container")]
    {
        ids.push(source_ids::CONTAINER);
        ids.push(source_ids::LXC);
    }
    #[cfg(feature = "network")]
    {
        ids.extend_from_slice(&[
            source_ids::AWS_IMDS,
            source_ids::GCP_METADATA,
            source_ids::AZURE_IMDS,
            source_ids::DIGITAL_OCEAN_METADATA,
            source_ids::HETZNER_METADATA,
            source_ids::OCI_METADATA,
            source_ids::KUBERNETES_POD_UID,
            source_ids::KUBERNETES_SERVICE_ACCOUNT,
            source_ids::KUBERNETES_DOWNWARD_API,
        ]);
    }
    ids.sort_unstable();
    ids
}

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

    #[test]
    fn wrap_arg_maps_every_variant_to_library_wrap() {
        assert!(matches!(Wrap::from(WrapArg::V5), Wrap::UuidV5Namespaced));
        assert!(matches!(Wrap::from(WrapArg::V3), Wrap::UuidV3Nil));
        assert!(matches!(
            Wrap::from(WrapArg::Passthrough),
            Wrap::Passthrough
        ));
    }

    #[test]
    fn available_source_ids_is_sorted_and_deduplicated() {
        let ids = available_source_ids();
        assert!(
            ids.windows(2).all(|w| w[0] < w[1]),
            "ids must be strictly sorted"
        );
        assert!(ids.contains(&source_ids::MACHINE_ID));
        assert!(ids.contains(&source_ids::DMI));
    }

    #[test]
    #[cfg(feature = "container")]
    fn available_source_ids_includes_container_when_feature_enabled() {
        assert!(available_source_ids().contains(&source_ids::CONTAINER));
        assert!(available_source_ids().contains(&source_ids::LXC));
    }

    #[test]
    fn build_resolver_defaults_when_no_flags_given() {
        let args = ResolveArgs::default();
        let resolver = build_resolver(&args).expect("defaults build");
        assert!(
            resolver
                .source_kinds()
                .contains(&host_identity::SourceKind::EnvOverride),
            "default chain must include env-override",
        );
    }

    #[test]
    fn build_resolver_uses_ids_chain_when_sources_set() {
        let args = ResolveArgs {
            sources: vec!["env-override".into(), "machine-id".into()],
            ..Default::default()
        };
        let resolver = build_resolver(&args).expect("ids build");
        let kinds = resolver.source_kinds();
        assert_eq!(kinds.len(), 2);
        assert_eq!(kinds[0], host_identity::SourceKind::EnvOverride);
        assert_eq!(kinds[1], host_identity::SourceKind::MachineId);
    }

    #[test]
    fn build_resolver_rejects_unknown_source_id() {
        let args = ResolveArgs {
            sources: vec!["definitely-not-a-source".into()],
            ..Default::default()
        };
        let err = build_resolver(&args).expect_err("unknown id must fail");
        assert!(
            err.into_inner()
                .to_string()
                .contains("unknown source identifier")
        );
    }

    #[test]
    #[cfg(feature = "network")]
    fn build_resolver_network_defaults_includes_cloud_sources() {
        let args = ResolveArgs {
            network: true,
            ..Default::default()
        };
        let resolver = build_resolver(&args).expect("network defaults build");
        assert!(
            resolver
                .source_kinds()
                .contains(&host_identity::SourceKind::AwsImds),
            "--network should add cloud sources to the default chain",
        );
    }

    #[test]
    #[cfg(feature = "network")]
    fn build_resolver_network_plus_ids_resolves_cloud_identifiers() {
        let args = ResolveArgs {
            sources: vec!["aws-imds".into()],
            network: true,
            ..Default::default()
        };
        let resolver = build_resolver(&args).expect("network + ids build");
        assert_eq!(
            resolver.source_kinds(),
            vec![host_identity::SourceKind::AwsImds]
        );
    }

    #[test]
    #[cfg(not(feature = "network"))]
    fn build_resolver_network_without_feature_errors() {
        let args = ResolveArgs {
            network: true,
            ..Default::default()
        };
        let err = build_resolver(&args).expect_err("--network must fail without feature");
        assert!(err.into_inner().to_string().contains("`network` feature"));
    }

    #[test]
    fn build_resolver_rejects_network_timeout_without_network() {
        let args = ResolveArgs {
            network_timeout_ms: Some(500),
            ..Default::default()
        };
        let err = build_resolver(&args).expect_err("must reject timeout without --network");
        assert!(
            err.into_inner()
                .to_string()
                .contains("requires `--network`")
        );
    }

    #[test]
    fn map_unknown_formats_each_variant_distinctly() {
        let cases = [
            (
                UnknownSourceError::Unknown("weird".to_owned()),
                "unknown source identifier",
            ),
            (
                UnknownSourceError::RequiresPath("file-override"),
                "caller-supplied path",
            ),
            (
                UnknownSourceError::RequiresTransport("aws-imds"),
                "pass `--network`",
            ),
            (
                UnknownSourceError::FeatureDisabled("aws-imds", "aws"),
                "isn't enabled in this build",
            ),
        ];
        for (err, expected_fragment) in cases {
            let msg = map_unknown(err).to_string();
            assert!(
                msg.contains(expected_fragment),
                "message {msg:?} missing fragment {expected_fragment:?}",
            );
        }
    }

    #[test]
    fn file_override_from_env_value_handles_absent_empty_and_set() {
        assert!(file_override_from_env_value(None).is_none());
        assert!(file_override_from_env_value(Some(OsStr::new(""))).is_none());
        let fo = file_override_from_env_value(Some(OsStr::new("/tmp/host-id")))
            .expect("non-empty value must yield a FileOverride");
        assert_eq!(fo.path(), std::path::Path::new("/tmp/host-id"));
    }

    #[test]
    fn host_id_json_schema_is_stable() {
        // Pins the `--format json` schema for `host-identity resolve`. Any field
        // rename or case change breaks downstream script parsers; this
        // snapshot catches that at test time.
        let sample = HostIdJson {
            uuid: "11111111-2222-3333-4444-555555555555".to_owned(),
            source: "machine-id",
            in_container: false,
        };
        let json = serde_json::to_value(&sample).unwrap();
        let obj = json.as_object().unwrap();
        assert_eq!(obj.len(), 3);
        assert_eq!(obj["uuid"], "11111111-2222-3333-4444-555555555555");
        assert_eq!(obj["source"], "machine-id");
        assert_eq!(obj["in_container"], false);
    }

    #[test]
    fn audit_entry_schema_is_stable_for_every_status() {
        use host_identity::sources::FnSource;
        let found_src = FnSource::new(SourceKind::custom("ok"), || Ok(Some("raw".into())));
        let err_src = FnSource::new(SourceKind::custom("bad"), || {
            Err(host_identity::Error::Platform {
                source_kind: SourceKind::custom("bad"),
                reason: "synthetic".into(),
            })
        });
        let skip_src = FnSource::new(SourceKind::custom("skip"), || Ok(None));
        let outcomes = Resolver::new()
            .push(found_src)
            .push(err_src)
            .push(skip_src)
            .resolve_all();
        let entries: Vec<AuditEntry> = outcomes.iter().map(AuditEntry::from).collect();
        let json = serde_json::to_value(&entries).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0]["status"], "found");
        assert!(arr[0]["uuid"].is_string());
        assert_eq!(arr[0]["error"], serde_json::Value::Null);
        assert_eq!(arr[1]["status"], "errored");
        assert!(arr[1]["error"].as_str().unwrap().contains("synthetic"));
        assert_eq!(arr[1]["uuid"], serde_json::Value::Null);
        assert_eq!(arr[2]["status"], "skipped");
        // Every entry shares the same key set.
        for entry in arr {
            let keys: Vec<_> = entry.as_object().unwrap().keys().collect();
            assert_eq!(keys.len(), 5);
        }
    }

    #[test]
    #[cfg(feature = "network")]
    fn available_source_ids_includes_every_cloud_and_k8s_source() {
        let ids = available_source_ids();
        for id in [
            source_ids::AWS_IMDS,
            source_ids::GCP_METADATA,
            source_ids::AZURE_IMDS,
            source_ids::DIGITAL_OCEAN_METADATA,
            source_ids::HETZNER_METADATA,
            source_ids::OCI_METADATA,
            source_ids::KUBERNETES_POD_UID,
            source_ids::KUBERNETES_SERVICE_ACCOUNT,
            source_ids::KUBERNETES_DOWNWARD_API,
        ] {
            assert!(ids.contains(&id), "missing {id}");
        }
    }
}