Skip to main content

vcon_server/tenants/
sessions.rs

1//! The sessions of users who signed in.
2//!
3//! A session is one row of the registry's `session` table, found by the
4//! SHA-256 of its id. It is for one membership of its user, a tenant's or
5//! the operator's, and holds the scopes that membership gave when the
6//! session started. It ends at its idle limit unless a request is seen, at
7//! its absolute limit whatever is seen, when its user ends it, and when the
8//! membership could have changed: `users` and `role_cap` remove sessions in
9//! the transaction that changes a membership, a user or a role cap.
10//!
11//! No sign-in method is built yet. [`Tenants::start_session`] is the seam
12//! one will call once it has checked who the user is.
13
14use 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/// A session as its user's browser may see it.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct SessionInfo {
33    pub user: UserId,
34    /// The tenant the session works in; None on the operator plane.
35    pub tenant: Option<TenantId>,
36    /// The scopes the membership gave when the session started.
37    pub scopes: Scopes,
38    /// The authentication methods the sign-in showed, joined with spaces.
39    pub amr: String,
40    pub created_at: OffsetDateTime,
41    pub last_seen_at: OffsetDateTime,
42    /// When the session ends unless a request is seen before; never after
43    /// `expires_at`.
44    pub idle_expires_at: OffsetDateTime,
45    /// When the session ends whatever is seen.
46    pub expires_at: OffsetDateTime,
47}
48
49impl SessionInfo {
50    /// The session as `GET /session` answers it, with the CSRF token
51    /// given: user, tenant (null on the operator plane), scopes,
52    /// authentication methods and the times in RFC 3339. None when a time
53    /// cannot be written so.
54    #[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/// A session just started or just given a new id: the id for the cookie,
72/// the CSRF token for the page, and the session. Its `Debug` form shows
73/// the session and neither the id nor the token, so a log line or a failed
74/// assertion that prints one gives nothing a request could use.
75#[derive(Clone, PartialEq, Eq)]
76pub struct Started {
77    /// The session's id. It is shown this once and kept nowhere.
78    pub id: String,
79    /// The session's CSRF token, `crate::session::csrf_token` of the id.
80    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/// What a request by session shows besides its cookie.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum Proof<'a> {
95    /// The hand-out, `GET /session`: no token, since the page asks for it.
96    Handout,
97    /// Any other request: the `X-CSRF-Token` header's value, if it has one.
98    Csrf(Option<&'a str>),
99}
100
101/// Why a call about a session was refused or failed.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum SessionError {
104    /// No user has the id.
105    NoUser,
106    /// The user is deactivated.
107    Deactivated,
108    /// The user has no membership there, or one whose roles give no scope
109    /// under the tenant's role cap.
110    NoMembership,
111    /// The authentication methods are not ones a session keeps.
112    BadAmr,
113    /// No live session has the id: it never was, or it has ended.
114    NoSession,
115    /// The CSRF token is missing or is not the session's.
116    BadCsrf,
117    /// The registry failed.
118    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    /// The status a refused start is recorded with.
129    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
141/// `seconds` after `at`, in the registry's nanoseconds.
142fn after(at: i64, seconds: i64) -> i64 {
143    at.saturating_add(seconds.saturating_mul(NANOS_PER_SECOND))
144}
145
146/// A row as its user's browser may see it. Scopes or a time that do not
147/// read back are damage, not a session with none.
148fn 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
162/// What a record of a session names: its user and where it works.
163fn 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
168/// A limit of a tenant's settings, in seconds.
169fn limit(settings: &Settings, name: Name) -> i64 {
170    match settings.get(name) {
171        Value::Seconds(seconds) => i64::from(seconds),
172        // `Settings::get` answers a limit's name with seconds.
173        Value::Flag(_) => 0,
174    }
175}
176
177impl Tenants {
178    /// Starts a session for a user's membership in `tenant`, or as an
179    /// operator for None, after a sign-in that showed the authentication
180    /// methods `amr`. The caller has checked who the user is.
181    ///
182    /// The session always has a new id, so an id a browser held before
183    /// sign-in is never the id after it. Its scopes are those of the
184    /// membership's roles under the tenant's role cap, fixed here. Its
185    /// limits are the tenant's settings `session.idle_seconds` and
186    /// `session.absolute_seconds` as they are now, or the defaults on the
187    /// operator plane. Sessions that have ended are removed from the table
188    /// here. The start, and a refusal, are recorded under the user in the
189    /// admin log, and a tenant's start in the tenant's log too.
190    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        // The copy opens the tenant's Store, which reads the registry.
240        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    /// The live session a request's cookie names, seen now: its idle limit
248    /// moves to its idle time from now. A session at or past either limit
249    /// has ended and its row is removed. A request that is not the
250    /// hand-out needs the session's CSRF token, compared by hash in
251    /// constant time; one refused for its token does not count as seen.
252    /// A refusal is counted in the audit as `auth_failed`: with no actor
253    /// when no live session has the id, under the user for a token.
254    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    /// Ends the live session with this id and answers what it was. The
281    /// caller has checked the request as [`Tenants::session`] does. The
282    /// end is recorded under the user in the admin log, and a tenant's in
283    /// the tenant's log too.
284    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        // The copy opens the tenant's Store, which reads the registry.
301        commit(tx)?;
302        if let Some(t) = row.tenant {
303            self.copy_to_tenant(t, &done)?;
304        }
305        Ok(session)
306    }
307
308    /// Gives the live session with this id a new id and CSRF token after a
309    /// step-up that showed the authentication methods `amr`, which replace
310    /// those it had. The session keeps its user, scopes, start and
311    /// absolute limit, and is seen now. The old id reaches nothing from
312    /// here on. Nothing is recorded here: the step-up records itself.
313    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    /// Counts one request by session in the minute it came: under the
339    /// user, in the tenant's log for a session in a tenant, or the admin
340    /// log for an operator's or when the tenant's log cannot be opened;
341    /// with no actor, in the admin log, when no session is known. A
342    /// failure to count changes nothing for the request.
343    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
368/// The session with this id unless it has ended; one found ended is
369/// removed, for the caller to commit.
370fn 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
384/// The scopes a user's membership gives now, and the settings a session
385/// for it takes its limits from.
386fn 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    // Roles, a cap or settings that do not read back are damage.
400    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;