forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

authorize.rs374 lines, 14.6 KiBHistoryRawDownload
1//! `GET /authorize` (contracts section 2.3, steps 1 and 2): checks the request, signs the person in if
2//! needed, and redirects back with a one-time code.
3//!
4//! The order is fixed. First the client and the redirect URI are checked against the registration by
5//! exact string match; until both pass, nothing is redirected and the error page is shown. Then every
6//! other error goes to the registered redirect URI, with `error`, the `state` (only when it is usable)
7//! 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.
10
11use std::time::Instant;
12
13use im_core::model::Client;
14use im_core::oauth::{MAX_ECHO_BYTES, is_supported_scope, is_user_scope, is_valid_challenge};
15use im_core::store::oidc::NewAuthCode;
16use im_core::time::{stamp_after, unix_now, unix_seconds};
17use im_core::token::{generate_token, hash_token};
18use topcoat::Result;
19use topcoat::context::{Cx, app_context};
20use topcoat::router::error::{SeeOther, see_other};
21use topcoat::router::request::uri;
22use topcoat::router::{StatusCode, page};
23use topcoat::view::{View, component, view};
24
25use super::{CODE_TTL, Pairs, Single, issuer, one, parse_pairs, single, with_query};
26use crate::auth::{current_user, percent_encode};
27use crate::i18n::Lang;
28use crate::i18n::oidc::{OidcText, text};
29use crate::state::AppState;
30use crate::throttle::{AUTHORIZE_SESSION_LIMIT, authorize_session_key};
31use crate::views::{page_lang, shell};
32
33/// The shortest age, in seconds, that a sign-in is still treated as fresh. A `max_age` below it, and
34/// `prompt=login`, count as this value. Without it, `max_age=0` would send the person back to sign in
35/// again straight after signing in, forever. A sign-in made less than a minute ago is fresh enough for
36/// any `max_age` up to this value (OIDC Core 3.1.2.1 leaves the grace to the provider).
37pub const REAUTH_GRACE: u64 = 60;
38
39/// What a request asks for, after the checks that need no database.
40struct Asked {
41 /// The request's `state`, echoed back on every answer.
42 state: Option<String>,
43 /// The PKCE challenge, stored with the code.
44 challenge: String,
45 /// The nonce, stored with the code and written into the ID token.
46 nonce: Option<String>,
47 /// The granted scope: the request's scopes that are user scopes and that the client may ask for.
48 scope: String,
49 /// True for `prompt=none`: no page may be shown, only a result.
50 no_prompt: bool,
51 /// The `max_age` in seconds, when the request carried one.
52 max_age: Option<u64>,
53 /// True for `prompt=login`: the person signs in again whatever the age of the session.
54 force_login: bool,
55}
56
57/// A refusal that goes to the redirect URI. `state` is set only when the state was usable.
58struct Refused {
59 code: &'static str,
60 state: Option<String>,
61}
62
63/// Parses `max_age`: one or more ASCII digits, so a sign, a fraction or a space is refused. A number too
64/// large for `u64` saturates, which is the same as any age being acceptable.
65fn parse_max_age(value: &str) -> Option<u64> {
66 if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
67 return None;
68 }
69 Some(value.parse().unwrap_or(u64::MAX))
70}
71
72/// True when the session must sign in again before a code is issued (OIDC Core 3.1.2.1). `prompt=login`
73/// counts as `max_age=0`. The limit is never below [`REAUTH_GRACE`]. `auth_time` is the Unix time of the
74/// sign-in that created the session. With no `max_age` and no `prompt=login` nothing is due.
75fn reauth_due(max_age: Option<u64>, force_login: bool, auth_time: i64, now: i64) -> bool {
76 let requested = if force_login {
77 0
78 } else {
79 match max_age {
80 Some(limit) => limit,
81 None => return false,
82 }
83 };
84 let limit = i64::try_from(requested.max(REAUTH_GRACE)).unwrap_or(i64::MAX);
85 now.saturating_sub(auth_time) > limit
86}
87
88/// True when a `state` or `nonce` may be echoed: short enough and free of control characters.
89fn usable_echo(value: &str) -> bool {
90 value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control)
91}
92
93/// Checks everything in the query that does not need a session. Returns what was asked, or the refusal
94/// to send to the redirect URI.
95fn read(pairs: &Pairs, client: &Client) -> std::result::Result<Asked, Refused> {
96 let state = match single(pairs, "state") {
97 Single::Absent => None,
98 Single::One(value) if usable_echo(value) => Some(value.to_owned()),
99 // A state that cannot be echoed is refused without echoing it.
100 _ => {
101 return Err(Refused {
102 code: "invalid_request",
103 state: None,
104 });
105 }
106 };
107 let refuse = |code: &'static str| Refused {
108 code,
109 state: state.clone(),
110 };
111 for name in [
112 "response_type",
113 "response_mode",
114 "code_challenge",
115 "code_challenge_method",
116 "nonce",
117 "scope",
118 "prompt",
119 "max_age",
120 ] {
121 if single(pairs, name) == Single::Repeated {
122 return Err(refuse("invalid_request"));
123 }
124 }
125 match single(pairs, "response_type") {
126 Single::One("code") => {}
127 Single::One(_) => return Err(refuse("unsupported_response_type")),
128 _ => return Err(refuse("invalid_request")),
129 }
130 // Only the query response mode exists (contracts section 2.1). Any other value is refused, not ignored.
131 match single(pairs, "response_mode") {
132 Single::Absent | Single::One("query") => {}
133 _ => return Err(refuse("invalid_request")),
134 }
135 let challenge = match single(pairs, "code_challenge") {
136 Single::One(value) if is_valid_challenge(value) => value.to_owned(),
137 _ => return Err(refuse("invalid_request")),
138 };
139 // `plain` and a missing method are refused: PKCE S256 is mandatory (contracts section 2.3).
140 if single(pairs, "code_challenge_method") != Single::One("S256") {
141 return Err(refuse("invalid_request"));
142 }
143 let nonce = match single(pairs, "nonce") {
144 Single::Absent => None,
145 Single::One(value) if usable_echo(value) => Some(value.to_owned()),
146 _ => return Err(refuse("invalid_request")),
147 };
148 let Single::One(requested) = single(pairs, "scope") else {
149 return Err(refuse("invalid_request"));
150 };
151 let mut granted: Vec<&str> = Vec::new();
152 for word in requested.split_whitespace() {
153 if !is_supported_scope(word) {
154 return Err(refuse("invalid_scope"));
155 }
156 if is_user_scope(word) && client.allows_scope(word) && !granted.contains(&word) {
157 granted.push(word);
158 }
159 }
160 if !granted.contains(&"openid") {
161 return Err(refuse("invalid_scope"));
162 }
163 // `none` and `login` are offered, alone (OIDC Core 3.1.2.6: `none` may not be combined). Consent and
164 // account selection are not offered; say so instead of ignoring them.
165 let (no_prompt, force_login) = match single(pairs, "prompt") {
166 Single::Absent => (false, false),
167 Single::One(value) => match value.split_whitespace().collect::<Vec<_>>().as_slice() {
168 [] => (false, false),
169 ["none"] => (true, false),
170 ["login"] => (false, true),
171 _ => return Err(refuse("invalid_request")),
172 },
173 Single::Repeated => return Err(refuse("invalid_request")),
174 };
175 let max_age = match single(pairs, "max_age") {
176 Single::Absent => None,
177 Single::One(value) => match parse_max_age(value) {
178 Some(seconds) => Some(seconds),
179 None => return Err(refuse("invalid_request")),
180 },
181 Single::Repeated => return Err(refuse("invalid_request")),
182 };
183 Ok(Asked {
184 state,
185 challenge,
186 nonce,
187 scope: granted.join(" "),
188 no_prompt,
189 max_age,
190 force_login,
191 })
192}
193
194/// The redirect to the sign-in page, with this exact request as `next`, so the request continues after
195/// the sign-in.
196fn sign_in_again(cx: &Cx) -> SeeOther {
197 // The login page checks `next` as a local path.
198 let back = uri(cx)
199 .path_and_query()
200 .map_or("/authorize", |p| p.as_str());
201 see_other(format!("/login?next={}", percent_encode(back)))
202}
203
204/// The redirect that carries a refusal to the client.
205fn refusal_redirect(redirect_uri: &str, issuer: &str, refused: &Refused) -> SeeOther {
206 let mut params = vec![("error", refused.code), ("iss", issuer)];
207 if let Some(state) = refused.state.as_deref() {
208 params.push(("state", state));
209 }
210 see_other(with_query(redirect_uri, &params))
211}
212
213/// `GET /authorize`.
214///
215/// Every answer is either a redirect (`Err` carrying a `SeeOther`) or the error page, which is the only
216/// `Ok` value. A request with an unknown client or an unregistered redirect URI never reaches a
217/// redirect.
218#[page(GET "/authorize")]
219async fn authorize(cx: &Cx) -> Result<impl View> {
220 let app = app_context::<AppState>(cx);
221 let lang = page_lang(cx, None);
222 let Some(pairs) = parse_pairs(uri(cx).query().unwrap_or_default().as_bytes()) else {
223 return Ok(error_page(cx, lang));
224 };
225 let Some(client_id) = one(&pairs, "client_id") else {
226 return Ok(error_page(cx, lang));
227 };
228 let Some(redirect_uri) = one(&pairs, "redirect_uri") else {
229 return Ok(error_page(cx, lang));
230 };
231 let client = match app.store.client_by_id(client_id).await? {
232 Some(client)
233 if !client.is_disabled()
234 && client
235 .redirect_uris
236 .iter()
237 .any(|registered| registered == redirect_uri) =>
238 {
239 client
240 }
241 _ => return Ok(error_page(cx, lang)),
242 };
243
244 // From here on the redirect URI is the registered one, so every refusal may go to it.
245 let issuer = issuer(app);
246 let asked = match read(&pairs, &client) {
247 Ok(asked) => asked,
248 Err(refused) => return Err(refusal_redirect(redirect_uri, issuer, &refused).into()),
249 };
250 let Some(viewer) = current_user(cx).await? else {
251 if asked.no_prompt {
252 let refused = Refused {
253 code: "login_required",
254 state: asked.state.clone(),
255 };
256 return Err(refusal_redirect(redirect_uri, issuer, &refused).into());
257 }
258 return Err(sign_in_again(cx).into());
259 };
260
261 // The sign-in that created the session is the authentication time (`sessions.auth_time`, which a
262 // new sign-in always sets to now). An unreadable stamp counts as very old, so it fails closed.
263 let auth_time = unix_seconds(&viewer.session.auth_time).unwrap_or(i64::MIN);
264 if reauth_due(asked.max_age, asked.force_login, auth_time, unix_now()) {
265 if asked.no_prompt {
266 let refused = Refused {
267 code: "login_required",
268 state: asked.state.clone(),
269 };
270 return Err(refusal_redirect(redirect_uri, issuer, &refused).into());
271 }
272 return Err(sign_in_again(cx).into());
273 }
274
275 // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a
276 // prompt=none request cannot show a page, so it is refused instead.
277 if viewer.user.is_admin && app.policy().require_2fa_for_admins && !viewer.user.totp_enabled() {
278 if asked.no_prompt {
279 let refused = Refused {
280 code: "interaction_required",
281 state: asked.state.clone(),
282 };
283 return Err(refusal_redirect(redirect_uri, issuer, &refused).into());
284 }
285 return Err(see_other("/account/security?notice=enrol").into());
286 }
287
288 // Each issue adds a row that lives a day, so a session that repeats the request is limited. The refusal
289 // goes to the registered redirect URI like the other refusals of this request.
290 if app
291 .per_minute
292 .reserve(
293 &authorize_session_key(&viewer.session.id),
294 AUTHORIZE_SESSION_LIMIT,
295 Instant::now(),
296 )
297 .is_err()
298 {
299 let refused = Refused {
300 code: "temporarily_unavailable",
301 state: asked.state.clone(),
302 };
303 return Err(refusal_redirect(redirect_uri, issuer, &refused).into());
304 }
305
306 let code = generate_token();
307 let expires_at = stamp_after(CODE_TTL);
308 app.store
309 .insert_auth_code(&NewAuthCode {
310 code_hash: &hash_token(&code),
311 client_id: &client.id,
312 user_id: &viewer.user.id,
313 session_id: &viewer.session.id,
314 redirect_uri,
315 scope: &asked.scope,
316 nonce: asked.nonce.as_deref(),
317 code_challenge: &asked.challenge,
318 expires_at: &expires_at,
319 })
320 .await?;
321 app.store
322 .touch_client_session(&viewer.session.id, &client.id)
323 .await?;
324
325 let mut params = vec![("code", code.as_str()), ("iss", issuer)];
326 if let Some(state) = asked.state.as_deref() {
327 params.push(("state", state));
328 }
329 Err(see_other(with_query(redirect_uri, &params)).into())
330}
331
332/// The error page: a 400 in the shell, with no redirect and no detail about the request.
333fn error_page(cx: &Cx, lang: Lang) -> impl View {
334 view! { cx =>
335 (StatusCode::BAD_REQUEST)
336 shell(title: text(lang, OidcText::ErrorTitle), lang: lang, viewer: None, error_body(lang: lang))
337 }
338}
339
340/// The body of the error page.
341#[component]
342async fn error_body(lang: Lang) -> Result<impl View> {
343 Ok(view! {
344 <section class="not-found">
345 <p>(text(lang, OidcText::ErrorBody))</p>
346 </section>
347 })
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353
354 #[test]
355 fn max_age_is_digits_only_and_the_grace_keeps_max_age_zero_from_looping() {
356 assert_eq!(parse_max_age("0"), Some(0));
357 assert_eq!(parse_max_age("3600"), Some(3600));
358 for bad in ["", "-1", "+5", "1.5", " 5", "5s"] {
359 assert_eq!(parse_max_age(bad), None, "{bad}");
360 }
361 let now = 1_000_000;
362 // A sign-in just now satisfies max_age=0 and prompt=login within the grace.
363 assert!(!reauth_due(Some(0), false, now - 5, now));
364 assert!(!reauth_due(None, true, now - 5, now));
365 // Older than the grace: max_age=0 and prompt=login send the person to sign in again.
366 assert!(reauth_due(Some(0), false, now - 61, now));
367 assert!(reauth_due(None, true, now - 61, now));
368 // max_age is compared with the age of the sign-in, and is never below the grace.
369 assert!(!reauth_due(Some(3600), false, now - 3600, now));
370 assert!(reauth_due(Some(3600), false, now - 3601, now));
371 // Without max_age or prompt=login nothing is due, however old the sign-in.
372 assert!(!reauth_due(None, false, now - 1_000_000, now));
373 }
374}