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