forge
Explore
Log in

Don't you dare go Hollow

iz_old

Clone
★ 0

0 watching0 forksRustGPL-3.02.2 MiB4c154b4Tahinli2 months ago301 commits

lib.rs1542 lines, 56.2 KiBHistoryRawDownload
1//! iz-client: drop-in OIDC client for topcoat apps authenticating against im.
2//!
3//! Vendored from im-client via in-client.
4//!
5//! An app adds three things: `iz_client::mount(builder, config)` when it
6//! builds its router, `.discover()` as usual (the `/auth/login`,
7//! `/auth/callback`, `/auth/logout` routes register themselves), and
8//! `iz_client::current_user(cx)` wherever it needs the person.
9//!
10//! The model: im holds the central session; this crate holds the app's side
11//! of it — an encrypted cookie with the identity claims and the refresh
12//! token. When the access token ages out, `current_user` silently rotates it
13//! against im; when im has revoked the central session, the rotation is
14//! refused and the app sees a signed-out user.
15
16use std::pin::Pin;
17use std::sync::Arc;
18
19use base64::Engine;
20use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url;
21use chacha20poly1305::aead::Aead;
22use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
23use rand::Rng;
24use serde::{Deserialize, Serialize};
25use sha2::{Digest, Sha256};
26use subtle::ConstantTimeEq;
27use time::OffsetDateTime;
28use topcoat::context::{Cx, try_app_context};
29use topcoat::cookie::{Cookie, Cookies, cookie, cookies};
30use topcoat::router::response::{IntoResponse, Response};
31use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route};
32
33// ---------------------------------------------------------------------------
34// Configuration and state
35// ---------------------------------------------------------------------------
36
37/// Everything the app knows about its im registration. `client_secret` and
38/// `cookie_key` are secrets: the first authenticates the app to im, the
39/// second seals the browser cookies this crate writes.
40#[derive(Clone)]
41pub struct Config {
42 /// im's base URL, e.g. `http://127.0.0.1:7650` or `https://auth.example.com`.
43 pub issuer: String,
44 pub client_id: String,
45 pub client_secret: String,
46 /// Must exactly match one of the URIs registered with im.
47 pub redirect_uri: String,
48 /// Fallback for where im sends the browser when a sign-out that
49 /// started here finishes: this app's public address. Offered to im's
50 /// `/logout` as its `back`, so the browser comes home. An app whose
51 /// public address is a stored setting — a live fact, not a boot-time
52 /// one — registers a [`LogoutBack`] resolver, and this is what answers
53 /// when that resolver is absent or has no opinion.
54 pub logout_back: String,
55 /// The app's session cookie name, e.g. `iz_session`.
56 pub cookie_name: String,
57 /// 32 bytes, generated once per app and kept out of the repository.
58 pub cookie_key: [u8; 32],
59}
60
61/// The answer a [`LogoutBack`] resolver returns for one request: where the
62/// browser comes home to, or `None` to say the app has no opinion this
63/// time and [`Config::logout_back`] should answer.
64pub type BackAnswer<'a> = Pin<Box<dyn Future<Output = Option<String>> + Send + 'a>>;
65
66/// A per-request resolver for where im sends the browser when a sign-out
67/// that started here finishes. An app whose public address is a stored
68/// setting registers one as an app context; `/auth/logout` asks it first
69/// and falls back to [`Config::logout_back`] when it is absent or answers
70/// `None`.
71pub struct LogoutBack(pub Arc<dyn for<'a> Fn(&'a Cx) -> BackAnswer<'a> + Send + Sync>);
72
73/// The registered state: the config, one HTTP client, and the JWKS cache.
74pub struct IzClient {
75 config: Config,
76 http: reqwest::Client,
77 jwks: tokio::sync::RwLock<Option<JwksCache>>,
78}
79
80struct JwksCache {
81 fetched_at: OffsetDateTime,
82 /// kid -> public key
83 keys: Vec<(String, rsa::RsaPublicKey)>,
84}
85
86#[derive(Debug, thiserror::Error)]
87pub enum Error {
88 #[error("http: {0}")]
89 Http(String),
90 #[error("im refused: {0}")]
91 Refused(String),
92 #[error("bad token: {0}")]
93 Token(String),
94}
95
96pub type Result<T, E = Error> = std::result::Result<T, E>;
97
98impl IzClient {
99 pub fn new(config: Config) -> Self {
100 IzClient {
101 config,
102 // Every issuer call — introspection on the render path, the
103 // family and directory mirrors on their beat — carries a
104 // ceiling: a provider that stalls (mid-deploy, half-open
105 // socket) otherwise parks the caller forever, and a parked
106 // mirror task never asks again. This exact freeze cost iz its
107 // switcher once, the beat landing inside im's deploy restart.
108 http: reqwest::Client::builder()
109 .timeout(std::time::Duration::from_secs(10))
110 .build()
111 .expect("reqwest client with a timeout"),
112 jwks: tokio::sync::RwLock::new(None),
113 }
114 }
115}
116
117/// Registers the client state on the router. The routes themselves register
118/// through `discover()` — call it as usual.
119pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder {
120 builder.app_context(IzClient::new(config))
121}
122
123fn client(cx: &Cx) -> &IzClient {
124 try_app_context::<IzClient>(cx).expect("iz_client::mount was called on the router")
125}
126
127/// The authenticated person, if this browser has one. Every call asks im:
128/// the cookie holds an opaque session token, introspected per request, so an
129/// admin revoking the person signs them out of this app immediately — there
130/// is no token-validity window in which a ghost lives.
131pub async fn current_user(cx: &Cx) -> Option<User> {
132 let state = client(cx);
133 let sealed = cookies(cx).get(&state.config.cookie_name)?;
134 let session: Session = open_json(&state.config.cookie_key, sealed.value())?;
135 if session.exp <= OffsetDateTime::now_utc().unix_timestamp() {
136 clear_cookie(cx, &state.config.cookie_name);
137 return None;
138 }
139 match introspect(state, &session.app_session).await {
140 Introspected::Active(user, _exp) => Some(user),
141 Introspected::Revoked => {
142 clear_cookie(cx, &state.config.cookie_name);
143 None
144 }
145 // The question went unanswered — a blackholed route, a dropped
146 // connection, a body that is not the JSON im speaks. Nothing was
147 // learned about the session, so this request reads as signed-out
148 // while the cookie stays for the next request to try again.
149 Introspected::Unanswered => None,
150 }
151}
152
153/// One entry of im's family list: the wordmark key, the human name, and
154/// where the app lives — exactly what the topbar switcher renders.
155/// `Serialize` because the app that fetched it mirrors it into its own
156/// store as the same JSON array im served.
157#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
158pub struct FamilyService {
159 pub key: String,
160 pub name: String,
161 pub url: String,
162}
163
164impl IzClient {
165 /// The family list: every app im's admin panel serves, fetched as the
166 /// app (`Authorization: Basic` with the client pair, the same
167 /// credentials the directory takes). `None` on anything that is not a
168 /// readable list — a refused pair, a dropped connection, a body that
169 /// is not the array — because a missed beat must never look like an
170 /// empty family: the caller keeps the list it has and asks again next
171 /// beat.
172 pub async fn family(&self) -> Option<Vec<FamilyService>> {
173 let reply = self
174 .http
175 .get(format!("{}/family", self.config.issuer))
176 .basic_auth(&self.config.client_id, Some(&self.config.client_secret))
177 .send()
178 .await
179 .ok()?;
180 if !reply.status().is_success() {
181 return None;
182 }
183 reply.json().await.ok()
184 }
185
186 /// Files this app in im's family list, so the switcher learns where it
187 /// lives without an admin typing the address: the app's key, name and
188 /// public origin posted as the app (`Authorization: Basic` with the
189 /// client pair, the same credentials the family fetch takes). `Ok` on
190 /// any 2xx; anything else is an `Err` naming the status and whatever
191 /// `error`/`reason` im gave with it — a refused pair, a key another app
192 /// owns, or the 404 an im too old to register answers. All of those are
193 /// a line in the log and never a reason to stop mirroring: the caller
194 /// goes on to the fetch either way.
195 pub async fn register_family(
196 &self,
197 key: &str,
198 name: &str,
199 url: &str,
200 ) -> std::result::Result<(), String> {
201 let reply = self
202 .http
203 .post(format!("{}/family/register", self.config.issuer))
204 .basic_auth(&self.config.client_id, Some(&self.config.client_secret))
205 .json(&serde_json::json!({ "key": key, "name": name, "url": url }))
206 .send()
207 .await
208 .map_err(|problem| problem.to_string())?;
209 let status = reply.status();
210 if status.is_success() {
211 return Ok(());
212 }
213 // The body is im's own account of the refusal — `owned`, `invalid`
214 // with a reason. A body that is not JSON, or one that names neither,
215 // leaves the status to speak alone.
216 let body = reply.text().await.unwrap_or_default();
217 let said = serde_json::from_str::<serde_json::Value>(&body).unwrap_or_default();
218 let error = said.get("error").and_then(|v| v.as_str()).unwrap_or("");
219 let reason = said.get("reason").and_then(|v| v.as_str()).unwrap_or("");
220 let detail = match (error, reason) {
221 ("", "") => String::new(),
222 (error, "") => format!(": {error}"),
223 ("", reason) => format!(": {reason}"),
224 (error, reason) => format!(": {error} ({reason})"),
225 };
226 Err(format!("im answered {status}{detail}"))
227 }
228}
229
230/// Path of im's RFC 7662 introspection endpoint, relative to the issuer.
231const INTROSPECT_PATH: &str = "/introspect";
232
233/// What one introspection round-trip settled.
234enum Introspected {
235 /// im answered `"active": true` with usable claims.
236 Active(User, i64),
237 /// im answered `"active": false`: the central session is gone and the
238 /// app cookie goes with it.
239 Revoked,
240 /// The question itself went unanswered — the transport failed, the body
241 /// was not JSON, or the claims were missing their fields. Nothing about
242 /// the session was learned, so the cookie must stay.
243 Unanswered,
244}
245
246async fn introspect(state: &IzClient, token: &str) -> Introspected {
247 let Ok(reply) = state
248 .http
249 .post(format!("{}{}", state.config.issuer, INTROSPECT_PATH))
250 .form(&[
251 ("token", token),
252 ("client_id", &state.config.client_id),
253 ("client_secret", &state.config.client_secret),
254 ])
255 .send()
256 .await
257 else {
258 return Introspected::Unanswered;
259 };
260 let Ok(answer): Result<serde_json::Value, _> = reply.json().await else {
261 return Introspected::Unanswered;
262 };
263 // Only an explicit `"active": false` revokes. A missing or non-boolean
264 // `active` is a malformed answer, not a revocation.
265 match answer.get("active") {
266 Some(serde_json::Value::Bool(true)) => {}
267 Some(serde_json::Value::Bool(false)) => return Introspected::Revoked,
268 _ => return Introspected::Unanswered,
269 }
270 let (Some(sub), Some(email), Some(name), Some(exp)) = (
271 answer["sub"].as_str(),
272 answer["email"].as_str(),
273 answer["name"].as_str(),
274 answer["exp"].as_i64(),
275 ) else {
276 return Introspected::Unanswered;
277 };
278 Introspected::Active(
279 User {
280 sub: sub.to_string(),
281 email: email.to_string(),
282 name: name.to_string(),
283 admin: answer["admin"].as_bool().unwrap_or(false),
284 },
285 exp,
286 )
287}
288
289/// Who this browser is, from the claims.
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct User {
292 pub sub: String,
293 pub email: String,
294 pub name: String,
295 #[serde(default)]
296 pub admin: bool,
297}
298
299// ---------------------------------------------------------------------------
300// The app session cookie
301// ---------------------------------------------------------------------------
302
303#[derive(Serialize, Deserialize)]
304struct Session {
305 /// The opaque token im issued at the code exchange; introspected per
306 /// request, never trusted on its own.
307 app_session: String,
308 exp: i64,
309}
310
311/// Test seam for integration tests: seals a session cookie exactly like the
312/// `/auth/callback` handler does, without a live im. Returns the cookie
313/// VALUE only; tests set the `Cookie` header themselves.
314#[cfg(feature = "test-seam")]
315pub fn mint_session_cookie(
316 config: &Config,
317 app_session: &str,
318 exp: time::OffsetDateTime,
319) -> String {
320 seal_json(
321 &config.cookie_key,
322 &Session {
323 app_session: app_session.to_string(),
324 exp: exp.unix_timestamp(),
325 },
326 )
327}
328
329/// The introspection path `current_user` POSTs to, so a fake-im test server
330/// can mount the right route.
331#[cfg(feature = "test-seam")]
332pub fn introspect_path() -> &'static str {
333 INTROSPECT_PATH
334}
335
336/// The in-flight login: PKCE verifier, state, nonce, and where to land after.
337#[derive(Serialize, Deserialize)]
338struct InFlight {
339 verifier: String,
340 state: String,
341 nonce: String,
342 next: String,
343 exp: i64,
344}
345
346const IN_FLIGHT_MINUTES: i64 = 10;
347
348fn seal(key: &[u8; 32], plaintext: &[u8]) -> String {
349 let cipher = XChaCha20Poly1305::new(key.into());
350 let mut nonce_bytes = [0u8; 24];
351 rand::rng().fill_bytes(&mut nonce_bytes);
352 let ciphertext = cipher
353 .encrypt(&XNonce::from(nonce_bytes), plaintext)
354 .expect("XChaCha20-Poly1305 cannot fail on a payload this small");
355 let mut payload = nonce_bytes.to_vec();
356 payload.extend_from_slice(&ciphertext);
357 b64url.encode(payload)
358}
359
360fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> {
361 let payload = b64url.decode(sealed).ok()?;
362 if payload.len() < 24 {
363 return None;
364 }
365 let (nonce_bytes, ciphertext) = payload.split_at(24);
366 let cipher = XChaCha20Poly1305::new(key.into());
367 let nonce: &XNonce = nonce_bytes.try_into().ok()?;
368 cipher.decrypt(nonce, ciphertext).ok()
369}
370
371fn seal_json<T: Serialize>(key: &[u8; 32], value: &T) -> String {
372 seal(key, &serde_json::to_vec(value).expect("plain data"))
373}
374
375fn open_json<T: for<'de> Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option<T> {
376 serde_json::from_slice(&open(key, sealed)?).ok()
377}
378
379fn app_cookies(cx: &Cx) -> impl Cookies {
380 cookies(cx)
381 .default_secure(client(cx).config.issuer.starts_with("https://"))
382 .default_http_only(true)
383 .default_same_site(topcoat::cookie::SameSite::Lax)
384 .default_path("/")
385}
386
387fn set_session_cookie(cx: &Cx, state: &IzClient, session: &Session) {
388 let name = state.config.cookie_name.clone();
389 app_cookies(cx).add(cookie! {
390 name = seal_json(&state.config.cookie_key, session);
391 Path = "/";
392 HttpOnly;
393 SameSite = Lax;
394 MaxAge = time::Duration::days(30)
395 });
396}
397
398fn clear_cookie(cx: &Cx, name: &str) {
399 app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build());
400}
401
402// ---------------------------------------------------------------------------
403// Routes
404// ---------------------------------------------------------------------------
405
406fn see(cx: &Cx, location: &str) -> Result<Response, topcoat::Error> {
407 (
408 StatusCode::SEE_OTHER,
409 [(header::LOCATION, location_value(location))],
410 )
411 .into_response(cx)
412}
413
414/// A `Location` value that cannot panic its handler: anything `HeaderValue`
415/// still refuses (a hostile `next` sealed before the strict validation, a
416/// query echo) lands on `/` instead of killing the request.
417fn location_value(location: &str) -> HeaderValue {
418 HeaderValue::from_str(location).unwrap_or_else(|_| HeaderValue::from_static("/"))
419}
420
421/// A `next` worth honoring: a local absolute path, never `//elsewhere`,
422/// never carrying control bytes, never touching a backslash. The query
423/// arrives percent-decoded, so `%0D%0A` is a real CR LF by the time it is
424/// checked — and a sealed `next` is rendered into a `Location` header, so
425/// anything `HeaderValue` would choke on must die here. Backslashes die
426/// here too: browsers normalize `\` to `/` in `Location`, turning
427/// `/\evil` into a cross-origin hop.
428fn safe_next(raw: &str) -> &str {
429 if raw.starts_with('/')
430 && !raw.starts_with("//")
431 && !raw.contains('\\')
432 && !raw.chars().any(|c| c.is_control())
433 {
434 raw
435 } else {
436 "/"
437 }
438}
439
440/// A JWKS older than this is refreshed before the next validation.
441const JWKS_TTL_SECONDS: i64 = 3600;
442
443async fn jwks_stale(state: &IzClient) -> bool {
444 match state.jwks.read().await.as_ref() {
445 None => true,
446 Some(cache) => {
447 cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS)
448 }
449 }
450}
451
452fn query_value(query: &str, key: &str) -> Option<String> {
453 query.split('&').find_map(|pair| {
454 let (k, v) = pair.split_once('=')?;
455 (k == key).then(|| urldecode(v))
456 })
457}
458
459/// Percent-decodes a query value (`+` is a space, form-style).
460fn urldecode(raw: &str) -> String {
461 let bytes = raw.as_bytes();
462 let mut out = Vec::with_capacity(bytes.len());
463 let mut i = 0;
464 while i < bytes.len() {
465 match bytes[i] {
466 b'+' => {
467 out.push(b' ');
468 i += 1;
469 }
470 b'%' if i + 2 < bytes.len() => {
471 let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
472 match u8::from_str_radix(hex, 16) {
473 Ok(byte) => {
474 out.push(byte);
475 i += 3;
476 }
477 Err(_) => {
478 out.push(b'%');
479 i += 1;
480 }
481 }
482 }
483 byte => {
484 out.push(byte);
485 i += 1;
486 }
487 }
488 }
489 String::from_utf8_lossy(&out).into_owned()
490}
491
492fn random_b64(bytes: usize) -> String {
493 let mut buf = vec![0u8; bytes];
494 rand::rng().fill_bytes(&mut buf);
495 b64url.encode(buf)
496}
497
498/// Sends the browser to im's `/authorize` with a fresh PKCE pair.
499#[route(GET "/auth/login")]
500async fn iz_login(cx: &Cx) -> Result<Response, topcoat::Error> {
501 let state = client(cx);
502 let query = topcoat::router::request::uri(cx)
503 .query()
504 .unwrap_or("")
505 .to_string();
506 let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string();
507
508 let flight = InFlight {
509 verifier: random_b64(32),
510 state: random_b64(16),
511 nonce: random_b64(16),
512 next,
513 exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60,
514 };
515 let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes()));
516 let cookie_name = format!("{}_pkce", state.config.cookie_name);
517 app_cookies(cx).add(cookie! {
518 cookie_name = seal_json(&state.config.cookie_key, &flight);
519 Path = "/";
520 HttpOnly;
521 SameSite = Lax;
522 MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES)
523 });
524
525 let url = format!(
526 "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256",
527 state.config.issuer,
528 state.config.client_id,
529 urlencoded(&state.config.redirect_uri),
530 flight.state,
531 flight.nonce,
532 challenge,
533 );
534 see(cx, &url)
535}
536
537/// im's answer lands here: exchange the code, validate the id_token, mint
538/// the app session.
539#[route(GET "/auth/callback")]
540async fn iz_callback(cx: &Cx) -> Result<Response, topcoat::Error> {
541 let state = client(cx);
542 let query = topcoat::router::request::uri(cx)
543 .query()
544 .unwrap_or("")
545 .to_string();
546 if let Some(error) = query_value(&query, "error") {
547 return see(cx, &format!("/?auth_error={error}"));
548 }
549 let (Some(code), Some(presented_state)) =
550 (query_value(&query, "code"), query_value(&query, "state"))
551 else {
552 return see(cx, "/?auth_error=invalid_request");
553 };
554 let cookie_name = format!("{}_pkce", state.config.cookie_name);
555 let flight: Option<InFlight> = cookies(cx)
556 .get(&cookie_name)
557 .and_then(|c| open_json(&state.config.cookie_key, c.value()));
558 let Some(flight) = flight else {
559 return see(cx, "/?auth_error=invalid_request");
560 };
561 clear_cookie(cx, &cookie_name);
562 if flight.exp <= OffsetDateTime::now_utc().unix_timestamp()
563 || flight
564 .state
565 .as_bytes()
566 .ct_eq(presented_state.as_bytes())
567 .unwrap_u8()
568 != 1
569 {
570 return see(cx, "/?auth_error=invalid_state");
571 }
572
573 match exchange_code(state, &code, &flight).await {
574 Ok(session) => {
575 set_session_cookie(cx, state, &session);
576 // Re-validated, not trusted: the flight cookie may predate the
577 // strict `next` rules, and its bytes land in a header.
578 see(cx, safe_next(&flight.next))
579 }
580 Err(_) => see(cx, "/?auth_error=exchange_failed"),
581 }
582}
583
584/// Signs out of the app and then of the family: the local cookie is
585/// cleared, and the browser is sent on to im's `/logout` with `back`
586/// pointed back here. Ending the central session is im's half of the
587/// handoff — which is why a sign-out anywhere is a sign-out everywhere.
588///
589/// Where "here" is resolves per request: a registered [`LogoutBack`] is
590/// asked first — a public address stored as a setting is a live fact, not
591/// a boot-time one — and [`Config::logout_back`] answers when it is
592/// absent or has no opinion. Either way the value goes out
593/// slash-terminated: im redirects onto it, and a back without its slash
594/// would make the next path segment join it by luck.
595#[route(GET "/auth/logout")]
596async fn iz_logout(cx: &Cx) -> Result<Response, topcoat::Error> {
597 let state = client(cx);
598 clear_cookie(cx, &state.config.cookie_name);
599 let asked = match try_app_context::<LogoutBack>(cx) {
600 Some(resolver) => (resolver.0)(cx).await,
601 None => None,
602 };
603 let back = format!(
604 "{}/",
605 asked.unwrap_or_else(|| state.config.logout_back.clone())
606 .trim_end_matches('/')
607 );
608 see(
609 cx,
610 &format!(
611 "{}/logout?back={}",
612 state.config.issuer,
613 urlencoded(&back)
614 ),
615 )
616}
617
618fn urlencoded(raw: &str) -> String {
619 let mut out = String::with_capacity(raw.len());
620 for byte in raw.bytes() {
621 match byte {
622 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
623 out.push(byte as char)
624 }
625 _ => out.push_str(&format!("%{byte:02X}")),
626 }
627 }
628 out
629}
630
631// ---------------------------------------------------------------------------
632// Token exchange, refresh, validation
633// ---------------------------------------------------------------------------
634
635#[derive(Deserialize)]
636struct TokenAnswer {
637 /// Validated for its nonce and signature; the identity the app serves
638 /// comes from introspection, not from these claims.
639 id_token: String,
640 /// Not OIDC — im's own: the opaque session this crate introspects per
641 /// request. Absent means the issuer is not a current im.
642 app_session: Option<String>,
643}
644
645async fn exchange_code(state: &IzClient, code: &str, flight: &InFlight) -> Result<Session> {
646 let answer: TokenAnswer = state
647 .http
648 .post(format!("{}/token", state.config.issuer))
649 .form(&[
650 ("grant_type", "authorization_code"),
651 ("code", code),
652 ("redirect_uri", &state.config.redirect_uri),
653 ("client_id", &state.config.client_id),
654 ("client_secret", &state.config.client_secret),
655 ("code_verifier", &flight.verifier),
656 ])
657 .send()
658 .await
659 .map_err(|e| Error::Http(e.to_string()))?
660 .error_for_status()
661 .map_err(|e| Error::Refused(e.to_string()))?
662 .json()
663 .await
664 .map_err(|e| Error::Http(e.to_string()))?;
665 let claims = validate_id_token(state, &answer.id_token).await?;
666 if claims["nonce"].as_str() != Some(flight.nonce.as_str()) {
667 return Err(Error::Token("nonce mismatch".into()));
668 }
669 let app_session = answer
670 .app_session
671 .ok_or_else(|| Error::Token("issuer gave no app session".into()))?;
672 // The session's expiry and identity come from a live introspection, not
673 // from the token answer — the same check every later request will make.
674 // Any non-answer (revoked or unanswered alike) means there is no fresh
675 // session to mint.
676 let (_user, exp) = match introspect(state, &app_session).await {
677 Introspected::Active(user, exp) => (user, exp),
678 Introspected::Revoked | Introspected::Unanswered => {
679 return Err(Error::Refused(
680 "fresh app session does not introspect".into(),
681 ));
682 }
683 };
684 Ok(Session { app_session, exp })
685}
686
687/// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry.
688/// The nonce is the caller's to check (only the callback holds one).
689async fn validate_id_token(state: &IzClient, token: &str) -> Result<serde_json::Value> {
690 let parts: Vec<&str> = token.split('.').collect();
691 if parts.len() != 3 {
692 return Err(Error::Token("not a compact JWT".into()));
693 }
694 let header: serde_json::Value = serde_json::from_slice(
695 &b64url
696 .decode(parts[0])
697 .map_err(|e| Error::Token(e.to_string()))?,
698 )
699 .map_err(|e| Error::Token(e.to_string()))?;
700 if header["alg"] != "RS256" {
701 return Err(Error::Token("unexpected alg".into()));
702 }
703 let kid = header["kid"]
704 .as_str()
705 .ok_or_else(|| Error::Token("no kid".into()))?
706 .to_string();
707
708 if jwks_stale(state).await {
709 refetch_jwks(state).await?;
710 }
711 let key = match cached_key(state, &kid).await {
712 Some(key) => key,
713 None => {
714 refetch_jwks(state).await?;
715 cached_key(state, &kid)
716 .await
717 .ok_or_else(|| Error::Token("unknown kid after refetch".into()))?
718 }
719 };
720
721 verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id)
722}
723
724/// The pure half of [`validate_id_token`]: signature, issuer, audience,
725/// expiry. Split out so the test suite signs its own tokens without standing
726/// a server up.
727fn verify_claims(
728 parts: &[&str],
729 key: &rsa::RsaPublicKey,
730 issuer: &str,
731 client_id: &str,
732) -> Result<serde_json::Value> {
733 use rsa::signature::Verifier;
734 let signature_bytes = b64url
735 .decode(parts[2])
736 .map_err(|e| Error::Token(e.to_string()))?;
737 let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice())
738 .map_err(|e| Error::Token(e.to_string()))?;
739 let verifying = rsa::pkcs1v15::VerifyingKey::<sha2::Sha256>::new(key.clone());
740 verifying
741 .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
742 .map_err(|_| Error::Token("bad signature".into()))?;
743
744 let claims: serde_json::Value = serde_json::from_slice(
745 &b64url
746 .decode(parts[1])
747 .map_err(|e| Error::Token(e.to_string()))?,
748 )
749 .map_err(|e| Error::Token(e.to_string()))?;
750 if claims["iss"].as_str() != Some(issuer) {
751 return Err(Error::Token("wrong issuer".into()));
752 }
753 if claims["aud"].as_str() != Some(client_id) {
754 return Err(Error::Token("wrong audience".into()));
755 }
756 match claims["exp"].as_i64() {
757 Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {}
758 _ => return Err(Error::Token("expired".into())),
759 }
760 Ok(claims)
761}
762
763async fn cached_key(state: &IzClient, kid: &str) -> Option<rsa::RsaPublicKey> {
764 state
765 .jwks
766 .read()
767 .await
768 .as_ref()?
769 .keys
770 .iter()
771 .find(|(k, _)| k == kid)
772 .map(|(_, key)| key.clone())
773}
774
775/// Fetches and caches im's JWKS. Cached for an hour at most; an unknown kid
776/// forces an immediate refetch above.
777async fn refetch_jwks(state: &IzClient) -> Result<()> {
778 let doc: serde_json::Value = state
779 .http
780 .get(format!("{}/jwks.json", state.config.issuer))
781 .send()
782 .await
783 .map_err(|e| Error::Http(e.to_string()))?
784 .error_for_status()
785 .map_err(|e| Error::Refused(e.to_string()))?
786 .json()
787 .await
788 .map_err(|e| Error::Http(e.to_string()))?;
789 let mut keys = Vec::new();
790 for jwk in doc["keys"].as_array().into_iter().flatten() {
791 let (Some(kid), Some(n), Some(e)) =
792 (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str())
793 else {
794 continue;
795 };
796 let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else {
797 continue;
798 };
799 let key = rsa::RsaPublicKey::new(
800 rsa::BoxedUint::from_be_slice_vartime(&n),
801 rsa::BoxedUint::from_be_slice_vartime(&e),
802 )
803 .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?;
804 keys.push((kid.to_string(), key));
805 }
806 *state.jwks.write().await = Some(JwksCache {
807 fetched_at: OffsetDateTime::now_utc(),
808 keys,
809 });
810 Ok(())
811}
812#[cfg(test)]
813mod tests {
814 use super::*;
815 use rsa::signature::{SignatureEncoding, Signer};
816 use rsa::traits::PublicKeyParts;
817 use std::sync::{Arc, OnceLock};
818 use topcoat::cookie::RouterBuilderCookieExt;
819 use topcoat::router::{Body, Router, to_bytes};
820
821 fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {
822 // 2048-bit generation is slow for a unit test; 1024 is the smallest
823 // rsa accepts and the signature math under test is identical.
824 let private = rsa::RsaPrivateKey::new(&mut rand::rng(), 1024).unwrap();
825 let public = private.to_public_key();
826 (private, public)
827 }
828
829 fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String {
830 let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"});
831 let mut out = b64url.encode(header.to_string());
832 out.push('.');
833 out.push_str(&b64url.encode(claims.to_string()));
834 let signing = rsa::pkcs1v15::SigningKey::<sha2::Sha256>::new(key.clone());
835 let signature = signing.sign(out.as_bytes());
836 format!("{}.{}", out, b64url.encode(signature.to_bytes()))
837 }
838
839 fn good_claims() -> serde_json::Value {
840 serde_json::json!({
841 "iss": "http://im.test",
842 "sub": "user-1",
843 "aud": "client-1",
844 "exp": OffsetDateTime::now_utc().unix_timestamp() + 600,
845 "iat": OffsetDateTime::now_utc().unix_timestamp(),
846 "email": "ann@example.com",
847 "name": "Ann",
848 })
849 }
850
851 #[test]
852 fn valid_token_validates() {
853 let (private, public) = keypair();
854 let token = sign(good_claims(), &private);
855 let parts: Vec<&str> = token.split('.').collect();
856 let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap();
857 assert_eq!(claims["sub"], "user-1");
858 }
859
860 #[test]
861 fn tampered_payload_rejected() {
862 let (private, public) = keypair();
863 let token = sign(good_claims(), &private);
864 let parts: Vec<&str> = token.split('.').collect();
865 let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#);
866 let forged = vec![parts[0], forged_payload.as_str(), parts[2]];
867 assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err());
868 }
869
870 #[test]
871 fn wrong_key_rejected() {
872 let (private, _) = keypair();
873 let (_, other_public) = keypair();
874 let token = sign(good_claims(), &private);
875 let parts: Vec<&str> = token.split('.').collect();
876 assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err());
877 }
878
879 #[test]
880 fn wrong_audience_rejected() {
881 let (private, public) = keypair();
882 let token = sign(good_claims(), &private);
883 let parts: Vec<&str> = token.split('.').collect();
884 assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err());
885 }
886
887 #[test]
888 fn wrong_issuer_rejected() {
889 let (private, public) = keypair();
890 let token = sign(good_claims(), &private);
891 let parts: Vec<&str> = token.split('.').collect();
892 assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err());
893 }
894
895 #[test]
896 fn expired_rejected() {
897 let (private, public) = keypair();
898 let mut claims = good_claims();
899 claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into();
900 let token = sign(claims, &private);
901 let parts: Vec<&str> = token.split('.').collect();
902 assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err());
903 }
904
905 #[test]
906 fn pkce_rfc7636_vector() {
907 // RFC 7636 Appendix B.
908 let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
909 let challenge = b64url.encode(Sha256::digest(verifier.as_bytes()));
910 assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
911 }
912
913 #[test]
914 fn cookie_seal_roundtrip() {
915 let key = [7u8; 32];
916 let session = Session {
917 app_session: "opaque-token".into(),
918 exp: 1,
919 };
920 let sealed = seal_json(&key, &session);
921 let back: Session = open_json(&key, &sealed).unwrap();
922 assert_eq!(back.app_session, "opaque-token");
923 assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none());
924 assert!(open_json::<Session>(&key, "garbage").is_none());
925 }
926
927 #[cfg(feature = "test-seam")]
928 #[test]
929 fn seam_cookie_reads_back() {
930 let config = Config {
931 issuer: "http://im.test".into(),
932 client_id: "client-1".into(),
933 client_secret: "secret".into(),
934 redirect_uri: "http://app.test/auth/callback".into(),
935 logout_back: "http://app.test/".into(),
936 cookie_name: "iz_session".into(),
937 cookie_key: [7u8; 32],
938 };
939 assert_eq!(introspect_path(), "/introspect");
940 let exp = OffsetDateTime::now_utc() + time::Duration::hours(1);
941 let sealed = mint_session_cookie(&config, "opaque-token", exp);
942 let back: Session = open_json(&config.cookie_key, &sealed).unwrap();
943 assert_eq!(back.app_session, "opaque-token");
944 assert_eq!(back.exp, exp.unix_timestamp());
945 }
946 // -- review regressions -------------------------------------------------
947 //
948 // Strict `next` (CRLF injection + backslash), a `Location` that cannot
949 // panic, and a `current_user` that only clears the cookie on an explicit
950 // `active:false`.
951
952 #[test]
953 fn next_allows_plain_local_paths() {
954 assert_eq!(safe_next("/"), "/");
955 assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a");
956 assert_eq!(
957 safe_next("/?auth_error=exchange_failed"),
958 "/?auth_error=exchange_failed"
959 );
960 }
961
962 #[test]
963 fn login_next_with_crlf_injection_is_neutralized() {
964 // The login half of the repro: the query arrives percent-encoded,
965 // `query_value` decodes it, `safe_next` judges the decoded bytes.
966 let decoded = query_value("next=/%0d%0aX-evil:1", "next").unwrap();
967 assert_eq!(decoded, "/\r\nX-evil:1");
968 assert_eq!(safe_next(&decoded), "/");
969 assert_eq!(safe_next("/\r\nX-evil:1"), "/");
970 assert_eq!(safe_next("/ok\r/evil"), "/");
971 assert_eq!(safe_next("/tab\there"), "/");
972 }
973
974 #[test]
975 fn next_rejects_backslash_paths() {
976 // Browsers normalize `\` to `/` in `Location`, so a backslash-led
977 // path is an open redirect wearing a local costume.
978 assert_eq!(safe_next("/\\evil"), "/");
979 assert_eq!(safe_next("/drive/\\evil"), "/");
980 assert_eq!(safe_next("\\evil"), "/");
981 assert_eq!(safe_next("//evil.example"), "/");
982 assert_eq!(safe_next("https://evil.example/"), "/");
983 assert_eq!(safe_next(""), "/");
984 }
985
986 #[test]
987 fn location_value_falls_back_to_root() {
988 // `HeaderValue` refuses the injected bytes; the redirect must land
989 // on `/` rather than panic its handler.
990 assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err());
991 assert_eq!(
992 location_value("/\r\nX-evil:1"),
993 HeaderValue::from_static("/")
994 );
995 assert_eq!(
996 location_value("/drive"),
997 HeaderValue::from_str("/drive").unwrap()
998 );
999 }
1000
1001 #[route(GET "/whoami")]
1002 async fn whoami(cx: &Cx) -> Result<Response, topcoat::Error> {
1003 match current_user(cx).await {
1004 Some(user) => user.email.into_response(cx),
1005 None => "anon".into_response(cx),
1006 }
1007 }
1008
1009 fn test_config(issuer: String) -> Config {
1010 Config {
1011 issuer,
1012 client_id: "client-1".into(),
1013 client_secret: "s3cr3t".into(),
1014 redirect_uri: "http://app.test/auth/callback".into(),
1015 logout_back: "http://app.test/".into(),
1016 cookie_name: "iz_session".into(),
1017 cookie_key: [7u8; 32],
1018 }
1019 }
1020
1021 fn test_router(config: Config) -> Router {
1022 mount(Router::builder(), config)
1023 .discover_routes()
1024 .cookies()
1025 .build()
1026 }
1027
1028 fn get(uri: &str, cookie: Option<&str>) -> http::Request<Body> {
1029 let mut builder = http::Request::builder().method("GET").uri(uri);
1030 if let Some(cookie) = cookie {
1031 builder = builder.header(http::header::COOKIE, cookie);
1032 }
1033 builder.body(Body::empty()).unwrap()
1034 }
1035
1036 struct TestResponse {
1037 status: http::StatusCode,
1038 location: Option<String>,
1039 set_cookies: Vec<String>,
1040 body: Vec<u8>,
1041 }
1042
1043 impl TestResponse {
1044 async fn of(response: Response) -> Self {
1045 let status = response.status();
1046 let headers = response.headers().clone();
1047 let location = headers
1048 .get(http::header::LOCATION)
1049 .and_then(|v| v.to_str().ok())
1050 .map(str::to_string);
1051 let set_cookies = headers
1052 .get_all(http::header::SET_COOKIE)
1053 .iter()
1054 .filter_map(|v| v.to_str().ok().map(str::to_string))
1055 .collect();
1056 let body = to_bytes(response.into_body(), usize::MAX)
1057 .await
1058 .unwrap()
1059 .to_vec();
1060 Self {
1061 status,
1062 location,
1063 set_cookies,
1064 body,
1065 }
1066 }
1067
1068 fn text(&self) -> &str {
1069 std::str::from_utf8(&self.body).unwrap()
1070 }
1071
1072 /// The session cookie was cleared iff a `Set-Cookie` names it —
1073 /// the test routes set no cookies of their own.
1074 fn clears_session(&self) -> bool {
1075 self.set_cookies
1076 .iter()
1077 .any(|c| c.starts_with("iz_session="))
1078 }
1079 }
1080
1081 fn session_cookie(token: &str) -> String {
1082 let session = Session {
1083 app_session: token.into(),
1084 exp: OffsetDateTime::now_utc().unix_timestamp() + 3600,
1085 };
1086 format!("iz_session={}", seal_json(&[7u8; 32], &session))
1087 }
1088
1089 /// Canned bodies served per path over plain HTTP/1.1 with keep-alive,
1090 /// behind locks so the test learns the URL first and fills them after.
1091 /// Raw strings, so a test can answer garbage on purpose.
1092 #[derive(Clone, Default)]
1093 struct CannedIm {
1094 token: Arc<OnceLock<String>>,
1095 jwks: Arc<OnceLock<String>>,
1096 introspect: Arc<OnceLock<String>>,
1097 /// Status and body for `POST /family/register`, so a test can be
1098 /// an im that accepts, one that says the key is owned, or one too
1099 /// old to know the route at all.
1100 register: Arc<OnceLock<(u16, String)>>,
1101 /// The whole first registration request, head and body, for the
1102 /// test that reads back what was sent.
1103 register_seen: Arc<OnceLock<String>>,
1104 }
1105
1106 struct FakeIm {
1107 addr: std::net::SocketAddr,
1108 }
1109
1110 impl FakeIm {
1111 async fn spawn(canned: CannedIm) -> Self {
1112 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1113 let addr = listener.local_addr().unwrap();
1114 tokio::spawn(async move {
1115 loop {
1116 let Ok((socket, _)) = listener.accept().await else {
1117 return;
1118 };
1119 let canned = canned.clone();
1120 tokio::spawn(async move {
1121 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1122 let mut socket = socket;
1123 let mut buf = vec![0u8; 8192];
1124 let mut req = Vec::new();
1125 loop {
1126 let body_start = loop {
1127 let Ok(n) = socket.read(&mut buf).await else {
1128 return;
1129 };
1130 if n == 0 {
1131 return;
1132 }
1133 req.extend_from_slice(&buf[..n]);
1134 if let Some(end) = headers_end(&req) {
1135 let head = String::from_utf8_lossy(&req[..end]).to_string();
1136 let len = content_length(&head);
1137 if req.len() >= end + len {
1138 break end;
1139 }
1140 }
1141 if req.len() > 1_000_000 {
1142 return;
1143 }
1144 };
1145 let head = String::from_utf8_lossy(&req[..body_start]).to_string();
1146 let first = head.lines().next().unwrap_or("").to_string();
1147 let len = content_length(&head);
1148 let whole =
1149 String::from_utf8_lossy(&req[..body_start + len]).to_string();
1150 req.drain(..body_start + len);
1151 let (status, payload) = if first.starts_with("POST /token ") {
1152 (200, canned.token.get().cloned().unwrap_or_default())
1153 } else if first.starts_with("GET /jwks.json ") {
1154 (200, canned.jwks.get().cloned().unwrap_or_default())
1155 } else if first.starts_with("POST /family/register ") {
1156 let _ = canned.register_seen.set(whole);
1157 canned
1158 .register
1159 .get()
1160 .cloned()
1161 .unwrap_or((200, String::new()))
1162 } else {
1163 (200, canned.introspect.get().cloned().unwrap_or_default())
1164 };
1165 let response = format!(
1166 "HTTP/1.1 {status} answer\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n",
1167 payload.len()
1168 );
1169 if socket.write_all(response.as_bytes()).await.is_err() {
1170 return;
1171 }
1172 if socket.write_all(payload.as_bytes()).await.is_err() {
1173 return;
1174 }
1175 }
1176 });
1177 }
1178 });
1179 Self { addr }
1180 }
1181
1182 fn url(&self) -> String {
1183 format!("http://{}", self.addr)
1184 }
1185 }
1186
1187 fn headers_end(req: &[u8]) -> Option<usize> {
1188 req.windows(4)
1189 .position(|w| w == b"\r\n\r\n")
1190 .map(|pos| pos + 4)
1191 }
1192
1193 fn content_length(head: &str) -> usize {
1194 head.lines()
1195 .find_map(|line| {
1196 let (name, value) = line.split_once(':')?;
1197 name.trim()
1198 .eq_ignore_ascii_case("content-length")
1199 .then(|| value.trim().parse().unwrap_or(0))
1200 })
1201 .unwrap_or(0)
1202 }
1203
1204 fn jwk_of(public: &rsa::RsaPublicKey, kid: &str) -> serde_json::Value {
1205 serde_json::json!({
1206 "kty": "RSA",
1207 "kid": kid,
1208 "n": b64url.encode(public.n().to_be_bytes_trimmed_vartime()),
1209 "e": b64url.encode(public.e().to_be_bytes_trimmed_vartime()),
1210 })
1211 }
1212
1213 /// The named repro end to end: `GET /auth/login?next=/%0d%0aX-evil:1`,
1214 /// then a completed callback. Pre-fix the sealed `next` carried the CR
1215 /// LF into `see()` and the callback died (500 via the panic boundary);
1216 /// now the browser lands on `/`.
1217 #[tokio::test]
1218 async fn login_then_callback_with_injected_next_lands_on_root() {
1219 let (private, public) = keypair();
1220 // Login touches no im endpoint, so any issuer will do; the flight
1221 // cookie below is opened with the test-known key.
1222 let login_router = test_router(test_config("http://im.test".into()));
1223 let login = TestResponse::of(
1224 login_router
1225 .handle(get("/auth/login?next=/%0d%0aX-evil:1", None))
1226 .await,
1227 )
1228 .await;
1229 assert_eq!(login.status, http::StatusCode::SEE_OTHER);
1230 let sealed = login
1231 .set_cookies
1232 .iter()
1233 .find(|c| c.starts_with("iz_session_pkce="))
1234 .expect("login sets the flight cookie");
1235 let sealed = sealed["iz_session_pkce=".len()..]
1236 .split(';')
1237 .next()
1238 .unwrap();
1239 let flight: InFlight = open_json(&[7u8; 32], sealed).unwrap();
1240 // Neutralized at login: the hostile bytes never reach the seal.
1241 assert_eq!(flight.next, "/");
1242
1243 // Now complete the dance against a fake im.
1244 let canned = CannedIm::default();
1245 let fake = FakeIm::spawn(canned.clone()).await;
1246 let now = OffsetDateTime::now_utc().unix_timestamp();
1247 let id_token = sign(
1248 serde_json::json!({
1249 "iss": fake.url(),
1250 "sub": "user-1",
1251 "aud": "client-1",
1252 "exp": now + 600,
1253 "iat": now,
1254 "nonce": flight.nonce,
1255 }),
1256 &private,
1257 );
1258 let _ = canned
1259 .jwks
1260 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1261 let _ = canned.token.set(
1262 serde_json::json!({
1263 "id_token": id_token,
1264 "app_session": "tok-1",
1265 })
1266 .to_string(),
1267 );
1268 let _ = canned.introspect.set(
1269 serde_json::json!({
1270 "active": true,
1271 "sub": "user-1",
1272 "email": "ann@example.com",
1273 "name": "Ann",
1274 "exp": now + 3600,
1275 })
1276 .to_string(),
1277 );
1278
1279 let router = test_router(test_config(fake.url()));
1280 let callback = TestResponse::of(
1281 router
1282 .handle(get(
1283 &format!("/auth/callback?code=code-1&state={}", flight.state),
1284 Some(&format!("iz_session_pkce={sealed}")),
1285 ))
1286 .await,
1287 )
1288 .await;
1289 assert_eq!(callback.status, http::StatusCode::SEE_OTHER);
1290 assert_eq!(callback.location.as_deref(), Some("/"));
1291 }
1292
1293 /// A flight cookie sealed before the strict rules (hand-sealed hostile
1294 /// here): the callback re-validates before rendering the header, so
1295 /// even this lands on `/` instead of panicking.
1296 #[tokio::test]
1297 async fn callback_with_hostile_stored_next_lands_on_root() {
1298 let (private, public) = keypair();
1299 let canned = CannedIm::default();
1300 let fake = FakeIm::spawn(canned.clone()).await;
1301 let now = OffsetDateTime::now_utc().unix_timestamp();
1302 let flight = InFlight {
1303 verifier: "verifier".into(),
1304 state: "state-1".into(),
1305 nonce: "nonce-1".into(),
1306 next: "/\r\nX-evil:1".into(),
1307 exp: now + 600,
1308 };
1309 let sealed = seal_json(&[7u8; 32], &flight);
1310 let id_token = sign(
1311 serde_json::json!({
1312 "iss": fake.url(),
1313 "sub": "user-1",
1314 "aud": "client-1",
1315 "exp": now + 600,
1316 "iat": now,
1317 "nonce": "nonce-1",
1318 }),
1319 &private,
1320 );
1321 let _ = canned
1322 .jwks
1323 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1324 let _ = canned.token.set(
1325 serde_json::json!({
1326 "id_token": id_token,
1327 "app_session": "tok-1",
1328 })
1329 .to_string(),
1330 );
1331 let _ = canned.introspect.set(
1332 serde_json::json!({
1333 "active": true,
1334 "sub": "user-1",
1335 "email": "ann@example.com",
1336 "name": "Ann",
1337 "exp": now + 3600,
1338 })
1339 .to_string(),
1340 );
1341
1342 let router = test_router(test_config(fake.url()));
1343 let callback = TestResponse::of(
1344 router
1345 .handle(get(
1346 "/auth/callback?code=code-1&state=state-1",
1347 Some(&format!("iz_session_pkce={sealed}")),
1348 ))
1349 .await,
1350 )
1351 .await;
1352 assert_eq!(callback.status, http::StatusCode::SEE_OTHER);
1353 assert_eq!(callback.location.as_deref(), Some("/"));
1354 }
1355
1356 #[tokio::test]
1357 async fn current_user_keeps_cookie_when_im_is_blackholed() {
1358 // Nothing listens: the POST fails, the request reads as signed-out,
1359 // and the cookie survives for the next try.
1360 let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1361 let port = probe.local_addr().unwrap().port();
1362 drop(probe);
1363 let router = test_router(test_config(format!("http://127.0.0.1:{port}")));
1364 let res = TestResponse::of(
1365 router
1366 .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1367 .await,
1368 )
1369 .await;
1370 assert_eq!(res.text(), "anon");
1371 assert!(
1372 !res.clears_session(),
1373 "a blackholed introspection must not clear the cookie: {:?}",
1374 res.set_cookies
1375 );
1376 }
1377
1378 #[tokio::test]
1379 async fn current_user_keeps_cookie_on_unparseable_introspection() {
1380 let canned = CannedIm::default();
1381 let _ = canned.introspect.set("not-json{{{".into());
1382 let fake = FakeIm::spawn(canned).await;
1383 let router = test_router(test_config(fake.url()));
1384 let res = TestResponse::of(
1385 router
1386 .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1387 .await,
1388 )
1389 .await;
1390 assert_eq!(res.text(), "anon");
1391 assert!(
1392 !res.clears_session(),
1393 "an unparseable introspection must not clear the cookie: {:?}",
1394 res.set_cookies
1395 );
1396 }
1397
1398 #[tokio::test]
1399 async fn current_user_keeps_cookie_when_active_is_missing() {
1400 // A malformed answer is not a revocation.
1401 let canned = CannedIm::default();
1402 let _ = canned
1403 .introspect
1404 .set(serde_json::json!({"sub": "user-1"}).to_string());
1405 let fake = FakeIm::spawn(canned).await;
1406 let router = test_router(test_config(fake.url()));
1407 let res = TestResponse::of(
1408 router
1409 .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1410 .await,
1411 )
1412 .await;
1413 assert_eq!(res.text(), "anon");
1414 assert!(
1415 !res.clears_session(),
1416 "an answer without `active` must not clear the cookie: {:?}",
1417 res.set_cookies
1418 );
1419 }
1420
1421 #[tokio::test]
1422 async fn current_user_clears_cookie_when_session_revoked() {
1423 let canned = CannedIm::default();
1424 let _ = canned
1425 .introspect
1426 .set(serde_json::json!({"active": false}).to_string());
1427 let fake = FakeIm::spawn(canned).await;
1428 let router = test_router(test_config(fake.url()));
1429 let res = TestResponse::of(
1430 router
1431 .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1432 .await,
1433 )
1434 .await;
1435 assert_eq!(res.text(), "anon");
1436 assert!(
1437 res.clears_session(),
1438 "an `active:false` answer must clear the cookie: {:?}",
1439 res.set_cookies
1440 );
1441 }
1442
1443 #[tokio::test]
1444 async fn current_user_serves_the_introspected_user() {
1445 let now = OffsetDateTime::now_utc().unix_timestamp();
1446 let canned = CannedIm::default();
1447 let _ = canned.introspect.set(
1448 serde_json::json!({
1449 "active": true,
1450 "sub": "user-1",
1451 "email": "ann@example.com",
1452 "name": "Ann",
1453 "exp": now + 3600,
1454 })
1455 .to_string(),
1456 );
1457 let fake = FakeIm::spawn(canned).await;
1458 let router = test_router(test_config(fake.url()));
1459 let res = TestResponse::of(
1460 router
1461 .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1462 .await,
1463 )
1464 .await;
1465 assert_eq!(res.text(), "ann@example.com");
1466 assert!(
1467 !res.clears_session(),
1468 "a live session must not clear the cookie: {:?}",
1469 res.set_cookies
1470 );
1471 }
1472
1473 /// The happy path, and the request im gets: the client pair as Basic
1474 /// auth and the three fields under the registration route.
1475 #[tokio::test]
1476 async fn register_family_files_the_app_and_carries_the_client_pair() {
1477 let canned = CannedIm::default();
1478 let _ = canned.register.set((
1479 200,
1480 serde_json::json!({"key": "iz", "name": "Board", "url": "https://iz.dizey.sh"})
1481 .to_string(),
1482 ));
1483 let fake = FakeIm::spawn(canned.clone()).await;
1484 let client = IzClient::new(test_config(fake.url()));
1485 let filed = client
1486 .register_family("iz", "Board", "https://iz.dizey.sh")
1487 .await;
1488 assert!(filed.is_ok(), "a 200 must read as filed: {filed:?}");
1489 let seen = canned.register_seen.get().cloned().unwrap_or_default();
1490 assert!(
1491 seen.contains(&format!(
1492 "Basic {}",
1493 base64::engine::general_purpose::STANDARD.encode("client-1:s3cr3t")
1494 )),
1495 "the registration must carry the client pair: {seen}"
1496 );
1497 assert!(
1498 seen.contains(r#""key":"iz""#)
1499 && seen.contains(r#""name":"Board""#)
1500 && seen.contains(r#""url":"https://iz.dizey.sh""#),
1501 "the registration must carry key, name and url: {seen}"
1502 );
1503 }
1504
1505 /// Another app holds the key: the error names the status and im's word
1506 /// for it, so the log line says which of the two it was.
1507 #[tokio::test]
1508 async fn register_family_reports_a_key_another_app_owns() {
1509 let canned = CannedIm::default();
1510 let _ = canned
1511 .register
1512 .set((409, serde_json::json!({"error": "owned"}).to_string()));
1513 let fake = FakeIm::spawn(canned).await;
1514 let client = IzClient::new(test_config(fake.url()));
1515 let problem = client
1516 .register_family("iz", "Board", "https://iz.dizey.sh")
1517 .await
1518 .expect_err("a 409 must not read as filed");
1519 assert!(
1520 problem.contains("409") && problem.contains("owned"),
1521 "the refusal must name the status and im's word: {problem}"
1522 );
1523 }
1524
1525 /// An im too old to register answers 404. That is an `Err` like any
1526 /// other — the caller logs it and goes on to the fetch.
1527 #[tokio::test]
1528 async fn register_family_reports_an_im_that_does_not_register_yet() {
1529 let canned = CannedIm::default();
1530 let _ = canned.register.set((404, "not found".into()));
1531 let fake = FakeIm::spawn(canned).await;
1532 let client = IzClient::new(test_config(fake.url()));
1533 let problem = client
1534 .register_family("iz", "Board", "https://iz.dizey.sh")
1535 .await
1536 .expect_err("a 404 must not read as filed");
1537 assert!(
1538 problem.contains("404"),
1539 "the refusal names the status: {problem}"
1540 );
1541 }
1542}