use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use super::role_cap::stored_cap;
use super::{RTx, TenantError, Tenants, commit};
use crate::access::Scopes;
use crate::audit::{Action, Actor, Entry};
use crate::backend::SessionRow;
use crate::clock::{from_nanos, nanos};
use crate::ids::{TenantId, UserId};
use crate::roles::Roles;
use crate::session::{amr_text, csrf_token, hash, new_secret, same, well_formed};
use crate::settings::{Name, Settings, Value};
const NANOS_PER_SECOND: i64 = 1_000_000_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionInfo {
pub user: UserId,
pub tenant: Option<TenantId>,
pub scopes: Scopes,
pub amr: String,
pub created_at: OffsetDateTime,
pub last_seen_at: OffsetDateTime,
pub idle_expires_at: OffsetDateTime,
pub expires_at: OffsetDateTime,
}
impl SessionInfo {
#[must_use]
pub fn to_json(&self, csrf: &str) -> Option<serde_json::Value> {
let time = |at: OffsetDateTime| at.format(&Rfc3339).ok();
Some(serde_json::json!({
"user": self.user.to_string(),
"tenant": self.tenant.map(|t| t.to_string()),
"scopes": self.scopes.names(),
"amr": self.amr.split(' ').collect::<Vec<_>>(),
"created_at": time(self.created_at)?,
"last_seen_at": time(self.last_seen_at)?,
"idle_expires_at": time(self.idle_expires_at)?,
"expires_at": time(self.expires_at)?,
"csrf_token": csrf,
}))
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Started {
pub id: String,
pub csrf: String,
pub session: SessionInfo,
}
impl std::fmt::Debug for Started {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Started")
.field("session", &self.session)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Proof<'a> {
Handout,
Csrf(Option<&'a str>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionError {
NoUser,
Deactivated,
NoMembership,
BadAmr,
NoSession,
BadCsrf,
Registry(TenantError),
}
impl From<TenantError> for SessionError {
fn from(e: TenantError) -> SessionError {
SessionError::Registry(e)
}
}
impl SessionError {
fn status(self) -> u16 {
match self {
SessionError::BadCsrf | SessionError::NoMembership => 403,
SessionError::NoSession => 401,
SessionError::NoUser => 404,
SessionError::Deactivated => 409,
SessionError::BadAmr => 422,
SessionError::Registry(_) => 500,
}
}
}
fn after(at: i64, seconds: i64) -> i64 {
at.saturating_add(seconds.saturating_mul(NANOS_PER_SECOND))
}
fn info(row: &SessionRow) -> Result<SessionInfo, TenantError> {
let time = |at| from_nanos(at).ok_or(TenantError::Io);
Ok(SessionInfo {
user: row.user,
tenant: row.tenant,
scopes: Scopes::parse(&row.scopes).ok_or(TenantError::Io)?,
amr: row.amr.clone(),
created_at: time(row.created_at)?,
last_seen_at: time(row.last_seen_at)?,
idle_expires_at: time(row.idle_expires_at.min(row.expires_at))?,
expires_at: time(row.expires_at)?,
})
}
fn target(user: UserId, tenant: Option<TenantId>) -> String {
let place = tenant.map_or_else(|| "operator".to_owned(), |t| t.to_string());
format!("{user}/{place}")
}
fn limit(settings: &Settings, name: Name) -> i64 {
match settings.get(name) {
Value::Seconds(seconds) => i64::from(seconds),
Value::Flag(_) => 0,
}
}
impl Tenants {
pub fn start_session(
&self,
user: UserId,
tenant: Option<TenantId>,
amr: &[&str],
) -> Result<Started, SessionError> {
let entry = |status| Entry {
actor: Actor::User(user),
action: Action::SessionStart,
target: Some(target(user, tenant)),
version: None,
status,
};
let mut tx = self.registry.immediate()?;
let found = match amr_text(amr) {
None => Err(SessionError::BadAmr),
Some(amr) => membership_scopes(&mut tx, user, tenant).map(|found| (amr, found)),
};
let (amr, (scopes, settings)) = match found {
Ok(found) => found,
Err(SessionError::Registry(error)) => return Err(error.into()),
Err(refused) => {
self.record(&mut tx, &entry(refused.status()))?;
commit(tx)?;
return Err(refused);
}
};
let now = nanos(self.clock.now());
let id = new_secret();
let csrf = csrf_token(&id);
let idle_seconds = limit(&settings, Name::SessionIdle);
let row = SessionRow {
id_hash: hash(&id).to_vec(),
user,
tenant,
scopes: scopes.to_string(),
created_at: now,
last_seen_at: now,
idle_expires_at: after(now, idle_seconds),
expires_at: after(now, limit(&settings, Name::SessionAbsolute)),
idle_seconds,
amr,
csrf_hash: hash(&csrf).to_vec(),
};
tx.delete_sessions_ended(now)?;
tx.insert_session(&row)?;
let session = info(&row)?;
let done = entry(201);
self.record(&mut tx, &done)?;
commit(tx)?;
if let Some(t) = tenant {
self.copy_to_tenant(t, &done)?;
}
Ok(Started { id, csrf, session })
}
pub fn session(&self, id: &str, proof: Proof<'_>) -> Result<SessionInfo, SessionError> {
let mut tx = self.registry.immediate()?;
let now = nanos(self.clock.now());
let Some(row) = live(&mut tx, id, now)? else {
commit(tx)?;
self.count_session(Action::AuthFailed, 401, None);
return Err(SessionError::NoSession);
};
if let Proof::Csrf(token) = proof
&& !token.is_some_and(|token| same(&hash(token), &row.csrf_hash))
{
drop(tx);
self.count_session(Action::AuthFailed, 403, Some((row.user, row.tenant)));
return Err(SessionError::BadCsrf);
}
let seen = SessionRow {
last_seen_at: now,
idle_expires_at: after(now, row.idle_seconds),
..row
};
let session = info(&seen)?;
tx.touch_session(&seen.id_hash, seen.last_seen_at, seen.idle_expires_at)?;
commit(tx)?;
Ok(session)
}
pub fn end_session(&self, id: &str) -> Result<SessionInfo, SessionError> {
let mut tx = self.registry.immediate()?;
let Some(row) = live(&mut tx, id, nanos(self.clock.now()))? else {
commit(tx)?;
return Err(SessionError::NoSession);
};
let session = info(&row)?;
tx.delete_session(&row.id_hash)?;
let done = Entry {
actor: Actor::User(row.user),
action: Action::SessionEnd,
target: Some(target(row.user, row.tenant)),
version: None,
status: 204,
};
self.record(&mut tx, &done)?;
commit(tx)?;
if let Some(t) = row.tenant {
self.copy_to_tenant(t, &done)?;
}
Ok(session)
}
pub fn step_up_session(&self, id: &str, amr: &[&str]) -> Result<Started, SessionError> {
let amr = amr_text(amr).ok_or(SessionError::BadAmr)?;
let mut tx = self.registry.immediate()?;
let now = nanos(self.clock.now());
let Some(row) = live(&mut tx, id, now)? else {
commit(tx)?;
return Err(SessionError::NoSession);
};
let id = new_secret();
let csrf = csrf_token(&id);
tx.delete_session(&row.id_hash)?;
let row = SessionRow {
id_hash: hash(&id).to_vec(),
last_seen_at: now,
idle_expires_at: after(now, row.idle_seconds),
amr,
csrf_hash: hash(&csrf).to_vec(),
..row
};
tx.insert_session(&row)?;
let session = info(&row)?;
commit(tx)?;
Ok(Started { id, csrf, session })
}
pub(crate) fn count_session(
&self,
action: Action,
status: u16,
known: Option<(UserId, Option<TenantId>)>,
) {
let entry = |actor| Entry {
actor,
action,
target: None,
version: None,
status,
};
if let Some((user, Some(tenant))) = known
&& self
.store(tenant)
.is_ok_and(|store| store.count(&entry(Actor::User(user))).is_ok())
{
return;
}
let actor = known.map_or(Actor::Unparsed, |(user, _)| Actor::User(user));
let _ = self.count_admin(&entry(actor));
}
}
fn live(tx: &mut RTx<'_>, id: &str, now: i64) -> Result<Option<SessionRow>, TenantError> {
if !well_formed(id) {
return Ok(None);
}
let Some(row) = tx.session(&hash(id))? else {
return Ok(None);
};
if row.idle_expires_at <= now || row.expires_at <= now {
tx.delete_session(&row.id_hash)?;
return Ok(None);
}
Ok(Some(row))
}
fn membership_scopes(
tx: &mut RTx<'_>,
user: UserId,
tenant: Option<TenantId>,
) -> Result<(Scopes, Settings), SessionError> {
match tx.user(user)? {
None => return Err(SessionError::NoUser),
Some(row) if row.deactivated_at.is_some() => return Err(SessionError::Deactivated),
Some(_) => {}
}
let Some(held) = tx.membership(user, tenant)? else {
return Err(SessionError::NoMembership);
};
let roles = Roles::parse(&held.roles).ok_or(TenantError::Io)?;
let (cap, settings) = match tenant {
None => (None, Settings::default()),
Some(t) => {
let Some(row) = tx.tenant(t)? else {
return Err(SessionError::NoMembership);
};
let settings = Settings::stored(&tx.settings(t)?).ok_or(TenantError::Io)?;
(stored_cap(row.role_cap.as_deref())?, settings)
}
};
let scopes = roles.within(cap).scopes();
if scopes.is_empty() {
return Err(SessionError::NoMembership);
}
Ok((scopes, settings))
}
#[cfg(test)]
mod tests;