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