From 00d311187ee01b831934c48ec6dfcb371043dba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 12:43:48 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20max=5Fage=20and=20prompt?= =?UTF-8?q?=3Dlogin=20force=20a=20fresh=20sign-in,=20unsupported=20respons?= =?UTF-8?q?e=5Fmode=20refused?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-web/src/oidc/authorize.rs | 124 +++++++++++++++++++++++++--- crates/im-web/src/oidc/discovery.rs | 4 + 2 files changed, 117 insertions(+), 11 deletions(-) diff --git a/crates/im-web/src/oidc/authorize.rs b/crates/im-web/src/oidc/authorize.rs index 44bd386..1ae334c 100644 --- a/crates/im-web/src/oidc/authorize.rs +++ b/crates/im-web/src/oidc/authorize.rs @@ -5,11 +5,13 @@ //! 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 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; +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}; @@ -25,6 +27,12 @@ use crate::i18n::oidc::{OidcText, text}; use crate::state::AppState; 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. @@ -37,6 +45,10 @@ struct Asked { 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. @@ -45,6 +57,31 @@ struct Refused { 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) @@ -70,11 +107,13 @@ fn read(pairs: &Pairs, client: &Client) -> std::result::Result { }; 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")); @@ -85,6 +124,11 @@ fn read(pairs: &Pairs, client: &Client) -> std::result::Result { 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")), @@ -113,25 +157,47 @@ fn read(pairs: &Pairs, client: &Client) -> std::result::Result { if !granted.contains(&"openid") { return Err(refuse("invalid_scope")); } - let no_prompt = match single(pairs, "prompt") { - Single::Absent => false, + // `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, - ["none"] => true, - // Re-authentication and consent prompts are not offered; say so instead of ignoring them. + [] => (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)]; @@ -186,13 +252,23 @@ async fn authorize(cx: &Cx) -> Result { }; return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); } - // Back to this exact request after sign-in: the login page checks `next` as a local path. - let back = uri(cx) - .path_and_query() - .map_or("/authorize", |p| p.as_str()); - return Err(see_other(format!("/login?next={}", percent_encode(back))).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() { @@ -249,3 +325,29 @@ async fn error_body(lang: Lang) -> Result { }) } + +#[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)); + } +} diff --git a/crates/im-web/src/oidc/discovery.rs b/crates/im-web/src/oidc/discovery.rs index e3bed51..c538cc7 100644 --- a/crates/im-web/src/oidc/discovery.rs +++ b/crates/im-web/src/oidc/discovery.rs @@ -16,6 +16,9 @@ use crate::state::AppState; /// The grant types this provider offers (contracts.md 2.1). const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"]; +/// The response modes of `/authorize`. Only the query mode exists; any other is refused there. +const RESPONSE_MODES: [&str; 1] = ["query"]; + /// The client authentication methods of `/token`, `/revoke` and `/introspect`. const AUTH_METHODS: [&str; 2] = ["client_secret_basic", "client_secret_post"]; @@ -42,6 +45,7 @@ async fn discovery(cx: &Cx) -> topcoat::Result { "revocation_endpoint": format!("{base}/revoke"), "introspection_endpoint": format!("{base}/introspect"), "response_types_supported": ["code"], + "response_modes_supported": RESPONSE_MODES, "grant_types_supported": GRANT_TYPES, "subject_types_supported": ["public"], "code_challenge_methods_supported": ["S256"],