//! The OpenID Connect provider of `im` (`docs/contracts.md` section 2): discovery, the signing keys, //! the authorization endpoint, the token endpoint and userinfo. //! //! Who may sign in is decided by the browser session (`auth.rs`); every endpoint here asks the store //! and never decides it alone. This module holds what the endpoints share: the token lifetimes, the //! JSON and OAuth error answers, the query and form parsing, and the URL builder for redirects. pub mod authorize; pub mod discovery; pub mod introspect; pub mod logout; pub mod revoke; pub mod signing; pub mod token; pub mod userinfo; #[cfg(test)] mod tests; use std::time::Duration; use http::header::{CACHE_CONTROL, CONTENT_TYPE, PRAGMA, WWW_AUTHENTICATE}; use serde_json::Value; use topcoat::router::content::Form; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderValue, StatusCode}; use crate::state::AppState; /// Lifetime of an authorization code (contracts section 2.3: 60 seconds, single use). pub const CODE_TTL: Duration = Duration::from_secs(60); /// Lifetime of an access token (contracts section 2.3: 10 minutes). pub const ACCESS_TTL: Duration = Duration::from_secs(10 * 60); /// Lifetime of an ID token. pub const ID_TOKEN_TTL: Duration = Duration::from_secs(10 * 60); /// Lifetime of a refresh token, unless its session ends first. pub const REFRESH_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); /// The largest form body the token endpoint reads, in bytes (task: 16 KiB). pub const TOKEN_BODY_LIMIT: usize = 16 * 1024; /// The audience of a user's access token: this provider's own userinfo endpoint, named by its family /// key. A machine token's audience is the target service instead (contracts section 2.6). pub const USERINFO_AUDIENCE: &str = "im"; /// Cache policy of the discovery document and the key set. Short, so a key change is seen soon. pub const PUBLIC_CACHE: &str = "public, max-age=300"; /// The issuer: the public origin with no trailing slash (`config.base_url`, validated at boot). pub fn issuer(app: &AppState) -> &str { &app.config.base_url } /// A JSON answer with `status` and no caching. pub fn json_response(status: StatusCode, body: &Value) -> Response { let mut response = Response::new(Body::from(body.to_string())); *response.status_mut() = status; let headers = response.headers_mut(); headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); headers.insert(PRAGMA, HeaderValue::from_static("no-cache")); response } /// An OAuth error at the token endpoint or another RFC 6749 endpoint (section 5.2). pub fn oauth_error(status: StatusCode, code: &str) -> Response { json_response(status, &serde_json::json!({ "error": code })) } /// `invalid_client`: 401 with a Basic challenge (RFC 6749 section 5.2). pub fn invalid_client() -> Response { let mut response = oauth_error(StatusCode::UNAUTHORIZED, "invalid_client"); response.headers_mut().insert( WWW_AUTHENTICATE, HeaderValue::from_static("Basic realm=\"im\""), ); response } /// `invalid_grant`: the code or token is not usable. One answer for every reason, so the reason is /// not disclosed. pub fn invalid_grant() -> Response { oauth_error(StatusCode::BAD_REQUEST, "invalid_grant") } /// The name and value pairs of a query string or a form body, in order. Repeats are kept. pub type Pairs = Vec<(String, String)>; /// Parses a query string or a form body. `None` when it is not valid URL-encoded data. pub fn parse_pairs(bytes: &[u8]) -> Option { Form::::from_bytes(bytes).ok().map(|form| form.0) } /// How often a parameter occurs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Single<'a> { /// Not present. Absent, /// Present exactly once. One(&'a str), /// Present more than once. Refused by every endpoint. Repeated, } /// How often `name` occurs in `pairs`. pub fn single<'a>(pairs: &'a [(String, String)], name: &str) -> Single<'a> { let mut values = pairs .iter() .filter(|(key, _)| key == name) .map(|(_, value)| value.as_str()); match (values.next(), values.next()) { (None, _) => Single::Absent, (Some(value), None) => Single::One(value), _ => Single::Repeated, } } /// The value of `name` when it occurs exactly once. pub fn one<'a>(pairs: &'a [(String, String)], name: &str) -> Option<&'a str> { match single(pairs, name) { Single::One(value) => Some(value), _ => None, } } /// Percent-encodes a query or form value: every byte except the RFC 3986 unreserved set. pub fn encode_value(value: &str) -> String { let mut out = String::with_capacity(value.len()); for byte in value.bytes() { if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { out.push(char::from(byte)); } else { out.push_str(&format!("%{byte:02X}")); } } out } /// Decodes `%XX` escapes. `None` for a bad escape or for bytes that are not UTF-8 once decoded. pub fn percent_decode(input: &str) -> Option { let bytes = input.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { if bytes[i] == b'%' { let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?; out.push(u8::from_str_radix(hex, 16).ok()?); i += 3; } else { out.push(bytes[i]); i += 1; } } String::from_utf8(out).ok() } /// Appends `params` to a redirect URI as a query, encoding every name and value. The registered URI /// has no fragment (checked at registration), so the query goes at its end. pub fn with_query(uri: &str, params: &[(&str, &str)]) -> String { let separator = if uri.ends_with(['?', '&']) { "" } else if uri.contains('?') { "&" } else { "?" }; let query: Vec = params .iter() .map(|(name, value)| format!("{}={}", encode_value(name), encode_value(value))) .collect(); format!("{uri}{separator}{}", query.join("&")) }