1use std::{
5 sync::Arc,
6 time::{Duration, SystemTime},
7};
8
9use jiff::Timestamp;
10use topcoat::{
11 context::Cx,
12 session::{self, TokenHash, TokenStore, cookie::CookieTokenStore},
13};
14
15use super::{
16 DynAuthenticator, PanelUser, SignedIn,
17 hook::{AuthEvent, AuthEventKind},
18 infrastructure_failure,
19 token::{CREDENTIALS, REVOCATION, TokenPurpose},
20};
21use crate::{
22 TenantId,
23 auth::realm::{Realm, current_realm, realms},
24};
25
26mod lifetime;
27pub(super) mod sweep;
28
29pub use self::lifetime::Sessions;
30use self::lifetime::Standing;
31
32pub const SESSION_LIFETIME: Duration = Duration::from_hours(24 * 7);
35
36#[doc(hidden)]
38pub const SESSION_COOKIE_PREFIX: &str = "__Host-tablo_session_";
39
40#[must_use]
46pub fn session_cookie(panel: &str) -> String {
47 format!(
48 "__Host-{}",
49 store_name(&crate::naming::normalize_prefix(panel))
50 )
51}
52
53fn store_name(prefix: &str) -> String {
57 use std::fmt::Write as _;
58
59 let mut name = SESSION_COOKIE_PREFIX
60 .trim_start_matches("__Host-")
61 .to_owned();
62 for byte in prefix.trim_start_matches('/').bytes() {
63 if byte.is_ascii_alphanumeric() || byte == b'-' {
64 name.push(char::from(byte));
65 } else {
66 write!(name, "_{byte:02x}").expect("writing to a String cannot fail");
67 }
68 }
69 name
70}
71
72fn token_store(panel: &Realm) -> CookieTokenStore {
74 CookieTokenStore::new().name(store_name(&panel.prefix))
75}
76
77fn session_panel(cx: &Cx) -> topcoat::Result<&Arc<Realm>> {
79 current_realm(cx).ok_or_else(|| {
80 crate::error::declaration("a panel session changes only under a panel".to_owned())
81 })
82}
83
84#[derive(Debug, Clone, toasty::Model)]
106pub struct AuthSession {
107 #[key]
109 pub token_hash: String,
110 #[index]
112 pub user_id: String,
113 pub panel: String,
116 pub tenant: Option<TenantId>,
118 #[index]
120 pub expires_at: Timestamp,
121 pub created_at: Timestamp,
122 pub impersonating: Option<String>,
125 pub impersonating_until: Option<Timestamp>,
127}
128
129pub(super) async fn start(cx: &Cx) -> topcoat::Result<session::Session> {
131 let token = session::Token::random();
132 let panel = session_panel(cx)?;
133 let sessions = &panel.auth.sessions;
134 token_store(panel)
136 .write(cx, token.clone(), sessions.lasts())
137 .await?;
138 Ok(session::Session {
139 token_hash: token.hash(),
140 expires_at: SystemTime::from(sessions.first_end(Timestamp::now())),
141 })
142}
143
144pub(super) async fn stop(cx: &Cx) -> topcoat::Result<Option<TokenHash>> {
146 let panel = session_panel(cx)?;
147 let hash = token_hash(cx, panel).await?;
148 token_store(panel).delete(cx).await?;
149 Ok(hash)
150}
151
152async fn token_hash(cx: &Cx, panel: &Realm) -> topcoat::Result<Option<TokenHash>> {
155 let token = token_store(panel).read(cx).await?;
156 Ok(token.map(|token| token.hash()))
157}
158
159pub(super) fn token_key(hash: &TokenHash) -> String {
160 use std::fmt::Write as _;
161
162 let mut key = String::with_capacity(64);
163 for byte in hash.iter() {
164 write!(key, "{byte:02x}").expect("writing to a String cannot fail");
165 }
166 key
167}
168
169pub(super) async fn record(
170 cx: &Cx,
171 session: &session::Session,
172 user: &dyn PanelUser,
173 panel: &Realm,
174) -> topcoat::Result<()> {
175 let expires_at = Timestamp::try_from(session.expires_at).map_err(topcoat::Error::from)?;
176 let mut db = crate::db::db(cx)?;
177 let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
178 insert(
179 &mut tx,
180 &session.token_hash,
181 user.user_id(),
182 panel.prefix.clone(),
183 None,
184 expires_at,
185 )
186 .await
187 .map_err(infrastructure_failure)?;
188 let event = AuthEvent::own(AuthEventKind::SignIn, &panel.id, None, user);
190 super::hook::run(cx, &panel.auth_hooks, &event, &mut tx).await?;
191 tx.commit().await.map_err(infrastructure_failure)
192}
193
194pub(super) fn credential_panels(
198 cx: &Cx,
199 user_type: std::any::TypeId,
200 own: &Arc<Realm>,
201) -> Vec<Arc<Realm>> {
202 let realms = realms(cx);
203 if realms.is_empty() {
204 return vec![Arc::clone(own)];
205 }
206 realms
207 .into_iter()
208 .filter(|realm| {
209 realm
210 .auth
211 .authenticator()
212 .is_some_and(|auth| auth.user_type() == user_type)
213 })
214 .collect()
215}
216
217pub(super) async fn end_credentials(
221 ex: &mut dyn toasty::Executor,
222 user_id: &str,
223 panels: &[Arc<Realm>],
224 purposes: &[TokenPurpose],
225) -> topcoat::Result<()> {
226 let prefixes: Vec<String> = panels.iter().map(|panel| panel.prefix.clone()).collect();
227 AuthSession::filter(
228 AuthSession::fields()
229 .user_id()
230 .eq(user_id.to_string())
231 .and(AuthSession::fields().panel().in_list(prefixes)),
232 )
233 .delete()
234 .exec(&mut *ex)
235 .await
236 .map_err(infrastructure_failure)?;
237 let issuing: Vec<String> = panels
238 .iter()
239 .filter(|panel| panel.auth.issues_tokens())
240 .map(|panel| panel.prefix.clone())
241 .collect();
242 if issuing.is_empty() {
243 return Ok(());
245 }
246 super::token::end_all(ex, user_id, Some(issuing), purposes).await
247}
248
249pub(super) async fn replace_sessions(
254 cx: &Cx,
255 ex: &mut dyn toasty::Executor,
256 signed: &SignedIn,
257 user_type: std::any::TypeId,
258 session: &session::Session,
259) -> topcoat::Result<()> {
260 let panels = credential_panels(cx, user_type, &signed.realm);
261 let user_id = signed.user.user_id();
262 end_credentials(&mut *ex, &user_id, &panels, CREDENTIALS).await?;
263 let expires_at = Timestamp::try_from(session.expires_at).map_err(topcoat::Error::from)?;
264 insert(
265 ex,
266 &session.token_hash,
267 user_id,
268 signed.realm.prefix.clone(),
269 signed.tenant,
270 expires_at,
271 )
272 .await
273 .map_err(infrastructure_failure)
274}
275
276#[cfg(feature = "testing")]
283#[doc(hidden)]
284pub async fn mint_session(
285 ex: &mut dyn toasty::Executor,
286 panel: &str,
287 user: &dyn PanelUser,
288) -> topcoat::Result<String> {
289 let token = session::Token::random();
290 let expires_at = Timestamp::try_from(std::time::SystemTime::now() + SESSION_LIFETIME)
291 .map_err(topcoat::Error::from)?;
292 insert(
293 ex,
294 &token.hash(),
295 user.user_id(),
296 crate::naming::normalize_prefix(panel),
297 None,
298 expires_at,
299 )
300 .await?;
301 Ok(token.encode())
302}
303
304async fn insert(
305 ex: &mut dyn toasty::Executor,
306 hash: &TokenHash,
307 user_id: String,
308 panel: String,
309 tenant: Option<TenantId>,
310 expires_at: Timestamp,
311) -> toasty::Result<()> {
312 toasty::create!(AuthSession {
313 token_hash: token_key(hash),
314 user_id,
315 panel,
316 tenant,
317 expires_at,
318 created_at: Timestamp::now(),
319 impersonating: None,
320 impersonating_until: None,
321 })
322 .exec(ex)
323 .await?;
324 Ok(())
325}
326
327pub(super) async fn select_tenant(cx: &Cx, tenant: TenantId) -> topcoat::Result<()> {
328 let Some(hash) = token_hash(cx, session_panel(cx)?).await? else {
329 return Err(topcoat::router::error::forbidden().into());
330 };
331 let mut db = crate::db::db(cx)?;
332 AuthSession::filter(AuthSession::fields().token_hash().eq(token_key(&hash)))
333 .update()
334 .tenant(Some(tenant))
335 .exec(&mut db)
336 .await
337 .map_err(infrastructure_failure)?;
338 Ok(())
339}
340
341pub(super) async fn impersonate(
344 cx: &Cx,
345 ex: &mut dyn toasty::Executor,
346 target: Option<(String, Timestamp)>,
347) -> topcoat::Result<()> {
348 let Some(hash) = token_hash(cx, session_panel(cx)?).await? else {
349 return Err(topcoat::router::error::forbidden().into());
350 };
351 set_impersonation(ex, &token_key(&hash), target).await
352}
353
354pub(super) async fn set_impersonation(
356 ex: &mut dyn toasty::Executor,
357 key: &str,
358 target: Option<(String, Timestamp)>,
359) -> topcoat::Result<()> {
360 let (user, until) = target.unzip();
361 AuthSession::filter(AuthSession::fields().token_hash().eq(key.to_owned()))
362 .update()
363 .impersonating(user)
364 .impersonating_until(until)
365 .tenant(None)
366 .exec(ex)
367 .await
368 .map_err(infrastructure_failure)?;
369 Ok(())
370}
371
372pub(super) async fn delete_session(cx: &Cx, hash: &TokenHash) -> topcoat::Result<()> {
373 delete_session_row(cx, &token_key(hash)).await
374}
375
376pub(super) async fn start_once(
380 cx: &Cx,
381 started: &mut Option<session::Session>,
382) -> topcoat::Result<session::Session> {
383 if let Some(session) = started {
384 return Ok(session.clone());
385 }
386 let session = start(cx).await?;
387 *started = Some(session.clone());
388 Ok(session)
389}
390
391pub(super) async fn fresh_session(cx: &Cx) -> topcoat::Result<session::Session> {
398 let panel = session_panel(cx)?;
399 if let Some(hash) = token_hash(cx, panel)
400 .await
401 .map_err(infrastructure_failure)?
402 {
403 delete_session(cx, &hash).await?;
404 }
405 start(cx).await.map_err(infrastructure_failure)
406}
407
408async fn delete_session_row(cx: &Cx, key: &str) -> topcoat::Result<()> {
409 let mut db = crate::db::db(cx)?;
410 AuthSession::filter(AuthSession::fields().token_hash().eq(key.to_string()))
411 .delete()
412 .exec(&mut db)
413 .await
414 .map_err(infrastructure_failure)?;
415 Ok(())
416}
417
418pub async fn revoke_sessions_for_user(cx: &Cx, user_id: &str) -> topcoat::Result<()> {
427 let mut db = crate::db::db(cx)?;
428 if let Some(panel) = current_realm(cx) {
429 let panels = match panel.auth.authenticator() {
430 Some(auth) => credential_panels(cx, auth.user_type(), panel),
431 None => vec![Arc::clone(panel)],
432 };
433 end_credentials(&mut db, user_id, &panels, REVOCATION).await?;
434 wake_bells(
435 cx,
436 user_id,
437 panels.iter().map(|panel| panel.prefix.as_str()),
438 );
439 return Ok(());
440 }
441 AuthSession::filter(AuthSession::fields().user_id().eq(user_id.to_string()))
442 .delete()
443 .exec(&mut db)
444 .await
445 .map_err(infrastructure_failure)?;
446 let realms = realms(cx);
447 if realms.iter().any(|realm| realm.auth.issues_tokens()) {
448 super::token::end_all(&mut db, user_id, None, REVOCATION).await?;
449 }
450 wake_bells(
451 cx,
452 user_id,
453 realms.iter().map(|realm| realm.prefix.as_str()),
454 );
455 Ok(())
456}
457
458fn wake_bells<'a>(cx: &Cx, user_id: &str, panels: impl Iterator<Item = &'a str>) {
460 let bus = crate::bus::bus(cx);
461 for panel in panels {
462 bus.wake(panel, user_id);
463 }
464}
465
466pub(super) async fn session_row(
473 cx: &Cx,
474 panel: &Realm,
475 activity: Activity,
476) -> topcoat::Result<Option<AuthSession>> {
477 let Some(hash) = token_hash(cx, panel).await? else {
478 return Ok(None);
479 };
480 let key = token_key(&hash);
481 let mut db = crate::db::db(cx)?;
482 let row = AuthSession::filter(AuthSession::fields().token_hash().eq(key))
483 .first()
484 .exec(&mut db)
485 .await
486 .map_err(infrastructure_failure)?;
487 let Some(mut row) = row else {
488 return Ok(None);
489 };
490 let end = match panel.auth.sessions.check(&row, Timestamp::now()) {
491 Standing::Ended => {
492 delete_session_row(cx, &row.token_hash).await?;
493 return Ok(None);
494 }
495 Standing::Live(end) => end,
496 };
497 if row.panel != panel.prefix {
498 return Ok(None);
499 }
500 if let (Activity::Counts, Some(end)) = (activity, end) {
501 AuthSession::filter(
502 AuthSession::fields()
503 .token_hash()
504 .eq(row.token_hash.clone()),
505 )
506 .update()
507 .expires_at(end)
508 .exec(&mut db)
509 .await
510 .map_err(infrastructure_failure)?;
511 row.expires_at = end;
512 }
513 Ok(Some(row))
514}
515
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518pub(super) enum Activity {
519 Counts,
521 Ignored,
523}
524
525pub(super) async fn session_user(
532 cx: &Cx,
533 row: AuthSession,
534 panel: &Arc<Realm>,
535 authenticator: &dyn DynAuthenticator,
536) -> topcoat::Result<Option<SignedIn>> {
537 match authenticator
538 .find_by_id(cx, &row.user_id)
539 .await
540 .map_err(infrastructure_failure)?
541 {
542 Some(user) if row.impersonating.is_some() => {
543 super::impersonation::resolve(cx, row, user, panel, authenticator)
544 .await
545 .map(Some)
546 }
547 Some(user) => Ok(Some(SignedIn {
548 user,
549 realm: Arc::clone(panel),
550 tenant: row.tenant,
551 impersonator: None,
552 })),
553 None => {
554 if panel.auth.external().is_none() {
555 delete_session_row(cx, &row.token_hash).await?;
556 }
557 Ok(None)
558 }
559 }
560}
561
562pub(super) async fn resolve(
564 cx: &Cx,
565 panel: &Arc<Realm>,
566 authenticator: &dyn DynAuthenticator,
567 activity: Activity,
568) -> topcoat::Result<Option<SignedIn>> {
569 match session_row(cx, panel, activity).await? {
570 Some(row) => session_user(cx, row, panel, authenticator).await,
571 None => Ok(None),
572 }
573}