forge
Explore
Log in

Don't you dare go Hollow

Max_age and prompt=login force a fresh sign-in, unsupported response_mode refused

Browse files at this commit

00d311187ee01b831934c48ec6dfcb371043dba9Ahmet Kaan GümüşParent: 243c4e4
  • fix
    • max_age and prompt=login force a fresh sign-in, unsupported response_mode refused
Show full message
🔒 fix: max_age and prompt=login force a fresh sign-in, unsupported response_mode refused
crates/im-web/src/oidc/authorize.rsmodified+113 -11
@@ -5,11 +5,13 @@
55 //! exact string match; until both pass, nothing is redirected and the error page is shown. Then every
66 //! other error goes to the registered redirect URI, with `error`, the `state` (only when it is usable)
77 //! and `iss`. Only then is a session asked for. PKCE with S256 is mandatory, and `plain` is refused.
8+//! A session older than `max_age` (or any session when `prompt=login`) must sign in again first
9+//! (OIDC Core 3.1.2.1). Only the `query` response mode is offered.
810
911 use im_core::model::Client;
1012 use im_core::oauth::{MAX_ECHO_BYTES, is_supported_scope, is_user_scope, is_valid_challenge};
1113 use im_core::store::oidc::NewAuthCode;
12-use im_core::time::stamp_after;
14+use im_core::time::{stamp_after, unix_now, unix_seconds};
1315 use im_core::token::{generate_token, hash_token};
1416 use topcoat::Result;
1517 use topcoat::context::{Cx, app_context};
@@ -25,6 +27,12 @@ use crate::i18n::oidc::{OidcText, text};
2527 use crate::state::AppState;
2628 use crate::views::{page_lang, shell};
2729
30+/// The shortest age, in seconds, that a sign-in is still treated as fresh. A `max_age` below it, and
31+/// `prompt=login`, count as this value. Without it, `max_age=0` would send the person back to sign in
32+/// again straight after signing in, forever. A sign-in made less than a minute ago is fresh enough for
33+/// any `max_age` up to this value (OIDC Core 3.1.2.1 leaves the grace to the provider).
34+pub const REAUTH_GRACE: u64 = 60;
35+
2836 /// What a request asks for, after the checks that need no database.
2937 struct Asked {
3038 /// The request's `state`, echoed back on every answer.
@@ -37,6 +45,10 @@ struct Asked {
3745 scope: String,
3846 /// True for `prompt=none`: no page may be shown, only a result.
3947 no_prompt: bool,
48+ /// The `max_age` in seconds, when the request carried one.
49+ max_age: Option<u64>,
50+ /// True for `prompt=login`: the person signs in again whatever the age of the session.
51+ force_login: bool,
4052 }
4153
4254 /// A refusal that goes to the redirect URI. `state` is set only when the state was usable.
@@ -45,6 +57,31 @@ struct Refused {
4557 state: Option<String>,
4658 }
4759
60+/// Parses `max_age`: one or more ASCII digits, so a sign, a fraction or a space is refused. A number too
61+/// large for `u64` saturates, which is the same as any age being acceptable.
62+fn parse_max_age(value: &str) -> Option<u64> {
63+ if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
64+ return None;
65+ }
66+ Some(value.parse().unwrap_or(u64::MAX))
67+}
68+
69+/// True when the session must sign in again before a code is issued (OIDC Core 3.1.2.1). `prompt=login`
70+/// counts as `max_age=0`. The limit is never below [`REAUTH_GRACE`]. `auth_time` is the Unix time of the
71+/// sign-in that created the session. With no `max_age` and no `prompt=login` nothing is due.
72+fn reauth_due(max_age: Option<u64>, force_login: bool, auth_time: i64, now: i64) -> bool {
73+ let requested = if force_login {
74+ 0
75+ } else {
76+ match max_age {
77+ Some(limit) => limit,
78+ None => return false,
79+ }
80+ };
81+ let limit = i64::try_from(requested.max(REAUTH_GRACE)).unwrap_or(i64::MAX);
82+ now.saturating_sub(auth_time) > limit
83+}
84+
4885 /// True when a `state` or `nonce` may be echoed: short enough and free of control characters.
4986 fn usable_echo(value: &str) -> bool {
5087 value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control)
@@ -70,11 +107,13 @@ fn read(pairs: &Pairs, client: &Client) -> std::result::Result<Asked, Refused> {
70107 };
71108 for name in [
72109 "response_type",
110+ "response_mode",
73111 "code_challenge",
74112 "code_challenge_method",
75113 "nonce",
76114 "scope",
77115 "prompt",
116+ "max_age",
78117 ] {
79118 if single(pairs, name) == Single::Repeated {
80119 return Err(refuse("invalid_request"));
@@ -85,6 +124,11 @@ fn read(pairs: &Pairs, client: &Client) -> std::result::Result<Asked, Refused> {
85124 Single::One(_) => return Err(refuse("unsupported_response_type")),
86125 _ => return Err(refuse("invalid_request")),
87126 }
127+ // Only the query response mode exists (contracts section 2.1). Any other value is refused, not ignored.
128+ match single(pairs, "response_mode") {
129+ Single::Absent | Single::One("query") => {}
130+ _ => return Err(refuse("invalid_request")),
131+ }
88132 let challenge = match single(pairs, "code_challenge") {
89133 Single::One(value) if is_valid_challenge(value) => value.to_owned(),
90134 _ => return Err(refuse("invalid_request")),
@@ -113,25 +157,47 @@ fn read(pairs: &Pairs, client: &Client) -> std::result::Result<Asked, Refused> {
113157 if !granted.contains(&"openid") {
114158 return Err(refuse("invalid_scope"));
115159 }
116- let no_prompt = match single(pairs, "prompt") {
117- Single::Absent => false,
160+ // `none` and `login` are offered, alone (OIDC Core 3.1.2.6: `none` may not be combined). Consent and
161+ // account selection are not offered; say so instead of ignoring them.
162+ let (no_prompt, force_login) = match single(pairs, "prompt") {
163+ Single::Absent => (false, false),
118164 Single::One(value) => match value.split_whitespace().collect::<Vec<_>>().as_slice() {
119- [] => false,
120- ["none"] => true,
121- // Re-authentication and consent prompts are not offered; say so instead of ignoring them.
165+ [] => (false, false),
166+ ["none"] => (true, false),
167+ ["login"] => (false, true),
122168 _ => return Err(refuse("invalid_request")),
123169 },
124170 Single::Repeated => return Err(refuse("invalid_request")),
125171 };
172+ let max_age = match single(pairs, "max_age") {
173+ Single::Absent => None,
174+ Single::One(value) => match parse_max_age(value) {
175+ Some(seconds) => Some(seconds),
176+ None => return Err(refuse("invalid_request")),
177+ },
178+ Single::Repeated => return Err(refuse("invalid_request")),
179+ };
126180 Ok(Asked {
127181 state,
128182 challenge,
129183 nonce,
130184 scope: granted.join(" "),
131185 no_prompt,
186+ max_age,
187+ force_login,
132188 })
133189 }
134190
191+/// The redirect to the sign-in page, with this exact request as `next`, so the request continues after
192+/// the sign-in.
193+fn sign_in_again(cx: &Cx) -> SeeOther {
194+ // The login page checks `next` as a local path.
195+ let back = uri(cx)
196+ .path_and_query()
197+ .map_or("/authorize", |p| p.as_str());
198+ see_other(format!("/login?next={}", percent_encode(back)))
199+}
200+
135201 /// The redirect that carries a refusal to the client.
136202 fn refusal_redirect(redirect_uri: &str, issuer: &str, refused: &Refused) -> SeeOther {
137203 let mut params = vec![("error", refused.code), ("iss", issuer)];
@@ -186,13 +252,23 @@ async fn authorize(cx: &Cx) -> Result<impl View> {
186252 };
187253 return Err(refusal_redirect(redirect_uri, issuer, &refused).into());
188254 }
189- // Back to this exact request after sign-in: the login page checks `next` as a local path.
190- let back = uri(cx)
191- .path_and_query()
192- .map_or("/authorize", |p| p.as_str());
193- return Err(see_other(format!("/login?next={}", percent_encode(back))).into());
255+ return Err(sign_in_again(cx).into());
194256 };
195257
258+ // The sign-in that created the session is the authentication time (`sessions.auth_time`, which a
259+ // new sign-in always sets to now). An unreadable stamp counts as very old, so it fails closed.
260+ let auth_time = unix_seconds(&viewer.session.auth_time).unwrap_or(i64::MIN);
261+ if reauth_due(asked.max_age, asked.force_login, auth_time, unix_now()) {
262+ if asked.no_prompt {
263+ let refused = Refused {
264+ code: "login_required",
265+ state: asked.state.clone(),
266+ };
267+ return Err(refusal_redirect(redirect_uri, issuer, &refused).into());
268+ }
269+ return Err(sign_in_again(cx).into());
270+ }
271+
196272 // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a
197273 // prompt=none request cannot show a page, so it is refused instead.
198274 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<impl View> {
249325 </section>
250326 })
251327 }
328+
329+#[cfg(test)]
330+mod tests {
331+ use super::*;
332+
333+ #[test]
334+ fn max_age_is_digits_only_and_the_grace_keeps_max_age_zero_from_looping() {
335+ assert_eq!(parse_max_age("0"), Some(0));
336+ assert_eq!(parse_max_age("3600"), Some(3600));
337+ for bad in ["", "-1", "+5", "1.5", " 5", "5s"] {
338+ assert_eq!(parse_max_age(bad), None, "{bad}");
339+ }
340+ let now = 1_000_000;
341+ // A sign-in just now satisfies max_age=0 and prompt=login within the grace.
342+ assert!(!reauth_due(Some(0), false, now - 5, now));
343+ assert!(!reauth_due(None, true, now - 5, now));
344+ // Older than the grace: max_age=0 and prompt=login send the person to sign in again.
345+ assert!(reauth_due(Some(0), false, now - 61, now));
346+ assert!(reauth_due(None, true, now - 61, now));
347+ // max_age is compared with the age of the sign-in, and is never below the grace.
348+ assert!(!reauth_due(Some(3600), false, now - 3600, now));
349+ assert!(reauth_due(Some(3600), false, now - 3601, now));
350+ // Without max_age or prompt=login nothing is due, however old the sign-in.
351+ assert!(!reauth_due(None, false, now - 1_000_000, now));
352+ }
353+}
crates/im-web/src/oidc/discovery.rsmodified+4 -0
@@ -16,6 +16,9 @@ use crate::state::AppState;
1616 /// The grant types this provider offers (contracts.md 2.1).
1717 const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"];
1818
19+/// The response modes of `/authorize`. Only the query mode exists; any other is refused there.
20+const RESPONSE_MODES: [&str; 1] = ["query"];
21+
1922 /// The client authentication methods of `/token`, `/revoke` and `/introspect`.
2023 const AUTH_METHODS: [&str; 2] = ["client_secret_basic", "client_secret_post"];
2124
@@ -42,6 +45,7 @@ async fn discovery(cx: &Cx) -> topcoat::Result<Response> {
4245 "revocation_endpoint": format!("{base}/revoke"),
4346 "introspection_endpoint": format!("{base}/introspect"),
4447 "response_types_supported": ["code"],
48+ "response_modes_supported": RESPONSE_MODES,
4549 "grant_types_supported": GRANT_TYPES,
4650 "subject_types_supported": ["public"],
4751 "code_challenge_methods_supported": ["S256"],