Skip to main content

ignition_core/
session.rs

1//! The execution session — the ONE seam every auth/gateway-client
2//! resolution flows through (CORE-09).
3//!
4//! Naming: THIS is an "execution session" — a resolved profile name plus
5//! the gateway client it builds. It is NOT a gateway session; the
6//! unrelated `client::sessions` family models the GATEWAY's
7//! Designer/Perspective/Vision sessions. One word, two domains — the
8//! doc-comments everywhere else say "gateway session" when they mean
9//! that other thing.
10//!
11//! Choreography (LOCKED — copied verbatim from the duplicated resolution
12//! sites this seam replaces: main.rs's `resolve_profile_context` +
13//! `resolve_gateway_api` + `resolve_headerless_api` + `rig_gateway_client`,
14//! and the TUI's `context::resolve_from` + `rig_client_with`):
15//!
16//! 1. The `IGNITION_URL` env overlay is applied FIRST, scoped to the
17//!    WOULD-BE selection (flag > active) — `config::apply_env_overlay`.
18//! 2. THEN the selection resolves — `config::resolve_selection`
19//!    (flag > active; unknown name → `ProfileNotFound` with the known
20//!    profiles in the hint; nothing resolvable → `NoActiveProfile`,
21//!    exactly what main.rs's `Ok(None)` consumers do today).
22//! 3. THEN the secret chain (env tokens → keyring → basic pair) —
23//!    `config::resolve_secret` over the one chain built below. The
24//!    SEQUENCE is unchanged, but the two generic (profile-less) env
25//!    rungs are auth-shape-conditional as of quick/260920-iti — see
26//!    `config::secret`'s module header for the full statement.
27//!
28//! The client is built from the POST-OVERLAY profile — the research-
29//! locked precedence (flag > `IGNITION_URL` env > profile value) must
30//! hold at the construction site, not just in the config unit tests
31//! (main.rs:431's contract, preserved here verbatim).
32//!
33//! Three credential modes, one per real call-site family:
34//!
35//! - [`Session::resolve`] — REQUIRED credential (the authed reads: a
36//!   missing secret is `SecretUnavailable`, exit 3 — never degraded).
37//! - [`Session::resolve_degraded`] — the credential DEGRADES to `None`
38//!   when the chain exhausts (version / waits / doctor: these must run
39//!   without a secret; every other credential error still propagates).
40//! - [`Session::for_url`] — headerless-BY-CONSTRUCTION rig clients: a
41//!   caller-derived URL + explicit credential, no config read at all.
42//!
43//! Concrete-with-deref (PLANNER DECISION, research open question 4):
44//! the handle is `Arc<ReqwestGatewayApi>`, not `Arc<dyn GatewayApi>` —
45//! the TUI's workers/`ClientHandle` are concretely typed and Phase 8's
46//! goal is construction-site unification, not handle-type churn;
47//! dyn-widening rides Phase 14 where MCP actually needs dyn. [`Deref`]
48//! feeds every existing free-fn action over `&GatewayApi` unchanged —
49//! the `version()` dyn precedent (`actions/version.rs`) and the
50//! `rig_stream.rs` cast precedent both keep working.
51//!
52//! Redaction boundary UNCHANGED: [`Secret::expose`] stays confined to
53//! the client's `apply_auth` header site (CORE-02's grep-auditable
54//! rule). This module composes existing public config fns and
55//! introduces NO new exposure path.
56//!
57//! `IGNITION_PROFILE` is deliberately NOT read here: the bin folds it
58//! into `--profile` in exactly one place (`apply_env_defaults`), so the
59//! flag this seam receives is already the effective selection.
60
61use std::ops::Deref;
62use std::sync::Arc;
63
64use crate::client::ReqwestGatewayApi;
65use crate::config::{self, AuthRef, Config, Credential, Profile, SecretStore};
66use crate::error::CoreError;
67
68/// One resolved execution context: a named profile and the gateway
69/// client built from its POST-OVERLAY state. Construct through the three
70/// constructors — never by struct literal (the fields are the resolved
71/// choreography's output, not inputs).
72///
73/// Manual `Debug` (no derive): the client isn't `Debug` and must never
74/// be rendered credential-side — the profile NAME is the only safe
75/// field (the redaction discipline, CORE-02).
76pub struct Session {
77    profile: String,
78    url: url::Url,
79    credential_present: bool,
80    api: Arc<ReqwestGatewayApi>,
81}
82
83impl std::fmt::Debug for Session {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.debug_struct("Session")
86            .field("profile", &self.profile)
87            .field("api", &"ReqwestGatewayApi")
88            .finish()
89    }
90}
91
92impl Session {
93    /// Resolve through config: REQUIRED credential mode. Loads config
94    /// (`IGNITION_CLI_CONFIG` first, platform path second), applies the
95    /// env overlay scoped to the would-be selection, resolves the
96    /// selection, then walks the LOCKED secret chain with NO
97    /// degradation — a missing secret is `CoreError::SecretUnavailable`
98    /// (exit 3), correct for authed reads. Replaces main.rs's
99    /// `resolve_gateway_api` (and `named_profile_client`: per-side
100    /// resolution is just `resolve(Some(name))`).
101    pub fn resolve(profile_flag: Option<&str>) -> Result<Self, CoreError> {
102        let mut config = config::load(&config::config_path())?;
103        Self::resolve_loaded(&mut config, profile_flag).map(|(session, _)| session)
104    }
105
106    /// Resolve through a config the CALLER already loaded — the caller
107    /// owns the load policy, the seam keeps everything downstream
108    /// (overlay scoped to the selection → selection → LOCKED secret
109    /// chain → REQUIRED-credential construction). This is the cockpit's
110    /// entry point: the TUI loads with `config::load_for_tui`, whose
111    /// NEW-surface degradation contract (a schema typo warns and
112    /// defaults instead of killing startup) must apply BEFORE the seam
113    /// runs, while selection/auth failures stay fatal. Returns the
114    /// session AND the selected POST-OVERLAY profile — the url string
115    /// and cadence fields consumers like the cockpit display, which a
116    /// `Session` deliberately doesn't re-expose.
117    pub fn resolve_loaded(
118        config: &mut Config,
119        profile_flag: Option<&str>,
120    ) -> Result<(Self, Profile), CoreError> {
121        let (name, profile) = resolve_selected(config, profile_flag)?;
122        let credential = config::resolve_secret(&name, &profile.auth, &locked_secret_chain())?;
123        let api = ReqwestGatewayApi::new(&profile, Some(credential))?;
124        Ok((
125            Self {
126                profile: name,
127                url: profile.url.clone(),
128                credential_present: true,
129                api: Arc::new(api),
130            },
131            profile,
132        ))
133    }
134
135    /// Resolve ONE NAMED side of a multi-profile command through a
136    /// config the CALLER already loaded — the project diff/sync shape.
137    /// Verbatim port of main.rs's `named_profile_client`: the selection
138    /// runs against the caller's config with NO env overlay applied
139    /// (side B carries its own URL even while `IGNITION_URL` overlays
140    /// the envelope's active profile — the contract the diff/sync
141    /// goldens pin), then the LOCKED chain (required) and the client
142    /// construction. The caller's `name` rides the secret resolution
143    /// verbatim, and the impossible empty-selection arm stays
144    /// `CoreError::Internal` exactly as the original wrote it.
145    pub fn resolve_side(config: &mut Config, name: &str) -> Result<Self, CoreError> {
146        let Some((_resolved, profile)) = config::resolve_selection(config, Some(name))? else {
147            return Err(CoreError::Internal(
148                "a named profile selection resolved to nothing".to_string(),
149            ));
150        };
151        let credential = config::resolve_secret(name, &profile.auth, &locked_secret_chain())?;
152        let api = ReqwestGatewayApi::new(&profile, Some(credential))?;
153        Ok(Self {
154            profile: name.to_string(),
155            url: profile.url.clone(),
156            credential_present: true,
157            api: Arc::new(api),
158        })
159    }
160
161    /// Resolve through config with the credential DEGRADED to `None`
162    /// when the secret chain exhausts: `version` must not demand a
163    /// secret (gateway-info answers), the wait commands must keep
164    /// polling while auth is broken, the doctor diagnoses absent auth
165    /// for a living. Every OTHER credential error propagates (the
166    /// `resolve_secret_opt` behavior behind main.rs:431/760 and
167    /// `resolve_headerless_api`). Selection errors are NOT degraded:
168    /// no target is `NoActiveProfile`, as today.
169    pub fn resolve_degraded(profile_flag: Option<&str>) -> Result<Self, CoreError> {
170        let mut config = config::load(&config::config_path())?;
171        let (name, profile) = resolve_selected(&mut config, profile_flag)?;
172        let credential = resolve_secret_opt(&name, &profile.auth)?;
173        let credential_present = credential.is_some();
174        let api = ReqwestGatewayApi::new(&profile, credential)?;
175        Ok(Self {
176            profile: name,
177            url: profile.url.clone(),
178            credential_present,
179            api: Arc::new(api),
180        })
181    }
182
183    /// Resolve ONLY a credential for a selection — the adopt
184    /// composition path (ADOPT-03): the bootstrap resolves DEGRADED
185    /// (the OIDC dance needs no token), while the post-bootstrap
186    /// steps (`--project`/`--checkout`/`--bake`) need a working token
187    /// when the key step SKIPPED (the mint path already holds the
188    /// fresh key). Same overlay → selection → LOCKED chain as
189    /// [`Self::resolve_degraded`], no client construction.
190    pub fn resolve_credential_opt(
191        profile_flag: Option<&str>,
192    ) -> Result<Option<Credential>, CoreError> {
193        let mut config = config::load(&config::config_path())?;
194        let (name, profile) = resolve_selected(&mut config, profile_flag)?;
195        resolve_secret_opt(&name, &profile.auth)
196    }
197
198    /// Headerless-BY-CONSTRUCTION client for the rig family: a caller-
199    /// derived gateway URL (never a profile's), an explicit optional
200    /// credential, and the caller's `ssl_verify` (rig probes use
201    /// `false` — localhost probes against self-signed rig https are the
202    /// norm). No config is read and no secret is resolved. Replaces
203    /// main.rs's `rig_gateway_client` + the TUI's `rig_client_with`
204    /// (the URL DERIVATION stays at the call sites; only the
205    /// `ReqwestGatewayApi` construction moves behind this constructor —
206    /// no second client construction anywhere).
207    ///
208    /// Rig sessions carry NO profile: [`Self::profile_name`] returns
209    /// the empty string (callers translate to `None` where the output
210    /// model wants a profile echo).
211    pub fn for_url(
212        url: url::Url,
213        credential: Option<Credential>,
214        ssl_verify: bool,
215    ) -> Result<Self, CoreError> {
216        let profile = Profile {
217            url,
218            label: None,
219            ssl_verify,
220            auth: AuthRef::default(),
221            webdev_secret: None,
222            webdev_tag_delete_secret: None,
223            poll_interval_secs: None,
224        };
225        let credential_present = credential.is_some();
226        let api = ReqwestGatewayApi::new(&profile, credential)?;
227        Ok(Self {
228            profile: String::new(),
229            url: profile.url.clone(),
230            credential_present,
231            api: Arc::new(api),
232        })
233    }
234
235    /// The resolved profile's name — empty for [`Self::for_url`] rig
236    /// sessions (no profile exists).
237    pub fn profile_name(&self) -> &str {
238        &self.profile
239    }
240
241    /// The resolved profile's configured gateway URL — the POST-OVERLAY
242    /// value (flag > `IGNITION_URL` env > profile), i.e. exactly what the
243    /// session's client targets. Doctor's url check re-parses this raw
244    /// value: the honest diagnosis must describe the URL the client
245    /// ACTUALLY connects to, overlay included. For [`Self::for_url`] rig
246    /// sessions this is the caller-derived rig URL.
247    pub fn profile_url(&self) -> &url::Url {
248        &self.url
249    }
250
251    /// Whether a credential resolved into this session's client — the
252    /// doctor's `credential_present` flag (a MISSING credential is a
253    /// different diagnosis than an UNRECOGNIZED one; the degraded chain
254    /// decides, this accessor reports, and the secret itself never
255    /// crosses the seam). Always `true` for [`Self::resolve`]; the
256    /// caller's `Some`-ness for [`Self::for_url`].
257    pub fn credential_present(&self) -> bool {
258        self.credential_present
259    }
260
261    /// The gateway client, borrowed.
262    pub fn api(&self) -> &ReqwestGatewayApi {
263        &self.api
264    }
265
266    /// The gateway client as an owned `Arc` handle — the TUI's
267    /// workers/`ClientHandle` shape, without a second construction.
268    pub fn api_handle(&self) -> Arc<ReqwestGatewayApi> {
269        Arc::clone(&self.api)
270    }
271}
272
273/// Feeds every existing free-fn action over `&GatewayApi` unchanged:
274/// `version(&*session, …)` and friends work exactly as they did against
275/// a bare `ReqwestGatewayApi`.
276impl Deref for Session {
277    type Target = ReqwestGatewayApi;
278
279    fn deref(&self) -> &Self::Target {
280        &self.api
281    }
282}
283
284/// THE secret chain (env tokens → keyring → basic pair), built in
285/// exactly one place — the chain, not the structs, encodes the
286/// SEQUENCE (main.rs's private `secret_chain`, now shared). The two
287/// generic (profile-less) env rungs within it are auth-shape-conditional
288/// as of quick/260920-iti; `config::secret`'s module header states the
289/// full rule this chain enforces.
290fn locked_secret_chain() -> Vec<Box<dyn SecretStore>> {
291    vec![
292        Box::new(config::EnvStore),
293        Box::new(config::KeyringStore),
294        Box::new(config::BasicEnvStore),
295    ]
296}
297
298/// Overlay scoped to the WOULD-BE selection FIRST, then the selection —
299/// the verbatim `resolve_profile_context` / TUI `resolve_from`
300/// choreography: the `IGNITION_URL` env overlay targets the profile the
301/// command is ABOUT to select (flag > active), and only then does the
302/// selection resolve against the overlaid config. Nothing resolvable →
303/// `NoActiveProfile` (the main.rs `Ok(None)` consumer behavior — not a
304/// new error class).
305fn resolve_selected(
306    config: &mut config::Config,
307    flag: Option<&str>,
308) -> Result<(String, Profile), CoreError> {
309    let overlay_target = flag.map(str::to_string).or_else(|| config.active.clone());
310    config::apply_env_overlay(config, overlay_target.as_deref());
311    match config::resolve_selection(config, flag)? {
312        Some((name, profile)) => Ok((name, profile)),
313        None => Err(CoreError::NoActiveProfile),
314    }
315}
316
317/// Credential resolution degraded for non-authenticating consumers: the
318/// LOCKED chain with `SecretUnavailable` mapped to `Ok(None)` — every
319/// other credential error propagates (the main.rs `resolve_secret_opt`
320/// port, verbatim).
321fn resolve_secret_opt(profile: &str, auth: &AuthRef) -> Result<Option<Credential>, CoreError> {
322    config::resolve_secret(profile, auth, &locked_secret_chain())
323        .map(Some)
324        .or_else(|err| match err {
325            CoreError::SecretUnavailable { .. } => Ok(None),
326            other => Err(other),
327        })
328}
329
330#[cfg(test)]
331mod tests {
332    use super::{Session, resolve_selected};
333    use crate::client::GatewayApi;
334    use crate::config::ENV_LOCK;
335    use crate::error::CoreError;
336
337    /// The gateway-info JSON body — the one field every 8.3 gateway
338    /// answers with (`ignitionVersion`, the `version` alias tolerated).
339    fn info_body() -> serde_json::Value {
340        serde_json::json!({ "ignitionVersion": "8.3.6 (b2026042713)" })
341    }
342
343    /// Lowercased Debug dump of a recorded request's headers — the
344    /// status_contract.rs presence/absence assertion pattern.
345    fn headers_debug(request: &wiremock::Request) -> String {
346        format!("{:?}", request.headers).to_lowercase()
347    }
348
349    /// Write a config.toml into a tempdir and point
350    /// `IGNITION_CLI_CONFIG` at it. Caller holds `ENV_LOCK`.
351    fn isolate_config(dir: &tempfile::TempDir, toml: &str) {
352        let path = dir.path().join("config.toml");
353        std::fs::write(&path, toml).expect("write config fixture");
354        // SAFETY: single-threaded under ENV_LOCK; each test unsets the
355        // var before returning.
356        unsafe { std::env::set_var("IGNITION_CLI_CONFIG", &path) };
357    }
358
359    fn unset(name: &str) {
360        // SAFETY: single-threaded under ENV_LOCK.
361        unsafe { std::env::remove_var(name) };
362    }
363
364    /// Two-profile fixture: `a` active at `url_a`, `b` at `url_b`, both
365    /// on the generic `IGNITION_TOKEN` auth reference.
366    fn two_profile_toml(url_a: &str, url_b: &str) -> String {
367        format!(
368            r#"
369active = "a"
370
371[profiles.a]
372url = "{url_a}"
373
374[profiles.b]
375url = "{url_b}"
376"#
377        )
378    }
379
380    /// A scoped gateway-info mock — the guard records the requests that
381    /// actually arrived (the status_contract.rs pattern).
382    async fn mount_info(server: &wiremock::MockServer, expected: u64) -> wiremock::MockGuard {
383        wiremock::Mock::given(wiremock::matchers::method("GET"))
384            .and(wiremock::matchers::path("/data/api/v1/gateway-info"))
385            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(info_body()))
386            .expect(expected)
387            .mount_as_scoped(server)
388            .await
389    }
390
391    /// PRECEDENCE: `IGNITION_URL` overrides the SELECTED profile only —
392    /// select profile B by flag while the env carries the overlay URL;
393    /// the session's client must target the OVERLAY (mock_a) for the
394    /// selected profile, and a second session without the overlay env
395    /// targets B's OWN URL (mock_b).
396    ///
397    /// Env mutation stays inside the `ENV_LOCK` scope; the `await`ed
398    /// requests run AFTER the guard drops — the client snapshots URL +
399    /// credential at construction, so the env vars are already gone.
400    #[tokio::test]
401    async fn env_overlay_targets_the_selected_profile() {
402        let mock_a = wiremock::MockServer::start().await;
403        let mock_b = wiremock::MockServer::start().await;
404        let guard_a = mount_info(&mock_a, 1).await;
405        let guard_b = mount_info(&mock_b, 1).await;
406        let dir = tempfile::tempdir().expect("tempdir");
407
408        // Phase 1: overlay set → the session targets the overlay URL.
409        let session = {
410            let _lock = ENV_LOCK.lock().expect("env lock");
411            isolate_config(
412                &dir,
413                &two_profile_toml(mock_b.uri().as_str(), mock_b.uri().as_str()),
414            );
415            // SAFETY: single-threaded under ENV_LOCK.
416            unsafe { std::env::set_var("IGNITION_URL", mock_a.uri()) };
417            // SAFETY: single-threaded under ENV_LOCK.
418            unsafe { std::env::set_var("IGNITION_TOKEN", "overlay-token") };
419            let session = Session::resolve(Some("b")).expect("resolve selects b");
420            // SAFETY: single-threaded under ENV_LOCK.
421            unsafe { std::env::remove_var("IGNITION_URL") };
422            // SAFETY: single-threaded under ENV_LOCK.
423            unsafe { std::env::remove_var("IGNITION_TOKEN") };
424            session
425        };
426        assert_eq!(session.profile_name(), "b");
427        // The overlay URL (mock_a) answered for the selected profile —
428        // NOT the profile's own URL (also mock_b here).
429        let info = session.gateway_info().await.expect("overlay url answers");
430        assert_eq!(info.ignition_version, "8.3.6 (b2026042713)");
431        assert_eq!(
432            guard_a.received_requests().await.len(),
433            1,
434            "the env overlay URL took the request"
435        );
436        assert_eq!(
437            guard_b.received_requests().await.len(),
438            0,
439            "the profile's own URL stayed untouched while the overlay was set"
440        );
441
442        // Phase 2: overlay gone → the session targets B's OWN URL.
443        // (The required-mode credential is re-supplied per phase — the
444        // env vars were already cleaned before phase 1's await.)
445        let session = {
446            let _lock = ENV_LOCK.lock().expect("env lock");
447            isolate_config(
448                &dir,
449                &two_profile_toml(mock_b.uri().as_str(), mock_b.uri().as_str()),
450            );
451            // SAFETY: single-threaded under ENV_LOCK.
452            unsafe { std::env::set_var("IGNITION_TOKEN", "overlay-token") };
453            let session = Session::resolve(Some("b")).expect("resolve again");
454            // SAFETY: single-threaded under ENV_LOCK.
455            unsafe { std::env::remove_var("IGNITION_TOKEN") };
456            // SAFETY: single-threaded under ENV_LOCK.
457            unsafe { std::env::remove_var("IGNITION_CLI_CONFIG") };
458            session
459        };
460        let info = session.gateway_info().await.expect("own url answers");
461        assert_eq!(info.ignition_version, "8.3.6 (b2026042713)");
462        assert_eq!(
463            guard_b.received_requests().await.len(),
464            1,
465            "without the overlay the selected profile's own URL answers"
466        );
467    }
468
469    /// SELECTION: flag > active; unknown name → `ProfileNotFound` with
470    /// the known profiles in the hint; nothing resolvable →
471    /// `NoActiveProfile` (the existing main.rs consumer of
472    /// `resolve_selection`'s `Ok(None)` — not a new error class).
473    /// `IGNITION_PROFILE` is deliberately inert here: the bin folds it
474    /// into the flag (`apply_env_defaults` — the one env→flag home), so
475    /// the seam never re-reads it.
476    #[test]
477    fn selection_precedence_flag_over_active_and_errors() {
478        let _lock = ENV_LOCK.lock().expect("env lock");
479        let dir = tempfile::tempdir().expect("tempdir");
480        isolate_config(
481            &dir,
482            &two_profile_toml("http://a.example:9088/", "http://b.example:9088/"),
483        );
484        // SAFETY: single-threaded under ENV_LOCK.
485        unsafe { std::env::set_var("IGNITION_TOKEN", "t") };
486
487        // Flag beats active.
488        let session = Session::resolve(Some("b")).expect("flag selects b");
489        assert_eq!(session.profile_name(), "b");
490
491        // Unknown name → ProfileNotFound carrying the knowns.
492        let err = Session::resolve(Some("nope")).expect_err("unknown errors");
493        match &err {
494            CoreError::ProfileNotFound { name, known } => {
495                assert_eq!(name, "nope");
496                assert_eq!(known, &vec!["a".to_string(), "b".to_string()]);
497            }
498            other => panic!("wrong error class: {other}"),
499        }
500        assert_eq!(err.exit_code(), 3);
501
502        // Nothing resolvable → NoActiveProfile, both modes.
503        isolate_config(&dir, "");
504        assert!(matches!(
505            Session::resolve(None).expect_err("no selection errors"),
506            CoreError::NoActiveProfile
507        ));
508        assert!(matches!(
509            Session::resolve_degraded(None).expect_err("no selection errors"),
510            CoreError::NoActiveProfile
511        ));
512
513        // The bin's env fold is upstream: IGNITION_PROFILE alone must
514        // NOT drive the seam's selection.
515        isolate_config(
516            &dir,
517            &two_profile_toml("http://a.example:9088/", "http://b.example:9088/"),
518        );
519        // SAFETY: single-threaded under ENV_LOCK.
520        unsafe { std::env::set_var("IGNITION_PROFILE", "b") };
521        let session = Session::resolve(None).expect("active wins without a flag");
522        assert_eq!(
523            session.profile_name(),
524            "a",
525            "IGNITION_PROFILE folding belongs to the bin, not the seam"
526        );
527
528        unset("IGNITION_PROFILE");
529        unset("IGNITION_TOKEN");
530        unset("IGNITION_CLI_CONFIG");
531    }
532
533    /// SECRET CHAIN (LOCKED): an env token beats the basic env pair
534    /// (env-first), and — when NO secret exists anywhere — required
535    /// mode errors with `SecretUnavailable` (exit 3) while degraded
536    /// mode returns a header-less client (the authed gateway-info
537    /// request carries NO auth header at all).
538    ///
539    /// Same lock discipline as the precedence test: env mutations and
540    /// the sync `resolve*` calls hold `ENV_LOCK`; the `await`ed
541    /// requests run with the guard dropped (the client already
542    /// snapshotted its credential).
543    #[tokio::test]
544    async fn locked_chain_env_first_required_errors_degraded_headerless() {
545        let mock = wiremock::MockServer::start().await;
546        let guard = mount_info(&mock, 2).await;
547        let dir = tempfile::tempdir().expect("tempdir");
548
549        // Env token beats the basic pair: both sets, the authed request
550        // carries the TOKEN header and no Authorization header.
551        let session = {
552            let _lock = ENV_LOCK.lock().expect("env lock");
553            isolate_config(
554                &dir,
555                &two_profile_toml(mock.uri().as_str(), mock.uri().as_str()),
556            );
557            // SAFETY: single-threaded under ENV_LOCK.
558            unsafe {
559                std::env::set_var("IGNITION_TOKEN", "chain-token");
560                std::env::set_var("IGNITION_USER", "admin");
561                std::env::set_var("IGNITION_PASSWORD", "pw");
562            }
563            let session = Session::resolve(Some("a")).expect("env token resolves");
564            // SAFETY: single-threaded under ENV_LOCK.
565            unsafe {
566                std::env::remove_var("IGNITION_TOKEN");
567                std::env::remove_var("IGNITION_USER");
568                std::env::remove_var("IGNITION_PASSWORD");
569            }
570            session
571        };
572        let info = session.gateway_info().await.expect("token answers");
573        assert_eq!(info.ignition_version, "8.3.6 (b2026042713)");
574        let requests = guard.received_requests().await;
575        assert_eq!(requests.len(), 1, "one token-carrying request so far");
576        let headers = headers_debug(&requests[0]);
577        assert!(
578            headers.contains("x-ignition-api-token"),
579            "env token must ride the token header: {headers}"
580        );
581        assert!(
582            !headers.contains("authorization"),
583            "basic pair must lose to the env token: {headers}"
584        );
585
586        // No secret anywhere: required mode refuses; degraded mode
587        // survives (the authed request goes out with ZERO auth headers
588        // — a credential must not sneak in from the OS keyring either).
589        {
590            let _lock = ENV_LOCK.lock().expect("env lock");
591            isolate_config(
592                &dir,
593                &two_profile_toml(mock.uri().as_str(), mock.uri().as_str()),
594            );
595            let err = Session::resolve(Some("a")).expect_err("required mode demands a secret");
596            assert!(matches!(err, CoreError::SecretUnavailable { .. }));
597            assert_eq!(err.exit_code(), 3);
598            assert!(
599                err.hint().expect("hint").contains("IGNITION_TOKEN"),
600                "hint names the env path"
601            );
602            let degraded = Session::resolve_degraded(Some("a")).expect("degraded tolerates none");
603            // SAFETY: single-threaded under ENV_LOCK.
604            unsafe { std::env::remove_var("IGNITION_CLI_CONFIG") };
605            degraded
606        }
607        .gateway_info()
608        .await
609        .map(|info| {
610            assert_eq!(info.ignition_version, "8.3.6 (b2026042713)");
611        })
612        .expect("headerless answers");
613        let requests = guard.received_requests().await;
614        assert_eq!(requests.len(), 2, "the headerless request arrived");
615        let headers = headers_debug(&requests[1]);
616        assert!(
617            !headers.contains("x-ignition-api-token"),
618            "degraded mode must be header-less: {headers}"
619        );
620        assert!(
621            !headers.contains("authorization"),
622            "degraded mode must be header-less: {headers}"
623        );
624    }
625
626    /// The shared selection helper maps `Ok(None)` → `NoActiveProfile`
627    /// (never a silent pass-through) — the exact consumer behavior the
628    /// main.rs call sites implement today.
629    #[test]
630    fn resolve_selected_maps_none_to_no_active_profile() {
631        let _lock = ENV_LOCK.lock().expect("env lock");
632        let dir = tempfile::tempdir().expect("tempdir");
633        isolate_config(&dir, "");
634        let mut config = crate::config::load(&crate::config::config_path()).expect("load");
635        let err = resolve_selected(&mut config, None).expect_err("none → error");
636        assert!(matches!(err, CoreError::NoActiveProfile));
637        unset("IGNITION_CLI_CONFIG");
638    }
639}