forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

auth.rs376 lines, 14.0 KiBHistoryRawDownload
1//! Sessions and access checks for the web layer: the cookies, the current member, the role and CSRF
2//! checks that every handler calls first, and the `next` guard for redirects.
3//!
4//! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256
5//! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in
6//! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it.
7
8use std::fmt;
9use std::time::Duration;
10
11use iz_core::authz::{Action, Actor, Denied, authorize};
12use iz_core::secret;
13use iz_core::store::Store;
14use iz_core::store::members::Member;
15use iz_core::store::sessions::SessionRecord;
16use iz_core::token::constant_time_eq;
17use reqwest::Url;
18use serde::{Deserialize, Serialize};
19use topcoat::Result;
20use topcoat::context::{Cx, app_context};
21use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
22use topcoat::router::error::{forbidden, not_found, see_other};
23use topcoat::router::request::{headers, uri};
24
25use crate::oidc::unix_now;
26use crate::state::AppState;
27
28/// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-iz_session`.
29pub const SESSION_COOKIE: &str = "iz_session";
30/// Logical name of the sign-in flight cookie. Stored as `__Host-iz_flight`.
31pub const STATE_COOKIE: &str = "iz_flight";
32/// Lifetime of a local session, in seconds of absolute age (contracts.md 2.4: at most 12 hours).
33pub const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60);
34/// How long a sign-in may take from the start to the callback (contracts.md 2.3 and this task).
35pub const STATE_LIFETIME: Duration = Duration::from_secs(10 * 60);
36/// Longest `next` target accepted, in bytes. Reason: a return path is a path, not a document.
37const MAX_NEXT_LEN: usize = 2048;
38/// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins.
39const MAX_USER_AGENT_LEN: usize = 256;
40
41/// The level a page or a write needs. Maps to one authorization action. The administrator level is
42/// added with the admin pages.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum Need {
45 /// Reading the board.
46 Viewer,
47 /// Creating and changing tasks, comments and files.
48 Member,
49 /// The administrator pages: sender, mail rules, logs and messages to members.
50 Admin,
51}
52
53/// A signed-in member and the session that carries them.
54pub struct CurrentMember {
55 /// The session row (its CSRF token, its sid and the sealed ID token).
56 pub session: SessionRecord,
57 /// The member row, read in the same request.
58 pub member: Member,
59}
60
61impl CurrentMember {
62 /// The actor for [`authorize`], built from the stored member.
63 pub fn actor(&self) -> Actor {
64 Actor::Member {
65 sub: self.member.sub.clone(),
66 role: self.member.role,
67 im_admin: self.member.im_admin,
68 disabled: self.member.disabled,
69 }
70 }
71
72 /// Whether `submitted` is this session's CSRF token, compared in constant time. An empty value
73 /// never matches.
74 pub fn csrf_matches(&self, submitted: &str) -> bool {
75 !submitted.is_empty()
76 && !self.session.csrf_token.is_empty()
77 && constant_time_eq(self.session.csrf_token.as_bytes(), submitted.as_bytes())
78 }
79}
80
81/// The state of one sign-in, sealed into the flight cookie.
82#[derive(Serialize, Deserialize)]
83pub struct SignInState {
84 /// The `state` parameter sent to `im`. Compared with the one that comes back.
85 pub state: String,
86 /// The `nonce` sent to `im`. Must equal the nonce of the ID token.
87 pub nonce: String,
88 /// The PKCE verifier. Only its challenge went to `im`.
89 pub verifier: String,
90 /// The return path, already checked by [`safe_next`] when it was stored.
91 pub next: String,
92 /// Unix time after which the flight is refused.
93 pub expires: u64,
94}
95
96// Hand-written so that a debug print never shows the state, the nonce or the PKCE verifier.
97impl fmt::Debug for SignInState {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 f.debug_struct("SignInState")
100 .field("state", &"<redacted>")
101 .field("nonce", &"<redacted>")
102 .field("verifier", &"<redacted>")
103 .field("next", &self.next)
104 .field("expires", &self.expires)
105 .finish()
106 }
107}
108
109/// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain.
110fn jar(cx: &Cx) -> impl Cookies + '_ {
111 cookies(cx).override_prefix_host()
112}
113
114/// The signed-in member, or `None` when there is no session, the session has expired, or its member
115/// is disabled or has no role. The store answers all of these the same way.
116pub async fn current_member(cx: &Cx) -> Result<Option<CurrentMember>> {
117 let Some(cookie) = jar(cx).get(SESSION_COOKIE) else {
118 return Ok(None);
119 };
120 member_of_token(&app_context::<AppState>(cx).store, cookie.value()).await
121}
122
123/// The value of the session cookie, or an empty string when there is none. A live stream keeps it, so
124/// it can check the session again after the request has ended.
125pub fn session_cookie(cx: &Cx) -> String {
126 jar(cx)
127 .get(SESSION_COOKIE)
128 .map(|cookie| cookie.value().to_owned())
129 .unwrap_or_default()
130}
131
132/// The member of a session cookie `token`, under the same rules as [`current_member`].
133pub async fn member_of_token(store: &Store, token: &str) -> Result<Option<CurrentMember>> {
134 let Some(session) = store.session_by_token(token).await? else {
135 return Ok(None);
136 };
137 let Some(member) = store.member(&session.sub).await? else {
138 return Ok(None);
139 };
140 Ok(Some(CurrentMember { session, member }))
141}
142
143/// Whether the session `token` still belongs to a member who may read the board. A live stream asks
144/// this before each event, so a signed-out or disabled viewer stops receiving them.
145pub async fn still_reads_board(store: &Store, token: &str) -> Result<bool> {
146 let Some(me) = member_of_token(store, token).await? else {
147 return Ok(false);
148 };
149 Ok(authorize(&me.actor(), &Action::ReadBoard).is_ok())
150}
151
152/// The signed-in member. Without a session, redirects to `/login?next=<this page>`.
153pub async fn require_member(cx: &Cx) -> Result<CurrentMember> {
154 match current_member(cx).await? {
155 Some(me) => Ok(me),
156 None => {
157 let path = uri(cx).path_and_query().map_or("/", |p| p.as_str());
158 let target = format!("/auth/login?next={}", percent_encode(path));
159 Err(see_other(target).into())
160 }
161 }
162}
163
164/// The signed-in member with the level `need`. A viewer or member who tries a write gets `403`; a
165/// member with no access, or a disabled one, gets `404`, so the page does not reveal that it exists.
166/// Administrator pages answer `404` to everyone who is not an administrator, anonymous visitors
167/// included: an admin page does not reveal that it exists, so it never redirects to sign-in.
168pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> {
169 if need == Need::Admin {
170 let Some(me) = current_member(cx).await? else {
171 return Err(not_found().into());
172 };
173 return match authorize(&me.actor(), &Action::Administer) {
174 Ok(()) => Ok(me),
175 Err(_) => Err(not_found().into()),
176 };
177 }
178 let me = require_member(cx).await?;
179 let action = match need {
180 Need::Viewer => Action::ReadBoard,
181 _ => Action::WriteTask,
182 };
183 match authorize(&me.actor(), &action) {
184 Ok(()) => Ok(me),
185 Err(Denied::Forbidden) => Err(forbidden().into()),
186 Err(_) => Err(not_found().into()),
187 }
188}
189
190/// The signed-in member with the level `need`, after the CSRF check. The level is checked first, so a
191/// viewer gets `403` whatever token they send. A missing or wrong `csrf` is `403`. Both run before any
192/// side effect of the handler.
193pub async fn require_csrf(cx: &Cx, need: Need, submitted: &str) -> Result<CurrentMember> {
194 let me = require_role(cx, need).await?;
195 if me.csrf_matches(submitted) {
196 Ok(me)
197 } else {
198 Err(forbidden().into())
199 }
200}
201
202/// Stores a new session cookie. `token` is the value from [`store::sessions::IssuedSession`].
203pub fn set_session_cookie(cx: &Cx, token: String) {
204 jar(cx).add(
205 Cookie::build((SESSION_COOKIE, token))
206 .path("/")
207 .secure(true)
208 .http_only(true)
209 .same_site(SameSite::Lax)
210 .max_age(time::Duration::seconds(
211 i64::try_from(SESSION_LIFETIME.as_secs()).unwrap_or(i64::MAX),
212 ))
213 .build(),
214 );
215}
216
217/// Removes the session cookie.
218pub fn clear_session_cookie(cx: &Cx) {
219 jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
220}
221
222/// Stores the sealed sign-in flight. `SameSite=Lax` is needed: the callback is a top-level
223/// navigation that comes back from `im`.
224pub fn set_state_cookie(cx: &Cx, sealed: String) {
225 jar(cx).add(
226 Cookie::build((STATE_COOKIE, sealed))
227 .path("/")
228 .secure(true)
229 .http_only(true)
230 .same_site(SameSite::Lax)
231 .max_age(time::Duration::seconds(
232 i64::try_from(STATE_LIFETIME.as_secs()).unwrap_or(i64::MAX),
233 ))
234 .build(),
235 );
236}
237
238/// The sealed sign-in flight cookie, if the browser sent one.
239pub fn state_cookie(cx: &Cx) -> Option<String> {
240 jar(cx).get(STATE_COOKIE).map(|c| c.value().to_owned())
241}
242
243/// Removes the sign-in flight cookie. Called on every callback, whatever the outcome, so a flight
244/// can be used only once.
245pub fn clear_state_cookie(cx: &Cx) {
246 jar(cx).remove(Cookie::build((STATE_COOKIE, "")).path("/"));
247}
248
249/// Seals a sign-in flight for the cookie.
250pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result<String> {
251 let json = serde_json::to_vec(state)
252 .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?;
253 secret::seal(key, secret::purpose::SIGN_IN_FLIGHT, &json)
254}
255
256/// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry.
257pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option<SignInState> {
258 let plain = secret::open(key, secret::purpose::SIGN_IN_FLIGHT, sealed).ok()?;
259 let state: SignInState = serde_json::from_slice(&plain).ok()?;
260 (unix_now() < state.expires).then_some(state)
261}
262
263/// The User-Agent of the request, shortened, for the session row.
264pub fn user_agent(cx: &Cx) -> Option<String> {
265 headers(cx)
266 .get(http::header::USER_AGENT)
267 .and_then(|value| value.to_str().ok())
268 .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect())
269}
270
271/// The raw query string of the request, without the `?`. `None` when the request has none.
272pub fn uri_query(cx: &Cx) -> Option<String> {
273 uri(cx).query().map(str::to_owned)
274}
275
276/// One query parameter of the request, decoded. `None` when it is absent.
277pub fn query_param(cx: &Cx, name: &str) -> Option<String> {
278 let mut url = Url::parse("http://iz.invalid/").ok()?;
279 url.set_query(uri(cx).query());
280 url.query_pairs()
281 .find(|(key, _)| key == name)
282 .map(|(_, value)| value.into_owned())
283}
284
285/// The return path, if it is safe to redirect to; otherwise `/`. A safe path starts with one `/`,
286/// is ASCII without control characters, and is at most 2048 bytes. Anything that could name another
287/// host (`//`, `/\`, a scheme) is refused.
288pub fn safe_next(next: Option<&str>) -> &str {
289 match next {
290 Some(path) if is_local_path(path) => path,
291 _ => "/",
292 }
293}
294
295fn is_local_path(path: &str) -> bool {
296 path.len() <= MAX_NEXT_LEN
297 && path.starts_with('/')
298 && !path.starts_with("//")
299 && !path.starts_with("/\\")
300 && path.bytes().all(|b| b.is_ascii() && !b.is_ascii_control())
301}
302
303/// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL.
304pub fn percent_encode(input: &str) -> String {
305 let mut out = String::with_capacity(input.len());
306 for b in input.bytes() {
307 match b {
308 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
309 out.push(char::from(b));
310 }
311 _ => out.push_str(&format!("%{b:02X}")),
312 }
313 }
314 out
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn safe_next_accepts_local_paths() {
323 assert_eq!(safe_next(Some("/")), "/");
324 assert_eq!(safe_next(Some("/tasks/IZ-4?file=2")), "/tasks/IZ-4?file=2");
325 }
326
327 /// Every string here is a classic open-redirect or header-injection attempt. None may come back.
328 #[test]
329 fn safe_next_refuses_the_attack_strings() {
330 let attacks = [
331 "//evil.example",
332 "/\\evil.example",
333 "\\\\evil.example",
334 "https://evil.example",
335 "HTTPS://evil.example",
336 "%2f%2fevil.example",
337 "%5c%5cevil.example",
338 "javascript:alert(1)",
339 "/\r\nSet-Cookie: x=y",
340 "/ok\nLocation: https://evil.example",
341 "/\t/evil.example",
342 " //evil.example",
343 "evil.example",
344 "",
345 ];
346 for attack in attacks {
347 assert_eq!(safe_next(Some(attack)), "/", "accepted {attack:?}");
348 }
349 assert_eq!(safe_next(None), "/");
350 let too_long = format!("/{}", "a".repeat(MAX_NEXT_LEN));
351 assert_eq!(safe_next(Some(&too_long)), "/");
352 }
353
354 #[test]
355 fn sign_in_state_round_trips_and_expires() {
356 let key = [9u8; 32];
357 let state = SignInState {
358 state: "s".into(),
359 nonce: "n".into(),
360 verifier: "v".into(),
361 next: "/".into(),
362 expires: unix_now() + 600,
363 };
364 let sealed = seal_sign_in_state(&key, &state).unwrap();
365 let opened = open_sign_in_state(&key, &sealed).unwrap();
366 assert_eq!(opened.nonce, "n");
367 assert!(open_sign_in_state(&[8u8; 32], &sealed).is_none());
368
369 let stale = SignInState {
370 expires: unix_now() - 1,
371 ..state
372 };
373 let sealed = seal_sign_in_state(&key, &stale).unwrap();
374 assert!(open_sign_in_state(&key, &sealed).is_none());
375 }
376}