Skip to main content

tuwunel_service/oauth/
sessions.rs

1mod adopt;
2pub mod association;
3
4use std::{
5	collections::BTreeSet,
6	fmt::Display,
7	iter::once,
8	sync::{Arc, Mutex},
9	time::SystemTime,
10};
11
12use derive_more::Debug;
13use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
14use ruma::{OwnedUserId, UserId};
15use serde::{Deserialize, Serialize};
16use tuwunel_core::{
17	Err, Error, Result, at, debug_warn, err, implement,
18	itertools::Itertools,
19	redacted_debug,
20	result::NotFound,
21	utils::{
22		MutexMap, OptionExt,
23		stream::{IterStream, ReadyExt, TryExpect, TryReadyExt},
24	},
25	warn,
26};
27use tuwunel_database::{Cbor, Database, Deserialized, Ignore, Map};
28use url::Url;
29
30pub use self::adopt::Counts;
31use super::{Provider, Providers, UserInfo, unique_id as session_unique_id};
32use crate::SelfServices;
33
34pub struct Sessions {
35	services: SelfServices,
36	association_pending: Mutex<association::Pending>,
37
38	/// Serializes probes and writes for each unique identity.
39	///
40	/// Transaction batches cannot conditionally claim an index key. Each
41	/// identity therefore has an independent critical section.
42	write_locks: MutexMap<String, ()>,
43
44	providers: Arc<Providers>,
45	db: Data,
46}
47
48struct Data {
49	oauthid_session: Arc<Map>,
50	oauthuniqid_oauthid: Arc<Map>,
51	userid_oauthid: Arc<Map>,
52	database: Arc<Database>,
53}
54
55/// Persistent state for one upstream OAuth authorization.
56///
57/// The record carries provider, redirect, PKCE, nonce, and token data across
58/// the authorization flow. Once linked, it also associates the provider
59/// identity with a Matrix user.
60#[derive(Clone, Debug, Default, Deserialize, Serialize)]
61pub struct Session {
62	/// Identity Provider ID (the `client_id` in the configuration) associated
63	/// with this session.
64	pub idp_id: Option<String>,
65
66	/// Session ID used as the index key for this session itself.
67	pub sess_id: Option<SessionId>,
68
69	/// Token type (bearer, mac, etc).
70	pub token_type: Option<String>,
71
72	/// Access token to the provider.
73	#[debug("{}", redacted_debug!(access_token))]
74	pub access_token: Option<String>,
75
76	/// OIDC ID token returned by the provider.
77	#[debug("{}", redacted_debug!(id_token))]
78	pub id_token: Option<String>,
79
80	/// Duration in seconds the access_token is valid for.
81	pub expires_in: Option<u64>,
82
83	/// Point in time that the access_token expires.
84	pub expires_at: Option<SystemTime>,
85
86	/// Token used to refresh the access_token.
87	#[debug("{}", redacted_debug!(refresh_token))]
88	pub refresh_token: Option<String>,
89
90	/// Duration in seconds the refresh_token is valid for
91	pub refresh_token_expires_in: Option<u64>,
92
93	/// Point in time that the refresh_token expires.
94	pub refresh_token_expires_at: Option<SystemTime>,
95
96	/// Access scope actually granted (if supported).
97	pub scope: Option<String>,
98
99	/// Redirect URL
100	pub redirect_url: Option<Url>,
101
102	/// Challenge preimage
103	#[debug("{}", redacted_debug!(code_verifier))]
104	pub code_verifier: Option<String>,
105
106	/// Random string passed exclusively in the grant session cookie.
107	#[debug("{}", redacted_debug!(cookie_nonce))]
108	pub cookie_nonce: Option<String>,
109
110	/// Random single-use string passed in the provider redirect.
111	#[debug("{}", redacted_debug!(query_nonce))]
112	pub query_nonce: Option<String>,
113
114	/// Point in time the authorization grant session expires.
115	pub authorize_expires_at: Option<SystemTime>,
116
117	/// Associated User Id registration.
118	pub user_id: Option<OwnedUserId>,
119
120	/// Last userinfo response persisted here.
121	pub user_info: Option<UserInfo>,
122}
123
124/// What deleting one session left of its indexes.
125///
126/// The identity binding is keyed by a hash only the session's provider can
127/// derive, so without that provider the binding cannot be found.
128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub enum Deleted {
130	/// Every index naming the session went with it.
131	Complete,
132
133	/// No configured provider derived the identity key, so a binding may remain.
134	ProviderUnresolved,
135}
136
137/// Outcome counts of one user-wide session delete.
138///
139/// Each session the user's index lists is counted under one outcome, so a
140/// session that fails is counted rather than stopping the rest.
141#[derive(Clone, Copy, Debug, Default)]
142pub struct Deletions {
143	/// Sessions removed with every index naming them.
144	pub complete: usize,
145
146	/// Sessions removed while an identity binding naming them may remain.
147	pub unresolved: usize,
148
149	/// Sessions the user's index lists without a stored record.
150	pub absent: usize,
151
152	/// Sessions kept because they or their indexes could not be read.
153	pub unreadable: usize,
154}
155
156/// Session Identifier type.
157pub type SessionId = String;
158
159/// Number of characters generated for our code_verifier. The code_verifier is a
160/// random string which must be between 43 and 128 characters.
161pub const CODE_VERIFIER_LENGTH: usize = 64;
162
163/// Number of characters we will generate for the Session ID.
164pub const SESSION_ID_LENGTH: usize = 32;
165
166#[implement(Sessions)]
167pub(super) fn build(args: &crate::Args<'_>, providers: Arc<Providers>) -> Self {
168	Self {
169		services: args.services.clone(),
170		association_pending: Default::default(),
171		write_locks: MutexMap::new(),
172		providers,
173		db: Data {
174			oauthid_session: args.db["oauthid_session"].clone(),
175			oauthuniqid_oauthid: args.db["oauthuniqid_oauthid"].clone(),
176			userid_oauthid: args.db["userid_oauthid"].clone(),
177			database: args.db.clone(),
178		},
179	}
180}
181
182/// Delete database state for the session.
183///
184/// The canonical session and every association index that still refers to it
185/// commit together. The result reports an identity binding that may remain
186/// because no configured provider derives its key. An absent session, or one
187/// whose record or indexes cannot be read, is an error, and nothing is deleted.
188#[implement(Sessions)]
189#[tracing::instrument(level = "debug", skip(self))]
190pub async fn delete(&self, sess_id: &str) -> Result<Deleted> {
191	let (session, unique_id, _write_guard) = loop {
192		let snapshot = self.get(sess_id).await?;
193
194		let provider = async {
195			let idp_id = snapshot.idp_id.as_deref()?;
196
197			self.providers.get(idp_id).map(Result::ok).await
198		}
199		.await;
200
201		let unique_id = provider
202			.as_ref()
203			.and_then(|provider| session_unique_id((provider, &snapshot)).ok());
204
205		let write_guard = match unique_id.as_deref() {
206			| Some(unique_id) => Some(self.write_locks.lock(unique_id).await),
207			| None => None,
208		};
209
210		let session = self.get(sess_id).await?;
211
212		if session.idp_id.as_deref() != snapshot.idp_id.as_deref() {
213			continue;
214		}
215
216		let current_unique_id = provider
217			.as_ref()
218			.and_then(|provider| session_unique_id((provider, &session)).ok());
219
220		if current_unique_id == unique_id {
221			break (session, unique_id, write_guard);
222		}
223	};
224
225	// Only a session holding user_info was ever bound to an identity.
226	let deleted = if unique_id.is_none() && session.user_info.is_some() {
227		Deleted::ProviderUnresolved
228	} else {
229		Deleted::Complete
230	};
231
232	// Preserve a unique identity association updated to a newer session.
233	let unique_id = unique_id
234		.as_deref()
235		.try_map_async(|unique_id| {
236			self.get_sess_id_by_unique_id(unique_id)
237				.map(NotFound::present)
238				.map_err(unreadable(&self.db.oauthuniqid_oauthid, unique_id))
239				.map_ok(move |assoc_id| {
240					assoc_id
241						.is_some_and(|assoc_id| assoc_id == sess_id)
242						.then_some(unique_id)
243				})
244		})
245		.map_ok(Option::flatten)
246		.await?;
247
248	let user_sessions = session
249		.user_id
250		.as_deref()
251		.try_map_async(|user_id| {
252			self.get_sess_id_by_user(user_id)
253				// A user with no index row has no other session to keep.
254				.ready_filter(|listed| !listed.is_missing())
255				.ready_try_filter(|listed| listed != sess_id)
256				.map_err(unreadable(&self.db.userid_oauthid, user_id))
257				.try_collect()
258				.map_ok(move |sess_ids: Vec<_>| (user_id, sess_ids))
259		})
260		.await?;
261
262	let mut txn = self.db.database.txn();
263
264	if let Some((user_id, sess_ids)) = user_sessions {
265		if !sess_ids.is_empty() {
266			txn.raw_put(&self.db.userid_oauthid, user_id, sess_ids);
267		} else {
268			txn.del_raw(&self.db.userid_oauthid, user_id);
269		}
270	}
271
272	if let Some(unique_id) = unique_id {
273		txn.del_raw(&self.db.oauthuniqid_oauthid, unique_id);
274	}
275
276	txn.del_raw(&self.db.oauthid_session, sess_id);
277	txn.execute();
278
279	Ok(deleted)
280}
281
282fn unreadable<K: Display>(map: &Map, key: K) -> impl Fn(Error) -> Error {
283	move |e| err!(Database("{} {key} is unreadable: {e}", map.name()))
284}
285
286#[implement(Deletions)]
287pub(super) fn tally(self, result: Result<Deleted>, sess_id: &str) -> Self {
288	match result {
289		| Ok(Deleted::Complete) => Self {
290			complete: self.complete.saturating_add(1),
291			..self
292		},
293		| Ok(Deleted::ProviderUnresolved) => Self {
294			unresolved: self.unresolved.saturating_add(1),
295			..self
296		},
297		| Err(e) if e.is_missing() => Self {
298			absent: self.absent.saturating_add(1),
299			..self
300		},
301		| Err(e) => {
302			warn!(%sess_id, error = %e, "an OAuth session could not be read for deletion");
303
304			Self {
305				unreadable: self.unreadable.saturating_add(1),
306				..self
307			}
308		},
309	}
310}
311
312/// Counts the sessions removed, whether or not a binding naming them remains.
313///
314/// That is every complete delete plus every delete no configured provider
315/// could derive the binding for.
316#[implement(Deletions)]
317#[inline]
318#[must_use]
319pub fn deleted(&self) -> usize { self.complete.saturating_add(self.unresolved) }
320
321/// Create or overwrite database state for the session.
322///
323/// The canonical session and its available identity and user indexes commit
324/// together.
325#[implement(Sessions)]
326#[tracing::instrument(level = "info", skip(self))]
327pub async fn put(&self, session: &Session) {
328	let unique_id = async {
329		let idp_id = session.idp_id.as_ref()?;
330		let provider = self.providers.get(idp_id).map(Result::ok).await?;
331
332		session_unique_id((&provider, session)).ok()
333	}
334	.await;
335
336	let _write_guard = match unique_id.as_deref() {
337		| Some(unique_id) => Some(self.write_locks.lock(unique_id).await),
338		| None => None,
339	};
340
341	self.put_locked(session, unique_id.as_deref())
342		.await;
343}
344
345/// Build and commit a session while exclusively claiming its identity key.
346///
347/// The callback's identity lookup and user selection remain ordered with bulk
348/// adoption until the canonical session and indexes have committed.
349#[implement(Sessions)]
350#[tracing::instrument(level = "debug", skip_all)]
351pub async fn commit_identity_session<T, F, Fut>(
352	&self,
353	unique_id: &str,
354	build: F,
355) -> Result<(Session, T, Option<SessionId>)>
356where
357	T: Send,
358	F: FnOnce(Option<OwnedUserId>) -> Fut + Send,
359	Fut: Future<Output = Result<(Session, T)>> + Send,
360{
361	let write_guard = self.write_locks.lock(unique_id).await;
362	let existing = self
363		.get_by_unique_id(unique_id)
364		.await
365		.optional()?;
366
367	let old_sess_id = existing
368		.as_ref()
369		.and_then(|session| session.sess_id.clone());
370
371	let old_user_id = existing.and_then(|session| session.user_id);
372	let (session, value) = build(old_user_id).await?;
373
374	self.put_locked(&session, Some(unique_id)).await;
375	drop(write_guard);
376
377	Ok((session, value, old_sess_id))
378}
379
380#[implement(Sessions)]
381async fn put_locked(&self, session: &Session, unique_id: Option<&str>) {
382	let sess_id = session
383		.sess_id
384		.as_deref()
385		.expect("Missing session.sess_id required for sessions.put()");
386
387	let user_sessions = async {
388		let user_id = session.user_id.as_deref()?;
389		let sess_ids: Vec<_> = self
390			.get_sess_id_by_user(user_id)
391			.ready_filter_map(Result::ok)
392			.chain(once(sess_id.to_owned()).stream())
393			.collect::<Vec<_>>()
394			.map(IntoIterator::into_iter)
395			.map(Itertools::sorted_unstable)
396			.map(Itertools::dedup)
397			.map(Iterator::collect)
398			.await;
399
400		Some((user_id, sess_ids))
401	}
402	.await;
403
404	let mut txn = self.db.database.txn();
405
406	txn.raw_put(&self.db.oauthid_session, sess_id, Cbor(session));
407
408	if let Some(unique_id) = unique_id {
409		txn.insert_raw(&self.db.oauthuniqid_oauthid, unique_id, sess_id);
410	}
411
412	if let Some((user_id, sess_ids)) = user_sessions {
413		txn.raw_put(&self.db.userid_oauthid, user_id, sess_ids);
414	}
415
416	txn.execute();
417}
418
419/// Fetch database state for a session from its associated `(iss,sub)`, in case
420/// `sess_id` is not known.
421#[implement(Sessions)]
422#[tracing::instrument(level = "debug", skip(self), ret(level = "debug"))]
423pub async fn get_by_unique_id(&self, unique_id: &str) -> Result<Session> {
424	self.get_sess_id_by_unique_id(unique_id)
425		.and_then(async |sess_id| self.get(&sess_id).await)
426		.await
427}
428
429/// Choose the linked, configured provider to bind a user's re-authentication.
430///
431/// Each linked provider id resolves against the configuration, and
432/// `Providers::find_preferred_config` picks among those that remain configured.
433/// An unreadable session is skipped.
434#[implement(Sessions)]
435#[tracing::instrument(level = "debug", skip(self), ret(level = "debug"))]
436pub async fn linked_provider(&self, user_id: &UserId) -> Option<&str> {
437	let linked: BTreeSet<_> = self
438		.get_by_user(user_id)
439		.ready_filter_map(|session| {
440			session
441				.optional()
442				.inspect_err(
443					|error| debug_warn!(%user_id, %error, "Skipping unreadable session."),
444				)
445				.ok()
446				.flatten()?
447				.idp_id
448		})
449		.ready_filter_map(|idp_id| {
450			self.providers
451				.find_config(&idp_id)
452				.map(Provider::id)
453				.ok()
454		})
455		.collect()
456		.await;
457
458	self.providers
459		.find_preferred_config(|provider| linked.contains(provider.id()))
460		.map(Provider::id)
461}
462
463/// Fetch database state for one or more sessions from its associated `user_id`,
464/// in case `sess_id` is not known.
465#[implement(Sessions)]
466#[tracing::instrument(level = "debug", skip(self))]
467pub fn get_by_user(&self, user_id: &UserId) -> impl Stream<Item = Result<Session>> + Send {
468	self.get_sess_id_by_user(user_id)
469		.and_then(async |sess_id| self.get(&sess_id).await)
470}
471
472/// Fetch database state for a session from its `sess_id`.
473#[implement(Sessions)]
474#[tracing::instrument(level = "debug", skip(self), ret(level = "debug"))]
475pub async fn get(&self, sess_id: &str) -> Result<Session> {
476	self.db
477		.oauthid_session
478		.get(sess_id)
479		.await
480		.deserialized::<Cbor<_>>()
481		.map(at!(0))
482}
483
484/// Resolve the `sess_id` associations with a `user_id`.
485#[implement(Sessions)]
486#[tracing::instrument(level = "debug", skip(self))]
487pub fn get_sess_id_by_user(&self, user_id: &UserId) -> impl Stream<Item = Result<String>> + Send {
488	self.db
489		.userid_oauthid
490		.get(user_id)
491		.map(Deserialized::deserialized)
492		.map_ok(Vec::into_iter)
493		.map_ok(IterStream::try_stream)
494		.try_flatten_stream()
495}
496
497/// Resolve the `sess_id` from an associated provider issuer and subject hash.
498#[implement(Sessions)]
499#[tracing::instrument(level = "debug", skip(self), ret(level = "debug"))]
500pub async fn get_sess_id_by_unique_id(&self, unique_id: &str) -> Result<String> {
501	self.db
502		.oauthuniqid_oauthid
503		.get(unique_id)
504		.await
505		.deserialized()
506}
507
508#[implement(Sessions)]
509pub fn users(&self) -> impl Stream<Item = OwnedUserId> + Send {
510	self.db
511		.userid_oauthid
512		.keys()
513		.expect_ok()
514		.map(UserId::to_owned)
515}
516
517#[implement(Sessions)]
518pub fn stream(&self) -> impl Stream<Item = Session> + Send {
519	self.db
520		.oauthid_session
521		.stream()
522		.expect_ok()
523		.map(|(_, session): (Ignore, Cbor<_>)| session.0)
524}
525
526#[implement(Sessions)]
527pub async fn provider(&self, session: &Session) -> Result<Provider> {
528	let Some(idp_id) = session.idp_id.as_deref() else {
529		return Err!(Request(NotFound("No provider for this session")));
530	};
531
532	self.providers.get(idp_id).await
533}