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;
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 = 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        // 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 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    /// Ends the live session with this id and answers what it was. The
280    /// caller has checked the request as [`Tenants::session`] does. The
281    /// end is recorded under the user in the admin log, and a tenant's in
282    /// the tenant's log too.
283    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        // The copy opens the tenant's Store, which reads the registry.
300        commit(tx)?;
301        if let Some(t) = row.tenant {
302            self.copy_to_tenant(t, &done)?;
303        }
304        Ok(session)
305    }
306
307    /// Gives the live session with this id a new id and CSRF token after a
308    /// step-up that showed the authentication methods `amr`, which replace
309    /// those it had. The session keeps its user, scopes, start and
310    /// absolute limit, and is seen now. The old id reaches nothing from
311    /// here on. Nothing is recorded here: the step-up records itself.
312    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    /// Counts one request by session in the minute it came: under the
337    /// user, in the tenant's log for a session in a tenant, or the admin
338    /// log for an operator's or when the tenant's log cannot be opened;
339    /// with no actor, in the admin log, when no session is known. A
340    /// failure to count changes nothing for the request.
341    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    /// The session with this id unless it has ended, with the time it
368    /// was judged at: the registry's clock in `tx`, read after the row,
369    /// so the begin's batch took it in the row's round trip. That one
370    /// reading is the time the caller writes too. A session found ended
371    /// is removed, for the caller to commit.
372    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
388/// The scopes a user's membership gives now, and the settings a session
389/// for it takes its limits from.
390fn 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    // Roles, a cap or settings that do not read back are damage.
404    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;