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, 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 = nanos(self.clock.now());
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 now = nanos(self.clock.now());
257 let Some(row) = live(&mut tx, id, now)? else {
258 commit(tx)?;
259 self.count_session(Action::AuthFailed, 401, None);
260 return Err(SessionError::NoSession);
261 };
262 if let Proof::Csrf(token) = proof
263 && !token.is_some_and(|token| same(&hash(token), &row.csrf_hash))
264 {
265 drop(tx);
266 self.count_session(Action::AuthFailed, 403, Some((row.user, row.tenant)));
267 return Err(SessionError::BadCsrf);
268 }
269 let seen = SessionRow {
270 last_seen_at: now,
271 idle_expires_at: after(now, row.idle_seconds),
272 ..row
273 };
274 let session = info(&seen)?;
275 tx.touch_session(&seen.id_hash, seen.last_seen_at, seen.idle_expires_at)?;
276 commit(tx)?;
277 Ok(session)
278 }
279
280 pub fn end_session(&self, id: &str) -> Result<SessionInfo, SessionError> {
285 let mut tx = self.registry.immediate()?;
286 let Some(row) = live(&mut tx, id, nanos(self.clock.now()))? else {
287 commit(tx)?;
288 return Err(SessionError::NoSession);
289 };
290 let session = info(&row)?;
291 tx.delete_session(&row.id_hash)?;
292 let done = Entry {
293 actor: Actor::User(row.user),
294 action: Action::SessionEnd,
295 target: Some(target(row.user, row.tenant)),
296 version: None,
297 status: 204,
298 };
299 self.record(&mut tx, &done)?;
300 commit(tx)?;
302 if let Some(t) = row.tenant {
303 self.copy_to_tenant(t, &done)?;
304 }
305 Ok(session)
306 }
307
308 pub fn step_up_session(&self, id: &str, amr: &[&str]) -> Result<Started, SessionError> {
314 let amr = amr_text(amr).ok_or(SessionError::BadAmr)?;
315 let mut tx = self.registry.immediate()?;
316 let now = nanos(self.clock.now());
317 let Some(row) = live(&mut tx, id, now)? else {
318 commit(tx)?;
319 return Err(SessionError::NoSession);
320 };
321 let id = new_secret();
322 let csrf = csrf_token(&id);
323 tx.delete_session(&row.id_hash)?;
324 let row = SessionRow {
325 id_hash: hash(&id).to_vec(),
326 last_seen_at: now,
327 idle_expires_at: after(now, row.idle_seconds),
328 amr,
329 csrf_hash: hash(&csrf).to_vec(),
330 ..row
331 };
332 tx.insert_session(&row)?;
333 let session = info(&row)?;
334 commit(tx)?;
335 Ok(Started { id, csrf, session })
336 }
337
338 pub(crate) fn count_session(
344 &self,
345 action: Action,
346 status: u16,
347 known: Option<(UserId, Option<TenantId>)>,
348 ) {
349 let entry = |actor| Entry {
350 actor,
351 action,
352 target: None,
353 version: None,
354 status,
355 };
356 if let Some((user, Some(tenant))) = known
357 && self
358 .store(tenant)
359 .is_ok_and(|store| store.count(&entry(Actor::User(user))).is_ok())
360 {
361 return;
362 }
363 let actor = known.map_or(Actor::Unparsed, |(user, _)| Actor::User(user));
364 let _ = self.count_admin(&entry(actor));
365 }
366}
367
368fn live(tx: &mut RTx<'_>, id: &str, now: i64) -> Result<Option<SessionRow>, TenantError> {
371 if !well_formed(id) {
372 return Ok(None);
373 }
374 let Some(row) = tx.session(&hash(id))? else {
375 return Ok(None);
376 };
377 if row.idle_expires_at <= now || row.expires_at <= now {
378 tx.delete_session(&row.id_hash)?;
379 return Ok(None);
380 }
381 Ok(Some(row))
382}
383
384fn membership_scopes(
387 tx: &mut RTx<'_>,
388 user: UserId,
389 tenant: Option<TenantId>,
390) -> Result<(Scopes, Settings), SessionError> {
391 match tx.user(user)? {
392 None => return Err(SessionError::NoUser),
393 Some(row) if row.deactivated_at.is_some() => return Err(SessionError::Deactivated),
394 Some(_) => {}
395 }
396 let Some(held) = tx.membership(user, tenant)? else {
397 return Err(SessionError::NoMembership);
398 };
399 let roles = Roles::parse(&held.roles).ok_or(TenantError::Io)?;
401 let (cap, settings) = match tenant {
402 None => (None, Settings::default()),
403 Some(t) => {
404 let Some(row) = tx.tenant(t)? else {
405 return Err(SessionError::NoMembership);
406 };
407 let settings = Settings::stored(&tx.settings(t)?).ok_or(TenantError::Io)?;
408 (stored_cap(row.role_cap.as_deref())?, settings)
409 }
410 };
411 let scopes = roles.within(cap).scopes();
412 if scopes.is_empty() {
413 return Err(SessionError::NoMembership);
414 }
415 Ok((scopes, settings))
416}
417
418#[cfg(test)]
419mod tests;