Skip to main content

tracevault_cli/
credentials.rs

1//! The on-disk credential (`~/.config/tracevault/credentials.json`) and the
2//! two kinds of authentication the CLI supports.
3//!
4//! There are exactly two, and they are not interchangeable:
5//!
6//! * **`tvk_` API key** — what automation and CI use, forever. Never
7//!   expires, never refreshes, comes from `TRACEVAULT_API_KEY`, a project
8//!   `config.toml`, or the `token` field of this file.
9//! * **Keycloak session** — what a human gets from `tracevault login`
10//!   (RFC 8628 device flow). Short-lived access token plus an
11//!   `offline_access` refresh token, stored under the `auth` object, and
12//!   refreshed transparently so unattended git hooks never prompt.
13//!
14//! The file shape is additive: a pre-Keycloak file
15//! (`{"server_url","token","email"}`, possibly still carrying a pre
16//! single-tenant `org_slug`) keeps working untouched.
17
18use crate::oidc::TokenSet;
19use serde::{Deserialize, Serialize};
20use std::fmt;
21use std::fs;
22use std::path::{Path, PathBuf};
23
24/// How long before expiry an access token is proactively refreshed. Sized to
25/// comfortably cover a slow request that is issued just under the wire: a
26/// token that would expire mid-flight is refreshed first instead.
27pub const REFRESH_WINDOW_SECS: i64 = 60;
28
29/// A live Keycloak session for the human who ran `tracevault login`.
30///
31/// `issuer` and `client_id` are stored alongside the tokens because a
32/// refresh needs them and must not depend on the TraceVault server being
33/// reachable to re-read its public config.
34#[derive(Clone, Serialize, Deserialize)]
35pub struct KeycloakSession {
36    pub issuer: String,
37    pub client_id: String,
38    /// SECRET. Long-lived (`offline_access`); this is the credential that
39    /// makes unattended hooks work.
40    pub refresh_token: String,
41    /// SECRET. Short-lived bearer presented to the TraceVault server.
42    pub access_token: String,
43    /// Absolute unix seconds at which `access_token` stops being valid.
44    pub access_expires_at: i64,
45}
46
47impl KeycloakSession {
48    /// Whether `access_token` is expired or close enough to expiry
49    /// ([`REFRESH_WINDOW_SECS`]) that it should be refreshed before use.
50    ///
51    /// `now` is passed in rather than read from the clock so callers — and
52    /// tests of the window boundary — are deterministic.
53    pub fn needs_refresh(&self, now: i64) -> bool {
54        self.access_expires_at.saturating_sub(now) < REFRESH_WINDOW_SECS
55    }
56
57    /// Fold a fresh token response into this session.
58    ///
59    /// A token endpoint may omit `refresh_token` when it doesn't rotate
60    /// refresh tokens; the previous one is kept in that case, since dropping
61    /// it would silently downgrade the session to "expires in 5 minutes".
62    pub fn apply(&mut self, tokens: &TokenSet, now: i64) {
63        self.access_token = tokens.access_token.clone();
64        if let Some(rt) = &tokens.refresh_token {
65            self.refresh_token = rt.clone();
66        }
67        self.access_expires_at = tokens.access_expires_at(now);
68    }
69}
70
71/// Hand-written so no `{:?}` can leak either token.
72impl fmt::Debug for KeycloakSession {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.debug_struct("KeycloakSession")
75            .field("issuer", &self.issuer)
76            .field("client_id", &self.client_id)
77            .field("refresh_token", &"<redacted>")
78            .field("access_token", &"<redacted>")
79            .field("access_expires_at", &self.access_expires_at)
80            .finish()
81    }
82}
83
84/// Whether two TraceVault base URLs identify the same instance.
85///
86/// Needed because the two sides reach us differently formatted from the same
87/// user-supplied string: `ApiClient` trims trailing slashes from its
88/// `base_url`, while `credentials.json` stores `server_url` exactly as it was
89/// passed to `tracevault login`. So `https://tv.example.com/` and
90/// `https://tv.example.com` must compare equal, or a legitimate session would
91/// never be adopted.
92///
93/// Comparison is otherwise byte-exact (no host lowercasing, no default-port
94/// folding). That is deliberate: both values originate from the same string in
95/// every real flow, and the two failure directions are not symmetric. A false
96/// negative costs one extra token refresh; a false positive would send an
97/// access token to a host it was not minted for. When in doubt, don't match.
98pub fn same_server(a: &str, b: &str) -> bool {
99    let norm = |s: &str| s.trim().trim_end_matches('/').to_string();
100    norm(a) == norm(b)
101}
102
103/// How a request authenticates itself.
104#[derive(Clone)]
105pub enum Credential {
106    /// A `tvk_` API key: presented verbatim, never refreshed.
107    ApiKey(String),
108    /// A Keycloak session: refreshed on demand.
109    Keycloak(KeycloakSession),
110}
111
112/// Hand-written so no `{:?}` can leak the key or the tokens.
113impl fmt::Debug for Credential {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Self::ApiKey(_) => f.write_str("Credential::ApiKey(<redacted>)"),
117            Self::Keycloak(s) => write!(f, "Credential::Keycloak({s:?})"),
118        }
119    }
120}
121
122/// `credentials.json`.
123///
124/// `token` and `auth` are both optional and mutually exclusive in practice:
125/// `token` is written by an API-key login, `auth` by `tracevault login`.
126/// Neither is written when absent, so an API-key file stays byte-identical
127/// in shape to what earlier CLI versions wrote.
128#[derive(Serialize, Deserialize)]
129pub struct Credentials {
130    pub server_url: String,
131    /// SECRET. A `tvk_` API key, when this file holds one.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub token: Option<String>,
134    /// The signed-in identity, for display. Empty when a login saved
135    /// credentials before `/auth/me` could resolve it (e.g. the account
136    /// lacks the `tracing` realm role).
137    #[serde(default)]
138    pub email: String,
139    /// The Keycloak session, when this file holds one.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub auth: Option<KeycloakSession>,
142}
143
144/// Hand-written so no `{:?}` can leak the API key.
145impl fmt::Debug for Credentials {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.debug_struct("Credentials")
148            .field("server_url", &self.server_url)
149            .field("token", &self.token.as_ref().map(|_| "<redacted>"))
150            .field("email", &self.email)
151            .field("auth", &self.auth)
152            .finish()
153    }
154}
155
156impl Credentials {
157    /// A Keycloak session credential file (what `tracevault login` writes).
158    ///
159    /// # The single policy both writers follow
160    ///
161    /// **A write never destroys a credential it did not come to replace.** This
162    /// constructor and [`Self::persist_session`] are the only two writers, and
163    /// they now agree: `persist_session` replaces `auth` and keeps everything
164    /// else, and this preserves any pre-existing `token` (an API key) instead of
165    /// dropping it. Logging in supersedes a key without deleting it, which is
166    /// safe because [`Self::credential`] already prefers a Keycloak session over
167    /// a leftover `token` — so the key is inert while the session lives, and
168    /// still there if the session is later removed.
169    ///
170    /// The token is only carried over when the existing file is for the SAME
171    /// server ([`same_server`]): moving another instance's key into this
172    /// instance's file would be the same cross-instance mixing the resolution
173    /// guards exist to prevent.
174    ///
175    /// There is deliberately no `api_key` counterpart constructor: nothing in
176    /// the CLI creates an API-key credentials file (a key comes from
177    /// `TRACEVAULT_API_KEY` or `config.toml`); such a file is only ever READ,
178    /// from one a user or an older CLI version wrote.
179    pub fn keycloak(server_url: &str, email: String, session: KeycloakSession) -> Self {
180        let preserved_token = Self::load()
181            .filter(|existing| same_server(&existing.server_url, server_url))
182            .and_then(|existing| existing.token);
183        Self {
184            server_url: server_url.to_string(),
185            token: preserved_token,
186            email,
187            auth: Some(session),
188        }
189    }
190
191    /// Which credential this file carries. A Keycloak session wins over a
192    /// leftover `token` so a re-login supersedes an old API key rather than
193    /// silently continuing to use it.
194    pub fn credential(&self) -> Option<Credential> {
195        if let Some(session) = &self.auth {
196            return Some(Credential::Keycloak(session.clone()));
197        }
198        self.token.clone().map(Credential::ApiKey)
199    }
200
201    /// Where the credential file lives, or an error naming what is missing.
202    ///
203    /// Returns `Err` rather than inventing a path. The previous fallback,
204    /// `PathBuf::from("~/.config")`, is a RELATIVE path — a shell expands `~`,
205    /// `Path` does not — so with no resolvable config directory `login` created
206    /// `./~/.config/tracevault/` in the current working directory and wrote an
207    /// offline refresh token into it, plausibly inside the user's repo. There is
208    /// no defensible guess for "where is this user's config", so failing loudly
209    /// is the only correct answer.
210    pub fn path() -> Result<PathBuf, std::io::Error> {
211        Self::path_in(dirs::config_dir())
212    }
213
214    /// [`Self::path`] with the config directory injected, so the
215    /// no-config-directory branch is testable.
216    ///
217    /// It cannot be reached through the environment on glibc Linux — with `HOME`
218    /// unset `dirs::config_dir()` falls back to the passwd database — so in the
219    /// wild it needs something more unusual (a container with no passwd entry
220    /// for the uid, some static builds). That makes it rarer than "HOME unset",
221    /// but no less wrong to guess at.
222    fn path_in(config_dir: Option<PathBuf>) -> Result<PathBuf, std::io::Error> {
223        let dir = config_dir.ok_or_else(|| {
224            std::io::Error::new(
225                std::io::ErrorKind::NotFound,
226                "cannot determine the user config directory: set XDG_CONFIG_HOME (or HOME) so \
227                 credentials can be stored under $XDG_CONFIG_HOME/tracevault/",
228            )
229        })?;
230        Ok(dir.join("tracevault").join("credentials.json"))
231    }
232
233    /// The credential file's path for DISPLAY, when there is nothing useful to
234    /// do about a missing config directory (a message is being printed either
235    /// way). Never used to read or write.
236    pub fn path_for_display() -> String {
237        match Self::path() {
238            Ok(p) => p.display().to_string(),
239            Err(_) => "<no user config directory: set XDG_CONFIG_HOME or HOME>".to_string(),
240        }
241    }
242
243    pub fn load() -> Option<Self> {
244        let path = Self::path().ok()?;
245        let content = fs::read_to_string(&path).ok()?;
246        serde_json::from_str(&content).ok()
247    }
248
249    /// Write the credential file atomically, readable only by its owner.
250    ///
251    /// Atomic because a token refresh rewrites this file while other
252    /// processes (git hooks, a parallel `tracevault stream`) may be reading
253    /// it: a plain truncate-then-write leaves a window in which a reader
254    /// parses a half-written file and concludes the user is logged out. The
255    /// temp file is created in the SAME directory so the `rename` stays
256    /// within one filesystem and is therefore atomic.
257    ///
258    /// The temp file is created with `create_new(true)`, which is what makes
259    /// the 0600 promise real: `OpenOptions::mode()` applies ONLY when the file
260    /// is created, so opening a path that already exists inherits whatever mode
261    /// (or symlink target) is already there, and the following `rename` would
262    /// then publish that mode as the credential file's. A stale
263    /// `.credentials.json.tmp*` left by an earlier crash under a looser umask
264    /// is enough to defeat it. `create_new` turns that case into
265    /// `AlreadyExists`, which we resolve by picking a fresh name rather than
266    /// failing the save.
267    pub fn save(&self) -> Result<(), std::io::Error> {
268        let path = Self::path()?;
269        if let Some(parent) = path.parent() {
270            fs::create_dir_all(parent)?;
271        }
272        let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
273
274        let mut opts = fs::OpenOptions::new();
275        // `create_new` also refuses to follow a symlink planted at the temp
276        // path, so tokens cannot be written outside this directory.
277        opts.write(true).create_new(true);
278        // Mode is set at creation, not after: a chmod afterwards would leave
279        // the tokens world-readable for the interval in between.
280        #[cfg(unix)]
281        {
282            use std::os::unix::fs::OpenOptionsExt;
283            opts.mode(0o600);
284        }
285
286        // A few attempts, since each `AlreadyExists` means a genuinely
287        // different name is tried next (the counter is process-local and
288        // monotonic, and the nanos component differs per attempt). Bounded so a
289        // pathological directory can't spin here forever.
290        const ATTEMPTS: usize = 8;
291        let mut last_err = None;
292        for _ in 0..ATTEMPTS {
293            let tmp = path.with_file_name(Self::temp_file_name());
294            let file = match opts.open(&tmp) {
295                Ok(f) => f,
296                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
297                    last_err = Some(e);
298                    continue;
299                }
300                Err(e) => return Err(e),
301            };
302
303            let write_result = (|| {
304                use std::io::Write;
305                let mut file = file;
306                file.write_all(json.as_bytes())?;
307                file.sync_all()
308            })();
309            if let Err(e) = write_result {
310                let _ = fs::remove_file(&tmp);
311                return Err(e);
312            }
313            if let Err(e) = fs::rename(&tmp, &path) {
314                let _ = fs::remove_file(&tmp);
315                return Err(e);
316            }
317            // Bound the accumulation of abandoned temp files, each of which
318            // holds a full credential including the refresh token.
319            Self::sweep_stale_temp_files();
320            return Ok(());
321        }
322        Err(last_err.unwrap_or_else(|| {
323            std::io::Error::new(
324                std::io::ErrorKind::AlreadyExists,
325                "could not create a unique temporary credentials file",
326            )
327        }))
328    }
329
330    /// Filename prefix of the atomic-write temp files. Anything matching this
331    /// contains a full credential JSON — including the offline refresh token —
332    /// so leftovers are credential material, not scratch data.
333    const TEMP_PREFIX: &'static str = ".credentials.json.tmp";
334
335    /// A temp file this old cannot still be in flight: a save is a couple of
336    /// syscalls. Only files older than this are swept, so a concurrent save in
337    /// another process never has its temp file deleted out from under it (which
338    /// would make its `rename` fail and turn a benign race into an error).
339    const TEMP_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(3600);
340
341    /// Best-effort removal of abandoned temp files, oldest-first semantics by
342    /// age threshold. Never reports failure: this is hygiene, and a stray file
343    /// we cannot delete must not fail the save or the logout that triggered it.
344    fn sweep_stale_temp_files() {
345        Self::remove_temp_files(Some(Self::TEMP_STALE_AFTER));
346    }
347
348    /// Remove atomic-write temp files in the credential directory. With
349    /// `min_age`, only files at least that old; without it, all of them (used
350    /// by `delete`, where the user is logging out and nothing should survive).
351    fn remove_temp_files(min_age: Option<std::time::Duration>) {
352        let Some(dir) = Self::path()
353            .ok()
354            .and_then(|p| p.parent().map(PathBuf::from))
355        else {
356            return;
357        };
358        let Ok(entries) = fs::read_dir(&dir) else {
359            return;
360        };
361        for entry in entries.flatten() {
362            let name = entry.file_name();
363            let Some(name) = name.to_str() else { continue };
364            if !name.starts_with(Self::TEMP_PREFIX) {
365                continue;
366            }
367            if let Some(min_age) = min_age {
368                let recent = entry
369                    .metadata()
370                    .and_then(|m| m.modified())
371                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
372                    .map(|age| age < min_age)
373                    // A clock skew or unreadable mtime means "can't prove it's
374                    // stale" — leave it rather than risk deleting a live temp.
375                    .unwrap_or(true);
376                if recent {
377                    continue;
378                }
379            }
380            let _ = fs::remove_file(entry.path());
381        }
382    }
383
384    /// A temp file name unique per process AND per call within a process.
385    ///
386    /// The pid alone is not enough: two saves in one process (a refresh racing
387    /// the second `save()` of a login) would collide on the same path, and with
388    /// `create_new` that turns into a spurious failure. The counter makes it
389    /// unique within the process; the nanos make a name unlikely to collide
390    /// with a stale file left by a previous process that had the same pid.
391    fn temp_file_name() -> String {
392        use std::sync::atomic::{AtomicU64, Ordering};
393        static COUNTER: AtomicU64 = AtomicU64::new(0);
394        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
395        let nanos = std::time::SystemTime::now()
396            .duration_since(std::time::UNIX_EPOCH)
397            .map(|d| d.subsec_nanos())
398            .unwrap_or(0);
399        format!(
400            "{}{}.{}.{}",
401            Self::TEMP_PREFIX,
402            std::process::id(),
403            n,
404            nanos
405        )
406    }
407
408    /// Persist refreshed Keycloak tokens for `server_url`, keeping every other
409    /// field of the file as it is on disk — including a `token` (API key),
410    /// per the single write policy documented on [`Self::keycloak`].
411    ///
412    /// Re-reads the file rather than rewriting a cached copy so a
413    /// concurrently changed `server_url`/`email` isn't reverted. A missing
414    /// file is not an error: there is nothing to keep in sync (the session
415    /// may be held by a process whose file was removed by `tv logout`).
416    ///
417    /// Writes NOTHING when the file on disk belongs to a different server (see
418    /// [`same_server`]). There is one credentials file, so a long-running
419    /// process holding instance A's session would otherwise overwrite the
420    /// credentials of instance B that the user logged into meanwhile —
421    /// silently signing them out of B. Skipping is not an error: A's refreshed
422    /// token still works for the rest of A's process lifetime.
423    ///
424    /// The skip warns, because it is otherwise undiagnosable from the outside:
425    /// if the two URLs differ only by formatting the mismatch is PERMANENT, so
426    /// persistence is disabled for every future invocation and the CLI silently
427    /// re-refreshes forever.
428    pub fn persist_session(
429        server_url: &str,
430        session: &KeycloakSession,
431    ) -> Result<(), std::io::Error> {
432        let Some(mut creds) = Self::load() else {
433            return Ok(());
434        };
435        if !same_server(&creds.server_url, server_url) {
436            eprintln!(
437                "Warning: not saving the refreshed token — the credentials file is for \
438                 '{}', but this session is for '{}'. The refreshed token applies to this \
439                 process only; every later command will refresh again.",
440                creds.server_url, server_url
441            );
442            return Ok(());
443        }
444        creds.auth = Some(session.clone());
445        creds.save()
446    }
447
448    /// Remove the credential file — and any atomic-write temp files left
449    /// behind.
450    ///
451    /// The sweep is the difference between "logout" and "logout, except for the
452    /// refresh tokens still on disk": every `.credentials.json.tmp*` holds a
453    /// full credential JSON, so a temp file abandoned by an earlier crash
454    /// between `open` and `rename` would keep a working offline refresh token
455    /// in the config directory after the user asked to be logged out. No age
456    /// threshold here (unlike [`Self::sweep_stale_temp_files`]): the user is
457    /// logging out, so a save racing this is already a lost race — and its
458    /// failed `rename` cannot resurrect the credential file, since the very
459    /// next thing that happens is this delete.
460    ///
461    /// The sweep is best-effort: a stray file that cannot be removed must not
462    /// fail the logout.
463    pub fn delete() -> Result<(), std::io::Error> {
464        let path = Self::path()?;
465        if path.exists() {
466            fs::remove_file(&path)?;
467        }
468        Self::remove_temp_files(None);
469        Ok(())
470    }
471}
472
473// ── Credential resolution ────────────────────────────────────────────────────
474//
475// Which secret to trust for a given project root, and the guard that keeps one
476// instance's credential from reaching another. This is policy about the on-disk
477// format and the environment — no HTTP — so it lives here, next to the file it
478// defends, rather than in the HTTP client module every command would otherwise
479// import it from. `api_client::resolve_client` is the thin wrapper that turns
480// the result into a client.
481
482/// Resolve server URL and credential from multiple sources.
483/// Priority: env var > credentials file > project config.toml
484/// Returns (server_url, credential).
485///
486/// Only the credentials file can yield a [`Credential::Keycloak`]: an env var
487/// or a `config.toml` `api_key` is always a `tvk_` API key, and an API key is
488/// never treated as refreshable. That asymmetry is the whole contract — CI
489/// and automation stay on the unchanging key path.
490///
491/// # Errors
492///
493/// Fails when the resolved server URL and a credential read from the
494/// credentials file are for different TraceVault instances (see
495/// [`server_mismatch_error`]). This covers EITHER kind of file-sourced
496/// credential — the distinction that matters is not Keycloak-vs-key but
497/// named-on-this-invocation vs. read-from-the-file. Failing is deliberate
498/// rather than silently dropping the credential: every "Not logged in, run
499/// `tracevault login`" message downstream would be actively WRONG advice — the
500/// user IS logged in, and logging in again to the same instance would not
501/// change anything.
502#[allow(clippy::type_complexity)]
503pub fn resolve_credentials(
504    project_root: &Path,
505) -> Result<(Option<String>, Option<Credential>), Box<dyn std::error::Error>> {
506    // 1. Env var API key
507    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
508
509    // 2. Credentials file
510    let creds = Credentials::load();
511
512    // 3. Project config — parsed as TOML by its own loader, not by hand.
513    //
514    // The previous line-scanning version split on `=` and took field 1, so a
515    // perfectly legal `api_key = "tvk_abc=="` resolved to `tvk_abc`: a silently
516    // truncated key, surfacing later as an unexplained 401 that (by design) is
517    // never retried. It also matched any line merely STARTING with the field
518    // name (`server_url_backup`) and read keys nested under a `[table]` as
519    // though they were top-level. `TracevaultConfig` already declares both
520    // fields, so the hand-parse only existed to duplicate it — badly. Using
521    // `load` also means a malformed config now warns instead of silently
522    // yielding nothing.
523    let config = crate::config::TracevaultConfig::load(project_root);
524    let config_server_url = config.as_ref().and_then(|c| c.server_url.clone());
525    let config_api_key = config.as_ref().and_then(|c| c.api_key.clone());
526
527    // Resolve server URL: env > creds > config
528    let server_url = std::env::var("TRACEVAULT_SERVER_URL")
529        .ok()
530        .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
531        .or(config_server_url);
532
533    // Resolve the credential: env api key > credentials file > config api key
534    let credential = match env_key {
535        // Named explicitly on this invocation: the operator's choice of
536        // key/URL pairing is deliberate and is not second-guessed.
537        Some(key) => Some(Credential::ApiKey(key)),
538        None => {
539            let from_file = creds.as_ref().and_then(Credentials::credential);
540            if from_file.is_some() {
541                // The two precedence chains above disagree: the URL can come
542                // from the env while the credential comes from the file. Every
543                // credential in that file — a Keycloak access token or a `tvk_`
544                // API key alike — was issued by ONE TraceVault instance, so
545                // handing it to a client pointed elsewhere transmits a secret to
546                // a host it was never issued for, which then has it in its logs.
547                //
548                // This is the FIRST request, before any refresh, so neither
549                // server-scoping guard in `refresh_locked` would see it.
550                //
551                // Only reachable when TRACEVAULT_SERVER_URL is set: with it
552                // unset the URL comes from this same file, so the two match by
553                // construction.
554                let file_url = creds.as_ref().map_or("", |c| c.server_url.as_str());
555                if let Some(target) = server_url.as_deref() {
556                    if !same_server(file_url, target) {
557                        return Err(server_mismatch_error(file_url, target));
558                    }
559                }
560            }
561            // A `config.toml` `api_key` is NOT guarded: committing a key to a
562            // project config, next to that config's own `server_url`, is as
563            // deliberate as naming it in the environment. It is also only
564            // reachable when the file yielded nothing.
565            from_file.or_else(|| config_api_key.map(Credential::ApiKey))
566        }
567    };
568
569    Ok((server_url, credential))
570}
571
572/// The error for "the saved credential is for a different TraceVault instance".
573///
574/// Applies to any FILE-SOURCED credential, Keycloak session or `tvk_` key
575/// alike: both are secrets issued by one instance, and a key would not even
576/// work against another instance — so without this the user gets a confusing
577/// 401 from the wrong host instead of an explanation.
578///
579/// Names BOTH URLs, because the whole failure is that two of them disagree and
580/// the user can see neither: `tracevault status` reports the file's URL, and
581/// the env var is often set in a shell profile or a CI job definition rather
582/// than on the command line.
583///
584/// The third suggestion matters: pointing at the SAME instance through another
585/// address (a `kubectl port-forward`, an internal vs. external hostname) is a
586/// legitimate workflow that this guard cannot distinguish from a genuine
587/// mismatch, so the message names the ways to proceed deliberately.
588fn server_mismatch_error(file_url: &str, target: &str) -> Box<dyn std::error::Error> {
589    format!(
590        "refusing to use the saved credentials: the credentials file is for '{file_url}', but \
591         this command is targeting '{target}'. A credential issued by one TraceVault instance \
592         must not be sent to another.\n\
593         Either unset TRACEVAULT_SERVER_URL to use '{file_url}', or run `tracevault login \
594         --server-url {target}`. If '{target}' is the same instance reached through a different \
595         address (e.g. a port-forward), set TRACEVAULT_API_KEY to a `tvk_` key for it instead."
596    )
597    .into()
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603
604    /// Redirect `XDG_CONFIG_HOME` at a tempdir and write `body` as the
605    /// credentials file. Returns the tempdir plus both guards, which the
606    /// caller must keep alive for the duration of the test (the env lock is
607    /// released, and the real `~/.config` restored, when they drop).
608    fn with_credentials_file(
609        body: &str,
610    ) -> (
611        tempfile::TempDir,
612        tokio::sync::MutexGuard<'static, ()>,
613        crate::test_helpers::EnvVarGuard,
614    ) {
615        let env_lock = crate::test_helpers::lock_env_mutation_sync();
616        let dir = tempfile::tempdir().unwrap();
617        let mut guard = crate::test_helpers::EnvVarGuard::new();
618        guard.set("XDG_CONFIG_HOME", dir.path());
619        let creds_dir = dir.path().join("tracevault");
620        fs::create_dir_all(&creds_dir).unwrap();
621        fs::write(creds_dir.join("credentials.json"), body).unwrap();
622        (dir, env_lock, guard)
623    }
624
625    /// Fixed "now" for the resolution fixtures. A constant rather than the wall
626    /// clock so nothing here depends on timing.
627    const NOW: i64 = 1_800_000_000;
628
629    /// Write a Keycloak credentials file for `server_url`/`issuer` into `dir`.
630    fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
631        let creds_dir = dir.join("tracevault");
632        fs::create_dir_all(&creds_dir).unwrap();
633        fs::write(
634            creds_dir.join("credentials.json"),
635            format!(
636                r#"{{"server_url":"{server_url}","email":"a@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"old-rt","access_token":"old-at","access_expires_at":{expires_at}}}}}"#
637            ),
638        )
639        .unwrap();
640    }
641
642    // ---- resolve_credentials: a credential read from the FILE must not follow
643    // ---- a TRACEVAULT_SERVER_URL override to another instance. Applies to a
644    // ---- Keycloak session and a `tvk_` key alike; an env- or config-supplied
645    // ---- key is a deliberate operator act and is left alone.
646
647    type ResolveFixture = (
648        tempfile::TempDir,
649        tokio::sync::MutexGuard<'static, ()>,
650        crate::test_helpers::EnvVarGuard,
651    );
652
653    /// Set up an empty project root with `TRACEVAULT_SERVER_URL` set to
654    /// `env_url` (unset when `None`) and `credentials.json` containing
655    /// `file_body` (no file when `None`). Returns the tempdir (which doubles as
656    /// the project root) plus the guards the caller must keep alive.
657    fn resolve_fixture_with(file_body: Option<&str>, env_url: Option<&str>) -> ResolveFixture {
658        let env_lock = crate::test_helpers::lock_env_mutation_sync();
659        let dir = tempfile::tempdir().unwrap();
660        let mut guard = crate::test_helpers::EnvVarGuard::new();
661        guard.set("XDG_CONFIG_HOME", dir.path());
662        // A stray key in the developer's environment would take precedence and
663        // mask what these tests are checking.
664        guard.remove("TRACEVAULT_API_KEY");
665        match env_url {
666            Some(u) => guard.set("TRACEVAULT_SERVER_URL", u),
667            None => guard.remove("TRACEVAULT_SERVER_URL"),
668        }
669        if let Some(body) = file_body {
670            let creds_dir = dir.path().join("tracevault");
671            fs::create_dir_all(&creds_dir).unwrap();
672            fs::write(creds_dir.join("credentials.json"), body).unwrap();
673        }
674        (dir, env_lock, guard)
675    }
676
677    /// [`resolve_fixture_with`] for a file holding a Keycloak session.
678    fn resolve_fixture(file_server_url: &str, env_url: Option<&str>) -> ResolveFixture {
679        let fixture = resolve_fixture_with(None, env_url);
680        write_keycloak_file(
681            fixture.0.path(),
682            file_server_url,
683            "https://idp.test/realms/v",
684            NOW + 3600,
685        );
686        fixture
687    }
688
689    /// [`resolve_fixture_with`] for a file holding a `tvk_` API key.
690    fn resolve_fixture_api_key(file_server_url: &str, env_url: Option<&str>) -> ResolveFixture {
691        resolve_fixture_with(
692            Some(&format!(
693                r#"{{"server_url":"{file_server_url}","token":"tvk_from_file","email":"a@b.com"}}"#
694            )),
695            env_url,
696        )
697    }
698
699    /// The precedence chains disagree: the URL comes from the env, the
700    /// credential from the file. Handing either kind over would send a secret
701    /// minted by instance B to instance A on the FIRST request, before any
702    /// refresh, so neither guard in `refresh_locked` would ever see it.
703    ///
704    /// Both credential kinds are checked here because the distinction that
705    /// matters is not Keycloak-vs-key but named-on-this-invocation
706    /// vs. read-from-the-file — and because the two assert the same message.
707    #[test]
708    fn a_mismatched_server_url_refuses_either_kind_of_file_credential() {
709        for kind in ["keycloak session", "api key"] {
710            let (dir, _lock, _guard) = if kind == "keycloak session" {
711                resolve_fixture(
712                    "https://instance-b.example.com",
713                    Some("https://instance-a.example.com"),
714                )
715            } else {
716                resolve_fixture_api_key(
717                    "https://instance-b.example.com",
718                    Some("https://instance-a.example.com"),
719                )
720            };
721
722            let err = resolve_credentials(dir.path())
723                .expect_err("a credential for another instance must not be handed out");
724            let msg = err.to_string();
725            // Both URLs must be named: the user can see neither (status prints
726            // the file's, and the env var is usually set in a profile or CI job).
727            assert!(
728                msg.contains("https://instance-b.example.com"),
729                "{kind}: must name the file's server: {msg}"
730            );
731            assert!(
732                msg.contains("https://instance-a.example.com"),
733                "{kind}: must name the targeted server: {msg}"
734            );
735            // And it must point at the deliberate ways forward, including the
736            // same-instance-different-address case this guard cannot
737            // distinguish from a real mismatch.
738            assert!(msg.contains("TRACEVAULT_SERVER_URL"), "{kind}: {msg}");
739            assert!(msg.contains("tracevault login"), "{kind}: {msg}");
740            assert!(msg.contains("TRACEVAULT_API_KEY"), "{kind}: {msg}");
741            assert!(
742                !msg.contains("tvk_from_file"),
743                "{kind}: the error must not echo the credential: {msg}"
744            );
745        }
746    }
747
748    /// The two sides are formatted differently by construction (`ApiClient`
749    /// trims trailing slashes, the file keeps what login was given), so a
750    /// trailing slash must not be read as "a different instance". This guard
751    /// hard-FAILS, so a false positive here would break every command — hence
752    /// one positive test, while the other call sites need only prove that they
753    /// consult `same_server` at all, which their mismatch tests do.
754    #[test]
755    fn a_matching_server_url_modulo_trailing_slash_still_resolves() {
756        let (dir, _lock, _guard) =
757            resolve_fixture("https://example.com/", Some("https://example.com"));
758
759        let (url, credential) =
760            resolve_credentials(dir.path()).expect("a trailing slash is not a different instance");
761        assert_eq!(url.as_deref(), Some("https://example.com"));
762        assert!(matches!(credential, Some(Credential::Keycloak(_))));
763    }
764
765    /// The normal case: no env override, so the URL comes from the same file as
766    /// the credential and they match by construction.
767    #[test]
768    fn no_env_override_resolves_the_files_session_unchanged() {
769        let (dir, _lock, _guard) = resolve_fixture("https://example.com", None);
770
771        let (url, credential) = resolve_credentials(dir.path()).expect("the normal case must work");
772        assert_eq!(url.as_deref(), Some("https://example.com"));
773        assert!(matches!(credential, Some(Credential::Keycloak(_))));
774    }
775
776    /// The config is parsed as TOML, not scanned line by line. A base64-ish key
777    /// containing `=` used to be truncated at the first `=` (`tvk_abc==` ->
778    /// `tvk_abc`), producing an unexplained 401 that the `ApiKey` path
779    /// deliberately never retries.
780    #[test]
781    fn a_config_api_key_containing_equals_signs_is_not_truncated() {
782        let (dir, _lock, _guard) = resolve_fixture_with(None, None);
783        let config_dir = dir.path().join(".tracevault");
784        fs::create_dir_all(&config_dir).unwrap();
785        fs::write(
786            config_dir.join("config.toml"),
787            "server_url = \"https://example.com\"\napi_key = \"tvk_YWJjZA==\"\n",
788        )
789        .unwrap();
790
791        let (url, credential) = resolve_credentials(dir.path()).unwrap();
792        assert_eq!(url.as_deref(), Some("https://example.com"));
793        match credential {
794            Some(Credential::ApiKey(k)) => assert_eq!(
795                k, "tvk_YWJjZA==",
796                "the key must survive verbatim, `=` padding and all"
797            ),
798            other => panic!("expected the config API key, got {other:?}"),
799        }
800    }
801
802    /// Line-scanning also matched any field whose name merely STARTED with the
803    /// one being looked for, and read a key nested in a `[table]` as top-level.
804    /// TOML parsing gets both right.
805    #[test]
806    fn a_config_lookalike_field_is_not_mistaken_for_the_real_one() {
807        let (dir, _lock, _guard) = resolve_fixture_with(None, None);
808        let config_dir = dir.path().join(".tracevault");
809        fs::create_dir_all(&config_dir).unwrap();
810        fs::write(
811            config_dir.join("config.toml"),
812            "server_url = \"https://real.example.com\"\n\
813             [user_context]\n\
814             enable = false\n",
815        )
816        .unwrap();
817
818        let (url, credential) = resolve_credentials(dir.path()).unwrap();
819        assert_eq!(url.as_deref(), Some("https://real.example.com"));
820        assert!(
821            credential.is_none(),
822            "no api_key is configured anywhere, so there is no credential"
823        );
824    }
825
826    /// A `config.toml` `api_key` is committed next to that config's own
827    /// `server_url`: as deliberate as naming it in the environment, so a URL
828    /// override must not break it. (It is also only consulted when the
829    /// credentials file yielded nothing, as here.)
830    #[test]
831    fn a_config_api_key_is_unaffected_by_a_mismatched_server_url() {
832        let (dir, _lock, _guard) =
833            resolve_fixture_with(None, Some("https://instance-a.example.com"));
834        let config_dir = dir.path().join(".tracevault");
835        fs::create_dir_all(&config_dir).unwrap();
836        fs::write(
837            config_dir.join("config.toml"),
838            "server_url = \"https://instance-b.example.com\"\napi_key = \"tvk_from_config\"\n",
839        )
840        .unwrap();
841
842        let (url, credential) = resolve_credentials(dir.path())
843            .expect("a config-supplied key must never be second-guessed");
844        assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
845        match credential {
846            Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_from_config"),
847            other => panic!("expected the config API key, got {other:?}"),
848        }
849    }
850
851    /// `TRACEVAULT_API_KEY` plus a URL pointing anywhere is a deliberate,
852    /// explicit act by the operator (and the CI path). It must be unaffected.
853    #[test]
854    fn an_env_api_key_is_unaffected_by_a_mismatched_server_url() {
855        let (dir, _lock, mut guard) = resolve_fixture(
856            "https://instance-b.example.com",
857            Some("https://instance-a.example.com"),
858        );
859        guard.set("TRACEVAULT_API_KEY", "tvk_abc");
860
861        let (url, credential) = resolve_credentials(dir.path())
862            .expect("an explicitly supplied API key must never be second-guessed");
863        assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
864        match credential {
865            Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_abc"),
866            other => panic!("expected the env API key, got {other:?}"),
867        }
868    }
869
870    /// Old on-disk `credentials.json` files may still contain `org_slug`
871    /// from before the single-tenant org removal (mirrors config.rs's
872    /// `load_old_config_with_org_slug_still_parses`). serde must silently
873    /// ignore the unknown field rather than fail to parse (no
874    /// `deny_unknown_fields` on `Credentials`), so `Credentials::load()` keeps
875    /// working on an un-migrated credentials file.
876    ///
877    /// `XDG_CONFIG_HOME` is redirected to a tempdir so this reads a fixture
878    /// file rather than the developer's real
879    /// `~/.config/tracevault/credentials.json`; `_env_lock` serializes this
880    /// against other tests in the crate that mutate the same env var (see
881    /// `test_helpers::lock_env_mutation_sync`).
882    #[test]
883    fn load_old_credentials_with_org_slug_still_parses() {
884        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
885        let dir = tempfile::tempdir().unwrap();
886        let mut _guard = crate::test_helpers::EnvVarGuard::new();
887        _guard.set("XDG_CONFIG_HOME", dir.path());
888
889        let creds_dir = dir.path().join("tracevault");
890        fs::create_dir_all(&creds_dir).unwrap();
891        fs::write(
892            creds_dir.join("credentials.json"),
893            r#"{"server_url":"https://example.com","token":"tok","email":"a@b.com","org_slug":"x"}"#,
894        )
895        .unwrap();
896
897        let creds =
898            Credentials::load().expect("old credentials.json with org_slug must still parse");
899        assert_eq!(creds.server_url, "https://example.com");
900        assert_eq!(creds.token.as_deref(), Some("tok"));
901        assert_eq!(creds.email, "a@b.com");
902    }
903
904    /// A pre-Keycloak flat file is an API key, not a broken Keycloak
905    /// session: automation must keep working across this change.
906    #[test]
907    fn flat_token_file_loads_as_api_key() {
908        let (_dir, _lock, _guard) = with_credentials_file(
909            r#"{"server_url":"https://example.com","token":"tvk_abc","email":"a@b.com"}"#,
910        );
911        let creds = Credentials::load().expect("flat credentials file must load");
912        match creds.credential() {
913            Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_abc"),
914            other => panic!("expected an ApiKey credential, got {other:?}"),
915        }
916    }
917
918    /// A file with an `auth` object is a refreshable Keycloak session.
919    #[test]
920    fn file_with_auth_object_loads_as_keycloak() {
921        let (_dir, _lock, _guard) = with_credentials_file(
922            r#"{
923                "server_url":"https://example.com",
924                "email":"a@b.com",
925                "auth":{
926                    "issuer":"https://idp.test/realms/visdom",
927                    "client_id":"tracing-cli",
928                    "refresh_token":"rt",
929                    "access_token":"at",
930                    "access_expires_at":1893456000
931                }
932            }"#,
933        );
934        let creds = Credentials::load().expect("keycloak credentials file must load");
935        match creds.credential() {
936            Some(Credential::Keycloak(s)) => {
937                assert_eq!(s.issuer, "https://idp.test/realms/visdom");
938                assert_eq!(s.client_id, "tracing-cli");
939                assert_eq!(s.refresh_token, "rt");
940                assert_eq!(s.access_token, "at");
941                assert_eq!(s.access_expires_at, 1_893_456_000);
942            }
943            other => panic!("expected a Keycloak credential, got {other:?}"),
944        }
945    }
946
947    #[test]
948    fn no_token_and_no_auth_yields_no_credential() {
949        let (_dir, _lock, _guard) =
950            with_credentials_file(r#"{"server_url":"https://example.com","email":"a@b.com"}"#);
951        let creds = Credentials::load().unwrap();
952        assert!(creds.credential().is_none());
953    }
954
955    /// The refresh window is a `<` on the remaining lifetime: exactly 60s
956    /// left is still usable, 59s is not.
957    #[test]
958    fn needs_refresh_only_inside_the_sixty_second_window() {
959        let session = KeycloakSession {
960            issuer: "https://idp.test/realms/visdom".into(),
961            client_id: "tracing-cli".into(),
962            refresh_token: "rt".into(),
963            access_token: "at".into(),
964            access_expires_at: 1_000_000,
965        };
966        assert!(!session.needs_refresh(1_000_000 - 61));
967        assert!(!session.needs_refresh(1_000_000 - 60));
968        assert!(session.needs_refresh(1_000_000 - 59));
969        assert!(session.needs_refresh(1_000_000));
970        assert!(session.needs_refresh(1_000_001));
971    }
972
973    #[test]
974    fn apply_keeps_the_previous_refresh_token_when_none_is_returned() {
975        let mut session = KeycloakSession {
976            issuer: "i".into(),
977            client_id: "c".into(),
978            refresh_token: "old-rt".into(),
979            access_token: "old-at".into(),
980            access_expires_at: 10,
981        };
982        session.apply(
983            &TokenSet {
984                access_token: "new-at".into(),
985                refresh_token: None,
986                expires_in: 300,
987            },
988            1_000,
989        );
990        assert_eq!(session.access_token, "new-at");
991        assert_eq!(session.refresh_token, "old-rt");
992        assert_eq!(session.access_expires_at, 1_300);
993
994        session.apply(
995            &TokenSet {
996                access_token: "newer-at".into(),
997                refresh_token: Some("new-rt".into()),
998                expires_in: 60,
999            },
1000            2_000,
1001        );
1002        assert_eq!(session.refresh_token, "new-rt");
1003        assert_eq!(session.access_expires_at, 2_060);
1004    }
1005
1006    /// A saved Keycloak file must round-trip, must not invent a `token`
1007    /// field, and (on unix) must not be readable by anyone else.
1008    #[test]
1009    fn save_round_trips_keycloak_and_is_owner_only() {
1010        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1011        let dir = tempfile::tempdir().unwrap();
1012        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1013        _guard.set("XDG_CONFIG_HOME", dir.path());
1014
1015        let session = KeycloakSession {
1016            issuer: "https://idp.test/realms/visdom".into(),
1017            client_id: "tracing-cli".into(),
1018            refresh_token: "rt".into(),
1019            access_token: "at".into(),
1020            access_expires_at: 42,
1021        };
1022        Credentials::keycloak("https://example.com", "a@b.com".into(), session)
1023            .save()
1024            .unwrap();
1025
1026        let raw = fs::read_to_string(Credentials::path().unwrap()).unwrap();
1027        assert!(
1028            !raw.contains("\"token\""),
1029            "a Keycloak file must not carry an api-key `token` field: {raw}"
1030        );
1031        let reloaded = Credentials::load().unwrap();
1032        assert!(matches!(
1033            reloaded.credential(),
1034            Some(Credential::Keycloak(_))
1035        ));
1036
1037        #[cfg(unix)]
1038        {
1039            use std::os::unix::fs::PermissionsExt;
1040            let mode = fs::metadata(Credentials::path().unwrap())
1041                .unwrap()
1042                .permissions()
1043                .mode();
1044            assert_eq!(mode & 0o777, 0o600, "credentials must be owner-only");
1045        }
1046
1047        // The atomic-write temp file must not be left behind.
1048        let leftovers: Vec<_> = fs::read_dir(dir.path().join("tracevault"))
1049            .unwrap()
1050            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1051            .filter(|n| n != "credentials.json")
1052            .collect();
1053        assert!(
1054            leftovers.is_empty(),
1055            "temp files left behind: {leftovers:?}"
1056        );
1057    }
1058
1059    /// A stale temp file must not donate its mode to the credential file.
1060    ///
1061    /// `OpenOptions::mode()` only applies at CREATION, so opening an existing
1062    /// path keeps that path's mode — and the `rename` would then publish it as
1063    /// `credentials.json`'s. A crash under a looser umask is enough to leave
1064    /// such a file behind. This test pre-creates the exact temp path the old
1065    /// pid-only scheme used, with mode 0644; it fails (0644) without
1066    /// `create_new` + a unique suffix, and passes (0600) with them.
1067    #[cfg(unix)]
1068    #[test]
1069    fn a_stale_world_readable_temp_file_cannot_relax_the_credential_mode() {
1070        use std::os::unix::fs::PermissionsExt;
1071
1072        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1073        let dir = tempfile::tempdir().unwrap();
1074        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1075        _guard.set("XDG_CONFIG_HOME", dir.path());
1076
1077        let creds_dir = dir.path().join("tracevault");
1078        fs::create_dir_all(&creds_dir).unwrap();
1079        let stale = creds_dir.join(format!(".credentials.json.tmp{}", std::process::id()));
1080        fs::write(&stale, "leftover from a crashed run").unwrap();
1081        fs::set_permissions(&stale, fs::Permissions::from_mode(0o644)).unwrap();
1082
1083        Credentials::keycloak(
1084            "https://example.com",
1085            "a@b.com".into(),
1086            KeycloakSession {
1087                issuer: "i".into(),
1088                client_id: "c".into(),
1089                refresh_token: "rt".into(),
1090                access_token: "at".into(),
1091                access_expires_at: 1,
1092            },
1093        )
1094        .save()
1095        .expect("a stale temp file must not fail the save");
1096
1097        let mode = fs::metadata(Credentials::path().unwrap())
1098            .unwrap()
1099            .permissions()
1100            .mode();
1101        assert_eq!(
1102            mode & 0o777,
1103            0o600,
1104            "credentials.json inherited the stale temp file's mode"
1105        );
1106        // The tokens must not have been written into the stale file either.
1107        let stale_contents = fs::read_to_string(&stale).unwrap();
1108        assert!(
1109            !stale_contents.contains("rt"),
1110            "secrets were written into the pre-existing temp file: {stale_contents}"
1111        );
1112    }
1113
1114    /// Two saves in one process must both succeed: with `create_new` and a
1115    /// pid-only temp name they would collide on the same path, so the name also
1116    /// carries a process-local counter.
1117    #[test]
1118    fn repeated_saves_in_one_process_do_not_collide() {
1119        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1120        let dir = tempfile::tempdir().unwrap();
1121        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1122        _guard.set("XDG_CONFIG_HOME", dir.path());
1123
1124        let session = KeycloakSession {
1125            issuer: "i".into(),
1126            client_id: "c".into(),
1127            refresh_token: "rt".into(),
1128            access_token: "at".into(),
1129            access_expires_at: 1,
1130        };
1131        for i in 0..5 {
1132            Credentials::keycloak(
1133                "https://example.com",
1134                format!("a{i}@b.com"),
1135                session.clone(),
1136            )
1137            .save()
1138            .unwrap_or_else(|e| panic!("save #{i} failed: {e}"));
1139        }
1140        assert_eq!(Credentials::load().unwrap().email, "a4@b.com");
1141
1142        // No temp files left behind by any of the attempts.
1143        let leftovers: Vec<_> = fs::read_dir(dir.path().join("tracevault"))
1144            .unwrap()
1145            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1146            .filter(|n| n != "credentials.json")
1147            .collect();
1148        assert!(
1149            leftovers.is_empty(),
1150            "temp files left behind: {leftovers:?}"
1151        );
1152    }
1153
1154    /// Logout must leave no credential material behind. Every
1155    /// `.credentials.json.tmp*` holds a full credential JSON including the
1156    /// offline refresh token, so a leftover from a crashed save would otherwise
1157    /// keep a working token on disk after the user logged out.
1158    #[test]
1159    fn delete_also_removes_leftover_temp_files() {
1160        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1161        let dir = tempfile::tempdir().unwrap();
1162        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1163        _guard.set("XDG_CONFIG_HOME", dir.path());
1164
1165        let creds_dir = dir.path().join("tracevault");
1166        fs::create_dir_all(&creds_dir).unwrap();
1167        fs::write(creds_dir.join("credentials.json"), "{}").unwrap();
1168        // Two leftovers, in both the old pid-only and the current shapes.
1169        let old_shape = creds_dir.join(".credentials.json.tmp4242");
1170        let new_shape = creds_dir.join(".credentials.json.tmp4242.0.123");
1171        fs::write(&old_shape, r#"{"auth":{"refresh_token":"still-live-rt"}}"#).unwrap();
1172        fs::write(&new_shape, r#"{"auth":{"refresh_token":"still-live-rt"}}"#).unwrap();
1173
1174        Credentials::delete().unwrap();
1175
1176        assert!(!Credentials::path().unwrap().exists());
1177        let remaining: Vec<_> = fs::read_dir(&creds_dir)
1178            .unwrap()
1179            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1180            .collect();
1181        assert!(
1182            remaining.is_empty(),
1183            "logout left credential material on disk: {remaining:?}"
1184        );
1185    }
1186
1187    /// The `save()` sweep must not delete a temp file that another process
1188    /// could still be writing — that would break its `rename`. Only files past
1189    /// the staleness threshold go.
1190    #[test]
1191    fn save_sweeps_only_old_temp_files() {
1192        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1193        let dir = tempfile::tempdir().unwrap();
1194        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1195        _guard.set("XDG_CONFIG_HOME", dir.path());
1196
1197        let creds_dir = dir.path().join("tracevault");
1198        fs::create_dir_all(&creds_dir).unwrap();
1199        let fresh = creds_dir.join(".credentials.json.tmp999.0.1");
1200        fs::write(&fresh, "in flight in another process").unwrap();
1201
1202        Credentials::keycloak(
1203            "https://example.com",
1204            "a@b.com".into(),
1205            KeycloakSession {
1206                issuer: "i".into(),
1207                client_id: "c".into(),
1208                refresh_token: "rt".into(),
1209                access_token: "at".into(),
1210                access_expires_at: 1,
1211            },
1212        )
1213        .save()
1214        .unwrap();
1215
1216        assert!(
1217            fresh.exists(),
1218            "a just-created temp file may still be in flight elsewhere; sweeping it would break \
1219             that process's rename"
1220        );
1221    }
1222
1223    /// With no way to locate the user's config directory, `path()` must FAIL
1224    /// rather than invent one. The old fallback was `PathBuf::from("~/.config")`
1225    /// — a relative path, since only a shell expands `~` — so `login` created
1226    /// `./~/.config/tracevault/` in the current working directory and wrote an
1227    /// offline refresh token into it, plausibly inside the user's repo.
1228    #[test]
1229    fn path_fails_instead_of_inventing_a_relative_home() {
1230        let err = Credentials::path_in(None)
1231            .expect_err("no config directory must not yield a guessed path");
1232        let msg = err.to_string();
1233        assert!(
1234            msg.contains("XDG_CONFIG_HOME") && msg.contains("HOME"),
1235            "the error must name the variables to set: {msg}"
1236        );
1237        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
1238
1239        // The display helper degrades to an explanation, never to a path that
1240        // would be wrong to write to.
1241        let shown = Credentials::path_for_display();
1242        assert!(
1243            !shown.starts_with('~'),
1244            "a `~`-prefixed path must never be presented as a location: {shown}"
1245        );
1246
1247        // And with a real directory it still composes the same layout.
1248        let dir = tempfile::tempdir().unwrap();
1249        assert_eq!(
1250            Credentials::path_in(Some(dir.path().to_path_buf())).unwrap(),
1251            dir.path().join("tracevault").join("credentials.json")
1252        );
1253    }
1254
1255    /// Logging in must not destroy a `tvk_` API key already in the file: the two
1256    /// writers had opposite policies, with `persist_session` carefully
1257    /// preserving the token that `keycloak` silently dropped. The key stays
1258    /// inert while the session lives (`credential()` prefers the session) and is
1259    /// still there if the session is later removed.
1260    #[test]
1261    fn keycloak_preserves_an_existing_api_key_for_the_same_server() {
1262        // Stored WITH a trailing slash, while login is given it without: the
1263        // carry-over filter must normalise, not compare bytes.
1264        let (_dir, _lock, _guard) = with_credentials_file(
1265            r#"{"server_url":"https://example.com/","token":"tvk_precious","email":"old@b.com"}"#,
1266        );
1267
1268        Credentials::keycloak(
1269            "https://example.com",
1270            "new@b.com".into(),
1271            KeycloakSession {
1272                issuer: "i".into(),
1273                client_id: "c".into(),
1274                refresh_token: "rt".into(),
1275                access_token: "at".into(),
1276                access_expires_at: 1,
1277            },
1278        )
1279        .save()
1280        .unwrap();
1281
1282        let reloaded = Credentials::load().unwrap();
1283        assert_eq!(
1284            reloaded.token.as_deref(),
1285            Some("tvk_precious"),
1286            "login destroyed an API key it did not come to replace"
1287        );
1288        assert_eq!(reloaded.email, "new@b.com");
1289        // The session still wins for actual use.
1290        assert!(matches!(
1291            reloaded.credential(),
1292            Some(Credential::Keycloak(_))
1293        ));
1294    }
1295
1296    /// ...but a key belonging to a DIFFERENT instance is not carried into this
1297    /// instance's file: that is the same cross-instance mixing the resolution
1298    /// guards exist to prevent.
1299    #[test]
1300    fn keycloak_does_not_carry_over_another_servers_api_key() {
1301        let (_dir, _lock, _guard) = with_credentials_file(
1302            r#"{"server_url":"https://instance-b.example.com","token":"tvk_for_b","email":"b@b.com"}"#,
1303        );
1304
1305        Credentials::keycloak(
1306            "https://instance-a.example.com",
1307            "a@b.com".into(),
1308            KeycloakSession {
1309                issuer: "i".into(),
1310                client_id: "c".into(),
1311                refresh_token: "rt".into(),
1312                access_token: "at".into(),
1313                access_expires_at: 1,
1314            },
1315        )
1316        .save()
1317        .unwrap();
1318
1319        let reloaded = Credentials::load().unwrap();
1320        assert_eq!(
1321            reloaded.token, None,
1322            "another instance's key must not be moved into this instance's file"
1323        );
1324        assert_eq!(reloaded.server_url, "https://instance-a.example.com");
1325    }
1326
1327    /// A refresh must update only the `auth` block — the file's `email`
1328    /// (used by `tracevault status`) has to survive.
1329    #[test]
1330    fn persist_session_preserves_other_fields() {
1331        let (_dir, _lock, _guard) = with_credentials_file(
1332            r#"{
1333                "server_url":"https://example.com",
1334                "email":"a@b.com",
1335                "auth":{"issuer":"i","client_id":"c","refresh_token":"rt","access_token":"at","access_expires_at":1}
1336            }"#,
1337        );
1338        let mut session = match Credentials::load().unwrap().credential() {
1339            Some(Credential::Keycloak(s)) => s,
1340            other => panic!("expected Keycloak, got {other:?}"),
1341        };
1342        session.apply(
1343            &TokenSet {
1344                access_token: "at2".into(),
1345                refresh_token: Some("rt2".into()),
1346                expires_in: 300,
1347            },
1348            1_000,
1349        );
1350        Credentials::persist_session("https://example.com", &session).unwrap();
1351
1352        let reloaded = Credentials::load().unwrap();
1353        assert_eq!(reloaded.email, "a@b.com");
1354        assert_eq!(reloaded.server_url, "https://example.com");
1355        let auth = reloaded.auth.unwrap();
1356        assert_eq!(auth.access_token, "at2");
1357        assert_eq!(auth.refresh_token, "rt2");
1358        assert_eq!(auth.access_expires_at, 1_300);
1359    }
1360
1361    /// One credentials file, several possible TraceVault instances: persisting
1362    /// a refresh for instance A must not clobber a file that now belongs to
1363    /// instance B, which would silently sign the user out of B.
1364    #[test]
1365    fn persist_session_leaves_another_servers_file_alone() {
1366        let original = r#"{"server_url":"https://instance-b.example.com","email":"b@b.com","auth":{"issuer":"i","client_id":"c","refresh_token":"b-rt","access_token":"b-at","access_expires_at":99}}"#;
1367        let (_dir, _lock, _guard) = with_credentials_file(original);
1368
1369        let a_session = KeycloakSession {
1370            issuer: "i".into(),
1371            client_id: "c".into(),
1372            refresh_token: "a-rt".into(),
1373            access_token: "a-at".into(),
1374            access_expires_at: 1_234,
1375        };
1376        Credentials::persist_session("https://instance-a.example.com", &a_session)
1377            .expect("a foreign file is a skip, not an error");
1378
1379        let after = fs::read_to_string(Credentials::path().unwrap()).unwrap();
1380        assert_eq!(after, original, "another server's file was overwritten");
1381
1382        // The other direction at this same call site: the file's URL differing
1383        // only by a trailing slash IS this server, so the write must happen.
1384        // Without this half, replacing `same_server` with `!=`/`==` here goes
1385        // unnoticed and quietly disables persistence — the state the skip
1386        // warning exists to explain.
1387        fs::write(
1388            Credentials::path().unwrap(),
1389            r#"{"server_url":"https://instance-a.example.com/","email":"a@b.com","auth":{"issuer":"i","client_id":"c","refresh_token":"old","access_token":"old","access_expires_at":1}}"#,
1390        )
1391        .unwrap();
1392        Credentials::persist_session("https://instance-a.example.com", &a_session).unwrap();
1393        let auth = Credentials::load().unwrap().auth.unwrap();
1394        assert_eq!(
1395            auth.access_token, "a-at",
1396            "a trailing slash must not block a legitimate persist"
1397        );
1398    }
1399
1400    /// The single owner of the normalisation property: the two sides of the
1401    /// comparison are formatted differently by construction (`ApiClient` trims
1402    /// trailing slashes, the file keeps whatever login was given), so a trailing
1403    /// slash must count as a match. Call sites only prove that they consult
1404    /// `same_server`, via their mismatch tests.
1405    #[test]
1406    fn same_server_normalises_trailing_slashes_and_whitespace() {
1407        assert!(same_server(
1408            "https://x.example.com",
1409            "https://x.example.com/"
1410        ));
1411        assert!(same_server(
1412            " https://x.example.com/ ",
1413            "https://x.example.com"
1414        ));
1415        assert!(!same_server(
1416            "https://x.example.com",
1417            "https://y.example.com"
1418        ));
1419        // A different path is a different instance, not a formatting variant.
1420        assert!(!same_server(
1421            "https://x.example.com",
1422            "https://x.example.com/tv"
1423        ));
1424    }
1425
1426    #[test]
1427    fn persist_session_on_a_missing_file_is_not_an_error() {
1428        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1429        let dir = tempfile::tempdir().unwrap();
1430        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1431        _guard.set("XDG_CONFIG_HOME", dir.path());
1432
1433        let session = KeycloakSession {
1434            issuer: "i".into(),
1435            client_id: "c".into(),
1436            refresh_token: "rt".into(),
1437            access_token: "at".into(),
1438            access_expires_at: 1,
1439        };
1440        Credentials::persist_session("https://example.com", &session)
1441            .expect("a logged-out user must not turn a refresh into a hard error");
1442        assert!(
1443            !Credentials::path().unwrap().exists(),
1444            "persist_session must not resurrect a deleted credentials file"
1445        );
1446    }
1447
1448    #[test]
1449    fn debug_impls_redact_secrets() {
1450        let creds = Credentials {
1451            server_url: "https://example.com".into(),
1452            token: Some("tvk_secret".into()),
1453            email: "a@b".into(),
1454            auth: None,
1455        };
1456        let dbg = format!("{creds:?}");
1457        assert!(!dbg.contains("tvk_secret"), "api key leaked: {dbg}");
1458
1459        let creds = Credentials::keycloak(
1460            "https://example.com",
1461            "a@b".into(),
1462            KeycloakSession {
1463                issuer: "i".into(),
1464                client_id: "c".into(),
1465                refresh_token: "secret-rt".into(),
1466                access_token: "secret-at".into(),
1467                access_expires_at: 1,
1468            },
1469        );
1470        let dbg = format!("{creds:?}");
1471        assert!(!dbg.contains("secret-rt"), "refresh token leaked: {dbg}");
1472        assert!(!dbg.contains("secret-at"), "access token leaked: {dbg}");
1473    }
1474}