Skip to main content

tuwunel_service/users/
browser_session.rs

1//! Browser sessions minted by a password sign-in on the built-in login page.
2//!
3//! A row records when the browser signed in; expiry is computed at each read
4//! from the live `authentication.oidc.browser_session_ttl`, so lowering the
5//! setting shortens existing sessions at once. The cookie names the user and a
6//! random secret, and only the secret's digest is stored.
7
8use std::time::Duration;
9
10use futures::TryFutureExt;
11use ruma::UserId;
12use tuwunel_core::{
13	Result, debug, implement,
14	utils::{
15		BoolExt, hash::sha256::hash as sha256, millis_since_unix_epoch, random_string,
16		result::NotFound, stream::TryReadyExt, time::now,
17	},
18	warn,
19};
20use tuwunel_database::{Deserialized, Interfix};
21
22/// Upper bound on `browser_session_ttl`, in seconds.
23///
24/// The `useridbrowsersession_createdat` descriptor drops rows at this age, so
25/// raising it means raising the descriptor's `ttl` too.
26const TTL_MAX: u64 = 60 * 60 * 24 * 90;
27
28const SECRET_LENGTH: usize = 32;
29
30/// A browser session started by a password sign-in.
31///
32/// The token is the cookie's value and the lifetime its `Max-Age`; neither is
33/// stored, since the row keeps only the secret's digest and the sign-in time.
34pub struct BrowserSession {
35	/// The opaque cookie value naming the session.
36	pub token: String,
37
38	/// How long the session lasts from its sign-in.
39	pub lifetime: Duration,
40}
41
42/// Starts a browser session for a user who just signed in with a password.
43///
44/// `verified` is the password hash the sign-in checked, `None` when it could
45/// not be read. The session is minted only while that hash is still the
46/// account's, read under the password lock, so a new password either lands
47/// first and refuses the session or lands after and ends it. Disabling a
48/// password ends no session, but a deactivated account's sessions are refused
49/// at use. The session named by `replaces` ends first, whoever it belongs to,
50/// so each sign-in mints a fresh session id and never adopts one the browser
51/// already carried. Returns `None` while browser sessions are turned off,
52/// without a verified hash, or once the stored hash differs or cannot be read.
53#[implement(super::Service)]
54#[tracing::instrument(level = "debug", skip(self, verified, replaces))]
55pub async fn create_browser_session(
56	&self,
57	user_id: &UserId,
58	verified: Option<&str>,
59	replaces: Option<&str>,
60) -> Option<BrowserSession> {
61	if let Some((owner, secret)) = replaces.and_then(parse_token) {
62		self.remove_browser_session(owner, secret);
63	}
64
65	let verified = verified?;
66	let _password_guard = self.changing_password.lock(user_id).await;
67
68	self.db
69		.userid_password
70		.get(user_id)
71		.map_ok(|current| &*current == verified.as_bytes())
72		.await
73		.inspect_err(
74			|error| warn!(%user_id, %error, "Unreadable password, starting no browser session"),
75		)
76		.ok()?
77		.and_then(|| self.mint_browser_session(user_id))
78}
79
80/// Stores a new browser session for a user and returns its cookie.
81///
82/// It checks no password, so a sign-in goes through `create_browser_session`.
83/// Returns `None` while browser sessions are turned off.
84#[implement(super::Service)]
85pub(super) fn mint_browser_session(&self, user_id: &UserId) -> Option<BrowserSession> {
86	let lifetime = self.browser_session_ttl()?;
87	let secret = random_string(SECRET_LENGTH);
88	let digest = sha256(&secret);
89
90	self.db
91		.useridbrowsersession_createdat
92		.put((user_id, digest.as_slice()), millis_since_unix_epoch());
93
94	Some(BrowserSession {
95		token: format!("{secret}.{user_id}"),
96		lifetime,
97	})
98}
99
100/// Returns the user a browser session belongs to while the session lasts.
101///
102/// A garbled, unknown, ended or expired token answers `None`, as does any
103/// token while browser sessions are turned off. A read failure other than a
104/// missing row is logged and answers `None` as well.
105#[implement(super::Service)]
106#[tracing::instrument(level = "debug", skip_all)]
107pub async fn find_browser_session<'a>(&self, token: &'a str) -> Option<&'a UserId> {
108	let lifetime = self.browser_session_ttl()?;
109	let Some((user_id, secret)) = parse_token(token) else {
110		debug!("Malformed browser session token, ignoring");
111		return None;
112	};
113
114	let digest = sha256(secret);
115
116	let created_at: u64 = self
117		.db
118		.useridbrowsersession_createdat
119		.qry(&(user_id, digest.as_slice()))
120		.await
121		.deserialized()
122		.present()
123		.inspect_err(|error| warn!(%user_id, %error, "Unreadable browser session, ignoring"))
124		.ok()
125		.flatten()?;
126
127	let age = now().saturating_sub(Duration::from_millis(created_at));
128
129	age.lt(&lifetime).then_some(user_id)
130}
131
132/// Ends a browser session when it belongs to `user_id`.
133///
134/// A token naming another user is left alone, so a request authenticated as
135/// one account never signs the browser out of a different one.
136#[implement(super::Service)]
137pub fn end_browser_session(&self, token: &str, user_id: &UserId) {
138	if let Some((owner, secret)) = parse_token(token).filter(|(owner, _)| *owner == user_id) {
139		self.remove_browser_session(owner, secret);
140	}
141}
142
143/// Ends every browser session of a user.
144///
145/// Password writes, deactivation and signing out of all devices call it. A failed scan is
146/// returned rather than skipped, so no caller reports the sessions ended while
147/// one survives. The scan stops at the user ID's separator, so a longer user
148/// ID sharing its bytes keeps its sessions.
149#[implement(super::Service)]
150#[tracing::instrument(level = "debug", skip(self))]
151pub async fn end_browser_sessions(&self, user_id: &UserId) -> Result {
152	let sessions = &self.db.useridbrowsersession_createdat;
153
154	sessions
155		.keys_prefix_raw(&(user_id, Interfix))
156		.ready_try_for_each(|key| {
157			sessions.remove(key);
158
159			Ok(())
160		})
161		.await
162}
163
164fn parse_token(token: &str) -> Option<(&UserId, &str)> {
165	let (secret, user_id) = token
166		.split_once('.')
167		.filter(|(secret, _)| secret.len().eq(&SECRET_LENGTH))?;
168
169	<&UserId>::try_from(user_id)
170		.ok()
171		.map(|user_id| (user_id, secret))
172}
173
174#[implement(super::Service)]
175fn remove_browser_session(&self, user_id: &UserId, secret: &str) {
176	let digest = sha256(secret);
177
178	self.db
179		.useridbrowsersession_createdat
180		.del((user_id, digest.as_slice()));
181}
182
183#[implement(super::Service)]
184fn browser_session_ttl(&self) -> Option<Duration> {
185	let ttl = self
186		.services
187		.config
188		.authentication
189		.oidc
190		.browser_session_ttl
191		.min(TTL_MAX);
192
193	ttl.gt(&0).then_some(Duration::from_secs(ttl))
194}