OIDC provider part 1: signing keys, discovery, JWKS, clients CLI, authorize, token, userinfo
Browse files at this commit088ace7a4e6860aac8a8eb4d8527597db337de63Parent: c829fac- feat
- OIDC provider part 1: signing keys, discovery, JWKS, clients CLI, authorize, token, userinfo
24 changed files +2811 -7
- crates/im-core/src/jwt.rs +197 -0
- crates/im-core/src/keys.rs +143 -0
- crates/im-core/src/lib.rs +3 -0
- crates/im-core/src/model.rs +110 -0
- crates/im-core/src/oauth.rs +140 -0
- crates/im-core/src/store/clients.rs +135 -0
- crates/im-core/src/store/keys.rs +86 -0
- crates/im-core/src/store/mod.rs +4 -1
- crates/im-core/src/store/oidc.rs +271 -0
- crates/im-core/src/store/sessions.rs +17 -0
- crates/im-core/src/time.rs +31 -0
- crates/im-web/src/boot.rs +7 -2
- crates/im-web/src/cli.rs +253 -0
- crates/im-web/src/i18n/mod.rs +1 -0
- crates/im-web/src/i18n/oidc.rs +28 -0
- crates/im-web/src/main.rs +6 -3
- crates/im-web/src/oidc/authorize.rs +238 -0
- crates/im-web/src/oidc/discovery.rs +80 -0
- crates/im-web/src/oidc/mod.rs +172 -0
- crates/im-web/src/oidc/signing.rs +96 -0
- crates/im-web/src/oidc/tests.rs +317 -0
- crates/im-web/src/oidc/token.rs +376 -0
- crates/im-web/src/oidc/userinfo.rs +93 -0
- crates/im-web/src/security.rs +7 -1
crates/im-core/src/jwt.rsadded+197 -0
| @@ -0,0 +1,197 @@ | |||
| 1 | +//! EdDSA (Ed25519) JSON Web Tokens: signing, verification, claim checks and the public key format. | ||
| 2 | +//! | ||
| 3 | +//! The header is `{"alg":"EdDSA","typ":"JWT","kid":...}`. Verification reads the algorithm first and | ||
| 4 | +//! accepts only `EdDSA`, so `none` and every other algorithm fail before any key is used. The key is | ||
| 5 | +//! chosen by `kid` from the keys that are published; an unknown `kid` is refused. Claim checks are a | ||
| 6 | +//! separate call, so each caller states its own issuer and audience. | ||
| 7 | + | ||
| 8 | +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 9 | +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; | ||
| 10 | +use serde_json::{Map, Value, json}; | ||
| 11 | + | ||
| 12 | +/// The only algorithm this provider signs or accepts. | ||
| 13 | +pub const ALG: &str = "EdDSA"; | ||
| 14 | + | ||
| 15 | +/// How far an `iat` may lie in the future, in seconds (contracts section 2.3: five minutes). | ||
| 16 | +pub const MAX_FUTURE_IAT_SECS: i64 = 300; | ||
| 17 | + | ||
| 18 | +/// Why a token was refused. Only the web layer sees these; the client gets one generic answer. | ||
| 19 | +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] | ||
| 20 | +pub enum JwtError { | ||
| 21 | + /// The token does not have three parts, or a part is not valid base64url JSON. | ||
| 22 | + #[error("the token is malformed")] | ||
| 23 | + Malformed, | ||
| 24 | + /// The header names an algorithm other than EdDSA. | ||
| 25 | + #[error("the algorithm is not EdDSA")] | ||
| 26 | + Algorithm, | ||
| 27 | + /// The `kid` is missing or not published. | ||
| 28 | + #[error("the key id is not published")] | ||
| 29 | + UnknownKey, | ||
| 30 | + /// The signature does not verify with the key. | ||
| 31 | + #[error("the signature does not verify")] | ||
| 32 | + Signature, | ||
| 33 | + /// A claim is missing, has the wrong type or has a wrong value. | ||
| 34 | + #[error("the claim {0} is missing or wrong")] | ||
| 35 | + Claim(&'static str), | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// A public key that may verify tokens, under its `kid`. | ||
| 39 | +pub struct PublishedKey { | ||
| 40 | + kid: String, | ||
| 41 | + key: VerifyingKey, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +impl PublishedKey { | ||
| 45 | + /// A verifying key from its `kid` and its 32 raw public bytes. `None` for bytes that are not a key. | ||
| 46 | + pub fn new(kid: String, public: &[u8]) -> Option<Self> { | ||
| 47 | + let raw: [u8; 32] = public.try_into().ok()?; | ||
| 48 | + VerifyingKey::from_bytes(&raw) | ||
| 49 | + .ok() | ||
| 50 | + .map(|key| PublishedKey { kid, key }) | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// Signs `claims` (a JSON object) with `key`, and puts `kid` in the header. | ||
| 55 | +pub fn sign(key: &SigningKey, kid: &str, claims: &Value) -> String { | ||
| 56 | + let header = json!({"alg": ALG, "typ": "JWT", "kid": kid}); | ||
| 57 | + let signing_input = format!("{}.{}", encode_json(&header), encode_json(claims)); | ||
| 58 | + let signature: Signature = key.sign(signing_input.as_bytes()); | ||
| 59 | + format!( | ||
| 60 | + "{signing_input}.{}", | ||
| 61 | + BASE64_URL_SAFE_NO_PAD.encode(signature.to_bytes()) | ||
| 62 | + ) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// Signs `claims` with the key whose 32-byte seed is `seed`. The seed is the sealed form of the key | ||
| 66 | +/// (`keys::generate`), opened for the one call. | ||
| 67 | +pub fn sign_with_seed(seed: &[u8; 32], kid: &str, claims: &Value) -> String { | ||
| 68 | + sign(&SigningKey::from_bytes(seed), kid, claims) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// Verifies a token against the published keys and returns its claims. The algorithm, the `kid`, and | ||
| 72 | +/// the signature are checked; the time and the issuer are not (see [`check_claims`]). | ||
| 73 | +pub fn verify(keys: &[PublishedKey], token: &str) -> Result<Map<String, Value>, JwtError> { | ||
| 74 | + let mut parts = token.split('.'); | ||
| 75 | + let (Some(header), Some(payload), Some(signature), None) = | ||
| 76 | + (parts.next(), parts.next(), parts.next(), parts.next()) | ||
| 77 | + else { | ||
| 78 | + return Err(JwtError::Malformed); | ||
| 79 | + }; | ||
| 80 | + let header = decode_object(header)?; | ||
| 81 | + if header.get("alg").and_then(Value::as_str) != Some(ALG) { | ||
| 82 | + return Err(JwtError::Algorithm); | ||
| 83 | + } | ||
| 84 | + let kid = header | ||
| 85 | + .get("kid") | ||
| 86 | + .and_then(Value::as_str) | ||
| 87 | + .ok_or(JwtError::UnknownKey)?; | ||
| 88 | + let key = keys | ||
| 89 | + .iter() | ||
| 90 | + .find(|known| known.kid == kid) | ||
| 91 | + .ok_or(JwtError::UnknownKey)?; | ||
| 92 | + let raw = BASE64_URL_SAFE_NO_PAD | ||
| 93 | + .decode(signature) | ||
| 94 | + .map_err(|_| JwtError::Malformed)?; | ||
| 95 | + let raw: [u8; 64] = raw.try_into().map_err(|_| JwtError::Malformed)?; | ||
| 96 | + let signature = Signature::from_bytes(&raw); | ||
| 97 | + let signing_input = format!( | ||
| 98 | + "{}.{}", | ||
| 99 | + token.split('.').next().unwrap_or_default(), | ||
| 100 | + payload | ||
| 101 | + ); | ||
| 102 | + key.key | ||
| 103 | + .verify_strict(signing_input.as_bytes(), &signature) | ||
| 104 | + .map_err(|_| JwtError::Signature)?; | ||
| 105 | + decode_object(payload) | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// Checks the registered claims: `iss` equals `issuer` exactly, `aud` is `audience` (a string, or an | ||
| 109 | +/// array holding only that string), `exp` is in the future, and `iat` is at most five minutes ahead. | ||
| 110 | +pub fn check_claims( | ||
| 111 | + claims: &Map<String, Value>, | ||
| 112 | + issuer: &str, | ||
| 113 | + audience: &str, | ||
| 114 | + now: i64, | ||
| 115 | +) -> Result<(), JwtError> { | ||
| 116 | + if claims.get("iss").and_then(Value::as_str) != Some(issuer) { | ||
| 117 | + return Err(JwtError::Claim("iss")); | ||
| 118 | + } | ||
| 119 | + if !audience_is(claims.get("aud"), audience) { | ||
| 120 | + return Err(JwtError::Claim("aud")); | ||
| 121 | + } | ||
| 122 | + let exp = claims | ||
| 123 | + .get("exp") | ||
| 124 | + .and_then(Value::as_i64) | ||
| 125 | + .ok_or(JwtError::Claim("exp"))?; | ||
| 126 | + if exp <= now { | ||
| 127 | + return Err(JwtError::Claim("exp")); | ||
| 128 | + } | ||
| 129 | + let iat = claims | ||
| 130 | + .get("iat") | ||
| 131 | + .and_then(Value::as_i64) | ||
| 132 | + .ok_or(JwtError::Claim("iat"))?; | ||
| 133 | + if iat > now + MAX_FUTURE_IAT_SECS { | ||
| 134 | + return Err(JwtError::Claim("iat")); | ||
| 135 | + } | ||
| 136 | + Ok(()) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +fn audience_is(aud: Option<&Value>, expected: &str) -> bool { | ||
| 140 | + match aud { | ||
| 141 | + Some(Value::String(one)) => one == expected, | ||
| 142 | + Some(Value::Array(list)) => list.len() == 1 && list[0].as_str() == Some(expected), | ||
| 143 | + _ => false, | ||
| 144 | + } | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/// One public key as a JWK (RFC 8037), for the JWKS document. | ||
| 148 | +pub fn jwk(kid: &str, public: &[u8]) -> Value { | ||
| 149 | + json!({ | ||
| 150 | + "kty": "OKP", | ||
| 151 | + "crv": "Ed25519", | ||
| 152 | + "x": BASE64_URL_SAFE_NO_PAD.encode(public), | ||
| 153 | + "kid": kid, | ||
| 154 | + "use": "sig", | ||
| 155 | + "alg": ALG, | ||
| 156 | + }) | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +fn encode_json(value: &Value) -> String { | ||
| 160 | + BASE64_URL_SAFE_NO_PAD.encode(value.to_string()) | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +fn decode_object(segment: &str) -> Result<Map<String, Value>, JwtError> { | ||
| 164 | + let bytes = BASE64_URL_SAFE_NO_PAD | ||
| 165 | + .decode(segment) | ||
| 166 | + .map_err(|_| JwtError::Malformed)?; | ||
| 167 | + match serde_json::from_slice(&bytes) { | ||
| 168 | + Ok(Value::Object(map)) => Ok(map), | ||
| 169 | + _ => Err(JwtError::Malformed), | ||
| 170 | + } | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +#[cfg(test)] | ||
| 174 | +mod tests { | ||
| 175 | + use super::*; | ||
| 176 | + | ||
| 177 | + #[test] | ||
| 178 | + fn a_signed_token_verifies_and_a_tampered_one_does_not() { | ||
| 179 | + let key = SigningKey::from_bytes(&[9u8; 32]); | ||
| 180 | + let public = key.verifying_key().to_bytes(); | ||
| 181 | + let keys = vec![PublishedKey::new("k1".into(), &public).expect("key")]; | ||
| 182 | + let token = sign(&key, "k1", &json!({"iss": "https://im.test", "aud": "im"})); | ||
| 183 | + assert!(verify(&keys, &token).is_ok()); | ||
| 184 | + | ||
| 185 | + let forged = json!({"iss": "https://im.test", "aud": "admin"}); | ||
| 186 | + let mut parts: Vec<&str> = token.split('.').collect(); | ||
| 187 | + let forged_part = BASE64_URL_SAFE_NO_PAD.encode(forged.to_string()); | ||
| 188 | + parts[1] = &forged_part; | ||
| 189 | + assert_eq!(verify(&keys, &parts.join(".")), Err(JwtError::Signature)); | ||
| 190 | + let none = format!( | ||
| 191 | + "{}.{}.", | ||
| 192 | + BASE64_URL_SAFE_NO_PAD.encode(r#"{"alg":"none","kid":"k1"}"#), | ||
| 193 | + BASE64_URL_SAFE_NO_PAD.encode("{}") | ||
| 194 | + ); | ||
| 195 | + assert_eq!(verify(&keys, &none), Err(JwtError::Algorithm)); | ||
| 196 | + } | ||
| 197 | +} | ||
crates/im-core/src/keys.rsadded+143 -0
| @@ -0,0 +1,143 @@ | |||
| 1 | +//! Token-signing keys: how a key is made, which key signs now, which keys are published, and when the | ||
| 2 | +//! next key is due. | ||
| 3 | +//! | ||
| 4 | +//! The chain (contracts section 2.2, architecture section 8): a key is created at least 24 hours before | ||
| 5 | +//! it signs, so it is published first. A key signs for 90 days. When its successor is created, it is | ||
| 6 | +//! retired at the successor's activation time, and it stays published for 7 more days, so tokens it | ||
| 7 | +//! signed before then still verify. Every instant here is a stored stamp; the comparisons are text. | ||
| 8 | + | ||
| 9 | +use std::time::Duration; | ||
| 10 | + | ||
| 11 | +use ed25519_dalek::SigningKey; | ||
| 12 | + | ||
| 13 | +use crate::model::KeyRecord; | ||
| 14 | +use crate::time::{stamp_minus, stamp_plus}; | ||
| 15 | + | ||
| 16 | +const DAY: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 17 | + | ||
| 18 | +/// How long a key signs before its successor takes over. | ||
| 19 | +pub const ROTATION_PERIOD: Duration = Duration::from_secs(90 * 24 * 60 * 60); | ||
| 20 | + | ||
| 21 | +/// How long before it signs a new key is created and published. | ||
| 22 | +pub const PUBLISH_LEAD: Duration = DAY; | ||
| 23 | + | ||
| 24 | +/// How long a retired key stays published after its retirement. | ||
| 25 | +pub const OVERLAP: Duration = Duration::from_secs(7 * 24 * 60 * 60); | ||
| 26 | + | ||
| 27 | +/// A freshly generated key: its id, its seed (the private key) and its public key. | ||
| 28 | +pub struct FreshKey { | ||
| 29 | + /// Random key id, 32 hex characters. | ||
| 30 | + pub kid: String, | ||
| 31 | + /// The 32-byte Ed25519 seed. Seal it before storing. | ||
| 32 | + pub seed: [u8; 32], | ||
| 33 | + /// The 32-byte public key. | ||
| 34 | + pub public: [u8; 32], | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// Generates a new Ed25519 key with a random seed and a random `kid`. | ||
| 38 | +pub fn generate() -> FreshKey { | ||
| 39 | + let mut seed = [0u8; 32]; | ||
| 40 | + rand::fill(&mut seed); | ||
| 41 | + let public = SigningKey::from_bytes(&seed).verifying_key().to_bytes(); | ||
| 42 | + let mut id = [0u8; 16]; | ||
| 43 | + rand::fill(&mut id); | ||
| 44 | + FreshKey { | ||
| 45 | + kid: hex::encode(id), | ||
| 46 | + seed, | ||
| 47 | + public, | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// The key that signs at `now`: the newest one whose activation has come and that is not yet retired. | ||
| 52 | +pub fn current<'a>(keys: &'a [KeyRecord], now: &str) -> Option<&'a KeyRecord> { | ||
| 53 | + keys.iter() | ||
| 54 | + .filter(|key| { | ||
| 55 | + key.activates_at.as_str() <= now | ||
| 56 | + && key | ||
| 57 | + .retires_at | ||
| 58 | + .as_deref() | ||
| 59 | + .is_none_or(|retired| retired > now) | ||
| 60 | + }) | ||
| 61 | + .max_by(|a, b| a.activates_at.cmp(&b.activates_at)) | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// The keys published at `now`: every key not retired, and every key retired less than [`OVERLAP`] ago. | ||
| 65 | +pub fn published<'a>(keys: &'a [KeyRecord], now: &str) -> Vec<&'a KeyRecord> { | ||
| 66 | + let cutoff = stamp_minus(now, OVERLAP).unwrap_or_else(|| now.to_owned()); | ||
| 67 | + keys.iter() | ||
| 68 | + .filter(|key| { | ||
| 69 | + key.retires_at | ||
| 70 | + .as_deref() | ||
| 71 | + .is_none_or(|retired| retired > cutoff.as_str()) | ||
| 72 | + }) | ||
| 73 | + .collect() | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Whether a new key must be created at `now`, and if so when it activates. `None` means the chain is | ||
| 77 | +/// fine: a key is pending, or the current one is not due within the publish lead. | ||
| 78 | +/// | ||
| 79 | +/// With no key at all, the new key activates at once. Otherwise it activates [`PUBLISH_LEAD`] from now, | ||
| 80 | +/// which is the first moment it can be published, and the newest key is retired at that same instant. | ||
| 81 | +pub fn next_activation(keys: &[KeyRecord], now: &str) -> Option<String> { | ||
| 82 | + let head = keys | ||
| 83 | + .iter() | ||
| 84 | + .filter(|key| key.retires_at.is_none()) | ||
| 85 | + .max_by(|a, b| a.activates_at.cmp(&b.activates_at)); | ||
| 86 | + let Some(head) = head else { | ||
| 87 | + return Some(now.to_owned()); | ||
| 88 | + }; | ||
| 89 | + if head.activates_at.as_str() > now { | ||
| 90 | + return None; | ||
| 91 | + } | ||
| 92 | + let activates_at = stamp_plus(now, PUBLISH_LEAD)?; | ||
| 93 | + let due = stamp_plus(&head.activates_at, ROTATION_PERIOD)?; | ||
| 94 | + (activates_at >= due).then_some(activates_at) | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +#[cfg(test)] | ||
| 98 | +mod tests { | ||
| 99 | + use super::*; | ||
| 100 | + | ||
| 101 | + fn key(kid: &str, activates_at: &str, retires_at: Option<&str>) -> KeyRecord { | ||
| 102 | + KeyRecord { | ||
| 103 | + kid: kid.into(), | ||
| 104 | + private_sealed: String::new(), | ||
| 105 | + public_raw: vec![0; 32], | ||
| 106 | + created_at: activates_at.into(), | ||
| 107 | + activates_at: activates_at.into(), | ||
| 108 | + retires_at: retires_at.map(str::to_owned), | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + #[test] | ||
| 113 | + fn the_chain_creates_its_successor_a_day_ahead_and_retires_the_old_key_then() { | ||
| 114 | + let now = "2026-10-28T00:00:00.000000000Z"; | ||
| 115 | + assert_eq!(next_activation(&[], now).as_deref(), Some(now)); | ||
| 116 | + | ||
| 117 | + let first = key("a", now, None); | ||
| 118 | + // Far from due: nothing to do. | ||
| 119 | + assert_eq!(next_activation(std::slice::from_ref(&first), now), None); | ||
| 120 | + // Due within the lead: the successor activates one day from now. | ||
| 121 | + let due_soon = "2027-01-25T12:00:00.000000000Z"; | ||
| 122 | + assert_eq!( | ||
| 123 | + next_activation(std::slice::from_ref(&first), due_soon).as_deref(), | ||
| 124 | + Some("2027-01-26T12:00:00.000000000Z") | ||
| 125 | + ); | ||
| 126 | + | ||
| 127 | + let retired = key("a", now, Some("2027-01-26T12:00:00.000000000Z")); | ||
| 128 | + let successor = key("b", "2027-01-26T12:00:00.000000000Z", None); | ||
| 129 | + let rows = [retired.clone(), successor.clone()]; | ||
| 130 | + // Before the handover the old key still signs; after it the successor does. | ||
| 131 | + assert_eq!( | ||
| 132 | + current(&rows, "2027-01-26T11:59:59.000000000Z").map(|k| k.kid.as_str()), | ||
| 133 | + Some("a") | ||
| 134 | + ); | ||
| 135 | + assert_eq!( | ||
| 136 | + current(&rows, "2027-01-26T12:00:00.000000000Z").map(|k| k.kid.as_str()), | ||
| 137 | + Some("b") | ||
| 138 | + ); | ||
| 139 | + // Both stay published across the overlap, and the retired one drops out after seven days. | ||
| 140 | + assert_eq!(published(&rows, "2027-01-30T00:00:00.000000000Z").len(), 2); | ||
| 141 | + assert_eq!(published(&rows, "2027-02-03T12:00:00.000000000Z").len(), 1); | ||
| 142 | + } | ||
| 143 | +} | ||
crates/im-core/src/lib.rsmodified+3 -0
| @@ -5,8 +5,11 @@ | |||
| 5 | 5 | ||
| 6 | pub mod config; | 6 | pub mod config; |
| 7 | pub mod error; | 7 | pub mod error; |
| 8 | +pub mod jwt; | ||
| 9 | +pub mod keys; | ||
| 8 | pub mod model; | 10 | pub mod model; |
| 9 | pub mod names; | 11 | pub mod names; |
| 12 | +pub mod oauth; | ||
| 10 | pub mod password; | 13 | pub mod password; |
| 11 | pub mod photo; | 14 | pub mod photo; |
| 12 | pub mod secret; | 15 | pub mod secret; |
crates/im-core/src/model.rsmodified+110 -0
| @@ -175,3 +175,113 @@ pub struct AuditEntry { | |||
| 175 | /// JSON with extra detail. Never holds a secret. | 175 | /// JSON with extra detail. Never holds a secret. |
| 176 | pub data: Option<String>, | 176 | pub data: Option<String>, |
| 177 | } | 177 | } |
| 178 | + | ||
| 179 | +/// An OpenID Connect client: one family app, or another client that asks for tokens. | ||
| 180 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 181 | +pub struct Client { | ||
| 182 | + /// ULID. This is the `client_id`. | ||
| 183 | + pub id: String, | ||
| 184 | + /// Display name, shown by the admin pages and the CLI. | ||
| 185 | + pub name: String, | ||
| 186 | + /// Hex SHA-256 of the client secret. The secret itself is shown once, at creation. | ||
| 187 | + pub secret_hash: String, | ||
| 188 | + /// When the secret was last issued. | ||
| 189 | + pub secret_rotated_at: String, | ||
| 190 | + /// Exact redirect URIs. A request matches only a string equal to one of them. | ||
| 191 | + pub redirect_uris: Vec<String>, | ||
| 192 | + /// Exact post-logout redirect URIs (used by RP-initiated logout). | ||
| 193 | + pub post_logout_redirect_uris: Vec<String>, | ||
| 194 | + /// Back-channel logout endpoint of the client, when it has one. | ||
| 195 | + pub backchannel_logout_uri: Option<String>, | ||
| 196 | + /// Space-separated scopes the client may ask for. | ||
| 197 | + pub allowed_scopes: String, | ||
| 198 | + /// Family key such as `in`, when the client is a family service. | ||
| 199 | + pub service_key: Option<String>, | ||
| 200 | + /// Creation time. | ||
| 201 | + pub created_at: String, | ||
| 202 | + /// Set when the client is disabled. A disabled client authenticates nowhere. | ||
| 203 | + pub disabled_at: Option<String>, | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +impl Client { | ||
| 207 | + /// True when the client is disabled. | ||
| 208 | + pub fn is_disabled(&self) -> bool { | ||
| 209 | + self.disabled_at.is_some() | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + /// True when the client may ask for `scope`. | ||
| 213 | + pub fn allows_scope(&self, scope: &str) -> bool { | ||
| 214 | + self.allowed_scopes.split_whitespace().any(|s| s == scope) | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// An authorization code row. Only the hash of the code is stored. | ||
| 219 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 220 | +pub struct AuthCode { | ||
| 221 | + /// Hex SHA-256 of the code. | ||
| 222 | + pub code_hash: String, | ||
| 223 | + /// The client the code was issued to. | ||
| 224 | + pub client_id: String, | ||
| 225 | + /// The person who signed in. | ||
| 226 | + pub user_id: String, | ||
| 227 | + /// The browser session the code was issued in. Its time and method go into the tokens. | ||
| 228 | + pub session_id: String, | ||
| 229 | + /// The redirect URI of the request, which the exchange must repeat. | ||
| 230 | + pub redirect_uri: String, | ||
| 231 | + /// The granted scope. | ||
| 232 | + pub scope: String, | ||
| 233 | + /// The nonce of the request, when there was one. | ||
| 234 | + pub nonce: Option<String>, | ||
| 235 | + /// The PKCE challenge (S256) of the request. | ||
| 236 | + pub code_challenge: String, | ||
| 237 | + /// When the code stops being usable. | ||
| 238 | + pub expires_at: String, | ||
| 239 | + /// Set when the code was exchanged. A code is exchanged once. | ||
| 240 | + pub used_at: Option<String>, | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +/// A refresh token row. Only the hash of the token is stored. | ||
| 244 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 245 | +pub struct RefreshToken { | ||
| 246 | + /// ULID. | ||
| 247 | + pub id: String, | ||
| 248 | + /// Hex SHA-256 of the token. | ||
| 249 | + pub token_hash: String, | ||
| 250 | + /// The first token of the chain. Reuse revokes every token with this family id. | ||
| 251 | + pub family_id: String, | ||
| 252 | + /// The client the token was issued to. | ||
| 253 | + pub client_id: String, | ||
| 254 | + /// The person. | ||
| 255 | + pub user_id: String, | ||
| 256 | + /// The browser session the chain belongs to. | ||
| 257 | + pub session_id: String, | ||
| 258 | + /// Hash of the authorization code the chain began with, when it began with one. | ||
| 259 | + pub code_hash: Option<String>, | ||
| 260 | + /// The granted scope. | ||
| 261 | + pub scope: String, | ||
| 262 | + /// Creation time. | ||
| 263 | + pub created_at: String, | ||
| 264 | + /// Expiry. | ||
| 265 | + pub expires_at: String, | ||
| 266 | + /// Set when the token was rotated. Presenting a used token is reuse. | ||
| 267 | + pub used_at: Option<String>, | ||
| 268 | + /// Set when the token or its family was revoked. | ||
| 269 | + pub revoked_at: Option<String>, | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// One token-signing key. The private part is sealed under the instance key. | ||
| 273 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 274 | +pub struct KeyRecord { | ||
| 275 | + /// Key id, published in the JWKS and in every token header. | ||
| 276 | + pub kid: String, | ||
| 277 | + /// The 32-byte Ed25519 seed, sealed with `secret::seal`. | ||
| 278 | + pub private_sealed: String, | ||
| 279 | + /// The 32-byte Ed25519 public key. | ||
| 280 | + pub public_raw: Vec<u8>, | ||
| 281 | + /// Creation time. | ||
| 282 | + pub created_at: String, | ||
| 283 | + /// When the key starts signing. Published before this time. | ||
| 284 | + pub activates_at: String, | ||
| 285 | + /// When the key stops signing. It stays published for a while after this time. | ||
| 286 | + pub retires_at: Option<String>, | ||
| 287 | +} | ||
crates/im-core/src/oauth.rsadded+140 -0
| @@ -0,0 +1,140 @@ | |||
| 1 | +//! The OAuth 2.0 and OpenID Connect rules that are pure text: the scope names, the URI rules of | ||
| 2 | +//! registered clients, the family-key format, and PKCE (RFC 7636). | ||
| 3 | +//! | ||
| 4 | +//! Nothing here touches the database or the network. The registration command and the endpoints use | ||
| 5 | +//! the same functions, so a value is accepted or refused the same way everywhere. | ||
| 6 | + | ||
| 7 | +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 8 | +use sha2::{Digest, Sha256}; | ||
| 9 | + | ||
| 10 | +/// Scopes a person grants at sign-in. Every family client is first-party, so there is no consent screen. | ||
| 11 | +pub const USER_SCOPES: [&str; 3] = ["openid", "profile", "email"]; | ||
| 12 | + | ||
| 13 | +/// Every scope the provider advertises (contracts section 2.1). | ||
| 14 | +pub const SUPPORTED_SCOPES: [&str; 5] = [ | ||
| 15 | + "openid", | ||
| 16 | + "profile", | ||
| 17 | + "email", | ||
| 18 | + "directory.read", | ||
| 19 | + "files.service", | ||
| 20 | +]; | ||
| 21 | + | ||
| 22 | +/// The longest `state` or `nonce` accepted, in bytes. Longer values are refused, not truncated. | ||
| 23 | +pub const MAX_ECHO_BYTES: usize = 512; | ||
| 24 | + | ||
| 25 | +/// The longest registered URI, in bytes. | ||
| 26 | +pub const MAX_URI_BYTES: usize = 2048; | ||
| 27 | + | ||
| 28 | +/// True for a scope the provider knows. | ||
| 29 | +pub fn is_supported_scope(scope: &str) -> bool { | ||
| 30 | + SUPPORTED_SCOPES.contains(&scope) | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// True for a scope a person can be granted at sign-in. | ||
| 34 | +pub fn is_user_scope(scope: &str) -> bool { | ||
| 35 | + USER_SCOPES.contains(&scope) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// The S256 code challenge of a verifier: base64url of its SHA-256, without padding. | ||
| 39 | +pub fn pkce_s256(verifier: &str) -> String { | ||
| 40 | + BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// True for a code challenge: exactly 43 base64url characters (32 bytes, unpadded). | ||
| 44 | +pub fn is_valid_challenge(challenge: &str) -> bool { | ||
| 45 | + challenge.len() == 43 | ||
| 46 | + && challenge | ||
| 47 | + .bytes() | ||
| 48 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// True for a code verifier: 43 to 128 unreserved characters (RFC 7636 section 4.1). | ||
| 52 | +pub fn is_valid_verifier(verifier: &str) -> bool { | ||
| 53 | + (43..=128).contains(&verifier.len()) | ||
| 54 | + && verifier | ||
| 55 | + .bytes() | ||
| 56 | + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// True for a registrable URI: `https`, or `http` to a loopback host (for development), absolute, with | ||
| 60 | +/// no fragment, no userinfo (`@`), no whitespace or control characters and no backslash. Redirect URIs, | ||
| 61 | +/// post-logout URIs and back-channel URIs all use this rule. | ||
| 62 | +pub fn is_valid_registered_uri(uri: &str) -> bool { | ||
| 63 | + if uri.len() > MAX_URI_BYTES | ||
| 64 | + || uri.bytes().any(|b| b <= 0x20 || b == 0x7f || b == b'\\') | ||
| 65 | + || uri.contains('#') | ||
| 66 | + { | ||
| 67 | + return false; | ||
| 68 | + } | ||
| 69 | + let Some((scheme, rest)) = uri.split_once("://") else { | ||
| 70 | + return false; | ||
| 71 | + }; | ||
| 72 | + let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())]; | ||
| 73 | + if authority.is_empty() || authority.contains('@') { | ||
| 74 | + return false; | ||
| 75 | + } | ||
| 76 | + let host = host_of(authority); | ||
| 77 | + match scheme { | ||
| 78 | + "https" => !host.is_empty(), | ||
| 79 | + "http" => is_loopback(host), | ||
| 80 | + _ => false, | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// The host of an authority (`host`, `host:port`, `[v6]:port`). | ||
| 85 | +fn host_of(authority: &str) -> &str { | ||
| 86 | + if let Some(bracketed) = authority.strip_prefix('[') { | ||
| 87 | + return bracketed.split(']').next().unwrap_or(""); | ||
| 88 | + } | ||
| 89 | + authority.split(':').next().unwrap_or("") | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +fn is_loopback(host: &str) -> bool { | ||
| 93 | + matches!(host, "localhost" | "127.0.0.1" | "::1") | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`. | ||
| 97 | +pub fn is_valid_family_key(key: &str) -> bool { | ||
| 98 | + let bytes = key.as_bytes(); | ||
| 99 | + (1..=32).contains(&bytes.len()) | ||
| 100 | + && bytes[0].is_ascii_lowercase() | ||
| 101 | + && bytes | ||
| 102 | + .iter() | ||
| 103 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-') | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +#[cfg(test)] | ||
| 107 | +mod tests { | ||
| 108 | + use super::*; | ||
| 109 | + | ||
| 110 | + #[test] | ||
| 111 | + fn the_rfc_7636_example_challenge_matches() { | ||
| 112 | + assert_eq!( | ||
| 113 | + pkce_s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), | ||
| 114 | + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" | ||
| 115 | + ); | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + #[test] | ||
| 119 | + fn registered_uris_must_be_exact_https_or_loopback_http() { | ||
| 120 | + assert!(is_valid_registered_uri( | ||
| 121 | + "https://in.example.com/auth/callback" | ||
| 122 | + )); | ||
| 123 | + assert!(is_valid_registered_uri( | ||
| 124 | + "http://127.0.0.1:7655/auth/callback" | ||
| 125 | + )); | ||
| 126 | + assert!(is_valid_registered_uri("http://[::1]:7655/auth/callback")); | ||
| 127 | + for bad in [ | ||
| 128 | + "http://in.example.com/auth/callback", | ||
| 129 | + "https://in.example.com@evil.example/auth/callback", | ||
| 130 | + "https://in.example.com/auth/callback#frag", | ||
| 131 | + "https:///auth/callback", | ||
| 132 | + "https://in.example.com/a b", | ||
| 133 | + "https://in.example.com\\evil", | ||
| 134 | + "in.example.com/auth/callback", | ||
| 135 | + "javascript://in.example.com/x", | ||
| 136 | + ] { | ||
| 137 | + assert!(!is_valid_registered_uri(bad), "accepted {bad:?}"); | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | +} | ||
crates/im-core/src/store/clients.rsadded+135 -0
| @@ -0,0 +1,135 @@ | |||
| 1 | +//! OIDC clients: registration, lookup, listing and disabling. | ||
| 2 | +//! | ||
| 3 | +//! The client secret is a random token, so only its SHA-256 is stored (`token.rs`). Redirect and | ||
| 4 | +//! logout URIs are JSON arrays that are matched exactly, never by prefix. A disabled client keeps its | ||
| 5 | +//! row, so its history stays readable, and it authenticates nowhere. | ||
| 6 | + | ||
| 7 | +use turso::Row; | ||
| 8 | + | ||
| 9 | +use crate::error::{Error, Result}; | ||
| 10 | +use crate::model::Client; | ||
| 11 | +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | ||
| 12 | +use crate::time::now_stamp; | ||
| 13 | + | ||
| 14 | +/// The columns of a client row, in the order [`map_client`] reads them. | ||
| 15 | +const CLIENT_COLS: &str = "id, name, secret_hash, secret_rotated_at, redirect_uris, \ | ||
| 16 | + post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, created_at, \ | ||
| 17 | + disabled_at"; | ||
| 18 | + | ||
| 19 | +fn uri_list(row: &Row, i: usize) -> Result<Vec<String>> { | ||
| 20 | + let text = col_text(row, i)?; | ||
| 21 | + serde_json::from_str(&text).map_err(|e| Error::Database(format!("bad URI list: {e}"))) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// Maps a row selected with [`CLIENT_COLS`]. | ||
| 25 | +fn map_client(row: &Row) -> Result<Client> { | ||
| 26 | + Ok(Client { | ||
| 27 | + id: col_text(row, 0)?, | ||
| 28 | + name: col_text(row, 1)?, | ||
| 29 | + secret_hash: col_text(row, 2)?, | ||
| 30 | + secret_rotated_at: col_text(row, 3)?, | ||
| 31 | + redirect_uris: uri_list(row, 4)?, | ||
| 32 | + post_logout_redirect_uris: uri_list(row, 5)?, | ||
| 33 | + backchannel_logout_uri: col_opt_text(row, 6)?, | ||
| 34 | + allowed_scopes: col_text(row, 7)?, | ||
| 35 | + service_key: col_opt_text(row, 8)?, | ||
| 36 | + created_at: col_text(row, 9)?, | ||
| 37 | + disabled_at: col_opt_text(row, 10)?, | ||
| 38 | + }) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// What is needed to register a client. The URIs must already be checked by `oauth.rs`. | ||
| 42 | +#[derive(Debug, Clone)] | ||
| 43 | +pub struct NewClient<'a> { | ||
| 44 | + /// Display name. | ||
| 45 | + pub name: &'a str, | ||
| 46 | + /// Hex SHA-256 of the secret that is shown once. | ||
| 47 | + pub secret_hash: &'a str, | ||
| 48 | + /// Exact redirect URIs. | ||
| 49 | + pub redirect_uris: &'a [String], | ||
| 50 | + /// Exact post-logout redirect URIs. | ||
| 51 | + pub post_logout_redirect_uris: &'a [String], | ||
| 52 | + /// Back-channel logout endpoint, if any. | ||
| 53 | + pub backchannel_logout_uri: Option<&'a str>, | ||
| 54 | + /// Space-separated scopes the client may ask for. | ||
| 55 | + pub allowed_scopes: &'a str, | ||
| 56 | + /// Family key, if the client is a family service. Unique. | ||
| 57 | + pub service_key: Option<&'a str>, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +impl Store { | ||
| 61 | + /// Registers a client and returns its row. A family key that is already used is a conflict. | ||
| 62 | + pub async fn create_client(&self, new: &NewClient<'_>) -> Result<Client> { | ||
| 63 | + let id = new_id(); | ||
| 64 | + let now = now_stamp(); | ||
| 65 | + let redirect_uris = | ||
| 66 | + serde_json::to_string(new.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; | ||
| 67 | + let post_logout = serde_json::to_string(new.post_logout_redirect_uris) | ||
| 68 | + .map_err(|e| Error::Invalid(e.to_string()))?; | ||
| 69 | + let conn = self.inner.conn.lock().await; | ||
| 70 | + conn.execute( | ||
| 71 | + "INSERT INTO clients (id, name, secret_hash, secret_rotated_at, redirect_uris, \ | ||
| 72 | + post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, \ | ||
| 73 | + created_at) \ | ||
| 74 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?4)", | ||
| 75 | + ( | ||
| 76 | + id.clone(), | ||
| 77 | + new.name.to_string(), | ||
| 78 | + new.secret_hash.to_string(), | ||
| 79 | + now, | ||
| 80 | + redirect_uris, | ||
| 81 | + post_logout, | ||
| 82 | + new.backchannel_logout_uri.map(str::to_owned), | ||
| 83 | + new.allowed_scopes.to_string(), | ||
| 84 | + new.service_key.map(str::to_owned), | ||
| 85 | + ), | ||
| 86 | + ) | ||
| 87 | + .await | ||
| 88 | + .map_err(|e| { | ||
| 89 | + if e.to_string().contains("UNIQUE") { | ||
| 90 | + Error::Conflict("that family key is already used by another client".into()) | ||
| 91 | + } else { | ||
| 92 | + db_err(e) | ||
| 93 | + } | ||
| 94 | + })?; | ||
| 95 | + drop(conn); | ||
| 96 | + self.client_by_id(&id).await?.ok_or(Error::NotFound) | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + /// The client with this id, disabled or not. | ||
| 100 | + pub async fn client_by_id(&self, id: &str) -> Result<Option<Client>> { | ||
| 101 | + let conn = self.read_conn().await; | ||
| 102 | + fetch_opt( | ||
| 103 | + &conn, | ||
| 104 | + &format!("SELECT {CLIENT_COLS} FROM clients WHERE id = ?1"), | ||
| 105 | + (id.to_string(),), | ||
| 106 | + map_client, | ||
| 107 | + ) | ||
| 108 | + .await | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + /// Every client, oldest first. | ||
| 112 | + pub async fn list_clients(&self) -> Result<Vec<Client>> { | ||
| 113 | + let conn = self.read_conn().await; | ||
| 114 | + fetch_all( | ||
| 115 | + &conn, | ||
| 116 | + &format!("SELECT {CLIENT_COLS} FROM clients ORDER BY created_at ASC, id ASC"), | ||
| 117 | + (), | ||
| 118 | + map_client, | ||
| 119 | + ) | ||
| 120 | + .await | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// Disables a client. Returns false when there was no such client or it was already disabled. | ||
| 124 | + pub async fn disable_client(&self, id: &str) -> Result<bool> { | ||
| 125 | + let conn = self.inner.conn.lock().await; | ||
| 126 | + let changed = conn | ||
| 127 | + .execute( | ||
| 128 | + "UPDATE clients SET disabled_at = ?2 WHERE id = ?1 AND disabled_at IS NULL", | ||
| 129 | + (id.to_string(), now_stamp()), | ||
| 130 | + ) | ||
| 131 | + .await | ||
| 132 | + .map_err(db_err)?; | ||
| 133 | + Ok(changed == 1) | ||
| 134 | + } | ||
| 135 | +} | ||
crates/im-core/src/store/keys.rsadded+86 -0
| @@ -0,0 +1,86 @@ | |||
| 1 | +//! Signing keys in the database: the chain of keys, and the one write that rotates it. | ||
| 2 | +//! | ||
| 3 | +//! The private seed is sealed before it reaches this module, so the rows hold no usable key material | ||
| 4 | +//! in clear. Adding a key retires the previous one in the same transaction, so there is never a moment | ||
| 5 | +//! with two keys both signing as the newest. | ||
| 6 | + | ||
| 7 | +use turso::Value; | ||
| 8 | + | ||
| 9 | +use crate::error::{Error, Result}; | ||
| 10 | +use crate::model::KeyRecord; | ||
| 11 | +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, finish}; | ||
| 12 | + | ||
| 13 | +/// The columns of a key row, in the order [`map_key`] reads them. | ||
| 14 | +const KEY_COLS: &str = "kid, private_sealed, public_raw, created_at, activates_at, retires_at"; | ||
| 15 | + | ||
| 16 | +fn map_key(row: &turso::Row) -> Result<KeyRecord> { | ||
| 17 | + let public_raw = match row.get_value(2).map_err(db_err)? { | ||
| 18 | + Value::Blob(bytes) => bytes, | ||
| 19 | + _ => return Err(Error::Database("public_raw is not a blob".into())), | ||
| 20 | + }; | ||
| 21 | + Ok(KeyRecord { | ||
| 22 | + kid: col_text(row, 0)?, | ||
| 23 | + private_sealed: col_text(row, 1)?, | ||
| 24 | + public_raw, | ||
| 25 | + created_at: col_text(row, 3)?, | ||
| 26 | + activates_at: col_text(row, 4)?, | ||
| 27 | + retires_at: col_opt_text(row, 5)?, | ||
| 28 | + }) | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl Store { | ||
| 32 | + /// Every key row, oldest activation first. | ||
| 33 | + pub async fn signing_keys(&self) -> Result<Vec<KeyRecord>> { | ||
| 34 | + let conn = self.read_conn().await; | ||
| 35 | + fetch_all( | ||
| 36 | + &conn, | ||
| 37 | + &format!("SELECT {KEY_COLS} FROM signing_keys ORDER BY activates_at ASC, kid ASC"), | ||
| 38 | + (), | ||
| 39 | + map_key, | ||
| 40 | + ) | ||
| 41 | + .await | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + /// Adds a key. Every key that is not yet retired and activates before it is retired at its | ||
| 45 | + /// activation time, in the same transaction. | ||
| 46 | + pub async fn add_signing_key(&self, key: &KeyRecord) -> Result<()> { | ||
| 47 | + let conn = self.inner.conn.lock().await; | ||
| 48 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 49 | + let outcome: Result<()> = async { | ||
| 50 | + tx.execute( | ||
| 51 | + "UPDATE signing_keys SET retires_at = ?1 \ | ||
| 52 | + WHERE retires_at IS NULL AND activates_at < ?1", | ||
| 53 | + (key.activates_at.clone(),), | ||
| 54 | + ) | ||
| 55 | + .await | ||
| 56 | + .map_err(db_err)?; | ||
| 57 | + tx.execute( | ||
| 58 | + "INSERT INTO signing_keys (kid, private_sealed, public_raw, created_at, activates_at, \ | ||
| 59 | + retires_at) VALUES (?1, ?2, ?3, ?4, ?5, NULL)", | ||
| 60 | + ( | ||
| 61 | + key.kid.clone(), | ||
| 62 | + key.private_sealed.clone(), | ||
| 63 | + key.public_raw.clone(), | ||
| 64 | + key.created_at.clone(), | ||
| 65 | + key.activates_at.clone(), | ||
| 66 | + ), | ||
| 67 | + ) | ||
| 68 | + .await | ||
| 69 | + .map_err(db_err)?; | ||
| 70 | + Ok(()) | ||
| 71 | + } | ||
| 72 | + .await; | ||
| 73 | + finish(tx, outcome).await | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + /// Deletes keys retired at or before `cutoff`. Returns how many were removed. | ||
| 77 | + pub async fn prune_signing_keys(&self, cutoff: &str) -> Result<u64> { | ||
| 78 | + let conn = self.inner.conn.lock().await; | ||
| 79 | + conn.execute( | ||
| 80 | + "DELETE FROM signing_keys WHERE retires_at IS NOT NULL AND retires_at <= ?1", | ||
| 81 | + (cutoff.to_string(),), | ||
| 82 | + ) | ||
| 83 | + .await | ||
| 84 | + .map_err(db_err) | ||
| 85 | + } | ||
| 86 | +} | ||
crates/im-core/src/store/mod.rsmodified+4 -1
| @@ -7,8 +7,11 @@ | |||
| 7 | //! in effect are logged at boot. | 7 | //! in effect are logged at boot. |
| 8 | 8 | ||
| 9 | pub mod audit; | 9 | pub mod audit; |
| 10 | +pub mod clients; | ||
| 10 | pub mod directory; | 11 | pub mod directory; |
| 12 | +pub mod keys; | ||
| 11 | pub mod migrate; | 13 | pub mod migrate; |
| 14 | +pub mod oidc; | ||
| 12 | pub mod sessions; | 15 | pub mod sessions; |
| 13 | pub mod snapshot; | 16 | pub mod snapshot; |
| 14 | pub mod users; | 17 | pub mod users; |
| @@ -159,7 +162,7 @@ pub async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> { | |||
| 159 | 162 | ||
| 160 | /// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order | 163 | /// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order |
| 161 | /// within a millisecond. | 164 | /// within a millisecond. |
| 162 | -pub(crate) fn new_id() -> String { | 165 | +pub fn new_id() -> String { |
| 163 | ulid::Ulid::generate().to_string() | 166 | ulid::Ulid::generate().to_string() |
| 164 | } | 167 | } |
| 165 | 168 | ||
crates/im-core/src/store/oidc.rsadded+271 -0
| @@ -0,0 +1,271 @@ | |||
| 1 | +//! OIDC state in the database: authorization codes, refresh tokens, and the sessions each client has | ||
| 2 | +//! signed into. | ||
| 3 | +//! | ||
| 4 | +//! The two single-use rules are one conditional statement each, inside one transaction together with | ||
| 5 | +//! the row they create. Two parallel exchanges of one code, or of one refresh token, cannot both win. | ||
| 6 | +//! A reuse is detected by the caller, which then revokes the family (`revoke_*`). | ||
| 7 | + | ||
| 8 | +use turso::Connection; | ||
| 9 | + | ||
| 10 | +use crate::error::Result; | ||
| 11 | +use crate::model::{AuthCode, RefreshToken}; | ||
| 12 | +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish}; | ||
| 13 | +use crate::time::now_stamp; | ||
| 14 | + | ||
| 15 | +/// The columns of an authorization code row, in the order [`map_code`] reads them. | ||
| 16 | +const CODE_COLS: &str = "code_hash, client_id, user_id, session_id, redirect_uri, scope, nonce, \ | ||
| 17 | + code_challenge, expires_at, used_at"; | ||
| 18 | + | ||
| 19 | +/// The columns of a refresh token row, in the order [`map_refresh`] reads them. | ||
| 20 | +const REFRESH_COLS: &str = "id, token_hash, family_id, client_id, user_id, session_id, code_hash, \ | ||
| 21 | + scope, created_at, expires_at, used_at, revoked_at"; | ||
| 22 | + | ||
| 23 | +fn map_code(row: &turso::Row) -> Result<AuthCode> { | ||
| 24 | + Ok(AuthCode { | ||
| 25 | + code_hash: col_text(row, 0)?, | ||
| 26 | + client_id: col_text(row, 1)?, | ||
| 27 | + user_id: col_text(row, 2)?, | ||
| 28 | + session_id: col_text(row, 3)?, | ||
| 29 | + redirect_uri: col_text(row, 4)?, | ||
| 30 | + scope: col_text(row, 5)?, | ||
| 31 | + nonce: col_opt_text(row, 6)?, | ||
| 32 | + code_challenge: col_text(row, 7)?, | ||
| 33 | + expires_at: col_text(row, 8)?, | ||
| 34 | + used_at: col_opt_text(row, 9)?, | ||
| 35 | + }) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +fn map_refresh(row: &turso::Row) -> Result<RefreshToken> { | ||
| 39 | + Ok(RefreshToken { | ||
| 40 | + id: col_text(row, 0)?, | ||
| 41 | + token_hash: col_text(row, 1)?, | ||
| 42 | + family_id: col_text(row, 2)?, | ||
| 43 | + client_id: col_text(row, 3)?, | ||
| 44 | + user_id: col_text(row, 4)?, | ||
| 45 | + session_id: col_text(row, 5)?, | ||
| 46 | + code_hash: col_opt_text(row, 6)?, | ||
| 47 | + scope: col_text(row, 7)?, | ||
| 48 | + created_at: col_text(row, 8)?, | ||
| 49 | + expires_at: col_text(row, 9)?, | ||
| 50 | + used_at: col_opt_text(row, 10)?, | ||
| 51 | + revoked_at: col_opt_text(row, 11)?, | ||
| 52 | + }) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// A new authorization code. Only its hash is stored. | ||
| 56 | +#[derive(Debug, Clone)] | ||
| 57 | +pub struct NewAuthCode<'a> { | ||
| 58 | + /// Hex SHA-256 of the code given to the client. | ||
| 59 | + pub code_hash: &'a str, | ||
| 60 | + /// The client the code is for. | ||
| 61 | + pub client_id: &'a str, | ||
| 62 | + /// The person who signed in. | ||
| 63 | + pub user_id: &'a str, | ||
| 64 | + /// The browser session the sign-in belongs to. | ||
| 65 | + pub session_id: &'a str, | ||
| 66 | + /// The redirect URI of the request. | ||
| 67 | + pub redirect_uri: &'a str, | ||
| 68 | + /// The granted scope. | ||
| 69 | + pub scope: &'a str, | ||
| 70 | + /// The nonce of the request, if any. | ||
| 71 | + pub nonce: Option<&'a str>, | ||
| 72 | + /// The S256 challenge of the request. | ||
| 73 | + pub code_challenge: &'a str, | ||
| 74 | + /// When the code stops being usable. | ||
| 75 | + pub expires_at: &'a str, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// A new refresh token. `created_at` is set by the store, at the time of the write. | ||
| 79 | +#[derive(Debug, Clone)] | ||
| 80 | +pub struct NewRefreshToken<'a> { | ||
| 81 | + /// ULID. | ||
| 82 | + pub id: &'a str, | ||
| 83 | + /// Hex SHA-256 of the token given to the client. | ||
| 84 | + pub token_hash: &'a str, | ||
| 85 | + /// The first token of the chain: its own id for a chain's first token. | ||
| 86 | + pub family_id: &'a str, | ||
| 87 | + /// The client the token is for. | ||
| 88 | + pub client_id: &'a str, | ||
| 89 | + /// The person. | ||
| 90 | + pub user_id: &'a str, | ||
| 91 | + /// The browser session the chain belongs to. | ||
| 92 | + pub session_id: &'a str, | ||
| 93 | + /// Hash of the authorization code the chain began with, if any. | ||
| 94 | + pub code_hash: Option<&'a str>, | ||
| 95 | + /// The granted scope. | ||
| 96 | + pub scope: &'a str, | ||
| 97 | + /// When the token stops being usable. | ||
| 98 | + pub expires_at: &'a str, | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +/// Inserts a refresh token row inside the caller's transaction. | ||
| 102 | +async fn insert_refresh(conn: &Connection, new: &NewRefreshToken<'_>, now: &str) -> Result<()> { | ||
| 103 | + conn.execute( | ||
| 104 | + "INSERT INTO refresh_tokens (id, token_hash, family_id, client_id, user_id, session_id, \ | ||
| 105 | + code_hash, scope, created_at, expires_at) \ | ||
| 106 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", | ||
| 107 | + ( | ||
| 108 | + new.id.to_string(), | ||
| 109 | + new.token_hash.to_string(), | ||
| 110 | + new.family_id.to_string(), | ||
| 111 | + new.client_id.to_string(), | ||
| 112 | + new.user_id.to_string(), | ||
| 113 | + new.session_id.to_string(), | ||
| 114 | + new.code_hash.map(str::to_owned), | ||
| 115 | + new.scope.to_string(), | ||
| 116 | + now.to_string(), | ||
| 117 | + new.expires_at.to_string(), | ||
| 118 | + ), | ||
| 119 | + ) | ||
| 120 | + .await | ||
| 121 | + .map_err(db_err)?; | ||
| 122 | + Ok(()) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +impl Store { | ||
| 126 | + /// Stores a new authorization code. | ||
| 127 | + pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> { | ||
| 128 | + let conn = self.inner.conn.lock().await; | ||
| 129 | + conn.execute( | ||
| 130 | + "INSERT INTO auth_codes (code_hash, client_id, user_id, session_id, redirect_uri, scope, \ | ||
| 131 | + nonce, code_challenge, expires_at) \ | ||
| 132 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | ||
| 133 | + ( | ||
| 134 | + new.code_hash.to_string(), | ||
| 135 | + new.client_id.to_string(), | ||
| 136 | + new.user_id.to_string(), | ||
| 137 | + new.session_id.to_string(), | ||
| 138 | + new.redirect_uri.to_string(), | ||
| 139 | + new.scope.to_string(), | ||
| 140 | + new.nonce.map(str::to_owned), | ||
| 141 | + new.code_challenge.to_string(), | ||
| 142 | + new.expires_at.to_string(), | ||
| 143 | + ), | ||
| 144 | + ) | ||
| 145 | + .await | ||
| 146 | + .map_err(db_err)?; | ||
| 147 | + Ok(()) | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + /// The authorization code with this hash, used or not. | ||
| 151 | + pub async fn auth_code(&self, code_hash: &str) -> Result<Option<AuthCode>> { | ||
| 152 | + let conn = self.read_conn().await; | ||
| 153 | + fetch_opt( | ||
| 154 | + &conn, | ||
| 155 | + &format!("SELECT {CODE_COLS} FROM auth_codes WHERE code_hash = ?1"), | ||
| 156 | + (code_hash.to_string(),), | ||
| 157 | + map_code, | ||
| 158 | + ) | ||
| 159 | + .await | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + /// Exchanges a code: marks it used and stores the first refresh token, in one transaction. Returns | ||
| 163 | + /// false, with nothing changed, when the code is already used, expired or unknown. The caller treats | ||
| 164 | + /// a false after its own checks passed as a race, which is a reuse. | ||
| 165 | + pub async fn redeem_auth_code( | ||
| 166 | + &self, | ||
| 167 | + code_hash: &str, | ||
| 168 | + refresh: &NewRefreshToken<'_>, | ||
| 169 | + ) -> Result<bool> { | ||
| 170 | + let now = now_stamp(); | ||
| 171 | + let conn = self.inner.conn.lock().await; | ||
| 172 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 173 | + let outcome: Result<bool> = async { | ||
| 174 | + let changed = tx | ||
| 175 | + .execute( | ||
| 176 | + "UPDATE auth_codes SET used_at = ?2 \ | ||
| 177 | + WHERE code_hash = ?1 AND used_at IS NULL AND expires_at > ?2", | ||
| 178 | + (code_hash.to_string(), now.clone()), | ||
| 179 | + ) | ||
| 180 | + .await | ||
| 181 | + .map_err(db_err)?; | ||
| 182 | + if changed != 1 { | ||
| 183 | + return Ok(false); | ||
| 184 | + } | ||
| 185 | + insert_refresh(&tx, refresh, &now).await?; | ||
| 186 | + Ok(true) | ||
| 187 | + } | ||
| 188 | + .await; | ||
| 189 | + finish(tx, outcome).await | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + /// The refresh token with this hash, used or not. | ||
| 193 | + pub async fn refresh_token(&self, token_hash: &str) -> Result<Option<RefreshToken>> { | ||
| 194 | + let conn = self.read_conn().await; | ||
| 195 | + fetch_opt( | ||
| 196 | + &conn, | ||
| 197 | + &format!("SELECT {REFRESH_COLS} FROM refresh_tokens WHERE token_hash = ?1"), | ||
| 198 | + (token_hash.to_string(),), | ||
| 199 | + map_refresh, | ||
| 200 | + ) | ||
| 201 | + .await | ||
| 202 | + } | ||
| 203 | + | ||
| 204 | + /// Rotates a refresh token: marks the presented one used and stores its successor, in one | ||
| 205 | + /// transaction. Returns false, with nothing changed, when the presented token was already used or | ||
| 206 | + /// revoked. | ||
| 207 | + pub async fn rotate_refresh_token( | ||
| 208 | + &self, | ||
| 209 | + presented_id: &str, | ||
| 210 | + next: &NewRefreshToken<'_>, | ||
| 211 | + ) -> Result<bool> { | ||
| 212 | + let now = now_stamp(); | ||
| 213 | + let conn = self.inner.conn.lock().await; | ||
| 214 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 215 | + let outcome: Result<bool> = async { | ||
| 216 | + let changed = tx | ||
| 217 | + .execute( | ||
| 218 | + "UPDATE refresh_tokens SET used_at = ?2 \ | ||
| 219 | + WHERE id = ?1 AND used_at IS NULL AND revoked_at IS NULL", | ||
| 220 | + (presented_id.to_string(), now.clone()), | ||
| 221 | + ) | ||
| 222 | + .await | ||
| 223 | + .map_err(db_err)?; | ||
| 224 | + if changed != 1 { | ||
| 225 | + return Ok(false); | ||
| 226 | + } | ||
| 227 | + insert_refresh(&tx, next, &now).await?; | ||
| 228 | + Ok(true) | ||
| 229 | + } | ||
| 230 | + .await; | ||
| 231 | + finish(tx, outcome).await | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + /// Revokes every token of a family that is not revoked yet. Returns how many were revoked. | ||
| 235 | + pub async fn revoke_refresh_family(&self, family_id: &str) -> Result<u64> { | ||
| 236 | + let conn = self.inner.conn.lock().await; | ||
| 237 | + conn.execute( | ||
| 238 | + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE family_id = ?1 AND revoked_at IS NULL", | ||
| 239 | + (family_id.to_string(), now_stamp()), | ||
| 240 | + ) | ||
| 241 | + .await | ||
| 242 | + .map_err(db_err) | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + /// Revokes every refresh token issued from one authorization code. Returns how many were revoked. | ||
| 246 | + pub async fn revoke_code_refresh_tokens(&self, code_hash: &str) -> Result<u64> { | ||
| 247 | + let conn = self.inner.conn.lock().await; | ||
| 248 | + conn.execute( | ||
| 249 | + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE code_hash = ?1 AND revoked_at IS NULL", | ||
| 250 | + (code_hash.to_string(), now_stamp()), | ||
| 251 | + ) | ||
| 252 | + .await | ||
| 253 | + .map_err(db_err) | ||
| 254 | + } | ||
| 255 | + | ||
| 256 | + /// Records that a browser session signed into a client. The first time sets `first_at`; every time | ||
| 257 | + /// sets `last_at`. Drives back-channel logout and the connected-apps list. | ||
| 258 | + pub async fn touch_client_session(&self, session_id: &str, client_id: &str) -> Result<()> { | ||
| 259 | + let now = now_stamp(); | ||
| 260 | + let conn = self.inner.conn.lock().await; | ||
| 261 | + conn.execute( | ||
| 262 | + "INSERT INTO client_sessions (session_id, client_id, first_at, last_at) \ | ||
| 263 | + VALUES (?1, ?2, ?3, ?3) \ | ||
| 264 | + ON CONFLICT (session_id, client_id) DO UPDATE SET last_at = excluded.last_at", | ||
| 265 | + (session_id.to_string(), client_id.to_string(), now), | ||
| 266 | + ) | ||
| 267 | + .await | ||
| 268 | + .map_err(db_err)?; | ||
| 269 | + Ok(()) | ||
| 270 | + } | ||
| 271 | +} | ||
crates/im-core/src/store/sessions.rsmodified+17 -0
| @@ -214,6 +214,23 @@ impl Store { | |||
| 214 | .await | 214 | .await |
| 215 | } | 215 | } |
| 216 | 216 | ||
| 217 | + /// The session with this id when it is live (same rules as [`Store::session_by_token_hash`]), else | ||
| 218 | + /// `None`. The token endpoints use it for the authentication time and method of the session. | ||
| 219 | + pub async fn live_session(&self, session_id: &str) -> Result<Option<Session>> { | ||
| 220 | + let conn = self.read_conn().await; | ||
| 221 | + fetch_opt( | ||
| 222 | + &conn, | ||
| 223 | + &format!( | ||
| 224 | + "SELECT {SESSION_COLS} FROM sessions \ | ||
| 225 | + WHERE id = ?1 AND expires_at > ?2 \ | ||
| 226 | + AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)" | ||
| 227 | + ), | ||
| 228 | + (session_id.to_string(), now_stamp()), | ||
| 229 | + map_session, | ||
| 230 | + ) | ||
| 231 | + .await | ||
| 232 | + } | ||
| 233 | + | ||
| 217 | /// True when the session with this id is still live (same rules as | 234 | /// True when the session with this id is still live (same rules as |
| 218 | /// [`Store::session_by_token_hash`]). The live stream checks this after every change. | 235 | /// [`Store::session_by_token_hash`]). The live stream checks this after every change. |
| 219 | pub async fn session_is_live(&self, session_id: &str) -> Result<bool> { | 236 | pub async fn session_is_live(&self, session_id: &str) -> Result<bool> { |
crates/im-core/src/time.rsmodified+31 -0
| @@ -37,6 +37,37 @@ pub fn stamp_before(before: Duration) -> String { | |||
| 37 | format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before))) | 37 | format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before))) |
| 38 | } | 38 | } |
| 39 | 39 | ||
| 40 | +/// Parses a stored stamp back into a time. `None` for anything that is not a stamp. | ||
| 41 | +fn parse_stamp(stamp: &str) -> Option<OffsetDateTime> { | ||
| 42 | + OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339).ok() | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// The Unix time, in whole seconds, of a stored stamp. `None` when it is not a stamp. | ||
| 46 | +pub fn unix_seconds(stamp: &str) -> Option<i64> { | ||
| 47 | + parse_stamp(stamp).map(OffsetDateTime::unix_timestamp) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The stamp `after` later than `stamp`, saturating at the largest time. `None` when `stamp` is not a | ||
| 51 | +/// stamp. | ||
| 52 | +pub fn stamp_plus(stamp: &str, after: Duration) -> Option<String> { | ||
| 53 | + Some(format_stamp( | ||
| 54 | + parse_stamp(stamp)?.saturating_add(signed(after)), | ||
| 55 | + )) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The stamp `before` earlier than `stamp`, saturating at the smallest time. `None` when `stamp` is not | ||
| 59 | +/// a stamp. | ||
| 60 | +pub fn stamp_minus(stamp: &str, before: Duration) -> Option<String> { | ||
| 61 | + Some(format_stamp( | ||
| 62 | + parse_stamp(stamp)?.saturating_sub(signed(before)), | ||
| 63 | + )) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// The current Unix time in whole seconds. | ||
| 67 | +pub fn unix_now() -> i64 { | ||
| 68 | + OffsetDateTime::now_utc().unix_timestamp() | ||
| 69 | +} | ||
| 70 | + | ||
| 40 | /// The IANA time zone names of the database compiled into this build, sorted. The bundled database | 71 | /// The IANA time zone names of the database compiled into this build, sorted. The bundled database |
| 41 | /// is used on purpose, so every install offers the same list whatever the host has installed. | 72 | /// is used on purpose, so every install offers the same list whatever the host has installed. |
| 42 | pub fn zone_names() -> Vec<String> { | 73 | pub fn zone_names() -> Vec<String> { |
crates/im-web/src/boot.rsmodified+7 -2
| @@ -20,6 +20,7 @@ use topcoat::cookie::RouterBuilderCookieExt; | |||
| 20 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; | 20 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 21 | 21 | ||
| 22 | use crate::live::LiveHub; | 22 | use crate::live::LiveHub; |
| 23 | +use crate::oidc::signing; | ||
| 23 | use crate::pages::not_found::NotFoundLayer; | 24 | use crate::pages::not_found::NotFoundLayer; |
| 24 | use crate::pages::profile::PHOTO_ROUTE; | 25 | use crate::pages::profile::PHOTO_ROUTE; |
| 25 | use crate::security::{self, SecurityHeaders}; | 26 | use crate::security::{self, SecurityHeaders}; |
| @@ -52,6 +53,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 52 | tracing::info!("shutdown signal received"); | 53 | tracing::info!("shutdown signal received"); |
| 53 | stop_tx.send_replace(true); | 54 | stop_tx.send_replace(true); |
| 54 | }); | 55 | }); |
| 56 | + let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); | ||
| 55 | 57 | ||
| 56 | topcoat::serve_until( | 58 | topcoat::serve_until( |
| 57 | listener, | 59 | listener, |
| @@ -59,13 +61,15 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 59 | wait_stop(stop_rx), | 61 | wait_stop(stop_rx), |
| 60 | ) | 62 | ) |
| 61 | .await?; | 63 | .await?; |
| 64 | + let _ = signing_worker.await; | ||
| 62 | tracing::info!("im stopped"); | 65 | tracing::info!("im stopped"); |
| 63 | Ok(()) | 66 | Ok(()) |
| 64 | } | 67 | } |
| 65 | 68 | ||
| 66 | /// Creates the data directory and opens the key and the database. Everything the router needs | 69 | /// Creates the data directory and opens the key and the database. Everything the router needs |
| 67 | -/// that touches the disk is ready when this returns. | 70 | +/// that touches the disk is ready when this returns. The signing keys are made ready too, so the |
| 68 | -async fn open_state(config: Config) -> im_core::Result<AppState> { | 71 | +/// first token can be signed. The operator commands use this as well. |
| 72 | +pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | ||
| 69 | std::fs::create_dir_all(&config.data_dir)?; | 73 | std::fs::create_dir_all(&config.data_dir)?; |
| 70 | // The directory holds the instance key. Only this user may enter it. | 74 | // The directory holds the instance key. Only this user may enter it. |
| 71 | std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; | 75 | 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<AppState> { | |||
| 79 | } | 83 | } |
| 80 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; | 84 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 81 | let store = Store::open(&config.database).await?; | 85 | let store = Store::open(&config.database).await?; |
| 86 | + signing::maintain(&store, &key).await?; | ||
| 82 | Ok(AppState { | 87 | Ok(AppState { |
| 83 | config: Arc::new(config), | 88 | config: Arc::new(config), |
| 84 | store, | 89 | store, |
crates/im-web/src/cli.rsadded+253 -0
| @@ -0,0 +1,253 @@ | |||
| 1 | +//! The `im client` commands: register, list and disable OpenID Connect clients from the operator's | ||
| 2 | +//! shell. | ||
| 3 | +//! | ||
| 4 | +//! The commands open the database and the instance key directly, as the server does at boot, so they | ||
| 5 | +//! need the data directory. A client secret is printed once, on standard output, and only its SHA-256 | ||
| 6 | +//! is stored. The redirect, logout and back-channel URIs are checked by the same rules the endpoints use. | ||
| 7 | + | ||
| 8 | +use std::fmt::Display; | ||
| 9 | +use std::path::Path; | ||
| 10 | +use std::process::ExitCode; | ||
| 11 | + | ||
| 12 | +use im_core::config::Config; | ||
| 13 | +use im_core::names::parse_display_name; | ||
| 14 | +use im_core::oauth::{ | ||
| 15 | + SUPPORTED_SCOPES, is_supported_scope, is_valid_family_key, is_valid_registered_uri, | ||
| 16 | +}; | ||
| 17 | +use im_core::store::clients::NewClient; | ||
| 18 | +use im_core::token::{generate_token, hash_token}; | ||
| 19 | + | ||
| 20 | +use crate::boot::open_state; | ||
| 21 | +use crate::state::AppState; | ||
| 22 | + | ||
| 23 | +/// Printed with a usage error. | ||
| 24 | +const USAGE: &str = "usage: | ||
| 25 | + im client add --name <name> [--redirect-uri <uri>]... [--post-logout-uri <uri>]... | ||
| 26 | + [--backchannel-uri <uri>] [--family-key <key>] [--scopes <scope ...>] | ||
| 27 | + im client list | ||
| 28 | + im client disable <client_id>"; | ||
| 29 | + | ||
| 30 | +/// The scopes a client gets when `--scopes` is not given: what a family app signs in with. | ||
| 31 | +const DEFAULT_SCOPES: &str = "openid profile email"; | ||
| 32 | + | ||
| 33 | +/// Runs one `im client` command. `words` are the words after `client`. | ||
| 34 | +pub async fn client(config: &Path, words: &[String]) -> ExitCode { | ||
| 35 | + let Some((verb, rest)) = words.split_first() else { | ||
| 36 | + return usage(); | ||
| 37 | + }; | ||
| 38 | + match verb.as_str() { | ||
| 39 | + "add" => match parse_add(rest) { | ||
| 40 | + Ok(args) => with_state(config, |state| add(state, args)).await, | ||
| 41 | + Err(message) => { | ||
| 42 | + eprintln!("im: {message}\n{USAGE}"); | ||
| 43 | + ExitCode::from(2) | ||
| 44 | + } | ||
| 45 | + }, | ||
| 46 | + "list" if rest.is_empty() => with_state(config, list).await, | ||
| 47 | + "disable" => match rest { | ||
| 48 | + [id] => with_state(config, |state| disable(state, id)).await, | ||
| 49 | + _ => usage(), | ||
| 50 | + }, | ||
| 51 | + _ => usage(), | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// Prints the usage and exits with status 2. | ||
| 56 | +fn usage() -> ExitCode { | ||
| 57 | + eprintln!("im: unknown client command\n{USAGE}"); | ||
| 58 | + ExitCode::from(2) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Prints a failure and exits with status 1. | ||
| 62 | +fn fail(error: impl Display) -> ExitCode { | ||
| 63 | + eprintln!("im: {error}"); | ||
| 64 | + ExitCode::FAILURE | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// Opens the configuration, the key and the database, runs `action`, and maps its result to an exit | ||
| 68 | +/// status. | ||
| 69 | +async fn with_state<F, Fut>(config: &Path, action: F) -> ExitCode | ||
| 70 | +where | ||
| 71 | + F: FnOnce(AppState) -> Fut, | ||
| 72 | + Fut: std::future::Future<Output = Result<(), String>>, | ||
| 73 | +{ | ||
| 74 | + let outcome = async { | ||
| 75 | + let config = Config::load(config).map_err(|e| e.to_string())?; | ||
| 76 | + let state = open_state(config).await.map_err(|e| e.to_string())?; | ||
| 77 | + action(state).await | ||
| 78 | + } | ||
| 79 | + .await; | ||
| 80 | + match outcome { | ||
| 81 | + Ok(()) => ExitCode::SUCCESS, | ||
| 82 | + Err(message) => fail(message), | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// The options of `im client add`. | ||
| 87 | +#[derive(Debug, Default, PartialEq, Eq)] | ||
| 88 | +struct AddArgs { | ||
| 89 | + name: Option<String>, | ||
| 90 | + redirect_uris: Vec<String>, | ||
| 91 | + post_logout_uris: Vec<String>, | ||
| 92 | + backchannel_uri: Option<String>, | ||
| 93 | + family_key: Option<String>, | ||
| 94 | + scopes: Option<String>, | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// Reads `--flag value` pairs. Flags that repeat collect; the rest may be given once. | ||
| 98 | +fn parse_add(words: &[String]) -> std::result::Result<AddArgs, String> { | ||
| 99 | + let mut args = AddArgs::default(); | ||
| 100 | + let mut words = words.iter(); | ||
| 101 | + while let Some(flag) = words.next() { | ||
| 102 | + let value = words | ||
| 103 | + .next() | ||
| 104 | + .ok_or_else(|| format!("{flag} needs a value"))? | ||
| 105 | + .clone(); | ||
| 106 | + let once = |slot: &mut Option<String>| { | ||
| 107 | + if slot.replace(value.clone()).is_some() { | ||
| 108 | + Err(format!("{flag} may be given only once")) | ||
| 109 | + } else { | ||
| 110 | + Ok(()) | ||
| 111 | + } | ||
| 112 | + }; | ||
| 113 | + match flag.as_str() { | ||
| 114 | + "--name" => once(&mut args.name)?, | ||
| 115 | + "--redirect-uri" => args.redirect_uris.push(value), | ||
| 116 | + "--post-logout-uri" => args.post_logout_uris.push(value), | ||
| 117 | + "--backchannel-uri" => once(&mut args.backchannel_uri)?, | ||
| 118 | + "--family-key" => once(&mut args.family_key)?, | ||
| 119 | + "--scopes" => once(&mut args.scopes)?, | ||
| 120 | + other => return Err(format!("unknown option {other}")), | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | + Ok(args) | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// Registers a client and prints its id and its secret. The secret is not shown again. | ||
| 127 | +async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> { | ||
| 128 | + let name = parse_display_name(args.name.as_deref().ok_or("--name is required")?) | ||
| 129 | + .map_err(|e| e.to_string())?; | ||
| 130 | + for uri in args | ||
| 131 | + .redirect_uris | ||
| 132 | + .iter() | ||
| 133 | + .chain(&args.post_logout_uris) | ||
| 134 | + .chain(args.backchannel_uri.iter()) | ||
| 135 | + { | ||
| 136 | + if !is_valid_registered_uri(uri) { | ||
| 137 | + return Err(format!( | ||
| 138 | + "{uri} is not a valid URI for a client (https, or http on loopback, no fragment or userinfo)" | ||
| 139 | + )); | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | + if let Some(key) = &args.family_key | ||
| 143 | + && !is_valid_family_key(key) | ||
| 144 | + { | ||
| 145 | + return Err(format!( | ||
| 146 | + "family key {key} must be lowercase letters, digits and hyphens" | ||
| 147 | + )); | ||
| 148 | + } | ||
| 149 | + let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?; | ||
| 150 | + | ||
| 151 | + let secret = generate_token(); | ||
| 152 | + let client = state | ||
| 153 | + .store | ||
| 154 | + .create_client(&NewClient { | ||
| 155 | + name: &name, | ||
| 156 | + secret_hash: &hash_token(&secret), | ||
| 157 | + redirect_uris: &args.redirect_uris, | ||
| 158 | + post_logout_redirect_uris: &args.post_logout_uris, | ||
| 159 | + backchannel_logout_uri: args.backchannel_uri.as_deref(), | ||
| 160 | + allowed_scopes: &scopes, | ||
| 161 | + service_key: args.family_key.as_deref(), | ||
| 162 | + }) | ||
| 163 | + .await | ||
| 164 | + .map_err(|e| e.to_string())?; | ||
| 165 | + println!("client_id: {}", client.id); | ||
| 166 | + println!("client_secret: {secret}"); | ||
| 167 | + eprintln!("im: the client secret is shown once; store it now"); | ||
| 168 | + Ok(()) | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +/// The requested scopes, checked and de-duplicated, space separated. | ||
| 172 | +fn scope_list(requested: &str) -> std::result::Result<String, String> { | ||
| 173 | + let mut scopes: Vec<&str> = Vec::new(); | ||
| 174 | + for word in requested.split_whitespace() { | ||
| 175 | + if !is_supported_scope(word) { | ||
| 176 | + return Err(format!( | ||
| 177 | + "unknown scope {word}; the scopes are {}", | ||
| 178 | + SUPPORTED_SCOPES.join(" ") | ||
| 179 | + )); | ||
| 180 | + } | ||
| 181 | + if !scopes.contains(&word) { | ||
| 182 | + scopes.push(word); | ||
| 183 | + } | ||
| 184 | + } | ||
| 185 | + if scopes.is_empty() { | ||
| 186 | + return Err("--scopes must name at least one scope".into()); | ||
| 187 | + } | ||
| 188 | + Ok(scopes.join(" ")) | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// Prints one line per client: id, name, family key, scopes and status. No secret. | ||
| 192 | +async fn list(state: AppState) -> std::result::Result<(), String> { | ||
| 193 | + for client in state | ||
| 194 | + .store | ||
| 195 | + .list_clients() | ||
| 196 | + .await | ||
| 197 | + .map_err(|e| e.to_string())? | ||
| 198 | + { | ||
| 199 | + println!( | ||
| 200 | + "{}\t{}\t{}\t{}\t{}", | ||
| 201 | + client.id, | ||
| 202 | + client.name, | ||
| 203 | + client.service_key.as_deref().unwrap_or("-"), | ||
| 204 | + client.allowed_scopes, | ||
| 205 | + if client.is_disabled() { | ||
| 206 | + "disabled" | ||
| 207 | + } else { | ||
| 208 | + "active" | ||
| 209 | + }, | ||
| 210 | + ); | ||
| 211 | + } | ||
| 212 | + Ok(()) | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Disables a client: it cannot authenticate, so it cannot exchange codes or refresh. | ||
| 216 | +async fn disable(state: AppState, id: &str) -> std::result::Result<(), String> { | ||
| 217 | + if state | ||
| 218 | + .store | ||
| 219 | + .disable_client(id) | ||
| 220 | + .await | ||
| 221 | + .map_err(|e| e.to_string())? | ||
| 222 | + { | ||
| 223 | + println!("disabled {id}"); | ||
| 224 | + Ok(()) | ||
| 225 | + } else { | ||
| 226 | + Err(format!("no active client {id}")) | ||
| 227 | + } | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +#[cfg(test)] | ||
| 231 | +mod tests { | ||
| 232 | + use super::*; | ||
| 233 | + | ||
| 234 | + fn words(list: &[&str]) -> Vec<String> { | ||
| 235 | + list.iter().map(|word| (*word).to_owned()).collect() | ||
| 236 | + } | ||
| 237 | + | ||
| 238 | + #[test] | ||
| 239 | + fn redirect_uris_repeat_and_a_name_is_given_once() { | ||
| 240 | + let args = parse_add(&words(&[ | ||
| 241 | + "--name", | ||
| 242 | + "Files", | ||
| 243 | + "--redirect-uri", | ||
| 244 | + "https://a/cb", | ||
| 245 | + "--redirect-uri", | ||
| 246 | + "https://b/cb", | ||
| 247 | + ])) | ||
| 248 | + .expect("parse"); | ||
| 249 | + assert_eq!(args.redirect_uris.len(), 2); | ||
| 250 | + assert!(parse_add(&words(&["--name", "a", "--name", "b"])).is_err()); | ||
| 251 | + assert!(parse_add(&words(&["--name"])).is_err()); | ||
| 252 | + } | ||
| 253 | +} | ||
crates/im-web/src/i18n/mod.rsmodified+1 -0
| @@ -8,6 +8,7 @@ | |||
| 8 | //! helper functions next to their keys. | 8 | //! helper functions next to their keys. |
| 9 | 9 | ||
| 10 | pub mod account; | 10 | pub mod account; |
| 11 | +pub mod oidc; | ||
| 11 | pub mod shell; | 12 | pub mod shell; |
| 12 | 13 | ||
| 13 | use topcoat::context::Cx; | 14 | use topcoat::context::Cx; |
crates/im-web/src/i18n/oidc.rsadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +//! Strings of the provider's own page: the page shown when an authorization request cannot be | ||
| 2 | +//! answered at all (unknown or disabled client, or a redirect URI that is not registered). That page | ||
| 3 | +//! is never a redirect, so it is the only place these words appear. | ||
| 4 | + | ||
| 5 | +use super::Lang; | ||
| 6 | + | ||
| 7 | +/// One variant per phrase. Add a variant, then its English and Turkish texts in [`text`]. | ||
| 8 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 9 | +pub enum OidcText { | ||
| 10 | + /// The title of the error page. | ||
| 11 | + ErrorTitle, | ||
| 12 | + /// The sentence under the title. | ||
| 13 | + ErrorBody, | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/// The text of `key` in `lang`. | ||
| 17 | +pub fn text(lang: Lang, key: OidcText) -> &'static str { | ||
| 18 | + match (key, lang) { | ||
| 19 | + (OidcText::ErrorTitle, Lang::En) => "Sign-in cannot continue", | ||
| 20 | + (OidcText::ErrorTitle, Lang::Tr) => "Oturum açma devam edemiyor", | ||
| 21 | + (OidcText::ErrorBody, Lang::En) => { | ||
| 22 | + "This sign-in request is not valid. Go back to the application and try again." | ||
| 23 | + } | ||
| 24 | + (OidcText::ErrorBody, Lang::Tr) => { | ||
| 25 | + "Bu oturum açma isteği geçerli değil. Uygulamaya dönüp yeniden deneyin." | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | +} | ||
crates/im-web/src/main.rsmodified+6 -3
| @@ -1,17 +1,19 @@ | |||
| 1 | //! The `im` binary: the command line, logging and the process lifetime. | 1 | //! The `im` binary: the command line, logging and the process lifetime. |
| 2 | //! | 2 | //! |
| 3 | -//! `im [--config <path>] [serve]` runs the server; a bare `im` does the same. `im admin ...` is the | 3 | +//! `im [--config <path>] [serve]` runs the server; a bare `im` does the same. `im client ...` manages the |
| 4 | -//! operator command line, which is not built yet. The configuration file is the `--config` path, | 4 | +//! OpenID Connect clients (`cli.rs`). `im admin ...` is the operator command line, which is not built yet. The configuration file is the `--config` path, |
| 5 | //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | mod assets; | 7 | mod assets; |
| 8 | mod audit; | 8 | mod audit; |
| 9 | mod auth; | 9 | mod auth; |
| 10 | mod boot; | 10 | mod boot; |
| 11 | +mod cli; | ||
| 11 | mod client_ip; | 12 | mod client_ip; |
| 12 | mod health; | 13 | mod health; |
| 13 | mod i18n; | 14 | mod i18n; |
| 14 | mod live; | 15 | mod live; |
| 16 | +mod oidc; | ||
| 15 | mod pages; | 17 | mod pages; |
| 16 | mod security; | 18 | mod security; |
| 17 | mod state; | 19 | mod state; |
| @@ -24,7 +26,7 @@ use std::process::ExitCode; | |||
| 24 | use tracing_subscriber::EnvFilter; | 26 | use tracing_subscriber::EnvFilter; |
| 25 | 27 | ||
| 26 | /// Printed with a usage error. | 28 | /// Printed with a usage error. |
| 27 | -const USAGE: &str = "usage: im [--config <path>] [serve]"; | 29 | +const USAGE: &str = "usage: im [--config <path>] [serve | client <add|list|disable> ...]"; |
| 28 | 30 | ||
| 29 | /// The configuration file when neither `--config` nor `IM_CONFIG` names one. | 31 | /// The configuration file when neither `--config` nor `IM_CONFIG` names one. |
| 30 | const DEFAULT_CONFIG: &str = "config/im.toml"; | 32 | const DEFAULT_CONFIG: &str = "config/im.toml"; |
| @@ -93,6 +95,7 @@ async fn main() -> ExitCode { | |||
| 93 | let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); | 95 | let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); |
| 94 | match words.as_slice() { | 96 | match words.as_slice() { |
| 95 | [] | ["serve"] => serve(&config_path(cli.config)).await, | 97 | [] | ["serve"] => serve(&config_path(cli.config)).await, |
| 98 | + ["client", ..] => cli::client(&config_path(cli.config), &cli.words[1..]).await, | ||
| 96 | ["admin", ..] => { | 99 | ["admin", ..] => { |
| 97 | eprintln!("im: admin commands are not implemented yet"); | 100 | eprintln!("im: admin commands are not implemented yet"); |
| 98 | ExitCode::from(2) | 101 | ExitCode::from(2) |
crates/im-web/src/oidc/authorize.rsadded+238 -0
| @@ -0,0 +1,238 @@ | |||
| 1 | +//! `GET /authorize` (contracts section 2.3, steps 1 and 2): checks the request, signs the person in if | ||
| 2 | +//! needed, and redirects back with a one-time code. | ||
| 3 | +//! | ||
| 4 | +//! The order is fixed. First the client and the redirect URI are checked against the registration by | ||
| 5 | +//! exact string match; until both pass, nothing is redirected and the error page is shown. Then every | ||
| 6 | +//! other error goes to the registered redirect URI, with `error`, the `state` (only when it is usable) | ||
| 7 | +//! and `iss`. Only then is a session asked for. PKCE with S256 is mandatory, and `plain` is refused. | ||
| 8 | + | ||
| 9 | +use im_core::model::Client; | ||
| 10 | +use im_core::oauth::{MAX_ECHO_BYTES, is_supported_scope, is_user_scope, is_valid_challenge}; | ||
| 11 | +use im_core::store::oidc::NewAuthCode; | ||
| 12 | +use im_core::time::stamp_after; | ||
| 13 | +use im_core::token::{generate_token, hash_token}; | ||
| 14 | +use topcoat::Result; | ||
| 15 | +use topcoat::context::{Cx, app_context}; | ||
| 16 | +use topcoat::router::error::{SeeOther, see_other}; | ||
| 17 | +use topcoat::router::request::uri; | ||
| 18 | +use topcoat::router::{StatusCode, page}; | ||
| 19 | +use topcoat::view::{View, component, view}; | ||
| 20 | + | ||
| 21 | +use super::{CODE_TTL, Pairs, Single, issuer, one, parse_pairs, single, with_query}; | ||
| 22 | +use crate::auth::{current_user, percent_encode}; | ||
| 23 | +use crate::i18n::Lang; | ||
| 24 | +use crate::i18n::oidc::{OidcText, text}; | ||
| 25 | +use crate::state::AppState; | ||
| 26 | +use crate::views::{page_lang, shell}; | ||
| 27 | + | ||
| 28 | +/// What a request asks for, after the checks that need no database. | ||
| 29 | +struct Asked { | ||
| 30 | + /// The request's `state`, echoed back on every answer. | ||
| 31 | + state: Option<String>, | ||
| 32 | + /// The PKCE challenge, stored with the code. | ||
| 33 | + challenge: String, | ||
| 34 | + /// The nonce, stored with the code and written into the ID token. | ||
| 35 | + nonce: Option<String>, | ||
| 36 | + /// The granted scope: the request's scopes that are user scopes and that the client may ask for. | ||
| 37 | + scope: String, | ||
| 38 | + /// True for `prompt=none`: no page may be shown, only a result. | ||
| 39 | + no_prompt: bool, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// A refusal that goes to the redirect URI. `state` is set only when the state was usable. | ||
| 43 | +struct Refused { | ||
| 44 | + code: &'static str, | ||
| 45 | + state: Option<String>, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// True when a `state` or `nonce` may be echoed: short enough and free of control characters. | ||
| 49 | +fn usable_echo(value: &str) -> bool { | ||
| 50 | + value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control) | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Checks everything in the query that does not need a session. Returns what was asked, or the refusal | ||
| 54 | +/// to send to the redirect URI. | ||
| 55 | +fn read(pairs: &Pairs, client: &Client) -> std::result::Result<Asked, Refused> { | ||
| 56 | + let state = match single(pairs, "state") { | ||
| 57 | + Single::Absent => None, | ||
| 58 | + Single::One(value) if usable_echo(value) => Some(value.to_owned()), | ||
| 59 | + // A state that cannot be echoed is refused without echoing it. | ||
| 60 | + _ => { | ||
| 61 | + return Err(Refused { | ||
| 62 | + code: "invalid_request", | ||
| 63 | + state: None, | ||
| 64 | + }); | ||
| 65 | + } | ||
| 66 | + }; | ||
| 67 | + let refuse = |code: &'static str| Refused { | ||
| 68 | + code, | ||
| 69 | + state: state.clone(), | ||
| 70 | + }; | ||
| 71 | + for name in [ | ||
| 72 | + "response_type", | ||
| 73 | + "code_challenge", | ||
| 74 | + "code_challenge_method", | ||
| 75 | + "nonce", | ||
| 76 | + "scope", | ||
| 77 | + "prompt", | ||
| 78 | + ] { | ||
| 79 | + if single(pairs, name) == Single::Repeated { | ||
| 80 | + return Err(refuse("invalid_request")); | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + match single(pairs, "response_type") { | ||
| 84 | + Single::One("code") => {} | ||
| 85 | + Single::One(_) => return Err(refuse("unsupported_response_type")), | ||
| 86 | + _ => return Err(refuse("invalid_request")), | ||
| 87 | + } | ||
| 88 | + let challenge = match single(pairs, "code_challenge") { | ||
| 89 | + Single::One(value) if is_valid_challenge(value) => value.to_owned(), | ||
| 90 | + _ => return Err(refuse("invalid_request")), | ||
| 91 | + }; | ||
| 92 | + // `plain` and a missing method are refused: PKCE S256 is mandatory (contracts section 2.3). | ||
| 93 | + if single(pairs, "code_challenge_method") != Single::One("S256") { | ||
| 94 | + return Err(refuse("invalid_request")); | ||
| 95 | + } | ||
| 96 | + let nonce = match single(pairs, "nonce") { | ||
| 97 | + Single::Absent => None, | ||
| 98 | + Single::One(value) if usable_echo(value) => Some(value.to_owned()), | ||
| 99 | + _ => return Err(refuse("invalid_request")), | ||
| 100 | + }; | ||
| 101 | + let Single::One(requested) = single(pairs, "scope") else { | ||
| 102 | + return Err(refuse("invalid_request")); | ||
| 103 | + }; | ||
| 104 | + let mut granted: Vec<&str> = Vec::new(); | ||
| 105 | + for word in requested.split_whitespace() { | ||
| 106 | + if !is_supported_scope(word) { | ||
| 107 | + return Err(refuse("invalid_scope")); | ||
| 108 | + } | ||
| 109 | + if is_user_scope(word) && client.allows_scope(word) && !granted.contains(&word) { | ||
| 110 | + granted.push(word); | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + if !granted.contains(&"openid") { | ||
| 114 | + return Err(refuse("invalid_scope")); | ||
| 115 | + } | ||
| 116 | + let no_prompt = match single(pairs, "prompt") { | ||
| 117 | + Single::Absent => false, | ||
| 118 | + Single::One(value) => match value.split_whitespace().collect::<Vec<_>>().as_slice() { | ||
| 119 | + [] => false, | ||
| 120 | + ["none"] => true, | ||
| 121 | + // Re-authentication and consent prompts are not offered; say so instead of ignoring them. | ||
| 122 | + _ => return Err(refuse("invalid_request")), | ||
| 123 | + }, | ||
| 124 | + Single::Repeated => return Err(refuse("invalid_request")), | ||
| 125 | + }; | ||
| 126 | + Ok(Asked { | ||
| 127 | + state, | ||
| 128 | + challenge, | ||
| 129 | + nonce, | ||
| 130 | + scope: granted.join(" "), | ||
| 131 | + no_prompt, | ||
| 132 | + }) | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// The redirect that carries a refusal to the client. | ||
| 136 | +fn refusal_redirect(redirect_uri: &str, issuer: &str, refused: &Refused) -> SeeOther { | ||
| 137 | + let mut params = vec![("error", refused.code), ("iss", issuer)]; | ||
| 138 | + if let Some(state) = refused.state.as_deref() { | ||
| 139 | + params.push(("state", state)); | ||
| 140 | + } | ||
| 141 | + see_other(with_query(redirect_uri, ¶ms)) | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/// `GET /authorize`. | ||
| 145 | +/// | ||
| 146 | +/// Every answer is either a redirect (`Err` carrying a `SeeOther`) or the error page, which is the only | ||
| 147 | +/// `Ok` value. A request with an unknown client or an unregistered redirect URI never reaches a | ||
| 148 | +/// redirect. | ||
| 149 | +#[page(GET "/authorize")] | ||
| 150 | +async fn authorize(cx: &Cx) -> Result<impl View> { | ||
| 151 | + let app = app_context::<AppState>(cx); | ||
| 152 | + let lang = page_lang(cx, None); | ||
| 153 | + let Some(pairs) = parse_pairs(uri(cx).query().unwrap_or_default().as_bytes()) else { | ||
| 154 | + return Ok(error_page(cx, lang)); | ||
| 155 | + }; | ||
| 156 | + let Some(client_id) = one(&pairs, "client_id") else { | ||
| 157 | + return Ok(error_page(cx, lang)); | ||
| 158 | + }; | ||
| 159 | + let Some(redirect_uri) = one(&pairs, "redirect_uri") else { | ||
| 160 | + return Ok(error_page(cx, lang)); | ||
| 161 | + }; | ||
| 162 | + let client = match app.store.client_by_id(client_id).await? { | ||
| 163 | + Some(client) | ||
| 164 | + if !client.is_disabled() | ||
| 165 | + && client | ||
| 166 | + .redirect_uris | ||
| 167 | + .iter() | ||
| 168 | + .any(|registered| registered == redirect_uri) => | ||
| 169 | + { | ||
| 170 | + client | ||
| 171 | + } | ||
| 172 | + _ => return Ok(error_page(cx, lang)), | ||
| 173 | + }; | ||
| 174 | + | ||
| 175 | + // From here on the redirect URI is the registered one, so every refusal may go to it. | ||
| 176 | + let issuer = issuer(app); | ||
| 177 | + let asked = match read(&pairs, &client) { | ||
| 178 | + Ok(asked) => asked, | ||
| 179 | + Err(refused) => return Err(refusal_redirect(redirect_uri, issuer, &refused).into()), | ||
| 180 | + }; | ||
| 181 | + let Some(viewer) = current_user(cx).await? else { | ||
| 182 | + if asked.no_prompt { | ||
| 183 | + let refused = Refused { | ||
| 184 | + code: "login_required", | ||
| 185 | + state: asked.state.clone(), | ||
| 186 | + }; | ||
| 187 | + return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); | ||
| 188 | + } | ||
| 189 | + // Back to this exact request after sign-in: the login page checks `next` as a local path. | ||
| 190 | + let back = uri(cx) | ||
| 191 | + .path_and_query() | ||
| 192 | + .map_or("/authorize", |p| p.as_str()); | ||
| 193 | + return Err(see_other(format!("/login?next={}", percent_encode(back))).into()); | ||
| 194 | + }; | ||
| 195 | + | ||
| 196 | + let code = generate_token(); | ||
| 197 | + let expires_at = stamp_after(CODE_TTL); | ||
| 198 | + app.store | ||
| 199 | + .insert_auth_code(&NewAuthCode { | ||
| 200 | + code_hash: &hash_token(&code), | ||
| 201 | + client_id: &client.id, | ||
| 202 | + user_id: &viewer.user.id, | ||
| 203 | + session_id: &viewer.session.id, | ||
| 204 | + redirect_uri, | ||
| 205 | + scope: &asked.scope, | ||
| 206 | + nonce: asked.nonce.as_deref(), | ||
| 207 | + code_challenge: &asked.challenge, | ||
| 208 | + expires_at: &expires_at, | ||
| 209 | + }) | ||
| 210 | + .await?; | ||
| 211 | + app.store | ||
| 212 | + .touch_client_session(&viewer.session.id, &client.id) | ||
| 213 | + .await?; | ||
| 214 | + | ||
| 215 | + let mut params = vec![("code", code.as_str()), ("iss", issuer)]; | ||
| 216 | + if let Some(state) = asked.state.as_deref() { | ||
| 217 | + params.push(("state", state)); | ||
| 218 | + } | ||
| 219 | + Err(see_other(with_query(redirect_uri, ¶ms)).into()) | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +/// The error page: a 400 in the shell, with no redirect and no detail about the request. | ||
| 223 | +fn error_page(cx: &Cx, lang: Lang) -> impl View { | ||
| 224 | + view! { cx => | ||
| 225 | + (StatusCode::BAD_REQUEST) | ||
| 226 | + shell(title: text(lang, OidcText::ErrorTitle), lang: lang, viewer: None, error_body(lang: lang)) | ||
| 227 | + } | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +/// The body of the error page. | ||
| 231 | +#[component] | ||
| 232 | +async fn error_body(lang: Lang) -> Result<impl View> { | ||
| 233 | + Ok(view! { | ||
| 234 | + <section class="not-found"> | ||
| 235 | + <p>(text(lang, OidcText::ErrorBody))</p> | ||
| 236 | + </section> | ||
| 237 | + }) | ||
| 238 | +} | ||
crates/im-web/src/oidc/discovery.rsadded+80 -0
| @@ -0,0 +1,80 @@ | |||
| 1 | +//! `GET /.well-known/openid-configuration` and `GET /jwks.json` (contracts sections 2.1 and 2.2). | ||
| 2 | +//! | ||
| 3 | +//! Both are public and cacheable for five minutes. Discovery lists the endpoints under the issuer; | ||
| 4 | +//! the key set publishes every key that is active, pending or retired within the overlap period. | ||
| 5 | + | ||
| 6 | +use im_core::jwt; | ||
| 7 | +use topcoat::Result; | ||
| 8 | +use topcoat::context::{Cx, app_context}; | ||
| 9 | +use topcoat::router::response::Response; | ||
| 10 | +use topcoat::router::{HeaderValue, StatusCode, header, route}; | ||
| 11 | + | ||
| 12 | +use super::signing; | ||
| 13 | +use super::{PUBLIC_CACHE, issuer, json_response}; | ||
| 14 | +use crate::state::AppState; | ||
| 15 | + | ||
| 16 | +/// The grant types this provider offers. `client_credentials` is listed as the contracts require; it is | ||
| 17 | +/// answered once the machine-token part is built. | ||
| 18 | +const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"]; | ||
| 19 | + | ||
| 20 | +/// The client authentication methods of `/token`, `/revoke` and `/introspect`. | ||
| 21 | +const AUTH_METHODS: [&str; 2] = ["client_secret_basic", "client_secret_post"]; | ||
| 22 | + | ||
| 23 | +/// The scopes this provider advertises. | ||
| 24 | +const SCOPES: [&str; 5] = [ | ||
| 25 | + "openid", | ||
| 26 | + "profile", | ||
| 27 | + "email", | ||
| 28 | + "directory.read", | ||
| 29 | + "files.service", | ||
| 30 | +]; | ||
| 31 | + | ||
| 32 | +/// `GET /.well-known/openid-configuration`. | ||
| 33 | +#[route(GET "/.well-known/openid-configuration")] | ||
| 34 | +async fn discovery(cx: &Cx) -> topcoat::Result<Response> { | ||
| 35 | + let base = issuer(app_context::<AppState>(cx)); | ||
| 36 | + let document = serde_json::json!({ | ||
| 37 | + "issuer": base, | ||
| 38 | + "authorization_endpoint": format!("{base}/authorize"), | ||
| 39 | + "token_endpoint": format!("{base}/token"), | ||
| 40 | + "userinfo_endpoint": format!("{base}/userinfo"), | ||
| 41 | + "jwks_uri": format!("{base}/jwks.json"), | ||
| 42 | + "end_session_endpoint": format!("{base}/logout"), | ||
| 43 | + "revocation_endpoint": format!("{base}/revoke"), | ||
| 44 | + "introspection_endpoint": format!("{base}/introspect"), | ||
| 45 | + "response_types_supported": ["code"], | ||
| 46 | + "grant_types_supported": GRANT_TYPES, | ||
| 47 | + "subject_types_supported": ["public"], | ||
| 48 | + "code_challenge_methods_supported": ["S256"], | ||
| 49 | + "id_token_signing_alg_values_supported": [jwt::ALG], | ||
| 50 | + "token_endpoint_auth_methods_supported": AUTH_METHODS, | ||
| 51 | + "backchannel_logout_supported": true, | ||
| 52 | + "backchannel_logout_session_supported": true, | ||
| 53 | + "scopes_supported": SCOPES, | ||
| 54 | + }); | ||
| 55 | + Ok(cacheable(json_response(StatusCode::OK, &document))) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// `GET /jwks.json`: the published public keys as an OKP/Ed25519 JWK set. | ||
| 59 | +#[route(GET "/jwks.json")] | ||
| 60 | +async fn jwks(cx: &Cx) -> Result<Response> { | ||
| 61 | + let app = app_context::<AppState>(cx); | ||
| 62 | + let keys = signing::published_keys(&app.store).await?; | ||
| 63 | + let set: Vec<serde_json::Value> = keys | ||
| 64 | + .iter() | ||
| 65 | + .map(|key| jwt::jwk(&key.kid, &key.public_raw)) | ||
| 66 | + .collect(); | ||
| 67 | + Ok(cacheable(json_response( | ||
| 68 | + StatusCode::OK, | ||
| 69 | + &serde_json::json!({ "keys": set }), | ||
| 70 | + ))) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Sets the short public cache policy on an answer that is not secret. | ||
| 74 | +fn cacheable(mut response: Response) -> Response { | ||
| 75 | + response.headers_mut().insert( | ||
| 76 | + header::CACHE_CONTROL, | ||
| 77 | + HeaderValue::from_static(PUBLIC_CACHE), | ||
| 78 | + ); | ||
| 79 | + response | ||
| 80 | +} | ||
crates/im-web/src/oidc/mod.rsadded+172 -0
| @@ -0,0 +1,172 @@ | |||
| 1 | +//! The OpenID Connect provider of `im` (`docs/contracts.md` section 2): discovery, the signing keys, | ||
| 2 | +//! the authorization endpoint, the token endpoint and userinfo. | ||
| 3 | +//! | ||
| 4 | +//! Who may sign in is decided by the browser session (`auth.rs`); every endpoint here asks the store | ||
| 5 | +//! and never decides it alone. This module holds what the endpoints share: the token lifetimes, the | ||
| 6 | +//! JSON and OAuth error answers, the query and form parsing, and the URL builder for redirects. | ||
| 7 | + | ||
| 8 | +pub mod authorize; | ||
| 9 | +pub mod discovery; | ||
| 10 | +pub mod signing; | ||
| 11 | +pub mod token; | ||
| 12 | +pub mod userinfo; | ||
| 13 | + | ||
| 14 | +#[cfg(test)] | ||
| 15 | +mod tests; | ||
| 16 | + | ||
| 17 | +use std::time::Duration; | ||
| 18 | + | ||
| 19 | +use http::header::{CACHE_CONTROL, CONTENT_TYPE, PRAGMA, WWW_AUTHENTICATE}; | ||
| 20 | +use serde_json::Value; | ||
| 21 | +use topcoat::router::content::Form; | ||
| 22 | +use topcoat::router::response::Response; | ||
| 23 | +use topcoat::router::{Body, HeaderValue, StatusCode}; | ||
| 24 | + | ||
| 25 | +use crate::state::AppState; | ||
| 26 | + | ||
| 27 | +/// Lifetime of an authorization code (contracts section 2.3: 60 seconds, single use). | ||
| 28 | +pub const CODE_TTL: Duration = Duration::from_secs(60); | ||
| 29 | + | ||
| 30 | +/// Lifetime of an access token (contracts section 2.3: 10 minutes). | ||
| 31 | +pub const ACCESS_TTL: Duration = Duration::from_secs(10 * 60); | ||
| 32 | + | ||
| 33 | +/// Lifetime of an ID token. | ||
| 34 | +pub const ID_TOKEN_TTL: Duration = Duration::from_secs(10 * 60); | ||
| 35 | + | ||
| 36 | +/// Lifetime of a refresh token, unless its session ends first. | ||
| 37 | +pub const REFRESH_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); | ||
| 38 | + | ||
| 39 | +/// The largest form body the token endpoint reads, in bytes (task: 16 KiB). | ||
| 40 | +pub const TOKEN_BODY_LIMIT: usize = 16 * 1024; | ||
| 41 | + | ||
| 42 | +/// The audience of a user's access token: this provider's own userinfo endpoint, named by its family | ||
| 43 | +/// key. A machine token's audience is the target service instead (contracts section 2.6). | ||
| 44 | +pub const USERINFO_AUDIENCE: &str = "im"; | ||
| 45 | + | ||
| 46 | +/// Cache policy of the discovery document and the key set. Short, so a key change is seen soon. | ||
| 47 | +pub const PUBLIC_CACHE: &str = "public, max-age=300"; | ||
| 48 | + | ||
| 49 | +/// The issuer: the public origin with no trailing slash (`config.base_url`, validated at boot). | ||
| 50 | +pub fn issuer(app: &AppState) -> &str { | ||
| 51 | + &app.config.base_url | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// A JSON answer with `status` and no caching. | ||
| 55 | +pub fn json_response(status: StatusCode, body: &Value) -> Response { | ||
| 56 | + let mut response = Response::new(Body::from(body.to_string())); | ||
| 57 | + *response.status_mut() = status; | ||
| 58 | + let headers = response.headers_mut(); | ||
| 59 | + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 60 | + headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); | ||
| 61 | + headers.insert(PRAGMA, HeaderValue::from_static("no-cache")); | ||
| 62 | + response | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// An OAuth error at the token endpoint or another RFC 6749 endpoint (section 5.2). | ||
| 66 | +pub fn oauth_error(status: StatusCode, code: &str) -> Response { | ||
| 67 | + json_response(status, &serde_json::json!({ "error": code })) | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// `invalid_client`: 401 with a Basic challenge (RFC 6749 section 5.2). | ||
| 71 | +pub fn invalid_client() -> Response { | ||
| 72 | + let mut response = oauth_error(StatusCode::UNAUTHORIZED, "invalid_client"); | ||
| 73 | + response.headers_mut().insert( | ||
| 74 | + WWW_AUTHENTICATE, | ||
| 75 | + HeaderValue::from_static("Basic realm=\"im\""), | ||
| 76 | + ); | ||
| 77 | + response | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// `invalid_grant`: the code or token is not usable. One answer for every reason, so the reason is | ||
| 81 | +/// not disclosed. | ||
| 82 | +pub fn invalid_grant() -> Response { | ||
| 83 | + oauth_error(StatusCode::BAD_REQUEST, "invalid_grant") | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// The name and value pairs of a query string or a form body, in order. Repeats are kept. | ||
| 87 | +pub type Pairs = Vec<(String, String)>; | ||
| 88 | + | ||
| 89 | +/// Parses a query string or a form body. `None` when it is not valid URL-encoded data. | ||
| 90 | +pub fn parse_pairs(bytes: &[u8]) -> Option<Pairs> { | ||
| 91 | + Form::<Pairs>::from_bytes(bytes).ok().map(|form| form.0) | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// How often a parameter occurs. | ||
| 95 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 96 | +pub enum Single<'a> { | ||
| 97 | + /// Not present. | ||
| 98 | + Absent, | ||
| 99 | + /// Present exactly once. | ||
| 100 | + One(&'a str), | ||
| 101 | + /// Present more than once. Refused by every endpoint. | ||
| 102 | + Repeated, | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// How often `name` occurs in `pairs`. | ||
| 106 | +pub fn single<'a>(pairs: &'a [(String, String)], name: &str) -> Single<'a> { | ||
| 107 | + let mut values = pairs | ||
| 108 | + .iter() | ||
| 109 | + .filter(|(key, _)| key == name) | ||
| 110 | + .map(|(_, value)| value.as_str()); | ||
| 111 | + match (values.next(), values.next()) { | ||
| 112 | + (None, _) => Single::Absent, | ||
| 113 | + (Some(value), None) => Single::One(value), | ||
| 114 | + _ => Single::Repeated, | ||
| 115 | + } | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// The value of `name` when it occurs exactly once. | ||
| 119 | +pub fn one<'a>(pairs: &'a [(String, String)], name: &str) -> Option<&'a str> { | ||
| 120 | + match single(pairs, name) { | ||
| 121 | + Single::One(value) => Some(value), | ||
| 122 | + _ => None, | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// Percent-encodes a query or form value: every byte except the RFC 3986 unreserved set. | ||
| 127 | +pub fn encode_value(value: &str) -> String { | ||
| 128 | + let mut out = String::with_capacity(value.len()); | ||
| 129 | + for byte in value.bytes() { | ||
| 130 | + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { | ||
| 131 | + out.push(char::from(byte)); | ||
| 132 | + } else { | ||
| 133 | + out.push_str(&format!("%{byte:02X}")); | ||
| 134 | + } | ||
| 135 | + } | ||
| 136 | + out | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Decodes `%XX` escapes. `None` for a bad escape or for bytes that are not UTF-8 once decoded. | ||
| 140 | +pub fn percent_decode(input: &str) -> Option<String> { | ||
| 141 | + let bytes = input.as_bytes(); | ||
| 142 | + let mut out = Vec::with_capacity(bytes.len()); | ||
| 143 | + let mut i = 0; | ||
| 144 | + while i < bytes.len() { | ||
| 145 | + if bytes[i] == b'%' { | ||
| 146 | + let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?; | ||
| 147 | + out.push(u8::from_str_radix(hex, 16).ok()?); | ||
| 148 | + i += 3; | ||
| 149 | + } else { | ||
| 150 | + out.push(bytes[i]); | ||
| 151 | + i += 1; | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + String::from_utf8(out).ok() | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// Appends `params` to a redirect URI as a query, encoding every name and value. The registered URI | ||
| 158 | +/// has no fragment (checked at registration), so the query goes at its end. | ||
| 159 | +pub fn with_query(uri: &str, params: &[(&str, &str)]) -> String { | ||
| 160 | + let separator = if uri.ends_with(['?', '&']) { | ||
| 161 | + "" | ||
| 162 | + } else if uri.contains('?') { | ||
| 163 | + "&" | ||
| 164 | + } else { | ||
| 165 | + "?" | ||
| 166 | + }; | ||
| 167 | + let query: Vec<String> = params | ||
| 168 | + .iter() | ||
| 169 | + .map(|(name, value)| format!("{}={}", encode_value(name), encode_value(value))) | ||
| 170 | + .collect(); | ||
| 171 | + format!("{uri}{separator}{}", query.join("&")) | ||
| 172 | +} | ||
crates/im-web/src/oidc/signing.rsadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +//! The signing keys at run time: the key that signs now, the keys that are published now, the seal of | ||
| 2 | +//! each private key, and the worker that keeps the chain of keys up to date. | ||
| 3 | +//! | ||
| 4 | +//! The private seed is opened for one signature and dropped; it is never kept in a field or a cache. | ||
| 5 | +//! The worker runs at boot and then daily (architecture section 8). Rotation is due after 90 days and | ||
| 6 | +//! the successor is created a day ahead, so it is published before it signs. | ||
| 7 | + | ||
| 8 | +use std::sync::Arc; | ||
| 9 | +use std::time::Duration; | ||
| 10 | + | ||
| 11 | +use im_core::jwt; | ||
| 12 | +use im_core::keys::{self, OVERLAP}; | ||
| 13 | +use im_core::model::KeyRecord; | ||
| 14 | +use im_core::secret; | ||
| 15 | +use im_core::store::Store; | ||
| 16 | +use im_core::time::{now_stamp, stamp_minus}; | ||
| 17 | +use serde_json::Value; | ||
| 18 | +use tokio::sync::watch; | ||
| 19 | + | ||
| 20 | +/// How often the worker checks the chain of keys. | ||
| 21 | +const CHECK_EVERY: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 22 | + | ||
| 23 | +/// Makes sure the chain is current: creates the first key when there is none, and creates the successor | ||
| 24 | +/// when the newest key is due within the publish lead. Then removes keys retired more than [`OVERLAP`] | ||
| 25 | +/// ago. Idempotent; safe to run at every boot. | ||
| 26 | +pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<()> { | ||
| 27 | + let rows = store.signing_keys().await?; | ||
| 28 | + let now = now_stamp(); | ||
| 29 | + if let Some(activates_at) = keys::next_activation(&rows, &now) { | ||
| 30 | + let fresh = keys::generate(); | ||
| 31 | + let record = KeyRecord { | ||
| 32 | + kid: fresh.kid.clone(), | ||
| 33 | + private_sealed: secret::seal(instance_key, &fresh.seed)?, | ||
| 34 | + public_raw: fresh.public.to_vec(), | ||
| 35 | + created_at: now.clone(), | ||
| 36 | + activates_at: activates_at.clone(), | ||
| 37 | + retires_at: None, | ||
| 38 | + }; | ||
| 39 | + store.add_signing_key(&record).await?; | ||
| 40 | + tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); | ||
| 41 | + } | ||
| 42 | + let cutoff = stamp_minus(&now, OVERLAP).unwrap_or_else(|| now.clone()); | ||
| 43 | + let pruned = store.prune_signing_keys(&cutoff).await?; | ||
| 44 | + if pruned > 0 { | ||
| 45 | + tracing::info!(pruned, "retired signing keys removed"); | ||
| 46 | + } | ||
| 47 | + Ok(()) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// Runs [`maintain`] daily until `stop` is set. Failures are logged; the next run tries again. | ||
| 51 | +pub fn spawn( | ||
| 52 | + store: Store, | ||
| 53 | + instance_key: Arc<[u8; 32]>, | ||
| 54 | + mut stop: watch::Receiver<bool>, | ||
| 55 | +) -> tokio::task::JoinHandle<()> { | ||
| 56 | + tokio::spawn(async move { | ||
| 57 | + loop { | ||
| 58 | + tokio::select! { | ||
| 59 | + () = tokio::time::sleep(CHECK_EVERY) => {} | ||
| 60 | + _ = stop.wait_for(|stopped| *stopped) => break, | ||
| 61 | + } | ||
| 62 | + if let Err(error) = maintain(&store, &instance_key).await { | ||
| 63 | + tracing::error!(error = %error, "signing key maintenance failed"); | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | + }) | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// The keys published now, for the JWKS document and for verifying tokens. | ||
| 70 | +pub async fn published_keys(store: &Store) -> im_core::Result<Vec<KeyRecord>> { | ||
| 71 | + let rows = store.signing_keys().await?; | ||
| 72 | + Ok(keys::published(&rows, &now_stamp()) | ||
| 73 | + .into_iter() | ||
| 74 | + .cloned() | ||
| 75 | + .collect()) | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// Signs `claims` with the key that is current now. | ||
| 79 | +pub async fn sign( | ||
| 80 | + store: &Store, | ||
| 81 | + instance_key: &[u8; 32], | ||
| 82 | + claims: &Value, | ||
| 83 | +) -> im_core::Result<String> { | ||
| 84 | + let rows = store.signing_keys().await?; | ||
| 85 | + let record = keys::current(&rows, &now_stamp()) | ||
| 86 | + .ok_or_else(|| im_core::Error::Crypto("no signing key is active".into()))?; | ||
| 87 | + let seed = seed_of(instance_key, record)?; | ||
| 88 | + Ok(jwt::sign_with_seed(&seed, &record.kid, claims)) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// Opens the sealed seed of a key row. | ||
| 92 | +fn seed_of(instance_key: &[u8; 32], record: &KeyRecord) -> im_core::Result<[u8; 32]> { | ||
| 93 | + let bytes = secret::open(instance_key, &record.private_sealed)?; | ||
| 94 | + <[u8; 32]>::try_from(bytes.as_slice()) | ||
| 95 | + .map_err(|_| im_core::Error::Crypto("signing key has the wrong length".into())) | ||
| 96 | +} | ||
crates/im-web/src/oidc/tests.rsadded+317 -0
| @@ -0,0 +1,317 @@ | |||
| 1 | +//! End-to-end tests of the provider through the router: the redirect rules, PKCE, code and refresh | ||
| 2 | +//! reuse, client binding, and the ID token checked against the published key set. | ||
| 3 | + | ||
| 4 | +use std::time::Duration; | ||
| 5 | + | ||
| 6 | +use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 7 | +use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, LOCATION}; | ||
| 8 | +use im_core::jwt::{self, PublishedKey}; | ||
| 9 | +use im_core::model::Client; | ||
| 10 | +use im_core::oauth::pkce_s256; | ||
| 11 | +use im_core::password::hash_password; | ||
| 12 | +use im_core::store::clients::NewClient; | ||
| 13 | +use im_core::store::sessions::{NewSession, SESSION_IDLE}; | ||
| 14 | +use im_core::token::{generate_token, hash_token}; | ||
| 15 | +use serde_json::Value; | ||
| 16 | +use topcoat::router::response::Response; | ||
| 17 | +use topcoat::router::{Body, StatusCode, to_bytes}; | ||
| 18 | + | ||
| 19 | +use super::{encode_value, one, parse_pairs}; | ||
| 20 | +use crate::boot::{router, test_state}; | ||
| 21 | +use crate::state::AppState; | ||
| 22 | + | ||
| 23 | +/// The registered redirect URI of the test client. | ||
| 24 | +const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback"; | ||
| 25 | + | ||
| 26 | +/// The cookie name the browser sends: the `__Host-` prefix is added by the jar. | ||
| 27 | +const SESSION_COOKIE: &str = "__Host-im_session"; | ||
| 28 | + | ||
| 29 | +/// A client with a secret, a person, and a live browser session of that person. | ||
| 30 | +struct Fixture { | ||
| 31 | + _dir: tempfile::TempDir, | ||
| 32 | + state: AppState, | ||
| 33 | + client: Client, | ||
| 34 | + secret: String, | ||
| 35 | + user_id: String, | ||
| 36 | + cookie: String, | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +async fn fixture() -> Fixture { | ||
| 40 | + let (dir, state) = test_state().await; | ||
| 41 | + crate::oidc::signing::maintain(&state.store, &state.key) | ||
| 42 | + .await | ||
| 43 | + .expect("signing key"); | ||
| 44 | + let secret = generate_token(); | ||
| 45 | + let uris = vec![REDIRECT.to_owned()]; | ||
| 46 | + let client = state | ||
| 47 | + .store | ||
| 48 | + .create_client(&NewClient { | ||
| 49 | + name: "Files", | ||
| 50 | + secret_hash: &hash_token(&secret), | ||
| 51 | + redirect_uris: &uris, | ||
| 52 | + post_logout_redirect_uris: &[], | ||
| 53 | + backchannel_logout_uri: None, | ||
| 54 | + allowed_scopes: "openid profile email", | ||
| 55 | + service_key: Some("in"), | ||
| 56 | + }) | ||
| 57 | + .await | ||
| 58 | + .expect("client"); | ||
| 59 | + let hash = hash_password("the current password").expect("hash"); | ||
| 60 | + let user = state | ||
| 61 | + .store | ||
| 62 | + .create_user("ada@example.com", "Ada", &hash, false) | ||
| 63 | + .await | ||
| 64 | + .expect("user"); | ||
| 65 | + let cookie = generate_token(); | ||
| 66 | + state | ||
| 67 | + .store | ||
| 68 | + .create_session( | ||
| 69 | + &NewSession { | ||
| 70 | + user_id: &user.id, | ||
| 71 | + token_hash: &hash_token(&cookie), | ||
| 72 | + csrf_token: &generate_token(), | ||
| 73 | + amr: "pwd", | ||
| 74 | + ip: None, | ||
| 75 | + user_agent: None, | ||
| 76 | + idle: SESSION_IDLE, | ||
| 77 | + max_age: Duration::from_secs(3600), | ||
| 78 | + }, | ||
| 79 | + 10, | ||
| 80 | + ) | ||
| 81 | + .await | ||
| 82 | + .expect("session"); | ||
| 83 | + Fixture { | ||
| 84 | + _dir: dir, | ||
| 85 | + state, | ||
| 86 | + client, | ||
| 87 | + secret, | ||
| 88 | + user_id: user.id, | ||
| 89 | + cookie, | ||
| 90 | + } | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// Sends a request through the whole router and returns the status, headers and body text. | ||
| 94 | +async fn send( | ||
| 95 | + state: &AppState, | ||
| 96 | + request: http::Request<Body>, | ||
| 97 | +) -> (StatusCode, http::HeaderMap, String) { | ||
| 98 | + let response: Response = router(state.clone()).handle(request).await; | ||
| 99 | + let status = response.status(); | ||
| 100 | + let headers = response.headers().clone(); | ||
| 101 | + let bytes = to_bytes(response.into_body(), 1024 * 1024) | ||
| 102 | + .await | ||
| 103 | + .expect("body"); | ||
| 104 | + ( | ||
| 105 | + status, | ||
| 106 | + headers, | ||
| 107 | + String::from_utf8_lossy(&bytes).into_owned(), | ||
| 108 | + ) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// The `/authorize` path for a request, with the given method and challenge. | ||
| 112 | +fn authorize_path(client_id: &str, redirect: &str, challenge: &str, method: &str) -> String { | ||
| 113 | + format!( | ||
| 114 | + "/authorize?response_type=code&client_id={client_id}&redirect_uri={}\ | ||
| 115 | + &scope=openid%20profile%20email&state=s1&nonce=n1&code_challenge={challenge}\ | ||
| 116 | + &code_challenge_method={method}", | ||
| 117 | + encode_value(redirect) | ||
| 118 | + ) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Runs `/authorize` as the signed-in person and returns the code from the redirect. | ||
| 122 | +async fn code_for(f: &Fixture, client: &Client, verifier: &str) -> String { | ||
| 123 | + let path = authorize_path(&client.id, REDIRECT, &pkce_s256(verifier), "S256"); | ||
| 124 | + let request = http::Request::get(path) | ||
| 125 | + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) | ||
| 126 | + .body(Body::empty()) | ||
| 127 | + .expect("request"); | ||
| 128 | + let (status, headers, _) = send(&f.state, request).await; | ||
| 129 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 130 | + let location = headers[LOCATION].to_str().expect("location").to_owned(); | ||
| 131 | + assert!(location.starts_with(&format!("{REDIRECT}?")), "{location}"); | ||
| 132 | + let query = location.split_once('?').expect("query").1; | ||
| 133 | + let pairs = parse_pairs(query.as_bytes()).expect("pairs"); | ||
| 134 | + assert_eq!(one(&pairs, "state"), Some("s1")); | ||
| 135 | + assert_eq!(one(&pairs, "iss"), Some(f.state.config.base_url.as_str())); | ||
| 136 | + one(&pairs, "code").expect("code").to_owned() | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Posts a form to `/token` with `client_secret_basic` for `client`. | ||
| 140 | +async fn token_with(f: &Fixture, client: &Client, secret: &str, body: &str) -> (StatusCode, Value) { | ||
| 141 | + let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret)); | ||
| 142 | + let request = http::Request::post("/token") | ||
| 143 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 144 | + .header(AUTHORIZATION, format!("Basic {basic}")) | ||
| 145 | + .body(Body::from(body.to_owned())) | ||
| 146 | + .expect("request"); | ||
| 147 | + let (status, _, text) = send(&f.state, request).await; | ||
| 148 | + (status, serde_json::from_str(&text).unwrap_or(Value::Null)) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// The form body of an authorization-code exchange. | ||
| 152 | +fn code_body(code: &str, verifier: &str) -> String { | ||
| 153 | + format!( | ||
| 154 | + "grant_type=authorization_code&code={code}&redirect_uri={}&code_verifier={verifier}", | ||
| 155 | + encode_value(REDIRECT) | ||
| 156 | + ) | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +#[tokio::test] | ||
| 160 | +async fn an_unregistered_redirect_uri_is_never_redirected_to() { | ||
| 161 | + let f = fixture().await; | ||
| 162 | + let challenge = pkce_s256(&generate_token()); | ||
| 163 | + for bad in [ | ||
| 164 | + "http://127.0.0.1:17651/auth/callback/evil", | ||
| 165 | + "http://127.0.0.1:17651/auth/callback/", | ||
| 166 | + "http://127.0.0.1:17651/Auth/callback", | ||
| 167 | + "http://127.0.0.1:17651@evil.example/auth/callback", | ||
| 168 | + "http://127.0.0.1:17651/auth/callback?x=1", | ||
| 169 | + "https://127.0.0.1:17651/auth/callback", | ||
| 170 | + "http://127.0.0.1:17651/auth/callback#x", | ||
| 171 | + ] { | ||
| 172 | + let request = http::Request::get(authorize_path(&f.client.id, bad, &challenge, "S256")) | ||
| 173 | + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) | ||
| 174 | + .body(Body::empty()) | ||
| 175 | + .expect("request"); | ||
| 176 | + let (status, headers, _) = send(&f.state, request).await; | ||
| 177 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}"); | ||
| 178 | + assert!(headers.get(LOCATION).is_none(), "redirected for {bad}"); | ||
| 179 | + } | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +#[tokio::test] | ||
| 183 | +async fn plain_pkce_is_refused_through_the_registered_redirect() { | ||
| 184 | + let f = fixture().await; | ||
| 185 | + let verifier = generate_token(); | ||
| 186 | + let request = http::Request::get(authorize_path(&f.client.id, REDIRECT, &verifier, "plain")) | ||
| 187 | + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) | ||
| 188 | + .body(Body::empty()) | ||
| 189 | + .expect("request"); | ||
| 190 | + let (status, headers, _) = send(&f.state, request).await; | ||
| 191 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 192 | + let location = headers[LOCATION].to_str().expect("location"); | ||
| 193 | + assert!(location.starts_with(REDIRECT), "{location}"); | ||
| 194 | + assert!(location.contains("error=invalid_request"), "{location}"); | ||
| 195 | + assert!(!location.contains("code="), "{location}"); | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +#[tokio::test] | ||
| 199 | +async fn a_code_is_single_use_and_its_reuse_revokes_the_refresh_token() { | ||
| 200 | + let f = fixture().await; | ||
| 201 | + let verifier = generate_token(); | ||
| 202 | + let code = code_for(&f, &f.client, &verifier).await; | ||
| 203 | + let body = code_body(&code, &verifier); | ||
| 204 | + | ||
| 205 | + let (status, first) = token_with(&f, &f.client, &f.secret, &body).await; | ||
| 206 | + assert_eq!(status, StatusCode::OK, "{first}"); | ||
| 207 | + let refresh = first["refresh_token"].as_str().expect("refresh").to_owned(); | ||
| 208 | + | ||
| 209 | + let (status, second) = token_with(&f, &f.client, &f.secret, &body).await; | ||
| 210 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 211 | + assert_eq!(second["error"], "invalid_grant"); | ||
| 212 | + | ||
| 213 | + let refresh_body = format!("grant_type=refresh_token&refresh_token={refresh}"); | ||
| 214 | + let (status, third) = token_with(&f, &f.client, &f.secret, &refresh_body).await; | ||
| 215 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{third}"); | ||
| 216 | + assert_eq!(third["error"], "invalid_grant"); | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +#[tokio::test] | ||
| 220 | +async fn a_code_for_another_client_is_refused_and_still_usable_by_its_own() { | ||
| 221 | + let f = fixture().await; | ||
| 222 | + let other_secret = generate_token(); | ||
| 223 | + let uris = vec![REDIRECT.to_owned()]; | ||
| 224 | + let other = f | ||
| 225 | + .state | ||
| 226 | + .store | ||
| 227 | + .create_client(&NewClient { | ||
| 228 | + name: "Board", | ||
| 229 | + secret_hash: &hash_token(&other_secret), | ||
| 230 | + redirect_uris: &uris, | ||
| 231 | + post_logout_redirect_uris: &[], | ||
| 232 | + backchannel_logout_uri: None, | ||
| 233 | + allowed_scopes: "openid profile email", | ||
| 234 | + service_key: Some("iz"), | ||
| 235 | + }) | ||
| 236 | + .await | ||
| 237 | + .expect("client"); | ||
| 238 | + let verifier = generate_token(); | ||
| 239 | + let code = code_for(&f, &f.client, &verifier).await; | ||
| 240 | + let body = code_body(&code, &verifier); | ||
| 241 | + | ||
| 242 | + let (status, wrong) = token_with(&f, &other, &other_secret, &body).await; | ||
| 243 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 244 | + assert_eq!(wrong["error"], "invalid_grant"); | ||
| 245 | + | ||
| 246 | + let (status, right) = token_with(&f, &f.client, &f.secret, &body).await; | ||
| 247 | + assert_eq!(status, StatusCode::OK, "{right}"); | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +#[tokio::test] | ||
| 251 | +async fn a_reused_refresh_token_revokes_the_whole_family() { | ||
| 252 | + let f = fixture().await; | ||
| 253 | + let verifier = generate_token(); | ||
| 254 | + let code = code_for(&f, &f.client, &verifier).await; | ||
| 255 | + let (_, first) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; | ||
| 256 | + let r1 = first["refresh_token"].as_str().expect("r1").to_owned(); | ||
| 257 | + | ||
| 258 | + let (status, rotated) = token_with( | ||
| 259 | + &f, | ||
| 260 | + &f.client, | ||
| 261 | + &f.secret, | ||
| 262 | + &format!("grant_type=refresh_token&refresh_token={r1}"), | ||
| 263 | + ) | ||
| 264 | + .await; | ||
| 265 | + assert_eq!(status, StatusCode::OK, "{rotated}"); | ||
| 266 | + let r2 = rotated["refresh_token"].as_str().expect("r2").to_owned(); | ||
| 267 | + | ||
| 268 | + // Presenting the rotated token again is reuse: the successor dies too. | ||
| 269 | + let (status, reused) = token_with( | ||
| 270 | + &f, | ||
| 271 | + &f.client, | ||
| 272 | + &f.secret, | ||
| 273 | + &format!("grant_type=refresh_token&refresh_token={r1}"), | ||
| 274 | + ) | ||
| 275 | + .await; | ||
| 276 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 277 | + assert_eq!(reused["error"], "invalid_grant"); | ||
| 278 | + let (status, successor) = token_with( | ||
| 279 | + &f, | ||
| 280 | + &f.client, | ||
| 281 | + &f.secret, | ||
| 282 | + &format!("grant_type=refresh_token&refresh_token={r2}"), | ||
| 283 | + ) | ||
| 284 | + .await; | ||
| 285 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{successor}"); | ||
| 286 | +} | ||
| 287 | + | ||
| 288 | +#[tokio::test] | ||
| 289 | +async fn the_id_token_verifies_against_the_published_key_and_carries_the_nonce() { | ||
| 290 | + let f = fixture().await; | ||
| 291 | + let verifier = generate_token(); | ||
| 292 | + let code = code_for(&f, &f.client, &verifier).await; | ||
| 293 | + let (status, tokens) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; | ||
| 294 | + assert_eq!(status, StatusCode::OK, "{tokens}"); | ||
| 295 | + let id_token = tokens["id_token"].as_str().expect("id_token"); | ||
| 296 | + | ||
| 297 | + let request = http::Request::get("/jwks.json") | ||
| 298 | + .body(Body::empty()) | ||
| 299 | + .expect("request"); | ||
| 300 | + let (status, _, jwks) = send(&f.state, request).await; | ||
| 301 | + assert_eq!(status, StatusCode::OK); | ||
| 302 | + let keys: Vec<PublishedKey> = serde_json::from_str::<Value>(&jwks).expect("jwks")["keys"] | ||
| 303 | + .as_array() | ||
| 304 | + .expect("keys") | ||
| 305 | + .iter() | ||
| 306 | + .filter_map(|jwk| { | ||
| 307 | + let raw = BASE64_URL_SAFE_NO_PAD.decode(jwk["x"].as_str()?).ok()?; | ||
| 308 | + PublishedKey::new(jwk["kid"].as_str()?.to_owned(), &raw) | ||
| 309 | + }) | ||
| 310 | + .collect(); | ||
| 311 | + let claims = jwt::verify(&keys, id_token).expect("signature verifies"); | ||
| 312 | + let now = im_core::time::unix_now(); | ||
| 313 | + jwt::check_claims(&claims, &f.state.config.base_url, &f.client.id, now).expect("claims"); | ||
| 314 | + assert_eq!(claims["nonce"], "n1"); | ||
| 315 | + assert_eq!(claims["sub"], f.user_id.as_str()); | ||
| 316 | + assert_eq!(claims["amr"], serde_json::json!(["pwd"])); | ||
| 317 | +} | ||
crates/im-web/src/oidc/token.rsadded+376 -0
| @@ -0,0 +1,376 @@ | |||
| 1 | +//! `POST /token` (contracts section 2.3, step 3, and refresh): client authentication, the | ||
| 2 | +//! authorization-code grant and the refresh-token grant, and the token response. | ||
| 3 | +//! | ||
| 4 | +//! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The | ||
| 5 | +//! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every | ||
| 6 | +//! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one | ||
| 7 | +//! revokes its whole family. Client credentials (machine tokens) is answered `unsupported_grant_type` | ||
| 8 | +//! until its part of the provider is built. | ||
| 9 | + | ||
| 10 | +use base64::prelude::{BASE64_STANDARD, Engine as _}; | ||
| 11 | +use http::header::AUTHORIZATION; | ||
| 12 | +use im_core::model::{Client, Session, User}; | ||
| 13 | +use im_core::oauth::{is_valid_verifier, pkce_s256}; | ||
| 14 | +use im_core::store::new_id; | ||
| 15 | +use im_core::store::oidc::NewRefreshToken; | ||
| 16 | +use im_core::time::{now_stamp, stamp_after, unix_seconds}; | ||
| 17 | +use im_core::token::{constant_time_eq, generate_token, hash_token}; | ||
| 18 | +use serde_json::{Map, Value, json}; | ||
| 19 | +use topcoat::Result; | ||
| 20 | +use topcoat::context::{Cx, app_context}; | ||
| 21 | +use topcoat::router::request::{content_type, headers}; | ||
| 22 | +use topcoat::router::response::Response; | ||
| 23 | +use topcoat::router::{Body, StatusCode, route, to_bytes}; | ||
| 24 | + | ||
| 25 | +use super::signing; | ||
| 26 | +use super::{ | ||
| 27 | + ACCESS_TTL, ID_TOKEN_TTL, Pairs, REFRESH_TTL, Single, TOKEN_BODY_LIMIT, USERINFO_AUDIENCE, | ||
| 28 | + invalid_client, invalid_grant, issuer, json_response, oauth_error, one, parse_pairs, single, | ||
| 29 | +}; | ||
| 30 | +use crate::state::AppState; | ||
| 31 | + | ||
| 32 | +/// `POST /token`. | ||
| 33 | +#[route(POST "/token")] | ||
| 34 | +async fn token_endpoint(cx: &Cx, body: Body) -> Result<Response> { | ||
| 35 | + let app = app_context::<AppState>(cx); | ||
| 36 | + if !is_form(content_type(cx)) { | ||
| 37 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 38 | + } | ||
| 39 | + let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else { | ||
| 40 | + return Ok(oauth_error( | ||
| 41 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 42 | + "invalid_request", | ||
| 43 | + )); | ||
| 44 | + }; | ||
| 45 | + let Some(pairs) = parse_pairs(&bytes) else { | ||
| 46 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 47 | + }; | ||
| 48 | + let authorization = headers(cx) | ||
| 49 | + .get(AUTHORIZATION) | ||
| 50 | + .and_then(|value| value.to_str().ok()) | ||
| 51 | + .map(str::to_owned); | ||
| 52 | + let client = match authenticate(app, authorization.as_deref(), &pairs).await? { | ||
| 53 | + Ok(client) => client, | ||
| 54 | + Err(response) => return Ok(response), | ||
| 55 | + }; | ||
| 56 | + match one(&pairs, "grant_type") { | ||
| 57 | + Some("authorization_code") => grant_code(app, &client, &pairs).await, | ||
| 58 | + Some("refresh_token") => grant_refresh(app, &client, &pairs).await, | ||
| 59 | + Some(_) => Ok(oauth_error( | ||
| 60 | + StatusCode::BAD_REQUEST, | ||
| 61 | + "unsupported_grant_type", | ||
| 62 | + )), | ||
| 63 | + None => Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")), | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// True for a form body, with or without parameters after the media type. | ||
| 68 | +fn is_form(content_type: Option<&str>) -> bool { | ||
| 69 | + content_type.is_some_and(|value| { | ||
| 70 | + value | ||
| 71 | + .split(';') | ||
| 72 | + .next() | ||
| 73 | + .unwrap_or_default() | ||
| 74 | + .trim() | ||
| 75 | + .eq_ignore_ascii_case("application/x-www-form-urlencoded") | ||
| 76 | + }) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// The `client_id` and `client_secret` of a `Basic` credential, percent-decoded (RFC 6749 section | ||
| 80 | +/// 2.3.1). `None` when the header is not a Basic one; `Some(Err)` when it is Basic but malformed. | ||
| 81 | +fn basic_credentials(header: &str) -> Option<std::result::Result<(String, String), ()>> { | ||
| 82 | + let (scheme, encoded) = header.split_once(' ')?; | ||
| 83 | + if !scheme.eq_ignore_ascii_case("basic") { | ||
| 84 | + return None; | ||
| 85 | + } | ||
| 86 | + let decoded = BASE64_STANDARD | ||
| 87 | + .decode(encoded.trim()) | ||
| 88 | + .ok() | ||
| 89 | + .and_then(|bytes| String::from_utf8(bytes).ok()); | ||
| 90 | + let parsed = decoded.as_deref().and_then(|text| { | ||
| 91 | + let (id, secret) = text.split_once(':')?; | ||
| 92 | + Some((super::percent_decode(id)?, super::percent_decode(secret)?)) | ||
| 93 | + }); | ||
| 94 | + Some(parsed.ok_or(())) | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// Authenticates the client. The outer `Result` is a server failure; the inner one is either the client | ||
| 98 | +/// or the response that refuses the request. | ||
| 99 | +async fn authenticate( | ||
| 100 | + app: &AppState, | ||
| 101 | + authorization: Option<&str>, | ||
| 102 | + pairs: &Pairs, | ||
| 103 | +) -> Result<std::result::Result<Client, Response>> { | ||
| 104 | + let basic = match authorization.and_then(basic_credentials) { | ||
| 105 | + Some(Ok(credentials)) => Some(credentials), | ||
| 106 | + Some(Err(())) => return Ok(Err(invalid_client())), | ||
| 107 | + None => None, | ||
| 108 | + }; | ||
| 109 | + let form_id = single(pairs, "client_id"); | ||
| 110 | + let form_secret = single(pairs, "client_secret"); | ||
| 111 | + if form_id == Single::Repeated || form_secret == Single::Repeated { | ||
| 112 | + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); | ||
| 113 | + } | ||
| 114 | + let (client_id, secret) = match basic { | ||
| 115 | + Some((id, secret)) => { | ||
| 116 | + // Two methods at once are refused, and so is a body id that names another client. | ||
| 117 | + if matches!(form_secret, Single::One(_)) | ||
| 118 | + || matches!(form_id, Single::One(other) if other != id) | ||
| 119 | + { | ||
| 120 | + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); | ||
| 121 | + } | ||
| 122 | + (id, secret) | ||
| 123 | + } | ||
| 124 | + None => match (form_id, form_secret) { | ||
| 125 | + (Single::One(id), Single::One(secret)) => (id.to_owned(), secret.to_owned()), | ||
| 126 | + _ => return Ok(Err(invalid_client())), | ||
| 127 | + }, | ||
| 128 | + }; | ||
| 129 | + let client = app.store.client_by_id(&client_id).await?; | ||
| 130 | + // The hash is computed even for an unknown client, so the time does not reveal it. | ||
| 131 | + let presented = hash_token(&secret); | ||
| 132 | + let secret_ok = client | ||
| 133 | + .as_ref() | ||
| 134 | + .is_some_and(|known| constant_time_eq(presented.as_bytes(), known.secret_hash.as_bytes())); | ||
| 135 | + match client { | ||
| 136 | + Some(client) if secret_ok && !client.is_disabled() => Ok(Ok(client)), | ||
| 137 | + _ => Ok(Err(invalid_client())), | ||
| 138 | + } | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +/// The authorization-code grant (contracts section 2.3, step 3). | ||
| 142 | +async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Response> { | ||
| 143 | + let (Some(code), Some(redirect_uri), Some(verifier)) = ( | ||
| 144 | + one(pairs, "code"), | ||
| 145 | + one(pairs, "redirect_uri"), | ||
| 146 | + one(pairs, "code_verifier"), | ||
| 147 | + ) else { | ||
| 148 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 149 | + }; | ||
| 150 | + let code_hash = hash_token(code); | ||
| 151 | + let Some(row) = app.store.auth_code(&code_hash).await? else { | ||
| 152 | + return Ok(invalid_grant()); | ||
| 153 | + }; | ||
| 154 | + // A code belongs to one client. A wrong client is refused without touching the code. | ||
| 155 | + if row.client_id != client.id { | ||
| 156 | + return Ok(invalid_grant()); | ||
| 157 | + } | ||
| 158 | + if row.used_at.is_some() { | ||
| 159 | + // The code was exchanged before. Whoever holds the tokens made from it must lose them. | ||
| 160 | + app.store.revoke_code_refresh_tokens(&code_hash).await?; | ||
| 161 | + return Ok(invalid_grant()); | ||
| 162 | + } | ||
| 163 | + let pkce_ok = is_valid_verifier(verifier) | ||
| 164 | + && constant_time_eq( | ||
| 165 | + pkce_s256(verifier).as_bytes(), | ||
| 166 | + row.code_challenge.as_bytes(), | ||
| 167 | + ); | ||
| 168 | + if !pkce_ok || row.redirect_uri != redirect_uri || row.expires_at <= now_stamp() { | ||
| 169 | + return Ok(invalid_grant()); | ||
| 170 | + } | ||
| 171 | + let Some(session) = app.store.live_session(&row.session_id).await? else { | ||
| 172 | + return Ok(invalid_grant()); | ||
| 173 | + }; | ||
| 174 | + let Some(user) = app | ||
| 175 | + .store | ||
| 176 | + .user_by_id(&row.user_id) | ||
| 177 | + .await? | ||
| 178 | + .filter(|u| !u.is_disabled()) | ||
| 179 | + else { | ||
| 180 | + return Ok(invalid_grant()); | ||
| 181 | + }; | ||
| 182 | + | ||
| 183 | + let refresh = generate_token(); | ||
| 184 | + let refresh_id = new_id(); | ||
| 185 | + let refresh_expires = stamp_after(REFRESH_TTL); | ||
| 186 | + let first = NewRefreshToken { | ||
| 187 | + id: &refresh_id, | ||
| 188 | + token_hash: &hash_token(&refresh), | ||
| 189 | + family_id: &refresh_id, | ||
| 190 | + client_id: &client.id, | ||
| 191 | + user_id: &user.id, | ||
| 192 | + session_id: &session.id, | ||
| 193 | + code_hash: Some(&code_hash), | ||
| 194 | + scope: &row.scope, | ||
| 195 | + expires_at: &refresh_expires, | ||
| 196 | + }; | ||
| 197 | + if !app.store.redeem_auth_code(&code_hash, &first).await? { | ||
| 198 | + // A parallel exchange of the same code won the race: that is a reuse. | ||
| 199 | + app.store.revoke_code_refresh_tokens(&code_hash).await?; | ||
| 200 | + return Ok(invalid_grant()); | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + let id_token = id_token( | ||
| 204 | + app, | ||
| 205 | + &user, | ||
| 206 | + client, | ||
| 207 | + &session, | ||
| 208 | + &row.scope, | ||
| 209 | + row.nonce.as_deref(), | ||
| 210 | + ) | ||
| 211 | + .await?; | ||
| 212 | + let access_token = access_token(app, &user, client, &session, &row.scope).await?; | ||
| 213 | + Ok(token_response( | ||
| 214 | + access_token, | ||
| 215 | + &row.scope, | ||
| 216 | + Some(id_token), | ||
| 217 | + Some(refresh), | ||
| 218 | + )) | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +/// The refresh-token grant (contracts section 2.3, refresh): rotates the token and issues a new access | ||
| 222 | +/// token. No ID token is issued here: a refresh carries no nonce. | ||
| 223 | +async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Response> { | ||
| 224 | + let Some(presented) = one(pairs, "refresh_token") else { | ||
| 225 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 226 | + }; | ||
| 227 | + let Some(row) = app.store.refresh_token(&hash_token(presented)).await? else { | ||
| 228 | + return Ok(invalid_grant()); | ||
| 229 | + }; | ||
| 230 | + if row.client_id != client.id { | ||
| 231 | + return Ok(invalid_grant()); | ||
| 232 | + } | ||
| 233 | + if row.used_at.is_some() { | ||
| 234 | + // A rotated token came back. Either the holder or someone who copied it is replaying it: | ||
| 235 | + // the whole chain is revoked, so both lose it. | ||
| 236 | + app.store.revoke_refresh_family(&row.family_id).await?; | ||
| 237 | + return Ok(invalid_grant()); | ||
| 238 | + } | ||
| 239 | + if row.revoked_at.is_some() || row.expires_at <= now_stamp() { | ||
| 240 | + return Ok(invalid_grant()); | ||
| 241 | + } | ||
| 242 | + // A chain ends with its session, and with the user's account when that is disabled. | ||
| 243 | + let Some(session) = app.store.live_session(&row.session_id).await? else { | ||
| 244 | + return Ok(invalid_grant()); | ||
| 245 | + }; | ||
| 246 | + let Some(user) = app | ||
| 247 | + .store | ||
| 248 | + .user_by_id(&row.user_id) | ||
| 249 | + .await? | ||
| 250 | + .filter(|u| !u.is_disabled()) | ||
| 251 | + else { | ||
| 252 | + return Ok(invalid_grant()); | ||
| 253 | + }; | ||
| 254 | + | ||
| 255 | + let refresh = generate_token(); | ||
| 256 | + let refresh_id = new_id(); | ||
| 257 | + let refresh_expires = stamp_after(REFRESH_TTL); | ||
| 258 | + let next = NewRefreshToken { | ||
| 259 | + id: &refresh_id, | ||
| 260 | + token_hash: &hash_token(&refresh), | ||
| 261 | + family_id: &row.family_id, | ||
| 262 | + client_id: &client.id, | ||
| 263 | + user_id: &user.id, | ||
| 264 | + session_id: &session.id, | ||
| 265 | + code_hash: row.code_hash.as_deref(), | ||
| 266 | + scope: &row.scope, | ||
| 267 | + expires_at: &refresh_expires, | ||
| 268 | + }; | ||
| 269 | + if !app.store.rotate_refresh_token(&row.id, &next).await? { | ||
| 270 | + // A parallel refresh with the same token won the race: that is a reuse. | ||
| 271 | + app.store.revoke_refresh_family(&row.family_id).await?; | ||
| 272 | + return Ok(invalid_grant()); | ||
| 273 | + } | ||
| 274 | + let access_token = access_token(app, &user, client, &session, &row.scope).await?; | ||
| 275 | + Ok(token_response( | ||
| 276 | + access_token, | ||
| 277 | + &row.scope, | ||
| 278 | + None, | ||
| 279 | + Some(refresh), | ||
| 280 | + )) | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +/// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires. | ||
| 284 | +fn token_response( | ||
| 285 | + access_token: String, | ||
| 286 | + scope: &str, | ||
| 287 | + id_token: Option<String>, | ||
| 288 | + refresh_token: Option<String>, | ||
| 289 | +) -> Response { | ||
| 290 | + let mut body = json!({ | ||
| 291 | + "access_token": access_token, | ||
| 292 | + "token_type": "Bearer", | ||
| 293 | + "expires_in": ACCESS_TTL.as_secs(), | ||
| 294 | + "scope": scope, | ||
| 295 | + }); | ||
| 296 | + if let (Some(object), Some(id_token)) = (body.as_object_mut(), id_token) { | ||
| 297 | + object.insert("id_token".into(), Value::String(id_token)); | ||
| 298 | + } | ||
| 299 | + if let (Some(object), Some(refresh)) = (body.as_object_mut(), refresh_token) { | ||
| 300 | + object.insert("refresh_token".into(), Value::String(refresh)); | ||
| 301 | + } | ||
| 302 | + json_response(StatusCode::OK, &body) | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +/// The claims about the person that a scope grants. `email` gates the address; `profile` gates the | ||
| 306 | +/// name, the language, the time zone, the administrator flag and the picture version (contracts 2.3). | ||
| 307 | +pub fn person_claims(user: &User, scope: &str) -> Map<String, Value> { | ||
| 308 | + let granted = |name: &str| scope.split_whitespace().any(|word| word == name); | ||
| 309 | + let mut claims = Map::new(); | ||
| 310 | + if granted("email") { | ||
| 311 | + claims.insert("email".into(), json!(user.email)); | ||
| 312 | + // Only confirmed addresses are stored, so the flag is always true. | ||
| 313 | + claims.insert("email_verified".into(), json!(true)); | ||
| 314 | + } | ||
| 315 | + if granted("profile") { | ||
| 316 | + claims.insert("name".into(), json!(user.name)); | ||
| 317 | + claims.insert("admin".into(), json!(user.is_admin)); | ||
| 318 | + claims.insert("locale".into(), json!(user.locale)); | ||
| 319 | + claims.insert("zoneinfo".into(), json!(user.zoneinfo)); | ||
| 320 | + claims.insert("picture_version".into(), json!(user.picture_version)); | ||
| 321 | + } | ||
| 322 | + claims | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +/// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to | ||
| 326 | +/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. | ||
| 327 | +async fn access_token( | ||
| 328 | + app: &AppState, | ||
| 329 | + user: &User, | ||
| 330 | + client: &Client, | ||
| 331 | + session: &Session, | ||
| 332 | + scope: &str, | ||
| 333 | +) -> im_core::Result<String> { | ||
| 334 | + let now = im_core::time::unix_now(); | ||
| 335 | + let claims = json!({ | ||
| 336 | + "iss": issuer(app), | ||
| 337 | + "sub": user.id, | ||
| 338 | + "aud": USERINFO_AUDIENCE, | ||
| 339 | + "azp": client.id, | ||
| 340 | + "scope": scope, | ||
| 341 | + "sid": session.id, | ||
| 342 | + "iat": now, | ||
| 343 | + "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), | ||
| 344 | + "jti": generate_token(), | ||
| 345 | + }); | ||
| 346 | + signing::sign(&app.store, &app.key, &claims).await | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +/// The ID token (OIDC Core section 2): who signed in, when and how, for which client and nonce. | ||
| 350 | +async fn id_token( | ||
| 351 | + app: &AppState, | ||
| 352 | + user: &User, | ||
| 353 | + client: &Client, | ||
| 354 | + session: &Session, | ||
| 355 | + scope: &str, | ||
| 356 | + nonce: Option<&str>, | ||
| 357 | +) -> im_core::Result<String> { | ||
| 358 | + let now = im_core::time::unix_now(); | ||
| 359 | + let mut claims = json!({ | ||
| 360 | + "iss": issuer(app), | ||
| 361 | + "sub": user.id, | ||
| 362 | + "aud": client.id, | ||
| 363 | + "iat": now, | ||
| 364 | + "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), | ||
| 365 | + "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), | ||
| 366 | + "sid": session.id, | ||
| 367 | + "amr": session.amr.split(' ').collect::<Vec<_>>(), | ||
| 368 | + }); | ||
| 369 | + if let Some(object) = claims.as_object_mut() { | ||
| 370 | + if let Some(nonce) = nonce { | ||
| 371 | + object.insert("nonce".into(), json!(nonce)); | ||
| 372 | + } | ||
| 373 | + object.extend(person_claims(user, scope)); | ||
| 374 | + } | ||
| 375 | + signing::sign(&app.store, &app.key, &claims).await | ||
| 376 | +} | ||
crates/im-web/src/oidc/userinfo.rsadded+93 -0
| @@ -0,0 +1,93 @@ | |||
| 1 | +//! `GET` and `POST /userinfo` (OpenID Connect Core section 5.3): the claims of the person a user access | ||
| 2 | +//! token was issued for. | ||
| 3 | +//! | ||
| 4 | +//! The token is verified against this provider's own published keys: signature, `iss`, `aud` (this | ||
| 5 | +//! provider), `exp` and `iat`, and the `openid` scope. The token is then checked against the session it | ||
| 6 | +//! names: a session that ended, or a disabled account, refuses the token at once, even before it expires. | ||
| 7 | + | ||
| 8 | +use http::header::{AUTHORIZATION, CACHE_CONTROL, HeaderValue, WWW_AUTHENTICATE}; | ||
| 9 | +use im_core::jwt::{self, PublishedKey}; | ||
| 10 | +use im_core::time::unix_now; | ||
| 11 | +use serde_json::{Value, json}; | ||
| 12 | +use topcoat::Result; | ||
| 13 | +use topcoat::context::{Cx, app_context}; | ||
| 14 | +use topcoat::router::request::headers; | ||
| 15 | +use topcoat::router::response::Response; | ||
| 16 | +use topcoat::router::{StatusCode, route}; | ||
| 17 | + | ||
| 18 | +use super::signing; | ||
| 19 | +use super::token::person_claims; | ||
| 20 | +use super::{USERINFO_AUDIENCE, issuer, json_response}; | ||
| 21 | +use crate::state::AppState; | ||
| 22 | + | ||
| 23 | +/// `GET /userinfo` and `POST /userinfo`, both with a Bearer token. | ||
| 24 | +#[route([GET, POST] "/userinfo")] | ||
| 25 | +async fn userinfo(cx: &Cx) -> Result<Response> { | ||
| 26 | + let app = app_context::<AppState>(cx); | ||
| 27 | + let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else { | ||
| 28 | + return Ok(unauthorized()); | ||
| 29 | + }; | ||
| 30 | + let published = signing::published_keys(&app.store).await?; | ||
| 31 | + let keys: Vec<PublishedKey> = published | ||
| 32 | + .iter() | ||
| 33 | + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) | ||
| 34 | + .collect(); | ||
| 35 | + let Ok(claims) = jwt::verify(&keys, token) else { | ||
| 36 | + return Ok(unauthorized()); | ||
| 37 | + }; | ||
| 38 | + let now = unix_now(); | ||
| 39 | + if jwt::check_claims(&claims, issuer(app), USERINFO_AUDIENCE, now).is_err() { | ||
| 40 | + return Ok(unauthorized()); | ||
| 41 | + } | ||
| 42 | + let scope = claims | ||
| 43 | + .get("scope") | ||
| 44 | + .and_then(Value::as_str) | ||
| 45 | + .unwrap_or_default(); | ||
| 46 | + if !scope.split_whitespace().any(|word| word == "openid") { | ||
| 47 | + return Ok(unauthorized()); | ||
| 48 | + } | ||
| 49 | + let (Some(sub), Some(sid)) = ( | ||
| 50 | + claims.get("sub").and_then(Value::as_str), | ||
| 51 | + claims.get("sid").and_then(Value::as_str), | ||
| 52 | + ) else { | ||
| 53 | + return Ok(unauthorized()); | ||
| 54 | + }; | ||
| 55 | + let Some(session) = app.store.live_session(sid).await? else { | ||
| 56 | + return Ok(unauthorized()); | ||
| 57 | + }; | ||
| 58 | + let Some(user) = app | ||
| 59 | + .store | ||
| 60 | + .user_by_id(sub) | ||
| 61 | + .await? | ||
| 62 | + .filter(|u| !u.is_disabled()) | ||
| 63 | + else { | ||
| 64 | + return Ok(unauthorized()); | ||
| 65 | + }; | ||
| 66 | + if session.user_id != user.id { | ||
| 67 | + return Ok(unauthorized()); | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + let mut body = person_claims(&user, scope); | ||
| 71 | + body.insert("sub".into(), json!(user.id)); | ||
| 72 | + let mut response = json_response(StatusCode::OK, &Value::Object(body)); | ||
| 73 | + response | ||
| 74 | + .headers_mut() | ||
| 75 | + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); | ||
| 76 | + Ok(response) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// The token of a `Bearer` authorization header, or `None`. | ||
| 80 | +fn bearer(value: Option<&HeaderValue>) -> Option<&str> { | ||
| 81 | + let (scheme, token) = value?.to_str().ok()?.split_once(' ')?; | ||
| 82 | + (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// `401 invalid_token` with the RFC 6750 challenge. One answer for every reason. | ||
| 86 | +fn unauthorized() -> Response { | ||
| 87 | + let mut response = json_response(StatusCode::UNAUTHORIZED, &json!({"error": "invalid_token"})); | ||
| 88 | + response.headers_mut().insert( | ||
| 89 | + WWW_AUTHENTICATE, | ||
| 90 | + HeaderValue::from_static("Bearer error=\"invalid_token\""), | ||
| 91 | + ); | ||
| 92 | + response | ||
| 93 | +} | ||
crates/im-web/src/security.rsmodified+7 -1
| @@ -58,6 +58,9 @@ pub enum Answer { | |||
| 58 | Asset, | 58 | Asset, |
| 59 | /// A profile photo under `/photo/`, with its own cache policy and its own CSP. | 59 | /// A profile photo under `/photo/`, with its own cache policy and its own CSP. |
| 60 | Photo, | 60 | Photo, |
| 61 | + /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler | ||
| 62 | + /// sets the short cache policy. | ||
| 63 | + Public, | ||
| 61 | /// Everything else: pages, forms, streams. Never stored. | 64 | /// Everything else: pages, forms, streams. Never stored. |
| 62 | Page, | 65 | Page, |
| 63 | } | 66 | } |
| @@ -68,6 +71,8 @@ pub fn answer_for(path: &str) -> Answer { | |||
| 68 | Answer::Asset | 71 | Answer::Asset |
| 69 | } else if path.starts_with("/photo/") { | 72 | } else if path.starts_with("/photo/") { |
| 70 | Answer::Photo | 73 | Answer::Photo |
| 74 | + } else if path == "/.well-known/openid-configuration" || path == "/jwks.json" { | ||
| 75 | + Answer::Public | ||
| 71 | } else { | 76 | } else { |
| 72 | Answer::Page | 77 | Answer::Page |
| 73 | } | 78 | } |
| @@ -105,7 +110,7 @@ impl Layer for SecurityHeaders { | |||
| 105 | let answer = answer_for(uri(cx).path()); | 110 | let answer = answer_for(uri(cx).path()); |
| 106 | let mut headers = match answer { | 111 | let mut headers = match answer { |
| 107 | Answer::Photo => self.photo_headers.clone(), | 112 | Answer::Photo => self.photo_headers.clone(), |
| 108 | - Answer::Asset | Answer::Page => self.headers.clone(), | 113 | + Answer::Asset | Answer::Public | Answer::Page => self.headers.clone(), |
| 109 | }; | 114 | }; |
| 110 | if answer == Answer::Page { | 115 | if answer == Answer::Page { |
| 111 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); | 116 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); |
| @@ -127,6 +132,7 @@ mod tests { | |||
| 127 | assert_eq!(answer_for("/setup"), Answer::Page); | 132 | assert_eq!(answer_for("/setup"), Answer::Page); |
| 128 | assert_eq!(answer_for("/photo/01HZ"), Answer::Photo); | 133 | assert_eq!(answer_for("/photo/01HZ"), Answer::Photo); |
| 129 | assert_eq!(answer_for("/assets/main.css"), Answer::Asset); | 134 | assert_eq!(answer_for("/assets/main.css"), Answer::Asset); |
| 135 | + assert_eq!(answer_for("/jwks.json"), Answer::Public); | ||
| 130 | // A prefix match on the segment only: a page whose name starts the same is still a page. | 136 | // A prefix match on the segment only: a page whose name starts the same is still a page. |
| 131 | assert_eq!(answer_for("/photographs"), Answer::Page); | 137 | assert_eq!(answer_for("/photographs"), Answer::Page); |
| 132 | } | 138 | } |