diff --git a/api-v3/Cargo.lock b/api-v3/Cargo.lock index 67ea9523..3bf469e3 100644 --- a/api-v3/Cargo.lock +++ b/api-v3/Cargo.lock @@ -51,6 +51,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "axum-macros", "bytes", "form_urlencoded", "futures-util", @@ -96,12 +97,29 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bitflags" version = "2.13.2" @@ -180,6 +198,12 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -213,6 +237,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-queue" version = "0.3.14" @@ -261,6 +294,9 @@ name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] [[package]] name = "digest" @@ -279,6 +315,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", + "const-oid", "crypto-common 0.2.2", "ctutils", ] @@ -608,6 +645,7 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", ] [[package]] @@ -616,13 +654,22 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", ] [[package]] @@ -741,6 +788,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.18" @@ -807,14 +860,22 @@ version = "0.0.0" dependencies = [ "anyhow", "axum", + "base64 0.23.1", + "crc32fast", + "hmac", "http-body-util", + "rand", + "reqwest", "serde", "serde_json", + "sha2 0.11.1", "sqlx", + "subtle", "thiserror", + "time", "tokio", "tower", - "tower-http", + "tower-http 0.7.1", "tracing", "tracing-subscriber", "utoipa", @@ -1046,6 +1107,37 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tower", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "ring" version = "0.17.14" @@ -1289,7 +1381,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "cfg-if", "crc", @@ -1393,7 +1485,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" dependencies = [ "atoi", - "base64", + "base64 0.22.1", "bitflags", "byteorder", "crc", @@ -1497,6 +1589,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -1639,6 +1734,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-http" version = "0.7.1" @@ -1744,6 +1857,12 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -1867,6 +1986,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1886,6 +2014,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -1918,6 +2057,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-roots" version = "1.0.11" diff --git a/api-v3/Cargo.toml b/api-v3/Cargo.toml index 6ef030d8..c723c2ba 100644 --- a/api-v3/Cargo.toml +++ b/api-v3/Cargo.toml @@ -8,18 +8,26 @@ name = "maproulette" [dependencies] anyhow = "1.0.104" -axum = "0.8.9" +axum = { version = "0.8.9", features = ["macros"] } +base64 = "0.23.1" +crc32fast = "1.5.3" +hmac = "0.13.0" +rand = "0.10.3" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +sha2 = "0.11.1" sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "postgres", "macros", "json", "time", "tls-rustls"] } +subtle = "2.6.1" thiserror = "2.0.21" +time = { version = "0.3.55", features = ["serde", "formatting", "parsing"] } tokio = { version = "1.54.1", features = ["full"] } -tower-http = { version = "0.7.1", features = ["trace", "request-id"] } +tower-http = { version = "0.7.1", features = ["trace", "request-id", "cors"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } -utoipa = { version = "6.0.0", features = ["axum_extras"] } +utoipa = { version = "6.0.0", features = ["axum_extras", "time"] } utoipa-axum = "0.3.0" [dev-dependencies] http-body-util = "0.1.5" +reqwest = { version = "0.13.5", default-features = false, features = ["json"] } tower = { version = "0.5.3", features = ["util"] } diff --git a/api-v3/src/auth/mod.rs b/api-v3/src/auth/mod.rs new file mode 100644 index 00000000..b90a6afe --- /dev/null +++ b/api-v3/src/auth/mod.rs @@ -0,0 +1,280 @@ +pub mod play; +pub mod token; + +use axum::extract::{FromRequestParts, OptionalFromRequestParts, Request, State}; +use axum::http::request::Parts; +use axum::http::{HeaderMap, HeaderValue, Method, header}; +use axum::middleware::Next; +use axum::response::Response; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +use crate::AppState; +use crate::db; +use crate::error::Error; +use crate::model::{CredentialId, Scope, UserId}; +use token::Token; + +#[derive(Clone, Debug)] +pub struct Principal { + pub user_id: UserId, + pub via: Via, +} + +#[derive(Clone, Debug)] +pub enum Via { + Session, + Token { + credential_id: CredentialId, + kind: TokenKind, + scopes: Vec, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum TokenKind { + Pat, + Editor, +} + +impl Principal { + /// Fails unless the principal may act with `scope`. A session acts with the user's full role, + /// so it has every scope. A token has the scopes it was created with. + pub fn require_scope(&self, scope: Scope) -> Result<(), Error> { + match &self.via { + Via::Session => Ok(()), + Via::Token { scopes, .. } if scopes.contains(&scope) => Ok(()), + Via::Token { .. } => Err(Error::InsufficientScope(scope.as_str())), + } + } + + /// Prepares a value for the `X-Auth` response header, which indicates how the + /// request was authenticated so the reverse proxy can log it. + fn x_auth(&self) -> String { + match &self.via { + Via::Session => format!("session:user/{}", self.user_id), + Via::Token { + credential_id, + kind: TokenKind::Pat, + .. + } => format!("pat:{credential_id}"), + Via::Token { + credential_id, + kind: TokenKind::Editor, + .. + } => format!("editor:{credential_id}"), + } + } +} + +/// The resolved principal, which `resolve` attaches to every request. +#[derive(Clone)] +struct Auth(Option); + +/// Middleware that resolves the request's principal, records it in the trace +/// span, and sets `X-Auth` on the response. +pub async fn resolve( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let principal = principal(&state, req.headers()).await?; + if let Some(Principal { + via: Via::Session, .. + }) = &principal + { + check_origin(&state.allowed_origins, req.method(), req.headers())?; + } + let x_auth = principal.as_ref().map(|p| { + let x_auth = p.x_auth(); + tracing::Span::current().record("auth", &x_auth); + HeaderValue::try_from(x_auth).expect("X-Auth is ASCII") + }); + req.extensions_mut().insert(Auth(principal)); + let mut res = next.run(req).await; + if let Some(x_auth) = x_auth { + res.headers_mut().insert("x-auth", x_auth); + } + Ok(res) +} + +/// Defends session-authenticated requests against cross-site request forgery (CSRF). +fn check_origin( + allowed: &[HeaderValue], + method: &Method, + headers: &HeaderMap, +) -> Result<(), Error> { + if method.is_safe() { + return Ok(()); + } + match headers.get(header::ORIGIN) { + Some(origin) if allowed.contains(origin) => Ok(()), + _ => Err(Error::Forbidden( + "A request that uses the session cookie to change something must come from a \ + MapRoulette frontend. Scripts should use a personal access token.", + )), + } +} + +async fn principal(state: &AppState, headers: &HeaderMap) -> Result, Error> { + let mut authorization = headers.get_all(header::AUTHORIZATION).iter(); + match (authorization.next(), authorization.next()) { + (None, _) => session(state, headers).await, + (Some(value), None) => { + let token = bearer(value).ok_or(Error::InvalidToken)?; + token_principal(state, &token).await.map(Some) + } + (Some(_), Some(_)) => Err(Error::InvalidToken), + } +} + +/// The token in an `Authorization: Bearer ` header, if it is well formed. +fn bearer(value: &HeaderValue) -> Option { + let (scheme, token) = value.to_str().ok()?.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("bearer") { + return None; + } + Token::parse(token.trim()) +} + +async fn token_principal(state: &AppState, token: &Token) -> Result { + let credential = db::credentials::find(&state.db, &token.hash()) + .await? + .ok_or(Error::InvalidToken)?; + let kind = match credential.kind.as_str() { + "pat" => TokenKind::Pat, + "editor" => TokenKind::Editor, + _ => return reject(credential.id, "not a bearer credential"), + }; + for (rejected, reason) in [ + (credential.revoked, "revoked"), + (credential.expired, "expired"), + (credential.idle, "idle"), + ] { + if rejected { + return reject(credential.id, reason); + } + } + if credential.stale { + // Update the credential's last_used_at time in the background + let db = state.db.clone(); + tokio::spawn(async move { + if let Err(e) = db::credentials::touch(&db, credential.id).await { + tracing::warn!(credential_id = %credential.id, error = %e, "updating last_used_at failed"); + } + }); + } + Ok(Principal { + user_id: credential.user_id, + via: Via::Token { + credential_id: credential.id, + kind, + scopes: credential.scopes, + }, + }) +} + +fn reject(credential_id: CredentialId, reason: &str) -> Result { + tracing::info!(%credential_id, reason, "rejected token"); + Err(Error::InvalidToken) +} + +/// The principal for v2's Play session cookie, if the request has a valid one. +/// The session is valid only while its token hash matches the user's current +/// OSM token. +async fn session(state: &AppState, headers: &HeaderMap) -> Result, Error> { + let Some(session) = + cookie(headers, play::COOKIE).and_then(|c| play::decode(c, &state.session_secret)) + else { + return Ok(None); + }; + let Some(oauth_token) = db::users::oauth_token(&state.db, session.user_id).await? else { + return Ok(None); + }; + let current = hex(&Sha256::digest(oauth_token.as_bytes())); + if !bool::from(current.as_bytes().ct_eq(session.token_hash.as_bytes())) { + return Ok(None); + } + Ok(Some(Principal { + user_id: session.user_id, + via: Via::Session, + })) +} + +fn cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .find_map(|pair| { + let (k, v) = pair.trim().split_once('=')?; + (k == name).then_some(v) + }) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +impl FromRequestParts for Principal { + type Rejection = Error; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + >::from_request_parts(parts, state) + .await? + .ok_or(Error::Unauthenticated) + } +} + +impl OptionalFromRequestParts for Principal { + type Rejection = Error; + + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result, Error> { + let Auth(principal) = parts + .extensions + .get::() + .expect("the resolve middleware runs on every route"); + Ok(principal.clone()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn session_writes_need_a_trusted_origin() { + let allowed = [HeaderValue::from_static("https://maproulette.org")]; + let check = |method: Method, origin: Option<&'static str>| { + let mut headers = HeaderMap::new(); + if let Some(origin) = origin { + headers.insert(header::ORIGIN, HeaderValue::from_static(origin)); + } + check_origin(&allowed, &method, &headers).is_ok() + }; + for method in [Method::POST, Method::PUT, Method::PATCH, Method::DELETE] { + assert!( + check(method.clone(), Some("https://maproulette.org")), + "{method}" + ); + for origin in [ + None, + Some("null"), + Some("https://evil.example"), + Some("http://maproulette.org"), + Some("https://maproulette.org.evil.example"), + Some("https://beta.maproulette.org"), + ] { + assert!(!check(method.clone(), origin), "{method} from {origin:?}"); + } + } + for method in [Method::GET, Method::HEAD, Method::OPTIONS] { + assert!(check(method.clone(), None), "{method}"); + assert!( + check(method.clone(), Some("https://evil.example")), + "{method}" + ); + } + } +} diff --git a/api-v3/src/auth/play.rs b/api-v3/src/auth/play.rs new file mode 100644 index 00000000..74c3a143 --- /dev/null +++ b/api-v3/src/auth/play.rs @@ -0,0 +1,81 @@ +//! Validation for v2's browser session cookie. +//! +//! This can be refactored once sessions move into the `credentials` table. + +use std::collections::HashMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use hmac::{Hmac, KeyInit, Mac}; +use serde::Deserialize; +use sha2::Sha256; + +use crate::model::UserId; + +pub const COOKIE: &str = "PLAY_SESSION"; + +// matches v2's maproulette.session.timeout +const LIFETIME_MS: i64 = 30 * 24 * 60 * 60 * 1000; + +// matches Play's default play.http.session.jwt.clockSkew +const CLOCK_SKEW_S: i64 = 5 * 60; + +/// The parts of a v2 session that identify the user. The caller still has to +/// check `token_hash` against the user's current OSM token. +#[derive(Debug, PartialEq)] +pub struct Session { + pub user_id: UserId, + /// Lowercase hex SHA-256 of the user's OSM access token at login. + pub token_hash: String, +} + +#[derive(Deserialize)] +struct Header { + alg: String, +} + +#[derive(Deserialize)] +struct Claims { + data: HashMap, + nbf: Option, + exp: Option, +} + +/// Verifies a `PLAY_SESSION` cookie value and returns the logged-in user's +/// session, or None if the cookie is invalid, expired, or belongs to a session +/// with nobody logged in (v2 stores the OAuth state there during login). +pub fn decode(cookie: &str, secret: &[u8]) -> Option { + let (signed, signature) = cookie.rsplit_once('.')?; + let (header, claims) = signed.split_once('.')?; + + let header: Header = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header).ok()?).ok()?; + if header.alg != "HS256" { + return None; + } + let mut mac = Hmac::::new_from_slice(secret).expect("HMAC accepts any key length"); + mac.update(signed.as_bytes()); + mac.verify_slice(&URL_SAFE_NO_PAD.decode(signature).ok()?) + .ok()?; + + let claims: Claims = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims).ok()?).ok()?; + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock is after 1970") + .as_millis() as i64; + let now = now_ms / 1000; + if claims.nbf.is_some_and(|nbf| nbf > now + CLOCK_SKEW_S) + || claims.exp.is_some_and(|exp| exp <= now - CLOCK_SKEW_S) + { + return None; + } + + let login_ms: i64 = claims.data.get("userTick")?.parse().ok()?; + if login_ms < now_ms - LIFETIME_MS { + return None; + } + Some(Session { + user_id: UserId(claims.data.get("userId")?.parse().ok()?), + token_hash: claims.data.get("tokenHash")?.clone(), + }) +} diff --git a/api-v3/src/auth/token.rs b/api-v3/src/auth/token.rs new file mode 100644 index 00000000..cde581e6 --- /dev/null +++ b/api-v3/src/auth/token.rs @@ -0,0 +1,151 @@ +//! Functions for generating, parsing, and verifying credential tokens. +//! +//! A token is a string starting with `mrt_` followed by 43 random base62 characters +//! (about 256 bits of entropy) followed by a base62 CRC32 of everything before it. +//! +//! Tokens are validated by looking up their hashed value in the `credentials` table +//! in the database. The code in this module only verifies that a token is well-formed, +//! not that it is valid or belongs to a particular user. + +use std::fmt; + +use rand::distr::{Alphanumeric, SampleString}; +use sha2::{Digest, Sha256}; + +const PREFIX: &str = "mrt_"; +const RANDOM_LEN: usize = 43; +const CHECKSUM_LEN: usize = 6; +const LEN: usize = PREFIX.len() + RANDOM_LEN + CHECKSUM_LEN; +const HINT_LEN: usize = PREFIX.len() + 4; +const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +pub struct Token(String); + +impl Token { + pub fn generate() -> Token { + Token::assemble(&Alphanumeric.sample_string(&mut rand::rng(), RANDOM_LEN)) + } + + fn assemble(random: &str) -> Token { + let body = format!("{PREFIX}{random}"); + let sum = checksum(&body); + Token(body + &sum) + } + + // Checks that a string is a well-formed token (correct prefix, length, and valid CRC). + // Returns Some(Token) if it is, and None if not. + pub fn parse(s: &str) -> Option { + let well_formed = s.len() == LEN + && s.starts_with(PREFIX) + && s[PREFIX.len()..].bytes().all(|b| b.is_ascii_alphanumeric()); + if !well_formed { + return None; + } + let (body, sum) = s.split_at(LEN - CHECKSUM_LEN); + (checksum(body) == sum).then(|| Token(s.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// The SHA-256 of the whole token. + pub fn hash(&self) -> [u8; 32] { + Sha256::digest(&self.0).into() + } + + /// The first 8 characters of the token. This can be shown in server debug + /// logs to tell tokens apart; doing so reveals only about 24 of the 256 + /// random bits. + pub fn hint(&self) -> &str { + &self.0[..HINT_LEN] + } +} + +impl fmt::Debug for Token { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Token({}...)", self.hint()) + } +} + +fn checksum(body: &str) -> String { + let mut n = crc32fast::hash(body.as_bytes()); + let mut sum = [b'0'; CHECKSUM_LEN]; + for c in sum.iter_mut().rev() { + *c = BASE62[(n % 62) as usize]; + n /= 62; + } + sum.iter().map(|&c| c as char).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + // These were computed with Python's zlib.crc32 and hashlib.sha256. + const RANDOM: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg"; + const TOKEN: &str = "mrt_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg27X3i3"; + const HASH: &str = "2dbb7d0272e9faa2d1c02b3607ed24e9e7a4d1fdc547cee606e56340d4a4814e"; + + #[test] + fn matches_reference_vector() { + assert_eq!(Token::assemble(RANDOM).as_str(), TOKEN); + let hash: String = Token::parse(TOKEN) + .unwrap() + .hash() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + assert_eq!(hash, HASH); + } + + #[test] + fn generated_tokens_parse() { + let token = Token::generate(); + assert_eq!(token.as_str().len(), LEN); + assert!(token.as_str().starts_with(PREFIX)); + assert!(Token::parse(token.as_str()).is_some()); + assert_ne!(token.as_str(), Token::generate().as_str()); + } + + #[test] + fn rejects_any_changed_character() { + for i in PREFIX.len()..LEN { + for &c in BASE62 { + let mut s = TOKEN.as_bytes().to_vec(); + if s[i] == c { + continue; + } + s[i] = c; + let s = String::from_utf8(s).unwrap(); + assert!(Token::parse(&s).is_none(), "{s} parsed"); + } + } + } + + #[test] + fn rejects_malformed() { + let wrong_prefix = TOKEN.replacen("mrt_", "mrx_", 1); + let non_alphanumeric = TOKEN.replacen('A', "-", 1); + let non_ascii = TOKEN.replacen("AB", "\u{e9}", 1); + for s in [ + "", + "mrt_", + &TOKEN[..LEN - 1], + &format!("{TOKEN}0"), + &format!(" {}", &TOKEN[1..]), + &wrong_prefix, + &non_alphanumeric, + &non_ascii, + ] { + assert!(Token::parse(s).is_none(), "{s:?} parsed"); + } + } + + #[test] + fn debug_shows_only_hint() { + let token = Token::parse(TOKEN).unwrap(); + assert_eq!(token.hint(), "mrt_0123"); + assert_eq!(format!("{token:?}"), "Token(mrt_0123...)"); + } +} diff --git a/api-v3/src/authz.rs b/api-v3/src/authz.rs new file mode 100644 index 00000000..33d54025 --- /dev/null +++ b/api-v3/src/authz.rs @@ -0,0 +1,105 @@ +//! This module implements authorization rules, i.e. who may do what. These functions +//! just take a Principal and a Resource and return whether the action named by the +//! function is allowed; they do not touch the database (that's left for the caller). + +use crate::auth::{Principal, Via}; +use crate::error::Error; +use crate::model::{ChallengeAccess, Role, Scope}; + +/// Is this user allowed to replace the set of tasks in the given challenge? +pub fn upload_tasks(p: &Principal, access: ChallengeAccess) -> Result<(), Error> { + let ChallengeAccess::Role(role) = access else { + return Err(Error::NotFound); + }; + p.require_scope(Scope::ChallengesWrite)?; + match role { + Some(role) if role.satisfies(Role::Write) => Ok(()), + _ => Err(Error::Forbidden( + "Uploading tasks needs write access to the challenge", + )), + } +} + +/// Is this principal allowed to list, create or revoke their own personal access tokens? +/// (Only if they authenticated via a session token; we don't allow PATs to be used to +/// create other PATs) +pub fn manage_tokens(p: &Principal) -> Result<(), Error> { + match p.via { + Via::Session => Ok(()), + Via::Token { .. } => Err(Error::Forbidden( + "Tokens can only be managed while logged in to MapRoulette, not with a token", + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::TokenKind; + use crate::model::{CredentialId, UserId}; + + fn session() -> Principal { + Principal { + user_id: UserId(1), + via: Via::Session, + } + } + + fn token(scopes: &[Scope]) -> Principal { + Principal { + user_id: UserId(1), + via: Via::Token { + credential_id: CredentialId(1), + kind: TokenKind::Pat, + scopes: scopes.to_vec(), + }, + } + } + + /// A short name for a policy's decision, so cases can be compared. + fn outcome(result: Result<(), Error>) -> &'static str { + match result { + Ok(()) => "allowed", + Err(Error::NotFound) => "not found", + Err(Error::Forbidden(_)) => "forbidden", + Err(Error::InsufficientScope(_)) => "insufficient scope", + Err(e) => panic!("unexpected policy error {e}"), + } + } + + #[test] + fn upload_tasks_needs_write_and_the_scope() { + use ChallengeAccess::{NotFound, Role as R}; + let write = [Scope::ChallengesWrite]; + let cases = [ + (session(), NotFound, "not found"), + (session(), R(None), "forbidden"), + (session(), R(Some(Role::Read)), "forbidden"), + (session(), R(Some(Role::Write)), "allowed"), + (session(), R(Some(Role::Admin)), "allowed"), + (session(), R(Some(Role::Owner)), "allowed"), + (session(), R(Some(Role::SuperUser)), "allowed"), + (token(&write), R(Some(Role::Write)), "allowed"), + (token(&write), R(Some(Role::Read)), "forbidden"), + (token(&write), NotFound, "not found"), + (token(&[]), R(Some(Role::SuperUser)), "insufficient scope"), + (token(&[]), R(None), "insufficient scope"), + (token(&[]), NotFound, "not found"), + ]; + for (principal, access, expected) in cases { + assert_eq!( + outcome(upload_tasks(&principal, access)), + expected, + "{principal:?} with {access:?}" + ); + } + } + + #[test] + fn manage_tokens_needs_a_session() { + assert_eq!(outcome(manage_tokens(&session())), "allowed"); + let write = [Scope::ChallengesWrite]; + assert_eq!(outcome(manage_tokens(&token(&write))), "forbidden"); + assert_eq!(outcome(manage_tokens(&token(&[]))), "forbidden"); + } +} diff --git a/api-v3/src/config.rs b/api-v3/src/config.rs index 3f05a39f..59402277 100644 --- a/api-v3/src/config.rs +++ b/api-v3/src/config.rs @@ -2,11 +2,17 @@ use std::env; use std::net::SocketAddr; use anyhow::Context; +use axum::http::HeaderValue; pub struct Config { pub database_url: String, pub database_max_connections: u32, pub listen_addr: SocketAddr, + /// The key that signs v2's session cookies (Play's `play.http.secret.key`). + pub session_secret: String, + /// MapRoulette's own frontends, as origins (`https://maproulette.org`). Only these may make + /// credentialed cross-origin requests, or change state with the session cookie. + pub allowed_origins: Vec, } impl Config { @@ -20,10 +26,37 @@ impl Config { .unwrap_or_else(|_| "127.0.0.1:9001".into()) .parse() .context("LISTEN_ADDR must be a socket address, like 127.0.0.1:9001")?; + let session_secret = + env::var("APPLICATION_SECRET").context("APPLICATION_SECRET must be set")?; + anyhow::ensure!( + session_secret.len() >= 32, + "APPLICATION_SECRET must be at least 32 bytes" + ); + let allowed_origins = env::var("ALLOWED_ORIGINS") + .context("ALLOWED_ORIGINS must be set")? + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(origin) + .collect::>()?; Ok(Config { database_url, database_max_connections, listen_addr, + session_secret, + allowed_origins, }) } } + +fn origin(s: &str) -> anyhow::Result { + let host = s + .strip_prefix("https://") + .or_else(|| s.strip_prefix("http://")) + .filter(|host| !host.is_empty() && !host.contains('/')); + anyhow::ensure!( + host.is_some(), + "ALLOWED_ORIGINS entries must be origins like https://maproulette.org, not {s:?}" + ); + Ok(HeaderValue::try_from(s)?) +} diff --git a/api-v3/src/db/authz.rs b/api-v3/src/db/authz.rs new file mode 100644 index 00000000..5a749526 --- /dev/null +++ b/api-v3/src/db/authz.rs @@ -0,0 +1,100 @@ +use sqlx::PgExecutor; + +use crate::model::{ChallengeAccess, ChallengeId, Role, UserId}; + +/// The user's access to a challenge (mirror's v2's `Permission.effectiveRole`) +pub async fn challenge_access( + db: impl PgExecutor<'_>, + user_id: UserId, + challenge_id: ChallengeId, +) -> Result { + // Grant object and grantee types: 0 project, 1 challenge, 5 user, 6 team. + // Team member status 1 is "invited". + let row = sqlx::query!( + r#" + WITH team_roles AS ( + SELECT g.object_id AS team_id, min(g.role) AS role + FROM grants g + JOIN group_members m + ON m.group_id = g.object_id + AND m.member_type = 5 + AND m.member_id = $1 + AND m.status <> 1 + WHERE g.grantee_type = 5 AND g.grantee_id = $1 AND g.object_type = 6 + GROUP BY g.object_id + HAVING min(g.role) <= 2 + ), + target AS ( + SELECT c.id AS challenge_id, c.owner_team_id AS challenge_team_id, + p.id AS project_id, p.owner_team_id AS project_team_id, + coalesce(c.deleted, false) OR coalesce(p.deleted, false) AS deleted + FROM challenges c + JOIN projects p ON p.id = c.parent_id + WHERE c.id = $2 + ), + challenge_roles AS ( + SELECT g.role + FROM grants g, target t + WHERE g.grantee_type = 5 AND g.grantee_id = $1 + AND g.object_type = 1 AND g.object_id = t.challenge_id + UNION ALL + SELECT r.role + FROM team_roles r, target t + WHERE r.team_id = t.challenge_team_id + OR r.team_id IN ( + SELECT g.grantee_id FROM grants g + WHERE g.grantee_type = 6 AND g.object_type = 1 AND g.object_id = t.challenge_id + ) + ), + project_roles AS ( + SELECT g.role + FROM grants g, target t + WHERE g.grantee_type = 5 AND g.grantee_id = $1 + AND g.object_type = 0 AND g.object_id = t.project_id + UNION ALL + SELECT r.role + FROM team_roles r, target t + WHERE r.team_id = t.project_team_id + OR r.team_id IN ( + SELECT g.grantee_id FROM grants g + WHERE g.grantee_type = 6 AND g.object_type = 0 AND g.object_id = t.project_id + ) + ) + SELECT + t.deleted AS "deleted!", + CASE + WHEN EXISTS ( + SELECT 1 FROM grants + WHERE grantee_type = 5 AND grantee_id = $1 + AND role = -1 AND object_type = 0 AND object_id = 0 + ) THEN -1 + ELSE coalesce( + (SELECT min(role) FROM challenge_roles), + (SELECT min(role) FROM project_roles) + ) + END AS role + FROM target t + "#, + user_id.0, + challenge_id.0, + ) + .fetch_optional(db) + .await?; + Ok(match row { + None => ChallengeAccess::NotFound, + Some(r) if r.deleted => ChallengeAccess::NotFound, + Some(r) => ChallengeAccess::Role(r.role.map(role)), + }) +} + +fn role(rank: i32) -> Role { + match rank { + -1 => Role::SuperUser, + 0 => Role::Owner, + 1 => Role::Admin, + 2 => Role::Write, + 3 => Role::Read, + // the grants_role_valid constraint enforces that only the above ranks exist + _ => unreachable!("invalid grant role {rank}"), + } +} diff --git a/api-v3/src/db/credentials.rs b/api-v3/src/db/credentials.rs new file mode 100644 index 00000000..a126a2b2 --- /dev/null +++ b/api-v3/src/db/credentials.rs @@ -0,0 +1,151 @@ +use sqlx::PgExecutor; + +use crate::model::{CredentialId, NewPat, Pat, Scope, UserId}; + +/// A credential from the database, which we look up by its token hash. The +/// fields returned here are what we need to know to determine whether the +/// credential is valid, and if not, why not. +pub struct Credential { + pub id: CredentialId, + pub user_id: UserId, + pub kind: String, + pub scopes: Vec, + pub revoked: bool, + pub expired: bool, + pub idle: bool, + pub stale: bool, +} + +pub async fn find( + db: impl PgExecutor<'_>, + token_hash: &[u8], +) -> Result, sqlx::Error> { + sqlx::query!( + r#" + SELECT id, user_id, kind, scopes, + revoked_at IS NOT NULL AS "revoked!", + coalesce(expires_at <= now(), false) AS "expired!", + kind = 'pat' AND last_used_at <= now() - interval '90 days' AS "idle!", + last_used_at < now() - interval '5 minutes' AS "stale!" + FROM credentials + WHERE token_hash = $1 + "#, + token_hash, + ) + .map(|r| Credential { + id: CredentialId(r.id), + user_id: UserId(r.user_id), + kind: r.kind, + scopes: scopes(&r.scopes), + revoked: r.revoked, + expired: r.expired, + idle: r.idle, + stale: r.stale, + }) + .fetch_optional(db) + .await +} + +/// Records that a credential was just used. +pub async fn touch(db: impl PgExecutor<'_>, id: CredentialId) -> Result<(), sqlx::Error> { + sqlx::query!( + "UPDATE credentials SET last_used_at = now() \ + WHERE id = $1 AND last_used_at < now() - interval '5 minutes'", + id.0 + ) + .execute(db) + .await?; + Ok(()) +} + +/// The user's active personal access tokens, newest first. +pub async fn list_pats(db: impl PgExecutor<'_>, user_id: UserId) -> Result, sqlx::Error> { + sqlx::query!( + r#" + SELECT id, name AS "name!", scopes, created_at, expires_at, last_used_at + FROM credentials + WHERE user_id = $1 AND kind = 'pat' AND revoked_at IS NULL + AND (expires_at IS NULL OR expires_at > now()) + AND last_used_at > now() - interval '90 days' + ORDER BY created_at DESC, id DESC + "#, + user_id.0, + ) + .map(|r| Pat { + id: CredentialId(r.id), + name: r.name, + scopes: scopes(&r.scopes), + created_at: r.created_at, + expires_at: r.expires_at, + last_used_at: r.last_used_at, + }) + .fetch_all(db) + .await +} + +/// Stores and returns a new personal access token, unless the user already has +/// `limit` active ones, in which case it returns None. +pub async fn create_pat( + db: impl PgExecutor<'_>, + user_id: UserId, + token_hash: &[u8], + // For operators, to identify a token in logs and the database. Never shown to users. + hint: &str, + pat: &NewPat, + limit: i64, +) -> Result, sqlx::Error> { + let scopes: Vec = pat.scopes.iter().map(|s| s.as_str().to_owned()).collect(); + sqlx::query!( + r#" + INSERT INTO credentials (user_id, kind, token_hash, hint, name, scopes, expires_at) + SELECT $1, 'pat', $2, $3, $4, $5, $6 + WHERE ( + SELECT count(*) FROM credentials + WHERE user_id = $1 AND kind = 'pat' AND revoked_at IS NULL + AND (expires_at IS NULL OR expires_at > now()) + AND last_used_at > now() - interval '90 days' + ) < $7 + RETURNING id, created_at, last_used_at + "#, + user_id.0, + token_hash, + hint, + pat.name, + &scopes, + pat.expires_at, + limit, + ) + .map(|r| Pat { + id: CredentialId(r.id), + name: pat.name.clone(), + scopes: pat.scopes.clone(), + created_at: r.created_at, + expires_at: pat.expires_at, + last_used_at: r.last_used_at, + }) + .fetch_optional(db) + .await +} + +/// Revokes one of the user's personal access tokens. Returns false if the user +/// has no such token, or it's already revoked. +pub async fn revoke_pat( + db: impl PgExecutor<'_>, + user_id: UserId, + id: CredentialId, +) -> Result { + let revoked = sqlx::query!( + "UPDATE credentials SET revoked_at = now() \ + WHERE id = $1 AND user_id = $2 AND kind = 'pat' AND revoked_at IS NULL", + id.0, + user_id.0, + ) + .execute(db) + .await? + .rows_affected(); + Ok(revoked == 1) +} + +fn scopes(stored: &[String]) -> Vec { + stored.iter().filter_map(|s| Scope::parse(s)).collect() +} diff --git a/api-v3/src/db.rs b/api-v3/src/db/mod.rs similarity index 60% rename from api-v3/src/db.rs rename to api-v3/src/db/mod.rs index f08e5aeb..461e24de 100644 --- a/api-v3/src/db.rs +++ b/api-v3/src/db/mod.rs @@ -1,17 +1,22 @@ +pub mod authz; +pub mod credentials; +pub mod users; + use std::str::FromStr; use std::time::Duration; use sqlx::PgPool; use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; -pub async fn connect(url: &str, max_connections: u32) -> Result { - PgPoolOptions::new() +/// A pool that opens connections as they're needed, configured by `options`. +pub fn connect(url: &str, max_connections: u32) -> Result { + Ok(PgPoolOptions::new() .max_connections(max_connections) .acquire_timeout(Duration::from_secs(5)) - .connect_with(options(url)?) - .await + .connect_lazy_with(options(url)?)) } +/// Connection options: the URL, plus the timeouts every session gets. pub fn options(url: &str) -> Result { Ok(PgConnectOptions::from_str(url)? .application_name("maproulette-backend") diff --git a/api-v3/src/db/users.rs b/api-v3/src/db/users.rs new file mode 100644 index 00000000..300361eb --- /dev/null +++ b/api-v3/src/db/users.rs @@ -0,0 +1,31 @@ +use sqlx::PgExecutor; + +use crate::model::{OsmUserId, UserId}; + +pub struct Profile { + pub id: UserId, + pub osm_id: OsmUserId, + pub name: String, +} + +pub async fn profile(db: impl PgExecutor<'_>, id: UserId) -> Result { + let row = sqlx::query!("SELECT id, osm_id, name FROM users WHERE id = $1", id.0) + .fetch_one(db) + .await?; + Ok(Profile { + id: UserId(row.id), + osm_id: OsmUserId(row.osm_id), + name: row.name, + }) +} + +/// The user's current OSM access token. v2 sessions are bound to it (logging in +/// again replaces it, which ends the user's other sessions) +pub async fn oauth_token( + db: impl PgExecutor<'_>, + id: UserId, +) -> Result, sqlx::Error> { + sqlx::query_scalar!("SELECT oauth_token FROM users WHERE id = $1", id.0) + .fetch_optional(db) + .await +} diff --git a/api-v3/src/error.rs b/api-v3/src/error.rs index 470b526c..0fa1d478 100644 --- a/api-v3/src/error.rs +++ b/api-v3/src/error.rs @@ -1,4 +1,9 @@ +use std::sync::Arc; + +use axum::body::Body; +use axum::extract::Request; use axum::http::{HeaderValue, StatusCode, header}; +use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use serde::Serialize; use utoipa::ToSchema; @@ -6,14 +11,84 @@ use utoipa::ToSchema; /// The error type returned by route handler functions. #[derive(Debug, thiserror::Error)] pub enum Error { + /// The route requires a logged-in user and the request has no credential. + #[error("authentication required")] + Unauthenticated, + /// The request's bearer token is malformed, unknown, expired or revoked. + #[error("invalid token")] + InvalidToken, + /// The request's token lacks the scope that the action needs. + #[error("token lacks the {0} scope")] + InsufficientScope(&'static str), + /// The caller can see the resource but may not do this to it, for the reason given. + #[error("forbidden: {0}")] + Forbidden(&'static str), + /// No such resource, or the caller may not know that it exists. #[error("not found")] NotFound, #[error("method not allowed")] MethodNotAllowed, - #[error("request timed out")] - Timeout, - #[error(transparent)] - Database(#[from] sqlx::Error), + /// The request can't be parsed at all, for the reason given. + #[error("bad request: {0}")] + BadRequest(String), + /// The request conflicts with the resource's current state, for the reason given. + #[error("conflict: {0}")] + Conflict(String), + #[error("request body too large")] + PayloadTooLarge, + /// The body's media type or encoding isn't one the route accepts, for the reason given. + #[error("unsupported media type: {0}")] + UnsupportedMediaType(String), + /// The request parsed, but these parts of it are invalid. + #[error("invalid request")] + Validation(Vec), + /// A condition that a retry can be expected to resolve: a lock timeout, a deadlock, the + /// database being unreachable, the request timing out. + #[error("service unavailable")] + Unavailable(#[source] anyhow::Error), + /// Anything else (clients get only a generic response). + #[error("unexpected error")] + Unexpected(#[source] anyhow::Error), +} + +#[derive(Clone, Debug, Serialize, ToSchema)] +pub struct FieldError { + /// An RFC 6901 JSON Pointer into the request body. + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(nullable = false)] + pub pointer: Option, + /// A query parameter. + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(nullable = false)] + pub parameter: Option, + pub message: String, +} + +impl FieldError { + /// A problem with the request body whose location is described only in the message. + pub fn body(message: impl Into) -> FieldError { + FieldError { + pointer: None, + parameter: None, + message: message.into(), + } + } + + pub fn pointer(pointer: impl Into, message: impl Into) -> FieldError { + FieldError { + pointer: Some(pointer.into()), + parameter: None, + message: message.into(), + } + } + + pub fn parameter(parameter: impl Into, message: impl Into) -> FieldError { + FieldError { + pointer: None, + parameter: Some(parameter.into()), + message: message.into(), + } + } } /// An RFC 9457 problem document (`application/problem+json`). @@ -24,9 +99,17 @@ pub struct Problem { pub kind: &'static str, pub title: &'static str, pub status: u16, + /// A human-readable explanation of this error. #[serde(skip_serializing_if = "Option::is_none")] #[schema(nullable = false)] pub detail: Option, + /// For 422 responses: every invalid part of the request. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub errors: Vec, + /// The request's `x-request-id`, which uniquely identifies it. + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(nullable = false)] + pub request_id: Option, } /// Seconds a client should wait before retrying after a 503. @@ -35,18 +118,70 @@ const RETRY_AFTER: &str = "5"; impl Error { fn status(&self) -> StatusCode { match self { + Error::Unauthenticated | Error::InvalidToken => StatusCode::UNAUTHORIZED, + Error::InsufficientScope(_) | Error::Forbidden(_) => StatusCode::FORBIDDEN, Error::NotFound => StatusCode::NOT_FOUND, Error::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED, - Error::Timeout => StatusCode::SERVICE_UNAVAILABLE, - Error::Database(e) if is_transient(e) => StatusCode::SERVICE_UNAVAILABLE, - Error::Database(_) => StatusCode::INTERNAL_SERVER_ERROR, + Error::BadRequest(_) => StatusCode::BAD_REQUEST, + Error::Conflict(_) => StatusCode::CONFLICT, + Error::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE, + Error::UnsupportedMediaType(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE, + Error::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY, + Error::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE, + Error::Unexpected(_) => StatusCode::INTERNAL_SERVER_ERROR, + } + } + + /// The `WWW-Authenticate` challenge, per RFC 6750 + fn challenge(&self) -> Option { + match self { + Error::Unauthenticated => Some("Bearer".into()), + Error::InvalidToken => Some(r#"Bearer error="invalid_token""#.into()), + Error::InsufficientScope(scope) => Some(format!( + r#"Bearer error="insufficient_scope", scope="{scope}""# + )), + _ => None, + } + } + + fn detail(&self) -> Option { + match self { + Error::InsufficientScope(scope) => Some(format!("The token lacks the {scope} scope")), + Error::Forbidden(reason) => Some((*reason).into()), + Error::BadRequest(detail) + | Error::Conflict(detail) + | Error::UnsupportedMediaType(detail) => Some(detail.clone()), + _ => None, + } + } + + fn problem(&self, request_id: Option) -> Problem { + let status = self.status(); + Problem { + kind: "about:blank", + title: status.canonical_reason().unwrap_or("Error"), + status: status.as_u16(), + detail: self.detail(), + errors: match self { + Error::Validation(errors) => errors.clone(), + _ => Vec::new(), + }, + request_id, + } + } +} + +impl From for Error { + fn from(e: sqlx::Error) -> Error { + if is_transient(&e) { + Error::Unavailable(e.into()) + } else { + Error::Unexpected(e.into()) } } } -/// Database errors that a retry can be expected to resolve. The server returns -/// 503 Service Unavailable for these, with a Retry-After header, and 500 -/// Internal Server Error for others. +/// Database errors that a retry can be expected to resolve. fn is_transient(e: &sqlx::Error) -> bool { match e { sqlx::Error::Io(_) | sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed => true, @@ -59,27 +194,60 @@ fn is_transient(e: &sqlx::Error) -> bool { } } +/// Carries an error from `into_response` to the `report` middleware. +#[derive(Clone)] +struct Report(Arc); + impl IntoResponse for Error { fn into_response(self) -> Response { - let status = self.status(); - if status.is_server_error() { - tracing::error!(error = %self, "request failed"); - } - let problem = Problem { - kind: "about:blank", - title: status.canonical_reason().unwrap_or("Error"), - status: status.as_u16(), - detail: None, - }; - let mut res = (status, axum::Json(problem)).into_response(); + let mut res = self.status().into_response(); let headers = res.headers_mut(); - headers.insert( - header::CONTENT_TYPE, - HeaderValue::from_static("application/problem+json"), - ); - if status == StatusCode::SERVICE_UNAVAILABLE { + if let Some(challenge) = self.challenge() { + headers.insert( + header::WWW_AUTHENTICATE, + HeaderValue::try_from(challenge).expect("challenges are ASCII"), + ); + } + if matches!(self, Error::Unavailable(_)) { headers.insert(header::RETRY_AFTER, HeaderValue::from_static(RETRY_AFTER)); } + res.extensions_mut().insert(Report(Arc::new(self))); res } } + +/// Middleware that turns an `Error` response into a problem document and logs +/// server errors with their causes. +pub async fn report(req: Request, next: Next) -> Response { + let request_id = req + .headers() + .get("x-request-id") + .and_then(|v| v.to_str().ok()) + .map(String::from); + let mut res = next.run(req).await; + let Some(Report(error)) = res.extensions_mut().remove::() else { + return res; + }; + if res.status().is_server_error() { + tracing::error!(error = %causes(&*error), "request failed"); + } + let body = serde_json::to_vec(&error.problem(request_id)).expect("problems serialize"); + *res.body_mut() = Body::from(body); + res.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/problem+json"), + ); + res +} + +/// An error and its chain of sources, as `outer: inner: innermost`. +fn causes(e: &dyn std::error::Error) -> String { + let mut s = e.to_string(); + let mut source = e.source(); + while let Some(e) = source { + s.push_str(": "); + s.push_str(&e.to_string()); + source = e.source(); + } + s +} diff --git a/api-v3/src/lib.rs b/api-v3/src/lib.rs index 4db35107..6783584a 100644 --- a/api-v3/src/lib.rs +++ b/api-v3/src/lib.rs @@ -1,11 +1,63 @@ +pub mod auth; +pub mod authz; pub mod config; pub mod db; pub mod error; +pub mod model; mod routes; pub use routes::{openapi, router}; +use std::sync::Arc; +use std::time::Duration; + +use axum::Router; +use axum::http::HeaderValue; +use tokio::net::TcpListener; +use tokio::sync::Notify; + +use config::Config; + #[derive(Clone)] pub struct AppState { pub db: sqlx::PgPool, + /// The key that signs v2's session cookies. + pub session_secret: Arc<[u8]>, + /// MapRoulette's own frontends. See `Config::allowed_origins`. + pub allowed_origins: Arc<[HeaderValue]>, +} + +/// How long in-flight requests get to finish after shutdown begins. +const DRAIN_TIMEOUT: Duration = Duration::from_secs(5); + +pub fn app(config: &Config) -> Result { + let db = db::connect(&config.database_url, config.database_max_connections)?; + Ok(router(AppState { + db, + session_secret: config.session_secret.as_bytes().into(), + allowed_origins: config.allowed_origins.as_slice().into(), + })) +} + +pub async fn serve( + listener: TcpListener, + app: Router, + shutdown: impl Future + Send + 'static, +) -> anyhow::Result<()> { + let stopping = Arc::new(Notify::new()); + let server = axum::serve(listener, app).with_graceful_shutdown({ + let stopping = stopping.clone(); + async move { + shutdown.await; + stopping.notify_one(); + } + }); + tokio::select! { + res = server.into_future() => res?, + _ = async { + stopping.notified().await; + tokio::time::sleep(DRAIN_TIMEOUT).await; + } => anyhow::bail!("requests still in flight {DRAIN_TIMEOUT:?} after shutdown began"), + } + Ok(()) } diff --git a/api-v3/src/main.rs b/api-v3/src/main.rs index 077b8084..9582ba15 100644 --- a/api-v3/src/main.rs +++ b/api-v3/src/main.rs @@ -1,17 +1,9 @@ -use std::sync::Arc; -use std::time::Duration; - use tokio::net::TcpListener; use tokio::signal::unix::{SignalKind, signal}; -use tokio::sync::Notify; use tracing_subscriber::EnvFilter; use tracing_subscriber::filter::LevelFilter; use maproulette::config::Config; -use maproulette::{AppState, db, router}; - -/// How long in-flight requests get to finish after a shutdown signal. -const DRAIN_TIMEOUT: Duration = Duration::from_secs(5); #[tokio::main] async fn main() -> anyhow::Result<()> { @@ -25,28 +17,10 @@ async fn main() -> anyhow::Result<()> { .init(); let config = Config::from_env()?; - let db = db::connect(&config.database_url, config.database_max_connections).await?; - let app = router(AppState { db }); - + let app = maproulette::app(&config)?; let listener = TcpListener::bind(config.listen_addr).await?; tracing::info!(addr = %config.listen_addr, "listening"); - - let stopping = Arc::new(Notify::new()); - let server = axum::serve(listener, app).with_graceful_shutdown({ - let stopping = stopping.clone(); - async move { - shutdown_signal().await; - stopping.notify_one(); - } - }); - tokio::select! { - res = server.into_future() => res?, - _ = async { - stopping.notified().await; - tokio::time::sleep(DRAIN_TIMEOUT).await; - } => anyhow::bail!("requests still in flight {DRAIN_TIMEOUT:?} after shutdown signal"), - } - Ok(()) + maproulette::serve(listener, app, shutdown_signal()).await } async fn shutdown_signal() { diff --git a/api-v3/src/model/access.rs b/api-v3/src/model/access.rs new file mode 100644 index 00000000..0354f208 --- /dev/null +++ b/api-v3/src/model/access.rs @@ -0,0 +1,53 @@ +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +/// A user's role on a challenge or project (ordered strongest first) +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Role { + SuperUser, + Owner, + Admin, + Write, + Read, +} + +impl Role { + pub fn satisfies(self, required: Role) -> bool { + self <= required + } +} + +/// What a user may do with a challenge, as loaded from the database. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChallengeAccess { + /// No such challenge, or it or its project is deleted. Callers respond 404 + /// whatever the user's role. + NotFound, + /// The challenge exists, and this is the user's role on it, if any. + Role(Option), +} + +/// What a token may be used for. A session may do anything its user's role allows; a token is +/// limited to its scopes. The `credentials` table lists every scope that can be stored. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub enum Scope { + /// Replace the task sets of challenges the user can write to. + #[serde(rename = "challenges:write")] + ChallengesWrite, +} + +impl Scope { + /// The scope stored as `s`, or None for one this version doesn't know. + pub fn parse(s: &str) -> Option { + match s { + "challenges:write" => Some(Scope::ChallengesWrite), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Scope::ChallengesWrite => "challenges:write", + } + } +} diff --git a/api-v3/src/model/credentials.rs b/api-v3/src/model/credentials.rs new file mode 100644 index 00000000..c84b3202 --- /dev/null +++ b/api-v3/src/model/credentials.rs @@ -0,0 +1,21 @@ +use time::OffsetDateTime; + +use super::{CredentialId, Scope}; + +/// A personal access token, without its secret, which is only ever shown once. +pub struct Pat { + pub id: CredentialId, + pub name: String, + pub scopes: Vec, + pub created_at: OffsetDateTime, + /// None for a token that doesn't expire. + pub expires_at: Option, + pub last_used_at: OffsetDateTime, +} + +/// A personal access token to be created: what the user chose. +pub struct NewPat { + pub name: String, + pub scopes: Vec, + pub expires_at: Option, +} diff --git a/api-v3/src/model/ids.rs b/api-v3/src/model/ids.rs new file mode 100644 index 00000000..0fa15b12 --- /dev/null +++ b/api-v3/src/model/ids.rs @@ -0,0 +1,47 @@ +use std::fmt; + +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +macro_rules! id { + ($(#[$doc:meta])* $name:ident($inner:ty)) => { + $(#[$doc])* + #[derive( + Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema, sqlx::Type, + )] + #[serde(transparent)] + #[sqlx(transparent)] + pub struct $name(pub $inner); + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } + } + }; +} + +id!( + /// A MapRoulette user (`users.id`). + UserId(i32) +); +id!( + /// An OpenStreetMap user (`users.osm_id`, and v2's `owner_id` columns). + OsmUserId(i32) +); +id!( + /// A project (`projects.id`). + ProjectId(i32) +); +id!( + /// A challenge (`challenges.id`). + ChallengeId(i32) +); +id!( + /// A task (`tasks.id`). + TaskId(i32) +); +id!( + /// A credential: a personal access token, editor token or session (`credentials.id`). + CredentialId(i64) +); diff --git a/api-v3/src/model/mod.rs b/api-v3/src/model/mod.rs new file mode 100644 index 00000000..4cc1e29f --- /dev/null +++ b/api-v3/src/model/mod.rs @@ -0,0 +1,7 @@ +mod access; +mod credentials; +mod ids; + +pub use access::{ChallengeAccess, Role, Scope}; +pub use credentials::{NewPat, Pat}; +pub use ids::{ChallengeId, CredentialId, OsmUserId, ProjectId, TaskId, UserId}; diff --git a/api-v3/src/routes/extract.rs b/api-v3/src/routes/extract.rs new file mode 100644 index 00000000..9bf6c46c --- /dev/null +++ b/api-v3/src/routes/extract.rs @@ -0,0 +1,170 @@ +//! Request extractors whose rejections are `Error`s, so they render as problem documents like +//! every other error. Handlers use these instead of axum's `Json` and `Path`, which reject with +//! plain text. + +use axum::extract::rejection::{JsonRejection, PathRejection}; +use axum::extract::{FromRequest, FromRequestParts}; +use axum::http::StatusCode; + +use crate::error::{Error, FieldError}; + +/// Path parameters. A value that doesn't parse (`/challenges/abc`) is a 404: no such resource. +#[derive(FromRequestParts)] +#[from_request(via(axum::extract::Path), rejection(Error))] +pub struct Path(pub T); + +impl From for Error { + fn from(rejection: PathRejection) -> Error { + match rejection { + PathRejection::FailedToDeserializePathParams(_) => Error::NotFound, + // The route and the handler's parameters disagree: a bug, not a bad request. + r => Error::Unexpected(anyhow::anyhow!(r.body_text())), + } + } +} + +/// A JSON request body. Needs `Content-Type: application/json` (or another `+json` type). +/// Malformed JSON is a 400. JSON that doesn't fit `T` (a missing or unknown member, a wrong type) +/// is a 422 whose message names the member. +#[derive(FromRequest)] +#[from_request(via(axum::Json), rejection(Error))] +pub struct JsonBody(pub T); + +impl From for Error { + fn from(rejection: JsonRejection) -> Error { + match rejection { + JsonRejection::JsonDataError(e) => { + Error::Validation(vec![FieldError::body(e.body_text())]) + } + JsonRejection::JsonSyntaxError(e) => Error::BadRequest(e.body_text()), + JsonRejection::MissingJsonContentType(_) => { + Error::UnsupportedMediaType("Expected Content-Type: application/json".into()) + } + r if r.status() == StatusCode::PAYLOAD_TOO_LARGE => Error::PayloadTooLarge, + r => Error::BadRequest(r.body_text()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::body::Body; + use axum::extract::Request; + use axum::http::header; + use serde::Deserialize; + + #[derive(Debug, Deserialize)] + #[serde(deny_unknown_fields)] + #[allow(dead_code)] + struct Input { + name: String, + tags: Vec, + } + + #[derive(Debug, Deserialize)] + #[serde(deny_unknown_fields)] + #[allow(dead_code)] + struct Tag { + #[serde(rename = "a/b")] + value: u8, + } + + async fn extract(content_type: Option<&str>, body: &str) -> Result { + let mut req = Request::builder().method("POST").uri("/"); + if let Some(ct) = content_type { + req = req.header(header::CONTENT_TYPE, ct); + } + let req = req.body(Body::from(body.to_owned())).unwrap(); + JsonBody::::from_request(req, &()).await.map(|b| b.0) + } + + fn field_errors(result: Result) -> Vec<(Option, String)> { + match result { + Err(Error::Validation(errors)) => { + errors.into_iter().map(|e| (e.pointer, e.message)).collect() + } + other => panic!("expected a validation error, got {other:?}"), + } + } + + #[tokio::test] + async fn unparseable_path_parameter_is_not_found() { + use axum::Router; + use axum::response::IntoResponse; + use axum::routing::get; + use tower::ServiceExt; + + let app = Router::new().route( + "/things/{id}", + get(|Path(id): Path| async move { id.to_string() }), + ); + let get = |uri: &'static str| { + let app = app.clone(); + async move { + let req = Request::get(uri).body(Body::empty()).unwrap(); + app.oneshot(req).await.unwrap().into_response().status() + } + }; + assert_eq!(get("/things/12").await, StatusCode::OK); + assert_eq!(get("/things/abc").await, StatusCode::NOT_FOUND); + assert_eq!(get("/things/99999999999").await, StatusCode::NOT_FOUND); + } + + #[tokio::test] + async fn accepts_json() { + let body = r#"{"name": "x", "tags": [{"a/b": 1}]}"#; + assert_eq!( + extract(Some("application/json"), body).await.unwrap().name, + "x" + ); + let body = r#"{"name": "x", "tags": []}"#; + assert!( + extract(Some("application/merge-patch+json; charset=utf-8"), body) + .await + .is_ok() + ); + } + + #[tokio::test] + async fn needs_a_json_content_type() { + for ct in [ + None, + Some("text/plain"), + Some("application/x-www-form-urlencoded"), + ] { + let result = extract(ct, r#"{"name": "x", "tags": []}"#).await; + assert!( + matches!(result, Err(Error::UnsupportedMediaType(_))), + "{ct:?}" + ); + } + } + + #[tokio::test] + async fn malformed_json_is_a_bad_request() { + for body in ["", "{", r#"{"name": "x", "tags": []} x"#, "{name: 1}"] { + let result = extract(Some("application/json"), body).await; + assert!( + matches!(result, Err(Error::BadRequest(_))), + "{body:?}: {result:?}" + ); + } + } + + #[tokio::test] + async fn misfit_json_is_a_validation_error_naming_the_member() { + let ct = Some("application/json"); + for (body, member) in [ + (r#"{"name": 1, "tags": []}"#, "name"), + (r#"{"name": "x", "tags": [{"a/b": 300}]}"#, "tags[0].a/b"), + (r#"{"name": "x", "tags": [], "extra": 1}"#, "extra"), + (r#"{"tags": []}"#, "name"), + ] { + let errors = field_errors(extract(ct, body).await); + assert_eq!(errors.len(), 1, "{body}"); + assert_eq!(errors[0].0, None, "{body}"); + assert!(errors[0].1.contains(member), "{body}: {}", errors[0].1); + } + } +} diff --git a/api-v3/src/routes/me.rs b/api-v3/src/routes/me.rs new file mode 100644 index 00000000..66b5f9d6 --- /dev/null +++ b/api-v3/src/routes/me.rs @@ -0,0 +1,45 @@ +use axum::Json; +use axum::extract::State; +use serde::Serialize; +use utoipa::ToSchema; + +use crate::AppState; +use crate::auth::Principal; +use crate::db; +use crate::error::{Error, Problem}; +use crate::model::{OsmUserId, UserId}; + +#[derive(Serialize, ToSchema)] +pub struct Me { + /// MapRoulette user id. + id: UserId, + /// OpenStreetMap user id. + osm_id: OsmUserId, + /// OpenStreetMap display name. + name: String, +} + +/// Returns the authenticated user. Lets a script check that its token works. +#[utoipa::path( + get, + path = "/me", + tag = "users", + security(("session" = []), ("bearer" = [])), + responses( + (status = 200, description = "The authenticated user", body = Me), + ( + status = 401, + description = "No credential, or an invalid token", + body = Problem, + content_type = "application/problem+json", + ), + ), +)] +pub async fn me(State(state): State, principal: Principal) -> Result, Error> { + let profile = db::users::profile(&state.db, principal.user_id).await?; + Ok(Json(Me { + id: profile.id, + osm_id: profile.osm_id, + name: profile.name, + })) +} diff --git a/api-v3/src/routes/mod.rs b/api-v3/src/routes/mod.rs index 94103fcd..1407c003 100644 --- a/api-v3/src/routes/mod.rs +++ b/api-v3/src/routes/mod.rs @@ -1,23 +1,33 @@ +mod extract; mod health; +mod me; +// `Patch` has no users until the challenge endpoints land. +#[cfg_attr(not(test), expect(dead_code))] +mod patch; +mod tokens; +use std::sync::Arc; use std::time::Duration; use axum::Router; use axum::body::Bytes; use axum::extract::{MatchedPath, Request}; -use axum::http::{HeaderValue, header}; +use axum::http::{HeaderName, HeaderValue, Method, header}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::get; +use tower_http::cors::{AllowCredentials, AllowOrigin, CorsLayer}; use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer}; use tower_http::trace::{DefaultOnResponse, TraceLayer}; use tracing::Level; -use utoipa::OpenApi; +use utoipa::openapi::security::{ApiKey, ApiKeyValue, HttpAuthScheme, HttpBuilder, SecurityScheme}; +use utoipa::{Modify, OpenApi}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::AppState; -use crate::error::Error; +use crate::auth::{self, play}; +use crate::error::{self, Error}; const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); @@ -25,17 +35,57 @@ const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); #[openapi( info(title = "MapRoulette API", version = "3"), servers((url = "/api/v3")), + modifiers(&SecuritySchemes), )] struct ApiDoc; +struct SecuritySchemes; + +impl Modify for SecuritySchemes { + fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { + let components = openapi.components.get_or_insert_with(Default::default); + components.add_security_scheme( + "bearer", + SecurityScheme::Http( + HttpBuilder::new() + .scheme(HttpAuthScheme::Bearer) + .description(Some("A personal access token (`mrt_...`)")) + .build(), + ), + ); + components.add_security_scheme( + "session", + SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::with_description( + play::COOKIE, + "The browser session from logging in to maproulette.org", + ))), + ); + } +} + /// Every documented route. Paths are relative to `/api/v3`. fn api() -> OpenApiRouter { OpenApiRouter::with_openapi(ApiDoc::openapi()) + .merge(probes()) + .merge(authenticated()) +} + +/// Routes that never look at credentials, so they keep working when the database is down. +fn probes() -> OpenApiRouter { + OpenApiRouter::new() .routes(routes!(health::live)) .routes(routes!(health::ready)) .routes(routes!(health::health)) } +/// Routes behind `auth::resolve`. +fn authenticated() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(me::me)) + .routes(routes!(tokens::list, tokens::create)) + .routes(routes!(tokens::revoke)) +} + /// The OpenAPI document for the routes in `api()`. pub fn openapi() -> utoipa::openapi::OpenApi { api().split_for_parts().1 @@ -44,13 +94,16 @@ pub fn openapi() -> utoipa::openapi::OpenApi { /// The whole service: every route under `/api/v3`, plus `/api/v3/openapi.json`, with the /// middleware that applies to all of them. pub fn router(state: AppState) -> Router { - let (api, spec) = api().split_for_parts(); - let spec = Bytes::from(serde_json::to_vec(&spec).expect("OpenAPI document serializes")); - let api = api + let cors = cors(state.allowed_origins.clone()); + let spec = Bytes::from(serde_json::to_vec(&openapi()).expect("OpenAPI document serializes")); + let (probes, _) = probes().split_for_parts(); + let (authenticated, _) = authenticated().split_for_parts(); + let api = probes .route( "/openapi.json", get(move || async move { ([(header::CONTENT_TYPE, "application/json")], spec) }), ) + .merge(authenticated.layer(middleware::from_fn_with_state(state.clone(), auth::resolve))) .method_not_allowed_fallback(|| async { Error::MethodNotAllowed }); // Layers run bottom to top on the way in. @@ -58,6 +111,8 @@ pub fn router(state: AppState) -> Router { .nest("/api/v3", api) .fallback(|| async { Error::NotFound }) .layer(middleware::from_fn(timeout)) + .layer(middleware::from_fn(error::report)) + .layer(cors) .layer(middleware::from_fn(route_header)) .layer(PropagateRequestIdLayer::x_request_id()) .layer( @@ -74,6 +129,7 @@ pub fn router(state: AppState) -> Router { uri = %req.uri(), route = route(req), request_id = id, + auth = tracing::field::Empty, ) }) .on_response(DefaultOnResponse::new().level(Level::INFO)) @@ -84,11 +140,45 @@ pub fn router(state: AppState) -> Router { .with_state(state) } +/// Lets web pages on other origins call the API. Any origin may make requests +/// without credentials, but only our own frontend can use cookies to make +/// requests or read their responses. +fn cors(allowed_origins: Arc<[HeaderValue]>) -> CorsLayer { + CorsLayer::new() + .allow_origin(AllowOrigin::mirror_request()) + .allow_credentials(AllowCredentials::predicate(move |origin, _| { + allowed_origins.contains(origin) + })) + .allow_methods([ + Method::GET, + Method::HEAD, + Method::POST, + Method::PUT, + Method::PATCH, + Method::DELETE, + ]) + .allow_headers([ + header::AUTHORIZATION, + header::CONTENT_TYPE, + header::CONTENT_ENCODING, + ]) + .expose_headers([ + HeaderName::from_static("x-request-id"), + header::LOCATION, + header::RETRY_AFTER, + header::WWW_AUTHENTICATE, + ]) + .max_age(Duration::from_secs(60 * 60)) +} + /// Fails the request with a 503 if the handler takes longer than `REQUEST_TIMEOUT`. async fn timeout(req: Request, next: Next) -> Response { match tokio::time::timeout(REQUEST_TIMEOUT, next.run(req)).await { Ok(res) => res, - Err(_) => Error::Timeout.into_response(), + Err(_) => Error::Unavailable(anyhow::anyhow!( + "request took longer than {REQUEST_TIMEOUT:?}" + )) + .into_response(), } } diff --git a/api-v3/src/routes/patch.rs b/api-v3/src/routes/patch.rs new file mode 100644 index 00000000..314adb45 --- /dev/null +++ b/api-v3/src/routes/patch.rs @@ -0,0 +1,94 @@ +use serde::{Deserialize, Deserializer}; + +/// A field in a PATCH body, with JSON Merge Patch (RFC 7396) semantics: an absent member leaves +/// the stored value alone, `null` clears it, and a value sets it. +/// +/// Fields of this type need `#[serde(default)]`, so that an absent member deserializes as +/// `Absent`. Without it, an absent member is a "missing field" error rather than a silent change. +/// For the OpenAPI document, they also need `#[schema(value_type = Option)]`. +#[derive(Clone, Debug, Default, PartialEq)] +pub enum Patch { + #[default] + Absent, + Null, + Value(T), +} + +impl Patch { + /// Whether the request names the field. For SQL that writes a column only when it does: + /// `col = CASE WHEN $1 THEN $2 ELSE col END`, binding `is_set()` and `into_option()`. + pub fn is_set(&self) -> bool { + !matches!(self, Patch::Absent) + } + + /// The new value, or None to clear the field (or when it's absent; check `is_set` first). + pub fn into_option(self) -> Option { + match self { + Patch::Value(v) => Some(v), + Patch::Absent | Patch::Null => None, + } + } +} + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch { + fn deserialize>(d: D) -> Result { + Ok(match Option::::deserialize(d)? { + None => Patch::Null, + Some(v) => Patch::Value(v), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + use utoipa::{PartialSchema, ToSchema}; + + #[derive(Debug, Deserialize, ToSchema)] + struct Change { + #[serde(default)] + #[schema(value_type = Option)] + name: Patch, + } + + fn parse(body: Value) -> Patch { + serde_json::from_value::(body).unwrap().name + } + + #[test] + fn distinguishes_absent_null_and_value() { + assert_eq!(parse(json!({})), Patch::Absent); + assert_eq!(parse(json!({"name": null})), Patch::Null); + assert_eq!(parse(json!({"name": "x"})), Patch::Value("x".into())); + } + + #[test] + fn sql_binding() { + assert_eq!( + ( + Patch::::Absent.is_set(), + Patch::::Absent.into_option() + ), + (false, None) + ); + assert_eq!( + (Patch::::Null.is_set(), Patch::::Null.into_option()), + (true, None) + ); + assert_eq!( + (Patch::Value(1).is_set(), Patch::Value(1).into_option()), + (true, Some(1)) + ); + } + + #[test] + fn schema_is_an_optional_nullable_value() { + let schema = serde_json::to_value(Change::schema()).unwrap(); + assert_eq!( + schema["properties"]["name"]["type"], + json!(["string", "null"]) + ); + assert!(schema.get("required").is_none(), "{schema}"); + } +} diff --git a/api-v3/src/routes/tokens.rs b/api-v3/src/routes/tokens.rs new file mode 100644 index 00000000..cea404bb --- /dev/null +++ b/api-v3/src/routes/tokens.rs @@ -0,0 +1,212 @@ +//! The user's personal access tokens: `/me/tokens`. + +use axum::Json; +use axum::extract::State; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; +use utoipa::ToSchema; + +use super::extract::{JsonBody, Path}; +use crate::AppState; +use crate::auth::{Principal, token}; +use crate::authz; +use crate::db; +use crate::error::{Error, FieldError, Problem}; +use crate::model::{CredentialId, NewPat, Pat, Scope}; + +/// How many active tokens a user may have. +const MAX_TOKENS: i64 = 20; + +const MAX_NAME_CHARS: usize = 100; + +/// A personal access token. The token itself is shown only when it's created. +#[derive(Serialize, ToSchema)] +pub struct Token { + id: CredentialId, + /// What the token is for, as the user described it when creating it. + name: String, + /// Scopes the token has access to. + scopes: Vec, + #[serde(with = "time::serde::rfc3339")] + created_at: OffsetDateTime, + /// When the token stops working, or null if it doesn't expire. + #[serde(with = "time::serde::rfc3339::option")] + #[schema(required = true)] + expires_at: Option, + /// When the token was last used, to within a few minutes. Starts at `created_at`. A token + /// that goes unused for 90 days stops working, even if it doesn't expire. + #[serde(with = "time::serde::rfc3339")] + last_used_at: OffsetDateTime, +} + +impl From for Token { + fn from(pat: Pat) -> Token { + Token { + id: pat.id, + name: pat.name, + scopes: pat.scopes, + created_at: pat.created_at, + expires_at: pat.expires_at, + last_used_at: pat.last_used_at, + } + } +} + +/// A newly created token, including the token itself. +#[derive(Serialize, ToSchema)] +pub struct CreatedToken { + /// The token itself. The only time it's ever shown is in this response; + /// the database stores only the hash of the token. + token: String, + /// Other details about the token (name, scopes, expiration date, etc) + #[serde(flatten)] + details: Token, +} + +#[derive(Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct NewToken { + name: String, + scopes: Vec, + #[serde(with = "time::serde::rfc3339::option")] + #[schema(required = true)] + expires_at: Option, +} + +impl NewToken { + fn parse(self, now: OffsetDateTime) -> Result { + let mut errors = Vec::new(); + let name = self.name.trim(); + if name.is_empty() { + errors.push(FieldError::pointer("/name", "must not be empty")); + } else if name.chars().count() > MAX_NAME_CHARS { + errors.push(FieldError::pointer( + "/name", + format!("must be at most {MAX_NAME_CHARS} characters"), + )); + } + if self.scopes.is_empty() { + errors.push(FieldError::pointer( + "/scopes", + "must list at least one scope", + )); + } + for (i, scope) in self.scopes.iter().enumerate() { + if self.scopes[..i].contains(scope) { + errors.push(FieldError::pointer( + format!("/scopes/{i}"), + "is listed twice", + )); + } + } + if self.expires_at.is_some_and(|t| t <= now) { + errors.push(FieldError::pointer("/expires_at", "must be in the future")); + } + if !errors.is_empty() { + return Err(Error::Validation(errors)); + } + Ok(NewPat { + name: name.to_owned(), + scopes: self.scopes, + expires_at: self.expires_at, + }) + } +} + +/// Lists the user's active tokens +#[utoipa::path( + get, + path = "/me/tokens", + tag = "tokens", + security(("session" = [])), + responses( + (status = 200, description = "The user's active tokens", body = Vec), + (status = 401, description = "Not logged in", body = Problem, content_type = "application/problem+json"), + (status = 403, description = "Authenticated with a token rather than a session", body = Problem, content_type = "application/problem+json"), + ), +)] +pub async fn list( + State(state): State, + principal: Principal, +) -> Result>, Error> { + authz::manage_tokens(&principal)?; + let pats = db::credentials::list_pats(&state.db, principal.user_id).await?; + Ok(Json(pats.into_iter().map(Token::from).collect())) +} + +/// Creates a token. The response is the only time the token itself is shown. +#[utoipa::path( + post, + path = "/me/tokens", + tag = "tokens", + security(("session" = [])), + request_body = NewToken, + responses( + (status = 201, description = "The new token", body = CreatedToken), + (status = 400, description = "The body isn't JSON", body = Problem, content_type = "application/problem+json"), + (status = 401, description = "Not logged in", body = Problem, content_type = "application/problem+json"), + (status = 403, description = "Authenticated with a token rather than a session, or from an untrusted origin", body = Problem, content_type = "application/problem+json"), + (status = 409, description = "The user already has the maximum number of active tokens", body = Problem, content_type = "application/problem+json"), + (status = 415, description = "The body isn't `application/json`", body = Problem, content_type = "application/problem+json"), + (status = 422, description = "The body is invalid", body = Problem, content_type = "application/problem+json"), + ), +)] +pub async fn create( + State(state): State, + principal: Principal, + JsonBody(body): JsonBody, +) -> Result<(StatusCode, Json), Error> { + authz::manage_tokens(&principal)?; + let pat = body.parse(OffsetDateTime::now_utc())?; + let secret = token::Token::generate(); + let pat = db::credentials::create_pat( + &state.db, + principal.user_id, + &secret.hash(), + secret.hint(), + &pat, + MAX_TOKENS, + ) + .await? + .ok_or_else(|| { + Error::Conflict(format!( + "You already have {MAX_TOKENS} active tokens. Revoke one before creating another." + )) + })?; + tracing::info!(credential_id = %pat.id, "created personal access token"); + Ok(( + StatusCode::CREATED, + Json(CreatedToken { + token: secret.as_str().to_owned(), + details: pat.into(), + }), + )) +} + +/// Revokes a token +#[utoipa::path( + delete, + path = "/me/tokens/{id}", + tag = "tokens", + security(("session" = [])), + params(("id" = CredentialId, Path, description = "The token's id")), + responses( + (status = 204, description = "Revoked"), + (status = 401, description = "Not logged in", body = Problem, content_type = "application/problem+json"), + (status = 403, description = "Authenticated with a token rather than a session, or from an untrusted origin", body = Problem, content_type = "application/problem+json"), + (status = 404, description = "The user has no such token, or it's already revoked", body = Problem, content_type = "application/problem+json"), + ), +)] +pub async fn revoke( + State(state): State, + principal: Principal, + Path(id): Path, +) -> Result { + authz::manage_tokens(&principal)?; + if !db::credentials::revoke_pat(&state.db, principal.user_id, id).await? { + return Err(Error::NotFound); + } + tracing::info!(credential_id = %id, "revoked personal access token"); + Ok(StatusCode::NO_CONTENT) +} diff --git a/conf/evolutions/default/133.sql b/conf/evolutions/default/133.sql new file mode 100644 index 00000000..ee9c0ae5 --- /dev/null +++ b/conf/evolutions/default/133.sql @@ -0,0 +1,34 @@ +# --- MapRoulette Scheme + +# --- !Ups + +-- Stores credentials for the v3 API: personal access tokens, editor tokens, and +-- browser sessions. A token is mrt_ plus random characters and a checksum. Only +-- the token's hash is ever stored. The v2 backend never reads this table. +CREATE TABLE IF NOT EXISTS credentials ( + id bigserial PRIMARY KEY, + user_id integer NOT NULL REFERENCES users (id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('session', 'pat', 'editor')), + token_hash bytea NOT NULL UNIQUE, + hint text NOT NULL, + name text, + scopes text[] NOT NULL DEFAULT '{}', + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz, + last_used_at timestamptz NOT NULL DEFAULT now(), + revoked_at timestamptz, + CONSTRAINT credentials_session_scopes CHECK (kind <> 'session' OR scopes = '{}'), + CONSTRAINT credentials_token_scopes CHECK (kind = 'session' OR cardinality(scopes) > 0), + CONSTRAINT credentials_pat_name CHECK (kind <> 'pat' OR name IS NOT NULL), + CONSTRAINT credentials_expiry CHECK (kind = 'pat' OR expires_at IS NOT NULL), + CONSTRAINT credentials_token_hash_length CHECK (octet_length(token_hash) = 32) +);; + +-- Used for listing a user's credentials, e.g. in the settings page of the UI. +-- When authenticating a request, we look up the token by its SHA-256 hash, +-- which uses the unique index on the token_hash column. +SELECT create_index_if_not_exists('credentials', 'user_id', '(user_id)');; + +# --- !Downs + +DROP TABLE IF EXISTS credentials;;