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 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#[derive(Clone, Debug, Default, Deserialize, Serialize)]
61pub struct Session {
62 pub idp_id: Option<String>,
65
66 pub sess_id: Option<SessionId>,
68
69 pub token_type: Option<String>,
71
72 #[debug("{}", redacted_debug!(access_token))]
74 pub access_token: Option<String>,
75
76 #[debug("{}", redacted_debug!(id_token))]
78 pub id_token: Option<String>,
79
80 pub expires_in: Option<u64>,
82
83 pub expires_at: Option<SystemTime>,
85
86 #[debug("{}", redacted_debug!(refresh_token))]
88 pub refresh_token: Option<String>,
89
90 pub refresh_token_expires_in: Option<u64>,
92
93 pub refresh_token_expires_at: Option<SystemTime>,
95
96 pub scope: Option<String>,
98
99 pub redirect_url: Option<Url>,
101
102 #[debug("{}", redacted_debug!(code_verifier))]
104 pub code_verifier: Option<String>,
105
106 #[debug("{}", redacted_debug!(cookie_nonce))]
108 pub cookie_nonce: Option<String>,
109
110 #[debug("{}", redacted_debug!(query_nonce))]
112 pub query_nonce: Option<String>,
113
114 pub authorize_expires_at: Option<SystemTime>,
116
117 pub user_id: Option<OwnedUserId>,
119
120 pub user_info: Option<UserInfo>,
122}
123
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub enum Deleted {
130 Complete,
132
133 ProviderUnresolved,
135}
136
137#[derive(Clone, Copy, Debug, Default)]
142pub struct Deletions {
143 pub complete: usize,
145
146 pub unresolved: usize,
148
149 pub absent: usize,
151
152 pub unreadable: usize,
154}
155
156pub type SessionId = String;
158
159pub const CODE_VERIFIER_LENGTH: usize = 64;
162
163pub 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#[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 let deleted = if unique_id.is_none() && session.user_info.is_some() {
227 Deleted::ProviderUnresolved
228 } else {
229 Deleted::Complete
230 };
231
232 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 .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#[implement(Deletions)]
317#[inline]
318#[must_use]
319pub fn deleted(&self) -> usize { self.complete.saturating_add(self.unresolved) }
320
321#[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#[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#[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#[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#[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#[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#[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#[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}