//! `GET /authorize` (contracts section 2.3, steps 1 and 2): checks the request, signs the person in if //! needed, and redirects back with a one-time code. //! //! The order is fixed. First the client and the redirect URI are checked against the registration by //! exact string match; until both pass, nothing is redirected and the error page is shown. Then every //! other error goes to the registered redirect URI, with `error`, the `state` (only when it is usable) //! and `iss`. Only then is a session asked for. PKCE with S256 is mandatory, and `plain` is refused. //! A session older than `max_age` (or any session when `prompt=login`) must sign in again first //! (OIDC Core 3.1.2.1). Only the `query` response mode is offered. use std::time::Instant; use im_core::model::Client; use im_core::oauth::{MAX_ECHO_BYTES, is_supported_scope, is_user_scope, is_valid_challenge}; use im_core::store::oidc::NewAuthCode; use im_core::time::{stamp_after, unix_now, unix_seconds}; use im_core::token::{generate_token, hash_token}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::{SeeOther, see_other}; use topcoat::router::request::uri; use topcoat::router::{StatusCode, page}; use topcoat::view::{View, component, view}; use super::{CODE_TTL, Pairs, Single, issuer, one, parse_pairs, single, with_query}; use crate::auth::{current_user, percent_encode}; use crate::i18n::Lang; use crate::i18n::oidc::{OidcText, text}; use crate::state::AppState; use crate::throttle::{AUTHORIZE_SESSION_LIMIT, authorize_session_key}; use crate::views::{page_lang, shell}; /// The shortest age, in seconds, that a sign-in is still treated as fresh. A `max_age` below it, and /// `prompt=login`, count as this value. Without it, `max_age=0` would send the person back to sign in /// again straight after signing in, forever. A sign-in made less than a minute ago is fresh enough for /// any `max_age` up to this value (OIDC Core 3.1.2.1 leaves the grace to the provider). pub const REAUTH_GRACE: u64 = 60; /// What a request asks for, after the checks that need no database. struct Asked { /// The request's `state`, echoed back on every answer. state: Option, /// The PKCE challenge, stored with the code. challenge: String, /// The nonce, stored with the code and written into the ID token. nonce: Option, /// The granted scope: the request's scopes that are user scopes and that the client may ask for. scope: String, /// True for `prompt=none`: no page may be shown, only a result. no_prompt: bool, /// The `max_age` in seconds, when the request carried one. max_age: Option, /// True for `prompt=login`: the person signs in again whatever the age of the session. force_login: bool, } /// A refusal that goes to the redirect URI. `state` is set only when the state was usable. struct Refused { code: &'static str, state: Option, } /// Parses `max_age`: one or more ASCII digits, so a sign, a fraction or a space is refused. A number too /// large for `u64` saturates, which is the same as any age being acceptable. fn parse_max_age(value: &str) -> Option { if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) { return None; } Some(value.parse().unwrap_or(u64::MAX)) } /// True when the session must sign in again before a code is issued (OIDC Core 3.1.2.1). `prompt=login` /// counts as `max_age=0`. The limit is never below [`REAUTH_GRACE`]. `auth_time` is the Unix time of the /// sign-in that created the session. With no `max_age` and no `prompt=login` nothing is due. fn reauth_due(max_age: Option, force_login: bool, auth_time: i64, now: i64) -> bool { let requested = if force_login { 0 } else { match max_age { Some(limit) => limit, None => return false, } }; let limit = i64::try_from(requested.max(REAUTH_GRACE)).unwrap_or(i64::MAX); now.saturating_sub(auth_time) > limit } /// True when a `state` or `nonce` may be echoed: short enough and free of control characters. fn usable_echo(value: &str) -> bool { value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control) } /// Checks everything in the query that does not need a session. Returns what was asked, or the refusal /// to send to the redirect URI. fn read(pairs: &Pairs, client: &Client) -> std::result::Result { let state = match single(pairs, "state") { Single::Absent => None, Single::One(value) if usable_echo(value) => Some(value.to_owned()), // A state that cannot be echoed is refused without echoing it. _ => { return Err(Refused { code: "invalid_request", state: None, }); } }; let refuse = |code: &'static str| Refused { code, state: state.clone(), }; for name in [ "response_type", "response_mode", "code_challenge", "code_challenge_method", "nonce", "scope", "prompt", "max_age", ] { if single(pairs, name) == Single::Repeated { return Err(refuse("invalid_request")); } } match single(pairs, "response_type") { Single::One("code") => {} Single::One(_) => return Err(refuse("unsupported_response_type")), _ => return Err(refuse("invalid_request")), } // Only the query response mode exists (contracts section 2.1). Any other value is refused, not ignored. match single(pairs, "response_mode") { Single::Absent | Single::One("query") => {} _ => return Err(refuse("invalid_request")), } let challenge = match single(pairs, "code_challenge") { Single::One(value) if is_valid_challenge(value) => value.to_owned(), _ => return Err(refuse("invalid_request")), }; // `plain` and a missing method are refused: PKCE S256 is mandatory (contracts section 2.3). if single(pairs, "code_challenge_method") != Single::One("S256") { return Err(refuse("invalid_request")); } let nonce = match single(pairs, "nonce") { Single::Absent => None, Single::One(value) if usable_echo(value) => Some(value.to_owned()), _ => return Err(refuse("invalid_request")), }; let Single::One(requested) = single(pairs, "scope") else { return Err(refuse("invalid_request")); }; let mut granted: Vec<&str> = Vec::new(); for word in requested.split_whitespace() { if !is_supported_scope(word) { return Err(refuse("invalid_scope")); } if is_user_scope(word) && client.allows_scope(word) && !granted.contains(&word) { granted.push(word); } } if !granted.contains(&"openid") { return Err(refuse("invalid_scope")); } // `none` and `login` are offered, alone (OIDC Core 3.1.2.6: `none` may not be combined). Consent and // account selection are not offered; say so instead of ignoring them. let (no_prompt, force_login) = match single(pairs, "prompt") { Single::Absent => (false, false), Single::One(value) => match value.split_whitespace().collect::>().as_slice() { [] => (false, false), ["none"] => (true, false), ["login"] => (false, true), _ => return Err(refuse("invalid_request")), }, Single::Repeated => return Err(refuse("invalid_request")), }; let max_age = match single(pairs, "max_age") { Single::Absent => None, Single::One(value) => match parse_max_age(value) { Some(seconds) => Some(seconds), None => return Err(refuse("invalid_request")), }, Single::Repeated => return Err(refuse("invalid_request")), }; Ok(Asked { state, challenge, nonce, scope: granted.join(" "), no_prompt, max_age, force_login, }) } /// The redirect to the sign-in page, with this exact request as `next`, so the request continues after /// the sign-in. fn sign_in_again(cx: &Cx) -> SeeOther { // The login page checks `next` as a local path. let back = uri(cx) .path_and_query() .map_or("/authorize", |p| p.as_str()); see_other(format!("/login?next={}", percent_encode(back))) } /// The redirect that carries a refusal to the client. fn refusal_redirect(redirect_uri: &str, issuer: &str, refused: &Refused) -> SeeOther { let mut params = vec![("error", refused.code), ("iss", issuer)]; if let Some(state) = refused.state.as_deref() { params.push(("state", state)); } see_other(with_query(redirect_uri, ¶ms)) } /// `GET /authorize`. /// /// Every answer is either a redirect (`Err` carrying a `SeeOther`) or the error page, which is the only /// `Ok` value. A request with an unknown client or an unregistered redirect URI never reaches a /// redirect. #[page(GET "/authorize")] async fn authorize(cx: &Cx) -> Result { let app = app_context::(cx); let lang = page_lang(cx, None); let Some(pairs) = parse_pairs(uri(cx).query().unwrap_or_default().as_bytes()) else { return Ok(error_page(cx, lang)); }; let Some(client_id) = one(&pairs, "client_id") else { return Ok(error_page(cx, lang)); }; let Some(redirect_uri) = one(&pairs, "redirect_uri") else { return Ok(error_page(cx, lang)); }; let client = match app.store.client_by_id(client_id).await? { Some(client) if !client.is_disabled() && client .redirect_uris .iter() .any(|registered| registered == redirect_uri) => { client } _ => return Ok(error_page(cx, lang)), }; // From here on the redirect URI is the registered one, so every refusal may go to it. let issuer = issuer(app); let asked = match read(&pairs, &client) { Ok(asked) => asked, Err(refused) => return Err(refusal_redirect(redirect_uri, issuer, &refused).into()), }; let Some(viewer) = current_user(cx).await? else { if asked.no_prompt { let refused = Refused { code: "login_required", state: asked.state.clone(), }; return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); } return Err(sign_in_again(cx).into()); }; // The sign-in that created the session is the authentication time (`sessions.auth_time`, which a // new sign-in always sets to now). An unreadable stamp counts as very old, so it fails closed. let auth_time = unix_seconds(&viewer.session.auth_time).unwrap_or(i64::MIN); if reauth_due(asked.max_age, asked.force_login, auth_time, unix_now()) { if asked.no_prompt { let refused = Refused { code: "login_required", state: asked.state.clone(), }; return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); } return Err(sign_in_again(cx).into()); } // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a // prompt=none request cannot show a page, so it is refused instead. if viewer.user.is_admin && app.policy().require_2fa_for_admins && !viewer.user.totp_enabled() { if asked.no_prompt { let refused = Refused { code: "interaction_required", state: asked.state.clone(), }; return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); } return Err(see_other("/account/security?notice=enrol").into()); } // Each issue adds a row that lives a day, so a session that repeats the request is limited. The refusal // goes to the registered redirect URI like the other refusals of this request. if app .per_minute .reserve( &authorize_session_key(&viewer.session.id), AUTHORIZE_SESSION_LIMIT, Instant::now(), ) .is_err() { let refused = Refused { code: "temporarily_unavailable", state: asked.state.clone(), }; return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); } let code = generate_token(); let expires_at = stamp_after(CODE_TTL); app.store .insert_auth_code(&NewAuthCode { code_hash: &hash_token(&code), client_id: &client.id, user_id: &viewer.user.id, session_id: &viewer.session.id, redirect_uri, scope: &asked.scope, nonce: asked.nonce.as_deref(), code_challenge: &asked.challenge, expires_at: &expires_at, }) .await?; app.store .touch_client_session(&viewer.session.id, &client.id) .await?; let mut params = vec![("code", code.as_str()), ("iss", issuer)]; if let Some(state) = asked.state.as_deref() { params.push(("state", state)); } Err(see_other(with_query(redirect_uri, ¶ms)).into()) } /// The error page: a 400 in the shell, with no redirect and no detail about the request. fn error_page(cx: &Cx, lang: Lang) -> impl View { view! { cx => (StatusCode::BAD_REQUEST) shell(title: text(lang, OidcText::ErrorTitle), lang: lang, viewer: None, error_body(lang: lang)) } } /// The body of the error page. #[component] async fn error_body(lang: Lang) -> Result { Ok(view! {

(text(lang, OidcText::ErrorBody))

}) } #[cfg(test)] mod tests { use super::*; #[test] fn max_age_is_digits_only_and_the_grace_keeps_max_age_zero_from_looping() { assert_eq!(parse_max_age("0"), Some(0)); assert_eq!(parse_max_age("3600"), Some(3600)); for bad in ["", "-1", "+5", "1.5", " 5", "5s"] { assert_eq!(parse_max_age(bad), None, "{bad}"); } let now = 1_000_000; // A sign-in just now satisfies max_age=0 and prompt=login within the grace. assert!(!reauth_due(Some(0), false, now - 5, now)); assert!(!reauth_due(None, true, now - 5, now)); // Older than the grace: max_age=0 and prompt=login send the person to sign in again. assert!(reauth_due(Some(0), false, now - 61, now)); assert!(reauth_due(None, true, now - 61, now)); // max_age is compared with the age of the sign-in, and is never below the grace. assert!(!reauth_due(Some(3600), false, now - 3600, now)); assert!(reauth_due(Some(3600), false, now - 3601, now)); // Without max_age or prompt=login nothing is due, however old the sign-in. assert!(!reauth_due(None, false, now - 1_000_000, now)); } }