Skip to main content

tracevault_cli/
oidc.rs

1//! OIDC / OAuth 2.0 plumbing for interactive (human) login.
2//!
3//! The CLI authenticates humans with Keycloak's RFC 8628 device
4//! authorization grant: it asks the TraceVault server which realm to talk to
5//! (`/api/v1/auth/public-config`), discovers the realm's endpoints, starts a
6//! device authorization, polls the token endpoint until the user finishes in
7//! the browser, and thereafter keeps the access token fresh with the refresh
8//! token. The TraceVault server itself is not part of the token exchange —
9//! it only publishes the issuer and client id.
10//!
11//! Everything here is transport + protocol only: no printing, no credential
12//! file access, no command-layer concerns. That keeps the whole module
13//! testable against a raw one-shot HTTP server.
14//!
15//! ## Secret hygiene
16//!
17//! `device_code`, `access_token` and `refresh_token` are secrets. [`DeviceAuth`]
18//! and [`TokenSet`] therefore implement `Debug` **by hand**, redacting those
19//! fields, so no `{:?}` anywhere (including a panicking `unwrap()` inside a
20//! test) can leak them into a log. For the same reason no error variant in
21//! [`OidcError`] carries a response body: an IdP error body is not supposed
22//! to contain a token, but a *success* body always does, and one shared
23//! "here is the body" error path would eventually be reached from a success
24//! response that failed to deserialize.
25
26use serde::Deserialize;
27use std::fmt;
28use std::time::Duration;
29use url::Url;
30
31/// Scopes requested for the device flow. `offline_access` is what makes
32/// Keycloak issue a long-lived refresh token, which is the whole point of
33/// this flow for a CLI: unattended git hooks must never prompt.
34pub const LOGIN_SCOPE: &str = "openid profile email offline_access";
35
36/// RFC 8628 grant type for exchanging a device code for tokens.
37const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
38
39/// Extra seconds added to the poll interval each time the IdP answers
40/// `slow_down` (RFC 8628 §3.5 specifies exactly 5).
41const SLOW_DOWN_INCREMENT_SECS: u64 = 5;
42
43/// Fallback poll interval when the device authorization response omits
44/// `interval` (RFC 8628 §3.2 default).
45const DEFAULT_POLL_INTERVAL_SECS: u64 = 5;
46
47/// What the TraceVault server publishes about its identity provider.
48///
49/// This type exists only for the CONFIGURED case: "no Keycloak here" is an
50/// error ([`OidcError::NoKeycloak`]), not a `PublicConfig` with empty fields,
51/// so no caller can accidentally proceed with an empty issuer.
52#[derive(Debug, Clone)]
53pub struct PublicConfig {
54    pub issuer: String,
55    pub cli_client_id: String,
56    /// The audience the server expects in an access token's `aud`. Optional so
57    /// the CLI keeps working against a server that does not publish it; used
58    /// only to sharpen the diagnosis when `/auth/me` rejects a fresh token.
59    pub audience: Option<String>,
60    /// The bazaar (context) MCP endpoint of this installation, when the server
61    /// publishes it. `visdom` uses it to check an agent's MCP registration.
62    pub bazaar_mcp_url: Option<String>,
63}
64
65/// Wire shape of `GET /api/v1/auth/public-config`.
66///
67/// Every field except `oidc_enabled` is optional on the wire because the
68/// not-configured response omits them; requiring them here would turn a
69/// well-formed "no Keycloak" answer into a parse error.
70#[derive(Deserialize)]
71struct PublicConfigWire {
72    #[serde(default)]
73    oidc_enabled: bool,
74    #[serde(default)]
75    issuer: Option<String>,
76    #[serde(default)]
77    cli_client_id: Option<String>,
78    #[serde(default)]
79    audience: Option<String>,
80    #[serde(default)]
81    bazaar_mcp_url: Option<String>,
82}
83
84/// The subset of the realm's OpenID discovery document the CLI uses.
85///
86/// `device_authorization_endpoint` and `revocation_endpoint` are optional
87/// because a non-Keycloak (or ancient Keycloak) issuer may not advertise
88/// them; the operations that need them fail with a specific message rather
89/// than discovery failing wholesale, so `tv logout` still works against an
90/// issuer with no revocation endpoint.
91#[derive(Debug, Clone)]
92pub struct Discovery {
93    pub device_authorization_endpoint: Option<String>,
94    pub token_endpoint: String,
95    pub revocation_endpoint: Option<String>,
96}
97
98/// Wire shape of the discovery document. `issuer` is read back so we can
99/// verify it matches the issuer we were told to trust.
100#[derive(Deserialize)]
101struct DiscoveryDoc {
102    issuer: String,
103    #[serde(default)]
104    device_authorization_endpoint: Option<String>,
105    token_endpoint: String,
106    #[serde(default)]
107    revocation_endpoint: Option<String>,
108}
109
110/// A started device authorization (RFC 8628 §3.2).
111#[derive(Clone, Deserialize)]
112pub struct DeviceAuth {
113    /// SECRET. Never print this — it is the bearer of the pending login.
114    pub device_code: String,
115    /// The short code the human types into the browser. This is the one
116    /// value in the whole flow that MUST be shown to the user.
117    pub user_code: String,
118    pub verification_uri: String,
119    #[serde(default)]
120    pub verification_uri_complete: Option<String>,
121    #[serde(default = "default_device_expires_in")]
122    pub expires_in: u64,
123    #[serde(default = "default_interval")]
124    pub interval: u64,
125}
126
127fn default_device_expires_in() -> u64 {
128    600
129}
130
131fn default_interval() -> u64 {
132    DEFAULT_POLL_INTERVAL_SECS
133}
134
135/// Hand-written so `device_code` cannot leak through `{:?}`.
136impl fmt::Debug for DeviceAuth {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.debug_struct("DeviceAuth")
139            .field("device_code", &"<redacted>")
140            .field("user_code", &self.user_code)
141            .field("verification_uri", &self.verification_uri)
142            .field(
143                "verification_uri_complete",
144                &self.verification_uri_complete.is_some(),
145            )
146            .field("expires_in", &self.expires_in)
147            .field("interval", &self.interval)
148            .finish()
149    }
150}
151
152/// A successful token response. `expires_in` is relative seconds as sent by
153/// the IdP; callers turn it into an absolute instant via
154/// [`TokenSet::access_expires_at`].
155///
156/// `refresh_token` is optional because a token endpoint is allowed to omit
157/// it on a refresh (no rotation); callers keep the previous one in that case.
158#[derive(Clone, Deserialize)]
159pub struct TokenSet {
160    /// SECRET.
161    pub access_token: String,
162    /// SECRET.
163    #[serde(default)]
164    pub refresh_token: Option<String>,
165    #[serde(default)]
166    pub expires_in: i64,
167}
168
169impl TokenSet {
170    /// Absolute unix-seconds expiry of `access_token`, given the current
171    /// time. `now` is a parameter (not read from the clock here) so callers
172    /// and tests share one deterministic notion of "now".
173    pub fn access_expires_at(&self, now: i64) -> i64 {
174        now.saturating_add(self.expires_in)
175    }
176}
177
178/// Hand-written so neither token can leak through `{:?}`.
179impl fmt::Debug for TokenSet {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        f.debug_struct("TokenSet")
182            .field("access_token", &"<redacted>")
183            .field(
184                "refresh_token",
185                &self.refresh_token.as_ref().map(|_| "<redacted>"),
186            )
187            .field("expires_in", &self.expires_in)
188            .finish()
189    }
190}
191
192/// Wire shape of an OAuth error response (RFC 6749 §5.2).
193#[derive(Deserialize)]
194struct OauthErrorBody {
195    error: String,
196    #[serde(default)]
197    error_description: Option<String>,
198}
199
200/// Failures of the login/refresh machinery. Every variant that a caller has
201/// to *behave* differently about is its own variant; anything else collapses
202/// into [`OidcError::Oauth`] (the IdP said no, with a code) or
203/// [`OidcError::Transport`] (we never got a usable answer).
204#[derive(Debug)]
205pub enum OidcError {
206    /// `/auth/public-config` answered `{"oidc_enabled": false}`: this TraceVault
207    /// instance has no Keycloak at all, so interactive login is impossible and
208    /// an API key must be used instead. Permanent until an operator changes the
209    /// deployment. See [`fetch_public_config`].
210    NoKeycloak,
211    /// `/auth/public-config` answered a 5xx — the server, or an intermediary in
212    /// front of it, is unhealthy right now. Retryable, and explicitly NOT a
213    /// reason to go get an API key.
214    IdpUnavailable { detail: String },
215    /// The discovery document's own `issuer` disagrees with the issuer the
216    /// server told us to use — a misconfiguration or a redirect to a
217    /// different realm. Both values are named so it is diagnosable.
218    IssuerMismatch { expected: String, found: String },
219    /// The refresh token is no longer accepted (`invalid_grant`).
220    SessionExpired,
221    /// The user rejected the login in the browser.
222    AccessDenied,
223    /// The device code expired before the user finished.
224    DeviceCodeExpired,
225    /// We polled for the full `expires_in` budget without a verdict.
226    PollTimeout { waited_secs: u64 },
227    /// The issuer does not advertise an endpoint this operation needs.
228    EndpointUnavailable { what: &'static str },
229    /// The issuer is not `https` (and not loopback), so the refresh token would
230    /// travel in clear text.
231    InsecureIssuer { issuer: String },
232    /// A discovery document named an endpoint on a different origin than the
233    /// issuer's — a misconfiguration, or an attempt to collect tokens elsewhere.
234    EndpointOriginMismatch {
235        what: &'static str,
236        endpoint: String,
237        issuer: String,
238    },
239    /// An OAuth error code we don't special-case.
240    Oauth {
241        error: String,
242        description: Option<String>,
243    },
244    /// Network/HTTP-level failure, or a response we could not parse.
245    Transport(String),
246}
247
248impl fmt::Display for OidcError {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        match self {
251            Self::NoKeycloak => write!(
252                f,
253                "this TraceVault server has no Keycloak/SSO configured, so interactive login is \
254                 unavailable"
255            ),
256            Self::IdpUnavailable { detail } => write!(
257                f,
258                "the identity provider is temporarily unavailable ({detail}) — this is not a \
259                 configuration problem; retry `tracevault login` in a moment"
260            ),
261            Self::IssuerMismatch { expected, found } => write!(
262                f,
263                "issuer mismatch: the server said the issuer is '{expected}', but its discovery \
264                 document identifies itself as '{found}'"
265            ),
266            Self::SessionExpired => write!(
267                f,
268                "your session has expired — run `tracevault login` to sign in again"
269            ),
270            Self::AccessDenied => write!(f, "the login was denied in the browser (access_denied)"),
271            Self::DeviceCodeExpired => write!(
272                f,
273                "the login code expired before it was approved — run `tracevault login` again"
274            ),
275            Self::PollTimeout { waited_secs } => write!(
276                f,
277                "gave up waiting for browser approval after {waited_secs}s — run \
278                 `tracevault login` again"
279            ),
280            Self::EndpointUnavailable { what } => write!(
281                f,
282                "the identity provider does not advertise a {what} endpoint"
283            ),
284            Self::InsecureIssuer { issuer } => write!(
285                f,
286                "refusing to use the insecure issuer '{issuer}': signing in would send a \
287                 long-lived refresh token over an unencrypted connection. Use an https issuer \
288                 (http is allowed only for a loopback address during local development)."
289            ),
290            Self::EndpointOriginMismatch {
291                what,
292                endpoint,
293                issuer,
294            } => write!(
295                f,
296                "the identity provider's discovery document points its {what} endpoint at \
297                 '{endpoint}', which is not the issuer's origin ('{issuer}'). Refusing, rather \
298                 than sending credentials to an unrelated host."
299            ),
300            Self::Oauth { error, description } => match description {
301                Some(d) => write!(f, "identity provider rejected the request: {error} ({d})"),
302                None => write!(f, "identity provider rejected the request: {error}"),
303            },
304            Self::Transport(m) => write!(f, "{m}"),
305        }
306    }
307}
308
309impl std::error::Error for OidcError {}
310
311/// Canonical form of an issuer URL for comparison: no surrounding
312/// whitespace, no trailing slashes. Both the configured issuer and the one
313/// the discovery document self-reports go through this before being
314/// compared, so `https://x/realms/v` and `https://x/realms/v/` match.
315pub fn canonical_issuer(issuer: &str) -> String {
316    issuer.trim().trim_end_matches('/').to_string()
317}
318
319/// Ask the TraceVault server which realm to authenticate against.
320///
321/// "Is this instance configured for SSO, and against which realm?"
322///
323/// Two outcomes must stay distinguishable, because the advice differs and one
324/// is permanent while the other is not:
325///
326/// * `200 {"oidc_enabled": false}` → the instance has no Keycloak at all.
327///   PERMANENT; the user needs a `tvk_` API key ([`OidcError::NoKeycloak`]).
328/// * any `5xx` → the server (or an intermediary/web proxy in front of it) is
329///   unhealthy right now. RETRYABLE ([`OidcError::IdpUnavailable`]), and
330///   deliberately never phrased as "go get an API key": telling a user in the
331///   middle of a 30-second restart to change credentials is unactionable.
332///
333/// The not-configured answer is a 200 rather than a 503 because a 503 from a
334/// healthy server makes load balancers fail the pod out and 5xx SLO alerts
335/// fire. The 5xx branch remains regardless, since an intermediary can still
336/// produce one when the backend is down.
337///
338/// `oidc_enabled: true` with `issuer` or `cli_client_id` missing is a hard
339/// error rather than an empty-string default: the alternative is a device
340/// authorization POSTed to `"/.well-known/..."`, failing with something
341/// unrelated to the actual misconfiguration.
342pub async fn fetch_public_config(
343    client: &reqwest::Client,
344    server_url: &str,
345) -> Result<PublicConfig, OidcError> {
346    let url = format!(
347        "{}/api/v1/auth/public-config",
348        server_url.trim_end_matches('/')
349    );
350    let resp = client.get(&url).send().await.map_err(transport)?;
351    let status = resp.status();
352
353    if status.is_server_error() {
354        return Err(OidcError::IdpUnavailable {
355            detail: format!("server returned {status}"),
356        });
357    }
358    if !status.is_success() {
359        return Err(OidcError::Transport(format!("GET {url} returned {status}")));
360    }
361
362    let wire: PublicConfigWire = resp
363        .json()
364        .await
365        .map_err(|e| OidcError::Transport(format!("malformed auth public-config response: {e}")))?;
366
367    if !wire.oidc_enabled {
368        return Err(OidcError::NoKeycloak);
369    }
370    let missing = |field: &'static str| {
371        OidcError::Transport(format!(
372            "the server reports SSO is enabled but its auth public-config omits `{field}` — the \
373         server is misconfigured; report this to whoever operates it"
374        ))
375    };
376    Ok(PublicConfig {
377        issuer: wire
378            .issuer
379            .filter(|s| !s.trim().is_empty())
380            .ok_or_else(|| missing("issuer"))?,
381        cli_client_id: wire
382            .cli_client_id
383            .filter(|s| !s.trim().is_empty())
384            .ok_or_else(|| missing("cli_client_id"))?,
385        audience: wire.audience.filter(|s| !s.trim().is_empty()),
386        bazaar_mcp_url: wire.bazaar_mcp_url.filter(|s| !s.trim().is_empty()),
387    })
388}
389
390/// Fetch and validate the realm's OpenID discovery document.
391///
392/// Three checks, because everything downstream trusts what this returns with a
393/// refresh token attached:
394///
395/// 1. The issuer must be `https`, unless it is loopback. A plaintext issuer
396///    would POST the long-lived `offline_access` refresh token in clear text.
397///    Loopback is exempt so local Keycloak development works.
398/// 2. The document's self-reported `issuer` must match the one we asked for
399///    (both canonicalised). Otherwise a redirect or a copy-pasted wrong realm
400///    silently mints tokens the TraceVault server will reject, with no clue why.
401/// 3. Every endpoint must share the issuer's ORIGIN. A misconfigured or tampered
402///    document could otherwise name an unrelated host as the token endpoint and
403///    collect the refresh token there.
404pub async fn discover(client: &reqwest::Client, issuer: &str) -> Result<Discovery, OidcError> {
405    let expected = canonical_issuer(issuer);
406    let issuer_url = Url::parse(&expected).map_err(|e| {
407        OidcError::Transport(format!("'{expected}' is not a valid issuer URL: {e}"))
408    })?;
409    require_secure(&issuer_url)?;
410
411    let url = format!("{expected}/.well-known/openid-configuration");
412    let resp = client.get(&url).send().await.map_err(transport)?;
413    let status = resp.status();
414    if !status.is_success() {
415        return Err(OidcError::Transport(format!("GET {url} returned {status}")));
416    }
417    let doc: DiscoveryDoc = resp
418        .json()
419        .await
420        .map_err(|e| OidcError::Transport(format!("malformed discovery document: {e}")))?;
421
422    let found = canonical_issuer(&doc.issuer);
423    if found != expected {
424        return Err(OidcError::IssuerMismatch { expected, found });
425    }
426
427    let origin = issuer_url.origin();
428    let checked =
429        |endpoint: Option<String>, what: &'static str| -> Result<Option<String>, OidcError> {
430            let Some(endpoint) = endpoint else {
431                return Ok(None);
432            };
433            let parsed = Url::parse(&endpoint).map_err(|e| {
434                OidcError::Transport(format!(
435                    "the discovery document's {what} endpoint '{endpoint}' is not a valid URL: {e}"
436                ))
437            })?;
438            if parsed.origin() != origin {
439                return Err(OidcError::EndpointOriginMismatch {
440                    what,
441                    endpoint,
442                    issuer: expected.clone(),
443                });
444            }
445            Ok(Some(endpoint))
446        };
447
448    let token_endpoint = checked(Some(doc.token_endpoint), "token")?
449        .expect("checked() returns Some for a Some input");
450    Ok(Discovery {
451        device_authorization_endpoint: checked(
452            doc.device_authorization_endpoint,
453            "device authorization",
454        )?,
455        token_endpoint,
456        revocation_endpoint: checked(doc.revocation_endpoint, "revocation")?,
457    })
458}
459
460/// Reject a non-TLS issuer, except on loopback.
461///
462/// The refresh token is long-lived and `offline_access`-scoped; handing it to an
463/// `http://` endpoint puts it on the wire in clear text. Loopback is exempt
464/// because a local Keycloak (`http://localhost:8080/realms/...`) is a normal
465/// development setup and never leaves the machine.
466fn require_secure(issuer: &Url) -> Result<(), OidcError> {
467    if issuer.scheme() == "https" || is_loopback_host(issuer) {
468        return Ok(());
469    }
470    Err(OidcError::InsecureIssuer {
471        issuer: issuer.to_string(),
472    })
473}
474
475/// Whether a URL's host is a loopback address or a `localhost` name.
476fn is_loopback_host(url: &Url) -> bool {
477    match url.host() {
478        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
479        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
480        Some(url::Host::Domain(d)) => d == "localhost" || d.ends_with(".localhost"),
481        None => false,
482    }
483}
484
485/// Whether `url` is safe to hand to the desktop's URL handler.
486///
487/// `open::that` launches whatever handler is registered for the scheme, so a
488/// broken or hostile realm response could otherwise get `file:///...` — or any
489/// registered application scheme — launched on the user's desktop. Only the two
490/// schemes a verification URI is ever legitimately expressed in are allowed.
491pub fn is_browser_safe(url: &str) -> bool {
492    Url::parse(url)
493        .map(|u| matches!(u.scheme(), "http" | "https"))
494        .unwrap_or(false)
495}
496
497/// Start a device authorization (RFC 8628 §3.1). `tracing-cli` is a
498/// PUBLIC client, so the form carries `client_id` and no client secret.
499pub async fn device_start(
500    client: &reqwest::Client,
501    discovery: &Discovery,
502    client_id: &str,
503) -> Result<DeviceAuth, OidcError> {
504    let endpoint = discovery.device_authorization_endpoint.as_deref().ok_or(
505        OidcError::EndpointUnavailable {
506            what: "device authorization",
507        },
508    )?;
509    let resp = post_form(
510        client,
511        endpoint,
512        &[("client_id", client_id), ("scope", LOGIN_SCOPE)],
513    )
514    .send()
515    .await
516    .map_err(transport)?;
517    let status = resp.status();
518    if !status.is_success() {
519        // Read the body only to extract an OAuth error code; the body of a
520        // FAILED device-authorization response holds no secret.
521        let body = resp.text().await.unwrap_or_default();
522        return Err(
523            oauth_error_from_body(&body).unwrap_or(OidcError::Transport(format!(
524                "device authorization request returned {status}"
525            ))),
526        );
527    }
528    resp.json::<DeviceAuth>()
529        .await
530        .map_err(|e| OidcError::Transport(format!("malformed device authorization response: {e}")))
531}
532
533/// Poll the token endpoint until the user approves, or the attempt dies.
534///
535/// The sleep is a parameter (production passes `tokio::time::sleep`) for two
536/// reasons: tests must not burn wall-clock seconds, and the elapsed budget is
537/// accumulated from the sleep durations rather than read off a clock — so "give
538/// up after `expires_in`" is exercised deterministically by a no-op sleep, and a
539/// `slow_down` genuinely shortens the number of remaining attempts.
540pub async fn poll_token_with<S, F>(
541    client: &reqwest::Client,
542    discovery: &Discovery,
543    client_id: &str,
544    device: &DeviceAuth,
545    mut sleep: S,
546) -> Result<TokenSet, OidcError>
547where
548    S: FnMut(Duration) -> F,
549    F: std::future::Future<Output = ()>,
550{
551    let mut interval = if device.interval == 0 {
552        DEFAULT_POLL_INTERVAL_SECS
553    } else {
554        device.interval
555    };
556    let mut waited: u64 = 0;
557
558    loop {
559        sleep(Duration::from_secs(interval)).await;
560        waited = waited.saturating_add(interval);
561
562        let attempt = token_request(
563            client,
564            &discovery.token_endpoint,
565            &[
566                ("grant_type", DEVICE_CODE_GRANT),
567                ("client_id", client_id),
568                ("device_code", &device.device_code),
569            ],
570        )
571        .await;
572
573        match attempt {
574            Ok(tokens) => return Ok(tokens),
575            Err(OidcError::Oauth { error, description }) => match error.as_str() {
576                // Still waiting on the human.
577                "authorization_pending" => {}
578                // RFC 8628 §3.5: back off permanently, by exactly 5s.
579                "slow_down" => interval = interval.saturating_add(SLOW_DOWN_INCREMENT_SECS),
580                "access_denied" => return Err(OidcError::AccessDenied),
581                "expired_token" => return Err(OidcError::DeviceCodeExpired),
582                _ => return Err(OidcError::Oauth { error, description }),
583            },
584            // Anything else (transport, 5xx, unparseable) is terminal: the
585            // loop must not be able to spin forever on a broken endpoint.
586            Err(e) => return Err(e),
587        }
588
589        // Budget check AFTER handling the attempt, so a login approved on
590        // the very last allowed poll still succeeds.
591        if waited >= device.expires_in {
592            return Err(OidcError::PollTimeout {
593                waited_secs: waited,
594            });
595        }
596    }
597}
598
599/// Exchange a refresh token for a fresh access token.
600pub async fn refresh(
601    client: &reqwest::Client,
602    discovery: &Discovery,
603    client_id: &str,
604    refresh_token: &str,
605) -> Result<TokenSet, OidcError> {
606    let result = token_request(
607        client,
608        &discovery.token_endpoint,
609        &[
610            ("grant_type", "refresh_token"),
611            ("client_id", client_id),
612            ("refresh_token", refresh_token),
613        ],
614    )
615    .await;
616
617    match result {
618        // `invalid_grant` on a refresh means the session is gone for good
619        // (expired, revoked, or the user's account was disabled) — a retry
620        // will never help, so it gets its own "run login again" message.
621        Err(OidcError::Oauth { error, .. }) if error == "invalid_grant" => {
622            Err(OidcError::SessionExpired)
623        }
624        other => other,
625    }
626}
627
628/// Best-effort revocation of a refresh token (RFC 7009). Called by
629/// `tv logout`; a failure there is a warning, not an error, because the
630/// local credential is removed regardless.
631pub async fn revoke(
632    client: &reqwest::Client,
633    discovery: &Discovery,
634    client_id: &str,
635    refresh_token: &str,
636) -> Result<(), OidcError> {
637    let endpoint = discovery
638        .revocation_endpoint
639        .as_deref()
640        .ok_or(OidcError::EndpointUnavailable { what: "revocation" })?;
641    let resp = post_form(
642        client,
643        endpoint,
644        &[
645            ("client_id", client_id),
646            ("token", refresh_token),
647            ("token_type_hint", "refresh_token"),
648        ],
649    )
650    .send()
651    .await
652    .map_err(transport)?;
653    let status = resp.status();
654    if !status.is_success() {
655        return Err(OidcError::Transport(format!(
656            "revocation endpoint returned {status}"
657        )));
658    }
659    Ok(())
660}
661
662/// POST a form to the token endpoint and interpret the answer.
663///
664/// OAuth error codes are read from the BODY, not inferred from the status:
665/// RFC 8628's `authorization_pending`/`slow_down` both arrive as HTTP 400,
666/// so a status-only reading of the response would turn "keep waiting" into
667/// a hard failure.
668async fn token_request(
669    client: &reqwest::Client,
670    token_endpoint: &str,
671    form: &[(&str, &str)],
672) -> Result<TokenSet, OidcError> {
673    let resp = post_form(client, token_endpoint, form)
674        .send()
675        .await
676        .map_err(transport)?;
677    let status = resp.status();
678
679    if status.is_success() {
680        // NOTE: on a deserialize failure the body is deliberately NOT
681        // included in the error — a 200 from the token endpoint contains
682        // live tokens.
683        return resp
684            .json::<TokenSet>()
685            .await
686            .map_err(|e| OidcError::Transport(format!("malformed token response: {e}")));
687    }
688
689    let body = resp.text().await.unwrap_or_default();
690    Err(
691        oauth_error_from_body(&body).unwrap_or(OidcError::Transport(format!(
692            "token endpoint returned {status}"
693        ))),
694    )
695}
696
697/// Parse an RFC 6749 §5.2 error body into [`OidcError::Oauth`], or `None`
698/// when the body isn't one.
699fn oauth_error_from_body(body: &str) -> Option<OidcError> {
700    serde_json::from_str::<OauthErrorBody>(body)
701        .ok()
702        .map(|b| OidcError::Oauth {
703            error: b.error,
704            description: b.error_description,
705        })
706}
707
708fn transport(e: reqwest::Error) -> OidcError {
709    OidcError::Transport(format!("network error: {e}"))
710}
711
712/// The `aud` claim of a JWT, read WITHOUT verifying the signature.
713///
714/// NOT authentication or validation of any kind, and must never be used as
715/// such: this is for one diagnostic sentence, deciding whether a rejected
716/// token was minted for this server at all. The CLI is the token's holder, not
717/// its verifier — the server does that — so reading the payload it just
718/// received from the IdP over TLS is only ever used to explain a failure.
719///
720/// Returns `None` on anything unexpected (not a JWT, un-decodable payload, no
721/// `aud`). Callers must treat `None` as "cannot tell" and fall back to the
722/// generic message rather than guessing.
723pub fn unverified_audiences(access_token: &str) -> Option<Vec<String>> {
724    let payload = access_token.split('.').nth(1)?;
725    let json = base64url_decode(payload)?;
726    let claims: serde_json::Value = serde_json::from_slice(&json).ok()?;
727    match claims.get("aud")? {
728        serde_json::Value::String(one) => Some(vec![one.clone()]),
729        serde_json::Value::Array(many) => Some(
730            many.iter()
731                .filter_map(|v| v.as_str().map(String::from))
732                .collect(),
733        ),
734        _ => None,
735    }
736}
737
738/// Minimal unpadded base64url decoder, so reading a JWT payload needs no new
739/// dependency. `None` on any character outside the alphabet.
740fn base64url_decode(input: &str) -> Option<Vec<u8>> {
741    let mut out = Vec::with_capacity(input.len() * 3 / 4);
742    let mut acc: u32 = 0;
743    let mut bits: u32 = 0;
744    for byte in input.bytes() {
745        let value = match byte {
746            b'A'..=b'Z' => byte - b'A',
747            b'a'..=b'z' => byte - b'a' + 26,
748            b'0'..=b'9' => byte - b'0' + 52,
749            b'-' => 62,
750            b'_' => 63,
751            // Padding is optional in base64url and always trailing.
752            b'=' => break,
753            _ => return None,
754        } as u32;
755        acc = (acc << 6) | value;
756        bits += 6;
757        if bits >= 8 {
758            bits -= 8;
759            out.push((acc >> bits) as u8);
760        }
761    }
762    Some(out)
763}
764
765/// Build an `application/x-www-form-urlencoded` POST.
766///
767/// Hand-encoded via `url::form_urlencoded` rather than `RequestBuilder::form`
768/// because reqwest 0.13 puts `form()` behind its `form` feature, which would
769/// pull `serde_urlencoded` into the dependency tree. `url` is already a
770/// direct dependency and does exactly the same percent-encoding, so this
771/// keeps the lockfile untouched.
772fn post_form(
773    client: &reqwest::Client,
774    url: &str,
775    pairs: &[(&str, &str)],
776) -> reqwest::RequestBuilder {
777    let body = url::form_urlencoded::Serializer::new(String::new())
778        .extend_pairs(pairs)
779        .finish();
780    client
781        .post(url)
782        .header(
783            reqwest::header::CONTENT_TYPE,
784            "application/x-www-form-urlencoded",
785        )
786        .body(body)
787}
788
789#[cfg(test)]
790mod tests {
791    use super::*;
792    use crate::test_helpers::{http_json, spawn_seq, RECV_TIMEOUT};
793    use std::sync::{Arc, Mutex};
794
795    /// A `Discovery` whose token endpoint points at `base`.
796    fn discovery_at(base: &str) -> Discovery {
797        Discovery {
798            device_authorization_endpoint: Some(format!("{base}/device")),
799            token_endpoint: format!("{base}/token"),
800            revocation_endpoint: Some(format!("{base}/revoke")),
801        }
802    }
803
804    fn device_auth(interval: u64, expires_in: u64) -> DeviceAuth {
805        DeviceAuth {
806            device_code: "dev-code".into(),
807            user_code: "WDJB-MJHT".into(),
808            verification_uri: "https://idp.test/device".into(),
809            verification_uri_complete: None,
810            expires_in,
811            interval,
812        }
813    }
814
815    /// A sleep that records what it was asked to wait and returns instantly,
816    /// so poll-loop timing is asserted without any wall-clock cost.
817    fn recording_sleep(
818        log: Arc<Mutex<Vec<u64>>>,
819    ) -> impl FnMut(Duration) -> std::future::Ready<()> {
820        move |d| {
821            log.lock().unwrap().push(d.as_secs());
822            std::future::ready(())
823        }
824    }
825
826    #[tokio::test]
827    async fn poll_retries_on_authorization_pending_then_succeeds() {
828        let (base, rx) = spawn_seq(vec![
829            http_json("400 Bad Request", r#"{"error":"authorization_pending"}"#),
830            http_json(
831                "200 OK",
832                r#"{"access_token":"at","refresh_token":"rt","expires_in":300}"#,
833            ),
834        ]);
835        let log = Arc::new(Mutex::new(Vec::new()));
836        let client = reqwest::Client::new();
837        let tokens = poll_token_with(
838            &client,
839            &discovery_at(&base),
840            "tracing-cli",
841            &device_auth(5, 600),
842            recording_sleep(log.clone()),
843        )
844        .await
845        .expect("a pending poll followed by success must succeed");
846
847        assert_eq!(tokens.access_token, "at");
848        assert_eq!(tokens.refresh_token.as_deref(), Some("rt"));
849        // Polled exactly twice, and both polls used the device_code grant.
850        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no first poll");
851        let second = rx.recv_timeout(RECV_TIMEOUT).expect("no second poll");
852        for req in [&first, &second] {
853            assert!(req.contains("POST /token"), "unexpected request: {req}");
854            assert!(
855                req.contains("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code"),
856                "poll must use the device_code grant: {req}"
857            );
858            assert!(req.contains("device_code=dev-code"), "missing device_code");
859            assert!(req.contains("client_id=tracing-cli"), "missing client_id");
860            assert!(
861                !req.contains("client_secret"),
862                "tracing-cli is a PUBLIC client; no secret may be sent: {req}"
863            );
864        }
865        assert_eq!(*log.lock().unwrap(), vec![5, 5]);
866    }
867
868    #[tokio::test]
869    async fn slow_down_raises_interval_by_five_seconds() {
870        let (base, _rx) = spawn_seq(vec![
871            http_json("400 Bad Request", r#"{"error":"slow_down"}"#),
872            http_json("400 Bad Request", r#"{"error":"authorization_pending"}"#),
873            http_json("200 OK", r#"{"access_token":"at","expires_in":300}"#),
874        ]);
875        let log = Arc::new(Mutex::new(Vec::new()));
876        let client = reqwest::Client::new();
877        poll_token_with(
878            &client,
879            &discovery_at(&base),
880            "tracing-cli",
881            &device_auth(5, 600),
882            recording_sleep(log.clone()),
883        )
884        .await
885        .expect("slow_down must not be fatal");
886
887        // First wait uses the advertised interval; every wait after the
888        // slow_down is permanently +5s.
889        assert_eq!(*log.lock().unwrap(), vec![5, 10, 10]);
890    }
891
892    #[tokio::test]
893    async fn expired_token_is_terminal_with_its_own_message() {
894        let (base, _rx) = spawn_seq(vec![http_json(
895            "400 Bad Request",
896            r#"{"error":"expired_token"}"#,
897        )]);
898        let client = reqwest::Client::new();
899        let err = poll_token_with(
900            &client,
901            &discovery_at(&base),
902            "tracing-cli",
903            &device_auth(5, 600),
904            recording_sleep(Arc::new(Mutex::new(Vec::new()))),
905        )
906        .await
907        .expect_err("expired_token must be terminal");
908
909        assert!(matches!(err, OidcError::DeviceCodeExpired), "got {err:?}");
910        assert!(
911            err.to_string().contains("expired"),
912            "message must say the code expired: {err}"
913        );
914        assert!(
915            !err.to_string().contains("denied"),
916            "expired must not read like a denial: {err}"
917        );
918    }
919
920    #[tokio::test]
921    async fn access_denied_is_terminal_with_its_own_message() {
922        let (base, _rx) = spawn_seq(vec![http_json(
923            "400 Bad Request",
924            r#"{"error":"access_denied"}"#,
925        )]);
926        let client = reqwest::Client::new();
927        let err = poll_token_with(
928            &client,
929            &discovery_at(&base),
930            "tracing-cli",
931            &device_auth(5, 600),
932            recording_sleep(Arc::new(Mutex::new(Vec::new()))),
933        )
934        .await
935        .expect_err("access_denied must be terminal");
936
937        assert!(matches!(err, OidcError::AccessDenied), "got {err:?}");
938        assert!(
939            err.to_string().contains("denied"),
940            "message must say the login was denied: {err}"
941        );
942        assert!(
943            !err.to_string().contains("expired"),
944            "denial must not read like an expiry: {err}"
945        );
946    }
947
948    #[tokio::test]
949    async fn poll_gives_up_after_the_device_codes_own_expiry() {
950        // expires_in=10 with interval=5 allows exactly two polls; a third
951        // response is provided to prove it is never requested.
952        let pending = || http_json("400 Bad Request", r#"{"error":"authorization_pending"}"#);
953        let (base, rx) = spawn_seq(vec![pending(), pending(), pending()]);
954        let log = Arc::new(Mutex::new(Vec::new()));
955        let client = reqwest::Client::new();
956        let err = poll_token_with(
957            &client,
958            &discovery_at(&base),
959            "tracing-cli",
960            &device_auth(5, 10),
961            recording_sleep(log.clone()),
962        )
963        .await
964        .expect_err("must give up once the device code's own lifetime is spent");
965
966        assert!(
967            matches!(err, OidcError::PollTimeout { waited_secs: 10 }),
968            "got {err:?}"
969        );
970        assert_eq!(*log.lock().unwrap(), vec![5, 5]);
971        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
972        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
973        assert!(
974            rx.recv_timeout(Duration::from_millis(200)).is_err(),
975            "the budget must cap polling; a third poll went out"
976        );
977    }
978
979    #[tokio::test]
980    async fn discovery_rejects_mismatched_issuer_naming_both_values() {
981        // The document self-reports a DIFFERENT realm than the one we asked
982        // for; the mismatch must be refused rather than silently followed.
983        let (base, _rx) = spawn_seq(vec![http_json(
984            "200 OK",
985            r#"{"issuer":"https://idp.test/realms/other","token_endpoint":"https://idp.test/token"}"#,
986        )]);
987        let client = reqwest::Client::new();
988        let err = discover(&client, &base)
989            .await
990            .expect_err("a self-reported issuer mismatch must be rejected");
991
992        let msg = err.to_string();
993        assert!(
994            msg.contains(&base),
995            "error must name the expected issuer ({base}): {msg}"
996        );
997        assert!(
998            msg.contains("https://idp.test/realms/other"),
999            "error must name the issuer found in the document: {msg}"
1000        );
1001    }
1002
1003    #[tokio::test]
1004    async fn discovery_accepts_issuer_differing_only_by_trailing_slash() {
1005        // `spawn_seq_with` because the document must self-report the URL it is
1006        // served from, which is only known once the port is bound.
1007        let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1008            vec![http_json(
1009                "200 OK",
1010                // Same issuer as requested, plus a trailing slash.
1011                &format!(
1012                    r#"{{"issuer":"{base}/","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device","revocation_endpoint":"{base}/revoke"}}"#
1013                ),
1014            )]
1015        });
1016        let client = reqwest::Client::new();
1017        let disc = discover(&client, &format!("{base}/"))
1018            .await
1019            .expect("trailing slashes must be canonicalised away, not treated as a mismatch");
1020        assert_eq!(disc.token_endpoint, format!("{base}/token"));
1021        assert_eq!(disc.revocation_endpoint, Some(format!("{base}/revoke")));
1022    }
1023
1024    /// "No Keycloak here" is a 200 with `oidc_enabled: false`, and it is
1025    /// PERMANENT: the user must switch to an API key. (The server answers 200
1026    /// rather than 503 because a 503 from a healthy server fails the pod out of
1027    /// its load balancer and trips 5xx SLO alerts.)
1028    /// An `http://` issuer would put the long-lived `offline_access` refresh
1029    /// token on the wire in clear text, so discovery refuses before it even
1030    /// fetches the document. (Nothing is spawned here: reaching the assertion
1031    /// proves no request was attempted.)
1032    #[tokio::test]
1033    async fn discovery_refuses_a_plaintext_issuer() {
1034        let client = reqwest::Client::new();
1035        let err = discover(&client, "http://idp.example.com/realms/v")
1036            .await
1037            .expect_err("a plaintext issuer must be refused");
1038        assert!(
1039            matches!(err, OidcError::InsecureIssuer { .. }),
1040            "got {err:?}"
1041        );
1042        let msg = err.to_string();
1043        assert!(
1044            msg.contains("refresh token") && msg.contains("https"),
1045            "{msg}"
1046        );
1047    }
1048
1049    /// ...but a loopback issuer over http is a normal local-development setup
1050    /// and must keep working: the token never leaves the machine.
1051    #[tokio::test]
1052    async fn discovery_allows_a_loopback_issuer_over_http() {
1053        let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1054            vec![http_json(
1055                "200 OK",
1056                &format!(r#"{{"issuer":"{base}","token_endpoint":"{base}/token"}}"#),
1057            )]
1058        });
1059        // `spawn_seq` binds 127.0.0.1, so this exercises the loopback exemption.
1060        assert!(base.starts_with("http://127.0.0.1"));
1061        let client = reqwest::Client::new();
1062        discover(&client, &base)
1063            .await
1064            .expect("loopback http must stay usable for local development");
1065    }
1066
1067    /// A document that names another host as its token endpoint would collect
1068    /// the refresh token there. Refused, naming the endpoint and the issuer.
1069    #[tokio::test]
1070    async fn discovery_rejects_an_endpoint_on_another_origin() {
1071        let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1072            vec![http_json(
1073                "200 OK",
1074                &format!(
1075                    r#"{{"issuer":"{base}","token_endpoint":"https://evil.example.com/token"}}"#
1076                ),
1077            )]
1078        });
1079        let client = reqwest::Client::new();
1080        let err = discover(&client, &base)
1081            .await
1082            .expect_err("a token endpoint on another origin must be refused");
1083        assert!(
1084            matches!(err, OidcError::EndpointOriginMismatch { what: "token", .. }),
1085            "got {err:?}"
1086        );
1087        let msg = err.to_string();
1088        assert!(
1089            msg.contains("evil.example.com"),
1090            "must name the endpoint: {msg}"
1091        );
1092        assert!(msg.contains(&base), "must name the issuer: {msg}");
1093    }
1094
1095    /// The same check covers the endpoints that are optional — the revocation
1096    /// endpoint also receives the refresh token.
1097    #[tokio::test]
1098    async fn discovery_rejects_an_offsite_revocation_endpoint() {
1099        let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1100            vec![http_json(
1101                "200 OK",
1102                &format!(
1103                    r#"{{"issuer":"{base}","token_endpoint":"{base}/token","revocation_endpoint":"https://evil.example.com/revoke"}}"#
1104                ),
1105            )]
1106        });
1107        let client = reqwest::Client::new();
1108        let err = discover(&client, &base).await.unwrap_err();
1109        assert!(
1110            matches!(
1111                err,
1112                OidcError::EndpointOriginMismatch {
1113                    what: "revocation",
1114                    ..
1115                }
1116            ),
1117            "got {err:?}"
1118        );
1119    }
1120
1121    /// A port or scheme difference is a different origin too — `https://host` and
1122    /// `https://host:8443` are not interchangeable for credential delivery.
1123    #[tokio::test]
1124    async fn discovery_treats_a_different_port_as_a_different_origin() {
1125        let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1126            // Same scheme and host as the issuer, different port. A fixed port
1127            // rather than one derived from `base`: prefixing a digit onto an
1128            // ephemeral port can exceed 65535, which would fail URL parsing and
1129            // pass this test for the wrong reason.
1130            vec![http_json(
1131                "200 OK",
1132                &format!(r#"{{"issuer":"{base}","token_endpoint":"http://127.0.0.1:9/token"}}"#),
1133            )]
1134        });
1135        let client = reqwest::Client::new();
1136        let err = discover(&client, &base).await.unwrap_err();
1137        assert!(
1138            matches!(err, OidcError::EndpointOriginMismatch { .. }),
1139            "got {err:?}"
1140        );
1141    }
1142
1143    /// The loopback exemption by name as well as by address: the
1144    /// server-backed test above only exercises `127.0.0.1`.
1145    #[test]
1146    fn require_secure_exempts_loopback_by_name_and_address() {
1147        for allowed in [
1148            "https://idp.example.com/realms/v",
1149            "http://localhost:8080/realms/v",
1150            "http://keycloak.localhost/realms/v",
1151            "http://127.0.0.1:8080/realms/v",
1152            "http://[::1]:8080/realms/v",
1153        ] {
1154            require_secure(&Url::parse(allowed).unwrap())
1155                .unwrap_or_else(|e| panic!("{allowed} must be allowed: {e}"));
1156        }
1157        for refused in [
1158            "http://idp.example.com/realms/v",
1159            // Not loopback despite the name resembling it.
1160            "http://localhost.evil.example.com/realms/v",
1161            "http://10.0.0.5:8080/realms/v",
1162        ] {
1163            let err = require_secure(&Url::parse(refused).unwrap())
1164                .expect_err("{refused} must be refused");
1165            assert!(matches!(err, OidcError::InsecureIssuer { .. }), "{refused}");
1166        }
1167    }
1168
1169    /// `open::that` hands the URL to the desktop's registered handler, so only
1170    /// the two schemes a verification URI is legitimately expressed in may pass.
1171    #[test]
1172    fn is_browser_safe_allows_only_http_and_https() {
1173        assert!(is_browser_safe("https://idp.example.com/device?code=X"));
1174        assert!(is_browser_safe("http://localhost:8080/device"));
1175
1176        for hostile in [
1177            "file:///etc/passwd",
1178            "file:///Users/me/.ssh/id_rsa",
1179            "javascript:alert(1)",
1180            "data:text/html,<script>alert(1)</script>",
1181            "vscode://file/etc/passwd",
1182            "smb://attacker.example.com/share",
1183            "not a url at all",
1184            "",
1185        ] {
1186            assert!(
1187                !is_browser_safe(hostile),
1188                "{hostile} must not be handed to the desktop URL handler"
1189            );
1190        }
1191    }
1192
1193    #[tokio::test]
1194    async fn public_config_oidc_disabled_is_permanent_no_keycloak() {
1195        let (base, _rx) = spawn_seq(vec![http_json("200 OK", r#"{"oidc_enabled":false}"#)]);
1196        let client = reqwest::Client::new();
1197        let err = fetch_public_config(&client, &base)
1198            .await
1199            .expect_err("oidc_enabled:false must not parse as a usable config");
1200        assert!(matches!(err, OidcError::NoKeycloak), "got {err:?}");
1201    }
1202
1203    /// A 5xx is the server (or an intermediary in front of it) being unhealthy:
1204    /// retryable, and never phrased as "go get an API key". This branch stays
1205    /// even though the not-configured case moved to 200, because a web proxy
1206    /// still answers 503 when the backend is down.
1207    #[tokio::test]
1208    async fn public_config_5xx_is_transient_not_no_keycloak() {
1209        for status in [
1210            "503 Service Unavailable",
1211            "502 Bad Gateway",
1212            "500 Internal Server Error",
1213        ] {
1214            let (base, _rx) = spawn_seq(vec![http_json(status, r#"{"error":"backend down"}"#)]);
1215            let client = reqwest::Client::new();
1216            let err = fetch_public_config(&client, &base).await.unwrap_err();
1217            assert!(
1218                matches!(err, OidcError::IdpUnavailable { .. }),
1219                "{status} must be the retryable variant; got {err:?}"
1220            );
1221            let msg = err.to_string();
1222            assert!(
1223                msg.contains("temporarily unavailable") && msg.contains("retry"),
1224                "message must read as retryable: {msg}"
1225            );
1226            assert!(
1227                !msg.to_lowercase().contains("api key"),
1228                "must not send the user off to get an API key: {msg}"
1229            );
1230        }
1231    }
1232
1233    /// A 5xx body is not parsed at all now, so a proxy's HTML error page or an
1234    /// empty body must still land in the retryable branch — never the permanent
1235    /// one, which is the stronger claim.
1236    #[tokio::test]
1237    async fn public_config_5xx_with_unparseable_body_is_transient() {
1238        for body in ["", "not json at all", "<html>502 Bad Gateway</html>"] {
1239            let (base, _rx) = spawn_seq(vec![http_json("503 Service Unavailable", body)]);
1240            let client = reqwest::Client::new();
1241            let err = fetch_public_config(&client, &base).await.unwrap_err();
1242            assert!(
1243                matches!(err, OidcError::IdpUnavailable { .. }),
1244                "body {body:?} must yield the retryable variant, got {err:?}"
1245            );
1246        }
1247    }
1248
1249    #[tokio::test]
1250    async fn public_config_200_parses_issuer_client_id_and_audience() {
1251        let (base, rx) = spawn_seq(vec![http_json(
1252            "200 OK",
1253            r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/visdom","audience":"tracevault","cli_client_id":"tracing-cli"}"#,
1254        )]);
1255        let client = reqwest::Client::new();
1256        let cfg = fetch_public_config(&client, &format!("{base}/"))
1257            .await
1258            .unwrap();
1259        assert_eq!(cfg.issuer, "https://idp.test/realms/visdom");
1260        assert_eq!(cfg.cli_client_id, "tracing-cli");
1261        assert_eq!(cfg.audience.as_deref(), Some("tracevault"));
1262        let req = rx.recv_timeout(RECV_TIMEOUT).unwrap();
1263        assert!(
1264            req.contains("GET /api/v1/auth/public-config"),
1265            "unexpected request: {req}"
1266        );
1267    }
1268
1269    /// A server that omits `audience` is still usable — it only costs the
1270    /// sharper wrong-audience diagnosis.
1271    #[tokio::test]
1272    async fn public_config_without_audience_still_resolves() {
1273        let (base, _rx) = spawn_seq(vec![http_json(
1274            "200 OK",
1275            r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v","cli_client_id":"tracing-cli"}"#,
1276        )]);
1277        let client = reqwest::Client::new();
1278        let cfg = fetch_public_config(&client, &base).await.unwrap();
1279        assert_eq!(cfg.audience, None);
1280        assert_eq!(cfg.bazaar_mcp_url, None);
1281    }
1282
1283    #[tokio::test]
1284    async fn public_config_with_bazaar_mcp_url() {
1285        let (base, _rx) = spawn_seq(vec![http_json(
1286            "200 OK",
1287            r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v","cli_client_id":"tracing-cli","bazaar_mcp_url":"https://ctx.example.com/mcp/remote"}"#,
1288        )]);
1289        let client = reqwest::Client::new();
1290        let cfg = fetch_public_config(&client, &base).await.unwrap();
1291        assert_eq!(
1292            cfg.bazaar_mcp_url.as_deref(),
1293            Some("https://ctx.example.com/mcp/remote")
1294        );
1295    }
1296
1297    /// `oidc_enabled: true` with a field missing is a misconfigured server.
1298    /// Defaulting to an empty string would send the device authorization to a
1299    /// nonsense URL and fail with something unrelated to the real cause.
1300    #[tokio::test]
1301    async fn public_config_enabled_but_incomplete_is_a_named_error() {
1302        for (body, field) in [
1303            (
1304                r#"{"oidc_enabled":true,"cli_client_id":"tracing-cli"}"#,
1305                "issuer",
1306            ),
1307            (
1308                r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v"}"#,
1309                "cli_client_id",
1310            ),
1311            (
1312                r#"{"oidc_enabled":true,"issuer":"  ","cli_client_id":"tracing-cli"}"#,
1313                "issuer",
1314            ),
1315        ] {
1316            let (base, _rx) = spawn_seq(vec![http_json("200 OK", body)]);
1317            let client = reqwest::Client::new();
1318            let err = fetch_public_config(&client, &base).await.unwrap_err();
1319            let msg = err.to_string();
1320            assert!(
1321                msg.contains(field) && msg.contains("misconfigured"),
1322                "must name the missing field `{field}`: {msg}"
1323            );
1324            assert!(
1325                !matches!(err, OidcError::NoKeycloak),
1326                "an incomplete config is not the same as no Keycloak: {msg}"
1327            );
1328        }
1329    }
1330
1331    #[tokio::test]
1332    async fn device_start_requests_offline_access_scope() {
1333        let (base, rx) = spawn_seq(vec![http_json(
1334            "200 OK",
1335            r#"{"device_code":"dc","user_code":"ABCD-EFGH","verification_uri":"https://idp.test/device","expires_in":600,"interval":5}"#,
1336        )]);
1337        let client = reqwest::Client::new();
1338        let device = device_start(&client, &discovery_at(&base), "tracing-cli")
1339            .await
1340            .unwrap();
1341        assert_eq!(device.user_code, "ABCD-EFGH");
1342        let req = rx.recv_timeout(RECV_TIMEOUT).unwrap();
1343        assert!(
1344            req.contains("offline_access"),
1345            "offline_access is what yields a refresh token: {req}"
1346        );
1347        assert!(req.contains("client_id=tracing-cli"));
1348    }
1349
1350    #[tokio::test]
1351    async fn refresh_invalid_grant_maps_to_session_expired() {
1352        let (base, _rx) = spawn_seq(vec![http_json(
1353            "400 Bad Request",
1354            r#"{"error":"invalid_grant","error_description":"Token is not active"}"#,
1355        )]);
1356        let client = reqwest::Client::new();
1357        let err = refresh(&client, &discovery_at(&base), "tracing-cli", "rt")
1358            .await
1359            .expect_err("invalid_grant must be a distinct 'session expired' error");
1360        assert!(matches!(err, OidcError::SessionExpired), "got {err:?}");
1361        assert!(
1362            err.to_string().contains("tracevault login"),
1363            "message must tell the user how to recover: {err}"
1364        );
1365    }
1366
1367    #[tokio::test]
1368    async fn revoke_sends_refresh_token_hint() {
1369        let (base, rx) = spawn_seq(vec![http_json("200 OK", "{}")]);
1370        let client = reqwest::Client::new();
1371        revoke(&client, &discovery_at(&base), "tracing-cli", "rt")
1372            .await
1373            .unwrap();
1374        let req = rx.recv_timeout(RECV_TIMEOUT).unwrap();
1375        assert!(req.contains("POST /revoke"), "unexpected request: {req}");
1376        assert!(req.contains("token_type_hint=refresh_token"), "{req}");
1377    }
1378
1379    #[tokio::test]
1380    async fn revoke_without_endpoint_is_a_named_error() {
1381        let disc = Discovery {
1382            device_authorization_endpoint: None,
1383            token_endpoint: "https://idp.test/token".into(),
1384            revocation_endpoint: None,
1385        };
1386        let client = reqwest::Client::new();
1387        let err = revoke(&client, &disc, "tracing-cli", "rt")
1388            .await
1389            .expect_err("no revocation endpoint must be an explicit error");
1390        assert!(err.to_string().contains("revocation"), "{err}");
1391    }
1392
1393    /// Secrets must not be reachable through `{:?}`, which is how they would
1394    /// most plausibly end up in a log or a panic message.
1395    #[test]
1396    fn debug_impls_redact_secrets() {
1397        let device = device_auth(5, 600);
1398        let dbg = format!("{device:?}");
1399        assert!(!dbg.contains("dev-code"), "device_code leaked: {dbg}");
1400
1401        let tokens = TokenSet {
1402            access_token: "super-secret-access".into(),
1403            refresh_token: Some("super-secret-refresh".into()),
1404            expires_in: 300,
1405        };
1406        let dbg = format!("{tokens:?}");
1407        assert!(!dbg.contains("super-secret-access"), "access leaked: {dbg}");
1408        assert!(
1409            !dbg.contains("super-secret-refresh"),
1410            "refresh leaked: {dbg}"
1411        );
1412    }
1413
1414    /// Unpadded base64url, so a fixture JWT can be assembled from a readable
1415    /// payload instead of a pasted blob. Test-only; production only ever decodes.
1416    fn base64url_encode(bytes: &[u8]) -> String {
1417        const ALPHABET: &[u8; 64] =
1418            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1419        let mut out = String::new();
1420        for chunk in bytes.chunks(3) {
1421            let b = [
1422                chunk[0],
1423                *chunk.get(1).unwrap_or(&0),
1424                *chunk.get(2).unwrap_or(&0),
1425            ];
1426            let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
1427            // Unpadded: emit only the characters backed by real input bytes —
1428            // 1 byte → 2 chars, 2 → 3, 3 → 4.
1429            for shift in [18, 12, 6, 0].iter().take(chunk.len() + 1) {
1430                out.push(ALPHABET[((n >> shift) & 63) as usize] as char);
1431            }
1432        }
1433        out
1434    }
1435
1436    /// Build an unsigned JWT for the fixtures below from a readable payload.
1437    ///
1438    /// Two reasons not to paste a pre-encoded literal. A base64 blob hides what
1439    /// the fixture asserts — you cannot see which `aud` it claims without decoding
1440    /// it by hand. And a JWT's encoded header is a short fixed prefix that every
1441    /// secret scanner matches on: these fixtures carry nothing secret (the
1442    /// signature is a placeholder `unverified_audiences` never checks), but a
1443    /// scanner cannot know that, and three HIGH findings on one test file is how a
1444    /// repo trains people to wave through "it's only a fixture" — after which a
1445    /// real leak looks the same. Aikido flagged exactly this on `f9ee250`.
1446    fn unsigned_jwt(payload_json: &str) -> String {
1447        format!(
1448            "{}.{}.signature-not-checked",
1449            base64url_encode(br#"{"alg":"none"}"#),
1450            base64url_encode(payload_json.as_bytes())
1451        )
1452    }
1453
1454    /// Anchors the test-only encoder against a value that did not come from it:
1455    /// `bm90LWpzb24` is the payload the "decodes but is not JSON" case below has
1456    /// always used. Without this, a mirrored bug in encode and decode could let
1457    /// every fixture-driven assertion pass while agreeing on the wrong bytes.
1458    #[test]
1459    fn base64url_encode_matches_a_known_value() {
1460        assert_eq!(base64url_encode(b"not-json"), "bm90LWpzb24");
1461        assert_eq!(
1462            base64url_decode(&base64url_encode(b"abc")),
1463            Some(b"abc".to_vec())
1464        );
1465        // Byte counts that exercise every remainder: 1, 2 and 0 mod 3.
1466        for raw in [&b"a"[..], &b"ab"[..], &b"abc"[..], &b"abcd"[..]] {
1467            assert_eq!(
1468                base64url_decode(&base64url_encode(raw)),
1469                Some(raw.to_vec()),
1470                "round trip failed for {raw:?}"
1471            );
1472        }
1473    }
1474
1475    /// Reading `aud` out of a JWT payload: diagnosis only, never validation.
1476    #[test]
1477    fn unverified_audiences_reads_string_and_array_forms() {
1478        assert_eq!(
1479            unverified_audiences(&unsigned_jwt(r#"{"aud":"tracevault","sub":"u"}"#)),
1480            Some(vec!["tracevault".to_string()])
1481        );
1482        assert_eq!(
1483            unverified_audiences(&unsigned_jwt(
1484                r#"{"aud":["account","tracevault"],"sub":"u"}"#
1485            )),
1486            Some(vec!["account".to_string(), "tracevault".to_string()])
1487        );
1488        assert_eq!(
1489            unverified_audiences(&unsigned_jwt(r#"{"aud":"some-other-app"}"#)),
1490            Some(vec!["some-other-app".to_string()])
1491        );
1492    }
1493
1494    /// Anything unexpected must be `None` — "cannot tell" — so the caller falls
1495    /// back to the generic message instead of guessing at a cause.
1496    #[test]
1497    fn unverified_audiences_is_none_when_it_cannot_tell() {
1498        // No `aud` claim.
1499        assert_eq!(unverified_audiences(&unsigned_jwt(r#"{"sub":"u"}"#)), None);
1500        // Not a JWT at all (an opaque token, as some IdPs issue).
1501        assert_eq!(unverified_audiences("opaque-token"), None);
1502        assert_eq!(unverified_audiences(""), None);
1503        // Payload is not base64url.
1504        assert_eq!(unverified_audiences("a.!!!not-base64!!!.c"), None);
1505        // Payload decodes but is not JSON.
1506        assert_eq!(unverified_audiences("a.bm90LWpzb24.c"), None);
1507    }
1508
1509    #[test]
1510    fn base64url_decode_handles_padding_and_rejects_junk() {
1511        assert_eq!(base64url_decode("aGVsbG8"), Some(b"hello".to_vec()));
1512        assert_eq!(base64url_decode("aGVsbG8="), Some(b"hello".to_vec()));
1513        // `-` and `_` are the url-safe substitutions for `+` and `/`:
1514        // 111110 111110 111111 111111 -> 0xFB 0xEF 0xFF.
1515        assert_eq!(base64url_decode("--__"), Some(vec![0xfb, 0xef, 0xff]));
1516        assert!(base64url_decode("not valid!").is_none());
1517    }
1518
1519    #[test]
1520    fn canonical_issuer_trims_whitespace_and_trailing_slashes() {
1521        assert_eq!(
1522            canonical_issuer("  https://idp.test/realms/v//  "),
1523            "https://idp.test/realms/v"
1524        );
1525    }
1526}