1use time::OffsetDateTime;
15use time::format_description::well_known::Rfc3339;
16
17use super::role_cap::stored_cap;
18use super::{RTx, TenantError, Tenants, commit};
19use crate::access::Scopes;
20use crate::audit::{Action, Actor, Entry};
21use crate::backend::SessionRow;
22use crate::clock::from_nanos;
23use crate::ids::{TenantId, UserId};
24use crate::roles::Roles;
25use crate::session::{amr_text, csrf_token, hash, new_secret, same, well_formed};
26use crate::settings::{Name, Settings, Value};
27
28const NANOS_PER_SECOND: i64 = 1_000_000_000;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct SessionInfo {
33 pub user: UserId,
34 pub tenant: Option<TenantId>,
36 pub scopes: Scopes,
38 pub amr: String,
40 pub created_at: OffsetDateTime,
41 pub last_seen_at: OffsetDateTime,
42 pub idle_expires_at: OffsetDateTime,
45 pub expires_at: OffsetDateTime,
47}
48
49impl SessionInfo {
50 #[must_use]
55 pub fn to_json(&self, csrf: &str) -> Option<serde_json::Value> {
56 let time = |at: OffsetDateTime| at.format(&Rfc3339).ok();
57 Some(serde_json::json!({
58 "user": self.user.to_string(),
59 "tenant": self.tenant.map(|t| t.to_string()),
60 "scopes": self.scopes.names(),
61 "amr": self.amr.split(' ').collect::<Vec<_>>(),
62 "created_at": time(self.created_at)?,
63 "last_seen_at": time(self.last_seen_at)?,
64 "idle_expires_at": time(self.idle_expires_at)?,
65 "expires_at": time(self.expires_at)?,
66 "csrf_token": csrf,
67 }))
68 }
69}
70
71#[derive(Clone, PartialEq, Eq)]
76pub struct Started {
77 pub id: String,
79 pub csrf: String,
81 pub session: SessionInfo,
82}
83
84impl std::fmt::Debug for Started {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 f.debug_struct("Started")
87 .field("session", &self.session)
88 .finish_non_exhaustive()
89 }
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum Proof<'a> {
95 Handout,
97 Csrf(Option<&'a str>),
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum SessionError {
104 NoUser,
106 Deactivated,
108 NoMembership,
111 BadAmr,
113 NoSession,
115 BadCsrf,
117 Registry(TenantError),
119}
120
121impl From<TenantError> for SessionError {
122 fn from(e: TenantError) -> SessionError {
123 SessionError::Registry(e)
124 }
125}
126
127impl SessionError {
128 fn status(self) -> u16 {
130 match self {
131 SessionError::BadCsrf | SessionError::NoMembership => 403,
132 SessionError::NoSession => 401,
133 SessionError::NoUser => 404,
134 SessionError::Deactivated => 409,
135 SessionError::BadAmr => 422,
136 SessionError::Registry(_) => 500,
137 }
138 }
139}
140
141fn after(at: i64, seconds: i64) -> i64 {
143 at.saturating_add(seconds.saturating_mul(NANOS_PER_SECOND))
144}
145
146fn info(row: &SessionRow) -> Result<SessionInfo, TenantError> {
149 let time = |at| from_nanos(at).ok_or(TenantError::Io);
150 Ok(SessionInfo {
151 user: row.user,
152 tenant: row.tenant,
153 scopes: Scopes::parse(&row.scopes).ok_or(TenantError::Io)?,
154 amr: row.amr.clone(),
155 created_at: time(row.created_at)?,
156 last_seen_at: time(row.last_seen_at)?,
157 idle_expires_at: time(row.idle_expires_at.min(row.expires_at))?,
158 expires_at: time(row.expires_at)?,
159 })
160}
161
162fn target(user: UserId, tenant: Option<TenantId>) -> String {
164 let place = tenant.map_or_else(|| "operator".to_owned(), |t| t.to_string());
165 format!("{user}/{place}")
166}
167
168fn limit(settings: &Settings, name: Name) -> i64 {
170 match settings.get(name) {
171 Value::Seconds(seconds) => i64::from(seconds),
172 Value::Flag(_) => 0,
174 }
175}
176
177impl Tenants {
178 pub fn start_session(
191 &self,
192 user: UserId,
193 tenant: Option<TenantId>,
194 amr: &[&str],
195 ) -> Result<Started, SessionError> {
196 let entry = |status| Entry {
197 actor: Actor::User(user),
198 action: Action::SessionStart,
199 target: Some(target(user, tenant)),
200 version: None,
201 status,
202 };
203 let mut tx = self.registry.immediate()?;
204 let found = match amr_text(amr) {
205 None => Err(SessionError::BadAmr),
206 Some(amr) => membership_scopes(&mut tx, user, tenant).map(|found| (amr, found)),
207 };
208 let (amr, (scopes, settings)) = match found {
209 Ok(found) => found,
210 Err(SessionError::Registry(error)) => return Err(error.into()),
211 Err(refused) => {
212 self.record(&mut tx, &entry(refused.status()))?;
213 commit(tx)?;
214 return Err(refused);
215 }
216 };
217 let now = self.now_in(tx.as_mut())?;
218 let id = new_secret();
219 let csrf = csrf_token(&id);
220 let idle_seconds = limit(&settings, Name::SessionIdle);
221 let row = SessionRow {
222 id_hash: hash(&id).to_vec(),
223 user,
224 tenant,
225 scopes: scopes.to_string(),
226 created_at: now,
227 last_seen_at: now,
228 idle_expires_at: after(now, idle_seconds),
229 expires_at: after(now, limit(&settings, Name::SessionAbsolute)),
230 idle_seconds,
231 amr,
232 csrf_hash: hash(&csrf).to_vec(),
233 };
234 tx.delete_sessions_ended(now)?;
235 tx.insert_session(&row)?;
236 let session = info(&row)?;
237 let done = entry(201);
238 self.record(&mut tx, &done)?;
239 commit(tx)?;
241 if let Some(t) = tenant {
242 self.copy_to_tenant(t, &done)?;
243 }
244 Ok(Started { id, csrf, session })
245 }
246
247 pub fn session(&self, id: &str, proof: Proof<'_>) -> Result<SessionInfo, SessionError> {
255 let mut tx = self.registry.immediate()?;
256 let Some((row, now)) = self.live(&mut tx, id)? else {
257 commit(tx)?;
258 self.count_session(Action::AuthFailed, 401, None);
259 return Err(SessionError::NoSession);
260 };
261 if let Proof::Csrf(token) = proof
262 && !token.is_some_and(|token| same(&hash(token), &row.csrf_hash))
263 {
264 drop(tx);
265 self.count_session(Action::AuthFailed, 403, Some((row.user, row.tenant)));
266 return Err(SessionError::BadCsrf);
267 }
268 let seen = SessionRow {
269 last_seen_at: now,
270 idle_expires_at: after(now, row.idle_seconds),
271 ..row
272 };
273 let session = info(&seen)?;
274 tx.touch_session(&seen.id_hash, seen.last_seen_at, seen.idle_expires_at)?;
275 commit(tx)?;
276 Ok(session)
277 }
278
279 pub fn end_session(&self, id: &str) -> Result<SessionInfo, SessionError> {
284 let mut tx = self.registry.immediate()?;
285 let Some((row, _)) = self.live(&mut tx, id)? else {
286 commit(tx)?;
287 return Err(SessionError::NoSession);
288 };
289 let session = info(&row)?;
290 tx.delete_session(&row.id_hash)?;
291 let done = Entry {
292 actor: Actor::User(row.user),
293 action: Action::SessionEnd,
294 target: Some(target(row.user, row.tenant)),
295 version: None,
296 status: 204,
297 };
298 self.record(&mut tx, &done)?;
299 commit(tx)?;
301 if let Some(t) = row.tenant {
302 self.copy_to_tenant(t, &done)?;
303 }
304 Ok(session)
305 }
306
307 pub fn step_up_session(&self, id: &str, amr: &[&str]) -> Result<Started, SessionError> {
313 let amr = amr_text(amr).ok_or(SessionError::BadAmr)?;
314 let mut tx = self.registry.immediate()?;
315 let Some((row, now)) = self.live(&mut tx, id)? else {
316 commit(tx)?;
317 return Err(SessionError::NoSession);
318 };
319 let id = new_secret();
320 let csrf = csrf_token(&id);
321 tx.delete_session(&row.id_hash)?;
322 let row = SessionRow {
323 id_hash: hash(&id).to_vec(),
324 last_seen_at: now,
325 idle_expires_at: after(now, row.idle_seconds),
326 amr,
327 csrf_hash: hash(&csrf).to_vec(),
328 ..row
329 };
330 tx.insert_session(&row)?;
331 let session = info(&row)?;
332 commit(tx)?;
333 Ok(Started { id, csrf, session })
334 }
335
336 pub(crate) fn count_session(
342 &self,
343 action: Action,
344 status: u16,
345 known: Option<(UserId, Option<TenantId>)>,
346 ) {
347 let entry = |actor| Entry {
348 actor,
349 action,
350 target: None,
351 version: None,
352 status,
353 };
354 if let Some((user, Some(tenant))) = known
355 && self
356 .store(tenant)
357 .is_ok_and(|store| store.count(&entry(Actor::User(user))).is_ok())
358 {
359 return;
360 }
361 let actor = known.map_or(Actor::Unparsed, |(user, _)| Actor::User(user));
362 let _ = self.count_admin(&entry(actor));
363 }
364}
365
366impl Tenants {
367 fn live(&self, tx: &mut RTx<'_>, id: &str) -> Result<Option<(SessionRow, i64)>, TenantError> {
373 if !well_formed(id) {
374 return Ok(None);
375 }
376 let Some(row) = tx.session(&hash(id))? else {
377 return Ok(None);
378 };
379 let now = self.now_in(tx.as_mut())?;
380 if row.idle_expires_at <= now || row.expires_at <= now {
381 tx.delete_session(&row.id_hash)?;
382 return Ok(None);
383 }
384 Ok(Some((row, now)))
385 }
386}
387
388fn membership_scopes(
391 tx: &mut RTx<'_>,
392 user: UserId,
393 tenant: Option<TenantId>,
394) -> Result<(Scopes, Settings), SessionError> {
395 match tx.user(user)? {
396 None => return Err(SessionError::NoUser),
397 Some(row) if row.deactivated_at.is_some() => return Err(SessionError::Deactivated),
398 Some(_) => {}
399 }
400 let Some(held) = tx.membership(user, tenant)? else {
401 return Err(SessionError::NoMembership);
402 };
403 let roles = Roles::parse(&held.roles).ok_or(TenantError::Io)?;
405 let (cap, settings) = match tenant {
406 None => (None, Settings::default()),
407 Some(t) => {
408 let Some(row) = tx.tenant(t)? else {
409 return Err(SessionError::NoMembership);
410 };
411 let settings = Settings::stored(&tx.settings(t)?).ok_or(TenantError::Io)?;
412 (stored_cap(row.role_cap.as_deref())?, settings)
413 }
414 };
415 let scopes = roles.within(cap).scopes();
416 if scopes.is_empty() {
417 return Err(SessionError::NoMembership);
418 }
419 Ok((scopes, settings))
420}
421
422#[cfg(test)]
423mod tests;