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