| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 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 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | #[derive(Clone)] |
| 39 | pub struct Config { |
| 40 | |
| 41 | pub issuer: String, |
| 42 | pub client_id: String, |
| 43 | pub client_secret: String, |
| 44 | |
| 45 | pub redirect_uri: String, |
| 46 | |
| 47 | pub cookie_name: String, |
| 48 | |
| 49 | pub cookie_key: [u8; 32], |
| 50 | } |
| 51 | |
| 52 | |
| 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 | |
| 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 | |
| 76 | |
| 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 | |
| 86 | |
| 87 | |
| 88 | |
| 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 | |
| 107 | |
| 108 | |
| 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 | |
| 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 | |
| 148 | |
| 149 | #[serde(default)] |
| 150 | pub photo_version: u64, |
| 151 | } |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | #[derive(Serialize, Deserialize)] |
| 158 | struct Session { |
| 159 | |
| 160 | |
| 161 | app_session: String, |
| 162 | exp: i64, |
| 163 | } |
| 164 | |
| 165 | |
| 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 nonce = XNonce::from(nonce_bytes); |
| 182 | let ciphertext = cipher |
| 183 | .encrypt(&nonce, plaintext) |
| 184 | .expect("XChaCha20-Poly1305 cannot fail on a payload this small"); |
| 185 | let mut payload = nonce_bytes.to_vec(); |
| 186 | payload.extend_from_slice(&ciphertext); |
| 187 | b64url.encode(payload) |
| 188 | } |
| 189 | |
| 190 | fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> { |
| 191 | let payload = b64url.decode(sealed).ok()?; |
| 192 | if payload.len() < 24 { |
| 193 | return None; |
| 194 | } |
| 195 | let (nonce_bytes, ciphertext) = payload.split_at(24); |
| 196 | let cipher = XChaCha20Poly1305::new(key.into()); |
| 197 | let nonce: &XNonce = nonce_bytes.try_into().ok()?; |
| 198 | cipher.decrypt(nonce, ciphertext).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 | |
| 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 | |
| 245 | |
| 246 | |
| 247 | fn safe_next(raw: &str) -> &str { |
| 248 | if raw.starts_with('/') && !raw.starts_with("//") && !raw.contains('\\') { |
| 249 | raw |
| 250 | } else { |
| 251 | "/" |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | |
| 256 | const JWKS_TTL_SECONDS: i64 = 3600; |
| 257 | |
| 258 | async fn jwks_stale(state: &ImClient) -> bool { |
| 259 | match state.jwks.read().await.as_ref() { |
| 260 | None => true, |
| 261 | Some(cache) => { |
| 262 | cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS) |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | fn query_value(query: &str, key: &str) -> Option<String> { |
| 268 | query.split('&').find_map(|pair| { |
| 269 | let (k, v) = pair.split_once('=')?; |
| 270 | (k == key).then(|| urldecode(v)) |
| 271 | }) |
| 272 | } |
| 273 | |
| 274 | |
| 275 | fn urldecode(raw: &str) -> String { |
| 276 | let bytes = raw.as_bytes(); |
| 277 | let mut out = Vec::with_capacity(bytes.len()); |
| 278 | let mut i = 0; |
| 279 | while i < bytes.len() { |
| 280 | match bytes[i] { |
| 281 | b'+' => { |
| 282 | out.push(b' '); |
| 283 | i += 1; |
| 284 | } |
| 285 | b'%' if i + 2 < bytes.len() => { |
| 286 | let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); |
| 287 | match u8::from_str_radix(hex, 16) { |
| 288 | Ok(byte) => { |
| 289 | out.push(byte); |
| 290 | i += 3; |
| 291 | } |
| 292 | Err(_) => { |
| 293 | out.push(b'%'); |
| 294 | i += 1; |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | byte => { |
| 299 | out.push(byte); |
| 300 | i += 1; |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | String::from_utf8_lossy(&out).into_owned() |
| 305 | } |
| 306 | |
| 307 | fn random_b64(bytes: usize) -> String { |
| 308 | let mut buf = vec![0u8; bytes]; |
| 309 | rand::rng().fill_bytes(&mut buf); |
| 310 | b64url.encode(buf) |
| 311 | } |
| 312 | |
| 313 | |
| 314 | #[route(GET "/auth/login")] |
| 315 | async fn im_login(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 316 | let state = client(cx); |
| 317 | let query = topcoat::router::request::uri(cx) |
| 318 | .query() |
| 319 | .unwrap_or("") |
| 320 | .to_string(); |
| 321 | let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string(); |
| 322 | |
| 323 | let flight = InFlight { |
| 324 | verifier: random_b64(32), |
| 325 | state: random_b64(16), |
| 326 | nonce: random_b64(16), |
| 327 | next, |
| 328 | exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60, |
| 329 | }; |
| 330 | let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes())); |
| 331 | let cookie_name = format!("{}_pkce", state.config.cookie_name); |
| 332 | app_cookies(cx).add(cookie! { |
| 333 | cookie_name = seal_json(&state.config.cookie_key, &flight); |
| 334 | Path = "/"; |
| 335 | HttpOnly; |
| 336 | SameSite = Lax; |
| 337 | MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES) |
| 338 | }); |
| 339 | |
| 340 | let url = format!( |
| 341 | "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256", |
| 342 | state.config.issuer, |
| 343 | state.config.client_id, |
| 344 | urlencoded(&state.config.redirect_uri), |
| 345 | flight.state, |
| 346 | flight.nonce, |
| 347 | challenge, |
| 348 | ); |
| 349 | see(cx, &url) |
| 350 | } |
| 351 | |
| 352 | |
| 353 | |
| 354 | #[route(GET "/auth/callback")] |
| 355 | async fn im_callback(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 356 | let state = client(cx); |
| 357 | let query = topcoat::router::request::uri(cx) |
| 358 | .query() |
| 359 | .unwrap_or("") |
| 360 | .to_string(); |
| 361 | if let Some(error) = query_value(&query, "error") { |
| 362 | return see(cx, &format!("/?auth_error={error}")); |
| 363 | } |
| 364 | let (Some(code), Some(presented_state)) = |
| 365 | (query_value(&query, "code"), query_value(&query, "state")) |
| 366 | else { |
| 367 | return see(cx, "/?auth_error=invalid_request"); |
| 368 | }; |
| 369 | let cookie_name = format!("{}_pkce", state.config.cookie_name); |
| 370 | let flight: Option<InFlight> = cookies(cx) |
| 371 | .get(&cookie_name) |
| 372 | .and_then(|c| open_json(&state.config.cookie_key, c.value())); |
| 373 | let Some(flight) = flight else { |
| 374 | return see(cx, "/?auth_error=invalid_request"); |
| 375 | }; |
| 376 | clear_cookie(cx, &cookie_name); |
| 377 | if flight.exp <= OffsetDateTime::now_utc().unix_timestamp() |
| 378 | || flight |
| 379 | .state |
| 380 | .as_bytes() |
| 381 | .ct_eq(presented_state.as_bytes()) |
| 382 | .unwrap_u8() |
| 383 | != 1 |
| 384 | { |
| 385 | return see(cx, "/?auth_error=invalid_state"); |
| 386 | } |
| 387 | |
| 388 | match exchange_code(state, &code, &flight).await { |
| 389 | Ok(session) => { |
| 390 | set_session_cookie(cx, state, &session); |
| 391 | see(cx, &flight.next) |
| 392 | } |
| 393 | Err(_) => see(cx, "/?auth_error=exchange_failed"), |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | |
| 398 | |
| 399 | #[route(GET "/auth/logout")] |
| 400 | async fn im_logout(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 401 | clear_cookie(cx, &client(cx).config.cookie_name); |
| 402 | see(cx, "/") |
| 403 | } |
| 404 | |
| 405 | fn urlencoded(raw: &str) -> String { |
| 406 | let mut out = String::with_capacity(raw.len()); |
| 407 | for byte in raw.bytes() { |
| 408 | match byte { |
| 409 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { |
| 410 | out.push(byte as char) |
| 411 | } |
| 412 | _ => out.push_str(&format!("%{byte:02X}")), |
| 413 | } |
| 414 | } |
| 415 | out |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | #[derive(Deserialize)] |
| 423 | struct TokenAnswer { |
| 424 | |
| 425 | |
| 426 | id_token: String, |
| 427 | |
| 428 | |
| 429 | app_session: Option<String>, |
| 430 | } |
| 431 | |
| 432 | async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result<Session> { |
| 433 | let answer: TokenAnswer = state |
| 434 | .http |
| 435 | .post(format!("{}/token", state.config.issuer)) |
| 436 | .form(&[ |
| 437 | ("grant_type", "authorization_code"), |
| 438 | ("code", code), |
| 439 | ("redirect_uri", &state.config.redirect_uri), |
| 440 | ("client_id", &state.config.client_id), |
| 441 | ("client_secret", &state.config.client_secret), |
| 442 | ("code_verifier", &flight.verifier), |
| 443 | ]) |
| 444 | .send() |
| 445 | .await |
| 446 | .map_err(|e| Error::Http(e.to_string()))? |
| 447 | .error_for_status() |
| 448 | .map_err(|e| Error::Refused(e.to_string()))? |
| 449 | .json() |
| 450 | .await |
| 451 | .map_err(|e| Error::Http(e.to_string()))?; |
| 452 | let claims = validate_id_token(state, &answer.id_token).await?; |
| 453 | if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { |
| 454 | return Err(Error::Token("nonce mismatch".into())); |
| 455 | } |
| 456 | let app_session = answer |
| 457 | .app_session |
| 458 | .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; |
| 459 | |
| 460 | |
| 461 | let (_user, exp) = introspect(state, &app_session) |
| 462 | .await |
| 463 | .ok_or_else(|| Error::Refused("fresh app session does not introspect".into()))?; |
| 464 | Ok(Session { app_session, exp }) |
| 465 | } |
| 466 | |
| 467 | |
| 468 | |
| 469 | async fn validate_id_token(state: &ImClient, token: &str) -> Result<serde_json::Value> { |
| 470 | let parts: Vec<&str> = token.split('.').collect(); |
| 471 | if parts.len() != 3 { |
| 472 | return Err(Error::Token("not a compact JWT".into())); |
| 473 | } |
| 474 | let header: serde_json::Value = serde_json::from_slice( |
| 475 | &b64url |
| 476 | .decode(parts[0]) |
| 477 | .map_err(|e| Error::Token(e.to_string()))?, |
| 478 | ) |
| 479 | .map_err(|e| Error::Token(e.to_string()))?; |
| 480 | if header["alg"] != "RS256" { |
| 481 | return Err(Error::Token("unexpected alg".into())); |
| 482 | } |
| 483 | let kid = header["kid"] |
| 484 | .as_str() |
| 485 | .ok_or_else(|| Error::Token("no kid".into()))? |
| 486 | .to_string(); |
| 487 | |
| 488 | if jwks_stale(state).await { |
| 489 | refetch_jwks(state).await?; |
| 490 | } |
| 491 | let key = match cached_key(state, &kid).await { |
| 492 | Some(key) => key, |
| 493 | None => { |
| 494 | refetch_jwks(state).await?; |
| 495 | cached_key(state, &kid) |
| 496 | .await |
| 497 | .ok_or_else(|| Error::Token("unknown kid after refetch".into()))? |
| 498 | } |
| 499 | }; |
| 500 | |
| 501 | verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id) |
| 502 | } |
| 503 | |
| 504 | |
| 505 | |
| 506 | |
| 507 | fn verify_claims( |
| 508 | parts: &[&str], |
| 509 | key: &rsa::RsaPublicKey, |
| 510 | issuer: &str, |
| 511 | client_id: &str, |
| 512 | ) -> Result<serde_json::Value> { |
| 513 | use rsa::signature::Verifier; |
| 514 | let signature_bytes = b64url |
| 515 | .decode(parts[2]) |
| 516 | .map_err(|e| Error::Token(e.to_string()))?; |
| 517 | let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) |
| 518 | .map_err(|e| Error::Token(e.to_string()))?; |
| 519 | let verifying = rsa::pkcs1v15::VerifyingKey::<sha2::Sha256>::new(key.clone()); |
| 520 | verifying |
| 521 | .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) |
| 522 | .map_err(|_| Error::Token("bad signature".into()))?; |
| 523 | |
| 524 | let claims: serde_json::Value = serde_json::from_slice( |
| 525 | &b64url |
| 526 | .decode(parts[1]) |
| 527 | .map_err(|e| Error::Token(e.to_string()))?, |
| 528 | ) |
| 529 | .map_err(|e| Error::Token(e.to_string()))?; |
| 530 | if claims["iss"].as_str() != Some(issuer) { |
| 531 | return Err(Error::Token("wrong issuer".into())); |
| 532 | } |
| 533 | if claims["aud"].as_str() != Some(client_id) { |
| 534 | return Err(Error::Token("wrong audience".into())); |
| 535 | } |
| 536 | match claims["exp"].as_i64() { |
| 537 | Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {} |
| 538 | _ => return Err(Error::Token("expired".into())), |
| 539 | } |
| 540 | Ok(claims) |
| 541 | } |
| 542 | |
| 543 | async fn cached_key(state: &ImClient, kid: &str) -> Option<rsa::RsaPublicKey> { |
| 544 | state |
| 545 | .jwks |
| 546 | .read() |
| 547 | .await |
| 548 | .as_ref()? |
| 549 | .keys |
| 550 | .iter() |
| 551 | .find(|(k, _)| k == kid) |
| 552 | .map(|(_, key)| key.clone()) |
| 553 | } |
| 554 | |
| 555 | |
| 556 | |
| 557 | async fn refetch_jwks(state: &ImClient) -> Result<()> { |
| 558 | let doc: serde_json::Value = state |
| 559 | .http |
| 560 | .get(format!("{}/jwks.json", state.config.issuer)) |
| 561 | .send() |
| 562 | .await |
| 563 | .map_err(|e| Error::Http(e.to_string()))? |
| 564 | .error_for_status() |
| 565 | .map_err(|e| Error::Refused(e.to_string()))? |
| 566 | .json() |
| 567 | .await |
| 568 | .map_err(|e| Error::Http(e.to_string()))?; |
| 569 | let mut keys = Vec::new(); |
| 570 | for jwk in doc["keys"].as_array().into_iter().flatten() { |
| 571 | let (Some(kid), Some(n), Some(e)) = |
| 572 | (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str()) |
| 573 | else { |
| 574 | continue; |
| 575 | }; |
| 576 | let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else { |
| 577 | continue; |
| 578 | }; |
| 579 | let key = rsa::RsaPublicKey::new( |
| 580 | rsa::BoxedUint::from_be_slice_vartime(&n), |
| 581 | rsa::BoxedUint::from_be_slice_vartime(&e), |
| 582 | ) |
| 583 | .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?; |
| 584 | keys.push((kid.to_string(), key)); |
| 585 | } |
| 586 | *state.jwks.write().await = Some(JwksCache { |
| 587 | fetched_at: OffsetDateTime::now_utc(), |
| 588 | keys, |
| 589 | }); |
| 590 | Ok(()) |
| 591 | } |
| 592 | |
| 593 | #[cfg(test)] |
| 594 | mod tests { |
| 595 | use super::*; |
| 596 | use rsa::signature::{SignatureEncoding, Signer}; |
| 597 | |
| 598 | fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) { |
| 599 | |
| 600 | |
| 601 | let private = rsa::RsaPrivateKey::new(&mut rand::rng(), 1024).unwrap(); |
| 602 | let public = private.to_public_key(); |
| 603 | (private, public) |
| 604 | } |
| 605 | |
| 606 | fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String { |
| 607 | let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"}); |
| 608 | let mut out = b64url.encode(header.to_string()); |
| 609 | out.push('.'); |
| 610 | out.push_str(&b64url.encode(claims.to_string())); |
| 611 | let signing = rsa::pkcs1v15::SigningKey::<sha2::Sha256>::new(key.clone()); |
| 612 | let signature = signing.sign(out.as_bytes()); |
| 613 | format!("{}.{}", out, b64url.encode(signature.to_bytes())) |
| 614 | } |
| 615 | |
| 616 | fn good_claims() -> serde_json::Value { |
| 617 | serde_json::json!({ |
| 618 | "iss": "http://im.test", |
| 619 | "sub": "user-1", |
| 620 | "aud": "client-1", |
| 621 | "exp": OffsetDateTime::now_utc().unix_timestamp() + 600, |
| 622 | "iat": OffsetDateTime::now_utc().unix_timestamp(), |
| 623 | "email": "ann@example.com", |
| 624 | "name": "Ann", |
| 625 | }) |
| 626 | } |
| 627 | |
| 628 | #[test] |
| 629 | fn valid_token_validates() { |
| 630 | let (private, public) = keypair(); |
| 631 | let token = sign(good_claims(), &private); |
| 632 | let parts: Vec<&str> = token.split('.').collect(); |
| 633 | let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap(); |
| 634 | assert_eq!(claims["sub"], "user-1"); |
| 635 | } |
| 636 | |
| 637 | #[test] |
| 638 | fn tampered_payload_rejected() { |
| 639 | let (private, public) = keypair(); |
| 640 | let token = sign(good_claims(), &private); |
| 641 | let parts: Vec<&str> = token.split('.').collect(); |
| 642 | let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#); |
| 643 | let forged = vec![parts[0], forged_payload.as_str(), parts[2]]; |
| 644 | assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err()); |
| 645 | } |
| 646 | |
| 647 | #[test] |
| 648 | fn wrong_key_rejected() { |
| 649 | let (private, _) = keypair(); |
| 650 | let (_, other_public) = keypair(); |
| 651 | let token = sign(good_claims(), &private); |
| 652 | let parts: Vec<&str> = token.split('.').collect(); |
| 653 | assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err()); |
| 654 | } |
| 655 | |
| 656 | #[test] |
| 657 | fn wrong_audience_rejected() { |
| 658 | let (private, public) = keypair(); |
| 659 | let token = sign(good_claims(), &private); |
| 660 | let parts: Vec<&str> = token.split('.').collect(); |
| 661 | assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err()); |
| 662 | } |
| 663 | |
| 664 | #[test] |
| 665 | fn wrong_issuer_rejected() { |
| 666 | let (private, public) = keypair(); |
| 667 | let token = sign(good_claims(), &private); |
| 668 | let parts: Vec<&str> = token.split('.').collect(); |
| 669 | assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err()); |
| 670 | } |
| 671 | |
| 672 | #[test] |
| 673 | fn expired_rejected() { |
| 674 | let (private, public) = keypair(); |
| 675 | let mut claims = good_claims(); |
| 676 | claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into(); |
| 677 | let token = sign(claims, &private); |
| 678 | let parts: Vec<&str> = token.split('.').collect(); |
| 679 | assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err()); |
| 680 | } |
| 681 | |
| 682 | #[test] |
| 683 | fn pkce_rfc7636_vector() { |
| 684 | |
| 685 | let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; |
| 686 | let challenge = b64url.encode(Sha256::digest(verifier.as_bytes())); |
| 687 | assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); |
| 688 | } |
| 689 | |
| 690 | #[test] |
| 691 | fn next_rejects_scheme_relative_and_backslash_paths() { |
| 692 | assert_eq!(safe_next("/files"), "/files"); |
| 693 | assert_eq!(safe_next("/files?sort=name"), "/files?sort=name"); |
| 694 | assert_eq!(safe_next("//evil.example/path"), "/"); |
| 695 | |
| 696 | |
| 697 | assert_eq!(safe_next("/\\evil.example"), "/"); |
| 698 | assert_eq!(safe_next("https://evil.example"), "/"); |
| 699 | assert_eq!(safe_next("relative"), "/"); |
| 700 | } |
| 701 | |
| 702 | #[test] |
| 703 | fn cookie_seal_roundtrip() { |
| 704 | let key = [7u8; 32]; |
| 705 | let session = Session { |
| 706 | app_session: "opaque-token".into(), |
| 707 | exp: 1, |
| 708 | }; |
| 709 | let sealed = seal_json(&key, &session); |
| 710 | let back: Session = open_json(&key, &sealed).unwrap(); |
| 711 | assert_eq!(back.app_session, "opaque-token"); |
| 712 | assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none()); |
| 713 | assert!(open_json::<Session>(&key, "garbage").is_none()); |
| 714 | } |
| 715 | } |