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 the project in the path and `repo_id` — when
680    /// there is one — as a query param rather than a path segment. The query
681    /// is built with `Url::query_pairs_mut`, mirroring `resolve_project`'s
682    /// `?git_url=`, so `repo_id` is percent-encoded rather than
683    /// string-interpolated into the URL.
684    ///
685    /// `repo_id` is `None` for a repo-less session, and the pair is then
686    /// omitted entirely: the server declares it optional
687    /// (`ProjectStreamQuery::repo_id: Option<Uuid>`) and would reject an
688    /// empty value as a malformed UUID.
689    ///
690    /// Called from `commands::stream::send_stream_event` for both the
691    /// `Attribution::Repo { project: Some(_) }` and `Attribution::ProjectOnly`
692    /// routes.
693    pub async fn stream_event_for_project(
694        &self,
695        project_id: uuid::Uuid,
696        repo_id: Option<&str>,
697        req: &tracevault_protocol::streaming::StreamEventRequest,
698    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
699        let mut url = Url::parse(&format!(
700            "{}/api/v1/projects/{}/stream",
701            self.base_url, project_id
702        ))?;
703        // `repo_id` is OPTIONAL server-side (`ProjectStreamQuery::repo_id:
704        // Option<Uuid>` — "repo-less (0-repo) projects are supported"), so a
705        // repo-less session must omit the pair entirely. Appending an empty
706        // value instead would be parsed as a malformed UUID and 400.
707        if let Some(repo_id) = repo_id {
708            url.query_pairs_mut().append_pair("repo_id", repo_id);
709        }
710        let builder = self.client.post(url).json(req);
711        self.authed_send_json(builder, |status| {
712            format!("Project stream failed ({status})")
713        })
714        .await
715    }
716
717    pub async fn check_policies(
718        &self,
719        repo_id: &uuid::Uuid,
720        req: CheckPoliciesRequest,
721    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
722        let builder = self
723            .client
724            .post(format!(
725                "{}/api/v1/repos/{}/policies/check",
726                self.base_url, repo_id
727            ))
728            .json(&req);
729        self.authed_send_json(builder, |status| format!("Policy check failed ({status})"))
730            .await
731    }
732
733    /// Resolve a git URL to its codebase (git remote) by NORMALIZED URL —
734    /// deduped, unlike an exact `github_url` match. `Ok(None)` if the
735    /// codebase isn't tracked: a genuine domain 404, identified by the
736    /// server's JSON error envelope (see [`is_domain_error_body`]). A bare
737    /// 404 with no such body — axum's built-in "no route matched" fallback
738    /// — is surfaced as `Err` instead, since it means this server doesn't
739    /// have this route at all (most plausibly a CLI/server version skew,
740    /// e.g. this CLI shipped ahead of a server that still uses the old
741    /// org-scoped paths) rather than an absent codebase.
742    pub async fn resolve_remote(
743        &self,
744        git_url: &str,
745    ) -> Result<Option<ResolveRemoteResponse>, Box<dyn std::error::Error>> {
746        let mut url = Url::parse(&format!("{}/api/v1/remotes/resolve", self.base_url))?;
747        url.query_pairs_mut().append_pair("git_url", git_url);
748        let resp = self.send_authed(self.client.get(url)).await?;
749        if resp.status() == reqwest::StatusCode::NOT_FOUND {
750            let body = resp.text().await.unwrap_or_default();
751            return if is_domain_error_body(&body) {
752                Ok(None)
753            } else {
754                Err(version_skew_404_error("resolve_remote"))
755            };
756        }
757        let parsed: ResolveRemoteResponse =
758            Self::success_json(resp, |status| format!("resolve_remote failed ({status})")).await?;
759        Ok(Some(parsed))
760    }
761
762    /// Full detail for a remote (codebase): its display name, normalized URL,
763    /// clone status, and linked repos.
764    pub async fn get_remote_detail(
765        &self,
766        remote_id: uuid::Uuid,
767    ) -> Result<RemoteDetail, Box<dyn std::error::Error>> {
768        let builder = self
769            .client
770            .get(format!("{}/api/v1/remotes/{}", self.base_url, remote_id));
771        self.authed_send_json(builder, |status| {
772            format!("get_remote_detail failed ({status})")
773        })
774        .await
775    }
776
777    /// The repos linked to a remote (the codebase's members).
778    pub async fn get_remote_repos(
779        &self,
780        remote_id: uuid::Uuid,
781    ) -> Result<Vec<RemoteRepoRef>, Box<dyn std::error::Error>> {
782        Ok(self.get_remote_detail(remote_id).await?.repos)
783    }
784
785    /// List all projects. `GET /api/v1/projects`.
786    pub async fn list_projects(&self) -> Result<Vec<ProjectListItem>, Box<dyn Error>> {
787        let builder = self
788            .client
789            .get(format!("{}/api/v1/projects", self.base_url));
790        self.authed_send_json(builder, |status| {
791            format!("Failed to list projects ({status})")
792        })
793        .await
794    }
795
796    /// Full detail for a project. `GET /api/v1/projects/{id}`.
797    pub async fn get_project(&self, id: uuid::Uuid) -> Result<ProjectDetail, Box<dyn Error>> {
798        let builder = self
799            .client
800            .get(format!("{}/api/v1/projects/{}", self.base_url, id));
801        self.authed_send_json(builder, |status| {
802            format!("Failed to get project ({status})")
803        })
804        .await
805    }
806
807    /// Resolve a git URL to its project, distinguishing "no project" (a
808    /// genuine domain 404 — see [`is_domain_error_body`]) from "ambiguous,
809    /// multiple candidate projects" (409). A bare 404 with no domain-error
810    /// body is surfaced as `Err` instead of `None` (see `resolve_remote`'s
811    /// doc comment for why). `GET /api/v1/projects/resolve?git_url=`.
812    pub async fn resolve_project(
813        &self,
814        git_url: &str,
815    ) -> Result<ResolveProjectOutcome, Box<dyn std::error::Error>> {
816        let mut url = Url::parse(&format!("{}/api/v1/projects/resolve", self.base_url))?;
817        url.query_pairs_mut().append_pair("git_url", git_url);
818        let resp = self.send_authed(self.client.get(url)).await?;
819        let status = resp.status();
820        if status == reqwest::StatusCode::NOT_FOUND {
821            let body = resp.text().await.unwrap_or_default();
822            return if is_domain_error_body(&body) {
823                Ok(ResolveProjectOutcome::None)
824            } else {
825                Err(version_skew_404_error("resolve_project"))
826            };
827        }
828        if status == reqwest::StatusCode::CONFLICT {
829            return Ok(ResolveProjectOutcome::Ambiguous);
830        }
831        let parsed: ResolveProjectResponse =
832            Self::success_json(resp, |status| format!("resolve_project failed ({status})")).await?;
833        Ok(ResolveProjectOutcome::Resolved(parsed.project_id))
834    }
835}
836
837/// Map an OIDC failure onto [`AuthError`], keeping "the session is dead"
838/// distinct from "the refresh attempt itself failed".
839fn auth_error(e: crate::oidc::OidcError) -> AuthError {
840    match e {
841        crate::oidc::OidcError::SessionExpired => AuthError::SessionExpired,
842        other => AuthError::Refresh(other.to_string()),
843    }
844}
845
846/// Classify a `send_authed` failure for the `GetMeError`-returning callers.
847/// A dead session becomes `Unauthorized`; everything else (transport, IdP
848/// unreachable) becomes `Network`, which callers render as "cannot confirm".
849fn get_me_send_error(e: Box<dyn Error>) -> GetMeError {
850    match e.downcast::<AuthError>() {
851        Ok(auth) => match *auth {
852            AuthError::SessionExpired => GetMeError::Unauthorized,
853            AuthError::Refresh(m) => GetMeError::Network(m),
854        },
855        Err(other) => GetMeError::Network(other.to_string()),
856    }
857}
858
859/// Whether a 404 response body matches the server's JSON error envelope —
860/// `{"error": "...", ...}`, emitted by every domain-level `AppError` (see
861/// `tracevault-server`'s `error.rs`) — rather than the empty/plain body
862/// axum's built-in "no route matched" fallback sends when the server has no
863/// handler for the path at all. Used by `resolve_remote`/`resolve_project`
864/// to tell a genuine "not tracked"/"no project" 404 apart from a 404 that
865/// really means "this server doesn't have this route" (most plausibly a
866/// CLI/server version skew).
867fn is_domain_error_body(body: &str) -> bool {
868    serde_json::from_str::<serde_json::Value>(body)
869        .ok()
870        .and_then(|v| v.get("error").map(|_| ()))
871        .is_some()
872}
873
874/// The error for a 404 whose body doesn't match the server's JSON error
875/// envelope (see [`is_domain_error_body`]) — surfaced instead of silently
876/// treating the call as "not tracked"/"no project", since this shape is the
877/// CLI's best signal that the server doesn't recognize `what`'s route at
878/// all, rather than a genuine absence of the resource.
879fn version_skew_404_error(what: &str) -> Box<dyn std::error::Error> {
880    format!(
881        "{what} got a 404 with no recognizable error body — this endpoint may not exist on \
882         this server yet. This usually means the CLI is newer than the server (a CLI/server \
883         version mismatch); confirm the server has been upgraded and retry."
884    )
885    .into()
886}
887
888/// Resolve `project_root`'s credentials (via `resolve_credentials`) into a
889/// ready `ApiClient`, or the standard "no server URL configured" error when
890/// none of the credential sources yield a server URL. Shared by every
891/// command that needs a client from a project root, so this
892/// resolve-then-construct shape has exactly one implementation.
893pub fn resolve_client(project_root: &Path) -> Result<ApiClient, Box<dyn Error>> {
894    let (server_url, credential) = resolve_credentials(project_root)?;
895    let server_url = server_url
896        .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
897    Ok(ApiClient::with_credential(&server_url, credential))
898}
899
900#[cfg(test)]
901mod tests {
902    use super::*;
903    use crate::credentials::KeycloakSession;
904    use crate::test_helpers::{http_json, spawn_seq, spawn_seq_with, RECV_TIMEOUT};
905    use std::time::Duration;
906
907    /// Fixed "now" for the refresh-window tests. Using a constant instead of
908    /// the wall clock is what makes the boundary assertions deterministic.
909    const NOW: i64 = 1_800_000_000;
910
911    fn fixed_now() -> i64 {
912        NOW
913    }
914
915    /// A fake IdP that answers discovery (self-reporting its own URL as the
916    /// issuer, as a real one must) and then one token request. Returns the
917    /// issuer URL to put in the session.
918    fn spawn_idp(token_response: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
919        spawn_seq_with(move |base| {
920            vec![
921                http_json(
922                    "200 OK",
923                    &format!(
924                        r#"{{"issuer":"{base}","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device","revocation_endpoint":"{base}/revoke"}}"#
925                    ),
926                ),
927                http_json("200 OK", token_response),
928            ]
929        })
930    }
931
932    /// Write a Keycloak credentials file for `server_url`/`issuer` into
933    /// `dir`, so a refresh has something to adopt from and persist into.
934    ///
935    /// `server_url` is explicit because the adopt and the persist are both
936    /// scoped to the client's `base_url`: a helper that hardcoded it would
937    /// silently disable persistence in tests whose client points elsewhere.
938    fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
939        let creds_dir = dir.join("tracevault");
940        std::fs::create_dir_all(&creds_dir).unwrap();
941        std::fs::write(
942            creds_dir.join("credentials.json"),
943            format!(
944                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}}}}}"#
945            ),
946        )
947        .unwrap();
948    }
949
950    fn session(issuer: &str, expires_at: i64) -> KeycloakSession {
951        KeycloakSession {
952            issuer: issuer.to_string(),
953            client_id: "tracing-cli".into(),
954            refresh_token: "old-rt".into(),
955            access_token: "old-at".into(),
956            access_expires_at: expires_at,
957        }
958    }
959
960    /// An access token inside the 60s window is refreshed BEFORE the request
961    /// goes out, and the new tokens are written back to disk so the next
962    /// process doesn't repeat the refresh.
963    #[tokio::test]
964    async fn bearer_refreshes_inside_the_sixty_second_window() {
965        let _env_lock = crate::test_helpers::lock_env_mutation().await;
966        let dir = tempfile::tempdir().unwrap();
967        let mut _guard = crate::test_helpers::EnvVarGuard::new();
968        _guard.set("XDG_CONFIG_HOME", dir.path());
969
970        let (issuer, rx) =
971            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
972        // 30s of life left — inside the window.
973        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 30);
974
975        let client = ApiClient::with_credential(
976            "https://example.com",
977            Some(Credential::Keycloak(session(&issuer, NOW + 30))),
978        )
979        .with_now(fixed_now);
980
981        let token = client.bearer().await.unwrap();
982        assert_eq!(token.as_deref(), Some("fresh-at"));
983
984        // Discovery, then the refresh_token grant.
985        let disc = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
986        assert!(disc.contains("/.well-known/openid-configuration"), "{disc}");
987        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
988        assert!(refresh.contains("grant_type=refresh_token"), "{refresh}");
989        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
990        assert!(
991            !refresh.contains("client_secret"),
992            "the CLI client is public; no secret may be sent: {refresh}"
993        );
994
995        // Persisted, so a git hook running a second later doesn't refresh again.
996        let saved = Credentials::load().expect("credentials must still exist");
997        let auth = saved.auth.expect("auth block must survive a refresh");
998        assert_eq!(auth.access_token, "fresh-at");
999        assert_eq!(auth.refresh_token, "fresh-rt");
1000        assert_eq!(auth.access_expires_at, NOW + 300);
1001        assert_eq!(saved.email, "a@b.com", "unrelated fields must be preserved");
1002    }
1003
1004    /// Two git hooks can run at once, and `tracevault status` builds two
1005    /// clients from one credential. If another process already refreshed, this
1006    /// one must ADOPT that session rather than present the refresh token that
1007    /// was just consumed — with refresh-token rotation enabled that would come
1008    /// back `invalid_grant` and log the user out for no reason.
1009    ///
1010    /// The issuer points at a dead port, so any actual refresh attempt would
1011    /// fail the call: reaching the assertion proves no round trip happened.
1012    #[tokio::test]
1013    async fn bearer_adopts_a_newer_session_written_by_another_process() {
1014        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1015        let dir = tempfile::tempdir().unwrap();
1016        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1017        _guard.set("XDG_CONFIG_HOME", dir.path());
1018
1019        // On disk: a session refreshed by "another process" — different
1020        // refresh token, plenty of life left.
1021        let creds_dir = dir.path().join("tracevault");
1022        std::fs::create_dir_all(&creds_dir).unwrap();
1023        std::fs::write(
1024            creds_dir.join("credentials.json"),
1025            format!(
1026                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":{}}}}}"#,
1027                NOW + 3600
1028            ),
1029        )
1030        .unwrap();
1031
1032        // In memory: the stale session this client was built from.
1033        let client = ApiClient::with_credential(
1034            "https://example.com",
1035            Some(Credential::Keycloak(session(
1036                "http://127.0.0.1:1",
1037                NOW + 10,
1038            ))),
1039        )
1040        .with_now(fixed_now);
1041
1042        let token = client
1043            .bearer()
1044            .await
1045            .expect("adopting the on-disk session must not require the IdP");
1046        assert_eq!(token.as_deref(), Some("other-process-at"));
1047    }
1048    /// There is one credentials file but a machine can target several
1049    /// TraceVault instances. A file belonging to instance B must NOT be adopted
1050    /// by a client talking to instance A (that would send B's token to A), and
1051    /// A's refreshed session must NOT overwrite B's file (that would sign the
1052    /// user out of B).
1053    ///
1054    /// Covers BOTH directions of the `same_server` comparison at this call site:
1055    /// the mismatch above, and — at the end — that a file differing only by a
1056    /// trailing slash IS still adopted. Without that second half, replacing
1057    /// `same_server` with `==` here goes unnoticed and quietly disables the
1058    /// adopt for every user whose stored URL has a trailing slash.
1059    #[tokio::test]
1060    async fn a_credentials_file_for_another_server_is_neither_adopted_nor_overwritten() {
1061        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1062        let dir = tempfile::tempdir().unwrap();
1063        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1064        _guard.set("XDG_CONFIG_HOME", dir.path());
1065
1066        let (issuer, rx) = spawn_idp(
1067            r#"{"access_token":"a-fresh-at","refresh_token":"a-fresh-rt","expires_in":300}"#,
1068        );
1069
1070        // On disk: instance B's session, freshly written by `tv login` in
1071        // another terminal. Different refresh token, plenty of life left — so
1072        // an unscoped adopt WOULD take it.
1073        let creds_dir = dir.path().join("tracevault");
1074        std::fs::create_dir_all(&creds_dir).unwrap();
1075        let b_file = format!(
1076            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":{}}}}}"#,
1077            NOW + 3600
1078        );
1079        std::fs::write(creds_dir.join("credentials.json"), &b_file).unwrap();
1080
1081        // This client talks to instance A and holds A's own session.
1082        let client = ApiClient::with_credential(
1083            "https://instance-a.example.com",
1084            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1085        )
1086        .with_now(fixed_now);
1087
1088        let token = client.bearer().await.expect("A's own refresh must succeed");
1089        assert_eq!(token.as_deref(), "a-fresh-at".into());
1090
1091        // The refresh used A's OWN in-memory token — B's was never presented.
1092        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1093        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1094        assert!(
1095            refresh.contains("refresh_token=old-rt"),
1096            "A must refresh with its own token: {refresh}"
1097        );
1098        assert!(
1099            !refresh.contains("b-rt"),
1100            "another server's refresh token must never be presented: {refresh}"
1101        );
1102
1103        // And B's credentials file is untouched: byte-identical to what
1104        // `tv login` wrote for B.
1105        let after = std::fs::read_to_string(creds_dir.join("credentials.json")).unwrap();
1106        assert_eq!(
1107            after, b_file,
1108            "instance A's refresh overwrote instance B's credentials"
1109        );
1110
1111        // The other direction at this same call site: a file for the SAME
1112        // instance, written with a trailing slash (as `tv login` stores whatever
1113        // it was given, while `ApiClient` trims). It must be adopted — so the
1114        // comparison has to be `same_server`, not `==`.
1115        std::fs::write(
1116            creds_dir.join("credentials.json"),
1117            format!(
1118                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":{}}}}}"#,
1119                NOW + 3600
1120            ),
1121        )
1122        .unwrap();
1123        // A dead issuer, so an un-adopted session could only fail here.
1124        let client = ApiClient::with_credential(
1125            "https://instance-a.example.com",
1126            Some(Credential::Keycloak(session(
1127                "http://127.0.0.1:1",
1128                NOW + 10,
1129            ))),
1130        )
1131        .with_now(fixed_now);
1132        assert_eq!(
1133            client
1134                .bearer()
1135                .await
1136                .expect("a trailing slash must not prevent the adopt")
1137                .as_deref(),
1138            Some("adopted-at")
1139        );
1140    }
1141
1142    /// The interleaving that makes the adopt unconditional: the on-disk
1143    /// session has a NEWER refresh token AND its access token is itself inside
1144    /// the refresh window. A refresh is genuinely needed, so it must be
1145    /// performed with the ADOPTED refresh token — refreshing with the
1146    /// in-memory one, which another client already consumed, is the
1147    /// guaranteed-`invalid_grant` case the adopt exists to prevent.
1148    #[tokio::test]
1149    async fn a_refresh_after_adopting_uses_the_disk_refresh_token() {
1150        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1151        let dir = tempfile::tempdir().unwrap();
1152        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1153        _guard.set("XDG_CONFIG_HOME", dir.path());
1154
1155        let (issuer, rx) = spawn_idp(
1156            r#"{"access_token":"newest-at","refresh_token":"newest-rt","expires_in":300}"#,
1157        );
1158
1159        // On disk: another client already rotated the refresh token, but its
1160        // access token is ALSO within 60s of expiry.
1161        let creds_dir = dir.path().join("tracevault");
1162        std::fs::create_dir_all(&creds_dir).unwrap();
1163        std::fs::write(
1164            creds_dir.join("credentials.json"),
1165            format!(
1166                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":{}}}}}"#,
1167                NOW + 5
1168            ),
1169        )
1170        .unwrap();
1171
1172        // In memory: the superseded session, also inside the window.
1173        let client = ApiClient::with_credential(
1174            "https://example.com",
1175            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1176        )
1177        .with_now(fixed_now);
1178
1179        let token = client.bearer().await.expect("the refresh must succeed");
1180        assert_eq!(token.as_deref(), Some("newest-at"));
1181
1182        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1183        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1184        assert!(
1185            refresh.contains("refresh_token=rotated-rt"),
1186            "the refresh must use the adopted on-disk token: {refresh}"
1187        );
1188        assert!(
1189            !refresh.contains("refresh_token=old-rt"),
1190            "the superseded in-memory token must NOT be presented: {refresh}"
1191        );
1192    }
1193
1194    /// On an IdP that does NOT rotate refresh tokens — RFC 6749 permits omitting
1195    /// `refresh_token` on a refresh, and `KeycloakSession::apply` keeps the
1196    /// previous one — every session on disk and in memory carries the SAME
1197    /// refresh token. A refresh-token comparison therefore never fires, so
1198    /// `tracevault status` (three clients from one credential) performed three
1199    /// redundant refreshes, silently. The on-disk access token outliving ours is
1200    /// the signal that actually works there.
1201    ///
1202    /// The issuer points at a dead port, so any refresh attempt would fail the
1203    /// call: reaching the assertion proves the adopt happened instead.
1204    #[tokio::test]
1205    async fn bearer_adopts_a_fresher_session_from_a_non_rotating_idp() {
1206        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1207        let dir = tempfile::tempdir().unwrap();
1208        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1209        _guard.set("XDG_CONFIG_HOME", dir.path());
1210
1211        // On disk: another client refreshed and got a new access token, but the
1212        // SAME refresh token back (no rotation).
1213        let creds_dir = dir.path().join("tracevault");
1214        std::fs::create_dir_all(&creds_dir).unwrap();
1215        std::fs::write(
1216            creds_dir.join("credentials.json"),
1217            format!(
1218                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":{}}}}}"#,
1219                NOW + 3600
1220            ),
1221        )
1222        .unwrap();
1223
1224        // In memory: the same refresh token, an access token about to expire.
1225        let client = ApiClient::with_credential(
1226            "https://example.com",
1227            Some(Credential::Keycloak(session(
1228                "http://127.0.0.1:1",
1229                NOW + 10,
1230            ))),
1231        )
1232        .with_now(fixed_now);
1233
1234        let token = client
1235            .bearer()
1236            .await
1237            .expect("a fresher on-disk session must be adopted, not re-refreshed");
1238        assert_eq!(token.as_deref(), Some("refreshed-by-someone-else"));
1239    }
1240
1241    /// Outside the window the stored token is used as-is. The issuer points
1242    /// at a port nothing listens on, so ANY refresh attempt would fail the
1243    /// call — proving no network round trip happened.
1244    #[tokio::test]
1245    async fn bearer_does_not_refresh_outside_the_window() {
1246        let client = ApiClient::with_credential(
1247            "https://example.com",
1248            Some(Credential::Keycloak(session(
1249                "http://127.0.0.1:1",
1250                NOW + 3600,
1251            ))),
1252        )
1253        .with_now(fixed_now);
1254
1255        let token = client
1256            .bearer()
1257            .await
1258            .expect("a still-valid token must not trigger any IdP call");
1259        assert_eq!(token.as_deref(), Some("old-at"));
1260    }
1261
1262    /// The API-key path is a pure passthrough: no clock, no IdP, no refresh.
1263    #[tokio::test]
1264    async fn bearer_returns_an_api_key_verbatim() {
1265        let client = ApiClient::new("https://example.com", Some("tvk_abc"));
1266        assert_eq!(client.bearer().await.unwrap().as_deref(), Some("tvk_abc"));
1267
1268        let anonymous = ApiClient::new("https://example.com", None);
1269        assert_eq!(anonymous.bearer().await.unwrap(), None);
1270    }
1271
1272    /// A 401 on an API key is a real rejection: retrying would double every
1273    /// failure and could re-run a non-idempotent write. Exactly ONE request
1274    /// must reach the server.
1275    #[tokio::test]
1276    async fn a_401_with_an_api_key_does_not_refresh_or_retry() {
1277        let (base, rx) = spawn_seq(vec![
1278            http_json("401 Unauthorized", r#"{"error":"invalid token"}"#),
1279            // A second response is queued precisely to prove it is unused.
1280            http_json("200 OK", "[]"),
1281        ]);
1282        let client = ApiClient::new(&base, Some("tvk_abc"));
1283        client
1284            .list_repos()
1285            .await
1286            .expect_err("a 401 must surface as an error");
1287
1288        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
1289        assert!(first.contains("GET /api/v1/repos"), "{first}");
1290        assert!(
1291            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1292            "an API key must never be retried after a 401"
1293        );
1294    }
1295
1296    /// A Keycloak credential that gets an unexpected 401 (server-side session
1297    /// invalidation, clock skew) force-refreshes and retries ONCE.
1298    #[tokio::test]
1299    async fn a_401_with_a_keycloak_credential_refreshes_and_retries_once() {
1300        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1301        let dir = tempfile::tempdir().unwrap();
1302        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1303        _guard.set("XDG_CONFIG_HOME", dir.path());
1304
1305        let (issuer, _idp_rx) =
1306            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1307        let (base, rx) = spawn_seq(vec![
1308            http_json("401 Unauthorized", r#"{"error":"expired"}"#),
1309            http_json("200 OK", "[]"),
1310        ]);
1311        // The file is for THIS client's server, so the refreshed session is
1312        // persisted rather than skipped by the same-server guard.
1313        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
1314
1315        // Far from expiry: the proactive window must NOT be what triggers the
1316        // refresh here — the 401 must.
1317        let client = ApiClient::with_credential(
1318            &base,
1319            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
1320        )
1321        .with_now(fixed_now);
1322
1323        let repos = client
1324            .list_repos()
1325            .await
1326            .expect("the retry after a forced refresh must succeed");
1327        assert!(repos.is_empty());
1328
1329        // The point of the retry is that it presents the REFRESHED token; a
1330        // retry that re-sent the rejected one would be pointless and would
1331        // still 401 in production.
1332        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no first request");
1333        assert!(first.contains("GET /api/v1/repos"), "{first}");
1334        assert!(
1335            first.contains("Bearer old-at"),
1336            "the first attempt must carry the stored token: {first}"
1337        );
1338        let second = rx.recv_timeout(RECV_TIMEOUT).expect("no retry request");
1339        assert!(second.contains("GET /api/v1/repos"), "{second}");
1340        assert!(
1341            second.contains("Bearer fresh-at"),
1342            "the retry must carry the REFRESHED token, not the rejected one: {second}"
1343        );
1344        assert!(
1345            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1346            "the retry must happen at most once, or a 401-always server would loop"
1347        );
1348    }
1349
1350    /// A 401 that survives the retry must not send the request a third time:
1351    /// a server answering 401 unconditionally has to terminate.
1352    #[tokio::test]
1353    async fn a_persistent_401_stops_after_one_retry() {
1354        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1355        let dir = tempfile::tempdir().unwrap();
1356        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1357        _guard.set("XDG_CONFIG_HOME", dir.path());
1358
1359        let (issuer, _idp_rx) =
1360            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1361        let (base, rx) = spawn_seq(vec![
1362            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
1363            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
1364            http_json("200 OK", "[]"),
1365        ]);
1366        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
1367        let client = ApiClient::with_credential(
1368            &base,
1369            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
1370        )
1371        .with_now(fixed_now);
1372
1373        client
1374            .list_repos()
1375            .await
1376            .expect_err("a persistent 401 must surface as an error");
1377
1378        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
1379        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
1380        assert!(
1381            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1382            "a third attempt means the retry can loop"
1383        );
1384    }
1385
1386    /// A dead refresh token must surface as "log in again", not as a bland
1387    /// 401 or a network error — `tracevault status` renders those differently.
1388    #[tokio::test]
1389    async fn get_me_maps_a_dead_refresh_token_to_unauthorized() {
1390        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1391        let dir = tempfile::tempdir().unwrap();
1392        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1393        _guard.set("XDG_CONFIG_HOME", dir.path());
1394
1395        let (issuer, _rx) = spawn_seq_with(|base| {
1396            vec![
1397                http_json(
1398                    "200 OK",
1399                    &format!(r#"{{"issuer":"{base}","token_endpoint":"{base}/token"}}"#),
1400                ),
1401                http_json("400 Bad Request", r#"{"error":"invalid_grant"}"#),
1402            ]
1403        });
1404        write_keycloak_file(dir.path(), "http://127.0.0.1:1", &issuer, NOW + 10);
1405
1406        let client = ApiClient::with_credential(
1407            "http://127.0.0.1:1",
1408            // Inside the window, so the (failing) refresh happens before any
1409            // request to the server is attempted.
1410            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1411        )
1412        .with_now(fixed_now);
1413
1414        match client.get_me().await {
1415            Err(GetMeError::Unauthorized) => {}
1416            other => panic!("expected Unauthorized for a dead session, got {other:?}"),
1417        }
1418    }
1419
1420    /// An unreachable IdP is NOT a dead session: it must stay distinguishable
1421    /// so status says "cannot confirm" rather than "you were logged out".
1422    #[tokio::test]
1423    async fn get_me_maps_an_unreachable_idp_to_network() {
1424        // The session is inside the refresh window, so `refresh_locked` calls
1425        // `Credentials::load()`. Without this redirect that reads the
1426        // DEVELOPER's real `~/.config/tracevault/credentials.json` — which on a
1427        // machine logged in with Keycloak means reading a live token, and makes
1428        // the test's outcome depend on the developer's own login state.
1429        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1430        let dir = tempfile::tempdir().unwrap();
1431        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1432        _guard.set("XDG_CONFIG_HOME", dir.path());
1433
1434        let client = ApiClient::with_credential(
1435            "http://127.0.0.1:1",
1436            Some(Credential::Keycloak(session(
1437                "http://127.0.0.1:1",
1438                NOW + 10,
1439            ))),
1440        )
1441        .with_now(fixed_now);
1442
1443        match client.get_me().await {
1444            Err(GetMeError::Network(_)) => {}
1445            other => panic!("expected Network for an unreachable IdP, got {other:?}"),
1446        }
1447    }
1448
1449    /// A 403 is its own outcome: the token is fine, the account isn't
1450    /// authorized, and "log in again" would be the wrong advice.
1451    #[tokio::test]
1452    async fn get_me_maps_403_to_forbidden() {
1453        let (base, _rx) = spawn_seq(vec![http_json(
1454            "403 Forbidden",
1455            r#"{"error":"missing role"}"#,
1456        )]);
1457        let client = ApiClient::new(&base, Some("tvk_abc"));
1458        match client.get_me().await {
1459            Err(GetMeError::Forbidden(_)) => {}
1460            other => panic!("expected Forbidden, got {other:?}"),
1461        }
1462    }
1463
1464    /// `resolve_client` is the funnel the project/repo commands use, so the
1465    /// guard has to hold through the wrapper too — not only in
1466    /// `resolve_credentials`, whose own tests now live beside it in
1467    /// `credentials.rs`.
1468    #[test]
1469    fn resolve_client_also_refuses_a_mismatched_server_url() {
1470        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1471        let dir = tempfile::tempdir().unwrap();
1472        let mut guard = crate::test_helpers::EnvVarGuard::new();
1473        guard.set("XDG_CONFIG_HOME", dir.path());
1474        guard.remove("TRACEVAULT_API_KEY");
1475        guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
1476        write_keycloak_file(
1477            dir.path(),
1478            "https://instance-b.example.com",
1479            "https://idp.test/realms/v",
1480            NOW + 3600,
1481        );
1482
1483        // `ApiClient` deliberately has no `Debug` (it holds a credential), so
1484        // match instead of `expect_err`.
1485        let err = match resolve_client(dir.path()) {
1486            Err(e) => e,
1487            Ok(_) => panic!("resolve_client must apply the guard"),
1488        };
1489        assert!(err.to_string().contains("instance-b.example.com"));
1490    }
1491}