| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::pin::Pin; |
| 15 | use std::sync::Arc; |
| 16 | |
| 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 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | pub logout_back: String, |
| 61 | } |
| 62 | |
| 63 | |
| 64 | pub struct InClient { |
| 65 | config: Config, |
| 66 | http: reqwest::Client, |
| 67 | jwks: tokio::sync::RwLock<Option<JwksCache>>, |
| 68 | } |
| 69 | |
| 70 | struct JwksCache { |
| 71 | fetched_at: OffsetDateTime, |
| 72 | |
| 73 | keys: Vec<(String, rsa::RsaPublicKey)>, |
| 74 | } |
| 75 | |
| 76 | #[derive(Debug, thiserror::Error)] |
| 77 | pub enum Error { |
| 78 | #[error("http: {0}")] |
| 79 | Http(String), |
| 80 | #[error("im refused: {0}")] |
| 81 | Refused(String), |
| 82 | #[error("bad token: {0}")] |
| 83 | Token(String), |
| 84 | } |
| 85 | |
| 86 | pub type Result<T, E = Error> = std::result::Result<T, E>; |
| 87 | |
| 88 | impl InClient { |
| 89 | pub fn new(config: Config) -> Self { |
| 90 | InClient { |
| 91 | config, |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | http: reqwest::Client::builder() |
| 98 | .timeout(std::time::Duration::from_secs(10)) |
| 99 | .build() |
| 100 | .expect("reqwest client with a timeout"), |
| 101 | jwks: tokio::sync::RwLock::new(None), |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | pub struct LogoutBack(pub Arc<dyn for<'a> Fn(&'a Cx) -> BackAnswer<'a> + Send + Sync>); |
| 113 | |
| 114 | |
| 115 | |
| 116 | pub type BackAnswer<'a> = Pin<Box<dyn Future<Output = Option<String>> + Send + 'a>>; |
| 117 | |
| 118 | |
| 119 | |
| 120 | pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder { |
| 121 | builder.app_context(InClient::new(config)) |
| 122 | } |
| 123 | |
| 124 | fn client(cx: &Cx) -> &InClient { |
| 125 | try_app_context::<InClient>(cx).expect("in_client::mount was called on the router") |
| 126 | } |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | pub async fn current_user(cx: &Cx) -> Option<User> { |
| 133 | let state = client(cx); |
| 134 | let sealed = cookies(cx).get(&state.config.cookie_name)?; |
| 135 | let session: Session = open_json(&state.config.cookie_key, sealed.value())?; |
| 136 | if session.exp <= OffsetDateTime::now_utc().unix_timestamp() { |
| 137 | clear_cookie(cx, &state.config.cookie_name); |
| 138 | return None; |
| 139 | } |
| 140 | match introspect(state, &session.app_session).await { |
| 141 | Introspected::Active(user, _exp) => Some(user), |
| 142 | Introspected::Revoked => { |
| 143 | clear_cookie(cx, &state.config.cookie_name); |
| 144 | None |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | Introspected::Unanswered => None, |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 158 | pub struct ServiceJson { |
| 159 | pub key: String, |
| 160 | pub name: String, |
| 161 | pub url: String, |
| 162 | |
| 163 | |
| 164 | |
| 165 | #[serde(default)] |
| 166 | pub limit_bytes: Option<u64>, |
| 167 | } |
| 168 | |
| 169 | impl InClient { |
| 170 | |
| 171 | |
| 172 | |
| 173 | pub async fn family(&self) -> Option<Vec<ServiceJson>> { |
| 174 | let reply = self |
| 175 | .http |
| 176 | .get(format!("{}/family", self.config.issuer)) |
| 177 | .basic_auth(&self.config.client_id, Some(&self.config.client_secret)) |
| 178 | .send() |
| 179 | .await |
| 180 | .ok()?; |
| 181 | if !reply.status().is_success() { |
| 182 | return None; |
| 183 | } |
| 184 | reply.json().await.ok() |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | pub async fn register_family(&self, key: &str, name: &str, url: &str) -> Result<(), String> { |
| 200 | let reply = self |
| 201 | .http |
| 202 | .post(format!("{}/family/register", self.config.issuer)) |
| 203 | .basic_auth(&self.config.client_id, Some(&self.config.client_secret)) |
| 204 | .json(&ServiceJson { |
| 205 | key: key.to_string(), |
| 206 | name: name.to_string(), |
| 207 | url: url.to_string(), |
| 208 | |
| 209 | limit_bytes: None, |
| 210 | }) |
| 211 | .send() |
| 212 | .await |
| 213 | .map_err(|problem| format!("im did not answer: {problem}"))?; |
| 214 | let status = reply.status(); |
| 215 | if status.is_success() { |
| 216 | return Ok(()); |
| 217 | } |
| 218 | let said = reply.json::<serde_json::Value>().await.ok(); |
| 219 | let detail = said.as_ref().and_then(|said| { |
| 220 | let error = said.get("error")?.as_str()?; |
| 221 | Some(match said.get("reason").and_then(|r| r.as_str()) { |
| 222 | Some(reason) => format!("{error}: {reason}"), |
| 223 | None => error.to_string(), |
| 224 | }) |
| 225 | }); |
| 226 | Err(match detail { |
| 227 | Some(detail) => format!("im refused with {status}: {detail}"), |
| 228 | None => format!("im refused with {status}"), |
| 229 | }) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | pub async fn family(cx: &Cx) -> Option<Vec<ServiceJson>> { |
| 244 | client(cx).family().await |
| 245 | } |
| 246 | |
| 247 | |
| 248 | const INTROSPECT_PATH: &str = "/introspect"; |
| 249 | |
| 250 | |
| 251 | enum Introspected { |
| 252 | |
| 253 | Active(User, i64), |
| 254 | |
| 255 | |
| 256 | Revoked, |
| 257 | |
| 258 | |
| 259 | |
| 260 | Unanswered, |
| 261 | } |
| 262 | |
| 263 | async fn introspect(state: &InClient, token: &str) -> Introspected { |
| 264 | let Ok(reply) = state |
| 265 | .http |
| 266 | .post(format!("{}{}", state.config.issuer, INTROSPECT_PATH)) |
| 267 | .form(&[ |
| 268 | ("token", token), |
| 269 | ("client_id", &state.config.client_id), |
| 270 | ("client_secret", &state.config.client_secret), |
| 271 | ]) |
| 272 | .send() |
| 273 | .await |
| 274 | else { |
| 275 | return Introspected::Unanswered; |
| 276 | }; |
| 277 | let Ok(answer): Result<serde_json::Value, _> = reply.json().await else { |
| 278 | return Introspected::Unanswered; |
| 279 | }; |
| 280 | |
| 281 | |
| 282 | match answer.get("active") { |
| 283 | Some(serde_json::Value::Bool(true)) => {} |
| 284 | Some(serde_json::Value::Bool(false)) => return Introspected::Revoked, |
| 285 | _ => return Introspected::Unanswered, |
| 286 | } |
| 287 | let (Some(sub), Some(email), Some(name), Some(exp)) = ( |
| 288 | answer["sub"].as_str(), |
| 289 | answer["email"].as_str(), |
| 290 | answer["name"].as_str(), |
| 291 | answer["exp"].as_i64(), |
| 292 | ) else { |
| 293 | return Introspected::Unanswered; |
| 294 | }; |
| 295 | Introspected::Active( |
| 296 | User { |
| 297 | sub: sub.to_string(), |
| 298 | email: email.to_string(), |
| 299 | name: name.to_string(), |
| 300 | |
| 301 | |
| 302 | photo_version: answer["photo_version"].as_u64().unwrap_or(0), |
| 303 | }, |
| 304 | exp, |
| 305 | ) |
| 306 | } |
| 307 | |
| 308 | |
| 309 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 310 | pub struct User { |
| 311 | pub sub: String, |
| 312 | pub email: String, |
| 313 | pub name: String, |
| 314 | |
| 315 | |
| 316 | |
| 317 | pub photo_version: u64, |
| 318 | } |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | #[derive(Serialize, Deserialize)] |
| 325 | struct Session { |
| 326 | |
| 327 | |
| 328 | app_session: String, |
| 329 | exp: i64, |
| 330 | } |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | #[cfg(feature = "test-seam")] |
| 336 | pub fn mint_session_cookie( |
| 337 | config: &Config, |
| 338 | app_session: &str, |
| 339 | exp: time::OffsetDateTime, |
| 340 | ) -> String { |
| 341 | seal_json( |
| 342 | &config.cookie_key, |
| 343 | &Session { |
| 344 | app_session: app_session.to_string(), |
| 345 | exp: exp.unix_timestamp(), |
| 346 | }, |
| 347 | ) |
| 348 | } |
| 349 | |
| 350 | |
| 351 | |
| 352 | #[cfg(feature = "test-seam")] |
| 353 | pub fn introspect_path() -> &'static str { |
| 354 | INTROSPECT_PATH |
| 355 | } |
| 356 | |
| 357 | |
| 358 | #[derive(Serialize, Deserialize)] |
| 359 | struct InFlight { |
| 360 | verifier: String, |
| 361 | state: String, |
| 362 | nonce: String, |
| 363 | next: String, |
| 364 | exp: i64, |
| 365 | } |
| 366 | |
| 367 | const IN_FLIGHT_MINUTES: i64 = 10; |
| 368 | |
| 369 | fn seal(key: &[u8; 32], plaintext: &[u8]) -> String { |
| 370 | let cipher = XChaCha20Poly1305::new(key.into()); |
| 371 | let mut nonce_bytes = [0u8; 24]; |
| 372 | rand::rng().fill_bytes(&mut nonce_bytes); |
| 373 | let ciphertext = cipher |
| 374 | .encrypt(&XNonce::from(nonce_bytes), plaintext) |
| 375 | .expect("XChaCha20-Poly1305 cannot fail on a payload this small"); |
| 376 | let mut payload = nonce_bytes.to_vec(); |
| 377 | payload.extend_from_slice(&ciphertext); |
| 378 | b64url.encode(payload) |
| 379 | } |
| 380 | |
| 381 | fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> { |
| 382 | let payload = b64url.decode(sealed).ok()?; |
| 383 | if payload.len() < 24 { |
| 384 | return None; |
| 385 | } |
| 386 | let (nonce_bytes, ciphertext) = payload.split_at(24); |
| 387 | let cipher = XChaCha20Poly1305::new(key.into()); |
| 388 | let nonce: &XNonce = nonce_bytes.try_into().ok()?; |
| 389 | cipher.decrypt(nonce, ciphertext).ok() |
| 390 | } |
| 391 | |
| 392 | fn seal_json<T: Serialize>(key: &[u8; 32], value: &T) -> String { |
| 393 | seal(key, &serde_json::to_vec(value).expect("plain data")) |
| 394 | } |
| 395 | |
| 396 | fn open_json<T: for<'de> Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option<T> { |
| 397 | serde_json::from_slice(&open(key, sealed)?).ok() |
| 398 | } |
| 399 | |
| 400 | fn app_cookies(cx: &Cx) -> impl Cookies { |
| 401 | cookies(cx) |
| 402 | .default_secure(client(cx).config.issuer.starts_with("https://")) |
| 403 | .default_http_only(true) |
| 404 | .default_same_site(topcoat::cookie::SameSite::Lax) |
| 405 | .default_path("/") |
| 406 | } |
| 407 | |
| 408 | fn set_session_cookie(cx: &Cx, state: &InClient, session: &Session) { |
| 409 | let name = state.config.cookie_name.clone(); |
| 410 | app_cookies(cx).add(cookie! { |
| 411 | name = seal_json(&state.config.cookie_key, session); |
| 412 | Path = "/"; |
| 413 | HttpOnly; |
| 414 | SameSite = Lax; |
| 415 | MaxAge = time::Duration::days(30) |
| 416 | }); |
| 417 | } |
| 418 | |
| 419 | fn clear_cookie(cx: &Cx, name: &str) { |
| 420 | app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build()); |
| 421 | } |
| 422 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | fn see(cx: &Cx, location: &str) -> Result<Response, topcoat::Error> { |
| 428 | ( |
| 429 | StatusCode::SEE_OTHER, |
| 430 | [(header::LOCATION, location_value(location))], |
| 431 | ) |
| 432 | .into_response(cx) |
| 433 | } |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | fn location_value(location: &str) -> HeaderValue { |
| 439 | HeaderValue::from_str(location).unwrap_or_else(|_| HeaderValue::from_static("/")) |
| 440 | } |
| 441 | |
| 442 | |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | fn safe_next(raw: &str) -> &str { |
| 450 | if raw.starts_with('/') |
| 451 | && !raw.starts_with("//") |
| 452 | && !raw.contains('\\') |
| 453 | && !raw.chars().any(|c| c.is_control()) |
| 454 | { |
| 455 | raw |
| 456 | } else { |
| 457 | "/" |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | |
| 462 | const JWKS_TTL_SECONDS: i64 = 3600; |
| 463 | |
| 464 | async fn jwks_stale(state: &InClient) -> bool { |
| 465 | match state.jwks.read().await.as_ref() { |
| 466 | None => true, |
| 467 | Some(cache) => { |
| 468 | cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS) |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | fn query_value(query: &str, key: &str) -> Option<String> { |
| 474 | query.split('&').find_map(|pair| { |
| 475 | let (k, v) = pair.split_once('=')?; |
| 476 | (k == key).then(|| urldecode(v)) |
| 477 | }) |
| 478 | } |
| 479 | |
| 480 | |
| 481 | fn urldecode(raw: &str) -> String { |
| 482 | let bytes = raw.as_bytes(); |
| 483 | let mut out = Vec::with_capacity(bytes.len()); |
| 484 | let mut i = 0; |
| 485 | while i < bytes.len() { |
| 486 | match bytes[i] { |
| 487 | b'+' => { |
| 488 | out.push(b' '); |
| 489 | i += 1; |
| 490 | } |
| 491 | b'%' if i + 2 < bytes.len() => { |
| 492 | let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); |
| 493 | match u8::from_str_radix(hex, 16) { |
| 494 | Ok(byte) => { |
| 495 | out.push(byte); |
| 496 | i += 3; |
| 497 | } |
| 498 | Err(_) => { |
| 499 | out.push(b'%'); |
| 500 | i += 1; |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | byte => { |
| 505 | out.push(byte); |
| 506 | i += 1; |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | String::from_utf8_lossy(&out).into_owned() |
| 511 | } |
| 512 | |
| 513 | fn random_b64(bytes: usize) -> String { |
| 514 | let mut buf = vec![0u8; bytes]; |
| 515 | rand::rng().fill_bytes(&mut buf); |
| 516 | b64url.encode(buf) |
| 517 | } |
| 518 | |
| 519 | |
| 520 | #[route(GET "/auth/login")] |
| 521 | async fn in_login(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 522 | let state = client(cx); |
| 523 | let query = topcoat::router::request::uri(cx) |
| 524 | .query() |
| 525 | .unwrap_or("") |
| 526 | .to_string(); |
| 527 | let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string(); |
| 528 | |
| 529 | let flight = InFlight { |
| 530 | verifier: random_b64(32), |
| 531 | state: random_b64(16), |
| 532 | nonce: random_b64(16), |
| 533 | next, |
| 534 | exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60, |
| 535 | }; |
| 536 | let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes())); |
| 537 | let cookie_name = format!("{}_pkce", state.config.cookie_name); |
| 538 | app_cookies(cx).add(cookie! { |
| 539 | cookie_name = seal_json(&state.config.cookie_key, &flight); |
| 540 | Path = "/"; |
| 541 | HttpOnly; |
| 542 | SameSite = Lax; |
| 543 | MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES) |
| 544 | }); |
| 545 | |
| 546 | let url = format!( |
| 547 | "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256", |
| 548 | state.config.issuer, |
| 549 | state.config.client_id, |
| 550 | urlencoded(&state.config.redirect_uri), |
| 551 | flight.state, |
| 552 | flight.nonce, |
| 553 | challenge, |
| 554 | ); |
| 555 | see(cx, &url) |
| 556 | } |
| 557 | |
| 558 | |
| 559 | |
| 560 | #[route(GET "/auth/callback")] |
| 561 | async fn in_callback(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 562 | let state = client(cx); |
| 563 | let query = topcoat::router::request::uri(cx) |
| 564 | .query() |
| 565 | .unwrap_or("") |
| 566 | .to_string(); |
| 567 | if let Some(error) = query_value(&query, "error") { |
| 568 | return see(cx, &format!("/?auth_error={error}")); |
| 569 | } |
| 570 | let (Some(code), Some(presented_state)) = |
| 571 | (query_value(&query, "code"), query_value(&query, "state")) |
| 572 | else { |
| 573 | return see(cx, "/?auth_error=invalid_request"); |
| 574 | }; |
| 575 | let cookie_name = format!("{}_pkce", state.config.cookie_name); |
| 576 | let flight: Option<InFlight> = cookies(cx) |
| 577 | .get(&cookie_name) |
| 578 | .and_then(|c| open_json(&state.config.cookie_key, c.value())); |
| 579 | let Some(flight) = flight else { |
| 580 | return see(cx, "/?auth_error=invalid_request"); |
| 581 | }; |
| 582 | clear_cookie(cx, &cookie_name); |
| 583 | if flight.exp <= OffsetDateTime::now_utc().unix_timestamp() |
| 584 | || flight |
| 585 | .state |
| 586 | .as_bytes() |
| 587 | .ct_eq(presented_state.as_bytes()) |
| 588 | .unwrap_u8() |
| 589 | != 1 |
| 590 | { |
| 591 | return see(cx, "/?auth_error=invalid_state"); |
| 592 | } |
| 593 | |
| 594 | match exchange_code(state, &code, &flight).await { |
| 595 | Ok(session) => { |
| 596 | set_session_cookie(cx, state, &session); |
| 597 | |
| 598 | |
| 599 | see(cx, safe_next(&flight.next)) |
| 600 | } |
| 601 | Err(_) => see(cx, "/?auth_error=exchange_failed"), |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | |
| 615 | #[route(GET "/auth/logout")] |
| 616 | async fn in_logout(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 617 | let state = client(cx); |
| 618 | clear_cookie(cx, &state.config.cookie_name); |
| 619 | let back = match try_app_context::<LogoutBack>(cx) { |
| 620 | Some(ask) => (ask.0)(cx) |
| 621 | .await |
| 622 | .unwrap_or_else(|| state.config.logout_back.clone()), |
| 623 | None => state.config.logout_back.clone(), |
| 624 | }; |
| 625 | see( |
| 626 | cx, |
| 627 | &format!( |
| 628 | "{}/logout?back={}", |
| 629 | state.config.issuer, |
| 630 | urlencoded(&format!("{}/", back)), |
| 631 | ), |
| 632 | ) |
| 633 | } |
| 634 | |
| 635 | fn urlencoded(raw: &str) -> String { |
| 636 | let mut out = String::with_capacity(raw.len()); |
| 637 | for byte in raw.bytes() { |
| 638 | match byte { |
| 639 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { |
| 640 | out.push(byte as char) |
| 641 | } |
| 642 | _ => out.push_str(&format!("%{byte:02X}")), |
| 643 | } |
| 644 | } |
| 645 | out |
| 646 | } |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | #[derive(Deserialize)] |
| 653 | struct TokenAnswer { |
| 654 | |
| 655 | |
| 656 | id_token: String, |
| 657 | |
| 658 | |
| 659 | app_session: Option<String>, |
| 660 | } |
| 661 | |
| 662 | async fn exchange_code(state: &InClient, code: &str, flight: &InFlight) -> Result<Session> { |
| 663 | let answer: TokenAnswer = state |
| 664 | .http |
| 665 | .post(format!("{}/token", state.config.issuer)) |
| 666 | .form(&[ |
| 667 | ("grant_type", "authorization_code"), |
| 668 | ("code", code), |
| 669 | ("redirect_uri", &state.config.redirect_uri), |
| 670 | ("client_id", &state.config.client_id), |
| 671 | ("client_secret", &state.config.client_secret), |
| 672 | ("code_verifier", &flight.verifier), |
| 673 | ]) |
| 674 | .send() |
| 675 | .await |
| 676 | .map_err(|e| Error::Http(e.to_string()))? |
| 677 | .error_for_status() |
| 678 | .map_err(|e| Error::Refused(e.to_string()))? |
| 679 | .json() |
| 680 | .await |
| 681 | .map_err(|e| Error::Http(e.to_string()))?; |
| 682 | let claims = validate_id_token(state, &answer.id_token).await?; |
| 683 | if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { |
| 684 | return Err(Error::Token("nonce mismatch".into())); |
| 685 | } |
| 686 | let app_session = answer |
| 687 | .app_session |
| 688 | .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; |
| 689 | |
| 690 | |
| 691 | |
| 692 | |
| 693 | let (_user, exp) = match introspect(state, &app_session).await { |
| 694 | Introspected::Active(user, exp) => (user, exp), |
| 695 | Introspected::Revoked | Introspected::Unanswered => { |
| 696 | return Err(Error::Refused( |
| 697 | "fresh app session does not introspect".into(), |
| 698 | )); |
| 699 | } |
| 700 | }; |
| 701 | Ok(Session { app_session, exp }) |
| 702 | } |
| 703 | |
| 704 | |
| 705 | |
| 706 | async fn validate_id_token(state: &InClient, token: &str) -> Result<serde_json::Value> { |
| 707 | let parts: Vec<&str> = token.split('.').collect(); |
| 708 | if parts.len() != 3 { |
| 709 | return Err(Error::Token("not a compact JWT".into())); |
| 710 | } |
| 711 | let header: serde_json::Value = serde_json::from_slice( |
| 712 | &b64url |
| 713 | .decode(parts[0]) |
| 714 | .map_err(|e| Error::Token(e.to_string()))?, |
| 715 | ) |
| 716 | .map_err(|e| Error::Token(e.to_string()))?; |
| 717 | if header["alg"] != "RS256" { |
| 718 | return Err(Error::Token("unexpected alg".into())); |
| 719 | } |
| 720 | let kid = header["kid"] |
| 721 | .as_str() |
| 722 | .ok_or_else(|| Error::Token("no kid".into()))? |
| 723 | .to_string(); |
| 724 | |
| 725 | if jwks_stale(state).await { |
| 726 | refetch_jwks(state).await?; |
| 727 | } |
| 728 | let key = match cached_key(state, &kid).await { |
| 729 | Some(key) => key, |
| 730 | None => { |
| 731 | refetch_jwks(state).await?; |
| 732 | cached_key(state, &kid) |
| 733 | .await |
| 734 | .ok_or_else(|| Error::Token("unknown kid after refetch".into()))? |
| 735 | } |
| 736 | }; |
| 737 | |
| 738 | verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id) |
| 739 | } |
| 740 | |
| 741 | |
| 742 | |
| 743 | |
| 744 | fn verify_claims( |
| 745 | parts: &[&str], |
| 746 | key: &rsa::RsaPublicKey, |
| 747 | issuer: &str, |
| 748 | client_id: &str, |
| 749 | ) -> Result<serde_json::Value> { |
| 750 | use rsa::signature::Verifier; |
| 751 | let signature_bytes = b64url |
| 752 | .decode(parts[2]) |
| 753 | .map_err(|e| Error::Token(e.to_string()))?; |
| 754 | let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) |
| 755 | .map_err(|e| Error::Token(e.to_string()))?; |
| 756 | let verifying = rsa::pkcs1v15::VerifyingKey::<sha2::Sha256>::new(key.clone()); |
| 757 | verifying |
| 758 | .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) |
| 759 | .map_err(|_| Error::Token("bad signature".into()))?; |
| 760 | |
| 761 | let claims: serde_json::Value = serde_json::from_slice( |
| 762 | &b64url |
| 763 | .decode(parts[1]) |
| 764 | .map_err(|e| Error::Token(e.to_string()))?, |
| 765 | ) |
| 766 | .map_err(|e| Error::Token(e.to_string()))?; |
| 767 | if claims["iss"].as_str() != Some(issuer) { |
| 768 | return Err(Error::Token("wrong issuer".into())); |
| 769 | } |
| 770 | if claims["aud"].as_str() != Some(client_id) { |
| 771 | return Err(Error::Token("wrong audience".into())); |
| 772 | } |
| 773 | match claims["exp"].as_i64() { |
| 774 | Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {} |
| 775 | _ => return Err(Error::Token("expired".into())), |
| 776 | } |
| 777 | Ok(claims) |
| 778 | } |
| 779 | |
| 780 | async fn cached_key(state: &InClient, kid: &str) -> Option<rsa::RsaPublicKey> { |
| 781 | state |
| 782 | .jwks |
| 783 | .read() |
| 784 | .await |
| 785 | .as_ref()? |
| 786 | .keys |
| 787 | .iter() |
| 788 | .find(|(k, _)| k == kid) |
| 789 | .map(|(_, key)| key.clone()) |
| 790 | } |
| 791 | |
| 792 | |
| 793 | |
| 794 | async fn refetch_jwks(state: &InClient) -> Result<()> { |
| 795 | let doc: serde_json::Value = state |
| 796 | .http |
| 797 | .get(format!("{}/jwks.json", state.config.issuer)) |
| 798 | .send() |
| 799 | .await |
| 800 | .map_err(|e| Error::Http(e.to_string()))? |
| 801 | .error_for_status() |
| 802 | .map_err(|e| Error::Refused(e.to_string()))? |
| 803 | .json() |
| 804 | .await |
| 805 | .map_err(|e| Error::Http(e.to_string()))?; |
| 806 | let mut keys = Vec::new(); |
| 807 | for jwk in doc["keys"].as_array().into_iter().flatten() { |
| 808 | let (Some(kid), Some(n), Some(e)) = |
| 809 | (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str()) |
| 810 | else { |
| 811 | continue; |
| 812 | }; |
| 813 | let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else { |
| 814 | continue; |
| 815 | }; |
| 816 | let key = rsa::RsaPublicKey::new( |
| 817 | rsa::BoxedUint::from_be_slice_vartime(&n), |
| 818 | rsa::BoxedUint::from_be_slice_vartime(&e), |
| 819 | ) |
| 820 | .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?; |
| 821 | keys.push((kid.to_string(), key)); |
| 822 | } |
| 823 | *state.jwks.write().await = Some(JwksCache { |
| 824 | fetched_at: OffsetDateTime::now_utc(), |
| 825 | keys, |
| 826 | }); |
| 827 | Ok(()) |
| 828 | } |
| 829 | #[cfg(test)] |
| 830 | mod tests { |
| 831 | use super::*; |
| 832 | use rsa::signature::{SignatureEncoding, Signer}; |
| 833 | use rsa::traits::PublicKeyParts; |
| 834 | use std::sync::{Arc, OnceLock}; |
| 835 | use topcoat::cookie::RouterBuilderCookieExt; |
| 836 | use topcoat::router::{Body, Router, to_bytes}; |
| 837 | |
| 838 | fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) { |
| 839 | |
| 840 | |
| 841 | let private = rsa::RsaPrivateKey::new(&mut rand::rng(), 1024).unwrap(); |
| 842 | let public = private.to_public_key(); |
| 843 | (private, public) |
| 844 | } |
| 845 | |
| 846 | fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String { |
| 847 | let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"}); |
| 848 | let mut out = b64url.encode(header.to_string()); |
| 849 | out.push('.'); |
| 850 | out.push_str(&b64url.encode(claims.to_string())); |
| 851 | let signing = rsa::pkcs1v15::SigningKey::<sha2::Sha256>::new(key.clone()); |
| 852 | let signature = signing.sign(out.as_bytes()); |
| 853 | format!("{}.{}", out, b64url.encode(signature.to_bytes())) |
| 854 | } |
| 855 | |
| 856 | fn good_claims() -> serde_json::Value { |
| 857 | serde_json::json!({ |
| 858 | "iss": "http://im.test", |
| 859 | "sub": "user-1", |
| 860 | "aud": "client-1", |
| 861 | "exp": OffsetDateTime::now_utc().unix_timestamp() + 600, |
| 862 | "iat": OffsetDateTime::now_utc().unix_timestamp(), |
| 863 | "email": "ann@example.com", |
| 864 | "name": "Ann", |
| 865 | }) |
| 866 | } |
| 867 | |
| 868 | #[test] |
| 869 | fn valid_token_validates() { |
| 870 | let (private, public) = keypair(); |
| 871 | let token = sign(good_claims(), &private); |
| 872 | let parts: Vec<&str> = token.split('.').collect(); |
| 873 | let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap(); |
| 874 | assert_eq!(claims["sub"], "user-1"); |
| 875 | } |
| 876 | |
| 877 | #[test] |
| 878 | fn tampered_payload_rejected() { |
| 879 | let (private, public) = keypair(); |
| 880 | let token = sign(good_claims(), &private); |
| 881 | let parts: Vec<&str> = token.split('.').collect(); |
| 882 | let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#); |
| 883 | let forged = vec![parts[0], forged_payload.as_str(), parts[2]]; |
| 884 | assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err()); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn wrong_key_rejected() { |
| 889 | let (private, _) = keypair(); |
| 890 | let (_, other_public) = keypair(); |
| 891 | let token = sign(good_claims(), &private); |
| 892 | let parts: Vec<&str> = token.split('.').collect(); |
| 893 | assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err()); |
| 894 | } |
| 895 | |
| 896 | #[test] |
| 897 | fn wrong_audience_rejected() { |
| 898 | let (private, public) = keypair(); |
| 899 | let token = sign(good_claims(), &private); |
| 900 | let parts: Vec<&str> = token.split('.').collect(); |
| 901 | assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err()); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn wrong_issuer_rejected() { |
| 906 | let (private, public) = keypair(); |
| 907 | let token = sign(good_claims(), &private); |
| 908 | let parts: Vec<&str> = token.split('.').collect(); |
| 909 | assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err()); |
| 910 | } |
| 911 | |
| 912 | #[test] |
| 913 | fn expired_rejected() { |
| 914 | let (private, public) = keypair(); |
| 915 | let mut claims = good_claims(); |
| 916 | claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into(); |
| 917 | let token = sign(claims, &private); |
| 918 | let parts: Vec<&str> = token.split('.').collect(); |
| 919 | assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err()); |
| 920 | } |
| 921 | |
| 922 | #[test] |
| 923 | fn pkce_rfc7636_vector() { |
| 924 | |
| 925 | let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; |
| 926 | let challenge = b64url.encode(Sha256::digest(verifier.as_bytes())); |
| 927 | assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); |
| 928 | } |
| 929 | |
| 930 | #[test] |
| 931 | fn cookie_seal_roundtrip() { |
| 932 | let key = [7u8; 32]; |
| 933 | let session = Session { |
| 934 | app_session: "opaque-token".into(), |
| 935 | exp: 1, |
| 936 | }; |
| 937 | let sealed = seal_json(&key, &session); |
| 938 | let back: Session = open_json(&key, &sealed).unwrap(); |
| 939 | assert_eq!(back.app_session, "opaque-token"); |
| 940 | assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none()); |
| 941 | assert!(open_json::<Session>(&key, "garbage").is_none()); |
| 942 | } |
| 943 | |
| 944 | #[cfg(feature = "test-seam")] |
| 945 | #[test] |
| 946 | fn seam_cookie_reads_back() { |
| 947 | let config = Config { |
| 948 | issuer: "http://im.test".into(), |
| 949 | client_id: "client-1".into(), |
| 950 | client_secret: "secret".into(), |
| 951 | redirect_uri: "http://app.test/auth/callback".into(), |
| 952 | cookie_name: "in_session".into(), |
| 953 | cookie_key: [7u8; 32], |
| 954 | logout_back: String::new(), |
| 955 | }; |
| 956 | assert_eq!(introspect_path(), "/introspect"); |
| 957 | let exp = OffsetDateTime::now_utc() + time::Duration::hours(1); |
| 958 | let sealed = mint_session_cookie(&config, "opaque-token", exp); |
| 959 | let back: Session = open_json(&config.cookie_key, &sealed).unwrap(); |
| 960 | assert_eq!(back.app_session, "opaque-token"); |
| 961 | assert_eq!(back.exp, exp.unix_timestamp()); |
| 962 | } |
| 963 | |
| 964 | |
| 965 | |
| 966 | |
| 967 | |
| 968 | |
| 969 | #[test] |
| 970 | fn next_allows_plain_local_paths() { |
| 971 | assert_eq!(safe_next("/"), "/"); |
| 972 | assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a"); |
| 973 | assert_eq!( |
| 974 | safe_next("/?auth_error=exchange_failed"), |
| 975 | "/?auth_error=exchange_failed" |
| 976 | ); |
| 977 | } |
| 978 | |
| 979 | #[test] |
| 980 | fn login_next_with_crlf_injection_is_neutralized() { |
| 981 | |
| 982 | |
| 983 | let decoded = query_value("next=/%0d%0aX-evil:1", "next").unwrap(); |
| 984 | assert_eq!(decoded, "/\r\nX-evil:1"); |
| 985 | assert_eq!(safe_next(&decoded), "/"); |
| 986 | assert_eq!(safe_next("/\r\nX-evil:1"), "/"); |
| 987 | assert_eq!(safe_next("/ok\r/evil"), "/"); |
| 988 | assert_eq!(safe_next("/tab\there"), "/"); |
| 989 | } |
| 990 | |
| 991 | #[test] |
| 992 | fn next_rejects_backslash_paths() { |
| 993 | |
| 994 | |
| 995 | assert_eq!(safe_next("/\\evil"), "/"); |
| 996 | assert_eq!(safe_next("/drive/\\evil"), "/"); |
| 997 | assert_eq!(safe_next("\\evil"), "/"); |
| 998 | assert_eq!(safe_next("//evil.example"), "/"); |
| 999 | assert_eq!(safe_next("https://evil.example/"), "/"); |
| 1000 | assert_eq!(safe_next(""), "/"); |
| 1001 | } |
| 1002 | |
| 1003 | #[test] |
| 1004 | fn location_value_falls_back_to_root() { |
| 1005 | |
| 1006 | |
| 1007 | assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err()); |
| 1008 | assert_eq!( |
| 1009 | location_value("/\r\nX-evil:1"), |
| 1010 | HeaderValue::from_static("/") |
| 1011 | ); |
| 1012 | assert_eq!( |
| 1013 | location_value("/drive"), |
| 1014 | HeaderValue::from_str("/drive").unwrap() |
| 1015 | ); |
| 1016 | } |
| 1017 | |
| 1018 | #[tokio::test] |
| 1019 | async fn logout_clears_the_cookie_and_walks_to_the_issuer() { |
| 1020 | let router = test_router(test_config("http://im.test".into())); |
| 1021 | let res = TestResponse::of( |
| 1022 | router |
| 1023 | .handle(get("/auth/logout", Some(&session_cookie("tok-1")))) |
| 1024 | .await, |
| 1025 | ) |
| 1026 | .await; |
| 1027 | assert_eq!(res.status, http::StatusCode::SEE_OTHER); |
| 1028 | assert_eq!( |
| 1029 | res.location.as_deref(), |
| 1030 | Some("http://im.test/logout?back=http%3A%2F%2Fapp.test%2F"), |
| 1031 | "{}", |
| 1032 | res.text() |
| 1033 | ); |
| 1034 | |
| 1035 | |
| 1036 | assert!(res.clears_session()); |
| 1037 | } |
| 1038 | |
| 1039 | #[route(GET "/whoami")] |
| 1040 | async fn whoami(cx: &Cx) -> Result<Response, topcoat::Error> { |
| 1041 | match current_user(cx).await { |
| 1042 | Some(user) => user.email.into_response(cx), |
| 1043 | None => "anon".into_response(cx), |
| 1044 | } |
| 1045 | } |
| 1046 | |
| 1047 | fn test_config(issuer: String) -> Config { |
| 1048 | Config { |
| 1049 | issuer, |
| 1050 | client_id: "client-1".into(), |
| 1051 | client_secret: "s3cr3t".into(), |
| 1052 | redirect_uri: "http://app.test/auth/callback".into(), |
| 1053 | cookie_name: "in_session".into(), |
| 1054 | cookie_key: [7u8; 32], |
| 1055 | logout_back: "http://app.test".into(), |
| 1056 | } |
| 1057 | } |
| 1058 | |
| 1059 | fn test_router(config: Config) -> Router { |
| 1060 | mount(Router::builder(), config) |
| 1061 | .discover_routes() |
| 1062 | .cookies() |
| 1063 | .build() |
| 1064 | } |
| 1065 | |
| 1066 | fn get(uri: &str, cookie: Option<&str>) -> http::Request<Body> { |
| 1067 | let mut builder = http::Request::builder().method("GET").uri(uri); |
| 1068 | if let Some(cookie) = cookie { |
| 1069 | builder = builder.header(http::header::COOKIE, cookie); |
| 1070 | } |
| 1071 | builder.body(Body::empty()).unwrap() |
| 1072 | } |
| 1073 | |
| 1074 | struct TestResponse { |
| 1075 | status: http::StatusCode, |
| 1076 | location: Option<String>, |
| 1077 | set_cookies: Vec<String>, |
| 1078 | body: Vec<u8>, |
| 1079 | } |
| 1080 | |
| 1081 | impl TestResponse { |
| 1082 | async fn of(response: Response) -> Self { |
| 1083 | let status = response.status(); |
| 1084 | let headers = response.headers().clone(); |
| 1085 | let location = headers |
| 1086 | .get(http::header::LOCATION) |
| 1087 | .and_then(|v| v.to_str().ok()) |
| 1088 | .map(str::to_string); |
| 1089 | let set_cookies = headers |
| 1090 | .get_all(http::header::SET_COOKIE) |
| 1091 | .iter() |
| 1092 | .filter_map(|v| v.to_str().ok().map(str::to_string)) |
| 1093 | .collect(); |
| 1094 | let body = to_bytes(response.into_body(), usize::MAX) |
| 1095 | .await |
| 1096 | .unwrap() |
| 1097 | .to_vec(); |
| 1098 | Self { |
| 1099 | status, |
| 1100 | location, |
| 1101 | set_cookies, |
| 1102 | body, |
| 1103 | } |
| 1104 | } |
| 1105 | |
| 1106 | fn text(&self) -> &str { |
| 1107 | std::str::from_utf8(&self.body).unwrap() |
| 1108 | } |
| 1109 | |
| 1110 | |
| 1111 | |
| 1112 | fn clears_session(&self) -> bool { |
| 1113 | self.set_cookies |
| 1114 | .iter() |
| 1115 | .any(|c| c.starts_with("in_session=")) |
| 1116 | } |
| 1117 | } |
| 1118 | |
| 1119 | fn session_cookie(token: &str) -> String { |
| 1120 | let session = Session { |
| 1121 | app_session: token.into(), |
| 1122 | exp: OffsetDateTime::now_utc().unix_timestamp() + 3600, |
| 1123 | }; |
| 1124 | format!("in_session={}", seal_json(&[7u8; 32], &session)) |
| 1125 | } |
| 1126 | |
| 1127 | |
| 1128 | |
| 1129 | |
| 1130 | #[derive(Clone, Default)] |
| 1131 | struct CannedIm { |
| 1132 | token: Arc<OnceLock<String>>, |
| 1133 | jwks: Arc<OnceLock<String>>, |
| 1134 | introspect: Arc<OnceLock<String>>, |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | register: Arc<OnceLock<(u16, String)>>, |
| 1139 | } |
| 1140 | |
| 1141 | struct FakeIm { |
| 1142 | addr: std::net::SocketAddr, |
| 1143 | } |
| 1144 | |
| 1145 | impl FakeIm { |
| 1146 | async fn spawn(canned: CannedIm) -> Self { |
| 1147 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 1148 | let addr = listener.local_addr().unwrap(); |
| 1149 | tokio::spawn(async move { |
| 1150 | loop { |
| 1151 | let Ok((socket, _)) = listener.accept().await else { |
| 1152 | return; |
| 1153 | }; |
| 1154 | let canned = canned.clone(); |
| 1155 | tokio::spawn(async move { |
| 1156 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 1157 | let mut socket = socket; |
| 1158 | let mut buf = vec![0u8; 8192]; |
| 1159 | let mut req = Vec::new(); |
| 1160 | loop { |
| 1161 | let body_start = loop { |
| 1162 | let Ok(n) = socket.read(&mut buf).await else { |
| 1163 | return; |
| 1164 | }; |
| 1165 | if n == 0 { |
| 1166 | return; |
| 1167 | } |
| 1168 | req.extend_from_slice(&buf[..n]); |
| 1169 | if let Some(end) = headers_end(&req) { |
| 1170 | let head = String::from_utf8_lossy(&req[..end]).to_string(); |
| 1171 | let len = content_length(&head); |
| 1172 | if req.len() >= end + len { |
| 1173 | break end; |
| 1174 | } |
| 1175 | } |
| 1176 | if req.len() > 1_000_000 { |
| 1177 | return; |
| 1178 | } |
| 1179 | }; |
| 1180 | let head = String::from_utf8_lossy(&req[..body_start]).to_string(); |
| 1181 | let first = head.lines().next().unwrap_or("").to_string(); |
| 1182 | let len = content_length(&head); |
| 1183 | req.drain(..body_start + len); |
| 1184 | let (status, payload) = if first.starts_with("POST /token ") { |
| 1185 | (200, canned.token.get().cloned().unwrap_or_default()) |
| 1186 | } else if first.starts_with("GET /jwks.json ") { |
| 1187 | (200, canned.jwks.get().cloned().unwrap_or_default()) |
| 1188 | } else if first.starts_with("POST /family/register ") { |
| 1189 | canned |
| 1190 | .register |
| 1191 | .get() |
| 1192 | .cloned() |
| 1193 | .unwrap_or((200, String::new())) |
| 1194 | } else { |
| 1195 | (200, canned.introspect.get().cloned().unwrap_or_default()) |
| 1196 | }; |
| 1197 | let response = format!( |
| 1198 | "HTTP/1.1 {status} x\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n", |
| 1199 | payload.len() |
| 1200 | ); |
| 1201 | if socket.write_all(response.as_bytes()).await.is_err() { |
| 1202 | return; |
| 1203 | } |
| 1204 | if socket.write_all(payload.as_bytes()).await.is_err() { |
| 1205 | return; |
| 1206 | } |
| 1207 | } |
| 1208 | }); |
| 1209 | } |
| 1210 | }); |
| 1211 | Self { addr } |
| 1212 | } |
| 1213 | |
| 1214 | fn url(&self) -> String { |
| 1215 | format!("http://{}", self.addr) |
| 1216 | } |
| 1217 | } |
| 1218 | |
| 1219 | fn headers_end(req: &[u8]) -> Option<usize> { |
| 1220 | req.windows(4) |
| 1221 | .position(|w| w == b"\r\n\r\n") |
| 1222 | .map(|pos| pos + 4) |
| 1223 | } |
| 1224 | |
| 1225 | fn content_length(head: &str) -> usize { |
| 1226 | head.lines() |
| 1227 | .find_map(|line| { |
| 1228 | let (name, value) = line.split_once(':')?; |
| 1229 | name.trim() |
| 1230 | .eq_ignore_ascii_case("content-length") |
| 1231 | .then(|| value.trim().parse().unwrap_or(0)) |
| 1232 | }) |
| 1233 | .unwrap_or(0) |
| 1234 | } |
| 1235 | |
| 1236 | fn jwk_of(public: &rsa::RsaPublicKey, kid: &str) -> serde_json::Value { |
| 1237 | serde_json::json!({ |
| 1238 | "kty": "RSA", |
| 1239 | "kid": kid, |
| 1240 | "n": b64url.encode(public.n().to_be_bytes()), |
| 1241 | "e": b64url.encode(public.e().to_be_bytes()), |
| 1242 | }) |
| 1243 | } |
| 1244 | |
| 1245 | |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | #[tokio::test] |
| 1250 | async fn login_then_callback_with_injected_next_lands_on_root() { |
| 1251 | let (private, public) = keypair(); |
| 1252 | |
| 1253 | |
| 1254 | let login_router = test_router(test_config("http://im.test".into())); |
| 1255 | let login = TestResponse::of( |
| 1256 | login_router |
| 1257 | .handle(get("/auth/login?next=/%0d%0aX-evil:1", None)) |
| 1258 | .await, |
| 1259 | ) |
| 1260 | .await; |
| 1261 | assert_eq!(login.status, http::StatusCode::SEE_OTHER); |
| 1262 | let sealed = login |
| 1263 | .set_cookies |
| 1264 | .iter() |
| 1265 | .find(|c| c.starts_with("in_session_pkce=")) |
| 1266 | .expect("login sets the flight cookie"); |
| 1267 | let sealed = sealed["in_session_pkce=".len()..] |
| 1268 | .split(';') |
| 1269 | .next() |
| 1270 | .unwrap(); |
| 1271 | let flight: InFlight = open_json(&[7u8; 32], sealed).unwrap(); |
| 1272 | |
| 1273 | assert_eq!(flight.next, "/"); |
| 1274 | |
| 1275 | |
| 1276 | let canned = CannedIm::default(); |
| 1277 | let fake = FakeIm::spawn(canned.clone()).await; |
| 1278 | let now = OffsetDateTime::now_utc().unix_timestamp(); |
| 1279 | let id_token = sign( |
| 1280 | serde_json::json!({ |
| 1281 | "iss": fake.url(), |
| 1282 | "sub": "user-1", |
| 1283 | "aud": "client-1", |
| 1284 | "exp": now + 600, |
| 1285 | "iat": now, |
| 1286 | "nonce": flight.nonce, |
| 1287 | }), |
| 1288 | &private, |
| 1289 | ); |
| 1290 | let _ = canned |
| 1291 | .jwks |
| 1292 | .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string()); |
| 1293 | let _ = canned.token.set( |
| 1294 | serde_json::json!({ |
| 1295 | "id_token": id_token, |
| 1296 | "app_session": "tok-1", |
| 1297 | }) |
| 1298 | .to_string(), |
| 1299 | ); |
| 1300 | let _ = canned.introspect.set( |
| 1301 | serde_json::json!({ |
| 1302 | "active": true, |
| 1303 | "sub": "user-1", |
| 1304 | "email": "ann@example.com", |
| 1305 | "name": "Ann", |
| 1306 | "exp": now + 3600, |
| 1307 | }) |
| 1308 | .to_string(), |
| 1309 | ); |
| 1310 | |
| 1311 | let router = test_router(test_config(fake.url())); |
| 1312 | let callback = TestResponse::of( |
| 1313 | router |
| 1314 | .handle(get( |
| 1315 | &format!("/auth/callback?code=code-1&state={}", flight.state), |
| 1316 | Some(&format!("in_session_pkce={sealed}")), |
| 1317 | )) |
| 1318 | .await, |
| 1319 | ) |
| 1320 | .await; |
| 1321 | assert_eq!(callback.status, http::StatusCode::SEE_OTHER); |
| 1322 | assert_eq!(callback.location.as_deref(), Some("/")); |
| 1323 | } |
| 1324 | |
| 1325 | |
| 1326 | |
| 1327 | |
| 1328 | #[tokio::test] |
| 1329 | async fn callback_with_hostile_stored_next_lands_on_root() { |
| 1330 | let (private, public) = keypair(); |
| 1331 | let canned = CannedIm::default(); |
| 1332 | let fake = FakeIm::spawn(canned.clone()).await; |
| 1333 | let now = OffsetDateTime::now_utc().unix_timestamp(); |
| 1334 | let flight = InFlight { |
| 1335 | verifier: "verifier".into(), |
| 1336 | state: "state-1".into(), |
| 1337 | nonce: "nonce-1".into(), |
| 1338 | next: "/\r\nX-evil:1".into(), |
| 1339 | exp: now + 600, |
| 1340 | }; |
| 1341 | let sealed = seal_json(&[7u8; 32], &flight); |
| 1342 | let id_token = sign( |
| 1343 | serde_json::json!({ |
| 1344 | "iss": fake.url(), |
| 1345 | "sub": "user-1", |
| 1346 | "aud": "client-1", |
| 1347 | "exp": now + 600, |
| 1348 | "iat": now, |
| 1349 | "nonce": "nonce-1", |
| 1350 | }), |
| 1351 | &private, |
| 1352 | ); |
| 1353 | let _ = canned |
| 1354 | .jwks |
| 1355 | .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string()); |
| 1356 | let _ = canned.token.set( |
| 1357 | serde_json::json!({ |
| 1358 | "id_token": id_token, |
| 1359 | "app_session": "tok-1", |
| 1360 | }) |
| 1361 | .to_string(), |
| 1362 | ); |
| 1363 | let _ = canned.introspect.set( |
| 1364 | serde_json::json!({ |
| 1365 | "active": true, |
| 1366 | "sub": "user-1", |
| 1367 | "email": "ann@example.com", |
| 1368 | "name": "Ann", |
| 1369 | "exp": now + 3600, |
| 1370 | }) |
| 1371 | .to_string(), |
| 1372 | ); |
| 1373 | |
| 1374 | let router = test_router(test_config(fake.url())); |
| 1375 | let callback = TestResponse::of( |
| 1376 | router |
| 1377 | .handle(get( |
| 1378 | "/auth/callback?code=code-1&state=state-1", |
| 1379 | Some(&format!("in_session_pkce={sealed}")), |
| 1380 | )) |
| 1381 | .await, |
| 1382 | ) |
| 1383 | .await; |
| 1384 | assert_eq!(callback.status, http::StatusCode::SEE_OTHER); |
| 1385 | assert_eq!(callback.location.as_deref(), Some("/")); |
| 1386 | } |
| 1387 | |
| 1388 | #[tokio::test] |
| 1389 | async fn current_user_keeps_cookie_when_im_is_blackholed() { |
| 1390 | |
| 1391 | |
| 1392 | let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 1393 | let port = probe.local_addr().unwrap().port(); |
| 1394 | drop(probe); |
| 1395 | let router = test_router(test_config(format!("http://127.0.0.1:{port}"))); |
| 1396 | let res = TestResponse::of( |
| 1397 | router |
| 1398 | .handle(get("/whoami", Some(&session_cookie("tok-1")))) |
| 1399 | .await, |
| 1400 | ) |
| 1401 | .await; |
| 1402 | assert_eq!(res.text(), "anon"); |
| 1403 | assert!( |
| 1404 | !res.clears_session(), |
| 1405 | "a blackholed introspection must not clear the cookie: {:?}", |
| 1406 | res.set_cookies |
| 1407 | ); |
| 1408 | } |
| 1409 | |
| 1410 | #[tokio::test] |
| 1411 | async fn current_user_keeps_cookie_on_unparseable_introspection() { |
| 1412 | let canned = CannedIm::default(); |
| 1413 | let _ = canned.introspect.set("not-json{{{".into()); |
| 1414 | let fake = FakeIm::spawn(canned).await; |
| 1415 | let router = test_router(test_config(fake.url())); |
| 1416 | let res = TestResponse::of( |
| 1417 | router |
| 1418 | .handle(get("/whoami", Some(&session_cookie("tok-1")))) |
| 1419 | .await, |
| 1420 | ) |
| 1421 | .await; |
| 1422 | assert_eq!(res.text(), "anon"); |
| 1423 | assert!( |
| 1424 | !res.clears_session(), |
| 1425 | "an unparseable introspection must not clear the cookie: {:?}", |
| 1426 | res.set_cookies |
| 1427 | ); |
| 1428 | } |
| 1429 | |
| 1430 | #[tokio::test] |
| 1431 | async fn current_user_keeps_cookie_when_active_is_missing() { |
| 1432 | |
| 1433 | let canned = CannedIm::default(); |
| 1434 | let _ = canned |
| 1435 | .introspect |
| 1436 | .set(serde_json::json!({"sub": "user-1"}).to_string()); |
| 1437 | let fake = FakeIm::spawn(canned).await; |
| 1438 | let router = test_router(test_config(fake.url())); |
| 1439 | let res = TestResponse::of( |
| 1440 | router |
| 1441 | .handle(get("/whoami", Some(&session_cookie("tok-1")))) |
| 1442 | .await, |
| 1443 | ) |
| 1444 | .await; |
| 1445 | assert_eq!(res.text(), "anon"); |
| 1446 | assert!( |
| 1447 | !res.clears_session(), |
| 1448 | "an answer without `active` must not clear the cookie: {:?}", |
| 1449 | res.set_cookies |
| 1450 | ); |
| 1451 | } |
| 1452 | |
| 1453 | #[tokio::test] |
| 1454 | async fn current_user_clears_cookie_when_session_revoked() { |
| 1455 | let canned = CannedIm::default(); |
| 1456 | let _ = canned |
| 1457 | .introspect |
| 1458 | .set(serde_json::json!({"active": false}).to_string()); |
| 1459 | let fake = FakeIm::spawn(canned).await; |
| 1460 | let router = test_router(test_config(fake.url())); |
| 1461 | let res = TestResponse::of( |
| 1462 | router |
| 1463 | .handle(get("/whoami", Some(&session_cookie("tok-1")))) |
| 1464 | .await, |
| 1465 | ) |
| 1466 | .await; |
| 1467 | assert_eq!(res.text(), "anon"); |
| 1468 | assert!( |
| 1469 | res.clears_session(), |
| 1470 | "an `active:false` answer must clear the cookie: {:?}", |
| 1471 | res.set_cookies |
| 1472 | ); |
| 1473 | } |
| 1474 | |
| 1475 | #[tokio::test] |
| 1476 | async fn current_user_serves_the_introspected_user() { |
| 1477 | let now = OffsetDateTime::now_utc().unix_timestamp(); |
| 1478 | let canned = CannedIm::default(); |
| 1479 | let _ = canned.introspect.set( |
| 1480 | serde_json::json!({ |
| 1481 | "active": true, |
| 1482 | "sub": "user-1", |
| 1483 | "email": "ann@example.com", |
| 1484 | "name": "Ann", |
| 1485 | "exp": now + 3600, |
| 1486 | }) |
| 1487 | .to_string(), |
| 1488 | ); |
| 1489 | let fake = FakeIm::spawn(canned).await; |
| 1490 | let router = test_router(test_config(fake.url())); |
| 1491 | let res = TestResponse::of( |
| 1492 | router |
| 1493 | .handle(get("/whoami", Some(&session_cookie("tok-1")))) |
| 1494 | .await, |
| 1495 | ) |
| 1496 | .await; |
| 1497 | assert_eq!(res.text(), "ann@example.com"); |
| 1498 | assert!( |
| 1499 | !res.clears_session(), |
| 1500 | "a live session must not clear the cookie: {:?}", |
| 1501 | res.set_cookies |
| 1502 | ); |
| 1503 | } |
| 1504 | |
| 1505 | #[tokio::test] |
| 1506 | async fn register_family_files_the_entry() { |
| 1507 | let canned = CannedIm::default(); |
| 1508 | let _ = canned.register.set(( |
| 1509 | 200, |
| 1510 | serde_json::json!({"key": "in", "name": "Files", "url": "http://app.test"}).to_string(), |
| 1511 | )); |
| 1512 | let fake = FakeIm::spawn(canned).await; |
| 1513 | let client = InClient::new(test_config(fake.url())); |
| 1514 | assert_eq!( |
| 1515 | client |
| 1516 | .register_family("in", "Files", "http://app.test") |
| 1517 | .await, |
| 1518 | Ok(()) |
| 1519 | ); |
| 1520 | } |
| 1521 | |
| 1522 | #[tokio::test] |
| 1523 | async fn register_family_names_a_key_another_app_owns() { |
| 1524 | let canned = CannedIm::default(); |
| 1525 | let _ = canned |
| 1526 | .register |
| 1527 | .set((409, serde_json::json!({"error": "owned"}).to_string())); |
| 1528 | let fake = FakeIm::spawn(canned).await; |
| 1529 | let client = InClient::new(test_config(fake.url())); |
| 1530 | let problem = client |
| 1531 | .register_family("in", "Files", "http://app.test") |
| 1532 | .await |
| 1533 | .unwrap_err(); |
| 1534 | assert!(problem.contains("owned"), "{problem}"); |
| 1535 | assert!(problem.contains("409"), "{problem}"); |
| 1536 | } |
| 1537 | |
| 1538 | |
| 1539 | |
| 1540 | #[tokio::test] |
| 1541 | async fn register_family_survives_an_im_without_the_route() { |
| 1542 | let canned = CannedIm::default(); |
| 1543 | let _ = canned.register.set((404, String::new())); |
| 1544 | let fake = FakeIm::spawn(canned).await; |
| 1545 | let client = InClient::new(test_config(fake.url())); |
| 1546 | let problem = client |
| 1547 | .register_family("in", "Files", "http://app.test") |
| 1548 | .await |
| 1549 | .unwrap_err(); |
| 1550 | assert!(problem.contains("404"), "{problem}"); |
| 1551 | } |
| 1552 | } |