Skip to main content

tracevault_cli/
api_client.rs

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