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    /// The bearer token for a caller that hands it to someone else to use
383    /// for a while (`tracevault otel-headers`: Claude Code reuses the header
384    /// until it runs the helper again). A Keycloak access token with less than
385    /// `min_valid_secs` left is refreshed first, so it does not expire between
386    /// two runs. An API key is returned as is.
387    pub async fn bearer_valid_for(&self, min_valid_secs: i64) -> Result<Option<String>, AuthError> {
388        match &self.credential {
389            Some(ClientCredential::Keycloak(session)) => {
390                let mut guard = session.lock().await;
391                let too_short = |s: &KeycloakSession| {
392                    s.access_expires_at.saturating_sub((self.now)()) < min_valid_secs
393                };
394                // `refresh_locked` may only adopt another process's session,
395                // which can still be too short for us; then the adopted (now
396                // current) session is refreshed for real. Two rounds at most,
397                // so a token lifetime below the minimum cannot loop.
398                for _ in 0..2 {
399                    if !too_short(&guard) {
400                        break;
401                    }
402                    self.refresh_locked(&mut guard).await?;
403                }
404                // Still too short after a real refresh: the IdP issues tokens
405                // that live less than the minimum. The token is still handed
406                // out — it authenticates for most of the interval, where an
407                // error would authenticate nothing — but the caller is told.
408                if too_short(&guard) {
409                    eprintln!(
410                        "Warning: the access token is valid for less than {min_valid_secs}s even \
411                         after a refresh; requests made with it later may be rejected"
412                    );
413                }
414                Ok(Some(guard.access_token.clone()))
415            }
416            _ => self.bearer().await,
417        }
418    }
419
420    /// Refresh the held session in place and persist it. Caller holds the
421    /// session lock, which is what makes "one refresh at a time" true.
422    ///
423    /// # Residual cross-process race, and why it is currently benign
424    ///
425    /// The on-disk adopt below closes the SEQUENTIAL case (something already
426    /// finished refreshing before we started) but only NARROWS the concurrent
427    /// one: two hooks spawned at the same instant can both read the same
428    /// session before either writes, and the window is this function's
429    /// discovery GET plus its token POST. Both would then present the same
430    /// refresh token.
431    ///
432    /// That is harmless ONLY because the realm keeps Keycloak's
433    /// `revokeRefreshToken` at its default (off): a re-presented refresh token
434    /// stays valid, so the worst outcome is one wasted round trip and a
435    /// last-writer-wins access token, both invisible to the user. If that
436    /// realm setting is ever enabled, the second presenter gets
437    /// `invalid_grant` — surfacing as a spurious "your session has expired" —
438    /// and this code then needs a real inter-process file lock around
439    /// read-refresh-write, not just the adopt.
440    ///
441    /// # Both directions are scoped to this client's server
442    ///
443    /// There is exactly ONE credentials file, but a machine can be pointed at
444    /// more than one TraceVault instance. So the adopt only reads, and
445    /// `persist_session` only writes, when that file's `server_url` is this
446    /// client's `base_url` (see [`crate::credentials::same_server`]).
447    /// Unscoped, a long-running `tracevault stream` against instance A plus a
448    /// `tracevault login` to instance B in another terminal would make A adopt
449    /// B's session and send B's access token to A — disclosing a token to a
450    /// host it was never minted for — and A's next refresh would then overwrite
451    /// B's credentials, signing the user out of B.
452    async fn refresh_locked(&self, session: &mut KeycloakSession) -> Result<(), AuthError> {
453        let now = (self.now)();
454
455        // Someone else may have refreshed already: another process (two git
456        // hooks firing at once), or another `ApiClient` in this process that
457        // was built from the same on-disk credential before either refreshed.
458        //
459        // Adopt when EITHER holds, because they catch different IdPs:
460        //
461        // * the on-disk access token outlives ours — the on-disk session is
462        //   genuinely newer. This is the only signal available on an IdP that
463        //   does NOT rotate refresh tokens (RFC 6749 permits omitting
464        //   `refresh_token` on a refresh, which `KeycloakSession::apply`
465        //   handles), where the refresh token is identical everywhere and a
466        //   token-comparison alone would never fire — leaving `tracevault
467        //   status`, which builds three clients from one credential, doing three
468        //   redundant refreshes.
469        // * the on-disk refresh token differs from ours — ours has been
470        //   superseded, and on a ROTATING IdP already consumed. This must adopt
471        //   even when the adopted session is itself older and still needs a
472        //   refresh (then falling through to refresh with the ADOPTED token),
473        //   because refreshing with a consumed token is a guaranteed
474        //   `invalid_grant`.
475        //
476        // Deliberately NOT "the access tokens differ": that would also adopt a
477        // strictly older session.
478        //
479        // There is deliberately no test asserting "never adopt an older
480        // session", because that property is unreachable where it would be
481        // desirable and undesirable where it is reachable. Through `bearer` it
482        // cannot be observed: this function is only entered when OURS is inside
483        // the refresh window, so an older disk session is inside it too and
484        // control falls through to a real refresh either way. Through
485        // `force_refresh` it IS reachable — and there, adopting a different
486        // token is exactly what we want, since the one we hold was just
487        // rejected. A test naming the downgrade would therefore have to be
488        // vacuous to pass; the predicate's existence is instead covered by the
489        // 401 retry tests, which fail if it always adopts.
490        //
491        // ... and only from a file that is still this server's (see above).
492        if let Some(disk) = Credentials::load()
493            .filter(|c| crate::credentials::same_server(&c.server_url, &self.base_url))
494            .and_then(|c| c.auth)
495        {
496            let disk_is_newer = disk.access_expires_at > session.access_expires_at;
497            let ours_superseded = disk.refresh_token != session.refresh_token;
498            if disk_is_newer || ours_superseded {
499                let disk_needs_refresh = disk.needs_refresh(now);
500                *session = disk;
501                if !disk_needs_refresh {
502                    return Ok(());
503                }
504            }
505        }
506
507        // Discovery is re-fetched per refresh rather than cached: a refresh
508        // happens at most once per access-token lifetime (minutes), and
509        // caching it would mean a rotated realm endpoint needs a re-login.
510        let discovery = crate::oidc::discover(&self.client, &session.issuer)
511            .await
512            .map_err(auth_error)?;
513        let tokens = crate::oidc::refresh(
514            &self.client,
515            &discovery,
516            &session.client_id,
517            &session.refresh_token,
518        )
519        .await
520        .map_err(auth_error)?;
521        session.apply(&tokens, now);
522
523        // Best-effort, and scoped to this server (see the doc comment): a token
524        // that can't be written to disk still works for THIS process, so
525        // failing the request would be worse than a warning. The message
526        // deliberately contains no token material.
527        if let Err(e) = Credentials::persist_session(&self.base_url, session) {
528            eprintln!("Warning: could not save refreshed credentials: {e}");
529        }
530        Ok(())
531    }
532
533    /// Force one refresh after an unexpected 401 and return the new token.
534    ///
535    /// `Ok(None)` means "not refreshable" (API key or no credential), which
536    /// is the signal not to retry. `stale` is the token that just got
537    /// rejected: if another task already refreshed while we waited for the
538    /// lock, the current token is already different and is reused instead of
539    /// refreshing a second time.
540    async fn force_refresh(&self, stale: Option<&str>) -> Result<Option<String>, AuthError> {
541        let Some(ClientCredential::Keycloak(session)) = &self.credential else {
542            return Ok(None);
543        };
544        let mut guard = session.lock().await;
545        if Some(guard.access_token.as_str()) != stale {
546            return Ok(Some(guard.access_token.clone()));
547        }
548        self.refresh_locked(&mut guard).await?;
549        Ok(Some(guard.access_token.clone()))
550    }
551
552    pub async fn register_repo(
553        &self,
554        req: RegisterRepoRequest,
555    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
556        let builder = self
557            .client
558            .post(format!("{}/api/v1/repos", self.base_url))
559            .json(&req);
560        self.authed_send_json(builder, |status| format!("Server returned {status}"))
561            .await
562    }
563
564    /// Attach a bearer token (if there is one) to a request. Shared by every
565    /// authenticated request builder so header attachment has exactly one
566    /// implementation.
567    fn attach_auth(
568        builder: reqwest::RequestBuilder,
569        token: Option<&str>,
570    ) -> reqwest::RequestBuilder {
571        match token {
572            Some(t) => builder.header("Authorization", format!("Bearer {t}")),
573            None => builder,
574        }
575    }
576
577    /// Attach the bearer token and send `builder`. The shared first step of
578    /// every authenticated request; callers that need bespoke status-code
579    /// handling (e.g. treating 404/409 as non-error outcomes) use this
580    /// directly instead of `authed_send_json`.
581    ///
582    /// On an unexpected 401 with a refreshable (Keycloak) credential the
583    /// request is retried EXACTLY once against a force-refreshed token —
584    /// covering a server-side session invalidation or a clock skew that the
585    /// proactive expiry window missed. The retry is a bare `send`, not a
586    /// recursive call, so a server that answers 401 unconditionally cannot
587    /// make this loop. An API key never retries: a 401 on a `tvk_` key is a
588    /// real rejection and re-sending it would just double every failure.
589    async fn send_authed(
590        &self,
591        builder: reqwest::RequestBuilder,
592    ) -> Result<reqwest::Response, Box<dyn Error>> {
593        // Cloned BEFORE sending: a builder is consumed by `send`. `None`
594        // means the body isn't replayable, in which case we simply don't
595        // retry.
596        let retry = builder.try_clone();
597        let token = self.bearer().await?;
598        let resp = Self::attach_auth(builder, token.as_deref()).send().await?;
599
600        if resp.status() != reqwest::StatusCode::UNAUTHORIZED {
601            return Ok(resp);
602        }
603        let Some(retry) = retry else {
604            return Ok(resp);
605        };
606        match self.force_refresh(token.as_deref()).await? {
607            Some(fresh) => Ok(Self::attach_auth(retry, Some(&fresh)).send().await?),
608            // Not refreshable — surface the original 401 unchanged.
609            None => Ok(resp),
610        }
611    }
612
613    /// Check that `resp`'s status is a success and deserialize its JSON
614    /// body; otherwise build an error as `"{err_prefix(status)}: {body}"`.
615    /// `err_prefix` receives the status so each caller can format its own
616    /// distinct message (parenthesized status, bare status, ...) — this
617    /// helper only supplies the shared "check status, else deserialize"
618    /// shape, not the message wording.
619    async fn success_json<T, F>(resp: reqwest::Response, err_prefix: F) -> Result<T, Box<dyn Error>>
620    where
621        T: serde::de::DeserializeOwned,
622        F: FnOnce(reqwest::StatusCode) -> String,
623    {
624        let status = resp.status();
625        if !status.is_success() {
626            let body = resp.text().await.unwrap_or_default();
627            return Err(format!("{}: {}", err_prefix(status), body).into());
628        }
629        Ok(resp.json().await?)
630    }
631
632    /// Attach the bearer token, send `builder`, and deserialize a successful
633    /// JSON response — the shared shape of every simple authenticated
634    /// request/response method (`send_authed` + `success_json`).
635    ///
636    /// NOTE: callers whose `err_prefix` renders the status as `"({status})"`
637    /// (e.g. `stream_event`'s `"Stream failed ({status})"`) produce error
638    /// strings containing `"(404 "`/`"(403 "`/etc. —
639    /// `commands::stream::deterministic_client_error_kind` matches on exactly
640    /// that substring shape to classify a stream-send failure, and to tell a 403
641    /// apart from the binding statuses. If you change how a status is rendered
642    /// here, check that function (and its tests) still pass.
643    async fn authed_send_json<T, F>(
644        &self,
645        builder: reqwest::RequestBuilder,
646        err_prefix: F,
647    ) -> Result<T, Box<dyn Error>>
648    where
649        T: serde::de::DeserializeOwned,
650        F: FnOnce(reqwest::StatusCode) -> String,
651    {
652        let resp = self.send_authed(builder).await?;
653        Self::success_json(resp, err_prefix).await
654    }
655
656    /// GET `{base}{path}` with the bearer token, mapping failures into
657    /// `GetMeError` (401 → `Unauthorized`, 403 → `Forbidden`, transport →
658    /// `Network`, other non-2xx or bad JSON → `Server`). Shared by the
659    /// credential-scoped GETs so auth/error handling lives in one place.
660    ///
661    /// Goes through `send_authed`, so a Keycloak access token is refreshed
662    /// before the call (and once after a 401) exactly like every other
663    /// request. A refresh failure is mapped by cause: a dead session is
664    /// `Unauthorized` ("log in again"), an unreachable IdP is `Network`
665    /// ("cannot confirm") — `tracevault status` renders those very
666    /// differently, so collapsing them would misreport a network blip as a
667    /// revoked login.
668    async fn authed_get_json<T: serde::de::DeserializeOwned>(
669        &self,
670        path: &str,
671    ) -> Result<T, GetMeError> {
672        let builder = self.client.get(format!("{}{}", self.base_url, path));
673        let resp = self.send_authed(builder).await.map_err(get_me_send_error)?;
674
675        let status = resp.status();
676        if status == reqwest::StatusCode::UNAUTHORIZED {
677            return Err(GetMeError::Unauthorized);
678        }
679        if status == reqwest::StatusCode::FORBIDDEN {
680            let body = resp.text().await.unwrap_or_default();
681            return Err(GetMeError::Forbidden(body));
682        }
683        if !status.is_success() {
684            let body = resp.text().await.unwrap_or_default();
685            return Err(GetMeError::Server(format!("{status}: {body}")));
686        }
687
688        resp.json::<T>()
689            .await
690            .map_err(|e| GetMeError::Server(e.to_string()))
691    }
692
693    /// GET /api/v1/auth/me — validates the bearer token and returns user
694    /// identity. Used by `tracevault status` to distinguish "logged out",
695    /// "expired token", and "server unreachable".
696    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
697        self.authed_get_json("/api/v1/auth/me").await
698    }
699
700    pub async fn list_repos(&self) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
701        let builder = self.client.get(format!("{}/api/v1/repos", self.base_url));
702        self.authed_send_json(builder, |status| format!("Failed to list repos ({status})"))
703            .await
704    }
705
706    pub async fn get_agent_instructions(
707        &self,
708        repo_id: &uuid::Uuid,
709    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
710        let builder = self.client.get(format!(
711            "{}/api/v1/repos/{}/policies/agent-instructions",
712            self.base_url, repo_id
713        ));
714        self.authed_send_json(builder, |status| {
715            format!("Failed to fetch agent instructions ({status})")
716        })
717        .await
718    }
719
720    pub async fn verify_commits(
721        &self,
722        repo_id: &uuid::Uuid,
723        req: CiVerifyRequest,
724    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
725        let builder = self
726            .client
727            .post(format!(
728                "{}/api/v1/repos/{}/ci/verify",
729                self.base_url, repo_id
730            ))
731            .json(&req);
732        self.authed_send_json(builder, |status| format!("CI verify failed ({status})"))
733            .await
734    }
735
736    pub async fn push_commit(
737        &self,
738        repo_id: &str,
739        req: &tracevault_protocol::streaming::CommitPushRequest,
740    ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
741        let builder = self
742            .client
743            .post(format!(
744                "{}/api/v1/repos/{}/commits",
745                self.base_url, repo_id
746            ))
747            .json(req);
748        self.authed_send_json(builder, |status| format!("Commit push failed ({status})"))
749            .await
750    }
751
752    pub async fn stream_event(
753        &self,
754        repo_id: &str,
755        req: &tracevault_protocol::streaming::StreamEventRequest,
756    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
757        let builder = self
758            .client
759            .post(format!("{}/api/v1/repos/{}/stream", self.base_url, repo_id))
760            .json(req);
761        self.authed_send_json(builder, |status| format!("Stream failed ({status})"))
762            .await
763    }
764
765    /// Project-scoped variant of `stream_event`: posts to the project's
766    /// stream endpoint with the project in the path and `repo_id` — when
767    /// there is one — as a query param rather than a path segment. The query
768    /// is built with `Url::query_pairs_mut`, mirroring `resolve_project`'s
769    /// `?git_url=`, so `repo_id` is percent-encoded rather than
770    /// string-interpolated into the URL.
771    ///
772    /// `repo_id` is `None` for a repo-less session, and the pair is then
773    /// omitted entirely: the server declares it optional
774    /// (`ProjectStreamQuery::repo_id: Option<Uuid>`) and would reject an
775    /// empty value as a malformed UUID.
776    ///
777    /// Called from `commands::stream::send_stream_event` for both the
778    /// `Attribution::Repo { project: Some(_) }` and `Attribution::ProjectOnly`
779    /// routes.
780    ///
781    /// `mode` is the attribution this send declares — decided by
782    /// `commands::stream::attribution_mode` and rendered into the
783    /// `x-tracevault-project-attribution` header by
784    /// [`AttributionMode::as_header_value`], which is the only place it
785    /// becomes a string.
786    ///
787    /// It is an [`AttributionMode`], not a `&str`, because the server
788    /// accepts exactly two values and rejects everything else with a `400`
789    /// — see that type's doc comment. (An older SERVER simply does not read
790    /// the header, which is the one direction that does degrade quietly, to
791    /// derived attribution.)
792    pub async fn stream_event_for_project(
793        &self,
794        project_id: uuid::Uuid,
795        repo_id: Option<&str>,
796        mode: AttributionMode,
797        req: &tracevault_protocol::streaming::StreamEventRequest,
798    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
799        let mut url = Url::parse(&format!(
800            "{}/api/v1/projects/{}/stream",
801            self.base_url, project_id
802        ))?;
803        // `repo_id` is OPTIONAL server-side (`ProjectStreamQuery::repo_id:
804        // Option<Uuid>` — "repo-less (0-repo) projects are supported"), so a
805        // repo-less session must omit the pair entirely. Appending an empty
806        // value instead would be parsed as a malformed UUID and 400.
807        if let Some(repo_id) = repo_id {
808            url.query_pairs_mut().append_pair("repo_id", repo_id);
809        }
810        let builder = self
811            .client
812            .post(url)
813            .header("x-tracevault-project-attribution", mode.as_header_value())
814            .json(req);
815        self.authed_send_json(builder, |status| {
816            format!("Project stream failed ({status})")
817        })
818        .await
819    }
820
821    pub async fn check_policies(
822        &self,
823        repo_id: &uuid::Uuid,
824        req: CheckPoliciesRequest,
825    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
826        let builder = self
827            .client
828            .post(format!(
829                "{}/api/v1/repos/{}/policies/check",
830                self.base_url, repo_id
831            ))
832            .json(&req);
833        self.authed_send_json(builder, |status| format!("Policy check failed ({status})"))
834            .await
835    }
836
837    /// Resolve a git URL to its codebase (git remote) by NORMALIZED URL —
838    /// deduped, unlike an exact `github_url` match. `Ok(None)` if the
839    /// codebase isn't tracked: a genuine domain 404, identified by the
840    /// server's JSON error envelope (see [`is_domain_error_body`]). A bare
841    /// 404 with no such body — axum's built-in "no route matched" fallback
842    /// — is surfaced as `Err` instead, since it means this server doesn't
843    /// have this route at all (most plausibly a CLI/server version skew,
844    /// e.g. this CLI shipped ahead of a server that still uses the old
845    /// org-scoped paths) rather than an absent codebase.
846    pub async fn resolve_remote(
847        &self,
848        git_url: &str,
849    ) -> Result<Option<ResolveRemoteResponse>, Box<dyn std::error::Error>> {
850        let mut url = Url::parse(&format!("{}/api/v1/remotes/resolve", self.base_url))?;
851        url.query_pairs_mut().append_pair("git_url", git_url);
852        let resp = self.send_authed(self.client.get(url)).await?;
853        if resp.status() == reqwest::StatusCode::NOT_FOUND {
854            let body = resp.text().await.unwrap_or_default();
855            return if is_domain_error_body(&body) {
856                Ok(None)
857            } else {
858                Err(version_skew_404_error("resolve_remote"))
859            };
860        }
861        let parsed: ResolveRemoteResponse =
862            Self::success_json(resp, |status| format!("resolve_remote failed ({status})")).await?;
863        Ok(Some(parsed))
864    }
865
866    /// Full detail for a remote (codebase): its display name, normalized URL,
867    /// clone status, and linked repos.
868    pub async fn get_remote_detail(
869        &self,
870        remote_id: uuid::Uuid,
871    ) -> Result<RemoteDetail, Box<dyn std::error::Error>> {
872        let builder = self
873            .client
874            .get(format!("{}/api/v1/remotes/{}", self.base_url, remote_id));
875        self.authed_send_json(builder, |status| {
876            format!("get_remote_detail failed ({status})")
877        })
878        .await
879    }
880
881    /// The repos linked to a remote (the codebase's members).
882    pub async fn get_remote_repos(
883        &self,
884        remote_id: uuid::Uuid,
885    ) -> Result<Vec<RemoteRepoRef>, Box<dyn std::error::Error>> {
886        Ok(self.get_remote_detail(remote_id).await?.repos)
887    }
888
889    /// List all projects. `GET /api/v1/projects`.
890    pub async fn list_projects(&self) -> Result<Vec<ProjectListItem>, Box<dyn Error>> {
891        let builder = self
892            .client
893            .get(format!("{}/api/v1/projects", self.base_url));
894        self.authed_send_json(builder, |status| {
895            format!("Failed to list projects ({status})")
896        })
897        .await
898    }
899
900    /// Full detail for a project. `GET /api/v1/projects/{id}`.
901    pub async fn get_project(&self, id: uuid::Uuid) -> Result<ProjectDetail, Box<dyn Error>> {
902        let builder = self
903            .client
904            .get(format!("{}/api/v1/projects/{}", self.base_url, id));
905        self.authed_send_json(builder, |status| {
906            format!("Failed to get project ({status})")
907        })
908        .await
909    }
910
911    /// Resolve a git URL to its project, distinguishing "no project" (a
912    /// genuine domain 404 — see [`is_domain_error_body`]) from "ambiguous,
913    /// multiple candidate projects" (409). A bare 404 with no domain-error
914    /// body is surfaced as `Err` instead of `None` (see `resolve_remote`'s
915    /// doc comment for why). `GET /api/v1/projects/resolve?git_url=`.
916    pub async fn resolve_project(
917        &self,
918        git_url: &str,
919    ) -> Result<ResolveProjectOutcome, Box<dyn std::error::Error>> {
920        let mut url = Url::parse(&format!("{}/api/v1/projects/resolve", self.base_url))?;
921        url.query_pairs_mut().append_pair("git_url", git_url);
922        let resp = self.send_authed(self.client.get(url)).await?;
923        let status = resp.status();
924        if status == reqwest::StatusCode::NOT_FOUND {
925            let body = resp.text().await.unwrap_or_default();
926            return if is_domain_error_body(&body) {
927                Ok(ResolveProjectOutcome::None)
928            } else {
929                Err(version_skew_404_error("resolve_project"))
930            };
931        }
932        if status == reqwest::StatusCode::CONFLICT {
933            return Ok(ResolveProjectOutcome::Ambiguous);
934        }
935        let parsed: ResolveProjectResponse =
936            Self::success_json(resp, |status| format!("resolve_project failed ({status})")).await?;
937        Ok(ResolveProjectOutcome::Resolved(parsed.project_id))
938    }
939}
940
941/// Map an OIDC failure onto [`AuthError`], keeping "the session is dead"
942/// distinct from "the refresh attempt itself failed".
943fn auth_error(e: crate::oidc::OidcError) -> AuthError {
944    match e {
945        crate::oidc::OidcError::SessionExpired => AuthError::SessionExpired,
946        other => AuthError::Refresh(other.to_string()),
947    }
948}
949
950/// Classify a `send_authed` failure for the `GetMeError`-returning callers.
951/// A dead session becomes `Unauthorized`; everything else (transport, IdP
952/// unreachable) becomes `Network`, which callers render as "cannot confirm".
953fn get_me_send_error(e: Box<dyn Error>) -> GetMeError {
954    match e.downcast::<AuthError>() {
955        Ok(auth) => match *auth {
956            AuthError::SessionExpired => GetMeError::Unauthorized,
957            AuthError::Refresh(m) => GetMeError::Network(m),
958        },
959        Err(other) => GetMeError::Network(other.to_string()),
960    }
961}
962
963/// Whether a 404 response body matches the server's JSON error envelope —
964/// `{"error": "...", ...}`, emitted by every domain-level `AppError` (see
965/// `tracevault-server`'s `error.rs`) — rather than the empty/plain body
966/// axum's built-in "no route matched" fallback sends when the server has no
967/// handler for the path at all. Used by `resolve_remote`/`resolve_project`
968/// to tell a genuine "not tracked"/"no project" 404 apart from a 404 that
969/// really means "this server doesn't have this route" (most plausibly a
970/// CLI/server version skew).
971fn is_domain_error_body(body: &str) -> bool {
972    serde_json::from_str::<serde_json::Value>(body)
973        .ok()
974        .and_then(|v| v.get("error").map(|_| ()))
975        .is_some()
976}
977
978/// The error for a 404 whose body doesn't match the server's JSON error
979/// envelope (see [`is_domain_error_body`]) — surfaced instead of silently
980/// treating the call as "not tracked"/"no project", since this shape is the
981/// CLI's best signal that the server doesn't recognize `what`'s route at
982/// all, rather than a genuine absence of the resource.
983fn version_skew_404_error(what: &str) -> Box<dyn std::error::Error> {
984    format!(
985        "{what} got a 404 with no recognizable error body — this endpoint may not exist on \
986         this server yet. This usually means the CLI is newer than the server (a CLI/server \
987         version mismatch); confirm the server has been upgraded and retry."
988    )
989    .into()
990}
991
992/// Resolve `project_root`'s credentials (via `resolve_credentials`) into a
993/// ready `ApiClient`, or the standard "no server URL configured" error when
994/// none of the credential sources yield a server URL. Shared by every
995/// command that needs a client from a project root, so this
996/// resolve-then-construct shape has exactly one implementation.
997pub fn resolve_client(project_root: &Path) -> Result<ApiClient, Box<dyn Error>> {
998    let (server_url, credential) = resolve_credentials(project_root)?;
999    let server_url = server_url
1000        .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
1001    Ok(ApiClient::with_credential(&server_url, credential))
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use super::*;
1007    use crate::credentials::KeycloakSession;
1008    use crate::test_helpers::{http_json, spawn_seq, spawn_seq_with, RECV_TIMEOUT};
1009    use std::time::Duration;
1010
1011    /// Fixed "now" for the refresh-window tests. Using a constant instead of
1012    /// the wall clock is what makes the boundary assertions deterministic.
1013    const NOW: i64 = 1_800_000_000;
1014
1015    fn fixed_now() -> i64 {
1016        NOW
1017    }
1018
1019    /// A fake IdP that answers discovery (self-reporting its own URL as the
1020    /// issuer, as a real one must) and then one token request. Returns the
1021    /// issuer URL to put in the session.
1022    fn spawn_idp(token_response: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1023        spawn_seq_with(move |base| {
1024            vec![
1025                http_json(
1026                    "200 OK",
1027                    &format!(
1028                        r#"{{"issuer":"{base}","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device","revocation_endpoint":"{base}/revoke"}}"#
1029                    ),
1030                ),
1031                http_json("200 OK", token_response),
1032            ]
1033        })
1034    }
1035
1036    /// Write a Keycloak credentials file for `server_url`/`issuer` into
1037    /// `dir`, so a refresh has something to adopt from and persist into.
1038    ///
1039    /// `server_url` is explicit because the adopt and the persist are both
1040    /// scoped to the client's `base_url`: a helper that hardcoded it would
1041    /// silently disable persistence in tests whose client points elsewhere.
1042    fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
1043        let creds_dir = dir.join("tracevault");
1044        std::fs::create_dir_all(&creds_dir).unwrap();
1045        std::fs::write(
1046            creds_dir.join("credentials.json"),
1047            format!(
1048                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}}}}}"#
1049            ),
1050        )
1051        .unwrap();
1052    }
1053
1054    fn session(issuer: &str, expires_at: i64) -> KeycloakSession {
1055        KeycloakSession {
1056            issuer: issuer.to_string(),
1057            client_id: "tracing-cli".into(),
1058            refresh_token: "old-rt".into(),
1059            access_token: "old-at".into(),
1060            access_expires_at: expires_at,
1061        }
1062    }
1063
1064    /// An access token inside the 60s window is refreshed BEFORE the request
1065    /// goes out, and the new tokens are written back to disk so the next
1066    /// process doesn't repeat the refresh.
1067    #[tokio::test]
1068    async fn bearer_refreshes_inside_the_sixty_second_window() {
1069        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1070        let dir = tempfile::tempdir().unwrap();
1071        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1072        _guard.set("XDG_CONFIG_HOME", dir.path());
1073
1074        let (issuer, rx) =
1075            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1076        // 30s of life left — inside the window.
1077        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 30);
1078
1079        let client = ApiClient::with_credential(
1080            "https://example.com",
1081            Some(Credential::Keycloak(session(&issuer, NOW + 30))),
1082        )
1083        .with_now(fixed_now);
1084
1085        let token = client.bearer().await.unwrap();
1086        assert_eq!(token.as_deref(), Some("fresh-at"));
1087
1088        // Discovery, then the refresh_token grant.
1089        let disc = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1090        assert!(disc.contains("/.well-known/openid-configuration"), "{disc}");
1091        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1092        assert!(refresh.contains("grant_type=refresh_token"), "{refresh}");
1093        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
1094        assert!(
1095            !refresh.contains("client_secret"),
1096            "the CLI client is public; no secret may be sent: {refresh}"
1097        );
1098
1099        // Persisted, so a git hook running a second later doesn't refresh again.
1100        let saved = Credentials::load().expect("credentials must still exist");
1101        let auth = saved.auth.expect("auth block must survive a refresh");
1102        assert_eq!(auth.access_token, "fresh-at");
1103        assert_eq!(auth.refresh_token, "fresh-rt");
1104        assert_eq!(auth.access_expires_at, NOW + 300);
1105        assert_eq!(saved.email, "a@b.com", "unrelated fields must be preserved");
1106    }
1107
1108    /// `otel-headers` needs a token that outlives Claude Code's helper
1109    /// interval: one with 120s left is fine for `bearer` (outside its 60s
1110    /// window) but is refreshed for a 240s minimum, and persisted.
1111    #[tokio::test]
1112    async fn bearer_valid_for_refreshes_a_token_expiring_within_the_minimum() {
1113        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1114        let dir = tempfile::tempdir().unwrap();
1115        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1116        _guard.set("XDG_CONFIG_HOME", dir.path());
1117
1118        let (issuer, rx) =
1119            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1120        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 120);
1121        let client = ApiClient::with_credential(
1122            "https://example.com",
1123            Some(Credential::Keycloak(session(&issuer, NOW + 120))),
1124        )
1125        .with_now(fixed_now);
1126
1127        let token = client.bearer_valid_for(240).await.unwrap();
1128        assert_eq!(token.as_deref(), Some("fresh-at"));
1129        rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1130        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1131        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
1132        let saved = Credentials::load().unwrap().auth.unwrap();
1133        assert_eq!(saved.access_token, "fresh-at");
1134    }
1135
1136    /// Another process left a newer session on disk that is still too short
1137    /// for the minimum: it is adopted (its refresh token is the live one) and
1138    /// then refreshed, never handed out as is.
1139    #[tokio::test]
1140    async fn bearer_valid_for_refreshes_an_adopted_session_that_is_still_too_short() {
1141        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1142        let dir = tempfile::tempdir().unwrap();
1143        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1144        _guard.set("XDG_CONFIG_HOME", dir.path());
1145
1146        let (issuer, rx) =
1147            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1148        // On disk: newer (150s) than ours (120s), but under 240s.
1149        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 150);
1150        let mut held = session(&issuer, NOW + 120);
1151        held.access_token = "older-at".into();
1152        let client =
1153            ApiClient::with_credential("https://example.com", Some(Credential::Keycloak(held)))
1154                .with_now(fixed_now);
1155
1156        let token = client.bearer_valid_for(240).await.unwrap();
1157        assert_eq!(token.as_deref(), Some("fresh-at"));
1158        rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1159        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1160        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
1161    }
1162
1163    /// A token valid for longer than the minimum is handed out as is: no IdP
1164    /// call (the issuer here is unreachable, so one would fail the test).
1165    #[tokio::test]
1166    async fn bearer_valid_for_keeps_a_token_valid_long_enough() {
1167        let client = ApiClient::with_credential(
1168            "https://example.com",
1169            Some(Credential::Keycloak(session(
1170                "http://127.0.0.1:9",
1171                NOW + 241,
1172            ))),
1173        )
1174        .with_now(fixed_now);
1175        let token = client.bearer_valid_for(240).await.unwrap();
1176        assert_eq!(token.as_deref(), Some("old-at"));
1177    }
1178
1179    /// A rejected refresh is an error, never the stale token.
1180    #[tokio::test]
1181    async fn bearer_valid_for_fails_when_the_refresh_is_rejected() {
1182        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1183        let dir = tempfile::tempdir().unwrap();
1184        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1185        _guard.set("XDG_CONFIG_HOME", dir.path());
1186
1187        let (issuer, _rx) = spawn_seq_with(|base| {
1188            vec![
1189                http_json(
1190                    "200 OK",
1191                    &format!(
1192                        r#"{{"issuer":"{base}","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device"}}"#
1193                    ),
1194                ),
1195                http_json("400 Bad Request", r#"{"error":"invalid_grant"}"#),
1196            ]
1197        });
1198        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 120);
1199        let client = ApiClient::with_credential(
1200            "https://example.com",
1201            Some(Credential::Keycloak(session(&issuer, NOW + 120))),
1202        )
1203        .with_now(fixed_now);
1204
1205        assert!(client.bearer_valid_for(240).await.is_err());
1206    }
1207
1208    /// Two git hooks can run at once, and `tracevault status` builds two
1209    /// clients from one credential. If another process already refreshed, this
1210    /// one must ADOPT that session rather than present the refresh token that
1211    /// was just consumed — with refresh-token rotation enabled that would come
1212    /// back `invalid_grant` and log the user out for no reason.
1213    ///
1214    /// The issuer points at a dead port, so any actual refresh attempt would
1215    /// fail the call: reaching the assertion proves no round trip happened.
1216    #[tokio::test]
1217    async fn bearer_adopts_a_newer_session_written_by_another_process() {
1218        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1219        let dir = tempfile::tempdir().unwrap();
1220        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1221        _guard.set("XDG_CONFIG_HOME", dir.path());
1222
1223        // On disk: a session refreshed by "another process" — different
1224        // refresh token, plenty of life left.
1225        let creds_dir = dir.path().join("tracevault");
1226        std::fs::create_dir_all(&creds_dir).unwrap();
1227        std::fs::write(
1228            creds_dir.join("credentials.json"),
1229            format!(
1230                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":{}}}}}"#,
1231                NOW + 3600
1232            ),
1233        )
1234        .unwrap();
1235
1236        // In memory: the stale session this client was built from.
1237        let client = ApiClient::with_credential(
1238            "https://example.com",
1239            Some(Credential::Keycloak(session(
1240                "http://127.0.0.1:1",
1241                NOW + 10,
1242            ))),
1243        )
1244        .with_now(fixed_now);
1245
1246        let token = client
1247            .bearer()
1248            .await
1249            .expect("adopting the on-disk session must not require the IdP");
1250        assert_eq!(token.as_deref(), Some("other-process-at"));
1251    }
1252    /// There is one credentials file but a machine can target several
1253    /// TraceVault instances. A file belonging to instance B must NOT be adopted
1254    /// by a client talking to instance A (that would send B's token to A), and
1255    /// A's refreshed session must NOT overwrite B's file (that would sign the
1256    /// user out of B).
1257    ///
1258    /// Covers BOTH directions of the `same_server` comparison at this call site:
1259    /// the mismatch above, and — at the end — that a file differing only by a
1260    /// trailing slash IS still adopted. Without that second half, replacing
1261    /// `same_server` with `==` here goes unnoticed and quietly disables the
1262    /// adopt for every user whose stored URL has a trailing slash.
1263    #[tokio::test]
1264    async fn a_credentials_file_for_another_server_is_neither_adopted_nor_overwritten() {
1265        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1266        let dir = tempfile::tempdir().unwrap();
1267        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1268        _guard.set("XDG_CONFIG_HOME", dir.path());
1269
1270        let (issuer, rx) = spawn_idp(
1271            r#"{"access_token":"a-fresh-at","refresh_token":"a-fresh-rt","expires_in":300}"#,
1272        );
1273
1274        // On disk: instance B's session, freshly written by `tv login` in
1275        // another terminal. Different refresh token, plenty of life left — so
1276        // an unscoped adopt WOULD take it.
1277        let creds_dir = dir.path().join("tracevault");
1278        std::fs::create_dir_all(&creds_dir).unwrap();
1279        let b_file = format!(
1280            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":{}}}}}"#,
1281            NOW + 3600
1282        );
1283        std::fs::write(creds_dir.join("credentials.json"), &b_file).unwrap();
1284
1285        // This client talks to instance A and holds A's own session.
1286        let client = ApiClient::with_credential(
1287            "https://instance-a.example.com",
1288            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1289        )
1290        .with_now(fixed_now);
1291
1292        let token = client.bearer().await.expect("A's own refresh must succeed");
1293        assert_eq!(token.as_deref(), "a-fresh-at".into());
1294
1295        // The refresh used A's OWN in-memory token — B's was never presented.
1296        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1297        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1298        assert!(
1299            refresh.contains("refresh_token=old-rt"),
1300            "A must refresh with its own token: {refresh}"
1301        );
1302        assert!(
1303            !refresh.contains("b-rt"),
1304            "another server's refresh token must never be presented: {refresh}"
1305        );
1306
1307        // And B's credentials file is untouched: byte-identical to what
1308        // `tv login` wrote for B.
1309        let after = std::fs::read_to_string(creds_dir.join("credentials.json")).unwrap();
1310        assert_eq!(
1311            after, b_file,
1312            "instance A's refresh overwrote instance B's credentials"
1313        );
1314
1315        // The other direction at this same call site: a file for the SAME
1316        // instance, written with a trailing slash (as `tv login` stores whatever
1317        // it was given, while `ApiClient` trims). It must be adopted — so the
1318        // comparison has to be `same_server`, not `==`.
1319        std::fs::write(
1320            creds_dir.join("credentials.json"),
1321            format!(
1322                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":{}}}}}"#,
1323                NOW + 3600
1324            ),
1325        )
1326        .unwrap();
1327        // A dead issuer, so an un-adopted session could only fail here.
1328        let client = ApiClient::with_credential(
1329            "https://instance-a.example.com",
1330            Some(Credential::Keycloak(session(
1331                "http://127.0.0.1:1",
1332                NOW + 10,
1333            ))),
1334        )
1335        .with_now(fixed_now);
1336        assert_eq!(
1337            client
1338                .bearer()
1339                .await
1340                .expect("a trailing slash must not prevent the adopt")
1341                .as_deref(),
1342            Some("adopted-at")
1343        );
1344    }
1345
1346    /// The interleaving that makes the adopt unconditional: the on-disk
1347    /// session has a NEWER refresh token AND its access token is itself inside
1348    /// the refresh window. A refresh is genuinely needed, so it must be
1349    /// performed with the ADOPTED refresh token — refreshing with the
1350    /// in-memory one, which another client already consumed, is the
1351    /// guaranteed-`invalid_grant` case the adopt exists to prevent.
1352    #[tokio::test]
1353    async fn a_refresh_after_adopting_uses_the_disk_refresh_token() {
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, rx) = spawn_idp(
1360            r#"{"access_token":"newest-at","refresh_token":"newest-rt","expires_in":300}"#,
1361        );
1362
1363        // On disk: another client already rotated the refresh token, but its
1364        // access token is ALSO within 60s of expiry.
1365        let creds_dir = dir.path().join("tracevault");
1366        std::fs::create_dir_all(&creds_dir).unwrap();
1367        std::fs::write(
1368            creds_dir.join("credentials.json"),
1369            format!(
1370                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":{}}}}}"#,
1371                NOW + 5
1372            ),
1373        )
1374        .unwrap();
1375
1376        // In memory: the superseded session, also inside the window.
1377        let client = ApiClient::with_credential(
1378            "https://example.com",
1379            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1380        )
1381        .with_now(fixed_now);
1382
1383        let token = client.bearer().await.expect("the refresh must succeed");
1384        assert_eq!(token.as_deref(), Some("newest-at"));
1385
1386        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
1387        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
1388        assert!(
1389            refresh.contains("refresh_token=rotated-rt"),
1390            "the refresh must use the adopted on-disk token: {refresh}"
1391        );
1392        assert!(
1393            !refresh.contains("refresh_token=old-rt"),
1394            "the superseded in-memory token must NOT be presented: {refresh}"
1395        );
1396    }
1397
1398    /// On an IdP that does NOT rotate refresh tokens — RFC 6749 permits omitting
1399    /// `refresh_token` on a refresh, and `KeycloakSession::apply` keeps the
1400    /// previous one — every session on disk and in memory carries the SAME
1401    /// refresh token. A refresh-token comparison therefore never fires, so
1402    /// `tracevault status` (three clients from one credential) performed three
1403    /// redundant refreshes, silently. The on-disk access token outliving ours is
1404    /// the signal that actually works there.
1405    ///
1406    /// The issuer points at a dead port, so any refresh attempt would fail the
1407    /// call: reaching the assertion proves the adopt happened instead.
1408    #[tokio::test]
1409    async fn bearer_adopts_a_fresher_session_from_a_non_rotating_idp() {
1410        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1411        let dir = tempfile::tempdir().unwrap();
1412        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1413        _guard.set("XDG_CONFIG_HOME", dir.path());
1414
1415        // On disk: another client refreshed and got a new access token, but the
1416        // SAME refresh token back (no rotation).
1417        let creds_dir = dir.path().join("tracevault");
1418        std::fs::create_dir_all(&creds_dir).unwrap();
1419        std::fs::write(
1420            creds_dir.join("credentials.json"),
1421            format!(
1422                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":{}}}}}"#,
1423                NOW + 3600
1424            ),
1425        )
1426        .unwrap();
1427
1428        // In memory: the same refresh token, an access token about to expire.
1429        let client = ApiClient::with_credential(
1430            "https://example.com",
1431            Some(Credential::Keycloak(session(
1432                "http://127.0.0.1:1",
1433                NOW + 10,
1434            ))),
1435        )
1436        .with_now(fixed_now);
1437
1438        let token = client
1439            .bearer()
1440            .await
1441            .expect("a fresher on-disk session must be adopted, not re-refreshed");
1442        assert_eq!(token.as_deref(), Some("refreshed-by-someone-else"));
1443    }
1444
1445    /// Outside the window the stored token is used as-is. The issuer points
1446    /// at a port nothing listens on, so ANY refresh attempt would fail the
1447    /// call — proving no network round trip happened.
1448    #[tokio::test]
1449    async fn bearer_does_not_refresh_outside_the_window() {
1450        let client = ApiClient::with_credential(
1451            "https://example.com",
1452            Some(Credential::Keycloak(session(
1453                "http://127.0.0.1:1",
1454                NOW + 3600,
1455            ))),
1456        )
1457        .with_now(fixed_now);
1458
1459        let token = client
1460            .bearer()
1461            .await
1462            .expect("a still-valid token must not trigger any IdP call");
1463        assert_eq!(token.as_deref(), Some("old-at"));
1464    }
1465
1466    /// The API-key path is a pure passthrough: no clock, no IdP, no refresh.
1467    #[tokio::test]
1468    async fn bearer_returns_an_api_key_verbatim() {
1469        let client = ApiClient::new("https://example.com", Some("tvk_abc"));
1470        assert_eq!(client.bearer().await.unwrap().as_deref(), Some("tvk_abc"));
1471
1472        let anonymous = ApiClient::new("https://example.com", None);
1473        assert_eq!(anonymous.bearer().await.unwrap(), None);
1474    }
1475
1476    /// A 401 on an API key is a real rejection: retrying would double every
1477    /// failure and could re-run a non-idempotent write. Exactly ONE request
1478    /// must reach the server.
1479    #[tokio::test]
1480    async fn a_401_with_an_api_key_does_not_refresh_or_retry() {
1481        let (base, rx) = spawn_seq(vec![
1482            http_json("401 Unauthorized", r#"{"error":"invalid token"}"#),
1483            // A second response is queued precisely to prove it is unused.
1484            http_json("200 OK", "[]"),
1485        ]);
1486        let client = ApiClient::new(&base, Some("tvk_abc"));
1487        client
1488            .list_repos()
1489            .await
1490            .expect_err("a 401 must surface as an error");
1491
1492        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
1493        assert!(first.contains("GET /api/v1/repos"), "{first}");
1494        assert!(
1495            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1496            "an API key must never be retried after a 401"
1497        );
1498    }
1499
1500    /// A Keycloak credential that gets an unexpected 401 (server-side session
1501    /// invalidation, clock skew) force-refreshes and retries ONCE.
1502    #[tokio::test]
1503    async fn a_401_with_a_keycloak_credential_refreshes_and_retries_once() {
1504        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1505        let dir = tempfile::tempdir().unwrap();
1506        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1507        _guard.set("XDG_CONFIG_HOME", dir.path());
1508
1509        let (issuer, _idp_rx) =
1510            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1511        let (base, rx) = spawn_seq(vec![
1512            http_json("401 Unauthorized", r#"{"error":"expired"}"#),
1513            http_json("200 OK", "[]"),
1514        ]);
1515        // The file is for THIS client's server, so the refreshed session is
1516        // persisted rather than skipped by the same-server guard.
1517        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
1518
1519        // Far from expiry: the proactive window must NOT be what triggers the
1520        // refresh here — the 401 must.
1521        let client = ApiClient::with_credential(
1522            &base,
1523            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
1524        )
1525        .with_now(fixed_now);
1526
1527        let repos = client
1528            .list_repos()
1529            .await
1530            .expect("the retry after a forced refresh must succeed");
1531        assert!(repos.is_empty());
1532
1533        // The point of the retry is that it presents the REFRESHED token; a
1534        // retry that re-sent the rejected one would be pointless and would
1535        // still 401 in production.
1536        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no first request");
1537        assert!(first.contains("GET /api/v1/repos"), "{first}");
1538        assert!(
1539            first.contains("Bearer old-at"),
1540            "the first attempt must carry the stored token: {first}"
1541        );
1542        let second = rx.recv_timeout(RECV_TIMEOUT).expect("no retry request");
1543        assert!(second.contains("GET /api/v1/repos"), "{second}");
1544        assert!(
1545            second.contains("Bearer fresh-at"),
1546            "the retry must carry the REFRESHED token, not the rejected one: {second}"
1547        );
1548        assert!(
1549            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1550            "the retry must happen at most once, or a 401-always server would loop"
1551        );
1552    }
1553
1554    /// A 401 that survives the retry must not send the request a third time:
1555    /// a server answering 401 unconditionally has to terminate.
1556    #[tokio::test]
1557    async fn a_persistent_401_stops_after_one_retry() {
1558        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1559        let dir = tempfile::tempdir().unwrap();
1560        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1561        _guard.set("XDG_CONFIG_HOME", dir.path());
1562
1563        let (issuer, _idp_rx) =
1564            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
1565        let (base, rx) = spawn_seq(vec![
1566            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
1567            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
1568            http_json("200 OK", "[]"),
1569        ]);
1570        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
1571        let client = ApiClient::with_credential(
1572            &base,
1573            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
1574        )
1575        .with_now(fixed_now);
1576
1577        client
1578            .list_repos()
1579            .await
1580            .expect_err("a persistent 401 must surface as an error");
1581
1582        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
1583        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
1584        assert!(
1585            rx.recv_timeout(Duration::from_millis(300)).is_err(),
1586            "a third attempt means the retry can loop"
1587        );
1588    }
1589
1590    /// A dead refresh token must surface as "log in again", not as a bland
1591    /// 401 or a network error — `tracevault status` renders those differently.
1592    #[tokio::test]
1593    async fn get_me_maps_a_dead_refresh_token_to_unauthorized() {
1594        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1595        let dir = tempfile::tempdir().unwrap();
1596        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1597        _guard.set("XDG_CONFIG_HOME", dir.path());
1598
1599        let (issuer, _rx) = spawn_seq_with(|base| {
1600            vec![
1601                http_json(
1602                    "200 OK",
1603                    &format!(r#"{{"issuer":"{base}","token_endpoint":"{base}/token"}}"#),
1604                ),
1605                http_json("400 Bad Request", r#"{"error":"invalid_grant"}"#),
1606            ]
1607        });
1608        write_keycloak_file(dir.path(), "http://127.0.0.1:1", &issuer, NOW + 10);
1609
1610        let client = ApiClient::with_credential(
1611            "http://127.0.0.1:1",
1612            // Inside the window, so the (failing) refresh happens before any
1613            // request to the server is attempted.
1614            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
1615        )
1616        .with_now(fixed_now);
1617
1618        match client.get_me().await {
1619            Err(GetMeError::Unauthorized) => {}
1620            other => panic!("expected Unauthorized for a dead session, got {other:?}"),
1621        }
1622    }
1623
1624    /// An unreachable IdP is NOT a dead session: it must stay distinguishable
1625    /// so status says "cannot confirm" rather than "you were logged out".
1626    #[tokio::test]
1627    async fn get_me_maps_an_unreachable_idp_to_network() {
1628        // The session is inside the refresh window, so `refresh_locked` calls
1629        // `Credentials::load()`. Without this redirect that reads the
1630        // DEVELOPER's real `~/.config/tracevault/credentials.json` — which on a
1631        // machine logged in with Keycloak means reading a live token, and makes
1632        // the test's outcome depend on the developer's own login state.
1633        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1634        let dir = tempfile::tempdir().unwrap();
1635        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1636        _guard.set("XDG_CONFIG_HOME", dir.path());
1637
1638        let client = ApiClient::with_credential(
1639            "http://127.0.0.1:1",
1640            Some(Credential::Keycloak(session(
1641                "http://127.0.0.1:1",
1642                NOW + 10,
1643            ))),
1644        )
1645        .with_now(fixed_now);
1646
1647        match client.get_me().await {
1648            Err(GetMeError::Network(_)) => {}
1649            other => panic!("expected Network for an unreachable IdP, got {other:?}"),
1650        }
1651    }
1652
1653    /// A 403 is its own outcome: the token is fine, the account isn't
1654    /// authorized, and "log in again" would be the wrong advice.
1655    #[tokio::test]
1656    async fn get_me_maps_403_to_forbidden() {
1657        let (base, _rx) = spawn_seq(vec![http_json(
1658            "403 Forbidden",
1659            r#"{"error":"missing role"}"#,
1660        )]);
1661        let client = ApiClient::new(&base, Some("tvk_abc"));
1662        match client.get_me().await {
1663            Err(GetMeError::Forbidden(_)) => {}
1664            other => panic!("expected Forbidden, got {other:?}"),
1665        }
1666    }
1667
1668    /// `resolve_client` is the funnel the project/repo commands use, so the
1669    /// guard has to hold through the wrapper too — not only in
1670    /// `resolve_credentials`, whose own tests now live beside it in
1671    /// `credentials.rs`.
1672    #[test]
1673    fn resolve_client_also_refuses_a_mismatched_server_url() {
1674        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1675        let dir = tempfile::tempdir().unwrap();
1676        let mut guard = crate::test_helpers::EnvVarGuard::new();
1677        guard.set("XDG_CONFIG_HOME", dir.path());
1678        guard.remove("TRACEVAULT_API_KEY");
1679        guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
1680        write_keycloak_file(
1681            dir.path(),
1682            "https://instance-b.example.com",
1683            "https://idp.test/realms/v",
1684            NOW + 3600,
1685        );
1686
1687        // `ApiClient` deliberately has no `Debug` (it holds a credential), so
1688        // match instead of `expect_err`.
1689        let err = match resolve_client(dir.path()) {
1690            Err(e) => e,
1691            Ok(_) => panic!("resolve_client must apply the guard"),
1692        };
1693        assert!(err.to_string().contains("instance-b.example.com"));
1694    }
1695}