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