Skip to main content

ruscker_sso/
lib.rs

1//! Sign people in to a Rust backend through a Ruscker portal.
2//!
3//! The portal is an OpenID Connect provider with a narrow profile:
4//! authorization code flow, PKCE `S256`, a confidential client, ID tokens
5//! signed with ES256. This crate is pre-set for exactly that profile so an
6//! integration is three calls:
7//!
8//! 1. [`Client::discover`] once at startup;
9//! 2. [`Client::start_sign_in`] in the "sign in" route — redirect the
10//!    browser to the URL and keep the [`Pending`] value until it returns;
11//! 3. [`Client::finish_sign_in`] in the callback route — it returns the
12//!    verified [`Identity`], from which the application issues its own
13//!    session.
14//!
15//! No cryptography is implemented here: signatures are checked by
16//! `jsonwebtoken` against the provider's published keys, randomness comes
17//! from the operating system (`getrandom`), and the PKCE hash from `sha2`.
18//!
19//! Two address builders complete it: [`Client::sign_out_url`] (the
20//! portal's sign-out page, after the application ended its own session)
21//! and [`Client::password_change_url`] (the portal's "change your
22//! password" page).
23//!
24//! What the crate deliberately does not do: sessions (the portal's tokens
25//! live five minutes and there is no refresh — re-run a sign-in with
26//! [`SignInOptions::prompt`] `"none"` to notice that the portal session
27//! ended), back-channel logout, and deciding what groups and roles mean
28//! inside the application.
29
30use std::collections::{BTreeMap, HashMap};
31use std::sync::{Arc, RwLock};
32use std::time::Duration;
33
34use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
35use base64::Engine as _;
36use jsonwebtoken::jwk::JwkSet;
37use jsonwebtoken::{Algorithm, DecodingKey, Validation};
38use serde::{Deserialize, Serialize};
39use serde_json::{Map, Value};
40use sha2::{Digest, Sha256};
41use subtle::ConstantTimeEq;
42use url::Url;
43
44/// The scopes asked for when [`Config::scopes`] is not called: every claim
45/// the provider offers.
46pub const DEFAULT_SCOPES: &str = "openid profile email groups roles setor";
47
48/// How long any single request to the provider may take. The provider
49/// answers in milliseconds; a hung connection should fail the sign-in
50/// rather than hold the callback request forever.
51const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
52
53/// The longest `state` [`Client::sign_out_url`] accepts, in characters
54/// (the same limit in every package; the portal refuses longer ones).
55pub const MAX_SIGN_OUT_STATE_LEN: usize = 512;
56
57// ---------------------------------------------------------------------------
58// Configuration
59// ---------------------------------------------------------------------------
60
61/// What the portal's administrator gives the system's developers.
62#[derive(Clone)]
63pub struct Config {
64    /// The portal's address, exactly as its discovery document states it
65    /// (e.g. `https://portal.example.org`, including a subpath if any).
66    pub issuer: String,
67    /// The system's id, as registered on the portal.
68    pub client_id: String,
69    /// The secret shown once at registration. Server side only.
70    pub client_secret: String,
71    /// The system's callback URL, exactly as registered.
72    pub redirect_uri: String,
73    /// Space-separated scopes; must contain `openid`.
74    pub scopes: String,
75}
76
77impl Config {
78    /// A configuration with the default scopes ([`DEFAULT_SCOPES`]).
79    pub fn new(
80        issuer: impl Into<String>,
81        client_id: impl Into<String>,
82        client_secret: impl Into<String>,
83        redirect_uri: impl Into<String>,
84    ) -> Self {
85        Config {
86            issuer: issuer.into(),
87            client_id: client_id.into(),
88            client_secret: client_secret.into(),
89            redirect_uri: redirect_uri.into(),
90            scopes: DEFAULT_SCOPES.to_string(),
91        }
92    }
93
94    /// Ask for other scopes than the default (space-separated).
95    pub fn scopes(mut self, scopes: impl Into<String>) -> Self {
96        self.scopes = scopes.into();
97        self
98    }
99}
100
101// Hand-written so the secret never ends up in a log line via `{:?}`.
102impl std::fmt::Debug for Config {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.debug_struct("Config")
105            .field("issuer", &self.issuer)
106            .field("client_id", &self.client_id)
107            .field("client_secret", &"<redacted>")
108            .field("redirect_uri", &self.redirect_uri)
109            .field("scopes", &self.scopes)
110            .finish()
111    }
112}
113
114// ---------------------------------------------------------------------------
115// Errors
116// ---------------------------------------------------------------------------
117
118/// Why a sign-in (or the discovery) failed.
119///
120/// The variants separate the cases an application may want to treat
121/// differently: [`Error::Provider`] is usually the person's situation
122/// (e.g. `access_denied` — not in the system's groups) and deserves a
123/// friendly page; the others mean a stale or forged callback, a
124/// misconfiguration, or an attack, and are best logged and answered with
125/// "please sign in again".
126#[derive(Debug, thiserror::Error)]
127pub enum Error {
128    /// The provider sent the person back with `error=…`.
129    #[error("the provider refused the sign-in: {error}")]
130    Provider {
131        /// The OAuth error code, e.g. `access_denied`.
132        error: String,
133        /// The provider's human-readable explanation, if any.
134        description: Option<String>,
135    },
136    /// The callback's `state` is missing or is not the one this browser
137    /// was given: a stale tab, a second sign-in in another tab, or a
138    /// forged callback. Nothing was sent to the provider.
139    #[error("the callback's state does not match the stored one")]
140    StateMismatch,
141    /// An issuer that is not the configured one: in the callback's `iss`
142    /// parameter, or in the discovery document.
143    #[error("issuer mismatch: expected {expected:?}, got {found:?}")]
144    IssuerMismatch {
145        /// The configured issuer.
146        expected: String,
147        /// The issuer that was presented.
148        found: String,
149    },
150    /// The callback query is malformed (no `code`, a repeated parameter).
151    #[error("malformed callback: {0}")]
152    InvalidCallback(&'static str),
153    /// The token endpoint refused the code exchange.
154    #[error("the token exchange was refused ({status}): {error}")]
155    TokenRefused {
156        /// The HTTP status of the answer.
157        status: u16,
158        /// The OAuth error code: `invalid_client` (wrong secret),
159        /// `invalid_grant` (code used, expired or not ours), …
160        error: String,
161        /// The provider's explanation, if any.
162        description: Option<String>,
163    },
164    /// The ID token failed verification; the string says which check.
165    #[error("invalid ID token: {0}")]
166    InvalidIdToken(String),
167    /// The discovery document or the key set could not be used.
168    #[error("discovery failed: {0}")]
169    Discovery(String),
170    /// A value given to the crate is not acceptable (e.g. a sign-out
171    /// `state` longer than [`MAX_SIGN_OUT_STATE_LEN`] characters). Nothing
172    /// was sent anywhere.
173    #[error("invalid argument: {0}")]
174    InvalidArgument(String),
175    /// The provider could not be reached, or answered something that is
176    /// not the expected JSON.
177    #[error("HTTP error talking to the provider: {0}")]
178    Http(#[from] reqwest::Error),
179}
180
181// ---------------------------------------------------------------------------
182// Values kept between the two halves of a sign-in
183// ---------------------------------------------------------------------------
184
185/// The three values to keep between [`Client::start_sign_in`] and
186/// [`Client::finish_sign_in`], bound to the person's browser.
187///
188/// Serializable so it fits a server-side session or a short-lived signed
189/// (or private) `HttpOnly` cookie. It is not secret in the way a password
190/// is, but it must not be readable or writable by other sites — never put
191/// it in the URL. A cookie for it must be `HttpOnly`, `Secure` and
192/// `SameSite=Lax`; signed or private where the framework offers it.
193#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
194pub struct Pending {
195    state: String,
196    nonce: String,
197    code_verifier: String,
198}
199
200impl Pending {
201    /// A fresh set of values from the OS random source.
202    fn generate() -> Self {
203        Pending { state: random_token(), nonce: random_token(), code_verifier: random_token() }
204    }
205
206    /// The `state` sent with the request (handy for correlating logs).
207    pub fn state(&self) -> &str {
208        &self.state
209    }
210}
211
212// The verifier is the secret half of PKCE; keep it out of `{:?}` output.
213impl std::fmt::Debug for Pending {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        f.debug_struct("Pending").field("state", &self.state).finish_non_exhaustive()
216    }
217}
218
219/// 32 bytes (256 bits) from the operating system's random source, as
220/// base64url without padding: 43 characters of `A-Z a-z 0-9 - _`, which
221/// is valid as a state, a nonce and a PKCE verifier alike.
222fn random_token() -> String {
223    let mut bytes = [0u8; 32];
224    // The OS random source failing is not something a sign-in can recover
225    // from (the `rand` crate panics in the same situation); refusing to
226    // continue beats continuing with predictable values.
227    getrandom::fill(&mut bytes).expect("the operating system's random source is unavailable");
228    URL_SAFE_NO_PAD.encode(bytes)
229}
230
231/// The PKCE `S256` challenge: base64url(SHA-256(verifier)), RFC 7636 §4.2.
232fn pkce_challenge(verifier: &str) -> String {
233    URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
234}
235
236/// Compare two strings without leaking, through timing, how many leading
237/// characters matched.
238///
239/// An empty value never matches: a `Pending` that lost its state or nonce
240/// (a bug, a hand-built value) must not "equal" an absent parameter.
241fn same(a: &str, b: &str) -> bool {
242    if a.is_empty() || b.is_empty() {
243        return false;
244    }
245    a.as_bytes().ct_eq(b.as_bytes()).into()
246}
247
248// ---------------------------------------------------------------------------
249// The identity
250// ---------------------------------------------------------------------------
251
252/// Who signed in, taken from the verified ID token.
253///
254/// Store [`Identity::sub`] as the key to the person: a username can be
255/// reused after an account is deleted, and `email` is neither verified nor
256/// unique.
257#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
258pub struct Identity {
259    /// The person's permanent id on the portal.
260    pub sub: String,
261    /// `preferred_username` (with the `profile` scope).
262    pub username: Option<String>,
263    /// Full name, or the username when the portal has none (with the
264    /// `profile` scope).
265    pub name: Option<String>,
266    /// E-mail, when the account has one and `email` was asked for.
267    pub email: Option<String>,
268    /// Department, when the account has one and `setor` was asked for.
269    pub setor: Option<String>,
270    /// Groups. For a restricted system, only those that give access to it.
271    pub groups: Vec<String>,
272    /// Group → roles the person holds in it; empty when none.
273    pub group_roles: BTreeMap<String, Vec<String>>,
274    /// Every claim of the ID token, as received.
275    pub claims: Map<String, Value>,
276}
277
278impl Identity {
279    /// Build the identity from verified claims. Claims that are absent, or
280    /// of an unexpected type, are left empty rather than failing the
281    /// sign-in: only `sub` is indispensable.
282    fn from_claims(claims: Map<String, Value>) -> Result<Self, Error> {
283        let text = |key: &str| claims.get(key).and_then(Value::as_str).map(str::to_owned);
284        let sub = text("sub")
285            .filter(|s| !s.is_empty())
286            .ok_or_else(|| Error::InvalidIdToken("no sub claim".into()))?;
287        let strings = |v: &Value| -> Vec<String> {
288            v.as_array()
289                .map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
290                .unwrap_or_default()
291        };
292        let groups = claims.get("groups").map(strings).unwrap_or_default();
293        let group_roles = claims
294            .get("group_roles")
295            .and_then(Value::as_object)
296            .map(|m| m.iter().map(|(g, r)| (g.clone(), strings(r))).collect())
297            .unwrap_or_default();
298        Ok(Identity {
299            sub,
300            username: text("preferred_username"),
301            name: text("name"),
302            email: text("email"),
303            setor: text("setor"),
304            groups,
305            group_roles,
306            claims,
307        })
308    }
309
310    /// Whether the person is in `group`.
311    pub fn has_group(&self, group: &str) -> bool {
312        self.groups.iter().any(|g| g == group)
313    }
314
315    /// Whether the person holds `role` in `group`.
316    pub fn has_role(&self, group: &str, role: &str) -> bool {
317        self.roles(group).iter().any(|r| r == role)
318    }
319
320    /// The roles the person holds in `group` (empty when none).
321    pub fn roles(&self, group: &str) -> &[String] {
322        self.group_roles.get(group).map(Vec::as_slice).unwrap_or(&[])
323    }
324}
325
326// ---------------------------------------------------------------------------
327// The client
328// ---------------------------------------------------------------------------
329
330/// The part of the discovery document this crate uses.
331#[derive(Debug, Clone, Deserialize)]
332struct Metadata {
333    issuer: String,
334    authorization_endpoint: String,
335    token_endpoint: String,
336    jwks_uri: String,
337    /// RP-Initiated Logout. Absent on portals older than sign-out support,
338    /// so optional here; [`Client::sign_out_url`] reports its absence.
339    #[serde(default)]
340    end_session_endpoint: Option<String>,
341}
342
343/// Options for [`Client::start_sign_in_with`]. The default is what
344/// [`Client::start_sign_in`] sends.
345#[derive(Debug, Clone, Default, PartialEq, Eq)]
346#[non_exhaustive]
347pub struct SignInOptions {
348    /// The OpenID Connect `prompt` parameter; omitted when `None`. The only
349    /// value the portal gives a meaning to is `"none"`: answer with an
350    /// error (`login_required`, …) instead of showing a sign-in page when
351    /// the person would have to interact. Use it to check, without a page,
352    /// whether the portal session is still alive.
353    pub prompt: Option<String>,
354}
355
356impl SignInOptions {
357    /// The default options (no `prompt`).
358    pub fn new() -> Self {
359        Self::default()
360    }
361
362    /// Send `prompt=<value>` — in practice `"none"`.
363    pub fn prompt(mut self, value: impl Into<String>) -> Self {
364        self.prompt = Some(value.into());
365        self
366    }
367}
368
369/// Options for [`Client::sign_out_url`]; every field is optional and is
370/// left out of the address when `None`.
371#[derive(Clone, Default, PartialEq, Eq)]
372#[non_exhaustive]
373pub struct SignOutOptions {
374    /// Where the portal sends the browser afterwards. Must be one of the
375    /// client's *Return addresses after sign-out* on the portal, exactly,
376    /// or the portal refuses the request.
377    pub post_logout_redirect_uri: Option<String>,
378    /// Echoed back on that return, at most [`MAX_SIGN_OUT_STATE_LEN`]
379    /// characters.
380    pub state: Option<String>,
381    /// The raw ID token, if the application kept it.
382    pub id_token_hint: Option<String>,
383}
384
385impl SignOutOptions {
386    /// No optional values: the address carries only `client_id`.
387    pub fn new() -> Self {
388        Self::default()
389    }
390
391    /// Set `post_logout_redirect_uri`.
392    pub fn post_logout_redirect_uri(mut self, uri: impl Into<String>) -> Self {
393        self.post_logout_redirect_uri = Some(uri.into());
394        self
395    }
396
397    /// Set `state`.
398    pub fn state(mut self, state: impl Into<String>) -> Self {
399        self.state = Some(state.into());
400        self
401    }
402
403    /// Set `id_token_hint`.
404    pub fn id_token_hint(mut self, id_token: impl Into<String>) -> Self {
405        self.id_token_hint = Some(id_token.into());
406        self
407    }
408}
409
410// The ID token names the person; keep it out of `{:?}` output.
411impl std::fmt::Debug for SignOutOptions {
412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413        f.debug_struct("SignOutOptions")
414            .field("post_logout_redirect_uri", &self.post_logout_redirect_uri)
415            .field("state", &self.state)
416            .field("id_token_hint", &self.id_token_hint.as_ref().map(|_| "<redacted>"))
417            .finish()
418    }
419}
420
421/// The token endpoint's answer. Only the ID token is used; the access
422/// token is valid five minutes and only at `/oauth/userinfo`.
423#[derive(Clone, Deserialize)]
424pub struct TokenResponse {
425    /// The signed ID token (a JWT). Verify it with
426    /// [`Client::verify_id_token`] before trusting anything in it.
427    pub id_token: String,
428    /// The access token, for `/oauth/userinfo`.
429    pub access_token: Option<String>,
430    /// The scopes granted.
431    pub scope: Option<String>,
432}
433
434impl std::fmt::Debug for TokenResponse {
435    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
436        f.debug_struct("TokenResponse").field("scope", &self.scope).finish_non_exhaustive()
437    }
438}
439
440/// An OAuth error body, `{"error": …, "error_description": …}`.
441#[derive(Deserialize)]
442struct OAuthError {
443    error: String,
444    error_description: Option<String>,
445}
446
447/// A client for one registered system. Cheap to clone (it is an `Arc`
448/// inside), so put it in the application's shared state.
449#[derive(Clone, Debug)]
450pub struct Client {
451    inner: Arc<Inner>,
452}
453
454#[derive(Debug)]
455struct Inner {
456    config: Config,
457    metadata: Metadata,
458    http: reqwest::Client,
459    /// The provider's public keys, refreshed once when a token names a key
460    /// id we have not seen (the provider can rotate keys). A std lock is
461    /// enough: it is never held across an `.await`.
462    jwks: RwLock<Arc<JwkSet>>,
463}
464
465impl Client {
466    /// Read the provider's discovery document and key set, once.
467    ///
468    /// Fails if the document's `issuer` is not exactly the configured one
469    /// — the same string is compared in every token, so a mismatch here
470    /// would only fail later, on every sign-in.
471    pub async fn discover(config: Config) -> Result<Self, Error> {
472        let http = reqwest::Client::builder()
473            .timeout(HTTP_TIMEOUT)
474            // The token endpoint never redirects; following a redirect
475            // would send the code (and the secret) somewhere else.
476            .redirect(reqwest::redirect::Policy::none())
477            .build()?;
478        Self::discover_with(config, http).await
479    }
480
481    /// [`Client::discover`] with an HTTP client of your own (proxy, custom
482    /// roots, timeouts). Disable redirects on it.
483    pub async fn discover_with(config: Config, http: reqwest::Client) -> Result<Self, Error> {
484        let url = format!("{}/.well-known/openid-configuration", config.issuer.trim_end_matches('/'));
485        let metadata: Metadata = http.get(&url).send().await?.error_for_status()?.json().await?;
486        check_metadata(&config, &metadata)?;
487        let jwks = fetch_jwks(&http, &metadata.jwks_uri).await?;
488        Ok(Self::from_parts(config, metadata, http, jwks))
489    }
490
491    fn from_parts(config: Config, metadata: Metadata, http: reqwest::Client, jwks: JwkSet) -> Self {
492        Client { inner: Arc::new(Inner { config, metadata, http, jwks: RwLock::new(Arc::new(jwks)) }) }
493    }
494
495    /// The configuration this client was built with.
496    pub fn config(&self) -> &Config {
497        &self.inner.config
498    }
499
500    /// Begin a sign-in: the URL to redirect the browser to, and the values
501    /// to keep (bound to that browser) until it comes back.
502    ///
503    /// Panics only if the operating system's random source is unavailable.
504    pub fn start_sign_in(&self) -> (Url, Pending) {
505        self.start_sign_in_with(&SignInOptions::default())
506    }
507
508    /// [`Client::start_sign_in`] with options, e.g.
509    /// `SignInOptions::new().prompt("none")` to check silently whether the
510    /// portal session is still alive.
511    ///
512    /// Panics only if the operating system's random source is unavailable.
513    pub fn start_sign_in_with(&self, options: &SignInOptions) -> (Url, Pending) {
514        let pending = Pending::generate();
515        let config = &self.inner.config;
516        let mut url = Url::parse(&self.inner.metadata.authorization_endpoint)
517            .expect("authorization_endpoint was validated at discovery");
518        url.query_pairs_mut()
519            .append_pair("response_type", "code")
520            .append_pair("client_id", &config.client_id)
521            .append_pair("redirect_uri", &config.redirect_uri)
522            .append_pair("scope", &config.scopes)
523            .append_pair("state", &pending.state)
524            .append_pair("nonce", &pending.nonce)
525            .append_pair("code_challenge", &pkce_challenge(&pending.code_verifier))
526            .append_pair("code_challenge_method", "S256");
527        if let Some(prompt) = &options.prompt {
528            url.query_pairs_mut().append_pair("prompt", prompt);
529        }
530        (url, pending)
531    }
532
533    /// The address of the portal's sign-out page (OpenID Connect
534    /// RP-Initiated Logout). End the application's OWN session first, then
535    /// redirect the browser here.
536    ///
537    /// The query carries `client_id`, then `id_token_hint`,
538    /// `post_logout_redirect_uri` and `state`, each only when given. The
539    /// portal asks the person before ending its session; someone not signed
540    /// in there goes straight back (with `state`, when one was sent).
541    ///
542    /// The endpoint is the discovery document's `end_session_endpoint`,
543    /// read at [`Client::discover`]: no network call here. A portal that
544    /// does not announce one is older than this feature, and the answer is
545    /// [`Error::Discovery`] rather than a guessed path. A `state` longer
546    /// than [`MAX_SIGN_OUT_STATE_LEN`] characters is
547    /// [`Error::InvalidArgument`].
548    pub fn sign_out_url(&self, options: &SignOutOptions) -> Result<Url, Error> {
549        if let Some(state) = &options.state {
550            if state.chars().count() > MAX_SIGN_OUT_STATE_LEN {
551                return Err(Error::InvalidArgument(format!(
552                    "the sign-out state is longer than {MAX_SIGN_OUT_STATE_LEN} characters"
553                )));
554            }
555        }
556        let endpoint = self.inner.metadata.end_session_endpoint.as_deref().ok_or_else(|| {
557            Error::Discovery(
558                "the discovery document has no end_session_endpoint (the portal is older than sign-out support)"
559                    .into(),
560            )
561        })?;
562        let mut url =
563            Url::parse(endpoint).map_err(|e| Error::Discovery(format!("end_session_endpoint is not a URL: {e}")))?;
564        {
565            // Order is fixed by the contract: client_id, then each optional
566            // value only when given.
567            let mut query = url.query_pairs_mut();
568            query.append_pair("client_id", &self.inner.config.client_id);
569            for (name, value) in [
570                ("id_token_hint", &options.id_token_hint),
571                ("post_logout_redirect_uri", &options.post_logout_redirect_uri),
572                ("state", &options.state),
573            ] {
574                if let Some(value) = value {
575                    query.append_pair(name, value);
576                }
577            }
578        }
579        Ok(url)
580    }
581
582    /// The address of the portal's "change your password" page:
583    /// `{issuer}/admin/account/password?client_id=…`.
584    ///
585    /// A fixed path, not in discovery, so no network call. The portal signs
586    /// the person in if needed, and its page links back to the client's
587    /// registered *System address*.
588    pub fn password_change_url(&self) -> String {
589        let config = &self.inner.config;
590        let client_id = url::form_urlencoded::byte_serialize(config.client_id.as_bytes()).collect::<String>();
591        format!("{}/admin/account/password?client_id={client_id}", config.issuer.trim_end_matches('/'))
592    }
593
594    /// Finish a sign-in from the callback's query string (with or without
595    /// the leading `?`; a full URL is accepted too) and the stored
596    /// [`Pending`] values.
597    ///
598    /// The checks run in this order, and the first failure stops it:
599    /// an `error` parameter; `state`; `iss`; the code exchange; the ID
600    /// token (signature, ES256, `iss`, `aud`, `exp`, `nonce`). Nothing
601    /// reaches the network before `state` and `iss` have passed. Whatever
602    /// the outcome, the [`Pending`] value must not be used again: drop it
603    /// from the session — a code is single-use and is never retried.
604    pub async fn finish_sign_in(&self, callback_query: &str, pending: &Pending) -> Result<Identity, Error> {
605        let code = self.check_callback(callback_query, pending)?;
606        let tokens = self.exchange_code(&code, &pending.code_verifier).await?;
607        self.verify_id_token(&tokens.id_token, &pending.nonce).await
608    }
609
610    /// Steps 1–3 of [`Client::finish_sign_in`], with no network: returns
611    /// the code when the callback is genuine.
612    fn check_callback(&self, callback_query: &str, pending: &Pending) -> Result<String, Error> {
613        let params = parse_query(callback_query)?;
614        if let Some(error) = params.get("error") {
615            return Err(Error::Provider {
616                error: error.clone(),
617                description: params.get("error_description").cloned(),
618            });
619        }
620        match params.get("state") {
621            Some(state) if same(state, &pending.state) => {}
622            _ => return Err(Error::StateMismatch),
623        }
624        let issuer = &self.inner.config.issuer;
625        // The portal always says who it is (RFC 9207). Requiring it means a
626        // callback from anywhere else cannot be mistaken for the portal's.
627        match params.get("iss") {
628            Some(iss) if iss == issuer => {}
629            other => {
630                return Err(Error::IssuerMismatch {
631                    expected: issuer.clone(),
632                    found: other.cloned().unwrap_or_else(|| "(absent)".into()),
633                });
634            }
635        }
636        params.get("code").filter(|c| !c.is_empty()).cloned().ok_or(Error::InvalidCallback("no code"))
637    }
638
639    /// Exchange an authorization code at the token endpoint, authenticating
640    /// with the client secret over HTTP Basic. One attempt only: the
641    /// provider spends the code whatever the outcome.
642    ///
643    /// Most applications call [`Client::finish_sign_in`] instead; this is
644    /// public for tests and for code that needs the raw tokens.
645    pub async fn exchange_code(&self, code: &str, code_verifier: &str) -> Result<TokenResponse, Error> {
646        let config = &self.inner.config;
647        let response = self
648            .inner
649            .http
650            .post(&self.inner.metadata.token_endpoint)
651            .header(reqwest::header::AUTHORIZATION, basic_auth(&config.client_id, &config.client_secret))
652            .form(&[
653                ("grant_type", "authorization_code"),
654                ("code", code),
655                ("redirect_uri", config.redirect_uri.as_str()),
656                ("code_verifier", code_verifier),
657            ])
658            .send()
659            .await?;
660        let status = response.status();
661        if status.is_success() {
662            return Ok(response.json().await?);
663        }
664        // An error answer is JSON `{error, error_description}`, except the
665        // 413 for an oversized body, which has none.
666        let body = response.bytes().await.unwrap_or_default();
667        let parsed: Option<OAuthError> = serde_json::from_slice(&body).ok();
668        Err(Error::TokenRefused {
669            status: status.as_u16(),
670            error: parsed.as_ref().map_or_else(|| format!("http_{}", status.as_u16()), |e| e.error.clone()),
671            description: parsed.and_then(|e| e.error_description),
672        })
673    }
674
675    /// Verify an ID token and turn it into an [`Identity`]: signature
676    /// against the provider's keys, algorithm ES256 only (the token's own
677    /// `alg` header never chooses it), `iss` = the issuer, `aud` = this
678    /// client's id, `exp`, and `nonce` = the one sent.
679    pub async fn verify_id_token(&self, id_token: &str, nonce: &str) -> Result<Identity, Error> {
680        let bad = |reason: String| Error::InvalidIdToken(reason);
681        let header = jsonwebtoken::decode_header(id_token).map_err(|e| bad(format!("unreadable header: {e}")))?;
682        let kid = header.kid.ok_or_else(|| bad("the token names no key id (kid)".into()))?;
683        let key = self.decoding_key(&kid).await?;
684
685        let config = &self.inner.config;
686        let mut validation = Validation::new(Algorithm::ES256);
687        validation.set_issuer(&[config.issuer.as_str()]);
688        validation.set_audience(&[config.client_id.as_str()]);
689        validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
690        // Clock tolerance on `exp`: 60 seconds, the same in every package.
691        validation.leeway = 60;
692        let data = jsonwebtoken::decode::<Map<String, Value>>(id_token, &key, &validation)
693            .map_err(|e| bad(e.to_string()))?;
694        let claims = data.claims;
695
696        match claims.get("nonce").and_then(Value::as_str) {
697            Some(n) if same(n, nonce) => {}
698            _ => return Err(bad("nonce mismatch".into())),
699        }
700        Identity::from_claims(claims)
701    }
702
703    /// The key named `kid`, refreshing the cached key set once if it is
704    /// not there (the provider may have rotated its key).
705    async fn decoding_key(&self, kid: &str) -> Result<DecodingKey, Error> {
706        let cached = self.inner.jwks.read().expect("jwks lock poisoned").clone();
707        let jwk = match cached.find(kid) {
708            Some(jwk) => jwk.clone(),
709            None => {
710                let fresh = Arc::new(fetch_jwks(&self.inner.http, &self.inner.metadata.jwks_uri).await?);
711                *self.inner.jwks.write().expect("jwks lock poisoned") = fresh.clone();
712                fresh
713                    .find(kid)
714                    .cloned()
715                    .ok_or_else(|| Error::InvalidIdToken(format!("signed with an unknown key {kid:?}")))?
716            }
717        };
718        DecodingKey::from_jwk(&jwk).map_err(|e| Error::InvalidIdToken(format!("unusable key {kid:?}: {e}")))
719    }
720}
721
722/// The discovery document must name the configured issuer exactly, and
723/// its endpoints must be URLs.
724fn check_metadata(config: &Config, metadata: &Metadata) -> Result<(), Error> {
725    if metadata.issuer != config.issuer {
726        return Err(Error::IssuerMismatch { expected: config.issuer.clone(), found: metadata.issuer.clone() });
727    }
728    for (name, value) in [
729        ("authorization_endpoint", &metadata.authorization_endpoint),
730        ("token_endpoint", &metadata.token_endpoint),
731        ("jwks_uri", &metadata.jwks_uri),
732    ] {
733        Url::parse(value).map_err(|e| Error::Discovery(format!("{name} is not a URL: {e}")))?;
734    }
735    if let Some(value) = &metadata.end_session_endpoint {
736        Url::parse(value).map_err(|e| Error::Discovery(format!("end_session_endpoint is not a URL: {e}")))?;
737    }
738    Ok(())
739}
740
741async fn fetch_jwks(http: &reqwest::Client, uri: &str) -> Result<JwkSet, Error> {
742    let body = http.get(uri).send().await?.error_for_status()?.bytes().await?;
743    serde_json::from_slice(&body).map_err(|e| Error::Discovery(format!("unreadable key set: {e}")))
744}
745
746/// `Authorization: Basic …` per RFC 6749 §2.3.1: each half is
747/// form-urlencoded before joining with `:` (a secret may contain `:`).
748fn basic_auth(id: &str, secret: &str) -> String {
749    let enc = |s: &str| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
750    format!("Basic {}", STANDARD.encode(format!("{}:{}", enc(id), enc(secret))))
751}
752
753/// Parse the callback query into a map, refusing a repeated parameter (two
754/// `state`s or two `code`s are not something a genuine redirect contains).
755fn parse_query(input: &str) -> Result<HashMap<String, String>, Error> {
756    let query = match input.split_once('?') {
757        Some((_, q)) => q,
758        None => input,
759    };
760    let query = query.split('#').next().unwrap_or("");
761    let mut params = HashMap::new();
762    for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
763        if params.insert(k.into_owned(), v.into_owned()).is_some() {
764            return Err(Error::InvalidCallback("a parameter is repeated"));
765        }
766    }
767    Ok(params)
768}
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773    use serde_json::json;
774
775    const ISSUER: &str = "https://portal.example.org";
776
777    /// A client built without the network, pointing at endpoints nobody
778    /// listens on — any test that reached the network would fail.
779    fn offline_client() -> Client {
780        let config = Config::new(ISSUER, "my-system", "s3cret", "https://app.example.org/auth/callback");
781        let metadata = Metadata {
782            issuer: ISSUER.into(),
783            authorization_endpoint: format!("{ISSUER}/oauth/authorize"),
784            token_endpoint: "http://127.0.0.1:9/oauth/token".into(),
785            jwks_uri: "http://127.0.0.1:9/oauth/jwks".into(),
786            end_session_endpoint: Some(format!("{ISSUER}/oauth/logout")),
787        };
788        Client::from_parts(config, metadata, reqwest::Client::new(), JwkSet { keys: vec![] })
789    }
790
791    fn query(url: &Url) -> HashMap<String, String> {
792        url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect()
793    }
794
795    #[test]
796    fn authorization_url_carries_the_profile() {
797        let client = offline_client();
798        let (url, pending) = client.start_sign_in();
799        assert!(url.as_str().starts_with("https://portal.example.org/oauth/authorize?"));
800        let q = query(&url);
801        assert_eq!(q["response_type"], "code");
802        assert_eq!(q["client_id"], "my-system");
803        assert_eq!(q["redirect_uri"], "https://app.example.org/auth/callback");
804        assert_eq!(q["scope"], DEFAULT_SCOPES);
805        assert_eq!(q["code_challenge_method"], "S256");
806        assert_eq!(q["state"], pending.state);
807        assert_eq!(q["nonce"], pending.nonce);
808        assert_eq!(q["code_challenge"], pkce_challenge(&pending.code_verifier));
809        // The verifier itself never leaves the server.
810        assert!(!url.as_str().contains(&pending.code_verifier));
811    }
812
813    #[test]
814    fn prompt_is_sent_only_when_asked() {
815        let client = offline_client();
816        let (url, _) = client.start_sign_in();
817        assert!(!query(&url).contains_key("prompt"));
818        let (url, _) = client.start_sign_in_with(&SignInOptions::default());
819        assert!(!query(&url).contains_key("prompt"));
820        let (url, _) = client.start_sign_in_with(&SignInOptions::new().prompt("none"));
821        assert_eq!(query(&url)["prompt"], "none");
822        assert!(url.as_str().ends_with("&prompt=none"));
823    }
824
825    #[test]
826    fn sign_out_url_with_only_the_client_id() {
827        let client = offline_client();
828        let url = client.sign_out_url(&SignOutOptions::new()).unwrap();
829        assert_eq!(url.as_str(), "https://portal.example.org/oauth/logout?client_id=my-system");
830    }
831
832    #[test]
833    fn sign_out_url_orders_and_encodes_the_query() {
834        let client = offline_client();
835        let options = SignOutOptions::new()
836            .state("a b&c?d")
837            .post_logout_redirect_uri("https://app.example.org/signed-out?x=1")
838            .id_token_hint("eyJ.hint.sig");
839        let url = client.sign_out_url(&options).unwrap();
840        assert_eq!(
841            url.as_str(),
842            "https://portal.example.org/oauth/logout?client_id=my-system&id_token_hint=eyJ.hint.sig\
843             &post_logout_redirect_uri=https%3A%2F%2Fapp.example.org%2Fsigned-out%3Fx%3D1&state=a+b%26c%3Fd"
844        );
845        // …and the values decode back to what was given.
846        let q = query(&url);
847        assert_eq!(q["state"], "a b&c?d");
848        assert_eq!(q["post_logout_redirect_uri"], "https://app.example.org/signed-out?x=1");
849    }
850
851    #[test]
852    fn sign_out_url_omits_absent_values() {
853        let client = offline_client();
854        let url = client.sign_out_url(&SignOutOptions::new().state("s")).unwrap();
855        assert_eq!(url.as_str(), "https://portal.example.org/oauth/logout?client_id=my-system&state=s");
856        let url = client.sign_out_url(&SignOutOptions::new().post_logout_redirect_uri("https://a.example/")).unwrap();
857        let q = query(&url);
858        assert_eq!(q.len(), 2);
859        assert_eq!(q["client_id"], "my-system");
860        assert!(!q.contains_key("state") && !q.contains_key("id_token_hint"));
861    }
862
863    #[test]
864    fn sign_out_state_longer_than_512_is_refused() {
865        let client = offline_client();
866        let ok = "é".repeat(MAX_SIGN_OUT_STATE_LEN); // counted in characters, not bytes
867        assert!(client.sign_out_url(&SignOutOptions::new().state(ok)).is_ok());
868        let long = "x".repeat(MAX_SIGN_OUT_STATE_LEN + 1);
869        assert!(matches!(client.sign_out_url(&SignOutOptions::new().state(long)), Err(Error::InvalidArgument(_))));
870    }
871
872    #[test]
873    fn sign_out_without_end_session_endpoint_is_a_discovery_error() {
874        let mut client = offline_client();
875        Arc::get_mut(&mut client.inner).unwrap().metadata.end_session_endpoint = None;
876        let err = client.sign_out_url(&SignOutOptions::new()).unwrap_err();
877        assert!(matches!(&err, Error::Discovery(m) if m.contains("end_session_endpoint")), "{err:?}");
878    }
879
880    #[test]
881    fn discovery_document_without_end_session_endpoint_parses() {
882        let doc = json!({
883            "issuer": ISSUER, "authorization_endpoint": format!("{ISSUER}/oauth/authorize"),
884            "token_endpoint": format!("{ISSUER}/oauth/token"), "jwks_uri": format!("{ISSUER}/oauth/jwks")
885        });
886        let m: Metadata = serde_json::from_value(doc).unwrap();
887        assert_eq!(m.end_session_endpoint, None);
888    }
889
890    #[test]
891    fn sign_out_options_debug_hides_the_id_token() {
892        let o = SignOutOptions::new().id_token_hint("eyJ.secret.sig");
893        assert!(!format!("{o:?}").contains("eyJ.secret.sig"));
894    }
895
896    #[test]
897    fn password_change_url_is_exact() {
898        let client = offline_client();
899        assert_eq!(client.password_change_url(), "https://portal.example.org/admin/account/password?client_id=my-system");
900        let mut client = offline_client();
901        Arc::get_mut(&mut client.inner).unwrap().config.client_id = "a b&c".into();
902        assert_eq!(client.password_change_url(), "https://portal.example.org/admin/account/password?client_id=a+b%26c");
903    }
904
905    #[test]
906    fn custom_scopes_are_sent() {
907        let mut client = offline_client();
908        Arc::get_mut(&mut client.inner).unwrap().config.scopes = "openid profile".into();
909        let (url, _) = client.start_sign_in();
910        assert_eq!(query(&url)["scope"], "openid profile");
911    }
912
913    #[test]
914    fn pending_values_are_random_and_well_formed() {
915        let a = Pending::generate();
916        let b = Pending::generate();
917        for v in [&a.state, &a.nonce, &a.code_verifier] {
918            // 32 random bytes → 43 base64url characters, a valid verifier.
919            assert_eq!(v.len(), 43);
920            assert!(v.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_'));
921        }
922        assert_ne!(a.state, a.nonce);
923        assert_ne!(a.nonce, a.code_verifier);
924        assert_ne!(a, b);
925    }
926
927    #[test]
928    fn pkce_challenge_matches_rfc_7636_example() {
929        // RFC 7636, Appendix B.
930        assert_eq!(
931            pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
932            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
933        );
934    }
935
936    #[test]
937    fn pending_round_trips_through_serde() {
938        let p = Pending::generate();
939        let json = serde_json::to_string(&p).unwrap();
940        assert_eq!(serde_json::from_str::<Pending>(&json).unwrap(), p);
941        // …and `{:?}` does not reveal the verifier.
942        assert!(!format!("{p:?}").contains(&p.code_verifier));
943    }
944
945    #[test]
946    fn error_callback_is_reported_with_its_code() {
947        let client = offline_client();
948        let (_, p) = client.start_sign_in();
949        let q = format!("error=access_denied&error_description=not+in+group&state={}", p.state);
950        match client.check_callback(&q, &p) {
951            Err(Error::Provider { error, description }) => {
952                assert_eq!(error, "access_denied");
953                assert_eq!(description.as_deref(), Some("not in group"));
954            }
955            other => panic!("expected Provider error, got {other:?}"),
956        }
957    }
958
959    #[test]
960    fn wrong_or_missing_state_is_refused() {
961        let client = offline_client();
962        let (_, p) = client.start_sign_in();
963        assert!(matches!(client.check_callback("code=abc&state=forged", &p), Err(Error::StateMismatch)));
964        assert!(matches!(client.check_callback("code=abc", &p), Err(Error::StateMismatch)));
965        // Empty never matches, even against itself.
966        assert!(!same("", ""));
967        assert!(!same("", "x"));
968        assert!(same("x", "x"));
969    }
970
971    #[tokio::test]
972    async fn state_mismatch_stops_before_the_network() {
973        // The token endpoint is unreachable: an Http error would mean the
974        // exchange was attempted.
975        let client = offline_client();
976        let (_, p) = client.start_sign_in();
977        let err = client.finish_sign_in("?code=abc&state=forged", &p).await.unwrap_err();
978        assert!(matches!(err, Error::StateMismatch), "{err:?}");
979    }
980
981    #[test]
982    fn foreign_or_absent_iss_is_refused() {
983        let client = offline_client();
984        let (_, p) = client.start_sign_in();
985        let q = format!("code=abc&state={}&iss=https%3A%2F%2Fevil.example.org", p.state);
986        assert!(matches!(client.check_callback(&q, &p), Err(Error::IssuerMismatch { .. })));
987        let q = format!("code=abc&state={}&iss=https%3A%2F%2Fportal.example.org", p.state);
988        assert_eq!(client.check_callback(&q, &p).unwrap(), "abc");
989        // Absent: the portal always sends it, so this is not the portal's.
990        let q = format!("code=abc&state={}", p.state);
991        assert!(matches!(client.check_callback(&q, &p), Err(Error::IssuerMismatch { .. })));
992    }
993
994    #[test]
995    fn full_callback_url_and_malformed_queries() {
996        let client = offline_client();
997        let (_, p) = client.start_sign_in();
998        const ISS: &str = "iss=https%3A%2F%2Fportal.example.org";
999        let url = format!("https://app.example.org/auth/callback?code=xyz&state={}&{ISS}", p.state);
1000        assert_eq!(client.check_callback(&url, &p).unwrap(), "xyz");
1001        let q = format!("state={}&{ISS}", p.state);
1002        assert!(matches!(client.check_callback(&q, &p), Err(Error::InvalidCallback(_))));
1003        let q = format!("code=a&code=b&state={}", p.state);
1004        assert!(matches!(client.check_callback(&q, &p), Err(Error::InvalidCallback(_))));
1005    }
1006
1007    #[test]
1008    fn discovery_with_another_issuer_is_refused() {
1009        let config = Config::new(ISSUER, "c", "s", "https://app.example.org/cb");
1010        let mut metadata = Metadata {
1011            issuer: format!("{ISSUER}/"),
1012            authorization_endpoint: format!("{ISSUER}/oauth/authorize"),
1013            token_endpoint: format!("{ISSUER}/oauth/token"),
1014            jwks_uri: format!("{ISSUER}/oauth/jwks"),
1015            end_session_endpoint: None,
1016        };
1017        assert!(matches!(check_metadata(&config, &metadata), Err(Error::IssuerMismatch { .. })));
1018        metadata.issuer = ISSUER.into();
1019        assert!(check_metadata(&config, &metadata).is_ok());
1020    }
1021
1022    #[test]
1023    fn basic_auth_form_encodes_both_halves() {
1024        // "a:b c" → "a%3Ab+c"; base64("id:a%3Ab+c").
1025        assert_eq!(basic_auth("id", "a:b c"), format!("Basic {}", STANDARD.encode("id:a%3Ab+c")));
1026    }
1027
1028    fn claims(v: Value) -> Map<String, Value> {
1029        v.as_object().unwrap().clone()
1030    }
1031
1032    #[test]
1033    fn identity_fields_and_helpers() {
1034        let id = Identity::from_claims(claims(json!({
1035            "sub": "5966f47e", "preferred_username": "ana", "name": "Ana Maria",
1036            "email": "ana@example.org", "setor": "FIN", "groups": ["fiscal"],
1037            "group_roles": {"fiscal": ["analista", "gestor"]}, "extra": 1
1038        })))
1039        .unwrap();
1040        assert_eq!(id.sub, "5966f47e");
1041        assert_eq!(id.username.as_deref(), Some("ana"));
1042        assert_eq!(id.name.as_deref(), Some("Ana Maria"));
1043        assert_eq!(id.email.as_deref(), Some("ana@example.org"));
1044        assert_eq!(id.setor.as_deref(), Some("FIN"));
1045        assert!(id.has_group("fiscal"));
1046        assert!(!id.has_group("other"));
1047        assert!(id.has_role("fiscal", "gestor"));
1048        assert!(!id.has_role("fiscal", "admin"));
1049        assert!(!id.has_role("other", "gestor"));
1050        assert_eq!(id.roles("fiscal"), ["analista", "gestor"]);
1051        assert!(id.roles("other").is_empty());
1052        assert_eq!(id.claims["extra"], 1);
1053    }
1054
1055    #[test]
1056    fn missing_optional_claims_are_empty() {
1057        let id = Identity::from_claims(claims(json!({"sub": "x"}))).unwrap();
1058        assert_eq!(id.username, None);
1059        assert_eq!(id.name, None);
1060        assert_eq!(id.email, None);
1061        assert_eq!(id.setor, None);
1062        assert!(id.groups.is_empty());
1063        assert!(id.group_roles.is_empty());
1064        assert!(id.roles("fiscal").is_empty());
1065    }
1066
1067    #[test]
1068    fn identity_without_sub_is_refused() {
1069        assert!(matches!(
1070            Identity::from_claims(claims(json!({"preferred_username": "ana"}))),
1071            Err(Error::InvalidIdToken(_))
1072        ));
1073    }
1074
1075    #[test]
1076    fn debug_output_hides_the_secret() {
1077        let c = offline_client();
1078        assert!(!format!("{:?}", c.config()).contains("s3cret"));
1079    }
1080
1081    /// The one-refresh-on-unknown-`kid` path, against the running test
1082    /// provider (skipped without `RUSCKER_ISSUER`). Lives here because it
1083    /// needs to start the client with an EMPTY key cache.
1084    #[tokio::test]
1085    async fn unknown_kid_refreshes_the_key_set_once() {
1086        let Ok(issuer) = std::env::var("RUSCKER_ISSUER") else {
1087            eprintln!("RUSCKER_ISSUER is not set: skipping");
1088            return;
1089        };
1090        let var = |n: &str| std::env::var(n).unwrap();
1091        let config = Config::new(issuer, var("RUSCKER_CLIENT_ID"), var("RUSCKER_CLIENT_SECRET"), var("RUSCKER_REDIRECT_URI"));
1092        let real = Client::discover(config.clone()).await.unwrap();
1093        let client =
1094            Client::from_parts(config, real.inner.metadata.clone(), reqwest::Client::new(), JwkSet { keys: vec![] });
1095
1096        let (url, pending) = client.start_sign_in();
1097        let script = concat!(env!("CARGO_MANIFEST_DIR"), "/../testing/authorize.sh");
1098        let out = std::process::Command::new(script).arg(url.as_str()).output().unwrap();
1099        let callback = String::from_utf8(out.stdout).unwrap();
1100        client.finish_sign_in(callback.trim(), &pending).await.expect("sign-in after a key refresh");
1101        assert!(!client.inner.jwks.read().unwrap().keys.is_empty(), "the cache was refreshed");
1102    }
1103}