diff --git a/crates/im-core/src/jwt.rs b/crates/im-core/src/jwt.rs new file mode 100644 index 0000000..6fc4465 --- /dev/null +++ b/crates/im-core/src/jwt.rs @@ -0,0 +1,197 @@ +//! EdDSA (Ed25519) JSON Web Tokens: signing, verification, claim checks and the public key format. +//! +//! The header is `{"alg":"EdDSA","typ":"JWT","kid":...}`. Verification reads the algorithm first and +//! accepts only `EdDSA`, so `none` and every other algorithm fail before any key is used. The key is +//! chosen by `kid` from the keys that are published; an unknown `kid` is refused. Claim checks are a +//! separate call, so each caller states its own issuer and audience. + +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde_json::{Map, Value, json}; + +/// The only algorithm this provider signs or accepts. +pub const ALG: &str = "EdDSA"; + +/// How far an `iat` may lie in the future, in seconds (contracts section 2.3: five minutes). +pub const MAX_FUTURE_IAT_SECS: i64 = 300; + +/// Why a token was refused. Only the web layer sees these; the client gets one generic answer. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum JwtError { + /// The token does not have three parts, or a part is not valid base64url JSON. + #[error("the token is malformed")] + Malformed, + /// The header names an algorithm other than EdDSA. + #[error("the algorithm is not EdDSA")] + Algorithm, + /// The `kid` is missing or not published. + #[error("the key id is not published")] + UnknownKey, + /// The signature does not verify with the key. + #[error("the signature does not verify")] + Signature, + /// A claim is missing, has the wrong type or has a wrong value. + #[error("the claim {0} is missing or wrong")] + Claim(&'static str), +} + +/// A public key that may verify tokens, under its `kid`. +pub struct PublishedKey { + kid: String, + key: VerifyingKey, +} + +impl PublishedKey { + /// A verifying key from its `kid` and its 32 raw public bytes. `None` for bytes that are not a key. + pub fn new(kid: String, public: &[u8]) -> Option { + let raw: [u8; 32] = public.try_into().ok()?; + VerifyingKey::from_bytes(&raw) + .ok() + .map(|key| PublishedKey { kid, key }) + } +} + +/// Signs `claims` (a JSON object) with `key`, and puts `kid` in the header. +pub fn sign(key: &SigningKey, kid: &str, claims: &Value) -> String { + let header = json!({"alg": ALG, "typ": "JWT", "kid": kid}); + let signing_input = format!("{}.{}", encode_json(&header), encode_json(claims)); + let signature: Signature = key.sign(signing_input.as_bytes()); + format!( + "{signing_input}.{}", + BASE64_URL_SAFE_NO_PAD.encode(signature.to_bytes()) + ) +} + +/// Signs `claims` with the key whose 32-byte seed is `seed`. The seed is the sealed form of the key +/// (`keys::generate`), opened for the one call. +pub fn sign_with_seed(seed: &[u8; 32], kid: &str, claims: &Value) -> String { + sign(&SigningKey::from_bytes(seed), kid, claims) +} + +/// Verifies a token against the published keys and returns its claims. The algorithm, the `kid`, and +/// the signature are checked; the time and the issuer are not (see [`check_claims`]). +pub fn verify(keys: &[PublishedKey], token: &str) -> Result, JwtError> { + let mut parts = token.split('.'); + let (Some(header), Some(payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(JwtError::Malformed); + }; + let header = decode_object(header)?; + if header.get("alg").and_then(Value::as_str) != Some(ALG) { + return Err(JwtError::Algorithm); + } + let kid = header + .get("kid") + .and_then(Value::as_str) + .ok_or(JwtError::UnknownKey)?; + let key = keys + .iter() + .find(|known| known.kid == kid) + .ok_or(JwtError::UnknownKey)?; + let raw = BASE64_URL_SAFE_NO_PAD + .decode(signature) + .map_err(|_| JwtError::Malformed)?; + let raw: [u8; 64] = raw.try_into().map_err(|_| JwtError::Malformed)?; + let signature = Signature::from_bytes(&raw); + let signing_input = format!( + "{}.{}", + token.split('.').next().unwrap_or_default(), + payload + ); + key.key + .verify_strict(signing_input.as_bytes(), &signature) + .map_err(|_| JwtError::Signature)?; + decode_object(payload) +} + +/// Checks the registered claims: `iss` equals `issuer` exactly, `aud` is `audience` (a string, or an +/// array holding only that string), `exp` is in the future, and `iat` is at most five minutes ahead. +pub fn check_claims( + claims: &Map, + issuer: &str, + audience: &str, + now: i64, +) -> Result<(), JwtError> { + if claims.get("iss").and_then(Value::as_str) != Some(issuer) { + return Err(JwtError::Claim("iss")); + } + if !audience_is(claims.get("aud"), audience) { + return Err(JwtError::Claim("aud")); + } + let exp = claims + .get("exp") + .and_then(Value::as_i64) + .ok_or(JwtError::Claim("exp"))?; + if exp <= now { + return Err(JwtError::Claim("exp")); + } + let iat = claims + .get("iat") + .and_then(Value::as_i64) + .ok_or(JwtError::Claim("iat"))?; + if iat > now + MAX_FUTURE_IAT_SECS { + return Err(JwtError::Claim("iat")); + } + Ok(()) +} + +fn audience_is(aud: Option<&Value>, expected: &str) -> bool { + match aud { + Some(Value::String(one)) => one == expected, + Some(Value::Array(list)) => list.len() == 1 && list[0].as_str() == Some(expected), + _ => false, + } +} + +/// One public key as a JWK (RFC 8037), for the JWKS document. +pub fn jwk(kid: &str, public: &[u8]) -> Value { + json!({ + "kty": "OKP", + "crv": "Ed25519", + "x": BASE64_URL_SAFE_NO_PAD.encode(public), + "kid": kid, + "use": "sig", + "alg": ALG, + }) +} + +fn encode_json(value: &Value) -> String { + BASE64_URL_SAFE_NO_PAD.encode(value.to_string()) +} + +fn decode_object(segment: &str) -> Result, JwtError> { + let bytes = BASE64_URL_SAFE_NO_PAD + .decode(segment) + .map_err(|_| JwtError::Malformed)?; + match serde_json::from_slice(&bytes) { + Ok(Value::Object(map)) => Ok(map), + _ => Err(JwtError::Malformed), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_signed_token_verifies_and_a_tampered_one_does_not() { + let key = SigningKey::from_bytes(&[9u8; 32]); + let public = key.verifying_key().to_bytes(); + let keys = vec![PublishedKey::new("k1".into(), &public).expect("key")]; + let token = sign(&key, "k1", &json!({"iss": "https://im.test", "aud": "im"})); + assert!(verify(&keys, &token).is_ok()); + + let forged = json!({"iss": "https://im.test", "aud": "admin"}); + let mut parts: Vec<&str> = token.split('.').collect(); + let forged_part = BASE64_URL_SAFE_NO_PAD.encode(forged.to_string()); + parts[1] = &forged_part; + assert_eq!(verify(&keys, &parts.join(".")), Err(JwtError::Signature)); + let none = format!( + "{}.{}.", + BASE64_URL_SAFE_NO_PAD.encode(r#"{"alg":"none","kid":"k1"}"#), + BASE64_URL_SAFE_NO_PAD.encode("{}") + ); + assert_eq!(verify(&keys, &none), Err(JwtError::Algorithm)); + } +} diff --git a/crates/im-core/src/keys.rs b/crates/im-core/src/keys.rs new file mode 100644 index 0000000..5c204d2 --- /dev/null +++ b/crates/im-core/src/keys.rs @@ -0,0 +1,143 @@ +//! Token-signing keys: how a key is made, which key signs now, which keys are published, and when the +//! next key is due. +//! +//! The chain (contracts section 2.2, architecture section 8): a key is created at least 24 hours before +//! it signs, so it is published first. A key signs for 90 days. When its successor is created, it is +//! retired at the successor's activation time, and it stays published for 7 more days, so tokens it +//! signed before then still verify. Every instant here is a stored stamp; the comparisons are text. + +use std::time::Duration; + +use ed25519_dalek::SigningKey; + +use crate::model::KeyRecord; +use crate::time::{stamp_minus, stamp_plus}; + +const DAY: Duration = Duration::from_secs(24 * 60 * 60); + +/// How long a key signs before its successor takes over. +pub const ROTATION_PERIOD: Duration = Duration::from_secs(90 * 24 * 60 * 60); + +/// How long before it signs a new key is created and published. +pub const PUBLISH_LEAD: Duration = DAY; + +/// How long a retired key stays published after its retirement. +pub const OVERLAP: Duration = Duration::from_secs(7 * 24 * 60 * 60); + +/// A freshly generated key: its id, its seed (the private key) and its public key. +pub struct FreshKey { + /// Random key id, 32 hex characters. + pub kid: String, + /// The 32-byte Ed25519 seed. Seal it before storing. + pub seed: [u8; 32], + /// The 32-byte public key. + pub public: [u8; 32], +} + +/// Generates a new Ed25519 key with a random seed and a random `kid`. +pub fn generate() -> FreshKey { + let mut seed = [0u8; 32]; + rand::fill(&mut seed); + let public = SigningKey::from_bytes(&seed).verifying_key().to_bytes(); + let mut id = [0u8; 16]; + rand::fill(&mut id); + FreshKey { + kid: hex::encode(id), + seed, + public, + } +} + +/// The key that signs at `now`: the newest one whose activation has come and that is not yet retired. +pub fn current<'a>(keys: &'a [KeyRecord], now: &str) -> Option<&'a KeyRecord> { + keys.iter() + .filter(|key| { + key.activates_at.as_str() <= now + && key + .retires_at + .as_deref() + .is_none_or(|retired| retired > now) + }) + .max_by(|a, b| a.activates_at.cmp(&b.activates_at)) +} + +/// The keys published at `now`: every key not retired, and every key retired less than [`OVERLAP`] ago. +pub fn published<'a>(keys: &'a [KeyRecord], now: &str) -> Vec<&'a KeyRecord> { + let cutoff = stamp_minus(now, OVERLAP).unwrap_or_else(|| now.to_owned()); + keys.iter() + .filter(|key| { + key.retires_at + .as_deref() + .is_none_or(|retired| retired > cutoff.as_str()) + }) + .collect() +} + +/// Whether a new key must be created at `now`, and if so when it activates. `None` means the chain is +/// fine: a key is pending, or the current one is not due within the publish lead. +/// +/// With no key at all, the new key activates at once. Otherwise it activates [`PUBLISH_LEAD`] from now, +/// which is the first moment it can be published, and the newest key is retired at that same instant. +pub fn next_activation(keys: &[KeyRecord], now: &str) -> Option { + let head = keys + .iter() + .filter(|key| key.retires_at.is_none()) + .max_by(|a, b| a.activates_at.cmp(&b.activates_at)); + let Some(head) = head else { + return Some(now.to_owned()); + }; + if head.activates_at.as_str() > now { + return None; + } + let activates_at = stamp_plus(now, PUBLISH_LEAD)?; + let due = stamp_plus(&head.activates_at, ROTATION_PERIOD)?; + (activates_at >= due).then_some(activates_at) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(kid: &str, activates_at: &str, retires_at: Option<&str>) -> KeyRecord { + KeyRecord { + kid: kid.into(), + private_sealed: String::new(), + public_raw: vec![0; 32], + created_at: activates_at.into(), + activates_at: activates_at.into(), + retires_at: retires_at.map(str::to_owned), + } + } + + #[test] + fn the_chain_creates_its_successor_a_day_ahead_and_retires_the_old_key_then() { + let now = "2026-10-28T00:00:00.000000000Z"; + assert_eq!(next_activation(&[], now).as_deref(), Some(now)); + + let first = key("a", now, None); + // Far from due: nothing to do. + assert_eq!(next_activation(std::slice::from_ref(&first), now), None); + // Due within the lead: the successor activates one day from now. + let due_soon = "2027-01-25T12:00:00.000000000Z"; + assert_eq!( + next_activation(std::slice::from_ref(&first), due_soon).as_deref(), + Some("2027-01-26T12:00:00.000000000Z") + ); + + let retired = key("a", now, Some("2027-01-26T12:00:00.000000000Z")); + let successor = key("b", "2027-01-26T12:00:00.000000000Z", None); + let rows = [retired.clone(), successor.clone()]; + // Before the handover the old key still signs; after it the successor does. + assert_eq!( + current(&rows, "2027-01-26T11:59:59.000000000Z").map(|k| k.kid.as_str()), + Some("a") + ); + assert_eq!( + current(&rows, "2027-01-26T12:00:00.000000000Z").map(|k| k.kid.as_str()), + Some("b") + ); + // Both stay published across the overlap, and the retired one drops out after seven days. + assert_eq!(published(&rows, "2027-01-30T00:00:00.000000000Z").len(), 2); + assert_eq!(published(&rows, "2027-02-03T12:00:00.000000000Z").len(), 1); + } +} diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 1a4e49a..2eb4541 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -5,8 +5,11 @@ pub mod config; pub mod error; +pub mod jwt; +pub mod keys; pub mod model; pub mod names; +pub mod oauth; pub mod password; pub mod photo; pub mod secret; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index d4ef908..c36d146 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -175,3 +175,113 @@ pub struct AuditEntry { /// JSON with extra detail. Never holds a secret. pub data: Option, } + +/// An OpenID Connect client: one family app, or another client that asks for tokens. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Client { + /// ULID. This is the `client_id`. + pub id: String, + /// Display name, shown by the admin pages and the CLI. + pub name: String, + /// Hex SHA-256 of the client secret. The secret itself is shown once, at creation. + pub secret_hash: String, + /// When the secret was last issued. + pub secret_rotated_at: String, + /// Exact redirect URIs. A request matches only a string equal to one of them. + pub redirect_uris: Vec, + /// Exact post-logout redirect URIs (used by RP-initiated logout). + pub post_logout_redirect_uris: Vec, + /// Back-channel logout endpoint of the client, when it has one. + pub backchannel_logout_uri: Option, + /// Space-separated scopes the client may ask for. + pub allowed_scopes: String, + /// Family key such as `in`, when the client is a family service. + pub service_key: Option, + /// Creation time. + pub created_at: String, + /// Set when the client is disabled. A disabled client authenticates nowhere. + pub disabled_at: Option, +} + +impl Client { + /// True when the client is disabled. + pub fn is_disabled(&self) -> bool { + self.disabled_at.is_some() + } + + /// True when the client may ask for `scope`. + pub fn allows_scope(&self, scope: &str) -> bool { + self.allowed_scopes.split_whitespace().any(|s| s == scope) + } +} + +/// An authorization code row. Only the hash of the code is stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthCode { + /// Hex SHA-256 of the code. + pub code_hash: String, + /// The client the code was issued to. + pub client_id: String, + /// The person who signed in. + pub user_id: String, + /// The browser session the code was issued in. Its time and method go into the tokens. + pub session_id: String, + /// The redirect URI of the request, which the exchange must repeat. + pub redirect_uri: String, + /// The granted scope. + pub scope: String, + /// The nonce of the request, when there was one. + pub nonce: Option, + /// The PKCE challenge (S256) of the request. + pub code_challenge: String, + /// When the code stops being usable. + pub expires_at: String, + /// Set when the code was exchanged. A code is exchanged once. + pub used_at: Option, +} + +/// A refresh token row. Only the hash of the token is stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RefreshToken { + /// ULID. + pub id: String, + /// Hex SHA-256 of the token. + pub token_hash: String, + /// The first token of the chain. Reuse revokes every token with this family id. + pub family_id: String, + /// The client the token was issued to. + pub client_id: String, + /// The person. + pub user_id: String, + /// The browser session the chain belongs to. + pub session_id: String, + /// Hash of the authorization code the chain began with, when it began with one. + pub code_hash: Option, + /// The granted scope. + pub scope: String, + /// Creation time. + pub created_at: String, + /// Expiry. + pub expires_at: String, + /// Set when the token was rotated. Presenting a used token is reuse. + pub used_at: Option, + /// Set when the token or its family was revoked. + pub revoked_at: Option, +} + +/// One token-signing key. The private part is sealed under the instance key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyRecord { + /// Key id, published in the JWKS and in every token header. + pub kid: String, + /// The 32-byte Ed25519 seed, sealed with `secret::seal`. + pub private_sealed: String, + /// The 32-byte Ed25519 public key. + pub public_raw: Vec, + /// Creation time. + pub created_at: String, + /// When the key starts signing. Published before this time. + pub activates_at: String, + /// When the key stops signing. It stays published for a while after this time. + pub retires_at: Option, +} diff --git a/crates/im-core/src/oauth.rs b/crates/im-core/src/oauth.rs new file mode 100644 index 0000000..3511491 --- /dev/null +++ b/crates/im-core/src/oauth.rs @@ -0,0 +1,140 @@ +//! The OAuth 2.0 and OpenID Connect rules that are pure text: the scope names, the URI rules of +//! registered clients, the family-key format, and PKCE (RFC 7636). +//! +//! Nothing here touches the database or the network. The registration command and the endpoints use +//! the same functions, so a value is accepted or refused the same way everywhere. + +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; +use sha2::{Digest, Sha256}; + +/// Scopes a person grants at sign-in. Every family client is first-party, so there is no consent screen. +pub const USER_SCOPES: [&str; 3] = ["openid", "profile", "email"]; + +/// Every scope the provider advertises (contracts section 2.1). +pub const SUPPORTED_SCOPES: [&str; 5] = [ + "openid", + "profile", + "email", + "directory.read", + "files.service", +]; + +/// The longest `state` or `nonce` accepted, in bytes. Longer values are refused, not truncated. +pub const MAX_ECHO_BYTES: usize = 512; + +/// The longest registered URI, in bytes. +pub const MAX_URI_BYTES: usize = 2048; + +/// True for a scope the provider knows. +pub fn is_supported_scope(scope: &str) -> bool { + SUPPORTED_SCOPES.contains(&scope) +} + +/// True for a scope a person can be granted at sign-in. +pub fn is_user_scope(scope: &str) -> bool { + USER_SCOPES.contains(&scope) +} + +/// The S256 code challenge of a verifier: base64url of its SHA-256, without padding. +pub fn pkce_s256(verifier: &str) -> String { + BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +/// True for a code challenge: exactly 43 base64url characters (32 bytes, unpadded). +pub fn is_valid_challenge(challenge: &str) -> bool { + challenge.len() == 43 + && challenge + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// True for a code verifier: 43 to 128 unreserved characters (RFC 7636 section 4.1). +pub fn is_valid_verifier(verifier: &str) -> bool { + (43..=128).contains(&verifier.len()) + && verifier + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')) +} + +/// True for a registrable URI: `https`, or `http` to a loopback host (for development), absolute, with +/// no fragment, no userinfo (`@`), no whitespace or control characters and no backslash. Redirect URIs, +/// post-logout URIs and back-channel URIs all use this rule. +pub fn is_valid_registered_uri(uri: &str) -> bool { + if uri.len() > MAX_URI_BYTES + || uri.bytes().any(|b| b <= 0x20 || b == 0x7f || b == b'\\') + || uri.contains('#') + { + return false; + } + let Some((scheme, rest)) = uri.split_once("://") else { + return false; + }; + let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())]; + if authority.is_empty() || authority.contains('@') { + return false; + } + let host = host_of(authority); + match scheme { + "https" => !host.is_empty(), + "http" => is_loopback(host), + _ => false, + } +} + +/// The host of an authority (`host`, `host:port`, `[v6]:port`). +fn host_of(authority: &str) -> &str { + if let Some(bracketed) = authority.strip_prefix('[') { + return bracketed.split(']').next().unwrap_or(""); + } + authority.split(':').next().unwrap_or("") +} + +fn is_loopback(host: &str) -> bool { + matches!(host, "localhost" | "127.0.0.1" | "::1") +} + +/// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`. +pub fn is_valid_family_key(key: &str) -> bool { + let bytes = key.as_bytes(); + (1..=32).contains(&bytes.len()) + && bytes[0].is_ascii_lowercase() + && bytes + .iter() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_rfc_7636_example_challenge_matches() { + assert_eq!( + pkce_s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn registered_uris_must_be_exact_https_or_loopback_http() { + assert!(is_valid_registered_uri( + "https://in.example.com/auth/callback" + )); + assert!(is_valid_registered_uri( + "http://127.0.0.1:7655/auth/callback" + )); + assert!(is_valid_registered_uri("http://[::1]:7655/auth/callback")); + for bad in [ + "http://in.example.com/auth/callback", + "https://in.example.com@evil.example/auth/callback", + "https://in.example.com/auth/callback#frag", + "https:///auth/callback", + "https://in.example.com/a b", + "https://in.example.com\\evil", + "in.example.com/auth/callback", + "javascript://in.example.com/x", + ] { + assert!(!is_valid_registered_uri(bad), "accepted {bad:?}"); + } + } +} diff --git a/crates/im-core/src/store/clients.rs b/crates/im-core/src/store/clients.rs new file mode 100644 index 0000000..39e4230 --- /dev/null +++ b/crates/im-core/src/store/clients.rs @@ -0,0 +1,135 @@ +//! OIDC clients: registration, lookup, listing and disabling. +//! +//! The client secret is a random token, so only its SHA-256 is stored (`token.rs`). Redirect and +//! logout URIs are JSON arrays that are matched exactly, never by prefix. A disabled client keeps its +//! row, so its history stays readable, and it authenticates nowhere. + +use turso::Row; + +use crate::error::{Error, Result}; +use crate::model::Client; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::time::now_stamp; + +/// The columns of a client row, in the order [`map_client`] reads them. +const CLIENT_COLS: &str = "id, name, secret_hash, secret_rotated_at, redirect_uris, \ + post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, created_at, \ + disabled_at"; + +fn uri_list(row: &Row, i: usize) -> Result> { + let text = col_text(row, i)?; + serde_json::from_str(&text).map_err(|e| Error::Database(format!("bad URI list: {e}"))) +} + +/// Maps a row selected with [`CLIENT_COLS`]. +fn map_client(row: &Row) -> Result { + Ok(Client { + id: col_text(row, 0)?, + name: col_text(row, 1)?, + secret_hash: col_text(row, 2)?, + secret_rotated_at: col_text(row, 3)?, + redirect_uris: uri_list(row, 4)?, + post_logout_redirect_uris: uri_list(row, 5)?, + backchannel_logout_uri: col_opt_text(row, 6)?, + allowed_scopes: col_text(row, 7)?, + service_key: col_opt_text(row, 8)?, + created_at: col_text(row, 9)?, + disabled_at: col_opt_text(row, 10)?, + }) +} + +/// What is needed to register a client. The URIs must already be checked by `oauth.rs`. +#[derive(Debug, Clone)] +pub struct NewClient<'a> { + /// Display name. + pub name: &'a str, + /// Hex SHA-256 of the secret that is shown once. + pub secret_hash: &'a str, + /// Exact redirect URIs. + pub redirect_uris: &'a [String], + /// Exact post-logout redirect URIs. + pub post_logout_redirect_uris: &'a [String], + /// Back-channel logout endpoint, if any. + pub backchannel_logout_uri: Option<&'a str>, + /// Space-separated scopes the client may ask for. + pub allowed_scopes: &'a str, + /// Family key, if the client is a family service. Unique. + pub service_key: Option<&'a str>, +} + +impl Store { + /// Registers a client and returns its row. A family key that is already used is a conflict. + pub async fn create_client(&self, new: &NewClient<'_>) -> Result { + let id = new_id(); + let now = now_stamp(); + let redirect_uris = + serde_json::to_string(new.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; + let post_logout = serde_json::to_string(new.post_logout_redirect_uris) + .map_err(|e| Error::Invalid(e.to_string()))?; + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO clients (id, name, secret_hash, secret_rotated_at, redirect_uris, \ + post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, \ + created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?4)", + ( + id.clone(), + new.name.to_string(), + new.secret_hash.to_string(), + now, + redirect_uris, + post_logout, + new.backchannel_logout_uri.map(str::to_owned), + new.allowed_scopes.to_string(), + new.service_key.map(str::to_owned), + ), + ) + .await + .map_err(|e| { + if e.to_string().contains("UNIQUE") { + Error::Conflict("that family key is already used by another client".into()) + } else { + db_err(e) + } + })?; + drop(conn); + self.client_by_id(&id).await?.ok_or(Error::NotFound) + } + + /// The client with this id, disabled or not. + pub async fn client_by_id(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {CLIENT_COLS} FROM clients WHERE id = ?1"), + (id.to_string(),), + map_client, + ) + .await + } + + /// Every client, oldest first. + pub async fn list_clients(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {CLIENT_COLS} FROM clients ORDER BY created_at ASC, id ASC"), + (), + map_client, + ) + .await + } + + /// Disables a client. Returns false when there was no such client or it was already disabled. + pub async fn disable_client(&self, id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE clients SET disabled_at = ?2 WHERE id = ?1 AND disabled_at IS NULL", + (id.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } +} diff --git a/crates/im-core/src/store/keys.rs b/crates/im-core/src/store/keys.rs new file mode 100644 index 0000000..dc4a144 --- /dev/null +++ b/crates/im-core/src/store/keys.rs @@ -0,0 +1,86 @@ +//! Signing keys in the database: the chain of keys, and the one write that rotates it. +//! +//! The private seed is sealed before it reaches this module, so the rows hold no usable key material +//! in clear. Adding a key retires the previous one in the same transaction, so there is never a moment +//! with two keys both signing as the newest. + +use turso::Value; + +use crate::error::{Error, Result}; +use crate::model::KeyRecord; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, finish}; + +/// The columns of a key row, in the order [`map_key`] reads them. +const KEY_COLS: &str = "kid, private_sealed, public_raw, created_at, activates_at, retires_at"; + +fn map_key(row: &turso::Row) -> Result { + let public_raw = match row.get_value(2).map_err(db_err)? { + Value::Blob(bytes) => bytes, + _ => return Err(Error::Database("public_raw is not a blob".into())), + }; + Ok(KeyRecord { + kid: col_text(row, 0)?, + private_sealed: col_text(row, 1)?, + public_raw, + created_at: col_text(row, 3)?, + activates_at: col_text(row, 4)?, + retires_at: col_opt_text(row, 5)?, + }) +} + +impl Store { + /// Every key row, oldest activation first. + pub async fn signing_keys(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {KEY_COLS} FROM signing_keys ORDER BY activates_at ASC, kid ASC"), + (), + map_key, + ) + .await + } + + /// Adds a key. Every key that is not yet retired and activates before it is retired at its + /// activation time, in the same transaction. + pub async fn add_signing_key(&self, key: &KeyRecord) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + tx.execute( + "UPDATE signing_keys SET retires_at = ?1 \ + WHERE retires_at IS NULL AND activates_at < ?1", + (key.activates_at.clone(),), + ) + .await + .map_err(db_err)?; + tx.execute( + "INSERT INTO signing_keys (kid, private_sealed, public_raw, created_at, activates_at, \ + retires_at) VALUES (?1, ?2, ?3, ?4, ?5, NULL)", + ( + key.kid.clone(), + key.private_sealed.clone(), + key.public_raw.clone(), + key.created_at.clone(), + key.activates_at.clone(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Deletes keys retired at or before `cutoff`. Returns how many were removed. + pub async fn prune_signing_keys(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM signing_keys WHERE retires_at IS NOT NULL AND retires_at <= ?1", + (cutoff.to_string(),), + ) + .await + .map_err(db_err) + } +} diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 35cd4a7..ab76590 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -7,8 +7,11 @@ //! in effect are logged at boot. pub mod audit; +pub mod clients; pub mod directory; +pub mod keys; pub mod migrate; +pub mod oidc; pub mod sessions; pub mod snapshot; pub mod users; @@ -159,7 +162,7 @@ pub async fn finish(tx: Transaction<'_>, outcome: Result) -> Result { /// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order /// within a millisecond. -pub(crate) fn new_id() -> String { +pub fn new_id() -> String { ulid::Ulid::generate().to_string() } diff --git a/crates/im-core/src/store/oidc.rs b/crates/im-core/src/store/oidc.rs new file mode 100644 index 0000000..eae9c08 --- /dev/null +++ b/crates/im-core/src/store/oidc.rs @@ -0,0 +1,271 @@ +//! OIDC state in the database: authorization codes, refresh tokens, and the sessions each client has +//! signed into. +//! +//! The two single-use rules are one conditional statement each, inside one transaction together with +//! the row they create. Two parallel exchanges of one code, or of one refresh token, cannot both win. +//! A reuse is detected by the caller, which then revokes the family (`revoke_*`). + +use turso::Connection; + +use crate::error::Result; +use crate::model::{AuthCode, RefreshToken}; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish}; +use crate::time::now_stamp; + +/// The columns of an authorization code row, in the order [`map_code`] reads them. +const CODE_COLS: &str = "code_hash, client_id, user_id, session_id, redirect_uri, scope, nonce, \ + code_challenge, expires_at, used_at"; + +/// The columns of a refresh token row, in the order [`map_refresh`] reads them. +const REFRESH_COLS: &str = "id, token_hash, family_id, client_id, user_id, session_id, code_hash, \ + scope, created_at, expires_at, used_at, revoked_at"; + +fn map_code(row: &turso::Row) -> Result { + Ok(AuthCode { + code_hash: col_text(row, 0)?, + client_id: col_text(row, 1)?, + user_id: col_text(row, 2)?, + session_id: col_text(row, 3)?, + redirect_uri: col_text(row, 4)?, + scope: col_text(row, 5)?, + nonce: col_opt_text(row, 6)?, + code_challenge: col_text(row, 7)?, + expires_at: col_text(row, 8)?, + used_at: col_opt_text(row, 9)?, + }) +} + +fn map_refresh(row: &turso::Row) -> Result { + Ok(RefreshToken { + id: col_text(row, 0)?, + token_hash: col_text(row, 1)?, + family_id: col_text(row, 2)?, + client_id: col_text(row, 3)?, + user_id: col_text(row, 4)?, + session_id: col_text(row, 5)?, + code_hash: col_opt_text(row, 6)?, + scope: col_text(row, 7)?, + created_at: col_text(row, 8)?, + expires_at: col_text(row, 9)?, + used_at: col_opt_text(row, 10)?, + revoked_at: col_opt_text(row, 11)?, + }) +} + +/// A new authorization code. Only its hash is stored. +#[derive(Debug, Clone)] +pub struct NewAuthCode<'a> { + /// Hex SHA-256 of the code given to the client. + pub code_hash: &'a str, + /// The client the code is for. + pub client_id: &'a str, + /// The person who signed in. + pub user_id: &'a str, + /// The browser session the sign-in belongs to. + pub session_id: &'a str, + /// The redirect URI of the request. + pub redirect_uri: &'a str, + /// The granted scope. + pub scope: &'a str, + /// The nonce of the request, if any. + pub nonce: Option<&'a str>, + /// The S256 challenge of the request. + pub code_challenge: &'a str, + /// When the code stops being usable. + pub expires_at: &'a str, +} + +/// A new refresh token. `created_at` is set by the store, at the time of the write. +#[derive(Debug, Clone)] +pub struct NewRefreshToken<'a> { + /// ULID. + pub id: &'a str, + /// Hex SHA-256 of the token given to the client. + pub token_hash: &'a str, + /// The first token of the chain: its own id for a chain's first token. + pub family_id: &'a str, + /// The client the token is for. + pub client_id: &'a str, + /// The person. + pub user_id: &'a str, + /// The browser session the chain belongs to. + pub session_id: &'a str, + /// Hash of the authorization code the chain began with, if any. + pub code_hash: Option<&'a str>, + /// The granted scope. + pub scope: &'a str, + /// When the token stops being usable. + pub expires_at: &'a str, +} + +/// Inserts a refresh token row inside the caller's transaction. +async fn insert_refresh(conn: &Connection, new: &NewRefreshToken<'_>, now: &str) -> Result<()> { + conn.execute( + "INSERT INTO refresh_tokens (id, token_hash, family_id, client_id, user_id, session_id, \ + code_hash, scope, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + ( + new.id.to_string(), + new.token_hash.to_string(), + new.family_id.to_string(), + new.client_id.to_string(), + new.user_id.to_string(), + new.session_id.to_string(), + new.code_hash.map(str::to_owned), + new.scope.to_string(), + now.to_string(), + new.expires_at.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +impl Store { + /// Stores a new authorization code. + pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO auth_codes (code_hash, client_id, user_id, session_id, redirect_uri, scope, \ + nonce, code_challenge, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + ( + new.code_hash.to_string(), + new.client_id.to_string(), + new.user_id.to_string(), + new.session_id.to_string(), + new.redirect_uri.to_string(), + new.scope.to_string(), + new.nonce.map(str::to_owned), + new.code_challenge.to_string(), + new.expires_at.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The authorization code with this hash, used or not. + pub async fn auth_code(&self, code_hash: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {CODE_COLS} FROM auth_codes WHERE code_hash = ?1"), + (code_hash.to_string(),), + map_code, + ) + .await + } + + /// Exchanges a code: marks it used and stores the first refresh token, in one transaction. Returns + /// false, with nothing changed, when the code is already used, expired or unknown. The caller treats + /// a false after its own checks passed as a race, which is a reuse. + pub async fn redeem_auth_code( + &self, + code_hash: &str, + refresh: &NewRefreshToken<'_>, + ) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "UPDATE auth_codes SET used_at = ?2 \ + WHERE code_hash = ?1 AND used_at IS NULL AND expires_at > ?2", + (code_hash.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + if changed != 1 { + return Ok(false); + } + insert_refresh(&tx, refresh, &now).await?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + + /// The refresh token with this hash, used or not. + pub async fn refresh_token(&self, token_hash: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {REFRESH_COLS} FROM refresh_tokens WHERE token_hash = ?1"), + (token_hash.to_string(),), + map_refresh, + ) + .await + } + + /// Rotates a refresh token: marks the presented one used and stores its successor, in one + /// transaction. Returns false, with nothing changed, when the presented token was already used or + /// revoked. + pub async fn rotate_refresh_token( + &self, + presented_id: &str, + next: &NewRefreshToken<'_>, + ) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "UPDATE refresh_tokens SET used_at = ?2 \ + WHERE id = ?1 AND used_at IS NULL AND revoked_at IS NULL", + (presented_id.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + if changed != 1 { + return Ok(false); + } + insert_refresh(&tx, next, &now).await?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + + /// Revokes every token of a family that is not revoked yet. Returns how many were revoked. + pub async fn revoke_refresh_family(&self, family_id: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE family_id = ?1 AND revoked_at IS NULL", + (family_id.to_string(), now_stamp()), + ) + .await + .map_err(db_err) + } + + /// Revokes every refresh token issued from one authorization code. Returns how many were revoked. + pub async fn revoke_code_refresh_tokens(&self, code_hash: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE code_hash = ?1 AND revoked_at IS NULL", + (code_hash.to_string(), now_stamp()), + ) + .await + .map_err(db_err) + } + + /// Records that a browser session signed into a client. The first time sets `first_at`; every time + /// sets `last_at`. Drives back-channel logout and the connected-apps list. + pub async fn touch_client_session(&self, session_id: &str, client_id: &str) -> Result<()> { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO client_sessions (session_id, client_id, first_at, last_at) \ + VALUES (?1, ?2, ?3, ?3) \ + ON CONFLICT (session_id, client_id) DO UPDATE SET last_at = excluded.last_at", + (session_id.to_string(), client_id.to_string(), now), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs index 20fe903..fc057fa 100644 --- a/crates/im-core/src/store/sessions.rs +++ b/crates/im-core/src/store/sessions.rs @@ -214,6 +214,23 @@ impl Store { .await } + /// The session with this id when it is live (same rules as [`Store::session_by_token_hash`]), else + /// `None`. The token endpoints use it for the authentication time and method of the session. + pub async fn live_session(&self, session_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {SESSION_COLS} FROM sessions \ + WHERE id = ?1 AND expires_at > ?2 \ + AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)" + ), + (session_id.to_string(), now_stamp()), + map_session, + ) + .await + } + /// True when the session with this id is still live (same rules as /// [`Store::session_by_token_hash`]). The live stream checks this after every change. pub async fn session_is_live(&self, session_id: &str) -> Result { diff --git a/crates/im-core/src/time.rs b/crates/im-core/src/time.rs index d6bd8a9..83f6943 100644 --- a/crates/im-core/src/time.rs +++ b/crates/im-core/src/time.rs @@ -37,6 +37,37 @@ pub fn stamp_before(before: Duration) -> String { format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before))) } +/// Parses a stored stamp back into a time. `None` for anything that is not a stamp. +fn parse_stamp(stamp: &str) -> Option { + OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339).ok() +} + +/// The Unix time, in whole seconds, of a stored stamp. `None` when it is not a stamp. +pub fn unix_seconds(stamp: &str) -> Option { + parse_stamp(stamp).map(OffsetDateTime::unix_timestamp) +} + +/// The stamp `after` later than `stamp`, saturating at the largest time. `None` when `stamp` is not a +/// stamp. +pub fn stamp_plus(stamp: &str, after: Duration) -> Option { + Some(format_stamp( + parse_stamp(stamp)?.saturating_add(signed(after)), + )) +} + +/// The stamp `before` earlier than `stamp`, saturating at the smallest time. `None` when `stamp` is not +/// a stamp. +pub fn stamp_minus(stamp: &str, before: Duration) -> Option { + Some(format_stamp( + parse_stamp(stamp)?.saturating_sub(signed(before)), + )) +} + +/// The current Unix time in whole seconds. +pub fn unix_now() -> i64 { + OffsetDateTime::now_utc().unix_timestamp() +} + /// The IANA time zone names of the database compiled into this build, sorted. The bundled database /// is used on purpose, so every install offers the same list whatever the host has installed. pub fn zone_names() -> Vec { diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index 219e655..ba9b3a0 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -20,6 +20,7 @@ use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; use crate::live::LiveHub; +use crate::oidc::signing; use crate::pages::not_found::NotFoundLayer; use crate::pages::profile::PHOTO_ROUTE; use crate::security::{self, SecurityHeaders}; @@ -52,6 +53,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { tracing::info!("shutdown signal received"); stop_tx.send_replace(true); }); + let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); topcoat::serve_until( listener, @@ -59,13 +61,15 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { wait_stop(stop_rx), ) .await?; + let _ = signing_worker.await; tracing::info!("im stopped"); Ok(()) } /// Creates the data directory and opens the key and the database. Everything the router needs -/// that touches the disk is ready when this returns. -async fn open_state(config: Config) -> im_core::Result { +/// that touches the disk is ready when this returns. The signing keys are made ready too, so the +/// first token can be signed. The operator commands use this as well. +pub(crate) async fn open_state(config: Config) -> im_core::Result { std::fs::create_dir_all(&config.data_dir)?; // The directory holds the instance key. Only this user may enter it. std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; @@ -79,6 +83,7 @@ async fn open_state(config: Config) -> im_core::Result { } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; + signing::maintain(&store, &key).await?; Ok(AppState { config: Arc::new(config), store, diff --git a/crates/im-web/src/cli.rs b/crates/im-web/src/cli.rs new file mode 100644 index 0000000..d32ee34 --- /dev/null +++ b/crates/im-web/src/cli.rs @@ -0,0 +1,253 @@ +//! The `im client` commands: register, list and disable OpenID Connect clients from the operator's +//! shell. +//! +//! The commands open the database and the instance key directly, as the server does at boot, so they +//! need the data directory. A client secret is printed once, on standard output, and only its SHA-256 +//! is stored. The redirect, logout and back-channel URIs are checked by the same rules the endpoints use. + +use std::fmt::Display; +use std::path::Path; +use std::process::ExitCode; + +use im_core::config::Config; +use im_core::names::parse_display_name; +use im_core::oauth::{ + SUPPORTED_SCOPES, is_supported_scope, is_valid_family_key, is_valid_registered_uri, +}; +use im_core::store::clients::NewClient; +use im_core::token::{generate_token, hash_token}; + +use crate::boot::open_state; +use crate::state::AppState; + +/// Printed with a usage error. +const USAGE: &str = "usage: + im client add --name [--redirect-uri ]... [--post-logout-uri ]... + [--backchannel-uri ] [--family-key ] [--scopes ] + im client list + im client disable "; + +/// The scopes a client gets when `--scopes` is not given: what a family app signs in with. +const DEFAULT_SCOPES: &str = "openid profile email"; + +/// Runs one `im client` command. `words` are the words after `client`. +pub async fn client(config: &Path, words: &[String]) -> ExitCode { + let Some((verb, rest)) = words.split_first() else { + return usage(); + }; + match verb.as_str() { + "add" => match parse_add(rest) { + Ok(args) => with_state(config, |state| add(state, args)).await, + Err(message) => { + eprintln!("im: {message}\n{USAGE}"); + ExitCode::from(2) + } + }, + "list" if rest.is_empty() => with_state(config, list).await, + "disable" => match rest { + [id] => with_state(config, |state| disable(state, id)).await, + _ => usage(), + }, + _ => usage(), + } +} + +/// Prints the usage and exits with status 2. +fn usage() -> ExitCode { + eprintln!("im: unknown client command\n{USAGE}"); + ExitCode::from(2) +} + +/// Prints a failure and exits with status 1. +fn fail(error: impl Display) -> ExitCode { + eprintln!("im: {error}"); + ExitCode::FAILURE +} + +/// Opens the configuration, the key and the database, runs `action`, and maps its result to an exit +/// status. +async fn with_state(config: &Path, action: F) -> ExitCode +where + F: FnOnce(AppState) -> Fut, + Fut: std::future::Future>, +{ + let outcome = async { + let config = Config::load(config).map_err(|e| e.to_string())?; + let state = open_state(config).await.map_err(|e| e.to_string())?; + action(state).await + } + .await; + match outcome { + Ok(()) => ExitCode::SUCCESS, + Err(message) => fail(message), + } +} + +/// The options of `im client add`. +#[derive(Debug, Default, PartialEq, Eq)] +struct AddArgs { + name: Option, + redirect_uris: Vec, + post_logout_uris: Vec, + backchannel_uri: Option, + family_key: Option, + scopes: Option, +} + +/// Reads `--flag value` pairs. Flags that repeat collect; the rest may be given once. +fn parse_add(words: &[String]) -> std::result::Result { + let mut args = AddArgs::default(); + let mut words = words.iter(); + while let Some(flag) = words.next() { + let value = words + .next() + .ok_or_else(|| format!("{flag} needs a value"))? + .clone(); + let once = |slot: &mut Option| { + if slot.replace(value.clone()).is_some() { + Err(format!("{flag} may be given only once")) + } else { + Ok(()) + } + }; + match flag.as_str() { + "--name" => once(&mut args.name)?, + "--redirect-uri" => args.redirect_uris.push(value), + "--post-logout-uri" => args.post_logout_uris.push(value), + "--backchannel-uri" => once(&mut args.backchannel_uri)?, + "--family-key" => once(&mut args.family_key)?, + "--scopes" => once(&mut args.scopes)?, + other => return Err(format!("unknown option {other}")), + } + } + Ok(args) +} + +/// Registers a client and prints its id and its secret. The secret is not shown again. +async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> { + let name = parse_display_name(args.name.as_deref().ok_or("--name is required")?) + .map_err(|e| e.to_string())?; + for uri in args + .redirect_uris + .iter() + .chain(&args.post_logout_uris) + .chain(args.backchannel_uri.iter()) + { + if !is_valid_registered_uri(uri) { + return Err(format!( + "{uri} is not a valid URI for a client (https, or http on loopback, no fragment or userinfo)" + )); + } + } + if let Some(key) = &args.family_key + && !is_valid_family_key(key) + { + return Err(format!( + "family key {key} must be lowercase letters, digits and hyphens" + )); + } + let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?; + + let secret = generate_token(); + let client = state + .store + .create_client(&NewClient { + name: &name, + secret_hash: &hash_token(&secret), + redirect_uris: &args.redirect_uris, + post_logout_redirect_uris: &args.post_logout_uris, + backchannel_logout_uri: args.backchannel_uri.as_deref(), + allowed_scopes: &scopes, + service_key: args.family_key.as_deref(), + }) + .await + .map_err(|e| e.to_string())?; + println!("client_id: {}", client.id); + println!("client_secret: {secret}"); + eprintln!("im: the client secret is shown once; store it now"); + Ok(()) +} + +/// The requested scopes, checked and de-duplicated, space separated. +fn scope_list(requested: &str) -> std::result::Result { + let mut scopes: Vec<&str> = Vec::new(); + for word in requested.split_whitespace() { + if !is_supported_scope(word) { + return Err(format!( + "unknown scope {word}; the scopes are {}", + SUPPORTED_SCOPES.join(" ") + )); + } + if !scopes.contains(&word) { + scopes.push(word); + } + } + if scopes.is_empty() { + return Err("--scopes must name at least one scope".into()); + } + Ok(scopes.join(" ")) +} + +/// Prints one line per client: id, name, family key, scopes and status. No secret. +async fn list(state: AppState) -> std::result::Result<(), String> { + for client in state + .store + .list_clients() + .await + .map_err(|e| e.to_string())? + { + println!( + "{}\t{}\t{}\t{}\t{}", + client.id, + client.name, + client.service_key.as_deref().unwrap_or("-"), + client.allowed_scopes, + if client.is_disabled() { + "disabled" + } else { + "active" + }, + ); + } + Ok(()) +} + +/// Disables a client: it cannot authenticate, so it cannot exchange codes or refresh. +async fn disable(state: AppState, id: &str) -> std::result::Result<(), String> { + if state + .store + .disable_client(id) + .await + .map_err(|e| e.to_string())? + { + println!("disabled {id}"); + Ok(()) + } else { + Err(format!("no active client {id}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn words(list: &[&str]) -> Vec { + list.iter().map(|word| (*word).to_owned()).collect() + } + + #[test] + fn redirect_uris_repeat_and_a_name_is_given_once() { + let args = parse_add(&words(&[ + "--name", + "Files", + "--redirect-uri", + "https://a/cb", + "--redirect-uri", + "https://b/cb", + ])) + .expect("parse"); + assert_eq!(args.redirect_uris.len(), 2); + assert!(parse_add(&words(&["--name", "a", "--name", "b"])).is_err()); + assert!(parse_add(&words(&["--name"])).is_err()); + } +} diff --git a/crates/im-web/src/i18n/mod.rs b/crates/im-web/src/i18n/mod.rs index 19e373f..58ff418 100644 --- a/crates/im-web/src/i18n/mod.rs +++ b/crates/im-web/src/i18n/mod.rs @@ -8,6 +8,7 @@ //! helper functions next to their keys. pub mod account; +pub mod oidc; pub mod shell; use topcoat::context::Cx; diff --git a/crates/im-web/src/i18n/oidc.rs b/crates/im-web/src/i18n/oidc.rs new file mode 100644 index 0000000..4b41da0 --- /dev/null +++ b/crates/im-web/src/i18n/oidc.rs @@ -0,0 +1,28 @@ +//! Strings of the provider's own page: the page shown when an authorization request cannot be +//! answered at all (unknown or disabled client, or a redirect URI that is not registered). That page +//! is never a redirect, so it is the only place these words appear. + +use super::Lang; + +/// One variant per phrase. Add a variant, then its English and Turkish texts in [`text`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OidcText { + /// The title of the error page. + ErrorTitle, + /// The sentence under the title. + ErrorBody, +} + +/// The text of `key` in `lang`. +pub fn text(lang: Lang, key: OidcText) -> &'static str { + match (key, lang) { + (OidcText::ErrorTitle, Lang::En) => "Sign-in cannot continue", + (OidcText::ErrorTitle, Lang::Tr) => "Oturum açma devam edemiyor", + (OidcText::ErrorBody, Lang::En) => { + "This sign-in request is not valid. Go back to the application and try again." + } + (OidcText::ErrorBody, Lang::Tr) => { + "Bu oturum açma isteği geçerli değil. Uygulamaya dönüp yeniden deneyin." + } + } +} diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 4224ca5..9aa8b38 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -1,17 +1,19 @@ //! The `im` binary: the command line, logging and the process lifetime. //! -//! `im [--config ] [serve]` runs the server; a bare `im` does the same. `im admin ...` is the -//! operator command line, which is not built yet. The configuration file is the `--config` path, +//! `im [--config ] [serve]` runs the server; a bare `im` does the same. `im client ...` manages the +//! OpenID Connect clients (`cli.rs`). `im admin ...` is the operator command line, which is not built yet. The configuration file is the `--config` path, //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. mod assets; mod audit; mod auth; mod boot; +mod cli; mod client_ip; mod health; mod i18n; mod live; +mod oidc; mod pages; mod security; mod state; @@ -24,7 +26,7 @@ use std::process::ExitCode; use tracing_subscriber::EnvFilter; /// Printed with a usage error. -const USAGE: &str = "usage: im [--config ] [serve]"; +const USAGE: &str = "usage: im [--config ] [serve | client ...]"; /// The configuration file when neither `--config` nor `IM_CONFIG` names one. const DEFAULT_CONFIG: &str = "config/im.toml"; @@ -93,6 +95,7 @@ async fn main() -> ExitCode { let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); match words.as_slice() { [] | ["serve"] => serve(&config_path(cli.config)).await, + ["client", ..] => cli::client(&config_path(cli.config), &cli.words[1..]).await, ["admin", ..] => { eprintln!("im: admin commands are not implemented yet"); ExitCode::from(2) diff --git a/crates/im-web/src/oidc/authorize.rs b/crates/im-web/src/oidc/authorize.rs new file mode 100644 index 0000000..a2d3355 --- /dev/null +++ b/crates/im-web/src/oidc/authorize.rs @@ -0,0 +1,238 @@ +//! `GET /authorize` (contracts section 2.3, steps 1 and 2): checks the request, signs the person in if +//! needed, and redirects back with a one-time code. +//! +//! The order is fixed. First the client and the redirect URI are checked against the registration by +//! exact string match; until both pass, nothing is redirected and the error page is shown. Then every +//! other error goes to the registered redirect URI, with `error`, the `state` (only when it is usable) +//! and `iss`. Only then is a session asked for. PKCE with S256 is mandatory, and `plain` is refused. + +use im_core::model::Client; +use im_core::oauth::{MAX_ECHO_BYTES, is_supported_scope, is_user_scope, is_valid_challenge}; +use im_core::store::oidc::NewAuthCode; +use im_core::time::stamp_after; +use im_core::token::{generate_token, hash_token}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::request::uri; +use topcoat::router::{StatusCode, page}; +use topcoat::view::{View, component, view}; + +use super::{CODE_TTL, Pairs, Single, issuer, one, parse_pairs, single, with_query}; +use crate::auth::{current_user, percent_encode}; +use crate::i18n::Lang; +use crate::i18n::oidc::{OidcText, text}; +use crate::state::AppState; +use crate::views::{page_lang, shell}; + +/// What a request asks for, after the checks that need no database. +struct Asked { + /// The request's `state`, echoed back on every answer. + state: Option, + /// The PKCE challenge, stored with the code. + challenge: String, + /// The nonce, stored with the code and written into the ID token. + nonce: Option, + /// The granted scope: the request's scopes that are user scopes and that the client may ask for. + scope: String, + /// True for `prompt=none`: no page may be shown, only a result. + no_prompt: bool, +} + +/// A refusal that goes to the redirect URI. `state` is set only when the state was usable. +struct Refused { + code: &'static str, + state: Option, +} + +/// True when a `state` or `nonce` may be echoed: short enough and free of control characters. +fn usable_echo(value: &str) -> bool { + value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control) +} + +/// Checks everything in the query that does not need a session. Returns what was asked, or the refusal +/// to send to the redirect URI. +fn read(pairs: &Pairs, client: &Client) -> std::result::Result { + let state = match single(pairs, "state") { + Single::Absent => None, + Single::One(value) if usable_echo(value) => Some(value.to_owned()), + // A state that cannot be echoed is refused without echoing it. + _ => { + return Err(Refused { + code: "invalid_request", + state: None, + }); + } + }; + let refuse = |code: &'static str| Refused { + code, + state: state.clone(), + }; + for name in [ + "response_type", + "code_challenge", + "code_challenge_method", + "nonce", + "scope", + "prompt", + ] { + if single(pairs, name) == Single::Repeated { + return Err(refuse("invalid_request")); + } + } + match single(pairs, "response_type") { + Single::One("code") => {} + Single::One(_) => return Err(refuse("unsupported_response_type")), + _ => return Err(refuse("invalid_request")), + } + let challenge = match single(pairs, "code_challenge") { + Single::One(value) if is_valid_challenge(value) => value.to_owned(), + _ => return Err(refuse("invalid_request")), + }; + // `plain` and a missing method are refused: PKCE S256 is mandatory (contracts section 2.3). + if single(pairs, "code_challenge_method") != Single::One("S256") { + return Err(refuse("invalid_request")); + } + let nonce = match single(pairs, "nonce") { + Single::Absent => None, + Single::One(value) if usable_echo(value) => Some(value.to_owned()), + _ => return Err(refuse("invalid_request")), + }; + let Single::One(requested) = single(pairs, "scope") else { + return Err(refuse("invalid_request")); + }; + let mut granted: Vec<&str> = Vec::new(); + for word in requested.split_whitespace() { + if !is_supported_scope(word) { + return Err(refuse("invalid_scope")); + } + if is_user_scope(word) && client.allows_scope(word) && !granted.contains(&word) { + granted.push(word); + } + } + if !granted.contains(&"openid") { + return Err(refuse("invalid_scope")); + } + let no_prompt = match single(pairs, "prompt") { + Single::Absent => false, + Single::One(value) => match value.split_whitespace().collect::>().as_slice() { + [] => false, + ["none"] => true, + // Re-authentication and consent prompts are not offered; say so instead of ignoring them. + _ => return Err(refuse("invalid_request")), + }, + Single::Repeated => return Err(refuse("invalid_request")), + }; + Ok(Asked { + state, + challenge, + nonce, + scope: granted.join(" "), + no_prompt, + }) +} + +/// The redirect that carries a refusal to the client. +fn refusal_redirect(redirect_uri: &str, issuer: &str, refused: &Refused) -> SeeOther { + let mut params = vec![("error", refused.code), ("iss", issuer)]; + if let Some(state) = refused.state.as_deref() { + params.push(("state", state)); + } + see_other(with_query(redirect_uri, ¶ms)) +} + +/// `GET /authorize`. +/// +/// Every answer is either a redirect (`Err` carrying a `SeeOther`) or the error page, which is the only +/// `Ok` value. A request with an unknown client or an unregistered redirect URI never reaches a +/// redirect. +#[page(GET "/authorize")] +async fn authorize(cx: &Cx) -> Result { + let app = app_context::(cx); + let lang = page_lang(cx, None); + let Some(pairs) = parse_pairs(uri(cx).query().unwrap_or_default().as_bytes()) else { + return Ok(error_page(cx, lang)); + }; + let Some(client_id) = one(&pairs, "client_id") else { + return Ok(error_page(cx, lang)); + }; + let Some(redirect_uri) = one(&pairs, "redirect_uri") else { + return Ok(error_page(cx, lang)); + }; + let client = match app.store.client_by_id(client_id).await? { + Some(client) + if !client.is_disabled() + && client + .redirect_uris + .iter() + .any(|registered| registered == redirect_uri) => + { + client + } + _ => return Ok(error_page(cx, lang)), + }; + + // From here on the redirect URI is the registered one, so every refusal may go to it. + let issuer = issuer(app); + let asked = match read(&pairs, &client) { + Ok(asked) => asked, + Err(refused) => return Err(refusal_redirect(redirect_uri, issuer, &refused).into()), + }; + let Some(viewer) = current_user(cx).await? else { + if asked.no_prompt { + let refused = Refused { + code: "login_required", + state: asked.state.clone(), + }; + return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); + } + // Back to this exact request after sign-in: the login page checks `next` as a local path. + let back = uri(cx) + .path_and_query() + .map_or("/authorize", |p| p.as_str()); + return Err(see_other(format!("/login?next={}", percent_encode(back))).into()); + }; + + let code = generate_token(); + let expires_at = stamp_after(CODE_TTL); + app.store + .insert_auth_code(&NewAuthCode { + code_hash: &hash_token(&code), + client_id: &client.id, + user_id: &viewer.user.id, + session_id: &viewer.session.id, + redirect_uri, + scope: &asked.scope, + nonce: asked.nonce.as_deref(), + code_challenge: &asked.challenge, + expires_at: &expires_at, + }) + .await?; + app.store + .touch_client_session(&viewer.session.id, &client.id) + .await?; + + let mut params = vec![("code", code.as_str()), ("iss", issuer)]; + if let Some(state) = asked.state.as_deref() { + params.push(("state", state)); + } + Err(see_other(with_query(redirect_uri, ¶ms)).into()) +} + +/// The error page: a 400 in the shell, with no redirect and no detail about the request. +fn error_page(cx: &Cx, lang: Lang) -> impl View { + view! { cx => + (StatusCode::BAD_REQUEST) + shell(title: text(lang, OidcText::ErrorTitle), lang: lang, viewer: None, error_body(lang: lang)) + } +} + +/// The body of the error page. +#[component] +async fn error_body(lang: Lang) -> Result { + Ok(view! { +
+

(text(lang, OidcText::ErrorBody))

+
+ }) +} diff --git a/crates/im-web/src/oidc/discovery.rs b/crates/im-web/src/oidc/discovery.rs new file mode 100644 index 0000000..18c3b1f --- /dev/null +++ b/crates/im-web/src/oidc/discovery.rs @@ -0,0 +1,80 @@ +//! `GET /.well-known/openid-configuration` and `GET /jwks.json` (contracts sections 2.1 and 2.2). +//! +//! Both are public and cacheable for five minutes. Discovery lists the endpoints under the issuer; +//! the key set publishes every key that is active, pending or retired within the overlap period. + +use im_core::jwt; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::response::Response; +use topcoat::router::{HeaderValue, StatusCode, header, route}; + +use super::signing; +use super::{PUBLIC_CACHE, issuer, json_response}; +use crate::state::AppState; + +/// The grant types this provider offers. `client_credentials` is listed as the contracts require; it is +/// answered once the machine-token part is built. +const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"]; + +/// The client authentication methods of `/token`, `/revoke` and `/introspect`. +const AUTH_METHODS: [&str; 2] = ["client_secret_basic", "client_secret_post"]; + +/// The scopes this provider advertises. +const SCOPES: [&str; 5] = [ + "openid", + "profile", + "email", + "directory.read", + "files.service", +]; + +/// `GET /.well-known/openid-configuration`. +#[route(GET "/.well-known/openid-configuration")] +async fn discovery(cx: &Cx) -> topcoat::Result { + let base = issuer(app_context::(cx)); + let document = serde_json::json!({ + "issuer": base, + "authorization_endpoint": format!("{base}/authorize"), + "token_endpoint": format!("{base}/token"), + "userinfo_endpoint": format!("{base}/userinfo"), + "jwks_uri": format!("{base}/jwks.json"), + "end_session_endpoint": format!("{base}/logout"), + "revocation_endpoint": format!("{base}/revoke"), + "introspection_endpoint": format!("{base}/introspect"), + "response_types_supported": ["code"], + "grant_types_supported": GRANT_TYPES, + "subject_types_supported": ["public"], + "code_challenge_methods_supported": ["S256"], + "id_token_signing_alg_values_supported": [jwt::ALG], + "token_endpoint_auth_methods_supported": AUTH_METHODS, + "backchannel_logout_supported": true, + "backchannel_logout_session_supported": true, + "scopes_supported": SCOPES, + }); + Ok(cacheable(json_response(StatusCode::OK, &document))) +} + +/// `GET /jwks.json`: the published public keys as an OKP/Ed25519 JWK set. +#[route(GET "/jwks.json")] +async fn jwks(cx: &Cx) -> Result { + let app = app_context::(cx); + let keys = signing::published_keys(&app.store).await?; + let set: Vec = keys + .iter() + .map(|key| jwt::jwk(&key.kid, &key.public_raw)) + .collect(); + Ok(cacheable(json_response( + StatusCode::OK, + &serde_json::json!({ "keys": set }), + ))) +} + +/// Sets the short public cache policy on an answer that is not secret. +fn cacheable(mut response: Response) -> Response { + response.headers_mut().insert( + header::CACHE_CONTROL, + HeaderValue::from_static(PUBLIC_CACHE), + ); + response +} diff --git a/crates/im-web/src/oidc/mod.rs b/crates/im-web/src/oidc/mod.rs new file mode 100644 index 0000000..4585645 --- /dev/null +++ b/crates/im-web/src/oidc/mod.rs @@ -0,0 +1,172 @@ +//! 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 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("&")) +} diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs new file mode 100644 index 0000000..d662015 --- /dev/null +++ b/crates/im-web/src/oidc/signing.rs @@ -0,0 +1,96 @@ +//! The signing keys at run time: the key that signs now, the keys that are published now, the seal of +//! each private key, and the worker that keeps the chain of keys up to date. +//! +//! The private seed is opened for one signature and dropped; it is never kept in a field or a cache. +//! The worker runs at boot and then daily (architecture section 8). Rotation is due after 90 days and +//! the successor is created a day ahead, so it is published before it signs. + +use std::sync::Arc; +use std::time::Duration; + +use im_core::jwt; +use im_core::keys::{self, OVERLAP}; +use im_core::model::KeyRecord; +use im_core::secret; +use im_core::store::Store; +use im_core::time::{now_stamp, stamp_minus}; +use serde_json::Value; +use tokio::sync::watch; + +/// How often the worker checks the chain of keys. +const CHECK_EVERY: Duration = Duration::from_secs(24 * 60 * 60); + +/// Makes sure the chain is current: creates the first key when there is none, and creates the successor +/// when the newest key is due within the publish lead. Then removes keys retired more than [`OVERLAP`] +/// ago. Idempotent; safe to run at every boot. +pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<()> { + let rows = store.signing_keys().await?; + let now = now_stamp(); + if let Some(activates_at) = keys::next_activation(&rows, &now) { + let fresh = keys::generate(); + let record = KeyRecord { + kid: fresh.kid.clone(), + private_sealed: secret::seal(instance_key, &fresh.seed)?, + public_raw: fresh.public.to_vec(), + created_at: now.clone(), + activates_at: activates_at.clone(), + retires_at: None, + }; + store.add_signing_key(&record).await?; + tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); + } + let cutoff = stamp_minus(&now, OVERLAP).unwrap_or_else(|| now.clone()); + let pruned = store.prune_signing_keys(&cutoff).await?; + if pruned > 0 { + tracing::info!(pruned, "retired signing keys removed"); + } + Ok(()) +} + +/// Runs [`maintain`] daily until `stop` is set. Failures are logged; the next run tries again. +pub fn spawn( + store: Store, + instance_key: Arc<[u8; 32]>, + mut stop: watch::Receiver, +) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + loop { + tokio::select! { + () = tokio::time::sleep(CHECK_EVERY) => {} + _ = stop.wait_for(|stopped| *stopped) => break, + } + if let Err(error) = maintain(&store, &instance_key).await { + tracing::error!(error = %error, "signing key maintenance failed"); + } + } + }) +} + +/// The keys published now, for the JWKS document and for verifying tokens. +pub async fn published_keys(store: &Store) -> im_core::Result> { + let rows = store.signing_keys().await?; + Ok(keys::published(&rows, &now_stamp()) + .into_iter() + .cloned() + .collect()) +} + +/// Signs `claims` with the key that is current now. +pub async fn sign( + store: &Store, + instance_key: &[u8; 32], + claims: &Value, +) -> im_core::Result { + let rows = store.signing_keys().await?; + let record = keys::current(&rows, &now_stamp()) + .ok_or_else(|| im_core::Error::Crypto("no signing key is active".into()))?; + let seed = seed_of(instance_key, record)?; + Ok(jwt::sign_with_seed(&seed, &record.kid, claims)) +} + +/// Opens the sealed seed of a key row. +fn seed_of(instance_key: &[u8; 32], record: &KeyRecord) -> im_core::Result<[u8; 32]> { + let bytes = secret::open(instance_key, &record.private_sealed)?; + <[u8; 32]>::try_from(bytes.as_slice()) + .map_err(|_| im_core::Error::Crypto("signing key has the wrong length".into())) +} diff --git a/crates/im-web/src/oidc/tests.rs b/crates/im-web/src/oidc/tests.rs new file mode 100644 index 0000000..6f4649c --- /dev/null +++ b/crates/im-web/src/oidc/tests.rs @@ -0,0 +1,317 @@ +//! End-to-end tests of the provider through the router: the redirect rules, PKCE, code and refresh +//! reuse, client binding, and the ID token checked against the published key set. + +use std::time::Duration; + +use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; +use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, LOCATION}; +use im_core::jwt::{self, PublishedKey}; +use im_core::model::Client; +use im_core::oauth::pkce_s256; +use im_core::password::hash_password; +use im_core::store::clients::NewClient; +use im_core::store::sessions::{NewSession, SESSION_IDLE}; +use im_core::token::{generate_token, hash_token}; +use serde_json::Value; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, to_bytes}; + +use super::{encode_value, one, parse_pairs}; +use crate::boot::{router, test_state}; +use crate::state::AppState; + +/// The registered redirect URI of the test client. +const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback"; + +/// The cookie name the browser sends: the `__Host-` prefix is added by the jar. +const SESSION_COOKIE: &str = "__Host-im_session"; + +/// A client with a secret, a person, and a live browser session of that person. +struct Fixture { + _dir: tempfile::TempDir, + state: AppState, + client: Client, + secret: String, + user_id: String, + cookie: String, +} + +async fn fixture() -> Fixture { + let (dir, state) = test_state().await; + crate::oidc::signing::maintain(&state.store, &state.key) + .await + .expect("signing key"); + let secret = generate_token(); + let uris = vec![REDIRECT.to_owned()]; + let client = state + .store + .create_client(&NewClient { + name: "Files", + secret_hash: &hash_token(&secret), + redirect_uris: &uris, + post_logout_redirect_uris: &[], + backchannel_logout_uri: None, + allowed_scopes: "openid profile email", + service_key: Some("in"), + }) + .await + .expect("client"); + let hash = hash_password("the current password").expect("hash"); + let user = state + .store + .create_user("ada@example.com", "Ada", &hash, false) + .await + .expect("user"); + let cookie = generate_token(); + state + .store + .create_session( + &NewSession { + user_id: &user.id, + token_hash: &hash_token(&cookie), + csrf_token: &generate_token(), + amr: "pwd", + ip: None, + user_agent: None, + idle: SESSION_IDLE, + max_age: Duration::from_secs(3600), + }, + 10, + ) + .await + .expect("session"); + Fixture { + _dir: dir, + state, + client, + secret, + user_id: user.id, + cookie, + } +} + +/// Sends a request through the whole router and returns the status, headers and body text. +async fn send( + state: &AppState, + request: http::Request, +) -> (StatusCode, http::HeaderMap, String) { + let response: Response = router(state.clone()).handle(request).await; + let status = response.status(); + let headers = response.headers().clone(); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("body"); + ( + status, + headers, + String::from_utf8_lossy(&bytes).into_owned(), + ) +} + +/// The `/authorize` path for a request, with the given method and challenge. +fn authorize_path(client_id: &str, redirect: &str, challenge: &str, method: &str) -> String { + format!( + "/authorize?response_type=code&client_id={client_id}&redirect_uri={}\ + &scope=openid%20profile%20email&state=s1&nonce=n1&code_challenge={challenge}\ + &code_challenge_method={method}", + encode_value(redirect) + ) +} + +/// Runs `/authorize` as the signed-in person and returns the code from the redirect. +async fn code_for(f: &Fixture, client: &Client, verifier: &str) -> String { + let path = authorize_path(&client.id, REDIRECT, &pkce_s256(verifier), "S256"); + let request = http::Request::get(path) + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) + .body(Body::empty()) + .expect("request"); + let (status, headers, _) = send(&f.state, request).await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = headers[LOCATION].to_str().expect("location").to_owned(); + assert!(location.starts_with(&format!("{REDIRECT}?")), "{location}"); + let query = location.split_once('?').expect("query").1; + let pairs = parse_pairs(query.as_bytes()).expect("pairs"); + assert_eq!(one(&pairs, "state"), Some("s1")); + assert_eq!(one(&pairs, "iss"), Some(f.state.config.base_url.as_str())); + one(&pairs, "code").expect("code").to_owned() +} + +/// Posts a form to `/token` with `client_secret_basic` for `client`. +async fn token_with(f: &Fixture, client: &Client, secret: &str, body: &str) -> (StatusCode, Value) { + let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret)); + let request = http::Request::post("/token") + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(AUTHORIZATION, format!("Basic {basic}")) + .body(Body::from(body.to_owned())) + .expect("request"); + let (status, _, text) = send(&f.state, request).await; + (status, serde_json::from_str(&text).unwrap_or(Value::Null)) +} + +/// The form body of an authorization-code exchange. +fn code_body(code: &str, verifier: &str) -> String { + format!( + "grant_type=authorization_code&code={code}&redirect_uri={}&code_verifier={verifier}", + encode_value(REDIRECT) + ) +} + +#[tokio::test] +async fn an_unregistered_redirect_uri_is_never_redirected_to() { + let f = fixture().await; + let challenge = pkce_s256(&generate_token()); + for bad in [ + "http://127.0.0.1:17651/auth/callback/evil", + "http://127.0.0.1:17651/auth/callback/", + "http://127.0.0.1:17651/Auth/callback", + "http://127.0.0.1:17651@evil.example/auth/callback", + "http://127.0.0.1:17651/auth/callback?x=1", + "https://127.0.0.1:17651/auth/callback", + "http://127.0.0.1:17651/auth/callback#x", + ] { + let request = http::Request::get(authorize_path(&f.client.id, bad, &challenge, "S256")) + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) + .body(Body::empty()) + .expect("request"); + let (status, headers, _) = send(&f.state, request).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}"); + assert!(headers.get(LOCATION).is_none(), "redirected for {bad}"); + } +} + +#[tokio::test] +async fn plain_pkce_is_refused_through_the_registered_redirect() { + let f = fixture().await; + let verifier = generate_token(); + let request = http::Request::get(authorize_path(&f.client.id, REDIRECT, &verifier, "plain")) + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) + .body(Body::empty()) + .expect("request"); + let (status, headers, _) = send(&f.state, request).await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = headers[LOCATION].to_str().expect("location"); + assert!(location.starts_with(REDIRECT), "{location}"); + assert!(location.contains("error=invalid_request"), "{location}"); + assert!(!location.contains("code="), "{location}"); +} + +#[tokio::test] +async fn a_code_is_single_use_and_its_reuse_revokes_the_refresh_token() { + let f = fixture().await; + let verifier = generate_token(); + let code = code_for(&f, &f.client, &verifier).await; + let body = code_body(&code, &verifier); + + let (status, first) = token_with(&f, &f.client, &f.secret, &body).await; + assert_eq!(status, StatusCode::OK, "{first}"); + let refresh = first["refresh_token"].as_str().expect("refresh").to_owned(); + + let (status, second) = token_with(&f, &f.client, &f.secret, &body).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(second["error"], "invalid_grant"); + + let refresh_body = format!("grant_type=refresh_token&refresh_token={refresh}"); + let (status, third) = token_with(&f, &f.client, &f.secret, &refresh_body).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{third}"); + assert_eq!(third["error"], "invalid_grant"); +} + +#[tokio::test] +async fn a_code_for_another_client_is_refused_and_still_usable_by_its_own() { + let f = fixture().await; + let other_secret = generate_token(); + let uris = vec![REDIRECT.to_owned()]; + let other = f + .state + .store + .create_client(&NewClient { + name: "Board", + secret_hash: &hash_token(&other_secret), + redirect_uris: &uris, + post_logout_redirect_uris: &[], + backchannel_logout_uri: None, + allowed_scopes: "openid profile email", + service_key: Some("iz"), + }) + .await + .expect("client"); + let verifier = generate_token(); + let code = code_for(&f, &f.client, &verifier).await; + let body = code_body(&code, &verifier); + + let (status, wrong) = token_with(&f, &other, &other_secret, &body).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(wrong["error"], "invalid_grant"); + + let (status, right) = token_with(&f, &f.client, &f.secret, &body).await; + assert_eq!(status, StatusCode::OK, "{right}"); +} + +#[tokio::test] +async fn a_reused_refresh_token_revokes_the_whole_family() { + let f = fixture().await; + let verifier = generate_token(); + let code = code_for(&f, &f.client, &verifier).await; + let (_, first) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; + let r1 = first["refresh_token"].as_str().expect("r1").to_owned(); + + let (status, rotated) = token_with( + &f, + &f.client, + &f.secret, + &format!("grant_type=refresh_token&refresh_token={r1}"), + ) + .await; + assert_eq!(status, StatusCode::OK, "{rotated}"); + let r2 = rotated["refresh_token"].as_str().expect("r2").to_owned(); + + // Presenting the rotated token again is reuse: the successor dies too. + let (status, reused) = token_with( + &f, + &f.client, + &f.secret, + &format!("grant_type=refresh_token&refresh_token={r1}"), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(reused["error"], "invalid_grant"); + let (status, successor) = token_with( + &f, + &f.client, + &f.secret, + &format!("grant_type=refresh_token&refresh_token={r2}"), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{successor}"); +} + +#[tokio::test] +async fn the_id_token_verifies_against_the_published_key_and_carries_the_nonce() { + let f = fixture().await; + let verifier = generate_token(); + let code = code_for(&f, &f.client, &verifier).await; + let (status, tokens) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; + assert_eq!(status, StatusCode::OK, "{tokens}"); + let id_token = tokens["id_token"].as_str().expect("id_token"); + + let request = http::Request::get("/jwks.json") + .body(Body::empty()) + .expect("request"); + let (status, _, jwks) = send(&f.state, request).await; + assert_eq!(status, StatusCode::OK); + let keys: Vec = serde_json::from_str::(&jwks).expect("jwks")["keys"] + .as_array() + .expect("keys") + .iter() + .filter_map(|jwk| { + let raw = BASE64_URL_SAFE_NO_PAD.decode(jwk["x"].as_str()?).ok()?; + PublishedKey::new(jwk["kid"].as_str()?.to_owned(), &raw) + }) + .collect(); + let claims = jwt::verify(&keys, id_token).expect("signature verifies"); + let now = im_core::time::unix_now(); + jwt::check_claims(&claims, &f.state.config.base_url, &f.client.id, now).expect("claims"); + assert_eq!(claims["nonce"], "n1"); + assert_eq!(claims["sub"], f.user_id.as_str()); + assert_eq!(claims["amr"], serde_json::json!(["pwd"])); +} diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs new file mode 100644 index 0000000..80ba329 --- /dev/null +++ b/crates/im-web/src/oidc/token.rs @@ -0,0 +1,376 @@ +//! `POST /token` (contracts section 2.3, step 3, and refresh): client authentication, the +//! authorization-code grant and the refresh-token grant, and the token response. +//! +//! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The +//! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every +//! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one +//! revokes its whole family. Client credentials (machine tokens) is answered `unsupported_grant_type` +//! until its part of the provider is built. + +use base64::prelude::{BASE64_STANDARD, Engine as _}; +use http::header::AUTHORIZATION; +use im_core::model::{Client, Session, User}; +use im_core::oauth::{is_valid_verifier, pkce_s256}; +use im_core::store::new_id; +use im_core::store::oidc::NewRefreshToken; +use im_core::time::{now_stamp, stamp_after, unix_seconds}; +use im_core::token::{constant_time_eq, generate_token, hash_token}; +use serde_json::{Map, Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{content_type, headers}; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, route, to_bytes}; + +use super::signing; +use super::{ + ACCESS_TTL, ID_TOKEN_TTL, Pairs, REFRESH_TTL, Single, TOKEN_BODY_LIMIT, USERINFO_AUDIENCE, + invalid_client, invalid_grant, issuer, json_response, oauth_error, one, parse_pairs, single, +}; +use crate::state::AppState; + +/// `POST /token`. +#[route(POST "/token")] +async fn token_endpoint(cx: &Cx, body: Body) -> Result { + let app = app_context::(cx); + if !is_form(content_type(cx)) { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + } + let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else { + return Ok(oauth_error( + StatusCode::PAYLOAD_TOO_LARGE, + "invalid_request", + )); + }; + let Some(pairs) = parse_pairs(&bytes) else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + }; + let authorization = headers(cx) + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let client = match authenticate(app, authorization.as_deref(), &pairs).await? { + Ok(client) => client, + Err(response) => return Ok(response), + }; + match one(&pairs, "grant_type") { + Some("authorization_code") => grant_code(app, &client, &pairs).await, + Some("refresh_token") => grant_refresh(app, &client, &pairs).await, + Some(_) => Ok(oauth_error( + StatusCode::BAD_REQUEST, + "unsupported_grant_type", + )), + None => Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")), + } +} + +/// True for a form body, with or without parameters after the media type. +fn is_form(content_type: Option<&str>) -> bool { + content_type.is_some_and(|value| { + value + .split(';') + .next() + .unwrap_or_default() + .trim() + .eq_ignore_ascii_case("application/x-www-form-urlencoded") + }) +} + +/// The `client_id` and `client_secret` of a `Basic` credential, percent-decoded (RFC 6749 section +/// 2.3.1). `None` when the header is not a Basic one; `Some(Err)` when it is Basic but malformed. +fn basic_credentials(header: &str) -> Option> { + let (scheme, encoded) = header.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("basic") { + return None; + } + let decoded = BASE64_STANDARD + .decode(encoded.trim()) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()); + let parsed = decoded.as_deref().and_then(|text| { + let (id, secret) = text.split_once(':')?; + Some((super::percent_decode(id)?, super::percent_decode(secret)?)) + }); + Some(parsed.ok_or(())) +} + +/// Authenticates the client. The outer `Result` is a server failure; the inner one is either the client +/// or the response that refuses the request. +async fn authenticate( + app: &AppState, + authorization: Option<&str>, + pairs: &Pairs, +) -> Result> { + let basic = match authorization.and_then(basic_credentials) { + Some(Ok(credentials)) => Some(credentials), + Some(Err(())) => return Ok(Err(invalid_client())), + None => None, + }; + let form_id = single(pairs, "client_id"); + let form_secret = single(pairs, "client_secret"); + if form_id == Single::Repeated || form_secret == Single::Repeated { + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); + } + let (client_id, secret) = match basic { + Some((id, secret)) => { + // Two methods at once are refused, and so is a body id that names another client. + if matches!(form_secret, Single::One(_)) + || matches!(form_id, Single::One(other) if other != id) + { + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); + } + (id, secret) + } + None => match (form_id, form_secret) { + (Single::One(id), Single::One(secret)) => (id.to_owned(), secret.to_owned()), + _ => return Ok(Err(invalid_client())), + }, + }; + let client = app.store.client_by_id(&client_id).await?; + // The hash is computed even for an unknown client, so the time does not reveal it. + let presented = hash_token(&secret); + let secret_ok = client + .as_ref() + .is_some_and(|known| constant_time_eq(presented.as_bytes(), known.secret_hash.as_bytes())); + match client { + Some(client) if secret_ok && !client.is_disabled() => Ok(Ok(client)), + _ => Ok(Err(invalid_client())), + } +} + +/// The authorization-code grant (contracts section 2.3, step 3). +async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result { + let (Some(code), Some(redirect_uri), Some(verifier)) = ( + one(pairs, "code"), + one(pairs, "redirect_uri"), + one(pairs, "code_verifier"), + ) else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + }; + let code_hash = hash_token(code); + let Some(row) = app.store.auth_code(&code_hash).await? else { + return Ok(invalid_grant()); + }; + // A code belongs to one client. A wrong client is refused without touching the code. + if row.client_id != client.id { + return Ok(invalid_grant()); + } + if row.used_at.is_some() { + // The code was exchanged before. Whoever holds the tokens made from it must lose them. + app.store.revoke_code_refresh_tokens(&code_hash).await?; + return Ok(invalid_grant()); + } + let pkce_ok = is_valid_verifier(verifier) + && constant_time_eq( + pkce_s256(verifier).as_bytes(), + row.code_challenge.as_bytes(), + ); + if !pkce_ok || row.redirect_uri != redirect_uri || row.expires_at <= now_stamp() { + return Ok(invalid_grant()); + } + let Some(session) = app.store.live_session(&row.session_id).await? else { + return Ok(invalid_grant()); + }; + let Some(user) = app + .store + .user_by_id(&row.user_id) + .await? + .filter(|u| !u.is_disabled()) + else { + return Ok(invalid_grant()); + }; + + let refresh = generate_token(); + let refresh_id = new_id(); + let refresh_expires = stamp_after(REFRESH_TTL); + let first = NewRefreshToken { + id: &refresh_id, + token_hash: &hash_token(&refresh), + family_id: &refresh_id, + client_id: &client.id, + user_id: &user.id, + session_id: &session.id, + code_hash: Some(&code_hash), + scope: &row.scope, + expires_at: &refresh_expires, + }; + if !app.store.redeem_auth_code(&code_hash, &first).await? { + // A parallel exchange of the same code won the race: that is a reuse. + app.store.revoke_code_refresh_tokens(&code_hash).await?; + return Ok(invalid_grant()); + } + + let id_token = id_token( + app, + &user, + client, + &session, + &row.scope, + row.nonce.as_deref(), + ) + .await?; + let access_token = access_token(app, &user, client, &session, &row.scope).await?; + Ok(token_response( + access_token, + &row.scope, + Some(id_token), + Some(refresh), + )) +} + +/// The refresh-token grant (contracts section 2.3, refresh): rotates the token and issues a new access +/// token. No ID token is issued here: a refresh carries no nonce. +async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result { + let Some(presented) = one(pairs, "refresh_token") else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + }; + let Some(row) = app.store.refresh_token(&hash_token(presented)).await? else { + return Ok(invalid_grant()); + }; + if row.client_id != client.id { + return Ok(invalid_grant()); + } + if row.used_at.is_some() { + // A rotated token came back. Either the holder or someone who copied it is replaying it: + // the whole chain is revoked, so both lose it. + app.store.revoke_refresh_family(&row.family_id).await?; + return Ok(invalid_grant()); + } + if row.revoked_at.is_some() || row.expires_at <= now_stamp() { + return Ok(invalid_grant()); + } + // A chain ends with its session, and with the user's account when that is disabled. + let Some(session) = app.store.live_session(&row.session_id).await? else { + return Ok(invalid_grant()); + }; + let Some(user) = app + .store + .user_by_id(&row.user_id) + .await? + .filter(|u| !u.is_disabled()) + else { + return Ok(invalid_grant()); + }; + + let refresh = generate_token(); + let refresh_id = new_id(); + let refresh_expires = stamp_after(REFRESH_TTL); + let next = NewRefreshToken { + id: &refresh_id, + token_hash: &hash_token(&refresh), + family_id: &row.family_id, + client_id: &client.id, + user_id: &user.id, + session_id: &session.id, + code_hash: row.code_hash.as_deref(), + scope: &row.scope, + expires_at: &refresh_expires, + }; + if !app.store.rotate_refresh_token(&row.id, &next).await? { + // A parallel refresh with the same token won the race: that is a reuse. + app.store.revoke_refresh_family(&row.family_id).await?; + return Ok(invalid_grant()); + } + let access_token = access_token(app, &user, client, &session, &row.scope).await?; + Ok(token_response( + access_token, + &row.scope, + None, + Some(refresh), + )) +} + +/// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires. +fn token_response( + access_token: String, + scope: &str, + id_token: Option, + refresh_token: Option, +) -> Response { + let mut body = json!({ + "access_token": access_token, + "token_type": "Bearer", + "expires_in": ACCESS_TTL.as_secs(), + "scope": scope, + }); + if let (Some(object), Some(id_token)) = (body.as_object_mut(), id_token) { + object.insert("id_token".into(), Value::String(id_token)); + } + if let (Some(object), Some(refresh)) = (body.as_object_mut(), refresh_token) { + object.insert("refresh_token".into(), Value::String(refresh)); + } + json_response(StatusCode::OK, &body) +} + +/// The claims about the person that a scope grants. `email` gates the address; `profile` gates the +/// name, the language, the time zone, the administrator flag and the picture version (contracts 2.3). +pub fn person_claims(user: &User, scope: &str) -> Map { + let granted = |name: &str| scope.split_whitespace().any(|word| word == name); + let mut claims = Map::new(); + if granted("email") { + claims.insert("email".into(), json!(user.email)); + // Only confirmed addresses are stored, so the flag is always true. + claims.insert("email_verified".into(), json!(true)); + } + if granted("profile") { + claims.insert("name".into(), json!(user.name)); + claims.insert("admin".into(), json!(user.is_admin)); + claims.insert("locale".into(), json!(user.locale)); + claims.insert("zoneinfo".into(), json!(user.zoneinfo)); + claims.insert("picture_version".into(), json!(user.picture_version)); + } + claims +} + +/// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to +/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. +async fn access_token( + app: &AppState, + user: &User, + client: &Client, + session: &Session, + scope: &str, +) -> im_core::Result { + let now = im_core::time::unix_now(); + let claims = json!({ + "iss": issuer(app), + "sub": user.id, + "aud": USERINFO_AUDIENCE, + "azp": client.id, + "scope": scope, + "sid": session.id, + "iat": now, + "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), + "jti": generate_token(), + }); + signing::sign(&app.store, &app.key, &claims).await +} + +/// The ID token (OIDC Core section 2): who signed in, when and how, for which client and nonce. +async fn id_token( + app: &AppState, + user: &User, + client: &Client, + session: &Session, + scope: &str, + nonce: Option<&str>, +) -> im_core::Result { + let now = im_core::time::unix_now(); + let mut claims = json!({ + "iss": issuer(app), + "sub": user.id, + "aud": client.id, + "iat": now, + "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), + "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), + "sid": session.id, + "amr": session.amr.split(' ').collect::>(), + }); + if let Some(object) = claims.as_object_mut() { + if let Some(nonce) = nonce { + object.insert("nonce".into(), json!(nonce)); + } + object.extend(person_claims(user, scope)); + } + signing::sign(&app.store, &app.key, &claims).await +} diff --git a/crates/im-web/src/oidc/userinfo.rs b/crates/im-web/src/oidc/userinfo.rs new file mode 100644 index 0000000..c1b2de7 --- /dev/null +++ b/crates/im-web/src/oidc/userinfo.rs @@ -0,0 +1,93 @@ +//! `GET` and `POST /userinfo` (OpenID Connect Core section 5.3): the claims of the person a user access +//! token was issued for. +//! +//! The token is verified against this provider's own published keys: signature, `iss`, `aud` (this +//! provider), `exp` and `iat`, and the `openid` scope. The token is then checked against the session it +//! names: a session that ended, or a disabled account, refuses the token at once, even before it expires. + +use http::header::{AUTHORIZATION, CACHE_CONTROL, HeaderValue, WWW_AUTHENTICATE}; +use im_core::jwt::{self, PublishedKey}; +use im_core::time::unix_now; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{StatusCode, route}; + +use super::signing; +use super::token::person_claims; +use super::{USERINFO_AUDIENCE, issuer, json_response}; +use crate::state::AppState; + +/// `GET /userinfo` and `POST /userinfo`, both with a Bearer token. +#[route([GET, POST] "/userinfo")] +async fn userinfo(cx: &Cx) -> Result { + let app = app_context::(cx); + let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else { + return Ok(unauthorized()); + }; + let published = signing::published_keys(&app.store).await?; + let keys: Vec = published + .iter() + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) + .collect(); + let Ok(claims) = jwt::verify(&keys, token) else { + return Ok(unauthorized()); + }; + let now = unix_now(); + if jwt::check_claims(&claims, issuer(app), USERINFO_AUDIENCE, now).is_err() { + return Ok(unauthorized()); + } + let scope = claims + .get("scope") + .and_then(Value::as_str) + .unwrap_or_default(); + if !scope.split_whitespace().any(|word| word == "openid") { + return Ok(unauthorized()); + } + let (Some(sub), Some(sid)) = ( + claims.get("sub").and_then(Value::as_str), + claims.get("sid").and_then(Value::as_str), + ) else { + return Ok(unauthorized()); + }; + let Some(session) = app.store.live_session(sid).await? else { + return Ok(unauthorized()); + }; + let Some(user) = app + .store + .user_by_id(sub) + .await? + .filter(|u| !u.is_disabled()) + else { + return Ok(unauthorized()); + }; + if session.user_id != user.id { + return Ok(unauthorized()); + } + + let mut body = person_claims(&user, scope); + body.insert("sub".into(), json!(user.id)); + let mut response = json_response(StatusCode::OK, &Value::Object(body)); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + Ok(response) +} + +/// The token of a `Bearer` authorization header, or `None`. +fn bearer(value: Option<&HeaderValue>) -> Option<&str> { + let (scheme, token) = value?.to_str().ok()?.split_once(' ')?; + (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) +} + +/// `401 invalid_token` with the RFC 6750 challenge. One answer for every reason. +fn unauthorized() -> Response { + let mut response = json_response(StatusCode::UNAUTHORIZED, &json!({"error": "invalid_token"})); + response.headers_mut().insert( + WWW_AUTHENTICATE, + HeaderValue::from_static("Bearer error=\"invalid_token\""), + ); + response +} diff --git a/crates/im-web/src/security.rs b/crates/im-web/src/security.rs index f31f8b9..1f05632 100644 --- a/crates/im-web/src/security.rs +++ b/crates/im-web/src/security.rs @@ -58,6 +58,9 @@ pub enum Answer { Asset, /// A profile photo under `/photo/`, with its own cache policy and its own CSP. Photo, + /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler + /// sets the short cache policy. + Public, /// Everything else: pages, forms, streams. Never stored. Page, } @@ -68,6 +71,8 @@ pub fn answer_for(path: &str) -> Answer { Answer::Asset } else if path.starts_with("/photo/") { Answer::Photo + } else if path == "/.well-known/openid-configuration" || path == "/jwks.json" { + Answer::Public } else { Answer::Page } @@ -105,7 +110,7 @@ impl Layer for SecurityHeaders { let answer = answer_for(uri(cx).path()); let mut headers = match answer { Answer::Photo => self.photo_headers.clone(), - Answer::Asset | Answer::Page => self.headers.clone(), + Answer::Asset | Answer::Public | Answer::Page => self.headers.clone(), }; if answer == Answer::Page { headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); @@ -127,6 +132,7 @@ mod tests { assert_eq!(answer_for("/setup"), Answer::Page); assert_eq!(answer_for("/photo/01HZ"), Answer::Photo); assert_eq!(answer_for("/assets/main.css"), Answer::Asset); + assert_eq!(answer_for("/jwks.json"), Answer::Public); // A prefix match on the segment only: a page whose name starts the same is still a page. assert_eq!(answer_for("/photographs"), Answer::Page); }