//! `POST /token` (contracts section 2.3, step 3, and refresh): client authentication, the //! authorization-code grant and the refresh-token grant, and the token response. //! //! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The //! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every //! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one //! revokes its whole family. The client-credentials grant issues the machine tokens of contracts.md 2.6. //! A disabled client fails client authentication, so no grant runs for it: its refresh tokens and its //! machine tokens are refused at once. use std::time::Instant; use base64::prelude::{BASE64_STANDARD, Engine as _}; use http::header::{AUTHORIZATION, RETRY_AFTER}; use im_core::model::{AuthCode, Client, Session, User, amr}; use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; use im_core::oauth::{is_valid_verifier, pkce_s256}; use im_core::store::new_id; use im_core::store::oidc::NewRefreshToken; use im_core::time::{now_stamp, stamp_after, stamp_of_unix, unix_now, unix_seconds}; use im_core::token::{constant_time_eq, generate_token, hash_token}; use serde_json::{Map, Value, json}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::request::{content_type, headers}; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderValue, StatusCode, route, to_bytes}; use super::signing; use super::{ ACCESS_TTL, ID_TOKEN_TTL, Pairs, REFRESH_TTL, Single, TOKEN_BODY_LIMIT, USERINFO_AUDIENCE, invalid_client, invalid_grant, issuer, json_response, oauth_error, one, parse_pairs, single, }; use crate::state::AppState; use crate::throttle::{ TOKEN_CHAIN_LIMIT, TOKEN_CLIENT_LIMIT, token_client_key, token_code_key, token_family_key, }; /// `POST /token`. #[route(POST "/token")] async fn token_endpoint(cx: &Cx, body: Body) -> Result { let app = app_context::(cx); if !is_form(content_type(cx)) { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); } let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else { return Ok(oauth_error( StatusCode::PAYLOAD_TOO_LARGE, "invalid_request", )); }; let Some(pairs) = parse_pairs(&bytes) else { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); }; let authorization = headers(cx) .get(AUTHORIZATION) .and_then(|value| value.to_str().ok()) .map(str::to_owned); let client = match authenticate(app, authorization.as_deref(), &pairs).await? { Ok(client) => client, Err(response) => return Ok(response), }; // Counted after the client is authenticated, so a caller without the secret cannot use up a client's // allowance. The client's ceiling applies to every grant; a chain or a code has its own lower limit, // counted once the grant has found its row (see the grants). if let Some(response) = throttled(app, &token_client_key(&client.id), TOKEN_CLIENT_LIMIT) { return Ok(response); } match one(&pairs, "grant_type") { Some("authorization_code") => grant_code(app, &client, &pairs).await, Some("refresh_token") => grant_refresh(app, &client, &pairs).await, Some("client_credentials") => grant_client(app, &client, &pairs).await, Some(_) => Ok(oauth_error( StatusCode::BAD_REQUEST, "unsupported_grant_type", )), None => Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")), } } /// Counts one request under `key` against `limit` per minute. Over the limit the answer is a 429 with the /// wait, in the OAuth error form; otherwise `None`. fn throttled(app: &AppState, key: &str, limit: usize) -> Option { let wait = app.per_minute.reserve(key, limit, Instant::now()).err()?; let mut response = oauth_error(StatusCode::TOO_MANY_REQUESTS, "invalid_request"); response .headers_mut() .insert(RETRY_AFTER, HeaderValue::from(wait.as_secs().max(1))); Some(response) } /// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and /// client authentication as `/token`. The inner `Err` is the refusal to send. pub(super) async fn client_form( cx: &Cx, body: Body, ) -> Result> { let app = app_context::(cx); if !is_form(content_type(cx)) { return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); } let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else { return Ok(Err(oauth_error( StatusCode::PAYLOAD_TOO_LARGE, "invalid_request", ))); }; let Some(pairs) = parse_pairs(&bytes) else { return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); }; let authorization = headers(cx) .get(AUTHORIZATION) .and_then(|value| value.to_str().ok()) .map(str::to_owned); match authenticate(app, authorization.as_deref(), &pairs).await? { Ok(client) => Ok(Ok((client, pairs))), Err(response) => Ok(Err(response)), } } /// True for a form body, with or without parameters after the media type. fn is_form(content_type: Option<&str>) -> bool { content_type.is_some_and(|value| { value .split(';') .next() .unwrap_or_default() .trim() .eq_ignore_ascii_case("application/x-www-form-urlencoded") }) } /// The `client_id` and `client_secret` of a `Basic` credential, percent-decoded (RFC 6749 section /// 2.3.1). `None` when the header is not a Basic one; `Some(Err)` when it is Basic but malformed. fn basic_credentials(header: &str) -> Option> { let (scheme, encoded) = header.split_once(' ')?; if !scheme.eq_ignore_ascii_case("basic") { return None; } let decoded = BASE64_STANDARD .decode(encoded.trim()) .ok() .and_then(|bytes| String::from_utf8(bytes).ok()); let parsed = decoded.as_deref().and_then(|text| { let (id, secret) = text.split_once(':')?; Some((super::percent_decode(id)?, super::percent_decode(secret)?)) }); Some(parsed.ok_or(())) } /// Authenticates the client. The outer `Result` is a server failure; the inner one is either the client /// or the response that refuses the request. pub(super) async fn authenticate( app: &AppState, authorization: Option<&str>, pairs: &Pairs, ) -> Result> { let basic = match authorization.and_then(basic_credentials) { Some(Ok(credentials)) => Some(credentials), Some(Err(())) => return Ok(Err(invalid_client())), None => None, }; let form_id = single(pairs, "client_id"); let form_secret = single(pairs, "client_secret"); if form_id == Single::Repeated || form_secret == Single::Repeated { return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); } let (client_id, secret) = match basic { Some((id, secret)) => { // Two methods at once are refused, and so is a body id that names another client. if matches!(form_secret, Single::One(_)) || matches!(form_id, Single::One(other) if other != id) { return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); } (id, secret) } None => match (form_id, form_secret) { (Single::One(id), Single::One(secret)) => (id.to_owned(), secret.to_owned()), _ => return Ok(Err(invalid_client())), }, }; let client = app.store.client_by_id(&client_id).await?; // The hash is computed even for an unknown client, so the time does not reveal it. let presented = hash_token(&secret); let secret_ok = client .as_ref() .is_some_and(|known| constant_time_eq(presented.as_bytes(), known.secret_hash.as_bytes())); match client { Some(client) if secret_ok && !client.is_disabled() => Ok(Ok(client)), _ => Ok(Err(invalid_client())), } } /// The authorization-code grant (contracts section 2.3, step 3). async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result { let (Some(code), Some(redirect_uri), Some(verifier)) = ( one(pairs, "code"), one(pairs, "redirect_uri"), one(pairs, "code_verifier"), ) else { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); }; let code_hash = hash_token(code); let Some(row) = app.store.auth_code(&code_hash).await? else { return Ok(invalid_grant()); }; // A code belongs to one client. A wrong client is refused without touching the code. if row.client_id != client.id { return Ok(invalid_grant()); } if let Some(response) = throttled( app, &token_code_key(&client.id, &code_hash), TOKEN_CHAIN_LIMIT, ) { return Ok(response); } if row.used_at.is_some() { // The code was exchanged before. Whoever holds the tokens made from it must lose them, the access // token included. app.store.revoke_code_refresh_tokens(&code_hash).await?; revoke_code_access(app, &row).await?; return Ok(invalid_grant()); } let pkce_ok = is_valid_verifier(verifier) && constant_time_eq( pkce_s256(verifier).as_bytes(), row.code_challenge.as_bytes(), ); if !pkce_ok || row.redirect_uri != redirect_uri || row.expires_at <= now_stamp() { return Ok(invalid_grant()); } let Some(session) = app.store.live_session(&row.session_id).await? else { return Ok(invalid_grant()); }; let Some(user) = app .store .user_by_id(&row.user_id) .await? .filter(|u| !u.is_disabled()) else { return Ok(invalid_grant()); }; let refresh = generate_token(); let refresh_id = new_id(); let refresh_expires = stamp_after(REFRESH_TTL); // The access token's jti and expiry are recorded with the redemption, so a replay can revoke it. let access_jti = generate_token(); let access_exp = access_expiry(); let access_expires_at = stamp_of_unix(access_exp).ok_or_else(|| { im_core::Error::Database("the access token's expiry is out of range".into()) })?; let first = NewRefreshToken { id: &refresh_id, token_hash: &hash_token(&refresh), family_id: &refresh_id, client_id: &client.id, user_id: &user.id, session_id: &session.id, code_hash: Some(&code_hash), scope: &row.scope, expires_at: &refresh_expires, }; if !app .store .redeem_auth_code(&code_hash, &access_jti, &access_expires_at, &first) .await? { // A parallel exchange of the same code won the race: that is a reuse. The winner's access token // was recorded in its own redemption, so it is read again and revoked too. app.store.revoke_code_refresh_tokens(&code_hash).await?; if let Some(winner) = app.store.auth_code(&code_hash).await? { revoke_code_access(app, &winner).await?; } return Ok(invalid_grant()); } let id_token = id_token( app, &user, client, &session, &row.scope, row.nonce.as_deref(), ) .await?; let access_token = access_token( app, &user, client, &session, &row.scope, (&access_jti, access_exp), ) .await?; Ok(token_response( access_token, &row.scope, Some(id_token), Some(refresh), )) } /// The refresh-token grant (contracts section 2.3, refresh): rotates the token and issues a new access /// token. No ID token is issued here: a refresh carries no nonce. async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result { let Some(presented) = one(pairs, "refresh_token") else { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); }; let Some(row) = app.store.refresh_token(&hash_token(presented)).await? else { return Ok(invalid_grant()); }; if row.client_id != client.id { return Ok(invalid_grant()); } // A refresh keeps the scope of its grant. A scope parameter is refused unless it stays inside that grant, // so a client never believes it widened or changed its token. The token is not spent on a refusal. if pairs.iter().any(|(name, _)| name == "scope") { let within = one(pairs, "scope").is_some_and(|requested| { requested .split(' ') .filter(|s| !s.is_empty()) .all(|s| row.scope.split(' ').any(|g| g == s)) }); if !within { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); } } if let Some(response) = throttled( app, &token_family_key(&client.id, &row.family_id), TOKEN_CHAIN_LIMIT, ) { return Ok(response); } if row.used_at.is_some() { // A rotated token came back. Either the holder or someone who copied it is replaying it: // the whole chain is revoked, so both lose it. app.store.revoke_refresh_family(&row.family_id).await?; return Ok(invalid_grant()); } if row.revoked_at.is_some() || row.expires_at <= now_stamp() { return Ok(invalid_grant()); } // A chain ends with its session, and with the user's account when that is disabled. let Some(session) = app.store.live_session(&row.session_id).await? else { return Ok(invalid_grant()); }; let Some(user) = app .store .user_by_id(&row.user_id) .await? .filter(|u| !u.is_disabled()) else { return Ok(invalid_grant()); }; // The administrator policy holds for refresh too: an administrator without two-factor sign-in gets no // more tokens, the same as the admin pages refuse them. if user.is_admin && app.policy().require_2fa_for_admins && !user.totp_enabled() { return Ok(invalid_grant()); } let refresh = generate_token(); let refresh_id = new_id(); let refresh_expires = stamp_after(REFRESH_TTL); let next = NewRefreshToken { id: &refresh_id, token_hash: &hash_token(&refresh), family_id: &row.family_id, client_id: &client.id, user_id: &user.id, session_id: &session.id, code_hash: row.code_hash.as_deref(), scope: &row.scope, expires_at: &refresh_expires, }; if !app.store.rotate_refresh_token(&row.id, &next).await? { // A parallel refresh with the same token won the race: that is a reuse. app.store.revoke_refresh_family(&row.family_id).await?; return Ok(invalid_grant()); } let access_jti = generate_token(); let access_token = access_token( app, &user, client, &session, &row.scope, (&access_jti, access_expiry()), ) .await?; Ok(token_response( access_token, &row.scope, None, Some(refresh), )) } /// The client-credentials grant (contracts.md 2.6): a machine token that a family service presents to /// another family service. The caller must be a family service (its key is `svc`), every requested scope /// must be a machine scope the client is allowed, and the audience must be a known family key. The token /// is addressed to that key, so it cannot be presented to any other service. async fn grant_client(app: &AppState, client: &Client, pairs: &Pairs) -> Result { let Some(caller) = client.service_key.as_deref() else { return Ok(oauth_error(StatusCode::BAD_REQUEST, "unauthorized_client")); }; let (Some(requested), Some(audience)) = (one(pairs, "scope"), one(pairs, "audience")) else { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); }; let mut granted: Vec<&str> = Vec::new(); for word in requested.split_whitespace() { // A person's scopes never come from this grant, so a user scope is refused like an unknown one. if !is_supported_scope(word) || is_user_scope(word) || !client.allows_scope(word) { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); } if !granted.contains(&word) { granted.push(word); } } if granted.is_empty() { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); } // `im` itself is always a known audience; any other one needs a registered family client. let known = audience == USERINFO_AUDIENCE || (is_valid_family_key(audience) && app.store.family_key_known(audience).await?); if !known { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_target")); } let scope = granted.join(" "); let now = unix_now(); let claims = json!({ "iss": issuer(app), "sub": format!("client:{}", client.id), "azp": client.id, "aud": audience, "scope": scope, "svc": caller, "iat": now, "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), "jti": generate_token(), }); let token = signing::sign(&app.store, &app.key, &claims).await?; Ok(token_response(token, &scope, None, None)) } /// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires. fn token_response( access_token: String, scope: &str, id_token: Option, refresh_token: Option, ) -> Response { let mut body = json!({ "access_token": access_token, "token_type": "Bearer", "expires_in": ACCESS_TTL.as_secs(), "scope": scope, }); if let (Some(object), Some(id_token)) = (body.as_object_mut(), id_token) { object.insert("id_token".into(), Value::String(id_token)); } if let (Some(object), Some(refresh)) = (body.as_object_mut(), refresh_token) { object.insert("refresh_token".into(), Value::String(refresh)); } json_response(StatusCode::OK, &body) } /// The claims about the person that a scope grants. `email` gates the address; `profile` gates the /// name, the language, the time zone, the administrator flag and the picture version (contracts 2.3). pub fn person_claims(user: &User, scope: &str) -> Map { let granted = |name: &str| scope.split_whitespace().any(|word| word == name); let mut claims = Map::new(); if granted("email") { claims.insert("email".into(), json!(user.email)); // Only confirmed addresses are stored, so the flag is always true. claims.insert("email_verified".into(), json!(true)); } if granted("profile") { claims.insert("name".into(), json!(user.name)); claims.insert("admin".into(), json!(user.is_admin)); // An account that follows the browser's language has no stored locale to share. if !user.locale_auto { claims.insert("locale".into(), json!(user.locale)); } claims.insert("zoneinfo".into(), json!(user.zoneinfo)); claims.insert("picture_version".into(), json!(user.picture_version)); } claims } /// When an access token issued now expires, in Unix seconds. fn access_expiry() -> i64 { unix_now() + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0) } /// Revokes the access token issued with an authorization code, when the code recorded one. From then on /// it is refused, as a token revoked at `/revoke` is. async fn revoke_code_access(app: &AppState, code: &AuthCode) -> im_core::Result<()> { if let (Some(jti), Some(expires_at)) = (&code.access_jti, &code.access_expires_at) { app.store.revoke_access_token(jti, expires_at).await?; } Ok(()) } /// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to /// and the client it was issued to (`azp`), so userinfo can check that the session still lives. Its /// `jti` and expiry are given by the caller, which records them when it needs to revoke the token. async fn access_token( app: &AppState, user: &User, client: &Client, session: &Session, scope: &str, (jti, exp): (&str, i64), ) -> im_core::Result { let claims = json!({ "iss": issuer(app), "sub": user.id, "aud": USERINFO_AUDIENCE, "azp": client.id, "scope": scope, "sid": session.id, "iat": unix_now(), "exp": exp, "jti": jti, }); signing::sign(&app.store, &app.key, &claims).await } /// The ID token (OIDC Core section 2): who signed in, when and how, for which client and nonce. async fn id_token( app: &AppState, user: &User, client: &Client, session: &Session, scope: &str, nonce: Option<&str>, ) -> im_core::Result { let now = im_core::time::unix_now(); // A stored stamp that does not parse is a server fault: it is never replaced by the current time. let auth_time = unix_seconds(&session.auth_time).ok_or_else(|| { im_core::Error::Database("the session's auth_time is not a stored stamp".into()) })?; let mut claims = json!({ "iss": issuer(app), "sub": user.id, "aud": client.id, "iat": now, "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), "auth_time": auth_time, "sid": session.id, "amr": amr::rfc8176(&session.amr), }); if let Some(object) = claims.as_object_mut() { if let Some(nonce) = nonce { object.insert("nonce".into(), json!(nonce)); } object.extend(person_claims(user, scope)); } signing::sign(&app.store, &app.key, &claims).await }