//! Who the viewer of a request is, and the checks that gate pages and forms. //! //! A signed-in viewer has a local session: a cookie with a random token, of which the database keeps only //! the SHA-256 (conventions section 5). Every check reads the store, never `im`, so pages keep working //! while `im` is down (contracts section 1.1). This module also owns the redirect target check, //! [`safe_next`], which every return path uses. //! //! The helpers here are called by the sign-in pages, the logout form, the photo proxy and the home //! page. The pages that come next (drive, admin) use [`require_member`], [`require_admin`] and //! [`require_csrf`] too. use std::time::Duration; use in_core::store::members::Member; use in_core::store::sessions::Session; use in_core::time::stamp_before; use in_core::token::{constant_time_eq, hash_token}; 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::uri; use crate::oidc::percent_encode; use crate::state::AppState; /// Cookie of the local session. The `__Host-` prefix pins it to this origin, to path `/`, and to HTTPS. pub const SESSION_COOKIE: &str = "__Host-in_session"; /// Cookie of a sign-in in progress: the sealed state, nonce, PKCE verifier and `next` target. pub const FLIGHT_COOKIE: &str = "__Host-in_flight"; /// Absolute age of a local session. Contracts section 2.4 caps it at 12 hours. pub const SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60); /// How long a sign-in may take from the redirect to `im` to the callback. pub const FLIGHT_TTL: Duration = Duration::from_secs(10 * 60); /// Longest `next` target accepted. Longer ones are refused rather than cut. pub const MAX_NEXT_BYTES: usize = 2048; /// How often `last_seen_at` is written. Writing it on every page view would make every read a write. const TOUCH_EVERY: Duration = Duration::from_secs(5 * 60); /// A request's signed-in person: the session that was presented and the member it belongs to. pub struct Viewer { /// The session. Its CSRF token checks the forms of this viewer. pub session: Session, /// The member the session belongs to. Disabled members never get here. pub member: Member, } /// Returns `candidate` when it is a safe place to redirect to, and `None` otherwise. /// /// A safe target is a single absolute path on this origin: it starts with one `/`, the next character is /// not `/` or `\` (browsers read `/\evil` as `//evil`), it has no control characters (no line breaks to /// inject headers) and no backslash anywhere, and it is at most [`MAX_NEXT_BYTES`] long. Anything that /// is not a path, such as a scheme, a percent-encoded slash or an empty string, is refused. pub fn safe_next(candidate: &str) -> Option<&str> { if candidate.len() > MAX_NEXT_BYTES { return None; } let mut chars = candidate.chars(); if chars.next() != Some('/') { return None; } if matches!(chars.next(), Some('/' | '\\')) { return None; } if candidate.chars().any(|c| c.is_control() || c == '\\') { return None; } Some(candidate) } /// The redirect target for an optional `next` value: the value when it is safe, else the start page. pub fn next_or_home(candidate: &str) -> String { safe_next(candidate).unwrap_or("/").to_owned() } /// The sign-in page URL that returns to `next` after sign-in. pub fn login_path(next: &str) -> String { format!("/auth/login?next={}", percent_encode(next)) } /// Sets a cookie that only this origin's root path can read, sent over HTTPS, and hidden from scripts. /// `SameSite=Lax` lets it arrive on the redirect back from `im`. A zero `ttl` deletes the cookie. pub fn set_cookie(cx: &Cx, name: &'static str, value: String, ttl: Duration) { let max_age = time::Duration::seconds(i64::try_from(ttl.as_secs()).unwrap_or(i64::MAX)); let cookie = Cookie::build((name, value)) .path("/") .http_only(true) .secure(true) .same_site(SameSite::Lax) .max_age(max_age) .build(); cookies(cx).add(cookie); } /// Reads a cookie's value, when it is present. pub fn cookie_value(cx: &Cx, name: &str) -> Option { cookies(cx) .get(name) .map(|cookie| cookie.value().to_owned()) } /// The local session that the request presents, when it is still live. The store filters out expired /// sessions and sessions of disabled members. Touches `last_seen_at` at most every [`TOUCH_EVERY`]. pub async fn current_session(cx: &Cx) -> Result> { let Some(token) = cookie_value(cx, SESSION_COOKIE) else { return Ok(None); }; let state = app_context::(cx); let Some(session) = state .store .session_by_token_hash(&hash_token(&token)) .await? else { return Ok(None); }; if session.last_seen_at < stamp_before(TOUCH_EVERY) { state.store.touch_session(&session.id).await?; } Ok(Some(session)) } /// The signed-in person of the request, if any. pub async fn current_member(cx: &Cx) -> Result> { let Some(session) = current_session(cx).await? else { return Ok(None); }; let state = app_context::(cx); let Some(member) = state.store.member(&session.sub).await? else { return Ok(None); }; if member.disabled { return Ok(None); } Ok(Some(Viewer { session, member })) } /// The signed-in person, or a redirect to sign-in that returns to this request's path and query. pub async fn require_member(cx: &Cx) -> Result { match current_member(cx).await? { Some(viewer) => Ok(viewer), None => { let here = uri(cx) .path_and_query() .map_or("/", |path_and_query| path_and_query.as_str()); Err(see_other(login_path(here)).into()) } } } /// A signed-in administrator. A signed-in member who is not one gets `404`, so the admin pages do not /// reveal that they exist. pub async fn require_admin(cx: &Cx) -> Result { let viewer = require_member(cx).await?; if !viewer.member.is_admin { return Err(not_found().into()); } Ok(viewer) } /// Whether `submitted` is the CSRF token of `session`. The comparison is constant-time, and an empty /// stored token never matches, not even an empty submission. pub fn csrf_matches(session: &Session, submitted: &str) -> bool { !session.csrf_token.is_empty() && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) } /// The signed-in administrator, after the CSRF check of an admin form. A member who is not an administrator /// gets `404` before the token is looked at, so the admin forms do not reveal themselves either. pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result { let viewer = require_admin(cx).await?; if !csrf_matches(&viewer.session, submitted) { return Err(forbidden().into()); } Ok(viewer) } /// The signed-in person, after the CSRF check of a state-changing form. A missing session redirects to /// sign-in; a wrong or missing token is `403`. Run it before any side effect. pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { let viewer = require_member(cx).await?; if !csrf_matches(&viewer.session, submitted) { return Err(forbidden().into()); } Ok(viewer) } #[cfg(test)] mod tests { use super::*; #[test] fn safe_next_accepts_local_paths() { assert_eq!(safe_next("/"), Some("/")); assert_eq!( safe_next("/drive/abc?sort=name"), Some("/drive/abc?sort=name") ); assert_eq!(next_or_home(""), "/"); assert_eq!(next_or_home("https://evil.example"), "/"); } #[test] fn safe_next_refuses_attack_strings() { let attacks = [ "//evil.example", "/\\evil.example", "\\\\evil.example", "/\\/evil.example", "https://evil.example", "http://evil.example", "javascript:alert(1)", "%2f%2fevil.example", "/\nSet-Cookie: x=1", "/\r\nLocation: https://evil.example", "/\t/evil.example", "/a\u{0}b", " //evil.example", "drive", "", ]; for attack in attacks { assert_eq!(safe_next(attack), None, "accepted {attack:?}"); } } #[test] fn safe_next_limits_the_length() { let longest = format!("/{}", "a".repeat(MAX_NEXT_BYTES - 1)); assert_eq!(safe_next(&longest), Some(longest.as_str())); assert_eq!(safe_next(&format!("{longest}a")), None); } } /// Helpers for the in-process router tests: a member with a live session. #[cfg(test)] pub(crate) mod test_support { use super::*; use in_core::quota::DEFAULT_MEMBER_QUOTA; use in_core::store::members::MemberFields; use in_core::store::new_id; use in_core::store::sessions::NewSession; use in_core::time::stamp_after; use in_core::token::{generate_token, hash_token}; /// Makes `sub` a member with `quota` bytes and a live session. Returns the session cookie value; the /// session's CSRF token is `csrf-`. pub async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String { state .store .upsert_member_from_claims( &MemberFields { sub: sub.into(), email: format!("{sub}@example.test"), name: sub.into(), is_admin: false, locale: "en".into(), zoneinfo: "UTC".into(), picture_version: 0, im_updated_at: String::new(), }, DEFAULT_MEMBER_QUOTA, ) .await .expect("member"); state.store.set_quota(sub, quota).await.expect("quota"); let token = generate_token(); state .store .create_session(NewSession { sub: sub.into(), token_hash: hash_token(&token), csrf_token: format!("csrf-{sub}"), im_sid: format!("im-{sub}-{}", new_id()), expires_at: stamp_after(SESSION_TTL), ip: None, user_agent: None, id_token_sealed: None, }) .await .expect("session"); token } }