forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

token.rs564 lines, 21.7 KiBHistoryRawDownload
1//! `POST /token` (contracts section 2.3, step 3, and refresh): client authentication, the
2//! authorization-code grant and the refresh-token grant, and the token response.
3//!
4//! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The
5//! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every
6//! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one
7//! revokes its whole family. The client-credentials grant issues the machine tokens of contracts.md 2.6.
8//! A disabled client fails client authentication, so no grant runs for it: its refresh tokens and its
9//! machine tokens are refused at once.
10
11use std::time::Instant;
12
13use base64::prelude::{BASE64_STANDARD, Engine as _};
14use http::header::{AUTHORIZATION, RETRY_AFTER};
15use im_core::model::{AuthCode, Client, Session, User, amr};
16use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key};
17use im_core::oauth::{is_valid_verifier, pkce_s256};
18use im_core::store::new_id;
19use im_core::store::oidc::NewRefreshToken;
20use im_core::time::{now_stamp, stamp_after, stamp_of_unix, unix_now, unix_seconds};
21use im_core::token::{constant_time_eq, generate_token, hash_token};
22use serde_json::{Map, Value, json};
23use topcoat::Result;
24use topcoat::context::{Cx, app_context};
25use topcoat::router::request::{content_type, headers};
26use topcoat::router::response::Response;
27use topcoat::router::{Body, HeaderValue, StatusCode, route, to_bytes};
28
29use super::signing;
30use super::{
31 ACCESS_TTL, ID_TOKEN_TTL, Pairs, REFRESH_TTL, Single, TOKEN_BODY_LIMIT, USERINFO_AUDIENCE,
32 invalid_client, invalid_grant, issuer, json_response, oauth_error, one, parse_pairs, single,
33};
34use crate::state::AppState;
35use crate::throttle::{
36 TOKEN_CHAIN_LIMIT, TOKEN_CLIENT_LIMIT, token_client_key, token_code_key, token_family_key,
37};
38
39/// `POST /token`.
40#[route(POST "/token")]
41async fn token_endpoint(cx: &Cx, body: Body) -> Result<Response> {
42 let app = app_context::<AppState>(cx);
43 if !is_form(content_type(cx)) {
44 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));
45 }
46 let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else {
47 return Ok(oauth_error(
48 StatusCode::PAYLOAD_TOO_LARGE,
49 "invalid_request",
50 ));
51 };
52 let Some(pairs) = parse_pairs(&bytes) else {
53 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));
54 };
55 let authorization = headers(cx)
56 .get(AUTHORIZATION)
57 .and_then(|value| value.to_str().ok())
58 .map(str::to_owned);
59 let client = match authenticate(app, authorization.as_deref(), &pairs).await? {
60 Ok(client) => client,
61 Err(response) => return Ok(response),
62 };
63 // Counted after the client is authenticated, so a caller without the secret cannot use up a client's
64 // allowance. The client's ceiling applies to every grant; a chain or a code has its own lower limit,
65 // counted once the grant has found its row (see the grants).
66 if let Some(response) = throttled(app, &token_client_key(&client.id), TOKEN_CLIENT_LIMIT) {
67 return Ok(response);
68 }
69 match one(&pairs, "grant_type") {
70 Some("authorization_code") => grant_code(app, &client, &pairs).await,
71 Some("refresh_token") => grant_refresh(app, &client, &pairs).await,
72 Some("client_credentials") => grant_client(app, &client, &pairs).await,
73 Some(_) => Ok(oauth_error(
74 StatusCode::BAD_REQUEST,
75 "unsupported_grant_type",
76 )),
77 None => Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")),
78 }
79}
80
81/// Counts one request under `key` against `limit` per minute. Over the limit the answer is a 429 with the
82/// wait, in the OAuth error form; otherwise `None`.
83fn throttled(app: &AppState, key: &str, limit: usize) -> Option<Response> {
84 let wait = app.per_minute.reserve(key, limit, Instant::now()).err()?;
85 let mut response = oauth_error(StatusCode::TOO_MANY_REQUESTS, "invalid_request");
86 response
87 .headers_mut()
88 .insert(RETRY_AFTER, HeaderValue::from(wait.as_secs().max(1)));
89 Some(response)
90}
91
92/// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and
93/// client authentication as `/token`. The inner `Err` is the refusal to send.
94pub(super) async fn client_form(
95 cx: &Cx,
96 body: Body,
97) -> Result<std::result::Result<(Client, Pairs), Response>> {
98 let app = app_context::<AppState>(cx);
99 if !is_form(content_type(cx)) {
100 return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")));
101 }
102 let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else {
103 return Ok(Err(oauth_error(
104 StatusCode::PAYLOAD_TOO_LARGE,
105 "invalid_request",
106 )));
107 };
108 let Some(pairs) = parse_pairs(&bytes) else {
109 return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")));
110 };
111 let authorization = headers(cx)
112 .get(AUTHORIZATION)
113 .and_then(|value| value.to_str().ok())
114 .map(str::to_owned);
115 match authenticate(app, authorization.as_deref(), &pairs).await? {
116 Ok(client) => Ok(Ok((client, pairs))),
117 Err(response) => Ok(Err(response)),
118 }
119}
120
121/// True for a form body, with or without parameters after the media type.
122fn is_form(content_type: Option<&str>) -> bool {
123 content_type.is_some_and(|value| {
124 value
125 .split(';')
126 .next()
127 .unwrap_or_default()
128 .trim()
129 .eq_ignore_ascii_case("application/x-www-form-urlencoded")
130 })
131}
132
133/// The `client_id` and `client_secret` of a `Basic` credential, percent-decoded (RFC 6749 section
134/// 2.3.1). `None` when the header is not a Basic one; `Some(Err)` when it is Basic but malformed.
135fn basic_credentials(header: &str) -> Option<std::result::Result<(String, String), ()>> {
136 let (scheme, encoded) = header.split_once(' ')?;
137 if !scheme.eq_ignore_ascii_case("basic") {
138 return None;
139 }
140 let decoded = BASE64_STANDARD
141 .decode(encoded.trim())
142 .ok()
143 .and_then(|bytes| String::from_utf8(bytes).ok());
144 let parsed = decoded.as_deref().and_then(|text| {
145 let (id, secret) = text.split_once(':')?;
146 Some((super::percent_decode(id)?, super::percent_decode(secret)?))
147 });
148 Some(parsed.ok_or(()))
149}
150
151/// Authenticates the client. The outer `Result` is a server failure; the inner one is either the client
152/// or the response that refuses the request.
153pub(super) async fn authenticate(
154 app: &AppState,
155 authorization: Option<&str>,
156 pairs: &Pairs,
157) -> Result<std::result::Result<Client, Response>> {
158 let basic = match authorization.and_then(basic_credentials) {
159 Some(Ok(credentials)) => Some(credentials),
160 Some(Err(())) => return Ok(Err(invalid_client())),
161 None => None,
162 };
163 let form_id = single(pairs, "client_id");
164 let form_secret = single(pairs, "client_secret");
165 if form_id == Single::Repeated || form_secret == Single::Repeated {
166 return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")));
167 }
168 let (client_id, secret) = match basic {
169 Some((id, secret)) => {
170 // Two methods at once are refused, and so is a body id that names another client.
171 if matches!(form_secret, Single::One(_))
172 || matches!(form_id, Single::One(other) if other != id)
173 {
174 return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")));
175 }
176 (id, secret)
177 }
178 None => match (form_id, form_secret) {
179 (Single::One(id), Single::One(secret)) => (id.to_owned(), secret.to_owned()),
180 _ => return Ok(Err(invalid_client())),
181 },
182 };
183 let client = app.store.client_by_id(&client_id).await?;
184 // The hash is computed even for an unknown client, so the time does not reveal it.
185 let presented = hash_token(&secret);
186 let secret_ok = client
187 .as_ref()
188 .is_some_and(|known| constant_time_eq(presented.as_bytes(), known.secret_hash.as_bytes()));
189 match client {
190 Some(client) if secret_ok && !client.is_disabled() => Ok(Ok(client)),
191 _ => Ok(Err(invalid_client())),
192 }
193}
194
195/// The authorization-code grant (contracts section 2.3, step 3).
196async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Response> {
197 let (Some(code), Some(redirect_uri), Some(verifier)) = (
198 one(pairs, "code"),
199 one(pairs, "redirect_uri"),
200 one(pairs, "code_verifier"),
201 ) else {
202 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));
203 };
204 let code_hash = hash_token(code);
205 let Some(row) = app.store.auth_code(&code_hash).await? else {
206 return Ok(invalid_grant());
207 };
208 // A code belongs to one client. A wrong client is refused without touching the code.
209 if row.client_id != client.id {
210 return Ok(invalid_grant());
211 }
212 if let Some(response) = throttled(
213 app,
214 &token_code_key(&client.id, &code_hash),
215 TOKEN_CHAIN_LIMIT,
216 ) {
217 return Ok(response);
218 }
219 if row.used_at.is_some() {
220 // The code was exchanged before. Whoever holds the tokens made from it must lose them, the access
221 // token included.
222 app.store.revoke_code_refresh_tokens(&code_hash).await?;
223 revoke_code_access(app, &row).await?;
224 return Ok(invalid_grant());
225 }
226 let pkce_ok = is_valid_verifier(verifier)
227 && constant_time_eq(
228 pkce_s256(verifier).as_bytes(),
229 row.code_challenge.as_bytes(),
230 );
231 if !pkce_ok || row.redirect_uri != redirect_uri || row.expires_at <= now_stamp() {
232 return Ok(invalid_grant());
233 }
234 let Some(session) = app.store.live_session(&row.session_id).await? else {
235 return Ok(invalid_grant());
236 };
237 let Some(user) = app
238 .store
239 .user_by_id(&row.user_id)
240 .await?
241 .filter(|u| !u.is_disabled())
242 else {
243 return Ok(invalid_grant());
244 };
245
246 let refresh = generate_token();
247 let refresh_id = new_id();
248 let refresh_expires = stamp_after(REFRESH_TTL);
249 // The access token's jti and expiry are recorded with the redemption, so a replay can revoke it.
250 let access_jti = generate_token();
251 let access_exp = access_expiry();
252 let access_expires_at = stamp_of_unix(access_exp).ok_or_else(|| {
253 im_core::Error::Database("the access token's expiry is out of range".into())
254 })?;
255 let first = NewRefreshToken {
256 id: &refresh_id,
257 token_hash: &hash_token(&refresh),
258 family_id: &refresh_id,
259 client_id: &client.id,
260 user_id: &user.id,
261 session_id: &session.id,
262 code_hash: Some(&code_hash),
263 scope: &row.scope,
264 expires_at: &refresh_expires,
265 };
266 if !app
267 .store
268 .redeem_auth_code(&code_hash, &access_jti, &access_expires_at, &first)
269 .await?
270 {
271 // A parallel exchange of the same code won the race: that is a reuse. The winner's access token
272 // was recorded in its own redemption, so it is read again and revoked too.
273 app.store.revoke_code_refresh_tokens(&code_hash).await?;
274 if let Some(winner) = app.store.auth_code(&code_hash).await? {
275 revoke_code_access(app, &winner).await?;
276 }
277 return Ok(invalid_grant());
278 }
279
280 let id_token = id_token(
281 app,
282 &user,
283 client,
284 &session,
285 &row.scope,
286 row.nonce.as_deref(),
287 )
288 .await?;
289 let access_token = access_token(
290 app,
291 &user,
292 client,
293 &session,
294 &row.scope,
295 (&access_jti, access_exp),
296 )
297 .await?;
298 Ok(token_response(
299 access_token,
300 &row.scope,
301 Some(id_token),
302 Some(refresh),
303 ))
304}
305
306/// The refresh-token grant (contracts section 2.3, refresh): rotates the token and issues a new access
307/// token. No ID token is issued here: a refresh carries no nonce.
308async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Response> {
309 let Some(presented) = one(pairs, "refresh_token") else {
310 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));
311 };
312 let Some(row) = app.store.refresh_token(&hash_token(presented)).await? else {
313 return Ok(invalid_grant());
314 };
315 if row.client_id != client.id {
316 return Ok(invalid_grant());
317 }
318 // A refresh keeps the scope of its grant. A scope parameter is refused unless it stays inside that grant,
319 // so a client never believes it widened or changed its token. The token is not spent on a refusal.
320 if pairs.iter().any(|(name, _)| name == "scope") {
321 let within = one(pairs, "scope").is_some_and(|requested| {
322 requested
323 .split(' ')
324 .filter(|s| !s.is_empty())
325 .all(|s| row.scope.split(' ').any(|g| g == s))
326 });
327 if !within {
328 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope"));
329 }
330 }
331 if let Some(response) = throttled(
332 app,
333 &token_family_key(&client.id, &row.family_id),
334 TOKEN_CHAIN_LIMIT,
335 ) {
336 return Ok(response);
337 }
338 if row.used_at.is_some() {
339 // A rotated token came back. Either the holder or someone who copied it is replaying it:
340 // the whole chain is revoked, so both lose it.
341 app.store.revoke_refresh_family(&row.family_id).await?;
342 return Ok(invalid_grant());
343 }
344 if row.revoked_at.is_some() || row.expires_at <= now_stamp() {
345 return Ok(invalid_grant());
346 }
347 // A chain ends with its session, and with the user's account when that is disabled.
348 let Some(session) = app.store.live_session(&row.session_id).await? else {
349 return Ok(invalid_grant());
350 };
351 let Some(user) = app
352 .store
353 .user_by_id(&row.user_id)
354 .await?
355 .filter(|u| !u.is_disabled())
356 else {
357 return Ok(invalid_grant());
358 };
359 // The administrator policy holds for refresh too: an administrator without two-factor sign-in gets no
360 // more tokens, the same as the admin pages refuse them.
361 if user.is_admin && app.policy().require_2fa_for_admins && !user.totp_enabled() {
362 return Ok(invalid_grant());
363 }
364
365 let refresh = generate_token();
366 let refresh_id = new_id();
367 let refresh_expires = stamp_after(REFRESH_TTL);
368 let next = NewRefreshToken {
369 id: &refresh_id,
370 token_hash: &hash_token(&refresh),
371 family_id: &row.family_id,
372 client_id: &client.id,
373 user_id: &user.id,
374 session_id: &session.id,
375 code_hash: row.code_hash.as_deref(),
376 scope: &row.scope,
377 expires_at: &refresh_expires,
378 };
379 if !app.store.rotate_refresh_token(&row.id, &next).await? {
380 // A parallel refresh with the same token won the race: that is a reuse.
381 app.store.revoke_refresh_family(&row.family_id).await?;
382 return Ok(invalid_grant());
383 }
384 let access_jti = generate_token();
385 let access_token = access_token(
386 app,
387 &user,
388 client,
389 &session,
390 &row.scope,
391 (&access_jti, access_expiry()),
392 )
393 .await?;
394 Ok(token_response(
395 access_token,
396 &row.scope,
397 None,
398 Some(refresh),
399 ))
400}
401
402/// The client-credentials grant (contracts.md 2.6): a machine token that a family service presents to
403/// another family service. The caller must be a family service (its key is `svc`), every requested scope
404/// must be a machine scope the client is allowed, and the audience must be a known family key. The token
405/// is addressed to that key, so it cannot be presented to any other service.
406async fn grant_client(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Response> {
407 let Some(caller) = client.service_key.as_deref() else {
408 return Ok(oauth_error(StatusCode::BAD_REQUEST, "unauthorized_client"));
409 };
410 let (Some(requested), Some(audience)) = (one(pairs, "scope"), one(pairs, "audience")) else {
411 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));
412 };
413 let mut granted: Vec<&str> = Vec::new();
414 for word in requested.split_whitespace() {
415 // A person's scopes never come from this grant, so a user scope is refused like an unknown one.
416 if !is_supported_scope(word) || is_user_scope(word) || !client.allows_scope(word) {
417 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope"));
418 }
419 if !granted.contains(&word) {
420 granted.push(word);
421 }
422 }
423 if granted.is_empty() {
424 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope"));
425 }
426 // `im` itself is always a known audience; any other one needs a registered family client.
427 let known = audience == USERINFO_AUDIENCE
428 || (is_valid_family_key(audience) && app.store.family_key_known(audience).await?);
429 if !known {
430 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_target"));
431 }
432 let scope = granted.join(" ");
433 let now = unix_now();
434 let claims = json!({
435 "iss": issuer(app),
436 "sub": format!("client:{}", client.id),
437 "azp": client.id,
438 "aud": audience,
439 "scope": scope,
440 "svc": caller,
441 "iat": now,
442 "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0),
443 "jti": generate_token(),
444 });
445 let token = signing::sign(&app.store, &app.key, &claims).await?;
446 Ok(token_response(token, &scope, None, None))
447}
448
449/// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires.
450fn token_response(
451 access_token: String,
452 scope: &str,
453 id_token: Option<String>,
454 refresh_token: Option<String>,
455) -> Response {
456 let mut body = json!({
457 "access_token": access_token,
458 "token_type": "Bearer",
459 "expires_in": ACCESS_TTL.as_secs(),
460 "scope": scope,
461 });
462 if let (Some(object), Some(id_token)) = (body.as_object_mut(), id_token) {
463 object.insert("id_token".into(), Value::String(id_token));
464 }
465 if let (Some(object), Some(refresh)) = (body.as_object_mut(), refresh_token) {
466 object.insert("refresh_token".into(), Value::String(refresh));
467 }
468 json_response(StatusCode::OK, &body)
469}
470
471/// The claims about the person that a scope grants. `email` gates the address; `profile` gates the
472/// name, the language, the time zone, the administrator flag and the picture version (contracts 2.3).
473pub fn person_claims(user: &User, scope: &str) -> Map<String, Value> {
474 let granted = |name: &str| scope.split_whitespace().any(|word| word == name);
475 let mut claims = Map::new();
476 if granted("email") {
477 claims.insert("email".into(), json!(user.email));
478 // Only confirmed addresses are stored, so the flag is always true.
479 claims.insert("email_verified".into(), json!(true));
480 }
481 if granted("profile") {
482 claims.insert("name".into(), json!(user.name));
483 claims.insert("admin".into(), json!(user.is_admin));
484 // An account that follows the browser's language has no stored locale to share.
485 if !user.locale_auto {
486 claims.insert("locale".into(), json!(user.locale));
487 }
488 claims.insert("zoneinfo".into(), json!(user.zoneinfo));
489 claims.insert("picture_version".into(), json!(user.picture_version));
490 }
491 claims
492}
493
494/// When an access token issued now expires, in Unix seconds.
495fn access_expiry() -> i64 {
496 unix_now() + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0)
497}
498
499/// Revokes the access token issued with an authorization code, when the code recorded one. From then on
500/// it is refused, as a token revoked at `/revoke` is.
501async fn revoke_code_access(app: &AppState, code: &AuthCode) -> im_core::Result<()> {
502 if let (Some(jti), Some(expires_at)) = (&code.access_jti, &code.access_expires_at) {
503 app.store.revoke_access_token(jti, expires_at).await?;
504 }
505 Ok(())
506}
507
508/// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to
509/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. Its
510/// `jti` and expiry are given by the caller, which records them when it needs to revoke the token.
511async fn access_token(
512 app: &AppState,
513 user: &User,
514 client: &Client,
515 session: &Session,
516 scope: &str,
517 (jti, exp): (&str, i64),
518) -> im_core::Result<String> {
519 let claims = json!({
520 "iss": issuer(app),
521 "sub": user.id,
522 "aud": USERINFO_AUDIENCE,
523 "azp": client.id,
524 "scope": scope,
525 "sid": session.id,
526 "iat": unix_now(),
527 "exp": exp,
528 "jti": jti,
529 });
530 signing::sign(&app.store, &app.key, &claims).await
531}
532
533/// The ID token (OIDC Core section 2): who signed in, when and how, for which client and nonce.
534async fn id_token(
535 app: &AppState,
536 user: &User,
537 client: &Client,
538 session: &Session,
539 scope: &str,
540 nonce: Option<&str>,
541) -> im_core::Result<String> {
542 let now = im_core::time::unix_now();
543 // A stored stamp that does not parse is a server fault: it is never replaced by the current time.
544 let auth_time = unix_seconds(&session.auth_time).ok_or_else(|| {
545 im_core::Error::Database("the session's auth_time is not a stored stamp".into())
546 })?;
547 let mut claims = json!({
548 "iss": issuer(app),
549 "sub": user.id,
550 "aud": client.id,
551 "iat": now,
552 "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0),
553 "auth_time": auth_time,
554 "sid": session.id,
555 "amr": amr::rfc8176(&session.amr),
556 });
557 if let Some(object) = claims.as_object_mut() {
558 if let Some(nonce) = nonce {
559 object.insert("nonce".into(), json!(nonce));
560 }
561 object.extend(person_claims(user, scope));
562 }
563 signing::sign(&app.store, &app.key, &claims).await
564}