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