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 /// has no `tracevault` grant in Control Plane).
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 resolve_credentials_inner(project_root, true)
507}
508
509/// [`resolve_credentials`] without the config-conflict warning.
510///
511/// For the two callers where that warning is wrong or unbearable:
512///
513/// - `init`, which has just REWRITTEN the very pin the warning compares
514/// against, and whose `--server-url` then wins over the resolved URL
515/// (`effective_url` in `init_in_directory`). The warning claims the login's
516/// URL is being used, which on that path is simply false, and advises the
517/// user to do what they are already doing.
518/// - `stream`, the hook path: one process per captured event, so a repo with a
519/// losing pin would print the line on every single tool call, for the whole
520/// session. `Once` cannot help — each event is a fresh process.
521#[allow(clippy::type_complexity)]
522pub fn resolve_credentials_quiet(
523 project_root: &Path,
524) -> Result<(Option<String>, Option<Credential>), Box<dyn std::error::Error>> {
525 resolve_credentials_inner(project_root, false)
526}
527
528#[allow(clippy::type_complexity)]
529fn resolve_credentials_inner(
530 project_root: &Path,
531 warn_on_conflict: bool,
532) -> Result<(Option<String>, Option<Credential>), Box<dyn std::error::Error>> {
533 // 1. Env var API key
534 let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
535
536 // 2. Credentials file
537 let creds = Credentials::load();
538
539 // 3. Project config — parsed as TOML by its own loader, not by hand.
540 //
541 // The previous line-scanning version split on `=` and took field 1, so a
542 // perfectly legal `api_key = "tvk_abc=="` resolved to `tvk_abc`: a silently
543 // truncated key, surfacing later as an unexplained 401 that (by design) is
544 // never retried. It also matched any line merely STARTING with the field
545 // name (`server_url_backup`) and read keys nested under a `[table]` as
546 // though they were top-level. `TracevaultConfig` already declares both
547 // fields, so the hand-parse only existed to duplicate it — badly. Using
548 // `load` also means a malformed config now warns instead of silently
549 // yielding nothing.
550 let config = crate::config::TracevaultConfig::load(project_root);
551 let config_server_url = config.as_ref().and_then(|c| c.server_url.clone());
552 let config_api_key = config.as_ref().and_then(|c| c.api_key.clone());
553
554 // Surface the pairing the guard below structurally cannot see. That guard's
555 // own comment notes it is "only reachable when TRACEVAULT_SERVER_URL is set:
556 // with it unset the URL comes from this same file, so the two match by
557 // construction" — true only because `config.toml` has already lost the
558 // precedence race on the next line, silently.
559 if warn_on_conflict {
560 if let Some((file_url, config_url)) = config_url_conflict(
561 config_server_url.as_deref(),
562 creds.as_ref().map(|c| c.server_url.as_str()),
563 std::env::var("TRACEVAULT_SERVER_URL").is_ok(),
564 ) {
565 // Once per process: `repo status` resolves twice in one command
566 // (`resolve_repo_flag` and the codebase line), and printing the
567 // identical line back to back reads like a bug.
568 static WARNED: std::sync::Once = std::sync::Once::new();
569 WARNED.call_once(|| {
570 eprintln!("{}", config_mismatch_warning(file_url, config_url));
571 });
572 }
573 }
574
575 // Resolve server URL: env > creds > config
576 let server_url = std::env::var("TRACEVAULT_SERVER_URL")
577 .ok()
578 .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
579 .or(config_server_url);
580
581 // Resolve the credential: env api key > credentials file > config api key
582 let credential = match env_key {
583 // Named explicitly on this invocation: the operator's choice of
584 // key/URL pairing is deliberate and is not second-guessed.
585 Some(key) => Some(Credential::ApiKey(key)),
586 None => {
587 let from_file = creds.as_ref().and_then(Credentials::credential);
588 if from_file.is_some() {
589 // The two precedence chains above disagree: the URL can come
590 // from the env while the credential comes from the file. Every
591 // credential in that file — a Keycloak access token or a `tvk_`
592 // API key alike — was issued by ONE TraceVault instance, so
593 // handing it to a client pointed elsewhere transmits a secret to
594 // a host it was never issued for, which then has it in its logs.
595 //
596 // This is the FIRST request, before any refresh, so neither
597 // server-scoping guard in `refresh_locked` would see it.
598 //
599 // Only reachable when TRACEVAULT_SERVER_URL is set: with it
600 // unset the URL comes from this same file, so the two match by
601 // construction.
602 let file_url = creds.as_ref().map_or("", |c| c.server_url.as_str());
603 if let Some(target) = server_url.as_deref() {
604 if !same_server(file_url, target) {
605 return Err(server_mismatch_error(file_url, target));
606 }
607 }
608 }
609 // A `config.toml` `api_key` is NOT guarded: committing a key to a
610 // project config, next to that config's own `server_url`, is as
611 // deliberate as naming it in the environment. It is also only
612 // reachable when the file yielded nothing.
613 from_file.or_else(|| config_api_key.map(Credential::ApiKey))
614 }
615 };
616
617 Ok((server_url, credential))
618}
619
620/// Whether a repo-local `config.toml` `server_url` disagrees with the
621/// credentials file's. Returns `(file_url, config_url)` when they conflict.
622///
623/// Deliberately a WARNING rather than a refusal, which is the whole difference
624/// from [`server_mismatch_error`]. There, the env-supplied URL is the one
625/// actually contacted, so refusing genuinely stops a token reaching a host it
626/// was not issued for. Here the config's URL has ALREADY lost the precedence
627/// race below and is never contacted, so refusing would prevent nothing — while
628/// handing anyone who can land a `.tracevault/config.toml` in a repo you clone a
629/// way to break every command (see
630/// `verification_phase::tests::a_committed_config_url_cannot_redirect_the_token`,
631/// which pins that a committed config URL is inert). The defect this addresses
632/// was never that the wrong URL got used; it was that the disagreement was
633/// SILENT — `tracevault sync` printed "Repo synced with server" while
634/// registering the repo on the logged-in instance instead of the pinned one.
635///
636/// `env_url_set` suppresses it: `TRACEVAULT_SERVER_URL` outranks both, so the
637/// pin is moot and the mismatch it can cause is already guarded below. Taken as
638/// a bool rather than read here so this stays pure and directly testable.
639pub(crate) fn config_url_conflict<'a>(
640 config_url: Option<&'a str>,
641 file_url: Option<&'a str>,
642 env_url_set: bool,
643) -> Option<(&'a str, &'a str)> {
644 if env_url_set {
645 return None;
646 }
647 let (config_url, file_url) = (config_url?, file_url?);
648 (!same_server(file_url, config_url)).then_some((file_url, config_url))
649}
650
651/// The warning text for [`config_url_conflict`].
652///
653/// Names BOTH URLs and says which one wins. `tracevault status` reports the
654/// credentials file's URL and does not read `config.toml` at all, so without
655/// naming them the user can see neither side of the disagreement — which is
656/// exactly how this went unnoticed long enough to register a repo on the wrong
657/// instance.
658fn config_mismatch_warning(file_url: &str, config_url: &str) -> String {
659 format!(
660 "tracevault: warning: this repo's .tracevault/config.toml pins '{config_url}', but you \
661 are logged in to '{file_url}' — using '{file_url}'. Run `tracevault login --server-url \
662 {config_url}` to use the repo's instance, or remove `server_url` from \
663 .tracevault/config.toml to silence this."
664 )
665}
666
667/// The error for "the saved credential is for a different TraceVault instance".
668///
669/// Applies to any FILE-SOURCED credential, Keycloak session or `tvk_` key
670/// alike: both are secrets issued by one instance, and a key would not even
671/// work against another instance — so without this the user gets a confusing
672/// 401 from the wrong host instead of an explanation.
673///
674/// Names BOTH URLs, because the whole failure is that two of them disagree and
675/// the user can see neither: `tracevault status` reports the file's URL, and
676/// the env var is often set in a shell profile or a CI job definition rather
677/// than on the command line.
678///
679/// The third suggestion matters: pointing at the SAME instance through another
680/// address (a `kubectl port-forward`, an internal vs. external hostname) is a
681/// legitimate workflow that this guard cannot distinguish from a genuine
682/// mismatch, so the message names the ways to proceed deliberately.
683fn server_mismatch_error(file_url: &str, target: &str) -> Box<dyn std::error::Error> {
684 format!(
685 "refusing to use the saved credentials: the credentials file is for '{file_url}', but \
686 this command is targeting '{target}'. A credential issued by one TraceVault instance \
687 must not be sent to another.\n\
688 Either unset TRACEVAULT_SERVER_URL to use '{file_url}', or run `tracevault login \
689 --server-url {target}`. If '{target}' is the same instance reached through a different \
690 address (e.g. a port-forward), set TRACEVAULT_API_KEY to a `tvk_` key for it instead."
691 )
692 .into()
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698
699 /// Redirect `XDG_CONFIG_HOME` at a tempdir and write `body` as the
700 /// credentials file. Returns the tempdir plus both guards, which the
701 /// caller must keep alive for the duration of the test (the env lock is
702 /// released, and the real `~/.config` restored, when they drop).
703 fn with_credentials_file(
704 body: &str,
705 ) -> (
706 tempfile::TempDir,
707 tokio::sync::MutexGuard<'static, ()>,
708 crate::test_helpers::EnvVarGuard,
709 ) {
710 let env_lock = crate::test_helpers::lock_env_mutation_sync();
711 let dir = tempfile::tempdir().unwrap();
712 let mut guard = crate::test_helpers::EnvVarGuard::new();
713 guard.set("XDG_CONFIG_HOME", dir.path());
714 let creds_dir = dir.path().join("tracevault");
715 fs::create_dir_all(&creds_dir).unwrap();
716 fs::write(creds_dir.join("credentials.json"), body).unwrap();
717 (dir, env_lock, guard)
718 }
719
720 /// Fixed "now" for the resolution fixtures. A constant rather than the wall
721 /// clock so nothing here depends on timing.
722 const NOW: i64 = 1_800_000_000;
723
724 /// Write a Keycloak credentials file for `server_url`/`issuer` into `dir`.
725 fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
726 let creds_dir = dir.join("tracevault");
727 fs::create_dir_all(&creds_dir).unwrap();
728 fs::write(
729 creds_dir.join("credentials.json"),
730 format!(
731 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}}}}}"#
732 ),
733 )
734 .unwrap();
735 }
736
737 // ---- resolve_credentials: a credential read from the FILE must not follow
738 // ---- a TRACEVAULT_SERVER_URL override to another instance. Applies to a
739 // ---- Keycloak session and a `tvk_` key alike; an env- or config-supplied
740 // ---- key is a deliberate operator act and is left alone.
741
742 type ResolveFixture = (
743 tempfile::TempDir,
744 tokio::sync::MutexGuard<'static, ()>,
745 crate::test_helpers::EnvVarGuard,
746 );
747
748 /// Set up an empty project root with `TRACEVAULT_SERVER_URL` set to
749 /// `env_url` (unset when `None`) and `credentials.json` containing
750 /// `file_body` (no file when `None`). Returns the tempdir (which doubles as
751 /// the project root) plus the guards the caller must keep alive.
752 fn resolve_fixture_with(file_body: Option<&str>, env_url: Option<&str>) -> ResolveFixture {
753 let env_lock = crate::test_helpers::lock_env_mutation_sync();
754 let dir = tempfile::tempdir().unwrap();
755 let mut guard = crate::test_helpers::EnvVarGuard::new();
756 guard.set("XDG_CONFIG_HOME", dir.path());
757 // A stray key in the developer's environment would take precedence and
758 // mask what these tests are checking.
759 guard.remove("TRACEVAULT_API_KEY");
760 match env_url {
761 Some(u) => guard.set("TRACEVAULT_SERVER_URL", u),
762 None => guard.remove("TRACEVAULT_SERVER_URL"),
763 }
764 if let Some(body) = file_body {
765 let creds_dir = dir.path().join("tracevault");
766 fs::create_dir_all(&creds_dir).unwrap();
767 fs::write(creds_dir.join("credentials.json"), body).unwrap();
768 }
769 (dir, env_lock, guard)
770 }
771
772 /// [`resolve_fixture_with`] for a file holding a Keycloak session.
773 fn resolve_fixture(file_server_url: &str, env_url: Option<&str>) -> ResolveFixture {
774 let fixture = resolve_fixture_with(None, env_url);
775 write_keycloak_file(
776 fixture.0.path(),
777 file_server_url,
778 "https://idp.test/realms/v",
779 NOW + 3600,
780 );
781 fixture
782 }
783
784 /// [`resolve_fixture_with`] for a file holding a `tvk_` API key.
785 fn resolve_fixture_api_key(file_server_url: &str, env_url: Option<&str>) -> ResolveFixture {
786 resolve_fixture_with(
787 Some(&format!(
788 r#"{{"server_url":"{file_server_url}","token":"tvk_from_file","email":"a@b.com"}}"#
789 )),
790 env_url,
791 )
792 }
793
794 /// The precedence chains disagree: the URL comes from the env, the
795 /// credential from the file. Handing either kind over would send a secret
796 /// minted by instance B to instance A on the FIRST request, before any
797 /// refresh, so neither guard in `refresh_locked` would ever see it.
798 ///
799 /// Both credential kinds are checked here because the distinction that
800 /// matters is not Keycloak-vs-key but named-on-this-invocation
801 /// vs. read-from-the-file — and because the two assert the same message.
802 #[test]
803 fn a_mismatched_server_url_refuses_either_kind_of_file_credential() {
804 for kind in ["keycloak session", "api key"] {
805 let (dir, _lock, _guard) = if kind == "keycloak session" {
806 resolve_fixture(
807 "https://instance-b.example.com",
808 Some("https://instance-a.example.com"),
809 )
810 } else {
811 resolve_fixture_api_key(
812 "https://instance-b.example.com",
813 Some("https://instance-a.example.com"),
814 )
815 };
816
817 let err = resolve_credentials(dir.path())
818 .expect_err("a credential for another instance must not be handed out");
819 let msg = err.to_string();
820 // Both URLs must be named: the user can see neither (status prints
821 // the file's, and the env var is usually set in a profile or CI job).
822 assert!(
823 msg.contains("https://instance-b.example.com"),
824 "{kind}: must name the file's server: {msg}"
825 );
826 assert!(
827 msg.contains("https://instance-a.example.com"),
828 "{kind}: must name the targeted server: {msg}"
829 );
830 // And it must point at the deliberate ways forward, including the
831 // same-instance-different-address case this guard cannot
832 // distinguish from a real mismatch.
833 assert!(msg.contains("TRACEVAULT_SERVER_URL"), "{kind}: {msg}");
834 assert!(msg.contains("tracevault login"), "{kind}: {msg}");
835 assert!(msg.contains("TRACEVAULT_API_KEY"), "{kind}: {msg}");
836 assert!(
837 !msg.contains("tvk_from_file"),
838 "{kind}: the error must not echo the credential: {msg}"
839 );
840 }
841 }
842
843 /// The two sides are formatted differently by construction (`ApiClient`
844 /// trims trailing slashes, the file keeps what login was given), so a
845 /// trailing slash must not be read as "a different instance". This guard
846 /// hard-FAILS, so a false positive here would break every command — hence
847 /// one positive test, while the other call sites need only prove that they
848 /// consult `same_server` at all, which their mismatch tests do.
849 #[test]
850 fn a_matching_server_url_modulo_trailing_slash_still_resolves() {
851 let (dir, _lock, _guard) =
852 resolve_fixture("https://example.com/", Some("https://example.com"));
853
854 let (url, credential) =
855 resolve_credentials(dir.path()).expect("a trailing slash is not a different instance");
856 assert_eq!(url.as_deref(), Some("https://example.com"));
857 assert!(matches!(credential, Some(Credential::Keycloak(_))));
858 }
859
860 /// The normal case: no env override, so the URL comes from the same file as
861 /// the credential and they match by construction.
862 #[test]
863 fn no_env_override_resolves_the_files_session_unchanged() {
864 let (dir, _lock, _guard) = resolve_fixture("https://example.com", None);
865
866 let (url, credential) = resolve_credentials(dir.path()).expect("the normal case must work");
867 assert_eq!(url.as_deref(), Some("https://example.com"));
868 assert!(matches!(credential, Some(Credential::Keycloak(_))));
869 }
870
871 /// The config is parsed as TOML, not scanned line by line. A base64-ish key
872 /// containing `=` used to be truncated at the first `=` (`tvk_abc==` ->
873 /// `tvk_abc`), producing an unexplained 401 that the `ApiKey` path
874 /// deliberately never retries.
875 #[test]
876 fn a_config_api_key_containing_equals_signs_is_not_truncated() {
877 let (dir, _lock, _guard) = resolve_fixture_with(None, None);
878 let config_dir = dir.path().join(".tracevault");
879 fs::create_dir_all(&config_dir).unwrap();
880 fs::write(
881 config_dir.join("config.toml"),
882 "server_url = \"https://example.com\"\napi_key = \"tvk_YWJjZA==\"\n",
883 )
884 .unwrap();
885
886 let (url, credential) = resolve_credentials(dir.path()).unwrap();
887 assert_eq!(url.as_deref(), Some("https://example.com"));
888 match credential {
889 Some(Credential::ApiKey(k)) => assert_eq!(
890 k, "tvk_YWJjZA==",
891 "the key must survive verbatim, `=` padding and all"
892 ),
893 other => panic!("expected the config API key, got {other:?}"),
894 }
895 }
896
897 /// Line-scanning also matched any field whose name merely STARTED with the
898 /// one being looked for, and read a key nested in a `[table]` as top-level.
899 /// TOML parsing gets both right.
900 #[test]
901 fn a_config_lookalike_field_is_not_mistaken_for_the_real_one() {
902 let (dir, _lock, _guard) = resolve_fixture_with(None, None);
903 let config_dir = dir.path().join(".tracevault");
904 fs::create_dir_all(&config_dir).unwrap();
905 fs::write(
906 config_dir.join("config.toml"),
907 "server_url = \"https://real.example.com\"\n\
908 [user_context]\n\
909 enable = false\n",
910 )
911 .unwrap();
912
913 let (url, credential) = resolve_credentials(dir.path()).unwrap();
914 assert_eq!(url.as_deref(), Some("https://real.example.com"));
915 assert!(
916 credential.is_none(),
917 "no api_key is configured anywhere, so there is no credential"
918 );
919 }
920
921 /// A `config.toml` `api_key` is committed next to that config's own
922 /// `server_url`: as deliberate as naming it in the environment, so a URL
923 /// override must not break it. (It is also only consulted when the
924 /// credentials file yielded nothing, as here.)
925 #[test]
926 fn a_config_api_key_is_unaffected_by_a_mismatched_server_url() {
927 let (dir, _lock, _guard) =
928 resolve_fixture_with(None, Some("https://instance-a.example.com"));
929 let config_dir = dir.path().join(".tracevault");
930 fs::create_dir_all(&config_dir).unwrap();
931 fs::write(
932 config_dir.join("config.toml"),
933 "server_url = \"https://instance-b.example.com\"\napi_key = \"tvk_from_config\"\n",
934 )
935 .unwrap();
936
937 let (url, credential) = resolve_credentials(dir.path())
938 .expect("a config-supplied key must never be second-guessed");
939 assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
940 match credential {
941 Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_from_config"),
942 other => panic!("expected the config API key, got {other:?}"),
943 }
944 }
945
946 /// `TRACEVAULT_API_KEY` plus a URL pointing anywhere is a deliberate,
947 /// explicit act by the operator (and the CI path). It must be unaffected.
948 #[test]
949 fn an_env_api_key_is_unaffected_by_a_mismatched_server_url() {
950 let (dir, _lock, mut guard) = resolve_fixture(
951 "https://instance-b.example.com",
952 Some("https://instance-a.example.com"),
953 );
954 guard.set("TRACEVAULT_API_KEY", "tvk_abc");
955
956 let (url, credential) = resolve_credentials(dir.path())
957 .expect("an explicitly supplied API key must never be second-guessed");
958 assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
959 match credential {
960 Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_abc"),
961 other => panic!("expected the env API key, got {other:?}"),
962 }
963 }
964
965 // ---- config_url_conflict: a repo-local `.tracevault/config.toml`
966 // ---- `server_url` sits BELOW the credentials file, so it loses silently.
967 // ---- It stays losing — it must only stop being silent.
968
969 /// Write a project-level `.tracevault/config.toml` under `root`.
970 fn write_project_config(root: &std::path::Path, body: &str) {
971 let config_dir = root.join(".tracevault");
972 fs::create_dir_all(&config_dir).unwrap();
973 fs::write(config_dir.join("config.toml"), body).unwrap();
974 }
975
976 #[test]
977 fn a_config_url_differing_from_the_files_is_a_conflict() {
978 assert_eq!(
979 config_url_conflict(
980 Some("https://pinned.example.com"),
981 Some("https://login.example.com"),
982 false
983 ),
984 Some(("https://login.example.com", "https://pinned.example.com")),
985 "the file's URL is returned first, as the one actually used"
986 );
987 }
988
989 /// The config is hand-authored while the file records whatever `login` was
990 /// given, so the two are formatted independently. A trailing slash must not
991 /// read as a disagreement, or every correctly-configured repo warns forever
992 /// and the warning stops being read.
993 #[test]
994 fn a_trailing_slash_is_not_a_conflict() {
995 assert_eq!(
996 config_url_conflict(
997 Some("https://example.com"),
998 Some("https://example.com/"),
999 false
1000 ),
1001 None
1002 );
1003 }
1004
1005 /// `TRACEVAULT_SERVER_URL` outranks both, so the pin is moot and the
1006 /// env-vs-file guard already covers that pairing.
1007 #[test]
1008 fn an_env_server_url_suppresses_the_conflict() {
1009 assert_eq!(
1010 config_url_conflict(
1011 Some("https://pinned.example.com"),
1012 Some("https://login.example.com"),
1013 true
1014 ),
1015 None
1016 );
1017 }
1018
1019 /// Nothing to disagree with on either side.
1020 #[test]
1021 fn a_missing_side_is_never_a_conflict() {
1022 assert_eq!(
1023 config_url_conflict(None, Some("https://login.example.com"), false),
1024 None
1025 );
1026 assert_eq!(
1027 config_url_conflict(Some("https://pinned.example.com"), None, false),
1028 None
1029 );
1030 }
1031
1032 /// The warning has to carry what neither `status` nor the success line ever
1033 /// showed: both URLs, and which one is actually being used.
1034 #[test]
1035 fn the_warning_names_both_urls_and_the_winner() {
1036 let msg = config_mismatch_warning("https://login.example.com", "http://localhost:8080");
1037 assert!(
1038 msg.contains("http://localhost:8080"),
1039 "must name the pin: {msg}"
1040 );
1041 assert!(
1042 msg.contains("https://login.example.com"),
1043 "must name the login: {msg}"
1044 );
1045 assert!(
1046 msg.contains("config.toml"),
1047 "must name where the pin lives: {msg}"
1048 );
1049 assert!(
1050 msg.contains("tracevault login"),
1051 "must name the way forward: {msg}"
1052 );
1053 }
1054
1055 /// The behavioural contract, and the reason this is a warning and not a
1056 /// refusal: a `config.toml` `server_url` remains inert. A committed one is
1057 /// attacker-controlled (see
1058 /// `verification_phase::tests::a_committed_config_url_cannot_redirect_the_token`),
1059 /// so it must neither redirect the credential NOR break the command.
1060 #[test]
1061 fn a_conflicting_config_url_still_resolves_to_the_files_instance() {
1062 for kind in ["keycloak session", "api key"] {
1063 let (dir, _lock, _guard) = if kind == "keycloak session" {
1064 resolve_fixture("https://instance-b.example.com", None)
1065 } else {
1066 resolve_fixture_api_key("https://instance-b.example.com", None)
1067 };
1068 write_project_config(dir.path(), "server_url = \"https://attacker.invalid\"\n");
1069
1070 let (url, credential) = resolve_credentials(dir.path())
1071 .expect("a conflicting config must warn, never break the command");
1072 assert_eq!(
1073 url.as_deref(),
1074 Some("https://instance-b.example.com"),
1075 "{kind}: the config URL must stay inert"
1076 );
1077 assert!(credential.is_some(), "{kind}: the credential must survive");
1078 }
1079 }
1080
1081 /// A config carrying its own `api_key` changes nothing: the file still wins
1082 /// both the URL and the credential, so the config's key is never sent
1083 /// anywhere. It is only consulted when the file yields nothing.
1084 #[test]
1085 fn a_conflicting_config_with_its_own_key_still_resolves_to_the_file() {
1086 let (dir, _lock, _guard) = resolve_fixture("https://instance-b.example.com", None);
1087 write_project_config(
1088 dir.path(),
1089 "server_url = \"https://instance-a.example.com\"\napi_key = \"tvk_from_config\"\n",
1090 );
1091
1092 let (url, credential) = resolve_credentials(dir.path()).unwrap();
1093 assert_eq!(url.as_deref(), Some("https://instance-b.example.com"));
1094 assert!(
1095 matches!(credential, Some(Credential::Keycloak(_))),
1096 "the file's session wins; the config key is never reached"
1097 );
1098 }
1099
1100 /// With no credentials file there is no disagreement, so the config's
1101 /// `server_url` is used exactly as before.
1102 #[test]
1103 fn a_config_server_url_is_used_when_there_is_no_credentials_file() {
1104 let (dir, _lock, _guard) = resolve_fixture_with(None, None);
1105 write_project_config(
1106 dir.path(),
1107 "server_url = \"https://instance-a.example.com\"\n",
1108 );
1109
1110 let (url, _credential) = resolve_credentials(dir.path()).unwrap();
1111 assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
1112 }
1113
1114 /// Old on-disk `credentials.json` files may still contain `org_slug`
1115 /// from before the single-tenant org removal (mirrors config.rs's
1116 /// `load_old_config_with_org_slug_still_parses`). serde must silently
1117 /// ignore the unknown field rather than fail to parse (no
1118 /// `deny_unknown_fields` on `Credentials`), so `Credentials::load()` keeps
1119 /// working on an un-migrated credentials file.
1120 ///
1121 /// `XDG_CONFIG_HOME` is redirected to a tempdir so this reads a fixture
1122 /// file rather than the developer's real
1123 /// `~/.config/tracevault/credentials.json`; `_env_lock` serializes this
1124 /// against other tests in the crate that mutate the same env var (see
1125 /// `test_helpers::lock_env_mutation_sync`).
1126 #[test]
1127 fn load_old_credentials_with_org_slug_still_parses() {
1128 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1129 let dir = tempfile::tempdir().unwrap();
1130 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1131 _guard.set("XDG_CONFIG_HOME", dir.path());
1132
1133 let creds_dir = dir.path().join("tracevault");
1134 fs::create_dir_all(&creds_dir).unwrap();
1135 fs::write(
1136 creds_dir.join("credentials.json"),
1137 r#"{"server_url":"https://example.com","token":"tok","email":"a@b.com","org_slug":"x"}"#,
1138 )
1139 .unwrap();
1140
1141 let creds =
1142 Credentials::load().expect("old credentials.json with org_slug must still parse");
1143 assert_eq!(creds.server_url, "https://example.com");
1144 assert_eq!(creds.token.as_deref(), Some("tok"));
1145 assert_eq!(creds.email, "a@b.com");
1146 }
1147
1148 /// A pre-Keycloak flat file is an API key, not a broken Keycloak
1149 /// session: automation must keep working across this change.
1150 #[test]
1151 fn flat_token_file_loads_as_api_key() {
1152 let (_dir, _lock, _guard) = with_credentials_file(
1153 r#"{"server_url":"https://example.com","token":"tvk_abc","email":"a@b.com"}"#,
1154 );
1155 let creds = Credentials::load().expect("flat credentials file must load");
1156 match creds.credential() {
1157 Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_abc"),
1158 other => panic!("expected an ApiKey credential, got {other:?}"),
1159 }
1160 }
1161
1162 /// A file with an `auth` object is a refreshable Keycloak session.
1163 #[test]
1164 fn file_with_auth_object_loads_as_keycloak() {
1165 let (_dir, _lock, _guard) = with_credentials_file(
1166 r#"{
1167 "server_url":"https://example.com",
1168 "email":"a@b.com",
1169 "auth":{
1170 "issuer":"https://idp.test/realms/visdom",
1171 "client_id":"tracing-cli",
1172 "refresh_token":"rt",
1173 "access_token":"at",
1174 "access_expires_at":1893456000
1175 }
1176 }"#,
1177 );
1178 let creds = Credentials::load().expect("keycloak credentials file must load");
1179 match creds.credential() {
1180 Some(Credential::Keycloak(s)) => {
1181 assert_eq!(s.issuer, "https://idp.test/realms/visdom");
1182 assert_eq!(s.client_id, "tracing-cli");
1183 assert_eq!(s.refresh_token, "rt");
1184 assert_eq!(s.access_token, "at");
1185 assert_eq!(s.access_expires_at, 1_893_456_000);
1186 }
1187 other => panic!("expected a Keycloak credential, got {other:?}"),
1188 }
1189 }
1190
1191 #[test]
1192 fn no_token_and_no_auth_yields_no_credential() {
1193 let (_dir, _lock, _guard) =
1194 with_credentials_file(r#"{"server_url":"https://example.com","email":"a@b.com"}"#);
1195 let creds = Credentials::load().unwrap();
1196 assert!(creds.credential().is_none());
1197 }
1198
1199 /// The refresh window is a `<` on the remaining lifetime: exactly 60s
1200 /// left is still usable, 59s is not.
1201 #[test]
1202 fn needs_refresh_only_inside_the_sixty_second_window() {
1203 let session = KeycloakSession {
1204 issuer: "https://idp.test/realms/visdom".into(),
1205 client_id: "tracing-cli".into(),
1206 refresh_token: "rt".into(),
1207 access_token: "at".into(),
1208 access_expires_at: 1_000_000,
1209 };
1210 assert!(!session.needs_refresh(1_000_000 - 61));
1211 assert!(!session.needs_refresh(1_000_000 - 60));
1212 assert!(session.needs_refresh(1_000_000 - 59));
1213 assert!(session.needs_refresh(1_000_000));
1214 assert!(session.needs_refresh(1_000_001));
1215 }
1216
1217 #[test]
1218 fn apply_keeps_the_previous_refresh_token_when_none_is_returned() {
1219 let mut session = KeycloakSession {
1220 issuer: "i".into(),
1221 client_id: "c".into(),
1222 refresh_token: "old-rt".into(),
1223 access_token: "old-at".into(),
1224 access_expires_at: 10,
1225 };
1226 session.apply(
1227 &TokenSet {
1228 access_token: "new-at".into(),
1229 refresh_token: None,
1230 expires_in: 300,
1231 },
1232 1_000,
1233 );
1234 assert_eq!(session.access_token, "new-at");
1235 assert_eq!(session.refresh_token, "old-rt");
1236 assert_eq!(session.access_expires_at, 1_300);
1237
1238 session.apply(
1239 &TokenSet {
1240 access_token: "newer-at".into(),
1241 refresh_token: Some("new-rt".into()),
1242 expires_in: 60,
1243 },
1244 2_000,
1245 );
1246 assert_eq!(session.refresh_token, "new-rt");
1247 assert_eq!(session.access_expires_at, 2_060);
1248 }
1249
1250 /// A saved Keycloak file must round-trip, must not invent a `token`
1251 /// field, and (on unix) must not be readable by anyone else.
1252 #[test]
1253 fn save_round_trips_keycloak_and_is_owner_only() {
1254 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1255 let dir = tempfile::tempdir().unwrap();
1256 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1257 _guard.set("XDG_CONFIG_HOME", dir.path());
1258
1259 let session = KeycloakSession {
1260 issuer: "https://idp.test/realms/visdom".into(),
1261 client_id: "tracing-cli".into(),
1262 refresh_token: "rt".into(),
1263 access_token: "at".into(),
1264 access_expires_at: 42,
1265 };
1266 Credentials::keycloak("https://example.com", "a@b.com".into(), session)
1267 .save()
1268 .unwrap();
1269
1270 let raw = fs::read_to_string(Credentials::path().unwrap()).unwrap();
1271 assert!(
1272 !raw.contains("\"token\""),
1273 "a Keycloak file must not carry an api-key `token` field: {raw}"
1274 );
1275 let reloaded = Credentials::load().unwrap();
1276 assert!(matches!(
1277 reloaded.credential(),
1278 Some(Credential::Keycloak(_))
1279 ));
1280
1281 #[cfg(unix)]
1282 {
1283 use std::os::unix::fs::PermissionsExt;
1284 let mode = fs::metadata(Credentials::path().unwrap())
1285 .unwrap()
1286 .permissions()
1287 .mode();
1288 assert_eq!(mode & 0o777, 0o600, "credentials must be owner-only");
1289 }
1290
1291 // The atomic-write temp file must not be left behind.
1292 let leftovers: Vec<_> = fs::read_dir(dir.path().join("tracevault"))
1293 .unwrap()
1294 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1295 .filter(|n| n != "credentials.json")
1296 .collect();
1297 assert!(
1298 leftovers.is_empty(),
1299 "temp files left behind: {leftovers:?}"
1300 );
1301 }
1302
1303 /// A stale temp file must not donate its mode to the credential file.
1304 ///
1305 /// `OpenOptions::mode()` only applies at CREATION, so opening an existing
1306 /// path keeps that path's mode — and the `rename` would then publish it as
1307 /// `credentials.json`'s. A crash under a looser umask is enough to leave
1308 /// such a file behind. This test pre-creates the exact temp path the old
1309 /// pid-only scheme used, with mode 0644; it fails (0644) without
1310 /// `create_new` + a unique suffix, and passes (0600) with them.
1311 #[cfg(unix)]
1312 #[test]
1313 fn a_stale_world_readable_temp_file_cannot_relax_the_credential_mode() {
1314 use std::os::unix::fs::PermissionsExt;
1315
1316 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1317 let dir = tempfile::tempdir().unwrap();
1318 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1319 _guard.set("XDG_CONFIG_HOME", dir.path());
1320
1321 let creds_dir = dir.path().join("tracevault");
1322 fs::create_dir_all(&creds_dir).unwrap();
1323 let stale = creds_dir.join(format!(".credentials.json.tmp{}", std::process::id()));
1324 fs::write(&stale, "leftover from a crashed run").unwrap();
1325 fs::set_permissions(&stale, fs::Permissions::from_mode(0o644)).unwrap();
1326
1327 Credentials::keycloak(
1328 "https://example.com",
1329 "a@b.com".into(),
1330 KeycloakSession {
1331 issuer: "i".into(),
1332 client_id: "c".into(),
1333 refresh_token: "rt".into(),
1334 access_token: "at".into(),
1335 access_expires_at: 1,
1336 },
1337 )
1338 .save()
1339 .expect("a stale temp file must not fail the save");
1340
1341 let mode = fs::metadata(Credentials::path().unwrap())
1342 .unwrap()
1343 .permissions()
1344 .mode();
1345 assert_eq!(
1346 mode & 0o777,
1347 0o600,
1348 "credentials.json inherited the stale temp file's mode"
1349 );
1350 // The tokens must not have been written into the stale file either.
1351 let stale_contents = fs::read_to_string(&stale).unwrap();
1352 assert!(
1353 !stale_contents.contains("rt"),
1354 "secrets were written into the pre-existing temp file: {stale_contents}"
1355 );
1356 }
1357
1358 /// Two saves in one process must both succeed: with `create_new` and a
1359 /// pid-only temp name they would collide on the same path, so the name also
1360 /// carries a process-local counter.
1361 #[test]
1362 fn repeated_saves_in_one_process_do_not_collide() {
1363 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1364 let dir = tempfile::tempdir().unwrap();
1365 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1366 _guard.set("XDG_CONFIG_HOME", dir.path());
1367
1368 let session = KeycloakSession {
1369 issuer: "i".into(),
1370 client_id: "c".into(),
1371 refresh_token: "rt".into(),
1372 access_token: "at".into(),
1373 access_expires_at: 1,
1374 };
1375 for i in 0..5 {
1376 Credentials::keycloak(
1377 "https://example.com",
1378 format!("a{i}@b.com"),
1379 session.clone(),
1380 )
1381 .save()
1382 .unwrap_or_else(|e| panic!("save #{i} failed: {e}"));
1383 }
1384 assert_eq!(Credentials::load().unwrap().email, "a4@b.com");
1385
1386 // No temp files left behind by any of the attempts.
1387 let leftovers: Vec<_> = fs::read_dir(dir.path().join("tracevault"))
1388 .unwrap()
1389 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1390 .filter(|n| n != "credentials.json")
1391 .collect();
1392 assert!(
1393 leftovers.is_empty(),
1394 "temp files left behind: {leftovers:?}"
1395 );
1396 }
1397
1398 /// Logout must leave no credential material behind. Every
1399 /// `.credentials.json.tmp*` holds a full credential JSON including the
1400 /// offline refresh token, so a leftover from a crashed save would otherwise
1401 /// keep a working token on disk after the user logged out.
1402 #[test]
1403 fn delete_also_removes_leftover_temp_files() {
1404 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1405 let dir = tempfile::tempdir().unwrap();
1406 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1407 _guard.set("XDG_CONFIG_HOME", dir.path());
1408
1409 let creds_dir = dir.path().join("tracevault");
1410 fs::create_dir_all(&creds_dir).unwrap();
1411 fs::write(creds_dir.join("credentials.json"), "{}").unwrap();
1412 // Two leftovers, in both the old pid-only and the current shapes.
1413 let old_shape = creds_dir.join(".credentials.json.tmp4242");
1414 let new_shape = creds_dir.join(".credentials.json.tmp4242.0.123");
1415 fs::write(&old_shape, r#"{"auth":{"refresh_token":"still-live-rt"}}"#).unwrap();
1416 fs::write(&new_shape, r#"{"auth":{"refresh_token":"still-live-rt"}}"#).unwrap();
1417
1418 Credentials::delete().unwrap();
1419
1420 assert!(!Credentials::path().unwrap().exists());
1421 let remaining: Vec<_> = fs::read_dir(&creds_dir)
1422 .unwrap()
1423 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1424 .collect();
1425 assert!(
1426 remaining.is_empty(),
1427 "logout left credential material on disk: {remaining:?}"
1428 );
1429 }
1430
1431 /// The `save()` sweep must not delete a temp file that another process
1432 /// could still be writing — that would break its `rename`. Only files past
1433 /// the staleness threshold go.
1434 #[test]
1435 fn save_sweeps_only_old_temp_files() {
1436 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1437 let dir = tempfile::tempdir().unwrap();
1438 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1439 _guard.set("XDG_CONFIG_HOME", dir.path());
1440
1441 let creds_dir = dir.path().join("tracevault");
1442 fs::create_dir_all(&creds_dir).unwrap();
1443 let fresh = creds_dir.join(".credentials.json.tmp999.0.1");
1444 fs::write(&fresh, "in flight in another process").unwrap();
1445
1446 Credentials::keycloak(
1447 "https://example.com",
1448 "a@b.com".into(),
1449 KeycloakSession {
1450 issuer: "i".into(),
1451 client_id: "c".into(),
1452 refresh_token: "rt".into(),
1453 access_token: "at".into(),
1454 access_expires_at: 1,
1455 },
1456 )
1457 .save()
1458 .unwrap();
1459
1460 assert!(
1461 fresh.exists(),
1462 "a just-created temp file may still be in flight elsewhere; sweeping it would break \
1463 that process's rename"
1464 );
1465 }
1466
1467 /// With no way to locate the user's config directory, `path()` must FAIL
1468 /// rather than invent one. The old fallback was `PathBuf::from("~/.config")`
1469 /// — a relative path, since only a shell expands `~` — so `login` created
1470 /// `./~/.config/tracevault/` in the current working directory and wrote an
1471 /// offline refresh token into it, plausibly inside the user's repo.
1472 #[test]
1473 fn path_fails_instead_of_inventing_a_relative_home() {
1474 let err = Credentials::path_in(None)
1475 .expect_err("no config directory must not yield a guessed path");
1476 let msg = err.to_string();
1477 assert!(
1478 msg.contains("XDG_CONFIG_HOME") && msg.contains("HOME"),
1479 "the error must name the variables to set: {msg}"
1480 );
1481 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
1482
1483 // The display helper degrades to an explanation, never to a path that
1484 // would be wrong to write to.
1485 let shown = Credentials::path_for_display();
1486 assert!(
1487 !shown.starts_with('~'),
1488 "a `~`-prefixed path must never be presented as a location: {shown}"
1489 );
1490
1491 // And with a real directory it still composes the same layout.
1492 let dir = tempfile::tempdir().unwrap();
1493 assert_eq!(
1494 Credentials::path_in(Some(dir.path().to_path_buf())).unwrap(),
1495 dir.path().join("tracevault").join("credentials.json")
1496 );
1497 }
1498
1499 /// Logging in must not destroy a `tvk_` API key already in the file: the two
1500 /// writers had opposite policies, with `persist_session` carefully
1501 /// preserving the token that `keycloak` silently dropped. The key stays
1502 /// inert while the session lives (`credential()` prefers the session) and is
1503 /// still there if the session is later removed.
1504 #[test]
1505 fn keycloak_preserves_an_existing_api_key_for_the_same_server() {
1506 // Stored WITH a trailing slash, while login is given it without: the
1507 // carry-over filter must normalise, not compare bytes.
1508 let (_dir, _lock, _guard) = with_credentials_file(
1509 r#"{"server_url":"https://example.com/","token":"tvk_precious","email":"old@b.com"}"#,
1510 );
1511
1512 Credentials::keycloak(
1513 "https://example.com",
1514 "new@b.com".into(),
1515 KeycloakSession {
1516 issuer: "i".into(),
1517 client_id: "c".into(),
1518 refresh_token: "rt".into(),
1519 access_token: "at".into(),
1520 access_expires_at: 1,
1521 },
1522 )
1523 .save()
1524 .unwrap();
1525
1526 let reloaded = Credentials::load().unwrap();
1527 assert_eq!(
1528 reloaded.token.as_deref(),
1529 Some("tvk_precious"),
1530 "login destroyed an API key it did not come to replace"
1531 );
1532 assert_eq!(reloaded.email, "new@b.com");
1533 // The session still wins for actual use.
1534 assert!(matches!(
1535 reloaded.credential(),
1536 Some(Credential::Keycloak(_))
1537 ));
1538 }
1539
1540 /// ...but a key belonging to a DIFFERENT instance is not carried into this
1541 /// instance's file: that is the same cross-instance mixing the resolution
1542 /// guards exist to prevent.
1543 #[test]
1544 fn keycloak_does_not_carry_over_another_servers_api_key() {
1545 let (_dir, _lock, _guard) = with_credentials_file(
1546 r#"{"server_url":"https://instance-b.example.com","token":"tvk_for_b","email":"b@b.com"}"#,
1547 );
1548
1549 Credentials::keycloak(
1550 "https://instance-a.example.com",
1551 "a@b.com".into(),
1552 KeycloakSession {
1553 issuer: "i".into(),
1554 client_id: "c".into(),
1555 refresh_token: "rt".into(),
1556 access_token: "at".into(),
1557 access_expires_at: 1,
1558 },
1559 )
1560 .save()
1561 .unwrap();
1562
1563 let reloaded = Credentials::load().unwrap();
1564 assert_eq!(
1565 reloaded.token, None,
1566 "another instance's key must not be moved into this instance's file"
1567 );
1568 assert_eq!(reloaded.server_url, "https://instance-a.example.com");
1569 }
1570
1571 /// A refresh must update only the `auth` block — the file's `email`
1572 /// (used by `tracevault status`) has to survive.
1573 #[test]
1574 fn persist_session_preserves_other_fields() {
1575 let (_dir, _lock, _guard) = with_credentials_file(
1576 r#"{
1577 "server_url":"https://example.com",
1578 "email":"a@b.com",
1579 "auth":{"issuer":"i","client_id":"c","refresh_token":"rt","access_token":"at","access_expires_at":1}
1580 }"#,
1581 );
1582 let mut session = match Credentials::load().unwrap().credential() {
1583 Some(Credential::Keycloak(s)) => s,
1584 other => panic!("expected Keycloak, got {other:?}"),
1585 };
1586 session.apply(
1587 &TokenSet {
1588 access_token: "at2".into(),
1589 refresh_token: Some("rt2".into()),
1590 expires_in: 300,
1591 },
1592 1_000,
1593 );
1594 Credentials::persist_session("https://example.com", &session).unwrap();
1595
1596 let reloaded = Credentials::load().unwrap();
1597 assert_eq!(reloaded.email, "a@b.com");
1598 assert_eq!(reloaded.server_url, "https://example.com");
1599 let auth = reloaded.auth.unwrap();
1600 assert_eq!(auth.access_token, "at2");
1601 assert_eq!(auth.refresh_token, "rt2");
1602 assert_eq!(auth.access_expires_at, 1_300);
1603 }
1604
1605 /// One credentials file, several possible TraceVault instances: persisting
1606 /// a refresh for instance A must not clobber a file that now belongs to
1607 /// instance B, which would silently sign the user out of B.
1608 #[test]
1609 fn persist_session_leaves_another_servers_file_alone() {
1610 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}}"#;
1611 let (_dir, _lock, _guard) = with_credentials_file(original);
1612
1613 let a_session = KeycloakSession {
1614 issuer: "i".into(),
1615 client_id: "c".into(),
1616 refresh_token: "a-rt".into(),
1617 access_token: "a-at".into(),
1618 access_expires_at: 1_234,
1619 };
1620 Credentials::persist_session("https://instance-a.example.com", &a_session)
1621 .expect("a foreign file is a skip, not an error");
1622
1623 let after = fs::read_to_string(Credentials::path().unwrap()).unwrap();
1624 assert_eq!(after, original, "another server's file was overwritten");
1625
1626 // The other direction at this same call site: the file's URL differing
1627 // only by a trailing slash IS this server, so the write must happen.
1628 // Without this half, replacing `same_server` with `!=`/`==` here goes
1629 // unnoticed and quietly disables persistence — the state the skip
1630 // warning exists to explain.
1631 fs::write(
1632 Credentials::path().unwrap(),
1633 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}}"#,
1634 )
1635 .unwrap();
1636 Credentials::persist_session("https://instance-a.example.com", &a_session).unwrap();
1637 let auth = Credentials::load().unwrap().auth.unwrap();
1638 assert_eq!(
1639 auth.access_token, "a-at",
1640 "a trailing slash must not block a legitimate persist"
1641 );
1642 }
1643
1644 /// The single owner of the normalisation property: the two sides of the
1645 /// comparison are formatted differently by construction (`ApiClient` trims
1646 /// trailing slashes, the file keeps whatever login was given), so a trailing
1647 /// slash must count as a match. Call sites only prove that they consult
1648 /// `same_server`, via their mismatch tests.
1649 #[test]
1650 fn same_server_normalises_trailing_slashes_and_whitespace() {
1651 assert!(same_server(
1652 "https://x.example.com",
1653 "https://x.example.com/"
1654 ));
1655 assert!(same_server(
1656 " https://x.example.com/ ",
1657 "https://x.example.com"
1658 ));
1659 assert!(!same_server(
1660 "https://x.example.com",
1661 "https://y.example.com"
1662 ));
1663 // A different path is a different instance, not a formatting variant.
1664 assert!(!same_server(
1665 "https://x.example.com",
1666 "https://x.example.com/tv"
1667 ));
1668 }
1669
1670 #[test]
1671 fn persist_session_on_a_missing_file_is_not_an_error() {
1672 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1673 let dir = tempfile::tempdir().unwrap();
1674 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1675 _guard.set("XDG_CONFIG_HOME", dir.path());
1676
1677 let session = KeycloakSession {
1678 issuer: "i".into(),
1679 client_id: "c".into(),
1680 refresh_token: "rt".into(),
1681 access_token: "at".into(),
1682 access_expires_at: 1,
1683 };
1684 Credentials::persist_session("https://example.com", &session)
1685 .expect("a logged-out user must not turn a refresh into a hard error");
1686 assert!(
1687 !Credentials::path().unwrap().exists(),
1688 "persist_session must not resurrect a deleted credentials file"
1689 );
1690 }
1691
1692 #[test]
1693 fn debug_impls_redact_secrets() {
1694 let creds = Credentials {
1695 server_url: "https://example.com".into(),
1696 token: Some("tvk_secret".into()),
1697 email: "a@b".into(),
1698 auth: None,
1699 };
1700 let dbg = format!("{creds:?}");
1701 assert!(!dbg.contains("tvk_secret"), "api key leaked: {dbg}");
1702
1703 let creds = Credentials::keycloak(
1704 "https://example.com",
1705 "a@b".into(),
1706 KeycloakSession {
1707 issuer: "i".into(),
1708 client_id: "c".into(),
1709 refresh_token: "secret-rt".into(),
1710 access_token: "secret-at".into(),
1711 access_expires_at: 1,
1712 },
1713 );
1714 let dbg = format!("{creds:?}");
1715 assert!(!dbg.contains("secret-rt"), "refresh token leaked: {dbg}");
1716 assert!(!dbg.contains("secret-at"), "access token leaked: {dbg}");
1717 }
1718}