Skip to main content

tracevault_cli/
api_client.rs

1use crate::credentials::{resolve_credentials, Credential, Credentials, KeycloakSession};
2use serde::{Deserialize, Serialize};
3use std::error::Error;
4use std::fmt;
5use std::path::Path;
6use std::sync::Arc;
7use tokio::sync::Mutex;
8use url::Url;
9
10pub struct ApiClient {
11    base_url: String,
12    credential: Option<ClientCredential>,
13    client: reqwest::Client,
14    /// Injectable "now" (unix seconds). Only the token-refresh window reads
15    /// it; tests override it so the boundary is deterministic instead of
16    /// depending on wall-clock time.
17    now: fn() -> i64,
18}
19
20/// A [`Credential`] prepared for use by a client.
21///
22/// A Keycloak session sits behind an `Arc<Mutex<..>>` so several concurrent
23/// in-process requests (the stream hook drains a queue with a shared client)
24/// serialise on ONE refresh instead of each racing to mint its own and
25/// invalidating the others' refresh token.
26enum ClientCredential {
27    ApiKey(String),
28    Keycloak(Arc<Mutex<KeycloakSession>>),
29}
30
31/// Why a request could not be given a bearer token.
32///
33/// Separate from [`GetMeError`] because it is produced before any request
34/// goes out, and separate from a plain string because callers must be able
35/// to distinguish "this session is dead, log in again" from "we couldn't
36/// reach the IdP right now".
37#[derive(Debug)]
38pub enum AuthError {
39    /// The refresh token was rejected: the user must log in again.
40    SessionExpired,
41    /// The refresh attempt itself failed (IdP unreachable, 5xx, ...).
42    Refresh(String),
43}
44
45impl fmt::Display for AuthError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::SessionExpired => write!(
49                f,
50                "your session has expired — run `tracevault login` to sign in again"
51            ),
52            Self::Refresh(m) => write!(f, "could not refresh the access token: {m}"),
53        }
54    }
55}
56
57impl std::error::Error for AuthError {}
58
59/// Wall-clock unix seconds; the production value of [`ApiClient::now`].
60fn now_unix() -> i64 {
61    chrono::Utc::now().timestamp()
62}
63
64/// The value of the `x-tracevault-project-attribution` header: the two
65/// spellings the server accepts, and no others.
66///
67/// A type rather than a `&str` because the wire contract is closed on the
68/// server side and fails LOUDLY: `explicit` and `derived` are the only
69/// accepted values, and anything else — a typo, a future mode this build
70/// does not know about, a hand-passed literal — is a `400`, not a silently
71/// ignored header. Every value is produced today by
72/// `commands::stream::attribution_mode`, so the invariant already holds, but
73/// it holds only by convention: one new call site passing `"Explicit"` or
74/// `"forced"` would turn a working hook into a hard client error. An enum
75/// moves that from "documented" to "unrepresentable", the same move that
76/// makes `ClientErrorKind` and `ForceStatus` types.
77///
78/// The CLI's own tolerance runs the other way, deliberately: an unrecognised
79/// `TRACEVAULT_PROJECT_ATTRIBUTION` reads as `Derived` rather than being
80/// forwarded (see `commands::stream::attribution_mode`), so a typo'd env var
81/// never reaches the server to be rejected. This enum is what keeps that
82/// function the only place a mode is decided.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum AttributionMode {
85    /// TraceVault checks repo→project membership itself. The default, and
86    /// what an absent header also means.
87    Derived,
88    /// The caller owns attribution and the server skips the membership
89    /// check. A trust claim, gated server-side (`Operator` + a Control Plane
90    /// identity).
91    Explicit,
92}
93
94impl AttributionMode {
95    /// The wire spelling. THE one place a mode becomes a string — the header
96    /// write in [`ApiClient::stream_event_for_project`] and the [`fmt::Display`]
97    /// impl below both go through this match, so no surface can invent a
98    /// third spelling or disagree with the wire.
99    pub fn as_header_value(self) -> &'static str {
100        match self {
101            Self::Derived => "derived",
102            Self::Explicit => "explicit",
103        }
104    }
105}
106
107impl fmt::Display for AttributionMode {
108    /// Deliberately the same word the header carries: `project status` prints
109    /// the mode a hook would send, and a separate spelling for human output
110    /// would be a second thing to keep in agreement with the wire.
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.write_str(self.as_header_value())
113    }
114}
115
116#[derive(Serialize)]
117pub struct RegisterRepoRequest {
118    pub repo_name: String,
119    pub github_url: Option<String>,
120}
121
122#[derive(Debug, Deserialize)]
123pub struct RegisterRepoResponse {
124    pub repo_id: uuid::Uuid,
125}
126
127#[derive(Debug, Deserialize)]
128pub struct ResolveRemoteResponse {
129    pub remote_id: uuid::Uuid,
130    #[serde(default)]
131    pub name: Option<String>,
132    pub normalized_url: String,
133    pub clone_status: String,
134}
135
136#[derive(Deserialize)]
137pub struct RemoteRepoRef {
138    pub id: uuid::Uuid,
139    // Reserved for display (e.g. a future `repo status`/error message listing
140    // a codebase's linked repos by name); not read by any caller yet.
141    #[allow(dead_code)]
142    pub name: String,
143}
144
145// The server's RemoteDetailResponse flattens the remote fields at top level and
146// adds a `repos` array; serde ignores any other top-level fields.
147#[derive(Deserialize)]
148pub struct RemoteDetail {
149    #[serde(default)]
150    pub name: Option<String>,
151    pub normalized_url: String,
152    pub clone_status: String,
153    pub repos: Vec<RemoteRepoRef>,
154}
155
156#[derive(Debug, Serialize)]
157pub struct CheckPoliciesRequest {
158    pub sessions: Vec<SessionCheckData>,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub commit_sha: Option<String>,
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub changed_paths: Option<Vec<String>>,
163}
164
165#[derive(Debug, Serialize)]
166pub struct SessionCheckData {
167    pub session_id: String,
168    pub tool_calls: Option<serde_json::Value>,
169    pub files_modified: Option<Vec<String>>,
170    pub total_tool_calls: Option<i32>,
171}
172
173#[derive(Debug, Deserialize)]
174pub struct CheckPoliciesResponse {
175    pub passed: bool,
176    pub results: Vec<CheckResultItem>,
177    pub blocked: bool,
178}
179
180#[derive(Debug, Deserialize)]
181pub struct CheckResultItem {
182    pub rule_name: String,
183    pub result: String,
184    pub action: String,
185    pub severity: String,
186    pub details: String,
187}
188
189#[derive(Debug, Deserialize)]
190pub struct RepoListItem {
191    pub id: uuid::Uuid,
192    pub name: String,
193    #[serde(default)]
194    pub github_url: Option<String>,
195    #[serde(default)]
196    pub clone_status: Option<String>,
197}
198
199/// Response shape for the `policies/agent-instructions` endpoint.
200#[derive(Debug, Clone, Deserialize)]
201pub struct AgentInstructionsResponse {
202    #[allow(dead_code)]
203    pub format: String,
204    pub content: String,
205}
206
207#[derive(Debug, Deserialize)]
208pub struct MeResponse {
209    #[allow(dead_code)]
210    pub user_id: uuid::Uuid,
211    pub email: String,
212    pub name: Option<String>,
213    /// The role the server derived for this caller (from Keycloak realm
214    /// roles or Control Plane grants for a Keycloak bearer). Optional so this
215    /// CLI keeps parsing a server that predates the field.
216    #[serde(default)]
217    pub role: Option<String>,
218}
219
220#[derive(Debug)]
221pub enum GetMeError {
222    /// 401 — token is missing or invalid.
223    Unauthorized,
224    /// 403 — the token is valid but the account is not authorized (for a
225    /// Keycloak bearer: it has no `tracevault` grant in Control Plane). Distinct from
226    /// `Unauthorized` because the fix is "an admin grants a role", not
227    /// "log in again".
228    Forbidden(String),
229    /// Transport-level failure (DNS, TCP, TLS, timeout).
230    Network(String),
231    /// HTTP ≥ 400 other than 401/403, or malformed JSON.
232    Server(String),
233}
234
235impl std::fmt::Display for GetMeError {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        match self {
238            Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
239            Self::Forbidden(m) => write!(f, "forbidden (account not authorized): {m}"),
240            Self::Network(m) => write!(f, "network error: {m}"),
241            Self::Server(m) => write!(f, "server error: {m}"),
242        }
243    }
244}
245
246impl std::error::Error for GetMeError {}
247
248#[derive(Debug, Serialize)]
249pub struct CiVerifyRequest {
250    pub commits: Vec<String>,
251}
252
253#[derive(Debug, Deserialize)]
254pub struct CiVerifyResponse {
255    pub status: String,
256    pub total_commits: usize,
257    pub registered_commits: usize,
258    pub sealed_commits: usize,
259    pub policy_passed_commits: usize,
260    pub results: Vec<CommitVerifyResult>,
261}
262
263#[derive(Debug, Deserialize)]
264pub struct CommitVerifyResult {
265    pub commit_sha: String,
266    pub status: String,
267    pub registered: bool,
268    pub sealed: bool,
269    pub signature_valid: bool,
270    pub chain_valid: bool,
271    pub policy_results: Vec<CiPolicyResult>,
272}
273
274#[derive(Debug, Deserialize)]
275pub struct CiPolicyResult {
276    pub rule_name: String,
277    pub result: String,
278    pub action: String,
279    pub severity: String,
280    pub details: String,
281}
282
283/// One project in `GET /api/v1/projects`. Server sends more
284/// fields; only these two are consumed today.
285#[derive(Debug, Deserialize)]
286pub struct ProjectListItem {
287    pub id: uuid::Uuid,
288    pub name: String,
289}
290
291/// A repo linked to a project (member of `ProjectDetail::repos`).
292#[derive(Debug, Deserialize)]
293pub struct ProjectRepoRef {
294    pub id: uuid::Uuid,
295}
296
297/// Full detail for a project. Server sends more fields; only `repos` is
298/// consumed today.
299#[derive(Debug, Deserialize)]
300pub struct ProjectDetail {
301    pub repos: Vec<ProjectRepoRef>,
302}
303
304/// Outcome of `ApiClient::resolve_project`, distinguishing "no project"
305/// (404) from "ambiguous, multiple candidates" (409) — unlike
306/// `resolve_remote`, which only distinguishes found/not-found.
307#[derive(Debug)]
308pub enum ResolveProjectOutcome {
309    Resolved(uuid::Uuid),
310    None,
311    Ambiguous,
312}
313
314/// Wire shape of a successful `resolve_project` response.
315#[derive(Deserialize)]
316struct ResolveProjectResponse {
317    project_id: uuid::Uuid,
318}
319
320impl ApiClient {
321    /// Construct a client authenticated with a raw API key (or nothing).
322    ///
323    /// Part of the crate's public API and the shape every test constructs, so
324    /// it stays exactly as it was. Command code goes through
325    /// [`ApiClient::with_credential`] instead, which is why the `tracevault`
326    /// BINARY target — where nothing but the lib's tests calls this — would
327    /// otherwise report it as dead.
328    #[allow(dead_code)]
329    pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
330        Self::with_credential(base_url, api_key.map(|k| Credential::ApiKey(k.to_string())))
331    }
332
333    /// Construct a client from a resolved [`Credential`].
334    ///
335    /// Takes an `Option` because every caller resolves credentials that may
336    /// be absent (`resolve_credentials` returns an `Option`), and an
337    /// unauthenticated client is a legitimate state — several commands
338    /// degrade gracefully rather than failing when nothing is configured.
339    pub fn with_credential(base_url: &str, credential: Option<Credential>) -> Self {
340        Self {
341            base_url: base_url.trim_end_matches('/').to_string(),
342            credential: credential.map(|c| match c {
343                Credential::ApiKey(k) => ClientCredential::ApiKey(k),
344                Credential::Keycloak(s) => ClientCredential::Keycloak(Arc::new(Mutex::new(s))),
345            }),
346            client: reqwest::Client::builder()
347                .timeout(std::time::Duration::from_secs(60))
348                .build()
349                .unwrap_or_default(),
350            now: now_unix,
351        }
352    }
353
354    /// Test-only clock override, so the refresh window can be exercised
355    /// without waiting for a token to actually age.
356    #[cfg(test)]
357    fn with_now(mut self, now: fn() -> i64) -> Self {
358        self.now = now;
359        self
360    }
361
362    /// The bearer token to present, refreshing first if needed.
363    ///
364    /// * `ApiKey` → the key verbatim. Never refreshed, never rotated: this is
365    ///   the automation path and it must stay a pure passthrough.
366    /// * `Keycloak` → refresh when the access token is inside
367    ///   [`crate::credentials::REFRESH_WINDOW_SECS`] of expiry, persist the
368    ///   new tokens, and return the fresh one. The session mutex is held
369    ///   across the refresh so concurrent callers wait for it instead of
370    ///   each starting their own.
371    async fn bearer(&self) -> Result<Option<String>, AuthError> {
372        match &self.credential {
373            None => Ok(None),
374            Some(ClientCredential::ApiKey(key)) => Ok(Some(key.clone())),
375            Some(ClientCredential::Keycloak(session)) => {
376                let mut guard = session.lock().await;
377                if guard.needs_refresh((self.now)()) {
378                    self.refresh_locked(&mut guard).await?;
379                }
380                Ok(Some(guard.access_token.clone()))
381            }
382        }
383    }
384
385    /// Refresh the held session in place and persist it. Caller holds the
386    /// session lock, which is what makes "one refresh at a time" true.
387    ///
388    /// # Residual cross-process race, and why it is currently benign
389    ///
390    /// The on-disk adopt below closes the SEQUENTIAL case (something already
391    /// finished refreshing before we started) but only NARROWS the concurrent
392    /// one: two hooks spawned at the same instant can both read the same
393    /// session before either writes, and the window is this function's
394    /// discovery GET plus its token POST. Both would then present the same
395    /// refresh token.
396    ///
397    /// That is harmless ONLY because the realm keeps Keycloak's
398    /// `revokeRefreshToken` at its default (off): a re-presented refresh token
399    /// stays valid, so the worst outcome is one wasted round trip and a
400    /// last-writer-wins access token, both invisible to the user. If that
401    /// realm setting is ever enabled, the second presenter gets
402    /// `invalid_grant` — surfacing as a spurious "your session has expired" —
403    /// and this code then needs a real inter-process file lock around
404    /// read-refresh-write, not just the adopt.
405    ///
406    /// # Both directions are scoped to this client's server
407    ///
408    /// There is exactly ONE credentials file, but a machine can be pointed at
409    /// more than one TraceVault instance. So the adopt only reads, and
410    /// `persist_session` only writes, when that file's `server_url` is this
411    /// client's `base_url` (see [`crate::credentials::same_server`]).
412    /// Unscoped, a long-running `tracevault stream` against instance A plus a
413    /// `tracevault login` to instance B in another terminal would make A adopt
414    /// B's session and send B's access token to A — disclosing a token to a
415    /// host it was never minted for — and A's next refresh would then overwrite
416    /// B's credentials, signing the user out of B.
417    async fn refresh_locked(&self, session: &mut KeycloakSession) -> Result<(), AuthError> {
418        let now = (self.now)();
419
420        // Someone else may have refreshed already: another process (two git
421        // hooks firing at once), or another `ApiClient` in this process that
422        // was built from the same on-disk credential before either refreshed.
423        //
424        // Adopt when EITHER holds, because they catch different IdPs:
425        //
426        // * the on-disk access token outlives ours — the on-disk session is
427        //   genuinely newer. This is the only signal available on an IdP that
428        //   does NOT rotate refresh tokens (RFC 6749 permits omitting
429        //   `refresh_token` on a refresh, which `KeycloakSession::apply`
430        //   handles), where the refresh token is identical everywhere and a
431        //   token-comparison alone would never fire — leaving `tracevault
432        //   status`, which builds three clients from one credential, doing three
433        //   redundant refreshes.
434        // * the on-disk refresh token differs from ours — ours has been
435        //   superseded, and on a ROTATING IdP already consumed. This must adopt
436        //   even when the adopted session is itself older and still needs a
437        //   refresh (then falling through to refresh with the ADOPTED token),
438        //   because refreshing with a consumed token is a guaranteed
439        //   `invalid_grant`.
440        //
441        // Deliberately NOT "the access tokens differ": that would also adopt a
442        // strictly older session.
443        //
444        // There is deliberately no test asserting "never adopt an older
445        // session", because that property is unreachable where it would be
446        // desirable and undesirable where it is reachable. Through `bearer` it
447        // cannot be observed: this function is only entered when OURS is inside
448        // the refresh window, so an older disk session is inside it too and
449        // control falls through to a real refresh either way. Through
450        // `force_refresh` it IS reachable — and there, adopting a different
451        // token is exactly what we want, since the one we hold was just
452        // rejected. A test naming the downgrade would therefore have to be
453        // vacuous to pass; the predicate's existence is instead covered by the
454        // 401 retry tests, which fail if it always adopts.
455        //
456        // ... and only from a file that is still this server's (see above).
457        if let Some(disk) = Credentials::load()
458            .filter(|c| crate::credentials::same_server(&c.server_url, &self.base_url))
459            .and_then(|c| c.auth)
460        {
461            let disk_is_newer = disk.access_expires_at > session.access_expires_at;
462            let ours_superseded = disk.refresh_token != session.refresh_token;
463            if disk_is_newer || ours_superseded {
464                let disk_needs_refresh = disk.needs_refresh(now);
465                *session = disk;
466                if !disk_needs_refresh {
467                    return Ok(());
468                }
469            }
470        }
471
472        // Discovery is re-fetched per refresh rather than cached: a refresh
473        // happens at most once per access-token lifetime (minutes), and
474        // caching it would mean a rotated realm endpoint needs a re-login.
475        let discovery = crate::oidc::discover(&self.client, &session.issuer)
476            .await
477            .map_err(auth_error)?;
478        let tokens = crate::oidc::refresh(
479            &self.client,
480            &discovery,
481            &session.client_id,
482            &session.refresh_token,
483        )
484        .await
485        .map_err(auth_error)?;
486        session.apply(&tokens, now);
487
488        // Best-effort, and scoped to this server (see the doc comment): a token
489        // that can't be written to disk still works for THIS process, so
490        // failing the request would be worse than a warning. The message
491        // deliberately contains no token material.
492        if let Err(e) = Credentials::persist_session(&self.base_url, session) {
493            eprintln!("Warning: could not save refreshed credentials: {e}");
494        }
495        Ok(())
496    }
497
498    /// Force one refresh after an unexpected 401 and return the new token.
499    ///
500    /// `Ok(None)` means "not refreshable" (API key or no credential), which
501    /// is the signal not to retry. `stale` is the token that just got
502    /// rejected: if another task already refreshed while we waited for the
503    /// lock, the current token is already different and is reused instead of
504    /// refreshing a second time.
505    async fn force_refresh(&self, stale: Option<&str>) -> Result<Option<String>, AuthError> {
506        let Some(ClientCredential::Keycloak(session)) = &self.credential else {
507            return Ok(None);
508        };
509        let mut guard = session.lock().await;
510        if Some(guard.access_token.as_str()) != stale {
511            return Ok(Some(guard.access_token.clone()));
512        }
513        self.refresh_locked(&mut guard).await?;
514        Ok(Some(guard.access_token.clone()))
515    }
516
517    pub async fn register_repo(
518        &self,
519        req: RegisterRepoRequest,
520    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
521        let builder = self
522            .client
523            .post(format!("{}/api/v1/repos", self.base_url))
524            .json(&req);
525        self.authed_send_json(builder, |status| format!("Server returned {status}"))
526            .await
527    }
528
529    /// Attach a bearer token (if there is one) to a request. Shared by every
530    /// authenticated request builder so header attachment has exactly one
531    /// implementation.
532    fn attach_auth(
533        builder: reqwest::RequestBuilder,
534        token: Option<&str>,
535    ) -> reqwest::RequestBuilder {
536        match token {
537            Some(t) => builder.header("Authorization", format!("Bearer {t}")),
538            None => builder,
539        }
540    }
541
542    /// Attach the bearer token and send `builder`. The shared first step of
543    /// every authenticated request; callers that need bespoke status-code
544    /// handling (e.g. treating 404/409 as non-error outcomes) use this
545    /// directly instead of `authed_send_json`.
546    ///
547    /// On an unexpected 401 with a refreshable (Keycloak) credential the
548    /// request is retried EXACTLY once against a force-refreshed token —
549    /// covering a server-side session invalidation or a clock skew that the
550    /// proactive expiry window missed. The retry is a bare `send`, not a
551    /// recursive call, so a server that answers 401 unconditionally cannot
552    /// make this loop. An API key never retries: a 401 on a `tvk_` key is a
553    /// real rejection and re-sending it would just double every failure.
554    async fn send_authed(
555        &self,
556        builder: reqwest::RequestBuilder,
557    ) -> Result<reqwest::Response, Box<dyn Error>> {
558        // Cloned BEFORE sending: a builder is consumed by `send`. `None`
559        // means the body isn't replayable, in which case we simply don't
560        // retry.
561        let retry = builder.try_clone();
562        let token = self.bearer().await?;
563        let resp = Self::attach_auth(builder, token.as_deref()).send().await?;
564
565        if resp.status() != reqwest::StatusCode::UNAUTHORIZED {
566            return Ok(resp);
567        }
568        let Some(retry) = retry else {
569            return Ok(resp);
570        };
571        match self.force_refresh(token.as_deref()).await? {
572            Some(fresh) => Ok(Self::attach_auth(retry, Some(&fresh)).send().await?),
573            // Not refreshable — surface the original 401 unchanged.
574            None => Ok(resp),
575        }
576    }
577
578    /// Check that `resp`'s status is a success and deserialize its JSON
579    /// body; otherwise build an error as `"{err_prefix(status)}: {body}"`.
580    /// `err_prefix` receives the status so each caller can format its own
581    /// distinct message (parenthesized status, bare status, ...) — this
582    /// helper only supplies the shared "check status, else deserialize"
583    /// shape, not the message wording.
584    async fn success_json<T, F>(resp: reqwest::Response, err_prefix: F) -> Result<T, Box<dyn Error>>
585    where
586        T: serde::de::DeserializeOwned,
587        F: FnOnce(reqwest::StatusCode) -> String,
588    {
589        let status = resp.status();
590        if !status.is_success() {
591            let body = resp.text().await.unwrap_or_default();
592            return Err(format!("{}: {}", err_prefix(status), body).into());
593        }
594        Ok(resp.json().await?)
595    }
596
597    /// Attach the bearer token, send `builder`, and deserialize a successful
598    /// JSON response — the shared shape of every simple authenticated
599    /// request/response method (`send_authed` + `success_json`).
600    ///
601    /// NOTE: callers whose `err_prefix` renders the status as `"({status})"`
602    /// (e.g. `stream_event`'s `"Stream failed ({status})"`) produce error
603    /// strings containing `"(404 "`/`"(403 "`/etc. —
604    /// `commands::stream::deterministic_client_error_kind` matches on exactly
605    /// that substring shape to classify a stream-send failure, and to tell a 403
606    /// apart from the binding statuses. If you change how a status is rendered
607    /// here, check that function (and its tests) still pass.
608    async fn authed_send_json<T, F>(
609        &self,
610        builder: reqwest::RequestBuilder,
611        err_prefix: F,
612    ) -> Result<T, Box<dyn Error>>
613    where
614        T: serde::de::DeserializeOwned,
615        F: FnOnce(reqwest::StatusCode) -> String,
616    {
617        let resp = self.send_authed(builder).await?;
618        Self::success_json(resp, err_prefix).await
619    }
620
621    /// GET `{base}{path}` with the bearer token, mapping failures into
622    /// `GetMeError` (401 → `Unauthorized`, 403 → `Forbidden`, transport →
623    /// `Network`, other non-2xx or bad JSON → `Server`). Shared by the
624    /// credential-scoped GETs so auth/error handling lives in one place.
625    ///
626    /// Goes through `send_authed`, so a Keycloak access token is refreshed
627    /// before the call (and once after a 401) exactly like every other
628    /// request. A refresh failure is mapped by cause: a dead session is
629    /// `Unauthorized` ("log in again"), an unreachable IdP is `Network`
630    /// ("cannot confirm") — `tracevault status` renders those very
631    /// differently, so collapsing them would misreport a network blip as a
632    /// revoked login.
633    async fn authed_get_json<T: serde::de::DeserializeOwned>(
634        &self,
635        path: &str,
636    ) -> Result<T, GetMeError> {
637        let builder = self.client.get(format!("{}{}", self.base_url, path));
638        let resp = self.send_authed(builder).await.map_err(get_me_send_error)?;
639
640        let status = resp.status();
641        if status == reqwest::StatusCode::UNAUTHORIZED {
642            return Err(GetMeError::Unauthorized);
643        }
644        if status == reqwest::StatusCode::FORBIDDEN {
645            let body = resp.text().await.unwrap_or_default();
646            return Err(GetMeError::Forbidden(body));
647        }
648        if !status.is_success() {
649            let body = resp.text().await.unwrap_or_default();
650            return Err(GetMeError::Server(format!("{status}: {body}")));
651        }
652
653        resp.json::<T>()
654            .await
655            .map_err(|e| GetMeError::Server(e.to_string()))
656    }
657
658    /// GET /api/v1/auth/me — validates the bearer token and returns user
659    /// identity. Used by `tracevault status` to distinguish "logged out",
660    /// "expired token", and "server unreachable".
661    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
662        self.authed_get_json("/api/v1/auth/me").await
663    }
664
665    pub async fn list_repos(&self) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
666        let builder = self.client.get(format!("{}/api/v1/repos", self.base_url));
667        self.authed_send_json(builder, |status| format!("Failed to list repos ({status})"))
668            .await
669    }
670
671    pub async fn get_agent_instructions(
672        &self,
673        repo_id: &uuid::Uuid,
674    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
675        let builder = self.client.get(format!(
676            "{}/api/v1/repos/{}/policies/agent-instructions",
677            self.base_url, repo_id
678        ));
679        self.authed_send_json(builder, |status| {
680            format!("Failed to fetch agent instructions ({status})")
681        })
682        .await
683    }
684
685    pub async fn verify_commits(
686        &self,
687        repo_id: &uuid::Uuid,
688        req: CiVerifyRequest,
689    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
690        let builder = self
691            .client
692            .post(format!(
693                "{}/api/v1/repos/{}/ci/verify",
694                self.base_url, repo_id
695            ))
696            .json(&req);
697        self.authed_send_json(builder, |status| format!("CI verify failed ({status})"))
698            .await
699    }
700
701    pub async fn push_commit(
702        &self,
703        repo_id: &str,
704        req: &tracevault_protocol::streaming::CommitPushRequest,
705    ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
706        let builder = self
707            .client
708            .post(format!(
709                "{}/api/v1/repos/{}/commits",
710                self.base_url, repo_id
711            ))
712            .json(req);
713        self.authed_send_json(builder, |status| format!("Commit push failed ({status})"))
714            .await
715    }
716
717    pub async fn stream_event(
718        &self,
719        repo_id: &str,
720        req: &tracevault_protocol::streaming::StreamEventRequest,
721    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
722        let builder = self
723            .client
724            .post(format!("{}/api/v1/repos/{}/stream", self.base_url, repo_id))
725            .json(req);
726        self.authed_send_json(builder, |status| format!("Stream failed ({status})"))
727            .await
728    }
729
730    /// Project-scoped variant of `stream_event`: posts to the project's
731    /// stream endpoint with the project in the path and `repo_id` — when
732    /// there is one — as a query param rather than a path segment. The query
733    /// is built with `Url::query_pairs_mut`, mirroring `resolve_project`'s
734    /// `?git_url=`, so `repo_id` is percent-encoded rather than
735    /// string-interpolated into the URL.
736    ///
737    /// `repo_id` is `None` for a repo-less session, and the pair is then
738    /// omitted entirely: the server declares it optional
739    /// (`ProjectStreamQuery::repo_id: Option<Uuid>`) and would reject an
740    /// empty value as a malformed UUID.
741    ///
742    /// Called from `commands::stream::send_stream_event` for both the
743    /// `Attribution::Repo { project: Some(_) }` and `Attribution::ProjectOnly`
744    /// routes.
745    ///
746    /// `mode` is the attribution this send declares — decided by
747    /// `commands::stream::attribution_mode` and rendered into the
748    /// `x-tracevault-project-attribution` header by
749    /// [`AttributionMode::as_header_value`], which is the only place it
750    /// becomes a string.
751    ///
752    /// It is an [`AttributionMode`], not a `&str`, because the server
753    /// accepts exactly two values and rejects everything else with a `400`
754    /// — see that type's doc comment. (An older SERVER simply does not read
755    /// the header, which is the one direction that does degrade quietly, to
756    /// derived attribution.)
757    pub async fn stream_event_for_project(
758        &self,
759        project_id: uuid::Uuid,
760        repo_id: Option<&str>,
761        mode: AttributionMode,
762        req: &tracevault_protocol::streaming::StreamEventRequest,
763    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
764        let mut url = Url::parse(&format!(
765            "{}/api/v1/projects/{}/stream",
766            self.base_url, project_id
767        ))?;
768        // `repo_id` is OPTIONAL server-side (`ProjectStreamQuery::repo_id:
769        // Option<Uuid>` — "repo-less (0-repo) projects are supported"), so a
770        // repo-less session must omit the pair entirely. Appending an empty
771        // value instead would be parsed as a malformed UUID and 400.
772        if let Some(repo_id) = repo_id {
773            url.query_pairs_mut().append_pair("repo_id", repo_id);
774        }
775        let builder = self
776            .client
777            .post(url)
778            .header("x-tracevault-project-attribution", mode.as_header_value())
779            .json(req);
780        self.authed_send_json(builder, |status| {
781            format!("Project stream failed ({status})")
782        })
783        .await
784    }
785
786    pub async fn check_policies(
787        &self,
788        repo_id: &uuid::Uuid,
789        req: CheckPoliciesRequest,
790    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
791        let builder = self
792            .client
793            .post(format!(
794                "{}/api/v1/repos/{}/policies/check",
795                self.base_url, repo_id
796            ))
797            .json(&req);
798        self.authed_send_json(builder, |status| format!("Policy check failed ({status})"))
799            .await
800    }
801
802    /// Resolve a git URL to its codebase (git remote) by NORMALIZED URL —
803    /// deduped, unlike an exact `github_url` match. `Ok(None)` if the
804    /// codebase isn't tracked: a genuine domain 404, identified by the
805    /// server's JSON error envelope (see [`is_domain_error_body`]). A bare
806    /// 404 with no such body — axum's built-in "no route matched" fallback
807    /// — is surfaced as `Err` instead, since it means this server doesn't
808    /// have this route at all (most plausibly a CLI/server version skew,
809    /// e.g. this CLI shipped ahead of a server that still uses the old
810    /// org-scoped paths) rather than an absent codebase.
811    pub async fn resolve_remote(
812        &self,
813        git_url: &str,
814    ) -> Result<Option<ResolveRemoteResponse>, Box<dyn std::error::Error>> {
815        let mut url = Url::parse(&format!("{}/api/v1/remotes/resolve", self.base_url))?;
816        url.query_pairs_mut().append_pair("git_url", git_url);
817        let resp = self.send_authed(self.client.get(url)).await?;
818        if resp.status() == reqwest::StatusCode::NOT_FOUND {
819            let body = resp.text().await.unwrap_or_default();
820            return if is_domain_error_body(&body) {
821                Ok(None)
822            } else {
823                Err(version_skew_404_error("resolve_remote"))
824            };
825        }
826        let parsed: ResolveRemoteResponse =
827            Self::success_json(resp, |status| format!("resolve_remote failed ({status})")).await?;
828        Ok(Some(parsed))
829    }
830
831    /// Full detail for a remote (codebase): its display name, normalized URL,
832    /// clone status, and linked repos.
833    pub async fn get_remote_detail(
834        &self,
835        remote_id: uuid::Uuid,
836    ) -> Result<RemoteDetail, Box<dyn std::error::Error>> {
837        let builder = self
838            .client
839            .get(format!("{}/api/v1/remotes/{}", self.base_url, remote_id));
840        self.authed_send_json(builder, |status| {
841            format!("get_remote_detail failed ({status})")
842        })
843        .await
844    }
845
846    /// The repos linked to a remote (the codebase's members).
847    pub async fn get_remote_repos(
848        &self,
849        remote_id: uuid::Uuid,
850    ) -> Result<Vec<RemoteRepoRef>, Box<dyn std::error::Error>> {
851        Ok(self.get_remote_detail(remote_id).await?.repos)
852    }
853
854    /// List all projects. `GET /api/v1/projects`.
855    pub async fn list_projects(&self) -> Result<Vec<ProjectListItem>, Box<dyn Error>> {
856        let builder = self
857            .client
858            .get(format!("{}/api/v1/projects", self.base_url));
859        self.authed_send_json(builder, |status| {
860            format!("Failed to list projects ({status})")
861        })
862        .await
863    }
864
865    /// Full detail for a project. `GET /api/v1/projects/{id}`.
866    pub async fn get_project(&self, id: uuid::Uuid) -> Result<ProjectDetail, Box<dyn Error>> {
867        let builder = self
868            .client
869            .get(format!("{}/api/v1/projects/{}", self.base_url, id));
870        self.authed_send_json(builder, |status| {
871            format!("Failed to get project ({status})")
872        })
873        .await
874    }
875
876    /// Resolve a git URL to its project, distinguishing "no project" (a
877    /// genuine domain 404 — see [`is_domain_error_body`]) from "ambiguous,
878    /// multiple candidate projects" (409). A bare 404 with no domain-error
879    /// body is surfaced as `Err` instead of `None` (see `resolve_remote`'s
880    /// doc comment for why). `GET /api/v1/projects/resolve?git_url=`.
881    pub async fn resolve_project(
882        &self,
883        git_url: &str,
884    ) -> Result<ResolveProjectOutcome, Box<dyn std::error::Error>> {
885        let mut url = Url::parse(&format!("{}/api/v1/projects/resolve", self.base_url))?;
886        url.query_pairs_mut().append_pair("git_url", git_url);
887        let resp = self.send_authed(self.client.get(url)).await?;
888        let status = resp.status();
889        if status == reqwest::StatusCode::NOT_FOUND {
890            let body = resp.text().await.unwrap_or_default();
891            return if is_domain_error_body(&body) {
892                Ok(ResolveProjectOutcome::None)
893            } else {
894                Err(version_skew_404_error("resolve_project"))
895            };
896        }
897        if status == reqwest::StatusCode::CONFLICT {
898            return Ok(ResolveProjectOutcome::Ambiguous);
899        }
900        let parsed: ResolveProjectResponse =
901            Self::success_json(resp, |status| format!("resolve_project failed ({status})")).await?;
902        Ok(ResolveProjectOutcome::Resolved(parsed.project_id))
903    }
904}
905
906/// Map an OIDC failure onto [`AuthError`], keeping "the session is dead"
907/// distinct from "the refresh attempt itself failed".
908fn auth_error(e: crate::oidc::OidcError) -> AuthError {
909    match e {
910        crate::oidc::OidcError::SessionExpired => AuthError::SessionExpired,
911        other => AuthError::Refresh(other.to_string()),
912    }
913}
914
915/// Classify a `send_authed` failure for the `GetMeError`-returning callers.
916/// A dead session becomes `Unauthorized`; everything else (transport, IdP
917/// unreachable) becomes `Network`, which callers render as "cannot confirm".
918fn get_me_send_error(e: Box<dyn Error>) -> GetMeError {
919    match e.downcast::<AuthError>() {
920        Ok(auth) => match *auth {
921            AuthError::SessionExpired => GetMeError::Unauthorized,
922            AuthError::Refresh(m) => GetMeError::Network(m),
923        },
924        Err(other) => GetMeError::Network(other.to_string()),
925    }
926}
927
928/// Whether a 404 response body matches the server's JSON error envelope —
929/// `{"error": "...", ...}`, emitted by every domain-level `AppError` (see
930/// `tracevault-server`'s `error.rs`) — rather than the empty/plain body
931/// axum's built-in "no route matched" fallback sends when the server has no
932/// handler for the path at all. Used by `resolve_remote`/`resolve_project`
933/// to tell a genuine "not tracked"/"no project" 404 apart from a 404 that
934/// really means "this server doesn't have this route" (most plausibly a
935/// CLI/server version skew).
936fn is_domain_error_body(body: &str) -> bool {
937    serde_json::from_str::<serde_json::Value>(body)
938        .ok()
939        .and_then(|v| v.get("error").map(|_| ()))
940        .is_some()
941}
942
943/// The error for a 404 whose body doesn't match the server's JSON error
944/// envelope (see [`is_domain_error_body`]) — surfaced instead of silently
945/// treating the call as "not tracked"/"no project", since this shape is the
946/// CLI's best signal that the server doesn't recognize `what`'s route at
947/// all, rather than a genuine absence of the resource.
948fn version_skew_404_error(what: &str) -> Box<dyn std::error::Error> {
949    format!(
950        "{what} got a 404 with no recognizable error body — this endpoint may not exist on \
951         this server yet. This usually means the CLI is newer than the server (a CLI/server \
952         version mismatch); confirm the server has been upgraded and retry."
953    )
954    .into()
955}
956
957/// Resolve `project_root`'s credentials (via `resolve_credentials`) into a
958/// ready `ApiClient`, or the standard "no server URL configured" error when
959/// none of the credential sources yield a server URL. Shared by every
960/// command that needs a client from a project root, so this
961/// resolve-then-construct shape has exactly one implementation.
962pub fn resolve_client(project_root: &Path) -> Result<ApiClient, Box<dyn Error>> {
963    let (server_url, credential) = resolve_credentials(project_root)?;
964    let server_url = server_url
965        .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
966    Ok(ApiClient::with_credential(&server_url, credential))
967}
968
969#[cfg(test)]
970mod tests {
971    use super::*;
972    use crate::credentials::KeycloakSession;
973    use crate::test_helpers::{http_json, spawn_seq, spawn_seq_with, RECV_TIMEOUT};
974    use std::time::Duration;
975
976    /// Fixed "now" for the refresh-window tests. Using a constant instead of
977    /// the wall clock is what makes the boundary assertions deterministic.
978    const NOW: i64 = 1_800_000_000;
979
980    fn fixed_now() -> i64 {
981        NOW
982    }
983
984    /// A fake IdP that answers discovery (self-reporting its own URL as the
985    /// issuer, as a real one must) and then one token request. Returns the
986    /// issuer URL to put in the session.
987    fn spawn_idp(token_response: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
988        spawn_seq_with(move |base| {
989            vec![
990                http_json(
991                    "200 OK",
992                    &format!(
993                        r#"{{"issuer":"{base}","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device","revocation_endpoint":"{base}/revoke"}}"#
994                    ),
995                ),
996                http_json("200 OK", token_response),
997            ]
998        })
999    }
1000
1001    /// Write a Keycloak credentials file for `server_url`/`issuer` into
1002    /// `dir`, so a refresh has something to adopt from and persist into.
1003    ///
1004    /// `server_url` is explicit because the adopt and the persist are both
1005    /// scoped to the client's `base_url`: a helper that hardcoded it would
1006    /// silently disable persistence in tests whose client points elsewhere.
1007    fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
1008        let creds_dir = dir.join("tracevault");
1009        std::fs::create_dir_all(&creds_dir).unwrap();
1010        std::fs::write(
1011            creds_dir.join("credentials.json"),
1012            format!(
1013                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}}}}}"#
1014            ),
1015        )
1016        .unwrap();
1017    }
1018
1019    fn session(issuer: &str, expires_at: i64) -> KeycloakSession {
1020        KeycloakSession {
1021            issuer: issuer.to_string(),
1022            client_id: "tracing-cli".into(),
1023            refresh_token: "old-rt".into(),
1024            access_token: "old-at".into(),
1025            access_expires_at: expires_at,
1026        }
1027    }
1028
1029    /// An access token inside the 60s window is refreshed BEFORE the request
1030    /// goes out, and the new tokens are written back to disk so the next
1031    /// process doesn't repeat the refresh.
1032    #[tokio::test]
1033    async fn bearer_refreshes_inside_the_sixty_second_window() {
1034        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1035        let dir = tempfile::tempdir().unwrap();
1036        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1037        _guard.set("XDG_CONFIG_HOME", dir.path());
1038
1039        let (issuer, rx) =
1040            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1041        // 30s of life left — inside the window.
1042        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 30);
1043
1044        let client = ApiClient::with_credential(
1045            "https://example.com",
1046            Some(Credential::Keycloak(session(&issuer, NOW + 30))),
1047        )
1048        .with_now(fixed_now);
1049
1050        let token = client.bearer().await.unwrap();
1051        assert_eq!(token.as_deref(), Some("fresh-at"));
1052
1053        // Discovery, then the refresh_token grant.
1054        let disc = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1055        assert!(disc.contains("/.well-known/openid-configuration"), "{disc}");
1056        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1057        assert!(refresh.contains("grant_type=refresh_token"), "{refresh}");
1058        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
1059        assert!(
1060            !refresh.contains("client_secret"),
1061            "the CLI client is public; no secret may be sent: {refresh}"
1062        );
1063
1064        // Persisted, so a git hook running a second later doesn't refresh again.
1065        let saved = Credentials::load().expect("credentials must still exist");
1066        let auth = saved.auth.expect("auth block must survive a refresh");
1067        assert_eq!(auth.access_token, "fresh-at");
1068        assert_eq!(auth.refresh_token, "fresh-rt");
1069        assert_eq!(auth.access_expires_at, NOW + 300);
1070        assert_eq!(saved.email, "a@b.com", "unrelated fields must be preserved");
1071    }
1072
1073    /// Two git hooks can run at once, and `tracevault status` builds two
1074    /// clients from one credential. If another process already refreshed, this
1075    /// one must ADOPT that session rather than present the refresh token that
1076    /// was just consumed — with refresh-token rotation enabled that would come
1077    /// back `invalid_grant` and log the user out for no reason.
1078    ///
1079    /// The issuer points at a dead port, so any actual refresh attempt would
1080    /// fail the call: reaching the assertion proves no round trip happened.
1081    #[tokio::test]
1082    async fn bearer_adopts_a_newer_session_written_by_another_process() {
1083        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1084        let dir = tempfile::tempdir().unwrap();
1085        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1086        _guard.set("XDG_CONFIG_HOME", dir.path());
1087
1088        // On disk: a session refreshed by "another process" — different
1089        // refresh token, plenty of life left.
1090        let creds_dir = dir.path().join("tracevault");
1091        std::fs::create_dir_all(&creds_dir).unwrap();
1092        std::fs::write(
1093            creds_dir.join("credentials.json"),
1094            format!(
1095                r#"{{"server_url":"https://example.com","email":"a@b.com","auth":{{"issuer":"http://127.0.0.1:1","client_id":"tracing-cli","refresh_token":"rotated-rt","access_token":"other-process-at","access_expires_at":{}}}}}"#,
1096                NOW + 3600
1097            ),
1098        )
1099        .unwrap();
1100
1101        // In memory: the stale session this client was built from.
1102        let client = ApiClient::with_credential(
1103            "https://example.com",
1104            Some(Credential::Keycloak(session(
1105                "http://127.0.0.1:1",
1106                NOW + 10,
1107            ))),
1108        )
1109        .with_now(fixed_now);
1110
1111        let token = client
1112            .bearer()
1113            .await
1114            .expect("adopting the on-disk session must not require the IdP");
1115        assert_eq!(token.as_deref(), Some("other-process-at"));
1116    }
1117    /// There is one credentials file but a machine can target several
1118    /// TraceVault instances. A file belonging to instance B must NOT be adopted
1119    /// by a client talking to instance A (that would send B's token to A), and
1120    /// A's refreshed session must NOT overwrite B's file (that would sign the
1121    /// user out of B).
1122    ///
1123    /// Covers BOTH directions of the `same_server` comparison at this call site:
1124    /// the mismatch above, and — at the end — that a file differing only by a
1125    /// trailing slash IS still adopted. Without that second half, replacing
1126    /// `same_server` with `==` here goes unnoticed and quietly disables the
1127    /// adopt for every user whose stored URL has a trailing slash.
1128    #[tokio::test]
1129    async fn a_credentials_file_for_another_server_is_neither_adopted_nor_overwritten() {
1130        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1131        let dir = tempfile::tempdir().unwrap();
1132        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1133        _guard.set("XDG_CONFIG_HOME", dir.path());
1134
1135        let (issuer, rx) = spawn_idp(
1136            r#"{"access_token":"a-fresh-at","refresh_token":"a-fresh-rt","expires_in":300}"#,
1137        );
1138
1139        // On disk: instance B's session, freshly written by `tv login` in
1140        // another terminal. Different refresh token, plenty of life left — so
1141        // an unscoped adopt WOULD take it.
1142        let creds_dir = dir.path().join("tracevault");
1143        std::fs::create_dir_all(&creds_dir).unwrap();
1144        let b_file = format!(
1145            r#"{{"server_url":"https://instance-b.example.com","email":"b@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"b-rt","access_token":"b-at","access_expires_at":{}}}}}"#,
1146            NOW + 3600
1147        );
1148        std::fs::write(creds_dir.join("credentials.json"), &b_file).unwrap();
1149
1150        // This client talks to instance A and holds A's own session.
1151        let client = ApiClient::with_credential(
1152            "https://instance-a.example.com",
1153            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1154        )
1155        .with_now(fixed_now);
1156
1157        let token = client.bearer().await.expect("A's own refresh must succeed");
1158        assert_eq!(token.as_deref(), "a-fresh-at".into());
1159
1160        // The refresh used A's OWN in-memory token — B's was never presented.
1161        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1162        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1163        assert!(
1164            refresh.contains("refresh_token=old-rt"),
1165            "A must refresh with its own token: {refresh}"
1166        );
1167        assert!(
1168            !refresh.contains("b-rt"),
1169            "another server's refresh token must never be presented: {refresh}"
1170        );
1171
1172        // And B's credentials file is untouched: byte-identical to what
1173        // `tv login` wrote for B.
1174        let after = std::fs::read_to_string(creds_dir.join("credentials.json")).unwrap();
1175        assert_eq!(
1176            after, b_file,
1177            "instance A's refresh overwrote instance B's credentials"
1178        );
1179
1180        // The other direction at this same call site: a file for the SAME
1181        // instance, written with a trailing slash (as `tv login` stores whatever
1182        // it was given, while `ApiClient` trims). It must be adopted — so the
1183        // comparison has to be `same_server`, not `==`.
1184        std::fs::write(
1185            creds_dir.join("credentials.json"),
1186            format!(
1187                r#"{{"server_url":"https://instance-a.example.com/","email":"a@b.com","auth":{{"issuer":"http://127.0.0.1:1","client_id":"tracing-cli","refresh_token":"adopted-rt","access_token":"adopted-at","access_expires_at":{}}}}}"#,
1188                NOW + 3600
1189            ),
1190        )
1191        .unwrap();
1192        // A dead issuer, so an un-adopted session could only fail here.
1193        let client = ApiClient::with_credential(
1194            "https://instance-a.example.com",
1195            Some(Credential::Keycloak(session(
1196                "http://127.0.0.1:1",
1197                NOW + 10,
1198            ))),
1199        )
1200        .with_now(fixed_now);
1201        assert_eq!(
1202            client
1203                .bearer()
1204                .await
1205                .expect("a trailing slash must not prevent the adopt")
1206                .as_deref(),
1207            Some("adopted-at")
1208        );
1209    }
1210
1211    /// The interleaving that makes the adopt unconditional: the on-disk
1212    /// session has a NEWER refresh token AND its access token is itself inside
1213    /// the refresh window. A refresh is genuinely needed, so it must be
1214    /// performed with the ADOPTED refresh token — refreshing with the
1215    /// in-memory one, which another client already consumed, is the
1216    /// guaranteed-`invalid_grant` case the adopt exists to prevent.
1217    #[tokio::test]
1218    async fn a_refresh_after_adopting_uses_the_disk_refresh_token() {
1219        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1220        let dir = tempfile::tempdir().unwrap();
1221        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1222        _guard.set("XDG_CONFIG_HOME", dir.path());
1223
1224        let (issuer, rx) = spawn_idp(
1225            r#"{"access_token":"newest-at","refresh_token":"newest-rt","expires_in":300}"#,
1226        );
1227
1228        // On disk: another client already rotated the refresh token, but its
1229        // access token is ALSO within 60s of expiry.
1230        let creds_dir = dir.path().join("tracevault");
1231        std::fs::create_dir_all(&creds_dir).unwrap();
1232        std::fs::write(
1233            creds_dir.join("credentials.json"),
1234            format!(
1235                r#"{{"server_url":"https://example.com","email":"a@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"rotated-rt","access_token":"rotated-at","access_expires_at":{}}}}}"#,
1236                NOW + 5
1237            ),
1238        )
1239        .unwrap();
1240
1241        // In memory: the superseded session, also inside the window.
1242        let client = ApiClient::with_credential(
1243            "https://example.com",
1244            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1245        )
1246        .with_now(fixed_now);
1247
1248        let token = client.bearer().await.expect("the refresh must succeed");
1249        assert_eq!(token.as_deref(), Some("newest-at"));
1250
1251        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1252        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1253        assert!(
1254            refresh.contains("refresh_token=rotated-rt"),
1255            "the refresh must use the adopted on-disk token: {refresh}"
1256        );
1257        assert!(
1258            !refresh.contains("refresh_token=old-rt"),
1259            "the superseded in-memory token must NOT be presented: {refresh}"
1260        );
1261    }
1262
1263    /// On an IdP that does NOT rotate refresh tokens — RFC 6749 permits omitting
1264    /// `refresh_token` on a refresh, and `KeycloakSession::apply` keeps the
1265    /// previous one — every session on disk and in memory carries the SAME
1266    /// refresh token. A refresh-token comparison therefore never fires, so
1267    /// `tracevault status` (three clients from one credential) performed three
1268    /// redundant refreshes, silently. The on-disk access token outliving ours is
1269    /// the signal that actually works there.
1270    ///
1271    /// The issuer points at a dead port, so any refresh attempt would fail the
1272    /// call: reaching the assertion proves the adopt happened instead.
1273    #[tokio::test]
1274    async fn bearer_adopts_a_fresher_session_from_a_non_rotating_idp() {
1275        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1276        let dir = tempfile::tempdir().unwrap();
1277        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1278        _guard.set("XDG_CONFIG_HOME", dir.path());
1279
1280        // On disk: another client refreshed and got a new access token, but the
1281        // SAME refresh token back (no rotation).
1282        let creds_dir = dir.path().join("tracevault");
1283        std::fs::create_dir_all(&creds_dir).unwrap();
1284        std::fs::write(
1285            creds_dir.join("credentials.json"),
1286            format!(
1287                r#"{{"server_url":"https://example.com","email":"a@b.com","auth":{{"issuer":"http://127.0.0.1:1","client_id":"tracing-cli","refresh_token":"old-rt","access_token":"refreshed-by-someone-else","access_expires_at":{}}}}}"#,
1288                NOW + 3600
1289            ),
1290        )
1291        .unwrap();
1292
1293        // In memory: the same refresh token, an access token about to expire.
1294        let client = ApiClient::with_credential(
1295            "https://example.com",
1296            Some(Credential::Keycloak(session(
1297                "http://127.0.0.1:1",
1298                NOW + 10,
1299            ))),
1300        )
1301        .with_now(fixed_now);
1302
1303        let token = client
1304            .bearer()
1305            .await
1306            .expect("a fresher on-disk session must be adopted, not re-refreshed");
1307        assert_eq!(token.as_deref(), Some("refreshed-by-someone-else"));
1308    }
1309
1310    /// Outside the window the stored token is used as-is. The issuer points
1311    /// at a port nothing listens on, so ANY refresh attempt would fail the
1312    /// call — proving no network round trip happened.
1313    #[tokio::test]
1314    async fn bearer_does_not_refresh_outside_the_window() {
1315        let client = ApiClient::with_credential(
1316            "https://example.com",
1317            Some(Credential::Keycloak(session(
1318                "http://127.0.0.1:1",
1319                NOW + 3600,
1320            ))),
1321        )
1322        .with_now(fixed_now);
1323
1324        let token = client
1325            .bearer()
1326            .await
1327            .expect("a still-valid token must not trigger any IdP call");
1328        assert_eq!(token.as_deref(), Some("old-at"));
1329    }
1330
1331    /// The API-key path is a pure passthrough: no clock, no IdP, no refresh.
1332    #[tokio::test]
1333    async fn bearer_returns_an_api_key_verbatim() {
1334        let client = ApiClient::new("https://example.com", Some("tvk_abc"));
1335        assert_eq!(client.bearer().await.unwrap().as_deref(), Some("tvk_abc"));
1336
1337        let anonymous = ApiClient::new("https://example.com", None);
1338        assert_eq!(anonymous.bearer().await.unwrap(), None);
1339    }
1340
1341    /// A 401 on an API key is a real rejection: retrying would double every
1342    /// failure and could re-run a non-idempotent write. Exactly ONE request
1343    /// must reach the server.
1344    #[tokio::test]
1345    async fn a_401_with_an_api_key_does_not_refresh_or_retry() {
1346        let (base, rx) = spawn_seq(vec![
1347            http_json("401 Unauthorized", r#"{"error":"invalid token"}"#),
1348            // A second response is queued precisely to prove it is unused.
1349            http_json("200 OK", "[]"),
1350        ]);
1351        let client = ApiClient::new(&base, Some("tvk_abc"));
1352        client
1353            .list_repos()
1354            .await
1355            .expect_err("a 401 must surface as an error");
1356
1357        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
1358        assert!(first.contains("GET /api/v1/repos"), "{first}");
1359        assert!(
1360            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1361            "an API key must never be retried after a 401"
1362        );
1363    }
1364
1365    /// A Keycloak credential that gets an unexpected 401 (server-side session
1366    /// invalidation, clock skew) force-refreshes and retries ONCE.
1367    #[tokio::test]
1368    async fn a_401_with_a_keycloak_credential_refreshes_and_retries_once() {
1369        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1370        let dir = tempfile::tempdir().unwrap();
1371        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1372        _guard.set("XDG_CONFIG_HOME", dir.path());
1373
1374        let (issuer, _idp_rx) =
1375            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1376        let (base, rx) = spawn_seq(vec![
1377            http_json("401 Unauthorized", r#"{"error":"expired"}"#),
1378            http_json("200 OK", "[]"),
1379        ]);
1380        // The file is for THIS client's server, so the refreshed session is
1381        // persisted rather than skipped by the same-server guard.
1382        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
1383
1384        // Far from expiry: the proactive window must NOT be what triggers the
1385        // refresh here — the 401 must.
1386        let client = ApiClient::with_credential(
1387            &base,
1388            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
1389        )
1390        .with_now(fixed_now);
1391
1392        let repos = client
1393            .list_repos()
1394            .await
1395            .expect("the retry after a forced refresh must succeed");
1396        assert!(repos.is_empty());
1397
1398        // The point of the retry is that it presents the REFRESHED token; a
1399        // retry that re-sent the rejected one would be pointless and would
1400        // still 401 in production.
1401        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no first request");
1402        assert!(first.contains("GET /api/v1/repos"), "{first}");
1403        assert!(
1404            first.contains("Bearer old-at"),
1405            "the first attempt must carry the stored token: {first}"
1406        );
1407        let second = rx.recv_timeout(RECV_TIMEOUT).expect("no retry request");
1408        assert!(second.contains("GET /api/v1/repos"), "{second}");
1409        assert!(
1410            second.contains("Bearer fresh-at"),
1411            "the retry must carry the REFRESHED token, not the rejected one: {second}"
1412        );
1413        assert!(
1414            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1415            "the retry must happen at most once, or a 401-always server would loop"
1416        );
1417    }
1418
1419    /// A 401 that survives the retry must not send the request a third time:
1420    /// a server answering 401 unconditionally has to terminate.
1421    #[tokio::test]
1422    async fn a_persistent_401_stops_after_one_retry() {
1423        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1424        let dir = tempfile::tempdir().unwrap();
1425        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1426        _guard.set("XDG_CONFIG_HOME", dir.path());
1427
1428        let (issuer, _idp_rx) =
1429            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1430        let (base, rx) = spawn_seq(vec![
1431            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
1432            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
1433            http_json("200 OK", "[]"),
1434        ]);
1435        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
1436        let client = ApiClient::with_credential(
1437            &base,
1438            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
1439        )
1440        .with_now(fixed_now);
1441
1442        client
1443            .list_repos()
1444            .await
1445            .expect_err("a persistent 401 must surface as an error");
1446
1447        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
1448        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
1449        assert!(
1450            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1451            "a third attempt means the retry can loop"
1452        );
1453    }
1454
1455    /// A dead refresh token must surface as "log in again", not as a bland
1456    /// 401 or a network error — `tracevault status` renders those differently.
1457    #[tokio::test]
1458    async fn get_me_maps_a_dead_refresh_token_to_unauthorized() {
1459        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1460        let dir = tempfile::tempdir().unwrap();
1461        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1462        _guard.set("XDG_CONFIG_HOME", dir.path());
1463
1464        let (issuer, _rx) = spawn_seq_with(|base| {
1465            vec![
1466                http_json(
1467                    "200 OK",
1468                    &format!(r#"{{"issuer":"{base}","token_endpoint":"{base}/token"}}"#),
1469                ),
1470                http_json("400 Bad Request", r#"{"error":"invalid_grant"}"#),
1471            ]
1472        });
1473        write_keycloak_file(dir.path(), "http://127.0.0.1:1", &issuer, NOW + 10);
1474
1475        let client = ApiClient::with_credential(
1476            "http://127.0.0.1:1",
1477            // Inside the window, so the (failing) refresh happens before any
1478            // request to the server is attempted.
1479            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1480        )
1481        .with_now(fixed_now);
1482
1483        match client.get_me().await {
1484            Err(GetMeError::Unauthorized) => {}
1485            other => panic!("expected Unauthorized for a dead session, got {other:?}"),
1486        }
1487    }
1488
1489    /// An unreachable IdP is NOT a dead session: it must stay distinguishable
1490    /// so status says "cannot confirm" rather than "you were logged out".
1491    #[tokio::test]
1492    async fn get_me_maps_an_unreachable_idp_to_network() {
1493        // The session is inside the refresh window, so `refresh_locked` calls
1494        // `Credentials::load()`. Without this redirect that reads the
1495        // DEVELOPER's real `~/.config/tracevault/credentials.json` — which on a
1496        // machine logged in with Keycloak means reading a live token, and makes
1497        // the test's outcome depend on the developer's own login state.
1498        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1499        let dir = tempfile::tempdir().unwrap();
1500        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1501        _guard.set("XDG_CONFIG_HOME", dir.path());
1502
1503        let client = ApiClient::with_credential(
1504            "http://127.0.0.1:1",
1505            Some(Credential::Keycloak(session(
1506                "http://127.0.0.1:1",
1507                NOW + 10,
1508            ))),
1509        )
1510        .with_now(fixed_now);
1511
1512        match client.get_me().await {
1513            Err(GetMeError::Network(_)) => {}
1514            other => panic!("expected Network for an unreachable IdP, got {other:?}"),
1515        }
1516    }
1517
1518    /// A 403 is its own outcome: the token is fine, the account isn't
1519    /// authorized, and "log in again" would be the wrong advice.
1520    #[tokio::test]
1521    async fn get_me_maps_403_to_forbidden() {
1522        let (base, _rx) = spawn_seq(vec![http_json(
1523            "403 Forbidden",
1524            r#"{"error":"missing role"}"#,
1525        )]);
1526        let client = ApiClient::new(&base, Some("tvk_abc"));
1527        match client.get_me().await {
1528            Err(GetMeError::Forbidden(_)) => {}
1529            other => panic!("expected Forbidden, got {other:?}"),
1530        }
1531    }
1532
1533    /// `resolve_client` is the funnel the project/repo commands use, so the
1534    /// guard has to hold through the wrapper too — not only in
1535    /// `resolve_credentials`, whose own tests now live beside it in
1536    /// `credentials.rs`.
1537    #[test]
1538    fn resolve_client_also_refuses_a_mismatched_server_url() {
1539        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1540        let dir = tempfile::tempdir().unwrap();
1541        let mut guard = crate::test_helpers::EnvVarGuard::new();
1542        guard.set("XDG_CONFIG_HOME", dir.path());
1543        guard.remove("TRACEVAULT_API_KEY");
1544        guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
1545        write_keycloak_file(
1546            dir.path(),
1547            "https://instance-b.example.com",
1548            "https://idp.test/realms/v",
1549            NOW + 3600,
1550        );
1551
1552        // `ApiClient` deliberately has no `Debug` (it holds a credential), so
1553        // match instead of `expect_err`.
1554        let err = match resolve_client(dir.path()) {
1555            Err(e) => e,
1556            Ok(_) => panic!("resolve_client must apply the guard"),
1557        };
1558        assert!(err.to_string().contains("instance-b.example.com"));
1559    }
1560}