ignition-core 1.1.0

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
//! Config discovery, load/save, selection, and the env overlay (research
//! Pattern 2).
//!
//! Discovery: `IGNITION_CLI_CONFIG` (explicit path — scripts and tests)
//! FIRST, the platform path second. macOS gotcha: `directories` ignores
//! `XDG_CONFIG_HOME`, which is exactly why every test drives the env
//! override.
//!
//! Precedence (LOCKED): CLI flag > `IGNITION_*` env > profile value >
//! default. Each env concern has exactly one home: profile selection env
//! (`IGNITION_PROFILE`) is folded into `--profile` by the bin's
//! `apply_env_defaults`; the URL env overlay lives here ([`apply_env_overlay`]);
//! auth env resolution lives in [`secret`].

pub mod profile;
pub mod secret;

pub use profile::{AuthRef, Config, Profile, RigConfig, RigEntry, UiConfig};
pub use secret::{
    BasicEnvStore, Credential, EnvStore, KeyringStore, Secret, SecretStore, resolve_secret,
};

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

use crate::error::CoreError;

/// Serializes env-var mutation across this crate's unit tests: env is
/// process-global and lib tests run in parallel threads (edition 2024 makes
/// `set_var` unsafe for exactly this reason — under this lock it is sound).
#[cfg(test)]
pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Config file location: `IGNITION_CLI_CONFIG` env override first, the
/// platform config dir second.
pub fn config_path() -> PathBuf {
    std::env::var_os("IGNITION_CLI_CONFIG")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            let dirs = directories::ProjectDirs::from("", "", "ignition-cli")
                .expect("no home directory discoverable");
            dirs.config_dir().join("config.toml")
        })
}

/// Load config from `path`. A missing file is a fresh install, NOT an error
/// (`version` must work day one). Unreadable or invalid TOML is
/// [`CoreError::ConfigInvalid`] (exit 3) naming the path. Unknown keys WARN
/// (tracing) and are otherwise tolerated — no `deny_unknown_fields`, ever
/// (Pitfall 7). Sub-second `poll_interval_secs` is REFUSED (exit 3,
/// `poll_interval_too_small`) — the strict path.
pub fn load(path: &Path) -> Result<Config, CoreError> {
    load_inner(path, true)
}

/// The TUI's load entry point (08-01, TUIX-05): identical parse and
/// lenient extraction to [`load`], but a clamp violation confined to the
/// NEW schema surface does NOT error — it warns carrying the same
/// `poll_interval_too_small` slug/message, substitutes the default
/// cadence, and returns Ok.
///
/// Contract: schema-surface failures degrade with a warning; resolution
/// failures are fatal — the TUI is an authed cockpit. Raw TOML parse
/// failures, profile deserialize failures (e.g. a broken profile URL),
/// and selection failures still hard-error through the frozen
/// `config_invalid` exit-3 taxonomy: a config that cannot name a
/// reachable profile cannot start the cockpit.
pub fn load_for_tui(path: &Path) -> Result<Config, CoreError> {
    load_inner(path, false)
}

/// Shared body of [`load`] / [`load_for_tui`]: everything is common
/// except the clamp's strictness.
fn load_inner(path: &Path, strict_clamp: bool) -> Result<Config, CoreError> {
    let raw = match std::fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(Config::default());
        }
        Err(err) => {
            return Err(CoreError::ConfigInvalid {
                reason: format!("cannot read {}: {err}", path.display()),
            });
        }
    };
    if raw.trim().is_empty() {
        return Ok(Config::default());
    }
    warn_unknown_keys(&raw);
    let mut config: Config = toml::from_str(&raw).map_err(|err| CoreError::ConfigInvalid {
        reason: format!("{}: {err}", path.display()),
    })?;
    if strict_clamp {
        validate(&config)?;
    } else {
        degrade_clamp_violations(&mut config);
    }
    Ok(config)
}

/// Post-deserialize validation — the sub-second clamp (08-01, TUIX-05):
/// `poll_interval_secs = 0` is REFUSED (exit 3, `poll_interval_too_small`)
/// rather than silently honoring a cadence that hammers the gateway. The
/// FIRST offending profile in BTreeMap order is named (deterministic).
/// Everything else — including the lenient-degraded defaults — passes.
fn validate(config: &Config) -> Result<(), CoreError> {
    for (name, profile) in &config.profiles {
        if profile.poll_interval_secs == Some(0) {
            return Err(CoreError::PollIntervalTooSmall {
                profile: name.clone(),
            });
        }
    }
    Ok(())
}

/// The [`load_for_tui`] half of the clamp: substitute the default cadence
/// for every sub-second value, warning with the SAME
/// `poll_interval_too_small` slug/message the strict path refuses with.
/// Only the NEW schema surface degrades; nothing else is touched.
fn degrade_clamp_violations(config: &mut Config) {
    for (name, profile) in &mut config.profiles {
        if profile.poll_interval_secs == Some(0) {
            profile.poll_interval_secs = None;
            tracing::warn!(
                slug = "poll_interval_too_small",
                profile = %name,
                "poll_interval_secs must be >= 1 (sub-second polling refused) — using the default cadence"
            );
        }
    }
}

const KNOWN_TOP_LEVEL: &[&str] = &["active", "profiles", "rig", "rigs", "ui"];
const KNOWN_PROFILE_KEYS: &[&str] = &[
    "url",
    "label",
    "ssl_verify",
    "auth",
    "webdev_secret",
    "poll_interval_secs",
];
const KNOWN_AUTH_KEYS: &[&str] = &["token_env", "keyring", "user_env", "password_env"];

/// Warn (never fail) about config keys a future CLI version might
/// understand. Invalid TOML is skipped here — [`load`] reports it properly.
fn warn_unknown_keys(raw: &str) {
    let Ok(table) = raw.parse::<toml::Table>() else {
        return;
    };
    for (key, value) in &table {
        if !KNOWN_TOP_LEVEL.contains(&key.as_str()) {
            tracing::warn!(key = %key, "unknown config key (ignored)");
        }
        if key != "profiles" {
            continue;
        }
        let Some(profiles) = value.as_table() else {
            continue;
        };
        for (name, profile_value) in profiles {
            let Some(profile_table) = profile_value.as_table() else {
                continue;
            };
            for (profile_key, auth_value) in profile_table {
                if !KNOWN_PROFILE_KEYS.contains(&profile_key.as_str()) {
                    tracing::warn!(profile = %name, key = %profile_key, "unknown profile key (ignored)");
                }
                if profile_key == "auth"
                    && let Some(auth_table) = auth_value.as_table()
                {
                    for auth_key in auth_table.keys() {
                        if !KNOWN_AUTH_KEYS.contains(&auth_key.as_str()) {
                            tracing::warn!(profile = %name, key = auth_key, "unknown auth key (ignored)");
                        }
                    }
                }
            }
        }
    }
}

/// Persist config to `path`, creating parent dirs. The file is written —
/// and re-asserted — with 0600 permissions on unix (Pitfall 3.6
/// prevention, verified by test).
pub fn save(path: &Path, config: &Config) -> Result<(), CoreError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|err| CoreError::ConfigInvalid {
            reason: format!("cannot create {}: {err}", parent.display()),
        })?;
    }
    let contents = toml::to_string_pretty(config).map_err(|err| CoreError::ConfigInvalid {
        reason: format!("cannot serialize config: {err}"),
    })?;
    std::fs::write(path, contents).map_err(|err| CoreError::ConfigInvalid {
        reason: format!("cannot write {}: {err}", path.display()),
    })?;
    enforce_0600(path)
}

/// Re-assert 0600 even when the file already existed with looser perms
/// (`OpenOptions::mode` only applies at creation).
#[cfg(unix)]
fn enforce_0600(path: &Path) -> Result<(), CoreError> {
    use std::os::unix::fs::PermissionsExt;

    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|err| {
        CoreError::ConfigInvalid {
            reason: format!("cannot set 0600 on {}: {err}", path.display()),
        }
    })
}

#[cfg(not(unix))]
fn enforce_0600(_path: &Path) -> Result<(), CoreError> {
    Ok(())
}

/// Env overlay (the `IGNITION_*` half of the LOCKED precedence): when
/// `IGNITION_URL` is set it overrides the selected profile's URL. Profile
/// selection env (`IGNITION_PROFILE`) is folded into the `--profile` flag by
/// the bin; auth env resolution lives in [`secret`] — one concern per home.
pub fn apply_env_overlay(config: &mut Config, selected_profile: Option<&str>) {
    let Some(name) = selected_profile else { return };
    let Ok(url_string) = std::env::var("IGNITION_URL") else {
        return;
    };
    if url_string.is_empty() {
        return;
    }
    let Ok(url) = url::Url::parse(&url_string) else {
        tracing::warn!(url = %url_string, "IGNITION_URL is not a valid URL; ignoring");
        return;
    };
    if let Some(profile) = config.profiles.get_mut(name) {
        profile.url = url;
    }
}

/// Resolve which profile a command targets: flag (which already contains
/// `IGNITION_PROFILE` via the bin's env-defaults step) > `config.active`.
///
/// Unknown name → [`CoreError::ProfileNotFound`] (exit 3). Nothing found →
/// `Ok(None)` — callers decide whether `None` is an error (gateway
/// commands: yes, via [`CoreError::NoActiveProfile`]; `version` and
/// `profile list` tolerate it).
pub fn resolve_selection(
    config: &Config,
    flag: Option<&str>,
) -> Result<Option<(String, Profile)>, CoreError> {
    let name = match flag.map(str::to_owned).or_else(|| config.active.clone()) {
        Some(name) => name,
        None => return Ok(None),
    };
    match config.profiles.get(&name) {
        Some(profile) => Ok(Some((name, profile.clone()))),
        None => Err(CoreError::ProfileNotFound {
            name,
            known: config.profiles.keys().cloned().collect(),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Config, Profile, apply_env_overlay, config_path, load, load_for_tui, resolve_selection,
        save,
    };
    use crate::config::AuthRef;
    use crate::config::ENV_LOCK;
    use crate::error::CoreError;

    use std::path::PathBuf;

    fn temp_config_path() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        (dir, path)
    }

    fn sample_config() -> Config {
        let mut config = Config {
            active: Some("dev".into()),
            ..Config::default()
        };
        config.profiles.insert(
            "dev".into(),
            Profile {
                url: "http://localhost:9088/".parse().expect("url"),
                label: Some("Dev rig".into()),
                ssl_verify: true,
                auth: AuthRef::TokenEnv {
                    token_env: "IGNITION_TOKEN".into(),
                },
                webdev_secret: None,
                poll_interval_secs: None,
            },
        );
        config.profiles.insert(
            "prod".into(),
            Profile {
                url: "https://gw.example.com:8443/".parse().expect("url"),
                label: None,
                ssl_verify: true,
                auth: AuthRef::Keyring {
                    keyring: "profile:prod".into(),
                },
                webdev_secret: None,
                poll_interval_secs: None,
            },
        );
        config
    }

    /// Save → load round-trips exactly, and the on-disk TOML omits `label`
    /// when unset (`skip_serializing_if` proven at the file level).
    #[test]
    fn round_trip_save_load() {
        let (_dir, path) = temp_config_path();
        let config = sample_config();

        save(&path, &config).expect("save");
        let reloaded = load(&path).expect("load");
        assert_eq!(reloaded, config, "round trip must be lossless");

        let raw = std::fs::read_to_string(&path).expect("read raw");
        assert!(raw.contains("label = \"Dev rig\""));
        let prod_section = raw
            .split("[profiles.prod]")
            .nth(1)
            .expect("prod section serialized");
        assert!(
            !prod_section.contains("label"),
            "unset label must not be serialized: {prod_section}",
        );
    }

    /// Config is written with 0600 perms — and re-asserted on overwrite
    /// even if something loosened them (Pitfall 3.6 prevention).
    #[test]
    #[cfg(unix)]
    fn save_enforces_0600_and_creates_parents() {
        use std::os::unix::fs::PermissionsExt;

        let (_dir, path) = temp_config_path();
        let nested = path.parent().unwrap().join("nested/deeper/config.toml");

        save(&nested, &sample_config()).expect("save creates parent dirs");
        let mode = std::fs::metadata(&nested)
            .expect("metadata")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600, "fresh config must be 0600");

        // Loosen, save again → still 0600 afterwards.
        std::fs::set_permissions(&nested, std::fs::Permissions::from_mode(0o644)).expect("loosen");
        save(&nested, &sample_config()).expect("save again");
        let mode = std::fs::metadata(&nested)
            .expect("metadata")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600, "overwrite must re-assert 0600");
    }

    /// Unknown TOML keys warn but do NOT fail the load (Pitfall 7).
    #[test]
    fn unknown_keys_warn_but_do_not_fail() {
        let (_dir, path) = temp_config_path();
        std::fs::write(
            &path,
            r#"
future_top_level = "whatever"
active = "dev"

[profiles.dev]
url = "http://localhost:9088/"
future_profile_key = 42

[profiles.dev.auth]
token_env = "IGNITION_TOKEN"
future_auth_key = "x"
"#,
        )
        .expect("write");

        let config = load(&path).expect("unknown keys must not fail the load");
        assert_eq!(config.active.as_deref(), Some("dev"));
        assert!(config.profiles.contains_key("dev"));
    }

    /// Warn-silent pin (TUIX-05): the NEW schema keys (`ui`, `poll_interval_secs`)
    /// must be on the warn-lists so loading a config that carries them emits
    /// NO unknown-key warning. Membership asserted against the private lists —
    /// the lists ARE the warning behavior.
    #[test]
    fn new_schema_keys_are_warn_silent() {
        assert!(
            super::KNOWN_TOP_LEVEL.contains(&"ui"),
            "KNOWN_TOP_LEVEL must carry \"ui\""
        );
        assert!(
            super::KNOWN_PROFILE_KEYS.contains(&"poll_interval_secs"),
            "KNOWN_PROFILE_KEYS must carry \"poll_interval_secs\""
        );

        // And a config carrying both loads cleanly (behavioral half).
        let (_dir, path) = temp_config_path();
        std::fs::write(
            &path,
            r#"
[ui]
theme = "dark"

[profiles.dev]
url = "http://localhost:9088/"
poll_interval_secs = 10
"#,
        )
        .expect("write");
        let config = load(&path).expect("new keys must not fail the load");
        assert_eq!(config.ui.theme.as_deref(), Some("dark"));
        assert_eq!(config.profiles["dev"].poll_interval_secs, Some(10));
    }

    /// The sub-second clamp (08-01): `poll_interval_secs = 0` is refused
    /// with the additive slug on the config class — exit 3, never a new
    /// exit code.
    #[test]
    fn poll_interval_zero_is_refused() {
        let (_dir, path) = temp_config_path();
        std::fs::write(
            &path,
            "[profiles.dev]\nurl = \"http://localhost:9088/\"\npoll_interval_secs = 0\n",
        )
        .expect("write");

        let err = load(&path).expect_err("0 must be refused");
        assert_eq!(err.code(), "poll_interval_too_small");
        assert_eq!(err.exit_code(), 3, "config class — no new exit code");
        let message = err.to_string();
        assert!(
            message.contains("dev") && message.contains("sub-second"),
            "refusal must name the profile + the rule: {message}"
        );
        let hint = err.hint().expect("hint required");
        assert!(
            hint.contains("[profiles.dev]") && hint.contains("poll_interval_secs"),
            "hint must point at the profile key: {hint}"
        );
    }

    /// The floor is 1: `Some(1)` passes the clamp.
    #[test]
    fn poll_interval_one_is_the_floor() {
        let (_dir, path) = temp_config_path();
        std::fs::write(
            &path,
            "[profiles.dev]\nurl = \"http://localhost:9088/\"\npoll_interval_secs = 1\n",
        )
        .expect("write");

        let config = load(&path).expect("1 is the floor — must load");
        assert_eq!(config.profiles["dev"].poll_interval_secs, Some(1));
    }

    /// `load_for_tui` (08-01): a clamp violation on the NEW schema surface
    /// degrades to the default cadence with a warning — Ok, field None.
    #[test]
    fn load_for_tui_degrades_clamp_violation() {
        let (_dir, path) = temp_config_path();
        std::fs::write(
            &path,
            "[profiles.dev]\nurl = \"http://localhost:9088/\"\npoll_interval_secs = 0\n",
        )
        .expect("write");

        let config = load_for_tui(&path).expect("the TUI degrades the clamp instead of refusing");
        assert_eq!(
            config.profiles["dev"].poll_interval_secs, None,
            "sub-second value substituted with the default cadence"
        );
    }

    /// `load_for_tui` degrades ONLY the new-surface clamp: a broken
    /// profile URL is a RESOLUTION failure and stays fatal (the TUI is
    /// an authed cockpit — a config that cannot name a reachable profile
    /// cannot start it).
    #[test]
    fn load_for_tui_still_refuses_broken_profile_url() {
        let (_dir, path) = temp_config_path();
        std::fs::write(
            &path,
            "[profiles.dev]\nurl = \"not a url at all\"\npoll_interval_secs = 5\n",
        )
        .expect("write");

        let err = load_for_tui(&path).expect_err("broken profile url is fatal");
        assert_eq!(err.exit_code(), 3, "config_invalid class");
        assert_eq!(err.code(), "config_invalid");
    }

    /// `load_for_tui` on garbage TOML: raw parse failure stays fatal.
    #[test]
    fn load_for_tui_still_refuses_garbage_toml() {
        let (_dir, path) = temp_config_path();
        std::fs::write(&path, "this is ][ not toml\n").expect("write");

        let err = load_for_tui(&path).expect_err("garbage toml is fatal");
        assert_eq!(err.exit_code(), 3);
        assert_eq!(err.code(), "config_invalid");
    }

    /// Missing file is a fresh install, not an error; with no flag and no
    /// active profile, selection is `Ok(None)` (version/profile-list
    /// tolerate it).
    #[test]
    fn missing_file_and_no_selection_resolve_none() {
        let (_dir, path) = temp_config_path();
        assert!(!path.exists(), "fixture sanity");

        let config = load(&path).expect("missing file is not an error");
        assert_eq!(config, Config::default());

        let selection =
            resolve_selection(&config, None).expect("no active + no flag is not an error");
        assert!(selection.is_none());
    }

    /// Unknown profile → `ProfileNotFound` (exit 3) carrying the known
    /// profile list for the hint.
    #[test]
    fn unknown_profile_lists_known() {
        let config = sample_config();
        let err = resolve_selection(&config, Some("nope")).expect_err("unknown profile errors");
        match err {
            CoreError::ProfileNotFound {
                ref name,
                ref known,
            } => {
                assert_eq!(name, "nope");
                assert_eq!(known, &vec!["dev".to_string(), "prod".to_string()]);
            }
            other => panic!("wrong error class: {other}"),
        }
        assert_eq!(err.exit_code(), 3);
        let hint = err.hint().expect("hint");
        assert!(
            hint.contains("dev") && hint.contains("prod"),
            "hint names knowns: {hint}"
        );
    }

    /// Flag > active: an explicit flag selects a non-active profile.
    #[test]
    fn selection_flag_beats_active() {
        let config = sample_config(); // active = dev
        let (name, profile) = resolve_selection(&config, Some("prod"))
            .expect("flag selects prod")
            .expect("some");
        assert_eq!(name, "prod");
        assert_eq!(
            profile.auth,
            AuthRef::Keyring {
                keyring: "profile:prod".into()
            }
        );
    }

    /// `IGNITION_URL` overrides the SELECTED profile only (env overlay
    /// scoped, per the LOCKED precedence).
    #[test]
    fn env_overlay_overrides_selected_profile_url() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; restored before return.
        unsafe { std::env::set_var("IGNITION_URL", "http://override.example:7000") };

        let mut config = sample_config();
        apply_env_overlay(&mut config, Some("dev"));
        assert_eq!(
            config.profiles["dev"].url.as_str(),
            "http://override.example:7000/",
            "selected profile URL overridden",
        );
        assert_eq!(
            config.profiles["prod"].url.as_str(),
            "https://gw.example.com:8443/",
            "other profiles untouched",
        );

        // No selection → no-op even with the env set.
        let mut config = sample_config();
        apply_env_overlay(&mut config, None);
        assert_eq!(
            config.profiles["dev"].url.as_str(),
            "http://localhost:9088/",
            "no selected profile → overlay is a no-op",
        );

        // SAFETY: single-threaded under ENV_LOCK.
        unsafe { std::env::remove_var("IGNITION_URL") };
    }

    /// `IGNITION_CLI_CONFIG` wins over the platform path; without it, the
    /// platform path ends in `config.toml`.
    #[test]
    fn config_path_env_override_first() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        let dir = tempfile::tempdir().expect("tempdir");
        let override_path = dir.path().join("my-config.toml");

        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe { std::env::set_var("IGNITION_CLI_CONFIG", &override_path) };
        assert_eq!(config_path(), override_path, "env override wins");
        // SAFETY: single-threaded under ENV_LOCK.
        unsafe { std::env::remove_var("IGNITION_CLI_CONFIG") };

        assert!(
            config_path().ends_with("config.toml"),
            "platform fallback lands on config.toml: {}",
            config_path().display(),
        );
    }
}