//! The authorization page and the error page, each the app the build //! embeds (`super::assets`) with its data, as `spec/OAUTH-PAGES.md` says; //! the API the app calls, and the redirect back //! to the client, as `spec/OAUTH.md` says. A browser is a *device*, named by //! a sealed `device-id` cookie; the accounts signed in on each device are //! kept, and a request is bound to the device that loads it. API calls carry //! the page's `csrf-token` cookie back as their `x-csrf-token` header. use super::{ EPHEMERAL_LIFE, REQUEST_LIFE, REQUEST_URI, Request, State, Tx, Whence, assets, client, clients, finish, json_response, new_id, scope, set, }; use crate::email::Purpose::AuthFactor; use crate::{Account, Service, Shared}; use axum::{ Extension, body::Body, extract::{Path, State as AxState}, http::{HeaderMap, Method, StatusCode, Uri, header}, response::{IntoResponse, Response}, }; use base64::Engine; use serde_json::{Map, Value as Json, json}; use sha2::{Digest, Sha256}; const DEVICE_COOKIE: &str = "device-id"; const CSRF_COOKIE: &str = "csrf-token"; /// How long a device cookie lasts in the browser. const DEVICE_COOKIE_LIFE: u64 = 365 * 24 * 60 * 60; /// How long after a device was last given new cookies a browser sending /// old ones is still that device. const DEVICE_GRACE: u64 = 30; /// A header's value as text, if it has one. pub(super) fn header_text<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> { headers.get(name).and_then(|v| v.to_str().ok()) } /// The cookies a request carries, by name; the first of a name counts. fn cookies(headers: &HeaderMap) -> Vec<(String, String)> { headers .get_all(header::COOKIE) .iter() .filter_map(|v| v.to_str().ok()) .flat_map(|v| v.split(';')) .filter_map(|c| { c.trim() .split_once('=') .map(|(k, v)| (k.to_string(), v.to_string())) }) .collect() } fn cookie(headers: &HeaderMap, name: &str) -> Option { cookies(headers) .into_iter() .find(|(k, _)| k == name) .map(|(_, v)| v) } /// The device a request is from, the key of the cookies to give it, if it /// is to be given any, and whether the request named a device, with /// cookies the server sealed. pub(super) struct Device { pub id: String, give: Option, pub named: bool, } impl Device { fn new() -> Device { Device { id: new_id(16), give: Some(new_id(16)), named: false, } } } /// The device a request is from (`spec/OAUTH.md`, "Devices"). A browser /// sending no cookie the server sealed is a new one; one sending its /// device's current cookies is that device, and so is one sending old ones /// within `DEVICE_GRACE` of the device's last new ones, given those. One /// sending old ones after that ends the device, every account signed out of /// it, logged in `tx`, and is a new one. fn device(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap) -> Device { let sealed = cookie(headers, DEVICE_COOKIE).and_then(|c| svc.oauth.unseal("device", &c)); let Some((id, key)) = sealed.and_then(|d| { Some(( d["id"].as_str()?.to_string(), d["key"].as_str().unwrap_or_default().to_string(), )) }) else { return Device::new(); }; tx.change(|st, now| match st.device_keys.get(&id) { None => ( vec![], Device { id, give: None, named: true, }, ), Some((current, _)) if *current == key => ( vec![], Device { id, give: None, named: true, }, ), Some((current, at)) if now.saturating_sub(*at) <= DEVICE_GRACE => ( vec![], Device { give: Some(current.clone()), id, named: true, }, ), Some(_) => ( vec![json!({ "t": "oauthDeviceEnd", "device": id })], Device { named: true, ..Device::new() }, ), }) } fn secure(svc: &Service) -> &'static str { if svc.oauth.issuer.starts_with("https:") { "; Secure" } else { "" } } /// Give a device the cookies it is to be given. fn device_cookie(svc: &Service, r: &mut Response, device: &Device) { let Some(key) = &device.give else { return }; let value = svc .oauth .seal("device", &json!({ "id": device.id, "key": key })); let c = format!( "{DEVICE_COOKIE}={value}; Path=/; Max-Age={DEVICE_COOKIE_LIFE}; HttpOnly; SameSite=Lax{}", secure(svc) ); if let Ok(v) = c.parse() { r.headers_mut().append(header::SET_COOKIE, v); } } /// A JSON value as `JSON.parse` takes it in a script: a JSON text as a JavaScript string literal. fn js_json(v: &Json) -> String { serde_json::to_string(&v.to_string()) .unwrap_or_default() .replace('<', "\\u003c") .replace('\u{2028}', "\\u2028") .replace('\u{2029}', "\\u2029") } fn html_escape(s: &str) -> String { s.replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('"', """) .replace('\'', "'") } /// The Content-Security-Policy of a page whose one inline script is `script` /// (`spec/OAUTH-PAGES.md`): scripts and stylesheets from the server alone, /// and that script, by its hash. fn csp(script: &str) -> String { let hash = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(script)); format!( "default-src 'none'; script-src 'self' 'sha256-{hash}'; style-src 'self'; img-src 'self' https: data:; \ connect-src 'self'; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" ) } /// A page: the app the build embeds (`super::assets`), and its data, as /// `window[""]=JSON.parse("…");` statements, its one inline script. pub(super) fn page(status: u16, title: &'static str, data: &[(&str, &Json)]) -> Response { let statements: String = data .iter() .map(|(name, v)| format!("window[\"{name}\"]=JSON.parse({});", js_json(v))) .collect(); let body = format!( "\n\ {title}{}\n
\n\ \n", assets::HEAD ); let mut r = ( StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body, ) .into_response(); set(&mut r, "cache-control", "no-store"); set(&mut r, "content-security-policy", &csp(&statements)); set(&mut r, "x-frame-options", "DENY"); set(&mut r, "x-content-type-options", "nosniff"); set(&mut r, "referrer-policy", "same-origin"); r } pub(super) fn error_page(status: u16, error: &str, description: &str) -> Response { page( status, "Something went wrong", &[( "__errorData", &json!({ "error": error, "error_description": description }), )], ) } pub(super) fn bad_page(description: &str) -> Response { error_page(400, "invalid_request", description) } /// Send the browser to a client's `redirect_uri` with `params`, as its response mode says. pub(super) fn redirect_to(mode: &str, redirect_uri: &str, params: &[(&str, String)]) -> Response { let Ok(mut u) = url::Url::parse(redirect_uri) else { return bad_page("Invalid redirect_uri"); }; let encoded = || { url::form_urlencoded::Serializer::new(String::new()) .extend_pairs(params.iter().map(|(k, v)| (*k, v.as_str()))) .finish() }; match mode { "query" | "fragment" => { if mode == "query" { u.query_pairs_mut() .extend_pairs(params.iter().map(|(k, v)| (*k, v.as_str()))); } else { u.set_fragment(Some(&encoded())); } let mut r = StatusCode::SEE_OTHER.into_response(); set(&mut r, "location", u.as_str()); set(&mut r, "cache-control", "no-store"); r } "form_post" => { let inputs: String = params .iter() .map(|(k, v)| { format!( "", html_escape(k), html_escape(v) ) }) .collect(); let body = format!( "\nRedirecting\
{inputs}
\ \n", html_escape(redirect_uri) ); let mut r = ( StatusCode::OK, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body, ) .into_response(); set(&mut r, "cache-control", "no-store"); r } _ => bad_page("Invalid redirect_mode"), } } /// The parameters a request's redirect back carries before its code or /// error: `iss`, its issuer's, and its `state`, if it has one (an MCP /// client's request may have none). fn back_params(svc: &Service, r: &Request) -> Vec<(&'static str, String)> { let mut params = vec![("iss", svc.oauth.issuer_of(r))]; if !r.state.is_empty() { params.push(("state", r.state.clone())); } params } /// The parameters of a request's error, as its redirect carries them. fn error_params( svc: &Service, r: &Request, error: &str, description: &str, ) -> Vec<(&'static str, String)> { let mut params = back_params(svc, r); params.push(("error", error.into())); params.push(("error_description", description.into())); params } /// The id a `request_uri` names, if it is of the form the server gives. fn request_id(request_uri: &str) -> Option<&str> { request_uri .strip_prefix(REQUEST_URI) .filter(|id| !id.is_empty()) } /// A request's query parameters, every one as given. pub(super) fn query(uri: &Uri) -> Vec<(String, String)> { url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) .into_owned() .collect() } pub(super) fn param<'q>(q: &'q [(String, String)], k: &str) -> Option<&'q str> { q.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) } /// An account, as the page and the API show it. pub(super) fn account_json(svc: &Service, a: &Account) -> Json { let m = crate::email::lock(&a.mail).clone(); let deactivated = crate::read(&a.state).deactivated; let mut out = json!({ "did": a.did, "pds": format!("did:web:{}", svc.config.hostname), "emailVerified": m.confirmed, "emailAuthFactor": m.auth_factor, "handle": a.handle(), "deactivated": deactivated, }); if let Some(e) = &m.email { out["email"] = json!(e); } let profile = crate::read(&a.store) .record("app.bsky.actor.profile/self") .map(|r| pds_repo::data::to_json(&r.value)); if let Some(p) = profile { if let Some(n) = p["displayName"].as_str() { out["name"] = json!(n); } // A blob ref, or a legacy one of a bare `cid`. if let Some(cid) = p["avatar"]["ref"]["$link"] .as_str() .or_else(|| p["avatar"]["cid"].as_str()) { out["picture"] = json!(crate::read_after_write::image_url( svc, "avatar", &a.did, cid )); } } out } /// Whether a request is a navigation to a page, as the authorization page needs. pub(super) fn navigation(svc: &Service, headers: &HeaderMap, sites: &[&str]) -> bool { header_text(headers, "sec-fetch-mode") == Some("navigate") && header_text(headers, "sec-fetch-dest") == Some("document") && header_text(headers, "sec-fetch-site").is_some_and(|s| sites.contains(&s)) && header_text(headers, "origin").is_none_or(|o| o == svc.oauth.issuer) } /// The request id a `Referer` names, if it is the authorization page. fn referer_request(svc: &Service, headers: &HeaderMap) -> Option { let u = url::Url::parse(header_text(headers, "referer")?).ok()?; if u.origin().ascii_serialization() != svc.oauth.issuer || u.path() != "/oauth/authorize" { return None; } let (_, request_uri) = u.query_pairs().find(|(k, _)| k == "request_uri")?; request_id(&request_uri).map(str::to_string) } /// What the authorization page shows of a request it loaded. struct Loaded { request: Request, signed_in: Vec<(String, u64)>, } /// `GET /oauth/authorize`. pub(super) async fn authorize( AxState(svc): AxState, method: Method, headers: HeaderMap, uri: Uri, ) -> Response { if method != Method::GET { return StatusCode::NOT_FOUND.into_response(); } finish(async move { if !navigation(&svc, &headers, &["same-origin", "same-site", "cross-site", "none"]) { return bad_page("This page must be navigated to"); } let q = query(&uri); let (Some(client_id), Some(request_uri)) = (param(&q, "client_id"), param(&q, "request_uri")) else { return bad_page("client_id and request_uri are required: requests must be pushed (PAR)"); }; let Some(id) = request_id(request_uri) else { return bad_page("Invalid request_uri") }; // An MCP issuer's request's client is loaded as that issuer loads it. let mcp = svc.oauth.lock().requests.get(id).is_some_and(Request::mcp); let client = match clients::load_for(&svc, client_id, mcp).await { Ok(c) => c, Err(e) => return error_page(400, e.error(), "Invalid client_id"), }; let mut tx = Tx::new(&svc); let device = device(&svc, &mut tx, &headers); let device_id = device.id.clone(); // The account a confidential client's request hints, if it is one here. let hinted = client.keys.as_ref().and_then(|_| { let hint = svc.oauth.lock().requests.get(id)?.login_hint.clone()?; svc.account(&hint).map(|a| a.did.clone()) }); let load = |st: &State, now: u64| { let Some(r) = st.requests.get(id) else { return (vec![], Err(None)) }; if r.approval.is_some() || now >= r.expires || r.client_id != client_id || r.device.as_ref().is_some_and(|d| *d != device_id) { let back = error_params(&svc, r, "access_denied", "This request can no longer be used"); return (vec![json!({ "t": "oauthEndRequest", "id": id })], Err(Some((r.clone(), back)))); } // A confidential client's request may be answered at once // (`spec/OAUTH-CLIENTS.md`), by an account the page lists: its // state read under OAuth's lock, which a change of it takes first. let deactivated = |did: &str| { let a = svc.account(did)?; let state = crate::read(&a.state); state.takedown.is_none().then_some(state.deactivated) }; if client.keys.is_some() && let Some((entries, back)) = clients::silent::decide(st, &svc.oauth.issuer, id, r, &device_id, hinted.as_deref(), &deactivated, now) { return (entries, Err(Some((r.clone(), back)))); } let load = json!({ "t": "oauthLoad", "id": id, "device": device_id, "expires": now + REQUEST_LIFE }); (vec![load], Ok(Loaded { request: r.clone(), signed_in: st.signed_in(&device_id).to_vec() })) }; let low = super::low(&svc); // Below the free-space floor, a load that would keep something is refused (None). let loaded = tx.change(|st, now| { let (entries, loaded) = load(st, now); if low && !entries.is_empty() { (vec![], None) } else { (entries, Some(loaded)) } }); if !tx.done().await { return error_page(500, "server_error", "Internal server error"); } let Some(loaded) = loaded else { return error_page(507, "temporarily_unavailable", "Not enough free space to store this") }; let loaded = match loaded { Ok(l) => l, Err(None) => return bad_page("Unknown or ended request"), Err(Some((r, back))) => return redirect_to(&r.response_mode, &r.redirect_uri, &back), }; // Each set the request includes, resolved again // (`spec/OAUTH-PERMISSION-SETS.md`); then each space type it names, // its sets' too, one that cannot be used ending the request, which // is sent back to its client (`spec/OAUTH-SCOPES.md`, "Space type // declarations"). let scope = &loaded.request.scope; let sets = svc.oauth.sets.resolve_all(&svc, scope).await; let spaces = match &sets { Ok(s) => svc.oauth.sets.resolve_spaces(&svc, scope, s).await.map(Some), Err(_) => Ok(None), }; let Ok(spaces) = spaces else { let mut tx = Tx::new(&svc); let ended = tx.change(|st, _| match st.requests.get(id) { Some(r) => { let back = error_params(&svc, r, "invalid_scope", "Unable to retrieve space declarations"); (vec![json!({ "t": "oauthEndRequest", "id": id })], Some((r.clone(), back))) } None => (vec![], None), }); if !tx.done().await { return error_page(500, "server_error", "Internal server error"); } return match ended { Some((r, back)) => redirect_to(&r.response_mode, &r.redirect_uri, &back), None => bad_page("Unknown or ended request"), }; }; let mut r = match sets { Ok(sets) => { // With a `space` permission, the declarations and the // handles of the scope's spaces' owners that verify // (`spec/OAUTH-SCOPES.md`, "On the authorization page"). let spaces = match spaces { Some(spaces) if super::sets::has_space(scope, &sets) => { let mut handles = Map::new(); for did in super::space_scope::authorities(scope.iter().map(String::as_str)) { if let Some(h) = verified_handle(&svc, &did).await { handles.insert(did, json!(h)); } } Some((spaces, handles)) } _ => None, }; authorization_page(&svc, request_uri, &client, &loaded, &sets, spaces, &device.id) } Err((nsid, _)) => error_page(400, "invalid_scope", &format!("Permission set {nsid} could not be resolved")), }; device_cookie(&svc, &mut r, &device); csrf_cookie(&svc, &mut r); r }) .await } /// Give a page the `csrf-token` cookie its script sends back as `x-csrf-token`. pub(super) fn csrf_cookie(svc: &Service, r: &mut Response) { let csrf = format!( "{CSRF_COOKIE}={}; Path=/; SameSite=Lax{}", hex::encode(rand::random::<[u8; 16]>()), secure(svc) ); if let Ok(v) = csrf.parse() { r.headers_mut().append(header::SET_COOKIE, v); } } /// The handle of `did` when it verifies (`spec/OAUTH-SCOPES.md`, "On the /// authorization page"): the DID's document's first `at://` name, a valid /// handle, that resolves to `did` as `spec/IDENTITY.md` resolves an /// external one, by DNS and HTTPS, even an account's here, lowercased for /// that alone; as the document writes it, its case kept. None when any /// step fails. async fn verified_handle(svc: &Service, did: &str) -> Option { let doc = crate::proxy::resolve_did(svc, did).await.ok()?; let name = doc["alsoKnownAs"] .as_array()? .iter() .filter_map(Json::as_str) .find(|u| u.starts_with("at://"))?; let given = name.strip_prefix("at://")?; let handle = given.to_lowercase(); if !pds_repo::data::valid_handle(&handle) { return None; } let verified = crate::identity::handle_resolves_to(svc, &handle, did).await; verified.then(|| given.to_string()) } /// A page's space type declarations, by NSID, and its owners' verified /// handles, by DID (`spaceHandles`). type PageSpaces = ( std::collections::HashMap>, Map, ); /// The authorization page of a request loaded on device `device`, which it /// gives a new passkey challenge (`spec/PASSKEYS.md`, "The page's options"). fn authorization_page( svc: &Service, request_uri: &str, client: &client::Client, loaded: &Loaded, sets: &std::collections::HashMap>, spaces: Option, device: &str, ) -> Response { let r = &loaded.request; let now = svc.sessions.now(); let mut data = json!({ "requestUri": request_uri, "clientId": client.id, "clientMetadata": client.metadata(), "clientTrusted": false, "clientFirstParty": false, "scope": r.scope.join(" "), "permissionSets": sets.iter().map(|(nsid, main)| (nsid.clone(), (**main).clone())).collect::>(), }); if let Some((spaces, handles)) = spaces { data["spaces"] = spaces .into_iter() .map(|(nsid, main)| (nsid, (*main).clone())) .collect::>() .into(); data["spaceHandles"] = handles.into(); } // A public client's request always has its kept prompt; a confidential one's may have none. if let Some(p) = &r.prompt { data["promptMode"] = json!(p); } if let Some(l) = &r.ui_locales { data["uiLocales"] = json!(l); } // The account the hint names here, if any: a taken-down one is none, // its DID shown as given and it not selected. let hinted = r .login_hint .as_deref() .and_then(|h| svc.account(h)) .filter(|a| crate::read(&a.state).takedown.is_none()); if let Some(h) = &r.login_hint { data["loginHint"] = json!(match &hinted { Some(a) if h.starts_with("did:") => a.handle(), _ => h.clone(), }); } let sessions: Vec = loaded .signed_in .iter() // A taken-down account stays signed in on the device, but is not shown. .filter_map(|(did, at)| svc.account(did).filter(|a| crate::read(&a.state).takedown.is_none()).map(|a| json!({ "account": account_json(svc, &a), "loginRequired": clients::silent::needs_sign_in(r, *at, now) }))) .collect(); // A public client's request selects the hinted account only when it asks // for consent, none when asked to create an account; a confidential // client's for these prompts. let selects = match client.keys { None => r.prompt.as_deref() == Some("consent"), Some(_) => matches!(r.prompt.as_deref(), None | Some("login" | "consent")), }; if let Some(a) = hinted.filter(|a| selects && loaded.signed_in.iter().any(|(d, _)| *d == a.did)) { data["selectedDid"] = json!(a.did); } let passkey = super::passkeys::challenge_for(svc, device); page( 200, "Sign in", &[ ("__authorizeData", &data), ("__sessions", &json!(sessions)), ("__passkeyOptions", &passkey), ], ) } /// `GET /oauth/authorize/redirect`: send the browser on to the client. pub(super) async fn redirect( AxState(svc): AxState, method: Method, headers: HeaderMap, uri: Uri, ) -> Response { if method != Method::GET { return StatusCode::NOT_FOUND.into_response(); } if !navigation(&svc, &headers, &["same-origin"]) || referer_request(&svc, &headers).is_none() { return bad_page("This page must be navigated to from the authorization page"); } let q = query(&uri); let (Some(mode), Some(redirect_uri)) = (param(&q, "redirect_mode"), param(&q, "redirect_uri")) else { return bad_page("Invalid redirect"); }; let fields: &[&str] = match (param(&q, "code"), param(&q, "error")) { (Some(_), None) => &[ "state", "iss", "code", "id_token", "access_token", "expires_in", "token_type", ], (None, Some(_)) => &["state", "iss", "error", "error_description", "error_uri"], _ => return bad_page("Invalid redirect"), }; let params: Vec<(&str, String)> = fields .iter() .filter_map(|k| param(&q, k).map(|v| (*k, v.to_string()))) .collect(); redirect_to(mode, redirect_uri, ¶ms) } /// An API refusal: `400 invalid_request` (or the status given), as JSON. fn api_error(status: u16, description: &str) -> Response { let mut r = json_response( status, &json!({ "error": "invalid_request", "error_description": description }), ); set(&mut r, "cache-control", "no-store"); r } /// A body field's type: `Any` is checked by its endpoint, in its own order. #[derive(Clone, Copy)] enum Field { Text(fn(&str) -> bool), Bool, Any, } /// The fields each endpoint takes: name, type, and whether it is required. fn fields(endpoint: &str) -> Option<&'static [(&'static str, Field, bool)]> { fn any(_: &str) -> bool { true } fn identifier(s: &str) -> bool { pds_repo::data::valid_handle(&s.to_lowercase()) || pds_repo::data::valid_did(s) || sign_in_email(s) } fn password(s: &str) -> bool { (1..=512).contains(&s.chars().count()) } const SIGN_IN: &[(&str, Field, bool)] = &[ ("locale", Field::Text(super::valid_locale), true), ("identifier", Field::Text(identifier), true), ("password", Field::Text(password), true), ("remember", Field::Bool, false), ("emailOtp", Field::Text(any), false), ]; const CONSENT: &[(&str, Field, bool)] = &[ ("did", Field::Text(pds_repo::data::valid_did), true), ("scope", Field::Text(scope::valid), false), ]; const SIGN_OUT: &[(&str, Field, bool)] = &[("did", Field::Text(pds_repo::data::valid_did), true)]; const PASSKEY_SIGN_IN: &[(&str, Field, bool)] = &[ ("locale", Field::Text(super::valid_locale), true), ("credential", Field::Any, true), ("remember", Field::Bool, false), ]; const PASSKEY_REGISTER: &[(&str, Field, bool)] = &[("credential", Field::Any, true)]; Some(match endpoint { "sign-in" => SIGN_IN, "consent" => CONSENT, "reject" | "passkey-options" => &[], "sign-out" => SIGN_OUT, "passkey-sign-in" => PASSKEY_SIGN_IN, "passkey-register" => PASSKEY_REGISTER, _ => return None, }) } /// Whether `sign-in` takes `s` as an email: case-insensitively the whole of /// `(?!\.)(?!.*\.\.)[A-Z0-9_'+\-.]*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}`, /// its local part at most 64 characters, each label at most 63, and the whole at most 254. fn sign_in_email(s: &str) -> bool { let Some((local, domain)) = s.split_once('@') else { return false; }; let local_ok = (1..=64).contains(&local.len()) && !local.starts_with('.') && !local.contains("..") && local .bytes() .all(|b| b.is_ascii_alphanumeric() || b"_'+-.".contains(&b)) && local .bytes() .last() .is_some_and(|b| b.is_ascii_alphanumeric() || b"_+-".contains(&b)); let labels: Vec<&str> = domain.split('.').collect(); let Some((tld, rest)) = labels.split_last() else { return false; }; let label_ok = |l: &&str| { l.len() <= 63 && l.bytes().next().is_some_and(|b| b.is_ascii_alphanumeric()) && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') }; s.len() <= 254 && local_ok && !rest.is_empty() && rest.iter().all(label_ok) && (2..=63).contains(&tld.len()) && tld.bytes().all(|b| b.is_ascii_alphabetic()) } /// A body with exactly an endpoint's fields, of their types. fn body_of(fields: &[(&str, Field, bool)], body: &[u8]) -> Result, String> { let Ok(Json::Object(m)) = serde_json::from_slice::(body) else { return Err("The body must be a JSON object".into()); }; if let Some(k) = m.keys().find(|k| !fields.iter().any(|(n, _, _)| n == k)) { return Err(format!("Unexpected field {k}")); } for (name, field, required) in fields { let right = match (m.get(*name), field) { (None, _) => !required, (Some(Json::String(s)), Field::Text(valid)) => valid(s), (Some(Json::Bool(_)), Field::Bool) => true, (Some(_), Field::Any) => true, _ => false, }; if !right { return Err(format!("Invalid {name}")); } } Ok(m) } /// `POST /@atproto/oauth-provider/~api/`. pub(super) async fn api( AxState(svc): AxState, Path(endpoint): Path, method: Method, headers: HeaderMap, peer: Option>, body: Body, ) -> Response { let Some(fields) = fields(&endpoint).filter(|_| method == Method::POST) else { return json_response( 404, &json!({ "error": "invalid_request", "error_description": "Not found" }), ); }; if header_text(&headers, "sec-fetch-mode") != Some("same-origin") || header_text(&headers, "sec-fetch-site") != Some("same-origin") { return api_error(400, "Requests must come from the authorization page"); } if header_text(&headers, "origin").is_some_and(|o| o != svc.oauth.issuer) { return api_error(400, "Invalid origin"); } // A call of the authorization page is for its request; `passkey-register`, // the passkey page's, for its link (`spec/PASSKEYS.md`, "passkey-register"). let from = if endpoint == "passkey-register" { super::passkeys::referer_link(&svc, &headers) } else { referer_request(&svc, &headers) }; let Some(from) = from else { return api_error(400, "Invalid referer"); }; let csrf = header_text(&headers, "x-csrf-token"); if csrf.is_none() || csrf.map(str::to_string) != cookie(&headers, CSRF_COOKIE) { return api_error(400, "Invalid CSRF token"); } let essence = header_text(&headers, "content-type").map(|v| { v.split(';') .next() .unwrap_or_default() .trim() .to_ascii_lowercase() }); if essence.as_deref() != Some("application/json") { return api_error(415, "Content-Type must be application/json"); } let body = match super::read_body(&headers, body, super::BODY_MAX).await { Ok(body) => body, Err(413) => return api_error(413, "Request body too large"), Err(status) => return api_error(status, "The body could not be read"), }; let b = match body_of(fields, &body) { Ok(b) => b, Err(why) => return api_error(400, &why), }; // A sign-in answers no sooner than this, whatever it answers. let floor = (endpoint == "sign-in").then(|| tokio::time::Instant::now() + svc.config.sign_in_floor); let client = crate::limits::client( &svc.config.trusted_proxies, &headers, peer.map(|Extension(p)| p.0), ); let whence = Whence::of(&headers, &client); finish(async move { let mut tx = Tx::new(&svc); // The passkey page names no device, and is given none. let mut device = (endpoint != "passkey-register").then(|| device(&svc, &mut tx, &headers)); let request_id = from.as_str(); let answer = match device.as_mut() { None => super::passkeys::register(&svc, &mut tx, &from, &b), Some(device) => match endpoint.as_str() { "sign-in" => sign_in(&svc, &mut tx, device, request_id, &client, &whence, &b).await, "consent" => consent(&svc, &mut tx, &headers, &device.id, request_id, &b).await, "reject" => reject(&svc, &mut tx, request_id), "passkey-options" => super::passkeys::options(&svc, device), "passkey-sign-in" => { super::passkeys::sign_in(&svc, &mut tx, device, request_id, &whence, &b) } _ => sign_out(&mut tx, &device.id, &b).map_err(Refusal::from), }, }; if let Some(floor) = floor { tokio::time::sleep_until(floor).await; } if !tx.done().await { return json_response( 500, &json!({ "error": "server_error", "error_description": "Internal server error" }), ); } let mut r = match answer { Ok(j) => json_response(200, &j), Err(no) => { let mut r = json_response( no.status, &json!({ "error": no.error, "error_description": no.description }), ); if let Some(secs) = no.retry_after { set(&mut r, "retry-after", &secs.to_string()); } r } }; set(&mut r, "cache-control", "no-store"); if let Some(device) = &device { device_cookie(&svc, &mut r, device); } r }) .await } fn text<'b>(b: &'b Map, k: &str) -> &'b str { b.get(k).and_then(Json::as_str).unwrap_or_default() } /// How long a device the account signed in on, remembered, needs no code of /// its email factor. const FACTOR_TRUST: u64 = 30 * 24 * 60 * 60; /// What the API answers in place of what was asked: its status, `error` /// and description, and for a rate limit, the seconds to wait. pub(super) struct Refusal { pub status: u16, pub error: &'static str, pub description: String, pub retry_after: Option, } /// The refusal of a call below the free-space floor that would keep something. pub(super) fn out_of_space() -> Refusal { Refusal { status: 507, error: "temporarily_unavailable", description: "Not enough free space to store this".into(), retry_after: None, } } impl From for Refusal { /// The usual refusal: `400 invalid_request`. fn from(description: String) -> Refusal { Refusal { status: 400, error: "invalid_request", description, retry_after: None, } } } impl From for Refusal { /// An XRPC method's error, in the API's terms: `500 server_error`, or else `400 invalid_request`. fn from(e: crate::XrpcError) -> Refusal { if e.status >= 500 { Refusal { status: 500, error: "server_error", description: "Internal server error".into(), retry_after: None, } } else { Refusal::from(e.message) } } } /// `sign-in`: the login limits paid, the account's own password, not an app /// password, then the code its email factor asks for, as `createSession` /// checks them (`spec/OAUTH.md`, "The API"). A sign-in remembered is kept /// with where it came from (`whence`). async fn sign_in( svc: &Shared, tx: &mut Tx<'_>, device: &mut Device, request_id: &str, client: &str, whence: &Whence, b: &Map, ) -> Result { let id = text(b, "identifier"); if let Err(secs) = crate::limits::charge_sign_in(svc, id, client) { return Err(Refusal { status: 429, error: "invalid_request", description: "Too many sign-in attempts".into(), retry_after: Some(secs), }); } let refused = || Err(Refusal::from("Invalid identifier or password".to_string())); let account = crate::server::login(svc, id); let (own, _) = crate::server::check_password(svc, account.as_deref(), text(b, "password")).await; let (Some(account), Some(own)) = (account, own) else { return refused(); }; if crate::read(&account.state).takedown.is_some() { return Err("Account was taken down".to_string().into()); } // The empty code is none. let code = b .get("emailOtp") .and_then(Json::as_str) .filter(|c| !c.is_empty()); let remember = b.get("remember").and_then(Json::as_bool); let did = account.did.clone(); let now = svc.sessions.now(); // A device it signed in on, remembered, lately, needs no code. let trusted = svc .oauth .lock() .signed_in(&device.id) .iter() .any(|(d, at)| *d == did && now.saturating_sub(*at) <= FACTOR_TRUST); let (mail, remembered) = { let mut m = crate::email::lock(&account.mail); // A password changed since it was checked makes it wrong. if m.password.as_ref() != Some(&own) { return refused(); } if let Some(code) = code { m.check(AuthFactor, code, now)?; } // Its checks passed, below the free space nothing is kept, a code // made or used up, or the sign-in. if super::low(svc) { return Err(out_of_space()); } match code { Some(_) => { let used = crate::email::use_entry(&did, AuthFactor); let remembered = sign_in_here(tx, device, &did, remember, whence, |_, _| { Ok(vec![used.clone()]) })?; if !tx.failed { crate::email::apply(svc, &did, &mut m, &[used]); } (None, remembered) } None if m.auth_factor && !trusted => ( Some(crate::email::make(svc, &did, &mut m, AuthFactor)?), false, ), None => ( None, sign_in_here(tx, device, &did, remember, whence, |_, _| Ok(vec![]))?, ), } }; if let Some(mail) = mail { crate::email::deliver(svc, mail).await?; let description = "A sign in code has been sent to your email address".to_string(); return Err(Refusal { status: 401, error: "second_authentication_factor_required", description, retry_after: None, }); } Ok(signed_in(svc, &account, device, request_id, remembered)) } /// What a sign-in of `account` on `device`, for request `request_id`, /// answers: the account, and, when it was not remembered there, an /// ephemeral token of the sign-in. pub(super) fn signed_in( svc: &Service, account: &Account, device: &Device, request_id: &str, remembered: bool, ) -> Json { let mut out = json!({ "account": account_json(svc, account) }); if !remembered { let exp = svc.sessions.now() + EPHEMERAL_LIFE; out["ephemeralToken"] = json!(svc.oauth.seal( "ephemeral", &json!({ "did": account.did, "device": device.id, "request": request_id, "exp": exp }) )); } out } /// Sign `did` in on `device`, in one frame with the entries `with` makes /// under OAuth's lock, as a code it used up, unless it refuses: remembered, /// or with `remember` left out when it is signed in here already, it is /// signed in here from now, from `whence`; otherwise it is not, or no /// longer. Either way the device is given new cookies, and those it had are /// old (`spec/OAUTH.md`, "Devices"). Answers whether it is remembered. pub(super) fn sign_in_here( tx: &mut Tx<'_>, device: &mut Device, did: &str, remember: Option, whence: &Whence, with: impl FnOnce(&State, u64) -> Result, Refusal>, ) -> Result { let (id, key) = (device.id.as_str(), new_id(16)); let remembered = tx.change(|st, now| { let first = match with(st, now) { Ok(entries) => entries, Err(no) => return (vec![], Err(no)), }; let signed = st.signed_in(id).iter().any(|(d, _)| d == did); let remembered = remember.unwrap_or(signed); let entry = if remembered { let mut e = json!({ "t": "oauthSignIn", "device": id, "did": did, "at": now }); whence.fill(&mut e); Some(e) } else { signed.then(|| json!({ "t": "oauthSignOut", "device": id, "did": did })) }; let renewed = json!({ "t": "oauthDeviceKey", "device": id, "key": key, "at": now }); ( first.into_iter().chain(entry).chain([renewed]).collect(), Ok(remembered), ) })?; device.give = Some(key); Ok(remembered) } /// Whether `Authorization: Bearer` holds an ephemeral token of a sign-in of `did`, on this device, for this request. fn ephemeral( svc: &Service, headers: &HeaderMap, did: &str, device: &str, request_id: &str, ) -> bool { let Some(token) = header_text(headers, "authorization") .and_then(|a| a.split_once(' ')) .filter(|(s, _)| s.eq_ignore_ascii_case("bearer")) .map(|(_, t)| t) else { return false; }; svc.oauth.unseal("ephemeral", token).is_some_and(|t| { t["did"] == did && t["device"] == device && t["request"] == request_id && t["exp"] .as_u64() .is_some_and(|exp| svc.sessions.now() < exp) }) } /// A request's scope narrowed by the one consented to: the tokens in both, /// those the request lacks dropped, in the request's order, or in /// `consented`'s if it names fewer distinct tokens than the request has, /// counting those the request lacks too. fn narrow(requested: &[String], consented: &str) -> Vec { let mut given: Vec<&str> = Vec::new(); for t in scope::tokens(consented) { if !given.contains(&t) { given.push(t); } } if given.len() < requested.len() { given .into_iter() .filter(|t| requested.iter().any(|r| r == t)) .map(str::to_string) .collect() } else { requested .iter() .filter(|r| given.contains(&r.as_str())) .cloned() .collect() } } /// The `url` the API answers: the redirect, through the server, with these parameters. fn redirect_url(svc: &Service, r: &Request, params: &[(&str, String)]) -> String { let mut all = vec![ ("redirect_mode", r.response_mode.clone()), ("redirect_uri", r.redirect_uri.clone()), ]; all.extend(params.iter().cloned()); let q = url::form_urlencoded::Serializer::new(String::new()) .extend_pairs(all.iter().map(|(k, v)| (*k, v.as_str()))) .finish(); format!("{}/oauth/authorize/redirect?{q}", svc.oauth.issuer) } /// End a request with an error: the entry, and the `url` answered. fn end_with( svc: &Service, id: &str, r: &Request, error: &str, description: &str, ) -> (Vec, Result) { let url = redirect_url(svc, r, &error_params(svc, r, error, description)); ( vec![json!({ "t": "oauthEndRequest", "id": id })], Ok(json!({ "url": url })), ) } /// What `consent` answers when it does not approve: the entries to log, and the answer. type Unapproved = (Vec, Result); /// `consent`'s checks 1 to 3: the request, if they pass. fn consent_checks<'s>( svc: &Service, st: &'s State, now: u64, id: &str, device: &str, did: &str, signed_by_token: bool, ) -> Result<&'s Request, Unapproved> { let Some(r) = st.requests.get(id) else { return Err((vec![], Err("Unknown or ended request".into()))); }; if r.approval.is_some() || now >= r.expires || r.device.as_ref().is_some_and(|d| d != device) { return Err(end_with( svc, id, r, "access_denied", "This request can no longer be used", )); } if !signed_by_token && !st.signed_in(device).iter().any(|(d, _)| d == did) { return Err(end_with( svc, id, r, "invalid_request", "The account is not signed in", )); } Ok(r) } /// `consent`: checks 1 to 3, then the request's client loaded /// (`spec/OAUTH-CLIENTS.md`, "At `consent`"), with no lock held while it is /// fetched, then checks 1 to 3 again, as the request may have moved on, and 4. async fn consent( svc: &Shared, tx: &mut Tx<'_>, headers: &HeaderMap, device: &str, id: &str, b: &Map, ) -> Result { let did = text(b, "did"); let signed_by_token = ephemeral(svc, headers, did, device, id); let low = super::low(svc); let first = tx.change(|st: &State, now| { match consent_checks(svc, st, now, id, device, did, signed_by_token) { Ok(r) => (vec![], Ok((r.client_id.clone(), r.mcp()))), Err(unapproved) => { let (entries, answer) = unless_low(low, unapproved); (entries, Err(answer)) } } }); let (client_id, mcp) = match first { Ok(c) => c, Err(answer) => return answer, }; let loaded = clients::load_for(svc, &client_id, mcp).await; tx.change(changing(low, |st: &State, now| { let r = match consent_checks(svc, st, now, id, device, did, signed_by_token) { Ok(r) => r, Err(unapproved) => return unapproved, }; if let Err(f) = loaded { return end_with(svc, id, r, f.at_consent(), "The client cannot be loaded"); } // A deactivated account signs in, but approves nothing (`spec/LIFECYCLE.md`). // A taken-down account still signed in on the device approves nothing either. if svc.account(did).is_some_and(|a| crate::read(&a.state).takedown.is_some()) { return end_with(svc, id, r, "invalid_request", "Account was taken down"); } if svc.account(did).is_some_and(|a| crate::read(&a.state).deactivated) { return end_with(svc, id, r, "access_denied", "This account has been deactivated"); } let scope = b.get("scope").and_then(Json::as_str).map_or_else(|| r.scope.clone(), |s| narrow(&r.scope, s)); if !scope.iter().any(|t| t == "atproto") { return end_with(svc, id, r, "access_denied", "The atproto scope is required"); } let code = format!("cod-{}", new_id(32)); let mut entries = Vec::new(); if r.device.is_none() { entries.push(json!({ "t": "oauthLoad", "id": id, "device": device, "expires": r.expires })); } entries.push(json!({ "t": "oauthApprove", "id": id, "code": code, "did": did, "scope": scope, "at": now })); let mut back = back_params(svc, r); back.push(("code", code)); let url = redirect_url(svc, r, &back); (entries, Ok(json!({ "url": url }))) })) } /// A change of the API's that would keep something, below the free-space /// floor (`low`): refused with `507`, changing nothing (`spec/OAUTH.md`, /// "Free space"). fn unless_low(low: bool, (entries, answer): Unapproved) -> (Vec, Result) { if low && !entries.is_empty() { let description = "Not enough free space to store this".to_string(); return ( vec![], Err(Refusal { status: 507, error: "temporarily_unavailable", description, retry_after: None, }), ); } (entries, answer.map_err(Refusal::from)) } /// A change `f` of the API's, held to the free-space floor (`unless_low`). fn changing<'f>( low: bool, f: impl FnOnce(&State, u64) -> Unapproved + 'f, ) -> impl FnOnce(&State, u64) -> (Vec, Result) + 'f { move |st: &State, now: u64| unless_low(low, f(st, now)) } fn reject(svc: &Shared, tx: &mut Tx, id: &str) -> Result { tx.change(changing(super::low(svc), |st: &State, _| { let Some(r) = st.requests.get(id) else { return (vec![], Err("Unknown or ended request".into())); }; end_with(svc, id, r, "access_denied", "The user denied the request") })) } fn sign_out(tx: &mut Tx, device: &str, b: &Map) -> Result { let did = text(b, "did"); tx.change(|st: &State, _| { let signed = st.signed_in(device).iter().any(|(d, _)| d == did); ( signed .then(|| json!({ "t": "oauthSignOut", "device": device, "did": did })) .into_iter() .collect(), (), ) }); Ok(json!({ "success": true })) } #[cfg(test)] mod tests { use super::*; #[test] fn narrowing() { let req: Vec = ["atproto", "transition:generic", "transition:email"] .iter() .map(|s| s.to_string()) .collect(); assert_eq!( narrow(&req, "transition:email atproto"), ["transition:email", "atproto"] ); assert_eq!( narrow(&req, "transition:email atproto transition:generic"), ["atproto", "transition:generic", "transition:email"] ); assert_eq!( narrow(&req, "other atproto transition:email transition:generic"), ["atproto", "transition:generic", "transition:email"] ); assert_eq!(narrow(&req, "transition:generic"), ["transition:generic"]); // Tokens the request lacks count, and are dropped. assert_eq!( narrow(&req, "transition:email atproto foo"), ["atproto", "transition:email"] ); assert_eq!(narrow(&req, "foo atproto"), ["atproto"]); } #[test] fn sign_in_emails() { for ok in [ "alice@mail.com", "A.B+c@Sub.Example.ORG", "o'neil-x@a-b.io", "_@x.io", ] { assert!(sign_in_email(ok), "{ok}"); } let long_local = format!("{}@x.io", "a".repeat(65)); let long_label = format!("a@{}.io", "b".repeat(64)); for bad in [ "pq8@b.c1", "a@b.c", "ü@x.io", "a!b@x.io", ".a@x.io", "a..b@x.io", "a.@x.io", "a'@x.io", "a@x", "a@-x.io", "@x.io", "a@x..io", &long_local, &long_label, ] { assert!(!sign_in_email(bad), "{bad}"); } } /// The page's Content-Security-Policy allows its one inline script, by /// the hash of that script as sent, and each asset its head names is one /// the build has. #[tokio::test] async fn page_policy() { let r = error_page(400, "invalid_request", "\u{2028}'\"&"); let policy = r.headers()["content-security-policy"] .to_str() .unwrap() .to_string(); let body = axum::body::to_bytes(r.into_body(), usize::MAX) .await .unwrap(); let html = String::from_utf8(body.to_vec()).unwrap(); let inline: Vec<&str> = html .split("").next().unwrap()) .collect(); assert_eq!(inline.len(), 1, "{html}"); let hash = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(inline[0])); assert!(policy.contains(&format!("'sha256-{hash}'")), "{policy}"); let named: Vec<&str> = html .split("/oauth/assets/") .skip(1) .map(|s| &s[..s.find('"').unwrap()]) .collect(); assert!(named.len() >= 3, "{html}"); for n in named { assert!(assets::ASSETS.iter().any(|(a, _, _)| *a == n), "{n}"); } } #[test] fn script_literals() { let v = json!({ "a": "\u{2028}\"" }); let lit = js_json(&v); assert!(!lit.contains('<') && !lit.contains('\u{2028}')); let back: String = serde_json::from_str(&lit).unwrap(); assert_eq!(serde_json::from_str::(&back).unwrap(), v); } }