//! Sessions and access checks for the web layer: the cookies, the current member, the role and CSRF //! checks that every handler calls first, and the `next` guard for redirects. //! //! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256 //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in //! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it. use std::fmt; use std::time::Duration; use iz_core::authz::{Action, Actor, Denied, authorize}; use iz_core::secret; use iz_core::store::Store; use iz_core::store::members::Member; use iz_core::store::sessions::SessionRecord; use iz_core::token::constant_time_eq; use reqwest::Url; use serde::{Deserialize, Serialize}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; use topcoat::router::error::{forbidden, not_found, see_other}; use topcoat::router::request::{headers, uri}; use crate::oidc::unix_now; use crate::state::AppState; /// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-iz_session`. pub const SESSION_COOKIE: &str = "iz_session"; /// Logical name of the sign-in flight cookie. Stored as `__Host-iz_flight`. pub const STATE_COOKIE: &str = "iz_flight"; /// Lifetime of a local session, in seconds of absolute age (contracts.md 2.4: at most 12 hours). pub const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60); /// How long a sign-in may take from the start to the callback (contracts.md 2.3 and this task). pub const STATE_LIFETIME: Duration = Duration::from_secs(10 * 60); /// Longest `next` target accepted, in bytes. Reason: a return path is a path, not a document. const MAX_NEXT_LEN: usize = 2048; /// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins. const MAX_USER_AGENT_LEN: usize = 256; /// The level a page or a write needs. Maps to one authorization action. The administrator level is /// added with the admin pages. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Need { /// Reading the board. Viewer, /// Creating and changing tasks, comments and files. Member, /// The administrator pages: sender, mail rules, logs and messages to members. Admin, } /// A signed-in member and the session that carries them. pub struct CurrentMember { /// The session row (its CSRF token, its sid and the sealed ID token). pub session: SessionRecord, /// The member row, read in the same request. pub member: Member, } impl CurrentMember { /// The actor for [`authorize`], built from the stored member. pub fn actor(&self) -> Actor { Actor::Member { sub: self.member.sub.clone(), role: self.member.role, im_admin: self.member.im_admin, disabled: self.member.disabled, } } /// Whether `submitted` is this session's CSRF token, compared in constant time. An empty value /// never matches. pub fn csrf_matches(&self, submitted: &str) -> bool { !submitted.is_empty() && !self.session.csrf_token.is_empty() && constant_time_eq(self.session.csrf_token.as_bytes(), submitted.as_bytes()) } } /// The state of one sign-in, sealed into the flight cookie. #[derive(Serialize, Deserialize)] pub struct SignInState { /// The `state` parameter sent to `im`. Compared with the one that comes back. pub state: String, /// The `nonce` sent to `im`. Must equal the nonce of the ID token. pub nonce: String, /// The PKCE verifier. Only its challenge went to `im`. pub verifier: String, /// The return path, already checked by [`safe_next`] when it was stored. pub next: String, /// Unix time after which the flight is refused. pub expires: u64, } // Hand-written so that a debug print never shows the state, the nonce or the PKCE verifier. impl fmt::Debug for SignInState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SignInState") .field("state", &"") .field("nonce", &"") .field("verifier", &"") .field("next", &self.next) .field("expires", &self.expires) .finish() } } /// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain. fn jar(cx: &Cx) -> impl Cookies + '_ { cookies(cx).override_prefix_host() } /// The signed-in member, or `None` when there is no session, the session has expired, or its member /// is disabled or has no role. The store answers all of these the same way. pub async fn current_member(cx: &Cx) -> Result> { let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { return Ok(None); }; member_of_token(&app_context::(cx).store, cookie.value()).await } /// The value of the session cookie, or an empty string when there is none. A live stream keeps it, so /// it can check the session again after the request has ended. pub fn session_cookie(cx: &Cx) -> String { jar(cx) .get(SESSION_COOKIE) .map(|cookie| cookie.value().to_owned()) .unwrap_or_default() } /// The member of a session cookie `token`, under the same rules as [`current_member`]. pub async fn member_of_token(store: &Store, token: &str) -> Result> { let Some(session) = store.session_by_token(token).await? else { return Ok(None); }; let Some(member) = store.member(&session.sub).await? else { return Ok(None); }; Ok(Some(CurrentMember { session, member })) } /// Whether the session `token` still belongs to a member who may read the board. A live stream asks /// this before each event, so a signed-out or disabled viewer stops receiving them. pub async fn still_reads_board(store: &Store, token: &str) -> Result { let Some(me) = member_of_token(store, token).await? else { return Ok(false); }; Ok(authorize(&me.actor(), &Action::ReadBoard).is_ok()) } /// The signed-in member. Without a session, redirects to `/login?next=`. pub async fn require_member(cx: &Cx) -> Result { match current_member(cx).await? { Some(me) => Ok(me), None => { let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); let target = format!("/auth/login?next={}", percent_encode(path)); Err(see_other(target).into()) } } } /// The signed-in member with the level `need`. A viewer or member who tries a write gets `403`; a /// member with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. /// Administrator pages answer `404` to everyone who is not an administrator, anonymous visitors /// included: an admin page does not reveal that it exists, so it never redirects to sign-in. pub async fn require_role(cx: &Cx, need: Need) -> Result { if need == Need::Admin { let Some(me) = current_member(cx).await? else { return Err(not_found().into()); }; return match authorize(&me.actor(), &Action::Administer) { Ok(()) => Ok(me), Err(_) => Err(not_found().into()), }; } let me = require_member(cx).await?; let action = match need { Need::Viewer => Action::ReadBoard, _ => Action::WriteTask, }; match authorize(&me.actor(), &action) { Ok(()) => Ok(me), Err(Denied::Forbidden) => Err(forbidden().into()), Err(_) => Err(not_found().into()), } } /// The signed-in member with the level `need`, after the CSRF check. The level is checked first, so a /// viewer gets `403` whatever token they send. A missing or wrong `csrf` is `403`. Both run before any /// side effect of the handler. pub async fn require_csrf(cx: &Cx, need: Need, submitted: &str) -> Result { let me = require_role(cx, need).await?; if me.csrf_matches(submitted) { Ok(me) } else { Err(forbidden().into()) } } /// Stores a new session cookie. `token` is the value from [`store::sessions::IssuedSession`]. pub fn set_session_cookie(cx: &Cx, token: String) { jar(cx).add( Cookie::build((SESSION_COOKIE, token)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Lax) .max_age(time::Duration::seconds( i64::try_from(SESSION_LIFETIME.as_secs()).unwrap_or(i64::MAX), )) .build(), ); } /// Removes the session cookie. pub fn clear_session_cookie(cx: &Cx) { jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); } /// Stores the sealed sign-in flight. `SameSite=Lax` is needed: the callback is a top-level /// navigation that comes back from `im`. pub fn set_state_cookie(cx: &Cx, sealed: String) { jar(cx).add( Cookie::build((STATE_COOKIE, sealed)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Lax) .max_age(time::Duration::seconds( i64::try_from(STATE_LIFETIME.as_secs()).unwrap_or(i64::MAX), )) .build(), ); } /// The sealed sign-in flight cookie, if the browser sent one. pub fn state_cookie(cx: &Cx) -> Option { jar(cx).get(STATE_COOKIE).map(|c| c.value().to_owned()) } /// Removes the sign-in flight cookie. Called on every callback, whatever the outcome, so a flight /// can be used only once. pub fn clear_state_cookie(cx: &Cx) { jar(cx).remove(Cookie::build((STATE_COOKIE, "")).path("/")); } /// Seals a sign-in flight for the cookie. pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result { let json = serde_json::to_vec(state) .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?; secret::seal(key, secret::purpose::SIGN_IN_FLIGHT, &json) } /// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry. pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option { let plain = secret::open(key, secret::purpose::SIGN_IN_FLIGHT, sealed).ok()?; let state: SignInState = serde_json::from_slice(&plain).ok()?; (unix_now() < state.expires).then_some(state) } /// The User-Agent of the request, shortened, for the session row. pub fn user_agent(cx: &Cx) -> Option { headers(cx) .get(http::header::USER_AGENT) .and_then(|value| value.to_str().ok()) .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect()) } /// The raw query string of the request, without the `?`. `None` when the request has none. pub fn uri_query(cx: &Cx) -> Option { uri(cx).query().map(str::to_owned) } /// One query parameter of the request, decoded. `None` when it is absent. pub fn query_param(cx: &Cx, name: &str) -> Option { let mut url = Url::parse("http://iz.invalid/").ok()?; url.set_query(uri(cx).query()); url.query_pairs() .find(|(key, _)| key == name) .map(|(_, value)| value.into_owned()) } /// The return path, if it is safe to redirect to; otherwise `/`. A safe path starts with one `/`, /// is ASCII without control characters, and is at most 2048 bytes. Anything that could name another /// host (`//`, `/\`, a scheme) is refused. pub fn safe_next(next: Option<&str>) -> &str { match next { Some(path) if is_local_path(path) => path, _ => "/", } } fn is_local_path(path: &str) -> bool { path.len() <= MAX_NEXT_LEN && path.starts_with('/') && !path.starts_with("//") && !path.starts_with("/\\") && path.bytes().all(|b| b.is_ascii() && !b.is_ascii_control()) } /// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL. pub fn percent_encode(input: &str) -> String { let mut out = String::with_capacity(input.len()); for b in input.bytes() { match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { out.push(char::from(b)); } _ => out.push_str(&format!("%{b:02X}")), } } out } #[cfg(test)] mod tests { use super::*; #[test] fn safe_next_accepts_local_paths() { assert_eq!(safe_next(Some("/")), "/"); assert_eq!(safe_next(Some("/tasks/IZ-4?file=2")), "/tasks/IZ-4?file=2"); } /// Every string here is a classic open-redirect or header-injection attempt. None may come back. #[test] fn safe_next_refuses_the_attack_strings() { let attacks = [ "//evil.example", "/\\evil.example", "\\\\evil.example", "https://evil.example", "HTTPS://evil.example", "%2f%2fevil.example", "%5c%5cevil.example", "javascript:alert(1)", "/\r\nSet-Cookie: x=y", "/ok\nLocation: https://evil.example", "/\t/evil.example", " //evil.example", "evil.example", "", ]; for attack in attacks { assert_eq!(safe_next(Some(attack)), "/", "accepted {attack:?}"); } assert_eq!(safe_next(None), "/"); let too_long = format!("/{}", "a".repeat(MAX_NEXT_LEN)); assert_eq!(safe_next(Some(&too_long)), "/"); } #[test] fn sign_in_state_round_trips_and_expires() { let key = [9u8; 32]; let state = SignInState { state: "s".into(), nonce: "n".into(), verifier: "v".into(), next: "/".into(), expires: unix_now() + 600, }; let sealed = seal_sign_in_state(&key, &state).unwrap(); let opened = open_sign_in_state(&key, &sealed).unwrap(); assert_eq!(opened.nonce, "n"); assert!(open_sign_in_state(&[8u8; 32], &sealed).is_none()); let stale = SignInState { expires: unix_now() - 1, ..state }; let sealed = seal_sign_in_state(&key, &stale).unwrap(); assert!(open_sign_in_state(&key, &sealed).is_none()); } }