im-client: feature-gate the OIDC half (default on); directory SDK always builds
Browse files at this commitf7b208171820ca309b10043c6e86de12b81f3826Parent: 3d752613 changed files +741 -693
- crates/im-client/Cargo.toml +15 -1
- crates/im-client/src/lib.rs +25 -692
- crates/im-client/src/oidc.rs +701 -0
crates/im-client/Cargo.tomlmodified+15 -1
| @@ -4,7 +4,15 @@ version.workspace = true | |||
| 4 | edition.workspace = true | 4 | edition.workspace = true |
| 5 | license.workspace = true | 5 | license.workspace = true |
| 6 | repository.workspace = true | 6 | repository.workspace = true |
| 7 | -description = "Drop-in OIDC client for topcoat apps authenticating against im" | 7 | +description = "im app-side SDK: the directory mirror (always) and the drop-in OIDC client (feature-gated)" |
| 8 | + | ||
| 9 | +[features] | ||
| 10 | +default = ["oidc"] | ||
| 11 | +# The drop-in OIDC client half (`mount`/`current_user` + the /auth routes). | ||
| 12 | +# Its routes register through the grammar's inventory, so a binary that | ||
| 13 | +# speaks OIDC through its own client crate builds this crate with | ||
| 14 | +# `default-features = false` and takes only the directory SDK. | ||
| 15 | +oidc = [] | ||
| 8 | 16 | ||
| 9 | [dependencies] | 17 | [dependencies] |
| 10 | topcoat = { version = "0.6.2", default-features = false, features = [ | 18 | topcoat = { version = "0.6.2", default-features = false, features = [ |
| @@ -31,6 +39,12 @@ reqwest = { version = "0.13.4", default-features = false, features = [ | |||
| 31 | "form", | 39 | "form", |
| 32 | ] } | 40 | ] } |
| 33 | 41 | ||
| 42 | +[[example]] | ||
| 43 | +name = "demo" | ||
| 44 | +# The example mounts the OIDC half; it is not part of the directory-only | ||
| 45 | +# build. | ||
| 46 | +required-features = ["oidc"] | ||
| 47 | + | ||
| 34 | [dev-dependencies] | 48 | [dev-dependencies] |
| 35 | topcoat = { version = "0.6.2", default-features = false, features = [ | 49 | topcoat = { version = "0.6.2", default-features = false, features = [ |
| 36 | "router", | 50 | "router", |
crates/im-client/src/lib.rsmodified+25 -692
| @@ -1,64 +1,29 @@ | |||
| 1 | -//! im-client: drop-in OIDC client for topcoat apps authenticating against im. | 1 | +//! im-client: the app-side SDK for im, in two halves. |
| 2 | //! | 2 | //! |
| 3 | -//! An app adds three things: `im_client::mount(builder, config)` when it | 3 | +//! **The directory SDK** ([`directory`], always compiled): a consumer with |
| 4 | -//! builds its router, `.discover()` as usual (the `/auth/login`, | 4 | +//! its own OIDC client crate takes this and nothing else — |
| 5 | -//! `/auth/callback`, `/auth/logout` routes register themselves), and | 5 | +//! [`directory::DirectoryClient`] pulls the roster and the photos and |
| 6 | -//! `im_client::current_user(cx)` wherever it needs the person. | 6 | +//! follows [`directory::DirectoryEvent`]s off the live stream, and |
| 7 | +//! [`directory::spawn_sync`] keeps a local mirror in step with backoff and | ||
| 8 | +//! resync. Build it with `default-features = false`. | ||
| 7 | //! | 9 | //! |
| 8 | -//! The model: im holds the central session; this crate holds the app's side | 10 | +//! **The drop-in OIDC client** (the `oidc` feature, on by default): |
| 9 | -//! of it — an encrypted cookie holding the opaque session token, introspected | 11 | +//! `im_client::mount(builder, config)` when it builds its router, |
| 10 | -//! against im on every request. | 12 | +//! `.discover()` as usual (the `/auth/login`, `/auth/callback`, |
| 11 | - | 13 | +//! `/auth/logout` routes register themselves), and |
| 12 | -use base64::Engine; | 14 | +//! `im_client::current_user(cx)` wherever it needs the person. im holds the |
| 13 | -use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url; | 15 | +//! central session; this half holds the app's side of it — an encrypted |
| 14 | -use chacha20poly1305::aead::Aead; | 16 | +//! cookie holding the opaque session token, introspected against im on |
| 15 | -use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; | 17 | +//! every request. |
| 16 | -use rand::Rng; | 18 | +//! |
| 17 | -use serde::{Deserialize, Serialize}; | 19 | +//! The two halves share the crate's [`Error`]/[`Result`]. The OIDC half's |
| 18 | -use sha2::{Digest, Sha256}; | 20 | +//! routes register through the grammar's inventory, so a binary that also |
| 19 | -use subtle::ConstantTimeEq; | 21 | +//! speaks OIDC through its own client crate must build this crate with |
| 20 | -use time::OffsetDateTime; | 22 | +//! `default-features = false`, or the two route sets collide at router |
| 21 | -use topcoat::context::{Cx, try_app_context}; | 23 | +//! build. |
| 22 | -use topcoat::cookie::{Cookie, Cookies, cookie, cookies}; | ||
| 23 | -use topcoat::router::response::{IntoResponse, Response}; | ||
| 24 | -use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route}; | ||
| 25 | 24 | ||
| 26 | pub mod directory; | 25 | pub mod directory; |
| 27 | 26 | ||
| 28 | -// --------------------------------------------------------------------------- | ||
| 29 | -// Configuration and state | ||
| 30 | -// --------------------------------------------------------------------------- | ||
| 31 | - | ||
| 32 | -/// Everything the app knows about its im registration. `client_secret` and | ||
| 33 | -/// `cookie_key` are secrets: the first authenticates the app to im, the | ||
| 34 | -/// second seals the browser cookies this crate writes. | ||
| 35 | -#[derive(Clone)] | ||
| 36 | -pub struct Config { | ||
| 37 | - /// im's base URL, e.g. `http://127.0.0.1:7650` or `https://auth.example.com`. | ||
| 38 | - pub issuer: String, | ||
| 39 | - pub client_id: String, | ||
| 40 | - pub client_secret: String, | ||
| 41 | - /// Must exactly match one of the URIs registered with im. | ||
| 42 | - pub redirect_uri: String, | ||
| 43 | - /// The app's session cookie name, e.g. `izlek_session`. | ||
| 44 | - pub cookie_name: String, | ||
| 45 | - /// 32 bytes, generated once per app and kept out of the repository. | ||
| 46 | - pub cookie_key: [u8; 32], | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -/// The registered state: the config, one HTTP client, and the JWKS cache. | ||
| 50 | -pub struct ImClient { | ||
| 51 | - config: Config, | ||
| 52 | - http: reqwest::Client, | ||
| 53 | - jwks: tokio::sync::RwLock<Option<JwksCache>>, | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -struct JwksCache { | ||
| 57 | - fetched_at: OffsetDateTime, | ||
| 58 | - /// kid -> public key | ||
| 59 | - keys: Vec<(String, rsa::RsaPublicKey)>, | ||
| 60 | -} | ||
| 61 | - | ||
| 62 | #[derive(Debug, thiserror::Error)] | 27 | #[derive(Debug, thiserror::Error)] |
| 63 | pub enum Error { | 28 | pub enum Error { |
| 64 | #[error("http: {0}")] | 29 | #[error("http: {0}")] |
| @@ -71,640 +36,8 @@ pub enum Error { | |||
| 71 | 36 | ||
| 72 | pub type Result<T, E = Error> = std::result::Result<T, E>; | 37 | pub type Result<T, E = Error> = std::result::Result<T, E>; |
| 73 | 38 | ||
| 74 | -impl ImClient { | 39 | +#[cfg(feature = "oidc")] |
| 75 | - pub fn new(config: Config) -> Self { | 40 | +mod oidc; |
| 76 | - ImClient { | ||
| 77 | - config, | ||
| 78 | - http: reqwest::Client::new(), | ||
| 79 | - jwks: tokio::sync::RwLock::new(None), | ||
| 80 | - } | ||
| 81 | - } | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -/// Registers the client state on the router. The routes themselves register | ||
| 85 | -/// through `discover()` — call it as usual. | ||
| 86 | -pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder { | ||
| 87 | - builder.app_context(ImClient::new(config)) | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -fn client(cx: &Cx) -> &ImClient { | ||
| 91 | - try_app_context::<ImClient>(cx).expect("im_client::mount was called on the router") | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -/// The authenticated person, if this browser has one. Every call asks im: | ||
| 95 | -/// the cookie holds an opaque session token, introspected per request, so an | ||
| 96 | -/// admin revoking the person signs them out of this app immediately — there | ||
| 97 | -/// is no token-validity window in which a ghost lives. | ||
| 98 | -pub async fn current_user(cx: &Cx) -> Option<User> { | ||
| 99 | - let state = client(cx); | ||
| 100 | - let sealed = cookies(cx).get(&state.config.cookie_name)?; | ||
| 101 | - let session: Session = open_json(&state.config.cookie_key, sealed.value())?; | ||
| 102 | - if session.exp <= OffsetDateTime::now_utc().unix_timestamp() { | ||
| 103 | - clear_cookie(cx, &state.config.cookie_name); | ||
| 104 | - return None; | ||
| 105 | - } | ||
| 106 | - match introspect(state, &session.app_session).await { | ||
| 107 | - Some((user, _exp)) => Some(user), | ||
| 108 | - None => { | ||
| 109 | - clear_cookie(cx, &state.config.cookie_name); | ||
| 110 | - None | ||
| 111 | - } | ||
| 112 | - } | ||
| 113 | -} | ||
| 114 | - | ||
| 115 | -/// POSTs the session token to im's `/introspect` with this app's credentials. | ||
| 116 | -/// Network failure reads as signed-out for this request — the cookie stays, | ||
| 117 | -/// so the next request tries again. | ||
| 118 | -async fn introspect(state: &ImClient, token: &str) -> Option<(User, i64)> { | ||
| 119 | - let answer: serde_json::Value = state | ||
| 120 | - .http | ||
| 121 | - .post(format!("{}/introspect", state.config.issuer)) | ||
| 122 | - .form(&[ | ||
| 123 | - ("token", token), | ||
| 124 | - ("client_id", &state.config.client_id), | ||
| 125 | - ("client_secret", &state.config.client_secret), | ||
| 126 | - ]) | ||
| 127 | - .send() | ||
| 128 | - .await | ||
| 129 | - .ok()? | ||
| 130 | - .json() | ||
| 131 | - .await | ||
| 132 | - .ok()?; | ||
| 133 | - if answer["active"] != true { | ||
| 134 | - return None; | ||
| 135 | - } | ||
| 136 | - Some(( | ||
| 137 | - User { | ||
| 138 | - sub: answer["sub"].as_str()?.to_string(), | ||
| 139 | - email: answer["email"].as_str()?.to_string(), | ||
| 140 | - name: answer["name"].as_str()?.to_string(), | ||
| 141 | - admin: answer["admin"].as_bool().unwrap_or(false), | ||
| 142 | - photo_version: answer["photo_version"].as_u64().unwrap_or(0), | ||
| 143 | - }, | ||
| 144 | - answer["exp"].as_i64()?, | ||
| 145 | - )) | ||
| 146 | -} | ||
| 147 | - | ||
| 148 | -/// Who this browser is, from the claims. | ||
| 149 | -#[derive(Debug, Clone, Serialize, Deserialize)] | ||
| 150 | -pub struct User { | ||
| 151 | - pub sub: String, | ||
| 152 | - pub email: String, | ||
| 153 | - pub name: String, | ||
| 154 | - #[serde(default)] | ||
| 155 | - pub admin: bool, | ||
| 156 | - /// How many times the person's photo has changed: the `/photo/{sub}?v=` | ||
| 157 | - /// cache buster. Absent on an older im — reads 0 there. | ||
| 158 | - #[serde(default)] | ||
| 159 | - pub photo_version: u64, | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -// --------------------------------------------------------------------------- | ||
| 163 | -// The app session cookie | ||
| 164 | -// --------------------------------------------------------------------------- | ||
| 165 | 41 | ||
| 166 | -#[derive(Serialize, Deserialize)] | 42 | +#[cfg(feature = "oidc")] |
| 167 | -struct Session { | 43 | +pub use oidc::{Config, ImClient, User, current_user, mount}; |
| 168 | - /// The opaque token im issued at the code exchange; introspected per | ||
| 169 | - /// request, never trusted on its own. | ||
| 170 | - app_session: String, | ||
| 171 | - exp: i64, | ||
| 172 | -} | ||
| 173 | - | ||
| 174 | -/// The in-flight login: PKCE verifier, state, nonce, and where to land after. | ||
| 175 | -#[derive(Serialize, Deserialize)] | ||
| 176 | -struct InFlight { | ||
| 177 | - verifier: String, | ||
| 178 | - state: String, | ||
| 179 | - nonce: String, | ||
| 180 | - next: String, | ||
| 181 | - exp: i64, | ||
| 182 | -} | ||
| 183 | - | ||
| 184 | -const IN_FLIGHT_MINUTES: i64 = 10; | ||
| 185 | - | ||
| 186 | -fn seal(key: &[u8; 32], plaintext: &[u8]) -> String { | ||
| 187 | - let cipher = XChaCha20Poly1305::new(key.into()); | ||
| 188 | - let mut nonce_bytes = [0u8; 24]; | ||
| 189 | - rand::rng().fill_bytes(&mut nonce_bytes); | ||
| 190 | - let ciphertext = cipher | ||
| 191 | - .encrypt(XNonce::from_slice(&nonce_bytes), plaintext) | ||
| 192 | - .expect("XChaCha20-Poly1305 cannot fail on a payload this small"); | ||
| 193 | - let mut payload = nonce_bytes.to_vec(); | ||
| 194 | - payload.extend_from_slice(&ciphertext); | ||
| 195 | - b64url.encode(payload) | ||
| 196 | -} | ||
| 197 | - | ||
| 198 | -fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> { | ||
| 199 | - let payload = b64url.decode(sealed).ok()?; | ||
| 200 | - if payload.len() < 24 { | ||
| 201 | - return None; | ||
| 202 | - } | ||
| 203 | - let (nonce_bytes, ciphertext) = payload.split_at(24); | ||
| 204 | - let cipher = XChaCha20Poly1305::new(key.into()); | ||
| 205 | - cipher | ||
| 206 | - .decrypt(XNonce::from_slice(nonce_bytes), ciphertext) | ||
| 207 | - .ok() | ||
| 208 | -} | ||
| 209 | - | ||
| 210 | -fn seal_json<T: Serialize>(key: &[u8; 32], value: &T) -> String { | ||
| 211 | - seal(key, &serde_json::to_vec(value).expect("plain data")) | ||
| 212 | -} | ||
| 213 | - | ||
| 214 | -fn open_json<T: for<'de> Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option<T> { | ||
| 215 | - serde_json::from_slice(&open(key, sealed)?).ok() | ||
| 216 | -} | ||
| 217 | - | ||
| 218 | -fn app_cookies(cx: &Cx) -> impl Cookies { | ||
| 219 | - cookies(cx) | ||
| 220 | - .default_secure(client(cx).config.issuer.starts_with("https://")) | ||
| 221 | - .default_http_only(true) | ||
| 222 | - .default_same_site(topcoat::cookie::SameSite::Lax) | ||
| 223 | - .default_path("/") | ||
| 224 | -} | ||
| 225 | - | ||
| 226 | -fn set_session_cookie(cx: &Cx, state: &ImClient, session: &Session) { | ||
| 227 | - let name = state.config.cookie_name.clone(); | ||
| 228 | - app_cookies(cx).add(cookie! { | ||
| 229 | - name = seal_json(&state.config.cookie_key, session); | ||
| 230 | - Path = "/"; | ||
| 231 | - HttpOnly; | ||
| 232 | - SameSite = Lax; | ||
| 233 | - MaxAge = time::Duration::days(30) | ||
| 234 | - }); | ||
| 235 | -} | ||
| 236 | - | ||
| 237 | -fn clear_cookie(cx: &Cx, name: &str) { | ||
| 238 | - app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build()); | ||
| 239 | -} | ||
| 240 | - | ||
| 241 | -// --------------------------------------------------------------------------- | ||
| 242 | -// Routes | ||
| 243 | -// --------------------------------------------------------------------------- | ||
| 244 | - | ||
| 245 | -fn see(cx: &Cx, location: &str) -> Result<Response, topcoat::Error> { | ||
| 246 | - ( | ||
| 247 | - StatusCode::SEE_OTHER, | ||
| 248 | - [(header::LOCATION, HeaderValue::from_str(location).unwrap())], | ||
| 249 | - ) | ||
| 250 | - .into_response(cx) | ||
| 251 | -} | ||
| 252 | - | ||
| 253 | -/// A `next` worth honoring: a local absolute path, never `//elsewhere`. | ||
| 254 | -fn safe_next(raw: &str) -> &str { | ||
| 255 | - if raw.starts_with('/') && !raw.starts_with("//") { | ||
| 256 | - raw | ||
| 257 | - } else { | ||
| 258 | - "/" | ||
| 259 | - } | ||
| 260 | -} | ||
| 261 | - | ||
| 262 | -/// A JWKS older than this is refreshed before the next validation. | ||
| 263 | -const JWKS_TTL_SECONDS: i64 = 3600; | ||
| 264 | - | ||
| 265 | -async fn jwks_stale(state: &ImClient) -> bool { | ||
| 266 | - match state.jwks.read().await.as_ref() { | ||
| 267 | - None => true, | ||
| 268 | - Some(cache) => { | ||
| 269 | - cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS) | ||
| 270 | - } | ||
| 271 | - } | ||
| 272 | -} | ||
| 273 | - | ||
| 274 | -fn query_value(query: &str, key: &str) -> Option<String> { | ||
| 275 | - query.split('&').find_map(|pair| { | ||
| 276 | - let (k, v) = pair.split_once('=')?; | ||
| 277 | - (k == key).then(|| urldecode(v)) | ||
| 278 | - }) | ||
| 279 | -} | ||
| 280 | - | ||
| 281 | -/// Percent-decodes a query value (`+` is a space, form-style). | ||
| 282 | -fn urldecode(raw: &str) -> String { | ||
| 283 | - let bytes = raw.as_bytes(); | ||
| 284 | - let mut out = Vec::with_capacity(bytes.len()); | ||
| 285 | - let mut i = 0; | ||
| 286 | - while i < bytes.len() { | ||
| 287 | - match bytes[i] { | ||
| 288 | - b'+' => { | ||
| 289 | - out.push(b' '); | ||
| 290 | - i += 1; | ||
| 291 | - } | ||
| 292 | - b'%' if i + 2 < bytes.len() => { | ||
| 293 | - let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); | ||
| 294 | - match u8::from_str_radix(hex, 16) { | ||
| 295 | - Ok(byte) => { | ||
| 296 | - out.push(byte); | ||
| 297 | - i += 3; | ||
| 298 | - } | ||
| 299 | - Err(_) => { | ||
| 300 | - out.push(b'%'); | ||
| 301 | - i += 1; | ||
| 302 | - } | ||
| 303 | - } | ||
| 304 | - } | ||
| 305 | - byte => { | ||
| 306 | - out.push(byte); | ||
| 307 | - i += 1; | ||
| 308 | - } | ||
| 309 | - } | ||
| 310 | - } | ||
| 311 | - String::from_utf8_lossy(&out).into_owned() | ||
| 312 | -} | ||
| 313 | - | ||
| 314 | -fn random_b64(bytes: usize) -> String { | ||
| 315 | - let mut buf = vec![0u8; bytes]; | ||
| 316 | - rand::rng().fill_bytes(&mut buf); | ||
| 317 | - b64url.encode(buf) | ||
| 318 | -} | ||
| 319 | - | ||
| 320 | -/// Sends the browser to im's `/authorize` with a fresh PKCE pair. | ||
| 321 | -#[route(GET "/auth/login")] | ||
| 322 | -async fn im_login(cx: &Cx) -> Result<Response, topcoat::Error> { | ||
| 323 | - let state = client(cx); | ||
| 324 | - let query = topcoat::router::request::uri(cx) | ||
| 325 | - .query() | ||
| 326 | - .unwrap_or("") | ||
| 327 | - .to_string(); | ||
| 328 | - let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string(); | ||
| 329 | - | ||
| 330 | - let flight = InFlight { | ||
| 331 | - verifier: random_b64(32), | ||
| 332 | - state: random_b64(16), | ||
| 333 | - nonce: random_b64(16), | ||
| 334 | - next, | ||
| 335 | - exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60, | ||
| 336 | - }; | ||
| 337 | - let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes())); | ||
| 338 | - let cookie_name = format!("{}_pkce", state.config.cookie_name); | ||
| 339 | - app_cookies(cx).add(cookie! { | ||
| 340 | - cookie_name = seal_json(&state.config.cookie_key, &flight); | ||
| 341 | - Path = "/"; | ||
| 342 | - HttpOnly; | ||
| 343 | - SameSite = Lax; | ||
| 344 | - MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES) | ||
| 345 | - }); | ||
| 346 | - | ||
| 347 | - let url = format!( | ||
| 348 | - "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256", | ||
| 349 | - state.config.issuer, | ||
| 350 | - state.config.client_id, | ||
| 351 | - urlencoded(&state.config.redirect_uri), | ||
| 352 | - flight.state, | ||
| 353 | - flight.nonce, | ||
| 354 | - challenge, | ||
| 355 | - ); | ||
| 356 | - see(cx, &url) | ||
| 357 | -} | ||
| 358 | - | ||
| 359 | -/// im's answer lands here: exchange the code, validate the id_token, mint | ||
| 360 | -/// the app session. | ||
| 361 | -#[route(GET "/auth/callback")] | ||
| 362 | -async fn im_callback(cx: &Cx) -> Result<Response, topcoat::Error> { | ||
| 363 | - let state = client(cx); | ||
| 364 | - let query = topcoat::router::request::uri(cx) | ||
| 365 | - .query() | ||
| 366 | - .unwrap_or("") | ||
| 367 | - .to_string(); | ||
| 368 | - if let Some(error) = query_value(&query, "error") { | ||
| 369 | - return see(cx, &format!("/?auth_error={error}")); | ||
| 370 | - } | ||
| 371 | - let (Some(code), Some(presented_state)) = | ||
| 372 | - (query_value(&query, "code"), query_value(&query, "state")) | ||
| 373 | - else { | ||
| 374 | - return see(cx, "/?auth_error=invalid_request"); | ||
| 375 | - }; | ||
| 376 | - let cookie_name = format!("{}_pkce", state.config.cookie_name); | ||
| 377 | - let flight: Option<InFlight> = cookies(cx) | ||
| 378 | - .get(&cookie_name) | ||
| 379 | - .and_then(|c| open_json(&state.config.cookie_key, c.value())); | ||
| 380 | - let Some(flight) = flight else { | ||
| 381 | - return see(cx, "/?auth_error=invalid_request"); | ||
| 382 | - }; | ||
| 383 | - clear_cookie(cx, &cookie_name); | ||
| 384 | - if flight.exp <= OffsetDateTime::now_utc().unix_timestamp() | ||
| 385 | - || flight | ||
| 386 | - .state | ||
| 387 | - .as_bytes() | ||
| 388 | - .ct_eq(presented_state.as_bytes()) | ||
| 389 | - .unwrap_u8() | ||
| 390 | - != 1 | ||
| 391 | - { | ||
| 392 | - return see(cx, "/?auth_error=invalid_state"); | ||
| 393 | - } | ||
| 394 | - | ||
| 395 | - match exchange_code(state, &code, &flight).await { | ||
| 396 | - Ok(session) => { | ||
| 397 | - set_session_cookie(cx, state, &session); | ||
| 398 | - see(cx, &flight.next) | ||
| 399 | - } | ||
| 400 | - Err(_) => see(cx, "/?auth_error=exchange_failed"), | ||
| 401 | - } | ||
| 402 | -} | ||
| 403 | - | ||
| 404 | -/// Signs out of the app only. To end the central session too, post to im's | ||
| 405 | -/// `/logout` — a link there is a silent re-login, by design. | ||
| 406 | -#[route(GET "/auth/logout")] | ||
| 407 | -async fn im_logout(cx: &Cx) -> Result<Response, topcoat::Error> { | ||
| 408 | - clear_cookie(cx, &client(cx).config.cookie_name); | ||
| 409 | - see(cx, "/") | ||
| 410 | -} | ||
| 411 | - | ||
| 412 | -fn urlencoded(raw: &str) -> String { | ||
| 413 | - let mut out = String::with_capacity(raw.len()); | ||
| 414 | - for byte in raw.bytes() { | ||
| 415 | - match byte { | ||
| 416 | - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { | ||
| 417 | - out.push(byte as char) | ||
| 418 | - } | ||
| 419 | - _ => out.push_str(&format!("%{byte:02X}")), | ||
| 420 | - } | ||
| 421 | - } | ||
| 422 | - out | ||
| 423 | -} | ||
| 424 | - | ||
| 425 | -// --------------------------------------------------------------------------- | ||
| 426 | -// Token exchange, refresh, validation | ||
| 427 | -// --------------------------------------------------------------------------- | ||
| 428 | - | ||
| 429 | -#[derive(Deserialize)] | ||
| 430 | -struct TokenAnswer { | ||
| 431 | - /// Validated for its nonce and signature; the identity the app serves | ||
| 432 | - /// comes from introspection, not from these claims. | ||
| 433 | - id_token: String, | ||
| 434 | - /// Not OIDC — im's own: the opaque session this crate introspects per | ||
| 435 | - /// request. Absent means the issuer is not a current im. | ||
| 436 | - app_session: Option<String>, | ||
| 437 | -} | ||
| 438 | - | ||
| 439 | -async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result<Session> { | ||
| 440 | - let answer: TokenAnswer = state | ||
| 441 | - .http | ||
| 442 | - .post(format!("{}/token", state.config.issuer)) | ||
| 443 | - .form(&[ | ||
| 444 | - ("grant_type", "authorization_code"), | ||
| 445 | - ("code", code), | ||
| 446 | - ("redirect_uri", &state.config.redirect_uri), | ||
| 447 | - ("client_id", &state.config.client_id), | ||
| 448 | - ("client_secret", &state.config.client_secret), | ||
| 449 | - ("code_verifier", &flight.verifier), | ||
| 450 | - ]) | ||
| 451 | - .send() | ||
| 452 | - .await | ||
| 453 | - .map_err(|e| Error::Http(e.to_string()))? | ||
| 454 | - .error_for_status() | ||
| 455 | - .map_err(|e| Error::Refused(e.to_string()))? | ||
| 456 | - .json() | ||
| 457 | - .await | ||
| 458 | - .map_err(|e| Error::Http(e.to_string()))?; | ||
| 459 | - let claims = validate_id_token(state, &answer.id_token).await?; | ||
| 460 | - if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { | ||
| 461 | - return Err(Error::Token("nonce mismatch".into())); | ||
| 462 | - } | ||
| 463 | - let app_session = answer | ||
| 464 | - .app_session | ||
| 465 | - .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; | ||
| 466 | - // The session's expiry and identity come from a live introspection, not | ||
| 467 | - // from the token answer — the same check every later request will make. | ||
| 468 | - let (_user, exp) = introspect(state, &app_session) | ||
| 469 | - .await | ||
| 470 | - .ok_or_else(|| Error::Refused("fresh app session does not introspect".into()))?; | ||
| 471 | - Ok(Session { app_session, exp }) | ||
| 472 | -} | ||
| 473 | - | ||
| 474 | -/// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry. | ||
| 475 | -/// The nonce is the caller's to check (only the callback holds one). | ||
| 476 | -async fn validate_id_token(state: &ImClient, token: &str) -> Result<serde_json::Value> { | ||
| 477 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 478 | - if parts.len() != 3 { | ||
| 479 | - return Err(Error::Token("not a compact JWT".into())); | ||
| 480 | - } | ||
| 481 | - let header: serde_json::Value = serde_json::from_slice( | ||
| 482 | - &b64url | ||
| 483 | - .decode(parts[0]) | ||
| 484 | - .map_err(|e| Error::Token(e.to_string()))?, | ||
| 485 | - ) | ||
| 486 | - .map_err(|e| Error::Token(e.to_string()))?; | ||
| 487 | - if header["alg"] != "RS256" { | ||
| 488 | - return Err(Error::Token("unexpected alg".into())); | ||
| 489 | - } | ||
| 490 | - let kid = header["kid"] | ||
| 491 | - .as_str() | ||
| 492 | - .ok_or_else(|| Error::Token("no kid".into()))? | ||
| 493 | - .to_string(); | ||
| 494 | - | ||
| 495 | - if jwks_stale(state).await { | ||
| 496 | - refetch_jwks(state).await?; | ||
| 497 | - } | ||
| 498 | - let key = match cached_key(state, &kid).await { | ||
| 499 | - Some(key) => key, | ||
| 500 | - None => { | ||
| 501 | - refetch_jwks(state).await?; | ||
| 502 | - cached_key(state, &kid) | ||
| 503 | - .await | ||
| 504 | - .ok_or_else(|| Error::Token("unknown kid after refetch".into()))? | ||
| 505 | - } | ||
| 506 | - }; | ||
| 507 | - | ||
| 508 | - verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id) | ||
| 509 | -} | ||
| 510 | - | ||
| 511 | -/// The pure half of [`validate_id_token`]: signature, issuer, audience, | ||
| 512 | -/// expiry. Split out so the test suite signs its own tokens without standing | ||
| 513 | -/// a server up. | ||
| 514 | -fn verify_claims( | ||
| 515 | - parts: &[&str], | ||
| 516 | - key: &rsa::RsaPublicKey, | ||
| 517 | - issuer: &str, | ||
| 518 | - client_id: &str, | ||
| 519 | -) -> Result<serde_json::Value> { | ||
| 520 | - use rsa::signature::Verifier; | ||
| 521 | - let signature_bytes = b64url | ||
| 522 | - .decode(parts[2]) | ||
| 523 | - .map_err(|e| Error::Token(e.to_string()))?; | ||
| 524 | - let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) | ||
| 525 | - .map_err(|e| Error::Token(e.to_string()))?; | ||
| 526 | - let verifying = rsa::pkcs1v15::VerifyingKey::<sha2_for_rsa::Sha256>::new(key.clone()); | ||
| 527 | - verifying | ||
| 528 | - .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) | ||
| 529 | - .map_err(|_| Error::Token("bad signature".into()))?; | ||
| 530 | - | ||
| 531 | - let claims: serde_json::Value = serde_json::from_slice( | ||
| 532 | - &b64url | ||
| 533 | - .decode(parts[1]) | ||
| 534 | - .map_err(|e| Error::Token(e.to_string()))?, | ||
| 535 | - ) | ||
| 536 | - .map_err(|e| Error::Token(e.to_string()))?; | ||
| 537 | - if claims["iss"].as_str() != Some(issuer) { | ||
| 538 | - return Err(Error::Token("wrong issuer".into())); | ||
| 539 | - } | ||
| 540 | - if claims["aud"].as_str() != Some(client_id) { | ||
| 541 | - return Err(Error::Token("wrong audience".into())); | ||
| 542 | - } | ||
| 543 | - match claims["exp"].as_i64() { | ||
| 544 | - Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {} | ||
| 545 | - _ => return Err(Error::Token("expired".into())), | ||
| 546 | - } | ||
| 547 | - Ok(claims) | ||
| 548 | -} | ||
| 549 | - | ||
| 550 | -async fn cached_key(state: &ImClient, kid: &str) -> Option<rsa::RsaPublicKey> { | ||
| 551 | - state | ||
| 552 | - .jwks | ||
| 553 | - .read() | ||
| 554 | - .await | ||
| 555 | - .as_ref()? | ||
| 556 | - .keys | ||
| 557 | - .iter() | ||
| 558 | - .find(|(k, _)| k == kid) | ||
| 559 | - .map(|(_, key)| key.clone()) | ||
| 560 | -} | ||
| 561 | - | ||
| 562 | -/// Fetches and caches im's JWKS. Cached for an hour at most; an unknown kid | ||
| 563 | -/// forces an immediate refetch above. | ||
| 564 | -async fn refetch_jwks(state: &ImClient) -> Result<()> { | ||
| 565 | - let doc: serde_json::Value = state | ||
| 566 | - .http | ||
| 567 | - .get(format!("{}/jwks.json", state.config.issuer)) | ||
| 568 | - .send() | ||
| 569 | - .await | ||
| 570 | - .map_err(|e| Error::Http(e.to_string()))? | ||
| 571 | - .error_for_status() | ||
| 572 | - .map_err(|e| Error::Refused(e.to_string()))? | ||
| 573 | - .json() | ||
| 574 | - .await | ||
| 575 | - .map_err(|e| Error::Http(e.to_string()))?; | ||
| 576 | - let mut keys = Vec::new(); | ||
| 577 | - for jwk in doc["keys"].as_array().into_iter().flatten() { | ||
| 578 | - let (Some(kid), Some(n), Some(e)) = | ||
| 579 | - (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str()) | ||
| 580 | - else { | ||
| 581 | - continue; | ||
| 582 | - }; | ||
| 583 | - let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else { | ||
| 584 | - continue; | ||
| 585 | - }; | ||
| 586 | - let key = rsa::RsaPublicKey::new( | ||
| 587 | - rsa::BigUint::from_bytes_be(&n), | ||
| 588 | - rsa::BigUint::from_bytes_be(&e), | ||
| 589 | - ) | ||
| 590 | - .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?; | ||
| 591 | - keys.push((kid.to_string(), key)); | ||
| 592 | - } | ||
| 593 | - *state.jwks.write().await = Some(JwksCache { | ||
| 594 | - fetched_at: OffsetDateTime::now_utc(), | ||
| 595 | - keys, | ||
| 596 | - }); | ||
| 597 | - Ok(()) | ||
| 598 | -} | ||
| 599 | - | ||
| 600 | -#[cfg(test)] | ||
| 601 | -mod tests { | ||
| 602 | - use super::*; | ||
| 603 | - use rsa::signature::{SignatureEncoding, Signer}; | ||
| 604 | - | ||
| 605 | - fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) { | ||
| 606 | - // 2048-bit generation is slow for a unit test; 1024 is the smallest | ||
| 607 | - // rsa 0.9 accepts and the signature math under test is identical. | ||
| 608 | - let private = rsa::RsaPrivateKey::new(&mut rand_core06::OsRng, 1024).unwrap(); | ||
| 609 | - let public = private.to_public_key(); | ||
| 610 | - (private, public) | ||
| 611 | - } | ||
| 612 | - | ||
| 613 | - fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String { | ||
| 614 | - let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"}); | ||
| 615 | - let mut out = b64url.encode(header.to_string()); | ||
| 616 | - out.push('.'); | ||
| 617 | - out.push_str(&b64url.encode(claims.to_string())); | ||
| 618 | - let signing = rsa::pkcs1v15::SigningKey::<sha2_for_rsa::Sha256>::new(key.clone()); | ||
| 619 | - let signature = signing.sign(out.as_bytes()); | ||
| 620 | - format!("{}.{}", out, b64url.encode(signature.to_bytes())) | ||
| 621 | - } | ||
| 622 | - | ||
| 623 | - fn good_claims() -> serde_json::Value { | ||
| 624 | - serde_json::json!({ | ||
| 625 | - "iss": "http://im.test", | ||
| 626 | - "sub": "user-1", | ||
| 627 | - "aud": "client-1", | ||
| 628 | - "exp": OffsetDateTime::now_utc().unix_timestamp() + 600, | ||
| 629 | - "iat": OffsetDateTime::now_utc().unix_timestamp(), | ||
| 630 | - "email": "ann@example.com", | ||
| 631 | - "name": "Ann", | ||
| 632 | - }) | ||
| 633 | - } | ||
| 634 | - | ||
| 635 | - #[test] | ||
| 636 | - fn valid_token_validates() { | ||
| 637 | - let (private, public) = keypair(); | ||
| 638 | - let token = sign(good_claims(), &private); | ||
| 639 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 640 | - let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap(); | ||
| 641 | - assert_eq!(claims["sub"], "user-1"); | ||
| 642 | - } | ||
| 643 | - | ||
| 644 | - #[test] | ||
| 645 | - fn tampered_payload_rejected() { | ||
| 646 | - let (private, public) = keypair(); | ||
| 647 | - let token = sign(good_claims(), &private); | ||
| 648 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 649 | - let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#); | ||
| 650 | - let forged = vec![parts[0], forged_payload.as_str(), parts[2]]; | ||
| 651 | - assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err()); | ||
| 652 | - } | ||
| 653 | - | ||
| 654 | - #[test] | ||
| 655 | - fn wrong_key_rejected() { | ||
| 656 | - let (private, _) = keypair(); | ||
| 657 | - let (_, other_public) = keypair(); | ||
| 658 | - let token = sign(good_claims(), &private); | ||
| 659 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 660 | - assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err()); | ||
| 661 | - } | ||
| 662 | - | ||
| 663 | - #[test] | ||
| 664 | - fn wrong_audience_rejected() { | ||
| 665 | - let (private, public) = keypair(); | ||
| 666 | - let token = sign(good_claims(), &private); | ||
| 667 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 668 | - assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err()); | ||
| 669 | - } | ||
| 670 | - | ||
| 671 | - #[test] | ||
| 672 | - fn wrong_issuer_rejected() { | ||
| 673 | - let (private, public) = keypair(); | ||
| 674 | - let token = sign(good_claims(), &private); | ||
| 675 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 676 | - assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err()); | ||
| 677 | - } | ||
| 678 | - | ||
| 679 | - #[test] | ||
| 680 | - fn expired_rejected() { | ||
| 681 | - let (private, public) = keypair(); | ||
| 682 | - let mut claims = good_claims(); | ||
| 683 | - claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into(); | ||
| 684 | - let token = sign(claims, &private); | ||
| 685 | - let parts: Vec<&str> = token.split('.').collect(); | ||
| 686 | - assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err()); | ||
| 687 | - } | ||
| 688 | - | ||
| 689 | - #[test] | ||
| 690 | - fn pkce_rfc7636_vector() { | ||
| 691 | - // RFC 7636 Appendix B. | ||
| 692 | - let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; | ||
| 693 | - let challenge = b64url.encode(Sha256::digest(verifier.as_bytes())); | ||
| 694 | - assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); | ||
| 695 | - } | ||
| 696 | - | ||
| 697 | - #[test] | ||
| 698 | - fn cookie_seal_roundtrip() { | ||
| 699 | - let key = [7u8; 32]; | ||
| 700 | - let session = Session { | ||
| 701 | - app_session: "opaque-token".into(), | ||
| 702 | - exp: 1, | ||
| 703 | - }; | ||
| 704 | - let sealed = seal_json(&key, &session); | ||
| 705 | - let back: Session = open_json(&key, &sealed).unwrap(); | ||
| 706 | - assert_eq!(back.app_session, "opaque-token"); | ||
| 707 | - assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none()); | ||
| 708 | - assert!(open_json::<Session>(&key, "garbage").is_none()); | ||
| 709 | - } | ||
| 710 | -} | ||
crates/im-client/src/oidc.rsadded+701 -0
| @@ -0,0 +1,701 @@ | |||
| 1 | +//! im-client's OIDC half: the drop-in client for topcoat apps that let im | ||
| 2 | +//! hold their sign-in. Compiled under the `oidc` feature — on by default. | ||
| 3 | +//! | ||
| 4 | +//! An app adds three things: `im_client::mount(builder, config)` when it | ||
| 5 | +//! builds its router, `.discover()` as usual (the `/auth/login`, | ||
| 6 | +//! `/auth/callback`, `/auth/logout` routes register themselves), and | ||
| 7 | +//! `im_client::current_user(cx)` wherever it needs the person. | ||
| 8 | +//! | ||
| 9 | +//! The model: im holds the central session; this half holds the app's | ||
| 10 | +//! side of it — an encrypted cookie holding the opaque session token, | ||
| 11 | +//! introspected against im on every request. The routes register through | ||
| 12 | +//! the grammar's inventory, so a binary that also speaks OIDC through its | ||
| 13 | +//! own client crate must build this half OFF (`default-features = false`), | ||
| 14 | +//! or the two route sets collide at router build. | ||
| 15 | + | ||
| 16 | +use crate::{Error, Result}; | ||
| 17 | +use base64::Engine; | ||
| 18 | +use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url; | ||
| 19 | +use chacha20poly1305::aead::Aead; | ||
| 20 | +use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; | ||
| 21 | +use rand::Rng; | ||
| 22 | +use serde::{Deserialize, Serialize}; | ||
| 23 | +use sha2::{Digest, Sha256}; | ||
| 24 | +use subtle::ConstantTimeEq; | ||
| 25 | +use time::OffsetDateTime; | ||
| 26 | +use topcoat::context::{Cx, try_app_context}; | ||
| 27 | +use topcoat::cookie::{Cookie, Cookies, cookie, cookies}; | ||
| 28 | +use topcoat::router::response::{IntoResponse, Response}; | ||
| 29 | +use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route}; | ||
| 30 | + | ||
| 31 | +// --------------------------------------------------------------------------- | ||
| 32 | +// Configuration and state | ||
| 33 | +// --------------------------------------------------------------------------- | ||
| 34 | + | ||
| 35 | +/// Everything the app knows about its im registration. `client_secret` and | ||
| 36 | +/// `cookie_key` are secrets: the first authenticates the app to im, the | ||
| 37 | +/// second seals the browser cookies this crate writes. | ||
| 38 | +#[derive(Clone)] | ||
| 39 | +pub struct Config { | ||
| 40 | + /// im's base URL, e.g. `http://127.0.0.1:7650` or `https://auth.example.com`. | ||
| 41 | + pub issuer: String, | ||
| 42 | + pub client_id: String, | ||
| 43 | + pub client_secret: String, | ||
| 44 | + /// Must exactly match one of the URIs registered with im. | ||
| 45 | + pub redirect_uri: String, | ||
| 46 | + /// The app's session cookie name, e.g. `izlek_session`. | ||
| 47 | + pub cookie_name: String, | ||
| 48 | + /// 32 bytes, generated once per app and kept out of the repository. | ||
| 49 | + pub cookie_key: [u8; 32], | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// The registered state: the config, one HTTP client, and the JWKS cache. | ||
| 53 | +pub struct ImClient { | ||
| 54 | + config: Config, | ||
| 55 | + http: reqwest::Client, | ||
| 56 | + jwks: tokio::sync::RwLock<Option<JwksCache>>, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +struct JwksCache { | ||
| 60 | + fetched_at: OffsetDateTime, | ||
| 61 | + /// kid -> public key | ||
| 62 | + keys: Vec<(String, rsa::RsaPublicKey)>, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +impl ImClient { | ||
| 66 | + pub fn new(config: Config) -> Self { | ||
| 67 | + ImClient { | ||
| 68 | + config, | ||
| 69 | + http: reqwest::Client::new(), | ||
| 70 | + jwks: tokio::sync::RwLock::new(None), | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// Registers the client state on the router. The routes themselves register | ||
| 76 | +/// through `discover()` — call it as usual. | ||
| 77 | +pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder { | ||
| 78 | + builder.app_context(ImClient::new(config)) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +fn client(cx: &Cx) -> &ImClient { | ||
| 82 | + try_app_context::<ImClient>(cx).expect("im_client::mount was called on the router") | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// The authenticated person, if this browser has one. Every call asks im: | ||
| 86 | +/// the cookie holds an opaque session token, introspected per request, so an | ||
| 87 | +/// admin revoking the person signs them out of this app immediately — there | ||
| 88 | +/// is no token-validity window in which a ghost lives. | ||
| 89 | +pub async fn current_user(cx: &Cx) -> Option<User> { | ||
| 90 | + let state = client(cx); | ||
| 91 | + let sealed = cookies(cx).get(&state.config.cookie_name)?; | ||
| 92 | + let session: Session = open_json(&state.config.cookie_key, sealed.value())?; | ||
| 93 | + if session.exp <= OffsetDateTime::now_utc().unix_timestamp() { | ||
| 94 | + clear_cookie(cx, &state.config.cookie_name); | ||
| 95 | + return None; | ||
| 96 | + } | ||
| 97 | + match introspect(state, &session.app_session).await { | ||
| 98 | + Some((user, _exp)) => Some(user), | ||
| 99 | + None => { | ||
| 100 | + clear_cookie(cx, &state.config.cookie_name); | ||
| 101 | + None | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// POSTs the session token to im's `/introspect` with this app's credentials. | ||
| 107 | +/// Network failure reads as signed-out for this request — the cookie stays, | ||
| 108 | +/// so the next request tries again. | ||
| 109 | +async fn introspect(state: &ImClient, token: &str) -> Option<(User, i64)> { | ||
| 110 | + let answer: serde_json::Value = state | ||
| 111 | + .http | ||
| 112 | + .post(format!("{}/introspect", state.config.issuer)) | ||
| 113 | + .form(&[ | ||
| 114 | + ("token", token), | ||
| 115 | + ("client_id", &state.config.client_id), | ||
| 116 | + ("client_secret", &state.config.client_secret), | ||
| 117 | + ]) | ||
| 118 | + .send() | ||
| 119 | + .await | ||
| 120 | + .ok()? | ||
| 121 | + .json() | ||
| 122 | + .await | ||
| 123 | + .ok()?; | ||
| 124 | + if answer["active"] != true { | ||
| 125 | + return None; | ||
| 126 | + } | ||
| 127 | + Some(( | ||
| 128 | + User { | ||
| 129 | + sub: answer["sub"].as_str()?.to_string(), | ||
| 130 | + email: answer["email"].as_str()?.to_string(), | ||
| 131 | + name: answer["name"].as_str()?.to_string(), | ||
| 132 | + admin: answer["admin"].as_bool().unwrap_or(false), | ||
| 133 | + photo_version: answer["photo_version"].as_u64().unwrap_or(0), | ||
| 134 | + }, | ||
| 135 | + answer["exp"].as_i64()?, | ||
| 136 | + )) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Who this browser is, from the claims. | ||
| 140 | +#[derive(Debug, Clone, Serialize, Deserialize)] | ||
| 141 | +pub struct User { | ||
| 142 | + pub sub: String, | ||
| 143 | + pub email: String, | ||
| 144 | + pub name: String, | ||
| 145 | + #[serde(default)] | ||
| 146 | + pub admin: bool, | ||
| 147 | + /// How many times the person's photo has changed: the `/photo/{sub}?v=` | ||
| 148 | + /// cache buster. Absent on an older im — reads 0 there. | ||
| 149 | + #[serde(default)] | ||
| 150 | + pub photo_version: u64, | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +// --------------------------------------------------------------------------- | ||
| 154 | +// The app session cookie | ||
| 155 | +// --------------------------------------------------------------------------- | ||
| 156 | + | ||
| 157 | +#[derive(Serialize, Deserialize)] | ||
| 158 | +struct Session { | ||
| 159 | + /// The opaque token im issued at the code exchange; introspected per | ||
| 160 | + /// request, never trusted on its own. | ||
| 161 | + app_session: String, | ||
| 162 | + exp: i64, | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// The in-flight login: PKCE verifier, state, nonce, and where to land after. | ||
| 166 | +#[derive(Serialize, Deserialize)] | ||
| 167 | +struct InFlight { | ||
| 168 | + verifier: String, | ||
| 169 | + state: String, | ||
| 170 | + nonce: String, | ||
| 171 | + next: String, | ||
| 172 | + exp: i64, | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +const IN_FLIGHT_MINUTES: i64 = 10; | ||
| 176 | + | ||
| 177 | +fn seal(key: &[u8; 32], plaintext: &[u8]) -> String { | ||
| 178 | + let cipher = XChaCha20Poly1305::new(key.into()); | ||
| 179 | + let mut nonce_bytes = [0u8; 24]; | ||
| 180 | + rand::rng().fill_bytes(&mut nonce_bytes); | ||
| 181 | + let ciphertext = cipher | ||
| 182 | + .encrypt(XNonce::from_slice(&nonce_bytes), plaintext) | ||
| 183 | + .expect("XChaCha20-Poly1305 cannot fail on a payload this small"); | ||
| 184 | + let mut payload = nonce_bytes.to_vec(); | ||
| 185 | + payload.extend_from_slice(&ciphertext); | ||
| 186 | + b64url.encode(payload) | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> { | ||
| 190 | + let payload = b64url.decode(sealed).ok()?; | ||
| 191 | + if payload.len() < 24 { | ||
| 192 | + return None; | ||
| 193 | + } | ||
| 194 | + let (nonce_bytes, ciphertext) = payload.split_at(24); | ||
| 195 | + let cipher = XChaCha20Poly1305::new(key.into()); | ||
| 196 | + cipher | ||
| 197 | + .decrypt(XNonce::from_slice(nonce_bytes), ciphertext) | ||
| 198 | + .ok() | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +fn seal_json<T: Serialize>(key: &[u8; 32], value: &T) -> String { | ||
| 202 | + seal(key, &serde_json::to_vec(value).expect("plain data")) | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +fn open_json<T: for<'de> Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option<T> { | ||
| 206 | + serde_json::from_slice(&open(key, sealed)?).ok() | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +fn app_cookies(cx: &Cx) -> impl Cookies { | ||
| 210 | + cookies(cx) | ||
| 211 | + .default_secure(client(cx).config.issuer.starts_with("https://")) | ||
| 212 | + .default_http_only(true) | ||
| 213 | + .default_same_site(topcoat::cookie::SameSite::Lax) | ||
| 214 | + .default_path("/") | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +fn set_session_cookie(cx: &Cx, state: &ImClient, session: &Session) { | ||
| 218 | + let name = state.config.cookie_name.clone(); | ||
| 219 | + app_cookies(cx).add(cookie! { | ||
| 220 | + name = seal_json(&state.config.cookie_key, session); | ||
| 221 | + Path = "/"; | ||
| 222 | + HttpOnly; | ||
| 223 | + SameSite = Lax; | ||
| 224 | + MaxAge = time::Duration::days(30) | ||
| 225 | + }); | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +fn clear_cookie(cx: &Cx, name: &str) { | ||
| 229 | + app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build()); | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +// --------------------------------------------------------------------------- | ||
| 233 | +// Routes | ||
| 234 | +// --------------------------------------------------------------------------- | ||
| 235 | + | ||
| 236 | +fn see(cx: &Cx, location: &str) -> Result<Response, topcoat::Error> { | ||
| 237 | + ( | ||
| 238 | + StatusCode::SEE_OTHER, | ||
| 239 | + [(header::LOCATION, HeaderValue::from_str(location).unwrap())], | ||
| 240 | + ) | ||
| 241 | + .into_response(cx) | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +/// A `next` worth honoring: a local absolute path, never `//elsewhere`. | ||
| 245 | +fn safe_next(raw: &str) -> &str { | ||
| 246 | + if raw.starts_with('/') && !raw.starts_with("//") { | ||
| 247 | + raw | ||
| 248 | + } else { | ||
| 249 | + "/" | ||
| 250 | + } | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +/// A JWKS older than this is refreshed before the next validation. | ||
| 254 | +const JWKS_TTL_SECONDS: i64 = 3600; | ||
| 255 | + | ||
| 256 | +async fn jwks_stale(state: &ImClient) -> bool { | ||
| 257 | + match state.jwks.read().await.as_ref() { | ||
| 258 | + None => true, | ||
| 259 | + Some(cache) => { | ||
| 260 | + cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS) | ||
| 261 | + } | ||
| 262 | + } | ||
| 263 | +} | ||
| 264 | + | ||
| 265 | +fn query_value(query: &str, key: &str) -> Option<String> { | ||
| 266 | + query.split('&').find_map(|pair| { | ||
| 267 | + let (k, v) = pair.split_once('=')?; | ||
| 268 | + (k == key).then(|| urldecode(v)) | ||
| 269 | + }) | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// Percent-decodes a query value (`+` is a space, form-style). | ||
| 273 | +fn urldecode(raw: &str) -> String { | ||
| 274 | + let bytes = raw.as_bytes(); | ||
| 275 | + let mut out = Vec::with_capacity(bytes.len()); | ||
| 276 | + let mut i = 0; | ||
| 277 | + while i < bytes.len() { | ||
| 278 | + match bytes[i] { | ||
| 279 | + b'+' => { | ||
| 280 | + out.push(b' '); | ||
| 281 | + i += 1; | ||
| 282 | + } | ||
| 283 | + b'%' if i + 2 < bytes.len() => { | ||
| 284 | + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); | ||
| 285 | + match u8::from_str_radix(hex, 16) { | ||
| 286 | + Ok(byte) => { | ||
| 287 | + out.push(byte); | ||
| 288 | + i += 3; | ||
| 289 | + } | ||
| 290 | + Err(_) => { | ||
| 291 | + out.push(b'%'); | ||
| 292 | + i += 1; | ||
| 293 | + } | ||
| 294 | + } | ||
| 295 | + } | ||
| 296 | + byte => { | ||
| 297 | + out.push(byte); | ||
| 298 | + i += 1; | ||
| 299 | + } | ||
| 300 | + } | ||
| 301 | + } | ||
| 302 | + String::from_utf8_lossy(&out).into_owned() | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +fn random_b64(bytes: usize) -> String { | ||
| 306 | + let mut buf = vec![0u8; bytes]; | ||
| 307 | + rand::rng().fill_bytes(&mut buf); | ||
| 308 | + b64url.encode(buf) | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +/// Sends the browser to im's `/authorize` with a fresh PKCE pair. | ||
| 312 | +#[route(GET "/auth/login")] | ||
| 313 | +async fn im_login(cx: &Cx) -> Result<Response, topcoat::Error> { | ||
| 314 | + let state = client(cx); | ||
| 315 | + let query = topcoat::router::request::uri(cx) | ||
| 316 | + .query() | ||
| 317 | + .unwrap_or("") | ||
| 318 | + .to_string(); | ||
| 319 | + let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string(); | ||
| 320 | + | ||
| 321 | + let flight = InFlight { | ||
| 322 | + verifier: random_b64(32), | ||
| 323 | + state: random_b64(16), | ||
| 324 | + nonce: random_b64(16), | ||
| 325 | + next, | ||
| 326 | + exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60, | ||
| 327 | + }; | ||
| 328 | + let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes())); | ||
| 329 | + let cookie_name = format!("{}_pkce", state.config.cookie_name); | ||
| 330 | + app_cookies(cx).add(cookie! { | ||
| 331 | + cookie_name = seal_json(&state.config.cookie_key, &flight); | ||
| 332 | + Path = "/"; | ||
| 333 | + HttpOnly; | ||
| 334 | + SameSite = Lax; | ||
| 335 | + MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES) | ||
| 336 | + }); | ||
| 337 | + | ||
| 338 | + let url = format!( | ||
| 339 | + "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256", | ||
| 340 | + state.config.issuer, | ||
| 341 | + state.config.client_id, | ||
| 342 | + urlencoded(&state.config.redirect_uri), | ||
| 343 | + flight.state, | ||
| 344 | + flight.nonce, | ||
| 345 | + challenge, | ||
| 346 | + ); | ||
| 347 | + see(cx, &url) | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +/// im's answer lands here: exchange the code, validate the id_token, mint | ||
| 351 | +/// the app session. | ||
| 352 | +#[route(GET "/auth/callback")] | ||
| 353 | +async fn im_callback(cx: &Cx) -> Result<Response, topcoat::Error> { | ||
| 354 | + let state = client(cx); | ||
| 355 | + let query = topcoat::router::request::uri(cx) | ||
| 356 | + .query() | ||
| 357 | + .unwrap_or("") | ||
| 358 | + .to_string(); | ||
| 359 | + if let Some(error) = query_value(&query, "error") { | ||
| 360 | + return see(cx, &format!("/?auth_error={error}")); | ||
| 361 | + } | ||
| 362 | + let (Some(code), Some(presented_state)) = | ||
| 363 | + (query_value(&query, "code"), query_value(&query, "state")) | ||
| 364 | + else { | ||
| 365 | + return see(cx, "/?auth_error=invalid_request"); | ||
| 366 | + }; | ||
| 367 | + let cookie_name = format!("{}_pkce", state.config.cookie_name); | ||
| 368 | + let flight: Option<InFlight> = cookies(cx) | ||
| 369 | + .get(&cookie_name) | ||
| 370 | + .and_then(|c| open_json(&state.config.cookie_key, c.value())); | ||
| 371 | + let Some(flight) = flight else { | ||
| 372 | + return see(cx, "/?auth_error=invalid_request"); | ||
| 373 | + }; | ||
| 374 | + clear_cookie(cx, &cookie_name); | ||
| 375 | + if flight.exp <= OffsetDateTime::now_utc().unix_timestamp() | ||
| 376 | + || flight | ||
| 377 | + .state | ||
| 378 | + .as_bytes() | ||
| 379 | + .ct_eq(presented_state.as_bytes()) | ||
| 380 | + .unwrap_u8() | ||
| 381 | + != 1 | ||
| 382 | + { | ||
| 383 | + return see(cx, "/?auth_error=invalid_state"); | ||
| 384 | + } | ||
| 385 | + | ||
| 386 | + match exchange_code(state, &code, &flight).await { | ||
| 387 | + Ok(session) => { | ||
| 388 | + set_session_cookie(cx, state, &session); | ||
| 389 | + see(cx, &flight.next) | ||
| 390 | + } | ||
| 391 | + Err(_) => see(cx, "/?auth_error=exchange_failed"), | ||
| 392 | + } | ||
| 393 | +} | ||
| 394 | + | ||
| 395 | +/// Signs out of the app only. To end the central session too, post to im's | ||
| 396 | +/// `/logout` — a link there is a silent re-login, by design. | ||
| 397 | +#[route(GET "/auth/logout")] | ||
| 398 | +async fn im_logout(cx: &Cx) -> Result<Response, topcoat::Error> { | ||
| 399 | + clear_cookie(cx, &client(cx).config.cookie_name); | ||
| 400 | + see(cx, "/") | ||
| 401 | +} | ||
| 402 | + | ||
| 403 | +fn urlencoded(raw: &str) -> String { | ||
| 404 | + let mut out = String::with_capacity(raw.len()); | ||
| 405 | + for byte in raw.bytes() { | ||
| 406 | + match byte { | ||
| 407 | + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { | ||
| 408 | + out.push(byte as char) | ||
| 409 | + } | ||
| 410 | + _ => out.push_str(&format!("%{byte:02X}")), | ||
| 411 | + } | ||
| 412 | + } | ||
| 413 | + out | ||
| 414 | +} | ||
| 415 | + | ||
| 416 | +// --------------------------------------------------------------------------- | ||
| 417 | +// Token exchange, refresh, validation | ||
| 418 | +// --------------------------------------------------------------------------- | ||
| 419 | + | ||
| 420 | +#[derive(Deserialize)] | ||
| 421 | +struct TokenAnswer { | ||
| 422 | + /// Validated for its nonce and signature; the identity the app serves | ||
| 423 | + /// comes from introspection, not from these claims. | ||
| 424 | + id_token: String, | ||
| 425 | + /// Not OIDC — im's own: the opaque session this crate introspects per | ||
| 426 | + /// request. Absent means the issuer is not a current im. | ||
| 427 | + app_session: Option<String>, | ||
| 428 | +} | ||
| 429 | + | ||
| 430 | +async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result<Session> { | ||
| 431 | + let answer: TokenAnswer = state | ||
| 432 | + .http | ||
| 433 | + .post(format!("{}/token", state.config.issuer)) | ||
| 434 | + .form(&[ | ||
| 435 | + ("grant_type", "authorization_code"), | ||
| 436 | + ("code", code), | ||
| 437 | + ("redirect_uri", &state.config.redirect_uri), | ||
| 438 | + ("client_id", &state.config.client_id), | ||
| 439 | + ("client_secret", &state.config.client_secret), | ||
| 440 | + ("code_verifier", &flight.verifier), | ||
| 441 | + ]) | ||
| 442 | + .send() | ||
| 443 | + .await | ||
| 444 | + .map_err(|e| Error::Http(e.to_string()))? | ||
| 445 | + .error_for_status() | ||
| 446 | + .map_err(|e| Error::Refused(e.to_string()))? | ||
| 447 | + .json() | ||
| 448 | + .await | ||
| 449 | + .map_err(|e| Error::Http(e.to_string()))?; | ||
| 450 | + let claims = validate_id_token(state, &answer.id_token).await?; | ||
| 451 | + if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { | ||
| 452 | + return Err(Error::Token("nonce mismatch".into())); | ||
| 453 | + } | ||
| 454 | + let app_session = answer | ||
| 455 | + .app_session | ||
| 456 | + .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; | ||
| 457 | + // The session's expiry and identity come from a live introspection, not | ||
| 458 | + // from the token answer — the same check every later request will make. | ||
| 459 | + let (_user, exp) = introspect(state, &app_session) | ||
| 460 | + .await | ||
| 461 | + .ok_or_else(|| Error::Refused("fresh app session does not introspect".into()))?; | ||
| 462 | + Ok(Session { app_session, exp }) | ||
| 463 | +} | ||
| 464 | + | ||
| 465 | +/// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry. | ||
| 466 | +/// The nonce is the caller's to check (only the callback holds one). | ||
| 467 | +async fn validate_id_token(state: &ImClient, token: &str) -> Result<serde_json::Value> { | ||
| 468 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 469 | + if parts.len() != 3 { | ||
| 470 | + return Err(Error::Token("not a compact JWT".into())); | ||
| 471 | + } | ||
| 472 | + let header: serde_json::Value = serde_json::from_slice( | ||
| 473 | + &b64url | ||
| 474 | + .decode(parts[0]) | ||
| 475 | + .map_err(|e| Error::Token(e.to_string()))?, | ||
| 476 | + ) | ||
| 477 | + .map_err(|e| Error::Token(e.to_string()))?; | ||
| 478 | + if header["alg"] != "RS256" { | ||
| 479 | + return Err(Error::Token("unexpected alg".into())); | ||
| 480 | + } | ||
| 481 | + let kid = header["kid"] | ||
| 482 | + .as_str() | ||
| 483 | + .ok_or_else(|| Error::Token("no kid".into()))? | ||
| 484 | + .to_string(); | ||
| 485 | + | ||
| 486 | + if jwks_stale(state).await { | ||
| 487 | + refetch_jwks(state).await?; | ||
| 488 | + } | ||
| 489 | + let key = match cached_key(state, &kid).await { | ||
| 490 | + Some(key) => key, | ||
| 491 | + None => { | ||
| 492 | + refetch_jwks(state).await?; | ||
| 493 | + cached_key(state, &kid) | ||
| 494 | + .await | ||
| 495 | + .ok_or_else(|| Error::Token("unknown kid after refetch".into()))? | ||
| 496 | + } | ||
| 497 | + }; | ||
| 498 | + | ||
| 499 | + verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id) | ||
| 500 | +} | ||
| 501 | + | ||
| 502 | +/// The pure half of [`validate_id_token`]: signature, issuer, audience, | ||
| 503 | +/// expiry. Split out so the test suite signs its own tokens without standing | ||
| 504 | +/// a server up. | ||
| 505 | +fn verify_claims( | ||
| 506 | + parts: &[&str], | ||
| 507 | + key: &rsa::RsaPublicKey, | ||
| 508 | + issuer: &str, | ||
| 509 | + client_id: &str, | ||
| 510 | +) -> Result<serde_json::Value> { | ||
| 511 | + use rsa::signature::Verifier; | ||
| 512 | + let signature_bytes = b64url | ||
| 513 | + .decode(parts[2]) | ||
| 514 | + .map_err(|e| Error::Token(e.to_string()))?; | ||
| 515 | + let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) | ||
| 516 | + .map_err(|e| Error::Token(e.to_string()))?; | ||
| 517 | + let verifying = rsa::pkcs1v15::VerifyingKey::<sha2_for_rsa::Sha256>::new(key.clone()); | ||
| 518 | + verifying | ||
| 519 | + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) | ||
| 520 | + .map_err(|_| Error::Token("bad signature".into()))?; | ||
| 521 | + | ||
| 522 | + let claims: serde_json::Value = serde_json::from_slice( | ||
| 523 | + &b64url | ||
| 524 | + .decode(parts[1]) | ||
| 525 | + .map_err(|e| Error::Token(e.to_string()))?, | ||
| 526 | + ) | ||
| 527 | + .map_err(|e| Error::Token(e.to_string()))?; | ||
| 528 | + if claims["iss"].as_str() != Some(issuer) { | ||
| 529 | + return Err(Error::Token("wrong issuer".into())); | ||
| 530 | + } | ||
| 531 | + if claims["aud"].as_str() != Some(client_id) { | ||
| 532 | + return Err(Error::Token("wrong audience".into())); | ||
| 533 | + } | ||
| 534 | + match claims["exp"].as_i64() { | ||
| 535 | + Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {} | ||
| 536 | + _ => return Err(Error::Token("expired".into())), | ||
| 537 | + } | ||
| 538 | + Ok(claims) | ||
| 539 | +} | ||
| 540 | + | ||
| 541 | +async fn cached_key(state: &ImClient, kid: &str) -> Option<rsa::RsaPublicKey> { | ||
| 542 | + state | ||
| 543 | + .jwks | ||
| 544 | + .read() | ||
| 545 | + .await | ||
| 546 | + .as_ref()? | ||
| 547 | + .keys | ||
| 548 | + .iter() | ||
| 549 | + .find(|(k, _)| k == kid) | ||
| 550 | + .map(|(_, key)| key.clone()) | ||
| 551 | +} | ||
| 552 | + | ||
| 553 | +/// Fetches and caches im's JWKS. Cached for an hour at most; an unknown kid | ||
| 554 | +/// forces an immediate refetch above. | ||
| 555 | +async fn refetch_jwks(state: &ImClient) -> Result<()> { | ||
| 556 | + let doc: serde_json::Value = state | ||
| 557 | + .http | ||
| 558 | + .get(format!("{}/jwks.json", state.config.issuer)) | ||
| 559 | + .send() | ||
| 560 | + .await | ||
| 561 | + .map_err(|e| Error::Http(e.to_string()))? | ||
| 562 | + .error_for_status() | ||
| 563 | + .map_err(|e| Error::Refused(e.to_string()))? | ||
| 564 | + .json() | ||
| 565 | + .await | ||
| 566 | + .map_err(|e| Error::Http(e.to_string()))?; | ||
| 567 | + let mut keys = Vec::new(); | ||
| 568 | + for jwk in doc["keys"].as_array().into_iter().flatten() { | ||
| 569 | + let (Some(kid), Some(n), Some(e)) = | ||
| 570 | + (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str()) | ||
| 571 | + else { | ||
| 572 | + continue; | ||
| 573 | + }; | ||
| 574 | + let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else { | ||
| 575 | + continue; | ||
| 576 | + }; | ||
| 577 | + let key = rsa::RsaPublicKey::new( | ||
| 578 | + rsa::BigUint::from_bytes_be(&n), | ||
| 579 | + rsa::BigUint::from_bytes_be(&e), | ||
| 580 | + ) | ||
| 581 | + .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?; | ||
| 582 | + keys.push((kid.to_string(), key)); | ||
| 583 | + } | ||
| 584 | + *state.jwks.write().await = Some(JwksCache { | ||
| 585 | + fetched_at: OffsetDateTime::now_utc(), | ||
| 586 | + keys, | ||
| 587 | + }); | ||
| 588 | + Ok(()) | ||
| 589 | +} | ||
| 590 | + | ||
| 591 | +#[cfg(test)] | ||
| 592 | +mod tests { | ||
| 593 | + use super::*; | ||
| 594 | + use rsa::signature::{SignatureEncoding, Signer}; | ||
| 595 | + | ||
| 596 | + fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) { | ||
| 597 | + // 2048-bit generation is slow for a unit test; 1024 is the smallest | ||
| 598 | + // rsa 0.9 accepts and the signature math under test is identical. | ||
| 599 | + let private = rsa::RsaPrivateKey::new(&mut rand_core06::OsRng, 1024).unwrap(); | ||
| 600 | + let public = private.to_public_key(); | ||
| 601 | + (private, public) | ||
| 602 | + } | ||
| 603 | + | ||
| 604 | + fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String { | ||
| 605 | + let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"}); | ||
| 606 | + let mut out = b64url.encode(header.to_string()); | ||
| 607 | + out.push('.'); | ||
| 608 | + out.push_str(&b64url.encode(claims.to_string())); | ||
| 609 | + let signing = rsa::pkcs1v15::SigningKey::<sha2_for_rsa::Sha256>::new(key.clone()); | ||
| 610 | + let signature = signing.sign(out.as_bytes()); | ||
| 611 | + format!("{}.{}", out, b64url.encode(signature.to_bytes())) | ||
| 612 | + } | ||
| 613 | + | ||
| 614 | + fn good_claims() -> serde_json::Value { | ||
| 615 | + serde_json::json!({ | ||
| 616 | + "iss": "http://im.test", | ||
| 617 | + "sub": "user-1", | ||
| 618 | + "aud": "client-1", | ||
| 619 | + "exp": OffsetDateTime::now_utc().unix_timestamp() + 600, | ||
| 620 | + "iat": OffsetDateTime::now_utc().unix_timestamp(), | ||
| 621 | + "email": "ann@example.com", | ||
| 622 | + "name": "Ann", | ||
| 623 | + }) | ||
| 624 | + } | ||
| 625 | + | ||
| 626 | + #[test] | ||
| 627 | + fn valid_token_validates() { | ||
| 628 | + let (private, public) = keypair(); | ||
| 629 | + let token = sign(good_claims(), &private); | ||
| 630 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 631 | + let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap(); | ||
| 632 | + assert_eq!(claims["sub"], "user-1"); | ||
| 633 | + } | ||
| 634 | + | ||
| 635 | + #[test] | ||
| 636 | + fn tampered_payload_rejected() { | ||
| 637 | + let (private, public) = keypair(); | ||
| 638 | + let token = sign(good_claims(), &private); | ||
| 639 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 640 | + let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#); | ||
| 641 | + let forged = vec![parts[0], forged_payload.as_str(), parts[2]]; | ||
| 642 | + assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err()); | ||
| 643 | + } | ||
| 644 | + | ||
| 645 | + #[test] | ||
| 646 | + fn wrong_key_rejected() { | ||
| 647 | + let (private, _) = keypair(); | ||
| 648 | + let (_, other_public) = keypair(); | ||
| 649 | + let token = sign(good_claims(), &private); | ||
| 650 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 651 | + assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err()); | ||
| 652 | + } | ||
| 653 | + | ||
| 654 | + #[test] | ||
| 655 | + fn wrong_audience_rejected() { | ||
| 656 | + let (private, public) = keypair(); | ||
| 657 | + let token = sign(good_claims(), &private); | ||
| 658 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 659 | + assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err()); | ||
| 660 | + } | ||
| 661 | + | ||
| 662 | + #[test] | ||
| 663 | + fn wrong_issuer_rejected() { | ||
| 664 | + let (private, public) = keypair(); | ||
| 665 | + let token = sign(good_claims(), &private); | ||
| 666 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 667 | + assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err()); | ||
| 668 | + } | ||
| 669 | + | ||
| 670 | + #[test] | ||
| 671 | + fn expired_rejected() { | ||
| 672 | + let (private, public) = keypair(); | ||
| 673 | + let mut claims = good_claims(); | ||
| 674 | + claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into(); | ||
| 675 | + let token = sign(claims, &private); | ||
| 676 | + let parts: Vec<&str> = token.split('.').collect(); | ||
| 677 | + assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err()); | ||
| 678 | + } | ||
| 679 | + | ||
| 680 | + #[test] | ||
| 681 | + fn pkce_rfc7636_vector() { | ||
| 682 | + // RFC 7636 Appendix B. | ||
| 683 | + let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; | ||
| 684 | + let challenge = b64url.encode(Sha256::digest(verifier.as_bytes())); | ||
| 685 | + assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); | ||
| 686 | + } | ||
| 687 | + | ||
| 688 | + #[test] | ||
| 689 | + fn cookie_seal_roundtrip() { | ||
| 690 | + let key = [7u8; 32]; | ||
| 691 | + let session = Session { | ||
| 692 | + app_session: "opaque-token".into(), | ||
| 693 | + exp: 1, | ||
| 694 | + }; | ||
| 695 | + let sealed = seal_json(&key, &session); | ||
| 696 | + let back: Session = open_json(&key, &sealed).unwrap(); | ||
| 697 | + assert_eq!(back.app_session, "opaque-token"); | ||
| 698 | + assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none()); | ||
| 699 | + assert!(open_json::<Session>(&key, "garbage").is_none()); | ||
| 700 | + } | ||
| 701 | +} | ||