ignition-core 1.6.4

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
//! Secrets: the `Secret` newtype (type-level redaction), the `SecretStore`
//! seam, and env-first resolution (research Pattern 3 — the STATE.md keyring
//! blocker resolution).
//!
//! Resolution order (auth-shape-conditional as of quick/260920-iti —
//! supersedes the old unconditional "LOCKED (CORE-02 must-have)" fallback):
//!
//! 1. `IGNITION_TOKEN_<PROFILE_UP>` — the universal explicit override,
//!    EVERY auth shape.
//! 2. the profile's own `token_env` var — `TokenEnv` profiles only.
//! 3. bare `IGNITION_TOKEN` — ONLY a profile whose `auth` equals
//!    `AuthRef::default()`, i.e. no `auth` key in the TOML at all.
//! 4. keyring entry `ignition-cli` / `profile:<name>` — every profile,
//!    UNCONDITIONALLY.
//! 5. the profile's own `user_env`/`password_env` — `Basic` profiles only.
//! 6. bare `IGNITION_USER` + `IGNITION_PASSWORD` — a default-auth profile,
//!    or a `Basic` profile whose own named vars are unset.
//!
//! The SEQUENCE above is unchanged from the original design; what changed
//! is that steps 3 and 6 — the two rungs naming NO profile — became
//! conditional on the profile's declared auth shape, gated by
//! [`is_generic_default`]. A `Keyring` or `Basic` profile (or a `TokenEnv`
//! profile naming some OTHER var) no longer falls through to a foreign
//! generic credential; it resolves `Ok(None)` from these two rungs and
//! lets the next store answer. `KeyringStore` stays UNCONDITIONAL: its
//! lookup is already profile-named (`profile:<name>`), so it cannot serve
//! one profile's credential to another, and a token-env profile simply has
//! no entry there (`Ok(None)`) — gating it would break the headless/adopt
//! interplay for no safety gain.
//!
//! The order lives in the STORE CHAIN (see the unit tests and, from 01-04,
//! the dispatch construction site) — which is why the basic env pair is a
//! separate [`BasicEnvStore`] placed AFTER [`KeyringStore`]: env tokens
//! first, keyring second, basic env last.
//!
//! The env-first order means default CI and tests never need a secret
//! service at all; `KeyringStore` fails soft (warn + skip) wherever no OS
//! keyring exists (headless Linux without D-Bus — keyring-rs fails fast at
//! `Entry::new`, never hangs).

use crate::config::AuthRef;
use crate::error::CoreError;

/// A value that must never render. NO `Serialize` impl exists on purpose
/// (type-level redaction: it cannot appear in JSON output); `Debug`/`Display`
/// render `***` so tracing logs are safe by construction (CORE-02).
#[derive(Clone)]
pub struct Secret(String);

impl std::fmt::Debug for Secret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Secret(***)")
    }
}

impl std::fmt::Display for Secret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("***")
    }
}

impl Secret {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// The ONLY way to read the value — grep-auditable: the single future
    /// read site is the reqwest header construction in 01-04.
    pub fn expose(&self) -> &str {
        &self.0
    }
}

/// A resolved credential: token OR basic pair — never both (that rule is
/// enforced at the header-construction site in 01-04).
#[derive(Debug, Clone)]
pub enum Credential {
    /// Bearer-style API token.
    Token(Secret),
    /// Basic-auth user/password pair.
    Basic(Secret, Secret),
}

/// One place to look for a credential. `Ok(None)` = not found here, try the
/// next store; `Err` = found-but-unreadable (surface with hint).
pub trait SecretStore: Send + Sync {
    fn resolve(&self, profile: &str, auth: &AuthRef) -> Result<Option<Credential>, CoreError>;
}

fn env_var(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|value| !value.is_empty())
}

/// True when a profile declared no `auth` block at all — the ONLY shape
/// entitled to the two generic (profile-less) env rungs. An equality test
/// against `AuthRef::default()`, not a restated `"IGNITION_TOKEN"` literal:
/// `profile.rs`'s `Default` impl keeps that string's single home.
fn is_generic_default(auth: &AuthRef) -> bool {
    *auth == AuthRef::default()
}

/// Token env lookups: `IGNITION_TOKEN_<PROFILE_UP>` (profile uppercased,
/// non-alphanumeric → `_`, EVERY auth shape) → the profile's own
/// `token_env` var (`TokenEnv` profiles only) → bare `IGNITION_TOKEN`
/// (ONLY a profile whose `auth` is `AuthRef::default()` — see
/// [`is_generic_default`]). A `Keyring` or `Basic` profile, or a
/// `TokenEnv` profile naming any other variable, falls through to
/// `Ok(None)` here and lets the next store in the chain answer.
pub struct EnvStore;

impl SecretStore for EnvStore {
    fn resolve(&self, profile: &str, auth: &AuthRef) -> Result<Option<Credential>, CoreError> {
        let specific = format!("IGNITION_TOKEN_{}", profile_env_suffix(profile));
        if let Some(token) = env_var(&specific) {
            return Ok(Some(Credential::Token(Secret::new(token))));
        }
        if let AuthRef::TokenEnv { token_env } = auth
            && let Some(token) = env_var(token_env)
        {
            return Ok(Some(Credential::Token(Secret::new(token))));
        }
        if is_generic_default(auth)
            && let Some(token) = env_var("IGNITION_TOKEN")
        {
            return Ok(Some(Credential::Token(Secret::new(token))));
        }
        Ok(None)
    }
}

/// Profile name → env-var-safe uppercase suffix: non-alphanumeric
/// characters become `_` (`my-rig` → `MY_RIG`). `pub(crate)` since
/// ADOPT-02: the adopt action names the fallback env var with the
/// SAME rule (one home — never restated).
pub(crate) fn profile_env_suffix(profile: &str) -> String {
    profile
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_uppercase()
            } else {
                '_'
            }
        })
        .collect()
}

/// Reads a two-var credential pair (user, password); `None` unless BOTH
/// are set and non-empty — a lone user is never a credential. Shared by
/// both the named-pair and generic-pair reads in [`BasicEnvStore`].
fn env_pair_credential(user_var: &str, password_var: &str) -> Option<Credential> {
    match (env_var(user_var), env_var(password_var)) {
        (Some(user), Some(password)) => {
            Some(Credential::Basic(Secret::new(user), Secret::new(password)))
        }
        _ => None,
    }
}

/// `IGNITION_USER` + `IGNITION_PASSWORD` basic pair — LAST in the
/// resolution order (after keyring), which is why it is a separate store
/// from [`EnvStore`]: the chain, not the struct, encodes the order. The
/// generic pair is auth-shape-conditional too: a `Basic` profile's own
/// `user_env`/`password_env` are read first, falling back to the generic
/// pair only when those named vars are unset; a default-auth profile
/// (no `auth` block) reads the generic pair directly; any other shape
/// (`Keyring`, or `TokenEnv` naming its own var) resolves `Ok(None)`
/// without touching the environment at all.
pub struct BasicEnvStore;

impl SecretStore for BasicEnvStore {
    fn resolve(&self, _profile: &str, auth: &AuthRef) -> Result<Option<Credential>, CoreError> {
        if let AuthRef::Basic {
            user_env,
            password_env,
        } = auth
        {
            if let Some(credential) = env_pair_credential(user_env, password_env) {
                return Ok(Some(credential));
            }
            return Ok(env_pair_credential("IGNITION_USER", "IGNITION_PASSWORD"));
        }
        if is_generic_default(auth) {
            return Ok(env_pair_credential("IGNITION_USER", "IGNITION_PASSWORD"));
        }
        Ok(None)
    }
}

/// OS keyring lookup: service `ignition-cli`, user `profile:<name>`.
///
/// ANY `Entry::new` failure → `tracing::debug!` + `Ok(None)` (store
/// unavailable — headless Linux without D-Bus is an EXPECTED condition,
/// not an anomaly: skip, never fatal, never hang; keyring-rs fails fast
/// at construction. debug, not warn, so headless hosts don't get a
/// non-JSON log line on stderr ahead of every JSON error envelope).
/// A live entry that exists but cannot be read surfaces as `Err`
/// (found-but-unreadable — THAT warns).
pub struct KeyringStore;

/// Keyring coordinates for a profile: fixed service, `profile:<name>` user.
fn keyring_entry(profile: &str) -> Result<keyring::Entry, keyring::Error> {
    keyring::Entry::new("ignition-cli", &format!("profile:{profile}"))
}

impl SecretStore for KeyringStore {
    fn resolve(&self, profile: &str, _auth: &AuthRef) -> Result<Option<Credential>, CoreError> {
        let entry = match keyring_entry(profile) {
            Ok(entry) => entry,
            Err(err) => {
                tracing::debug!(error = %err, profile, "keyring unavailable; skipping");
                return Ok(None);
            }
        };
        match entry.get_password() {
            Ok(password) => Ok(Some(Credential::Token(Secret::new(password)))),
            Err(keyring::Error::NoEntry) => Ok(None),
            Err(err) => {
                tracing::warn!(error = %err, profile, "keyring entry unreadable");
                Err(CoreError::SecretUnavailable {
                    profile: profile.to_string(),
                })
            }
        }
    }
}

impl KeyringStore {
    /// Store a token for `profile` in the OS keyring. Unlike [`SecretStore::resolve`],
    /// a SET failure is an error (writing requires a working store) — used by
    /// future `profile add --keyring` flows and the keyring smoke test.
    pub fn set(&self, profile: &str, secret: &Secret) -> Result<(), CoreError> {
        let entry = keyring_entry(profile).map_err(|_| CoreError::SecretUnavailable {
            profile: profile.to_string(),
        })?;
        entry
            .set_password(secret.expose())
            .map_err(|_| CoreError::SecretUnavailable {
                profile: profile.to_string(),
            })
    }

    /// Delete the keyring entry for `profile`; a missing entry is success
    /// (idempotent).
    pub fn delete(&self, profile: &str) -> Result<(), CoreError> {
        let entry = keyring_entry(profile).map_err(|_| CoreError::SecretUnavailable {
            profile: profile.to_string(),
        })?;
        match entry.delete_credential() {
            Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
            Err(_) => Err(CoreError::SecretUnavailable {
                profile: profile.to_string(),
            }),
        }
    }
}

/// First store to yield a credential wins; exhausted →
/// [`CoreError::SecretUnavailable`] (exit 3) whose hint names the env-var
/// path — the supported headless route.
pub fn resolve_secret(
    profile: &str,
    auth: &AuthRef,
    stores: &[Box<dyn SecretStore>],
) -> Result<Credential, CoreError> {
    for store in stores {
        match store.resolve(profile, auth)? {
            Some(credential) => return Ok(credential),
            None => continue,
        }
    }
    Err(CoreError::SecretUnavailable {
        profile: profile.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::{
        BasicEnvStore, Credential, EnvStore, KeyringStore, Secret, SecretStore, resolve_secret,
    };
    use crate::config::AuthRef;
    use crate::config::ENV_LOCK;
    use crate::error::CoreError;

    /// Test double for chain-order tests: yields a fixed answer.
    struct FixedStore(Result<Option<Credential>, ()>);
    impl SecretStore for FixedStore {
        fn resolve(
            &self,
            _profile: &str,
            _auth: &AuthRef,
        ) -> Result<Option<Credential>, CoreError> {
            self.0.clone().map_err(|()| CoreError::SecretUnavailable {
                profile: "fixed".into(),
            })
        }
    }

    /// CORE-02 type-level redaction: Debug/Display never leak the value.
    #[test]
    fn secret_renders_redacted() {
        let secret = Secret::new("CANARY-t0k3n");
        assert_eq!(format!("{secret:?}"), "Secret(***)");
        assert_eq!(format!("{secret}"), "***");
        assert_eq!(
            secret.expose(),
            "CANARY-t0k3n",
            "expose is the only read path"
        );
    }

    /// Order step 1: `IGNITION_TOKEN_<PROFILE_UP>` beats both the
    /// auth-ref var and the generic token.
    #[test]
    fn env_store_profile_specific_token_wins() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_TOKEN_DEV", "specific");
            std::env::set_var("IGNITION_TOKEN", "generic");
        }
        let auth = AuthRef::TokenEnv {
            token_env: "MY_TOKEN".into(),
        };
        let credential = EnvStore
            .resolve("dev", &auth)
            .expect("resolve")
            .expect("some");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "specific");
        // SAFETY: single-threaded under ENV_LOCK.
        unsafe {
            std::env::remove_var("IGNITION_TOKEN_DEV");
            std::env::remove_var("IGNITION_TOKEN");
        }
    }

    /// Order step 2: the profile's `token_env` var beats the generic one;
    /// non-alphanumeric profile chars map to `_` in the specific var name.
    #[test]
    fn env_store_token_env_ref_and_suffix_mapping() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("MY_TOKEN", "from-ref");
            std::env::set_var("IGNITION_TOKEN", "generic");
            std::env::set_var("IGNITION_TOKEN_MY_RIG", "rig-specific");
        }

        let auth = AuthRef::TokenEnv {
            token_env: "MY_TOKEN".into(),
        };
        let credential = EnvStore
            .resolve("dev", &auth)
            .expect("resolve")
            .expect("some");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "from-ref", "token_env ref beats generic");

        let credential = EnvStore
            .resolve("my-rig", &auth)
            .expect("resolve")
            .expect("some");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(
            token.expose(),
            "rig-specific",
            "hyphen maps to _ then uppercases"
        );

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

    /// Order step 5: the basic env pair needs BOTH vars; a lone user is not
    /// a credential.
    #[test]
    fn basic_env_store_requires_both_vars() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_USER", "admin");
            std::env::remove_var("IGNITION_PASSWORD");
        }
        assert!(
            BasicEnvStore
                .resolve("dev", &AuthRef::default())
                .expect("resolve")
                .is_none()
        );

        // SAFETY: single-threaded under ENV_LOCK.
        unsafe {
            std::env::set_var("IGNITION_PASSWORD", "pw");
        }
        let credential = BasicEnvStore
            .resolve("dev", &AuthRef::default())
            .expect("resolve")
            .expect("some with both vars");
        let Credential::Basic(user, password) = credential else {
            panic!("expected basic credential");
        };
        assert_eq!(user.expose(), "admin");
        assert_eq!(password.expose(), "pw");

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

    /// The LOCKED chain order end-to-end (env tokens → keyring-shaped store
    /// → basic env) via test doubles, plus first-Some-wins and exhaustion.
    #[test]
    fn resolve_secret_chain_order_first_some_wins_and_exhaustion() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_TOKEN", "env-token");
            std::env::set_var("IGNITION_USER", "admin");
            std::env::set_var("IGNITION_PASSWORD", "pw");
        }
        let auth = AuthRef::default();

        // A store shaped like a populated keyring sits BETWEEN EnvStore and
        // BasicEnvStore in the chain; the env token must still win (env-first).
        let keyring_like = FixedStore(Ok(Some(Credential::Token(Secret::new("keyring-token")))));
        let chain: Vec<Box<dyn SecretStore>> = vec![
            Box::new(EnvStore),
            Box::new(keyring_like),
            Box::new(BasicEnvStore),
        ];
        let credential = resolve_secret("dev", &auth, &chain).expect("resolve");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "env-token");

        // Keyring-shaped store wins over basic env (order: keyring before USER/PASSWORD).
        let keyring_like = FixedStore(Ok(Some(Credential::Token(Secret::new("keyring-token")))));
        let chain: Vec<Box<dyn SecretStore>> = vec![
            Box::new(EnvStore),
            Box::new(keyring_like),
            Box::new(BasicEnvStore),
        ];
        // SAFETY: single-threaded under ENV_LOCK.
        unsafe { std::env::remove_var("IGNITION_TOKEN") };
        let credential = resolve_secret("dev", &auth, &chain).expect("resolve");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "keyring-token", "keyring beats basic env");

        // Basic env is the last resort.
        let chain: Vec<Box<dyn SecretStore>> = vec![Box::new(EnvStore), Box::new(BasicEnvStore)];
        let credential = resolve_secret("dev", &auth, &chain).expect("resolve");
        let Credential::Basic(user, _) = credential else {
            panic!("expected basic credential");
        };
        assert_eq!(user.expose(), "admin");

        // Exhausted → SecretUnavailable (exit 3) with the env-first hint.
        // SAFETY: single-threaded under ENV_LOCK.
        unsafe {
            std::env::remove_var("IGNITION_USER");
            std::env::remove_var("IGNITION_PASSWORD");
        }
        let err = resolve_secret("dev", &auth, &[]).expect_err("empty chain exhausts");
        assert!(matches!(err, CoreError::SecretUnavailable { .. }));
        assert_eq!(err.exit_code(), 3);
        assert!(
            err.hint().expect("hint").contains("IGNITION_TOKEN"),
            "hint names the env path: {}",
            err.hint().unwrap(),
        );
    }

    /// `KeyringStore` trait-level resolve is exercised ONLY by the
    /// `#[ignore]`-gated smoke test (Pitfall 8: unit tests never touch a
    /// real keychain). This test merely pins that the type exists at the
    /// chain type level without calling into the OS.
    #[test]
    fn keyring_store_is_constructible_without_side_effects() {
        let _store = KeyringStore;
    }

    /// T-iti-01 pin: the live bug, reproduced at the store level. A profile
    /// whose auth is `Keyring` must not receive a foreign bare
    /// `IGNITION_TOKEN` — the `ign adopt` → `ign --profile e2e status` →
    /// `auth_rejected` failure this plan closes.
    #[test]
    fn env_store_keyring_profile_skips_bare_generic_token() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_TOKEN", "foreign");
            std::env::remove_var("IGNITION_TOKEN_E2E");
        }
        let auth = AuthRef::Keyring {
            keyring: "profile:e2e".into(),
        };
        let result = EnvStore.resolve("e2e", &auth).expect("resolve");
        assert!(
            result.is_none(),
            "a keyring profile must skip the bare generic token"
        );

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

    /// Step 1 stays universal: `IGNITION_TOKEN_<PROFILE_UP>` still overrides
    /// even a keyring-shaped profile.
    #[test]
    fn env_store_profile_specific_token_overrides_keyring_profile() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_TOKEN", "foreign");
            std::env::set_var("IGNITION_TOKEN_E2E", "specific");
        }
        let auth = AuthRef::Keyring {
            keyring: "profile:e2e".into(),
        };
        let credential = EnvStore
            .resolve("e2e", &auth)
            .expect("resolve")
            .expect("some");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "specific");

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

    /// The no-`auth`-block / `IGNITION_URL`-overlay path is pinned
    /// unchanged: a default-auth profile still resolves the bare generic
    /// token.
    #[test]
    fn env_store_default_auth_still_uses_bare_generic_token() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_TOKEN", "generic");
            std::env::remove_var("IGNITION_TOKEN_DEV");
        }
        let credential = EnvStore
            .resolve("dev", &AuthRef::default())
            .expect("resolve")
            .expect("some");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "generic");

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

    /// A `TokenEnv` profile naming its OWN var must not fall back to the
    /// unrelated bare `IGNITION_TOKEN` when that named var is absent.
    #[test]
    fn env_store_named_token_env_skips_bare_generic() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::remove_var("MY_TOKEN");
            std::env::set_var("IGNITION_TOKEN", "generic");
            std::env::remove_var("IGNITION_TOKEN_DEV");
        }
        let auth = AuthRef::TokenEnv {
            token_env: "MY_TOKEN".into(),
        };
        let result = EnvStore.resolve("dev", &auth).expect("resolve");
        assert!(
            result.is_none(),
            "a named token_env profile must not fall back to the bare generic token"
        );

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

    /// T-iti-02 pin: a keyring-shaped profile must not receive the generic
    /// basic pair either.
    #[test]
    fn basic_env_store_skips_keyring_profile() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_USER", "admin");
            std::env::set_var("IGNITION_PASSWORD", "pw");
        }
        let auth = AuthRef::Keyring {
            keyring: "profile:e2e".into(),
        };
        let result = BasicEnvStore.resolve("e2e", &auth).expect("resolve");
        assert!(
            result.is_none(),
            "a keyring profile must skip the generic basic pair"
        );

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

    /// A `Basic` profile reads its OWN named vars first, falling back to
    /// the generic pair only when those named vars are unset.
    #[test]
    fn basic_env_store_prefers_profile_named_vars_then_generic_pair() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        let auth = AuthRef::Basic {
            user_env: "GW_USER".into(),
            password_env: "GW_PASS".into(),
        };

        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("GW_USER", "named-user");
            std::env::set_var("GW_PASS", "named-pass");
            std::env::remove_var("IGNITION_USER");
            std::env::remove_var("IGNITION_PASSWORD");
        }
        let credential = BasicEnvStore
            .resolve("dev", &auth)
            .expect("resolve")
            .expect("some via named vars");
        let Credential::Basic(user, password) = credential else {
            panic!("expected basic credential");
        };
        assert_eq!(user.expose(), "named-user");
        assert_eq!(password.expose(), "named-pass");

        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::remove_var("GW_USER");
            std::env::remove_var("GW_PASS");
            std::env::set_var("IGNITION_USER", "generic-user");
            std::env::set_var("IGNITION_PASSWORD", "generic-pass");
        }
        let credential = BasicEnvStore
            .resolve("dev", &auth)
            .expect("resolve")
            .expect("some via generic fallback");
        let Credential::Basic(user, password) = credential else {
            panic!("expected basic credential");
        };
        assert_eq!(user.expose(), "generic-user");
        assert_eq!(password.expose(), "generic-pass");

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

    /// The chain-level pin — the end-to-end shape of the live bug: a
    /// keyring profile with a populated keyring wins over a foreign
    /// generic env token AND a foreign generic basic pair.
    #[test]
    fn resolve_secret_keyring_profile_beats_foreign_generic_env() {
        let _lock = ENV_LOCK.lock().expect("env lock");
        // SAFETY: single-threaded under ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("IGNITION_TOKEN", "foreign-token");
            std::env::set_var("IGNITION_USER", "foreign-user");
            std::env::set_var("IGNITION_PASSWORD", "foreign-pass");
            std::env::remove_var("IGNITION_TOKEN_E2E");
        }
        let auth = AuthRef::Keyring {
            keyring: "profile:e2e".into(),
        };
        let keyring_like = FixedStore(Ok(Some(Credential::Token(Secret::new("keyring-token")))));
        let chain: Vec<Box<dyn SecretStore>> = vec![
            Box::new(EnvStore),
            Box::new(keyring_like),
            Box::new(BasicEnvStore),
        ];
        let credential = resolve_secret("e2e", &auth, &chain).expect("resolve");
        let Credential::Token(token) = credential else {
            panic!("expected token credential");
        };
        assert_eq!(token.expose(), "keyring-token");

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