Skip to main content

tracevault_cli/
api_client.rs

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