forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

auth.rs288 lines, 10.4 KiBHistoryRawDownload
1//! Who the viewer of a request is, and the checks that gate pages and forms.
2//!
3//! A signed-in viewer has a local session: a cookie with a random token, of which the database keeps only
4//! the SHA-256 (conventions section 5). Every check reads the store, never `im`, so pages keep working
5//! while `im` is down (contracts section 1.1). This module also owns the redirect target check,
6//! [`safe_next`], which every return path uses.
7//!
8//! The helpers here are called by the sign-in pages, the logout form, the photo proxy and the home
9//! page. The pages that come next (drive, admin) use [`require_member`], [`require_admin`] and
10//! [`require_csrf`] too.
11
12use std::time::Duration;
13
14use in_core::store::members::Member;
15use in_core::store::sessions::Session;
16use in_core::time::stamp_before;
17use in_core::token::{constant_time_eq, hash_token};
18use topcoat::Result;
19use topcoat::context::{Cx, app_context};
20use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
21use topcoat::router::error::{forbidden, not_found, see_other};
22use topcoat::router::request::uri;
23
24use crate::oidc::percent_encode;
25use crate::state::AppState;
26
27/// Cookie of the local session. The `__Host-` prefix pins it to this origin, to path `/`, and to HTTPS.
28pub const SESSION_COOKIE: &str = "__Host-in_session";
29
30/// Cookie of a sign-in in progress: the sealed state, nonce, PKCE verifier and `next` target.
31pub const FLIGHT_COOKIE: &str = "__Host-in_flight";
32
33/// Absolute age of a local session. Contracts section 2.4 caps it at 12 hours.
34pub const SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60);
35
36/// How long a sign-in may take from the redirect to `im` to the callback.
37pub const FLIGHT_TTL: Duration = Duration::from_secs(10 * 60);
38
39/// Longest `next` target accepted. Longer ones are refused rather than cut.
40pub const MAX_NEXT_BYTES: usize = 2048;
41
42/// How often `last_seen_at` is written. Writing it on every page view would make every read a write.
43const TOUCH_EVERY: Duration = Duration::from_secs(5 * 60);
44
45/// A request's signed-in person: the session that was presented and the member it belongs to.
46pub struct Viewer {
47 /// The session. Its CSRF token checks the forms of this viewer.
48 pub session: Session,
49 /// The member the session belongs to. Disabled members never get here.
50 pub member: Member,
51}
52
53/// Returns `candidate` when it is a safe place to redirect to, and `None` otherwise.
54///
55/// A safe target is a single absolute path on this origin: it starts with one `/`, the next character is
56/// not `/` or `\` (browsers read `/\evil` as `//evil`), it has no control characters (no line breaks to
57/// inject headers) and no backslash anywhere, and it is at most [`MAX_NEXT_BYTES`] long. Anything that
58/// is not a path, such as a scheme, a percent-encoded slash or an empty string, is refused.
59pub fn safe_next(candidate: &str) -> Option<&str> {
60 if candidate.len() > MAX_NEXT_BYTES {
61 return None;
62 }
63 let mut chars = candidate.chars();
64 if chars.next() != Some('/') {
65 return None;
66 }
67 if matches!(chars.next(), Some('/' | '\\')) {
68 return None;
69 }
70 if candidate.chars().any(|c| c.is_control() || c == '\\') {
71 return None;
72 }
73 Some(candidate)
74}
75
76/// The redirect target for an optional `next` value: the value when it is safe, else the start page.
77pub fn next_or_home(candidate: &str) -> String {
78 safe_next(candidate).unwrap_or("/").to_owned()
79}
80
81/// The sign-in page URL that returns to `next` after sign-in.
82pub fn login_path(next: &str) -> String {
83 format!("/auth/login?next={}", percent_encode(next))
84}
85
86/// Sets a cookie that only this origin's root path can read, sent over HTTPS, and hidden from scripts.
87/// `SameSite=Lax` lets it arrive on the redirect back from `im`. A zero `ttl` deletes the cookie.
88pub fn set_cookie(cx: &Cx, name: &'static str, value: String, ttl: Duration) {
89 let max_age = time::Duration::seconds(i64::try_from(ttl.as_secs()).unwrap_or(i64::MAX));
90 let cookie = Cookie::build((name, value))
91 .path("/")
92 .http_only(true)
93 .secure(true)
94 .same_site(SameSite::Lax)
95 .max_age(max_age)
96 .build();
97 cookies(cx).add(cookie);
98}
99
100/// Reads a cookie's value, when it is present.
101pub fn cookie_value(cx: &Cx, name: &str) -> Option<String> {
102 cookies(cx)
103 .get(name)
104 .map(|cookie| cookie.value().to_owned())
105}
106
107/// The local session that the request presents, when it is still live. The store filters out expired
108/// sessions and sessions of disabled members. Touches `last_seen_at` at most every [`TOUCH_EVERY`].
109pub async fn current_session(cx: &Cx) -> Result<Option<Session>> {
110 let Some(token) = cookie_value(cx, SESSION_COOKIE) else {
111 return Ok(None);
112 };
113 let state = app_context::<AppState>(cx);
114 let Some(session) = state
115 .store
116 .session_by_token_hash(&hash_token(&token))
117 .await?
118 else {
119 return Ok(None);
120 };
121 if session.last_seen_at < stamp_before(TOUCH_EVERY) {
122 state.store.touch_session(&session.id).await?;
123 }
124 Ok(Some(session))
125}
126
127/// The signed-in person of the request, if any.
128pub async fn current_member(cx: &Cx) -> Result<Option<Viewer>> {
129 let Some(session) = current_session(cx).await? else {
130 return Ok(None);
131 };
132 let state = app_context::<AppState>(cx);
133 let Some(member) = state.store.member(&session.sub).await? else {
134 return Ok(None);
135 };
136 if member.disabled {
137 return Ok(None);
138 }
139 Ok(Some(Viewer { session, member }))
140}
141
142/// The signed-in person, or a redirect to sign-in that returns to this request's path and query.
143pub async fn require_member(cx: &Cx) -> Result<Viewer> {
144 match current_member(cx).await? {
145 Some(viewer) => Ok(viewer),
146 None => {
147 let here = uri(cx)
148 .path_and_query()
149 .map_or("/", |path_and_query| path_and_query.as_str());
150 Err(see_other(login_path(here)).into())
151 }
152 }
153}
154
155/// A signed-in administrator. A signed-in member who is not one gets `404`, so the admin pages do not
156/// reveal that they exist.
157pub async fn require_admin(cx: &Cx) -> Result<Viewer> {
158 let viewer = require_member(cx).await?;
159 if !viewer.member.is_admin {
160 return Err(not_found().into());
161 }
162 Ok(viewer)
163}
164
165/// Whether `submitted` is the CSRF token of `session`. The comparison is constant-time, and an empty
166/// stored token never matches, not even an empty submission.
167pub fn csrf_matches(session: &Session, submitted: &str) -> bool {
168 !session.csrf_token.is_empty()
169 && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes())
170}
171
172/// The signed-in administrator, after the CSRF check of an admin form. A member who is not an administrator
173/// gets `404` before the token is looked at, so the admin forms do not reveal themselves either.
174pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> {
175 let viewer = require_admin(cx).await?;
176 if !csrf_matches(&viewer.session, submitted) {
177 return Err(forbidden().into());
178 }
179 Ok(viewer)
180}
181
182/// The signed-in person, after the CSRF check of a state-changing form. A missing session redirects to
183/// sign-in; a wrong or missing token is `403`. Run it before any side effect.
184pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> {
185 let viewer = require_member(cx).await?;
186 if !csrf_matches(&viewer.session, submitted) {
187 return Err(forbidden().into());
188 }
189 Ok(viewer)
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[test]
197 fn safe_next_accepts_local_paths() {
198 assert_eq!(safe_next("/"), Some("/"));
199 assert_eq!(
200 safe_next("/drive/abc?sort=name"),
201 Some("/drive/abc?sort=name")
202 );
203 assert_eq!(next_or_home(""), "/");
204 assert_eq!(next_or_home("https://evil.example"), "/");
205 }
206
207 #[test]
208 fn safe_next_refuses_attack_strings() {
209 let attacks = [
210 "//evil.example",
211 "/\\evil.example",
212 "\\\\evil.example",
213 "/\\/evil.example",
214 "https://evil.example",
215 "http://evil.example",
216 "javascript:alert(1)",
217 "%2f%2fevil.example",
218 "/\nSet-Cookie: x=1",
219 "/\r\nLocation: https://evil.example",
220 "/\t/evil.example",
221 "/a\u{0}b",
222 " //evil.example",
223 "drive",
224 "",
225 ];
226 for attack in attacks {
227 assert_eq!(safe_next(attack), None, "accepted {attack:?}");
228 }
229 }
230
231 #[test]
232 fn safe_next_limits_the_length() {
233 let longest = format!("/{}", "a".repeat(MAX_NEXT_BYTES - 1));
234 assert_eq!(safe_next(&longest), Some(longest.as_str()));
235 assert_eq!(safe_next(&format!("{longest}a")), None);
236 }
237}
238
239/// Helpers for the in-process router tests: a member with a live session.
240#[cfg(test)]
241pub(crate) mod test_support {
242 use super::*;
243 use in_core::quota::DEFAULT_MEMBER_QUOTA;
244 use in_core::store::members::MemberFields;
245 use in_core::store::new_id;
246 use in_core::store::sessions::NewSession;
247 use in_core::time::stamp_after;
248 use in_core::token::{generate_token, hash_token};
249
250 /// Makes `sub` a member with `quota` bytes and a live session. Returns the session cookie value; the
251 /// session's CSRF token is `csrf-<sub>`.
252 pub async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String {
253 state
254 .store
255 .upsert_member_from_claims(
256 &MemberFields {
257 sub: sub.into(),
258 email: format!("{sub}@example.test"),
259 name: sub.into(),
260 is_admin: false,
261 locale: "en".into(),
262 zoneinfo: "UTC".into(),
263 picture_version: 0,
264 im_updated_at: String::new(),
265 },
266 DEFAULT_MEMBER_QUOTA,
267 )
268 .await
269 .expect("member");
270 state.store.set_quota(sub, quota).await.expect("quota");
271 let token = generate_token();
272 state
273 .store
274 .create_session(NewSession {
275 sub: sub.into(),
276 token_hash: hash_token(&token),
277 csrf_token: format!("csrf-{sub}"),
278 im_sid: format!("im-{sub}-{}", new_id()),
279 expires_at: stamp_after(SESSION_TTL),
280 ip: None,
281 user_agent: None,
282 id_token_sealed: None,
283 })
284 .await
285 .expect("session");
286 token
287 }
288}