Skip to main content

sofie_http/
session.rs

1use std::sync::{Arc, Mutex};
2
3use http::header::SET_COOKIE;
4use http::{HeaderMap, HeaderValue};
5use sofie_auth::{OpenError, SessionClaims, SigningKeys};
6use sofie_core::{Result, Timestamp, Uuid, unpoisoned};
7#[cfg(any(
8    feature = "permissions",
9    feature = "tokens",
10    feature = "shield",
11    feature = "session-list"
12))]
13use sofie_db::BoxFuture;
14use sofie_db::{Id, Resolve};
15
16use crate::answer::{self, Response};
17use crate::caller::Caller;
18use crate::cookie::CookieNames;
19use crate::{Area, PrincipalRecord, RequestContext};
20
21pub trait AreaMembers: Send + Sync + 'static {
22    #[cfg(feature = "permissions")]
23    fn grants<'a>(
24        &'a self,
25        read: &'a sofie_db::Read,
26        area: &'static str,
27        principal: Uuid,
28    ) -> BoxFuture<'a, Result<Vec<String>>> {
29        let _ = (read, area, principal);
30        Box::pin(std::future::ready(Ok(Vec::new())))
31    }
32
33    #[cfg(feature = "tokens")]
34    fn bearer<'a>(
35        &'a self,
36        db: &'a sofie_db::Db,
37        area: &'static str,
38        digest: &'a str,
39    ) -> BoxFuture<'a, Result<Option<crate::Bearer>>> {
40        let _ = (db, area, digest);
41        Box::pin(std::future::ready(Ok(None)))
42    }
43
44    #[cfg(feature = "shield")]
45    fn sign_in_locked<'a>(
46        &'a self,
47        db: &'a sofie_db::Db,
48        account: Uuid,
49        until: Timestamp,
50    ) -> BoxFuture<'a, Result<()>> {
51        let _ = (db, account, until);
52        Box::pin(std::future::ready(Ok(())))
53    }
54
55    /// Asked for a session a request's cookie names when the cache does not hold it, and
56    /// whenever the cookie is refreshed (`seen` set, at most every five minutes). A session no
57    /// longer live is signed out.
58    #[cfg(feature = "session-list")]
59    fn session_record<'a>(
60        &'a self,
61        db: &'a sofie_db::Db,
62        session: Uuid,
63        seen: Option<Timestamp>,
64    ) -> BoxFuture<'a, Result<SessionRecord>> {
65        let _ = (db, session, seen);
66        Box::pin(std::future::ready(Ok(SessionRecord::Unrecorded)))
67    }
68
69    /// The table of `session_record`'s records, written each time one ends, owned by its
70    /// account. With it, records are cached until such a write, here or on another instance.
71    #[cfg(feature = "session-list")]
72    fn session_topic(&self) -> Option<sofie_db::Topic> {
73        None
74    }
75}
76
77/// What a session store holds of a session.
78#[cfg(feature = "session-list")]
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum SessionRecord {
81    /// Signed in before the store recorded sessions: live until its cookie expires.
82    Unrecorded,
83    Live {
84        account: Uuid,
85        /// Ends by itself then, as an impersonation's does.
86        expires_at: Option<sofie_core::Instant>,
87        /// The account signed in as `account`; each request it makes is logged.
88        impersonator: Option<Uuid>,
89    },
90    Ended,
91}
92
93#[cfg(feature = "session-list")]
94impl SessionRecord {
95    #[must_use]
96    pub fn is_live(self, now: sofie_core::Instant) -> bool {
97        match self {
98            Self::Unrecorded => true,
99            Self::Live { expires_at, .. } => expires_at.is_none_or(|at| at > now),
100            Self::Ended => false,
101        }
102    }
103}
104
105/// Changes reach the cookie only once the handler's outcome has committed.
106pub struct Session {
107    changes: Arc<Mutex<Changes>>,
108    current: Option<Uuid>,
109    #[cfg(feature = "flows")]
110    flow: Option<String>,
111    #[cfg(feature = "client-headers")]
112    client: Client,
113}
114
115/// What a client says of itself: untrusted, read only by handlers that ask.
116#[cfg(feature = "client-headers")]
117#[derive(Clone, Default)]
118struct Client {
119    user_agent: Option<HeaderValue>,
120    origin: Option<HeaderValue>,
121}
122
123#[cfg(feature = "client-headers")]
124impl Client {
125    fn of(request: &http::request::Parts) -> Self {
126        let origin = request.headers.get(http::header::ORIGIN).filter(|origin| {
127            crate::csrf::host_of(request)
128                .is_some_and(|host| crate::csrf::is_origin_of(origin, host))
129        });
130        Self {
131            user_agent: request.headers.get(http::header::USER_AGENT).cloned(),
132            origin: origin.cloned(),
133        }
134    }
135}
136
137#[derive(Default)]
138struct Changes {
139    requested: Option<Change>,
140    #[cfg(feature = "flows")]
141    begun_flow: Option<String>,
142    committed: bool,
143}
144
145#[derive(Clone, Copy)]
146enum Change {
147    SignIn {
148        session: Uuid,
149        area: &'static str,
150        principal: Uuid,
151    },
152    SignOut,
153}
154
155/// Implemented by a private type of each package whose job is signing principals in, such as
156/// sofie-identity's: it alone mints the `SignInRight` that `Session::sign_in` takes. Code that
157/// implements it for a type of its own can sign anyone in, so only such a package should.
158pub trait Admitter {}
159
160/// The right to sign a principal in, minted only for an `Admitter`; zero-sized, so carrying it
161/// costs nothing. It cannot be built any other way:
162///
163/// ```compile_fail,E0451
164/// let right = sofie_http::SignInRight { sealed: () };
165/// ```
166///
167/// ```compile_fail,E0277
168/// struct Visitor;
169/// let right = sofie_http::SignInRight::of::<Visitor>();
170/// ```
171#[derive(Clone, Copy)]
172pub struct SignInRight {
173    sealed: (),
174}
175
176const _: () = assert!(size_of::<SignInRight>() == 0);
177
178impl SignInRight {
179    #[must_use]
180    pub const fn of<K: Admitter>() -> Self {
181        Self { sealed: () }
182    }
183}
184
185impl Session {
186    /// Issues a fresh cookie, so no session value from before signing in stays valid; whether
187    /// the principal may enter the area is the caller's to check. An action without a
188    /// `SignInRight` cannot sign anyone in:
189    ///
190    /// ```compile_fail,E0061
191    /// # use sofie_http::{Area, PrincipalRecord, Session};
192    /// fn sign_in_anyone<A: Area>(session: &Session, anyone: sofie_db::Id<PrincipalRecord<A>>) {
193    ///     let _ = session.sign_in::<A>(anyone);
194    /// }
195    /// ```
196    pub fn sign_in<A: Area>(
197        &self,
198        right: SignInRight,
199        principal: Id<PrincipalRecord<A>>,
200    ) -> Result<Uuid> {
201        let SignInRight { sealed: () } = right;
202        let session = Uuid::new_v4()
203            .map_err(|error| sofie_core::Error::internal("choosing a session id", error))?;
204        #[cfg(feature = "product-events")]
205        sofie_telemetry::attach_principal(&tracing::Span::current(), principal.uuid());
206        self.request(Change::SignIn {
207            session,
208            area: A::NAME,
209            principal: principal.uuid(),
210        });
211        Ok(session)
212    }
213
214    #[must_use]
215    pub fn current(&self) -> Option<Uuid> {
216        self.current
217    }
218
219    /// As the client sent it: untrusted, for showing a session's device to its owner.
220    #[cfg(feature = "client-headers")]
221    #[must_use]
222    pub fn user_agent(&self) -> Option<std::borrow::Cow<'_, str>> {
223        let value = self.client.user_agent.as_ref()?;
224        Some(String::from_utf8_lossy(value.as_bytes()))
225    }
226
227    /// The `Origin` the browser sent, when it names the host the request was sent to.
228    #[cfg(feature = "client-headers")]
229    #[must_use]
230    pub fn origin(&self) -> Option<&str> {
231        self.client.origin.as_ref()?.to_str().ok()
232    }
233
234    pub fn sign_out(&self) {
235        self.request(Change::SignOut);
236    }
237
238    /// Ties a flow through another site, such as an OAuth sign-in, to this browser: the
239    /// returned value goes into the flow's state, and `flow` reads it back on return.
240    #[cfg(feature = "flows")]
241    pub fn begin_flow(&self) -> Result<String> {
242        let value = Uuid::new_v4()
243            .map_err(|error| sofie_core::Error::internal("choosing a flow's value", error))?
244            .to_string();
245        unpoisoned::lock(&self.changes).begun_flow = Some(value.clone());
246        Ok(value)
247    }
248
249    #[cfg(feature = "flows")]
250    #[must_use]
251    pub fn flow(&self) -> Option<&str> {
252        self.flow.as_deref()
253    }
254
255    fn request(&self, change: Change) {
256        unpoisoned::lock(&self.changes).requested = Some(change);
257    }
258}
259
260impl<A: Area> Resolve<RequestContext<A>> for Session {
261    fn resolve(context: &mut RequestContext<A>) -> impl Future<Output = Result<Self>> + Send {
262        let session = context.session();
263        std::future::ready(Ok(Self {
264            changes: Arc::clone(&session.changes),
265            current: session.recorded,
266            #[cfg(feature = "flows")]
267            flow: session.flow.clone(),
268            #[cfg(feature = "client-headers")]
269            client: session.client.clone(),
270        }))
271    }
272}
273
274/// The session the request's cookie carries, read in a page's loader as in an action.
275pub struct CurrentSession(Option<Uuid>);
276
277impl CurrentSession {
278    #[must_use]
279    pub fn id(&self) -> Option<Uuid> {
280        self.0
281    }
282}
283
284impl<A: Area, M> Resolve<RequestContext<A, M>> for CurrentSession {
285    fn resolve(context: &mut RequestContext<A, M>) -> impl Future<Output = Result<Self>> + Send {
286        std::future::ready(Ok(Self(context.session().recorded)))
287    }
288}
289
290pub(crate) struct Sessions {
291    pub(crate) keys: Arc<SigningKeys>,
292    #[cfg(any(feature = "tokens", feature = "session-list"))]
293    pub(crate) members: Option<Arc<dyn AreaMembers>>,
294    pub(crate) cookies: CookieNames,
295    #[cfg(feature = "session-list")]
296    pub(crate) records: crate::session_cache::SessionCache,
297}
298
299impl Sessions {
300    pub(crate) fn open(&self, headers: &HeaderMap, now: Timestamp) -> RequestSession {
301        let sealed = self.cookies.session_value(headers);
302        let claims = sealed.and_then(|sealed| opened(&self.keys, sealed, now));
303        let is_dead = sealed.is_some() && claims.is_none();
304        let recorded = claims.as_ref().map(SessionClaims::session);
305        #[cfg(all(feature = "toolbar", debug_assertions))]
306        let toolbar = crate::toolbar::Overrides::of(headers, self.cookies.toolbar());
307        #[cfg(all(feature = "toolbar", debug_assertions))]
308        let (claims, recorded) = match toolbar.claims(now) {
309            Some(acting) => (Some(acting), None),
310            None => (claims, recorded),
311        };
312        RequestSession {
313            claims,
314            recorded,
315            #[cfg(feature = "flows")]
316            flow: self.cookies.flow_value(headers).map(str::to_owned),
317            is_dead,
318            #[cfg(all(feature = "toolbar", debug_assertions))]
319            toolbar,
320            ..RequestSession::default()
321        }
322    }
323}
324
325fn opened(keys: &SigningKeys, sealed: &str, now: Timestamp) -> Option<SessionClaims> {
326    SessionClaims::open(keys, sealed, now)
327        .map_err(log_unopened)
328        .ok()
329}
330
331/// A client can send any cookie, so only a corrupt one, which our own keys sealed, is an error.
332fn log_unopened(error: OpenError) {
333    let refused = match error {
334        OpenError::Malformed => "malformed",
335        OpenError::Unauthenticated => "unauthenticated",
336        OpenError::Expired => "expired",
337        OpenError::Corrupt => "corrupt",
338    };
339    match error {
340        OpenError::Malformed | OpenError::Expired => {
341            tracing::debug!(session.refused = refused, "the session cookie did not open");
342        }
343        OpenError::Unauthenticated => {
344            tracing::info!(session.refused = refused, "the session cookie did not open");
345        }
346        OpenError::Corrupt => {
347            tracing::error!(error.kind = "session", session.refused = refused, error = %error, "the session cookie did not open");
348        }
349    }
350}
351
352#[derive(Clone, Default)]
353pub(crate) struct RequestSession {
354    claims: Option<SessionClaims>,
355    /// The cookie's session, when the claims are the cookie's own.
356    recorded: Option<Uuid>,
357    #[cfg(feature = "flows")]
358    flow: Option<String>,
359    #[cfg(feature = "client-headers")]
360    client: Client,
361    /// Tampered, sealed by a retired key or expired; it is cleared.
362    is_dead: bool,
363    changes: Arc<Mutex<Changes>>,
364    /// A bearer token's; its request never writes a cookie.
365    #[cfg(feature = "tokens")]
366    scopes: Option<Arc<[String]>>,
367    /// Its principal, when acting as one, has replaced the signed-in one.
368    #[cfg(all(feature = "toolbar", debug_assertions))]
369    pub(crate) toolbar: crate::toolbar::Overrides,
370}
371
372impl RequestSession {
373    #[cfg(feature = "tokens")]
374    pub(crate) fn bearer(area: &str, bearer: crate::Bearer, now: Timestamp) -> Self {
375        let claims = SessionClaims::new(bearer.token, area, bearer.principal, now);
376        Self {
377            claims: Some(claims),
378            scopes: Some(bearer.scopes.into()),
379            ..Self::default()
380        }
381    }
382
383    #[cfg(feature = "engine")]
384    pub(crate) fn for_loader(&self) -> Self {
385        Self {
386            changes: Arc::default(),
387            ..self.clone()
388        }
389    }
390
391    #[cfg(feature = "client-headers")]
392    pub(crate) fn with_client(self, request: &http::request::Parts) -> Self {
393        Self {
394            client: Client::of(request),
395            ..self
396        }
397    }
398
399    #[cfg(feature = "session-list")]
400    pub(crate) async fn confirmed(
401        mut self,
402        sessions: &Sessions,
403        db: &sofie_db::Db,
404        now: Timestamp,
405    ) -> Result<Self> {
406        let (Some(session), Some(members)) = (self.recorded, sessions.members.as_deref()) else {
407            return Ok(self);
408        };
409        let seen = self
410            .claims
411            .as_ref()
412            .is_some_and(|claims| claims.needs_refresh(now))
413            .then_some(now);
414        match sessions.records.live(members, db, session, seen).await? {
415            Some(SessionRecord::Live {
416                account,
417                impersonator: Some(impersonator),
418                ..
419            }) => tracing::info!(
420                impersonation.account = %account,
421                impersonation.impersonator = %impersonator,
422                "a request made while impersonating"
423            ),
424            Some(_) => {}
425            None => {
426                self.claims = None;
427                self.recorded = None;
428                self.is_dead = true;
429            }
430        }
431        Ok(self)
432    }
433
434    #[cfg(feature = "tokens")]
435    pub(crate) fn scopes(&self) -> Option<Arc<[String]>> {
436        self.scopes.clone()
437    }
438
439    #[cfg_attr(
440        not(feature = "tokens"),
441        expect(clippy::unused_self, reason = "only a token opens a bearer session")
442    )]
443    pub(crate) fn is_bearer(&self) -> bool {
444        #[cfg(feature = "tokens")]
445        return self.scopes.is_some();
446        #[cfg(not(feature = "tokens"))]
447        false
448    }
449
450    pub(crate) fn principal(&self) -> Option<Uuid> {
451        self.claims.as_ref().map(SessionClaims::principal)
452    }
453
454    #[cfg(feature = "remote-contracts")]
455    pub(crate) fn acting(&self) -> Option<sofie_auth::Acting> {
456        self.claims.as_ref().map(|claims| sofie_auth::Acting {
457            area: claims.area().to_owned(),
458            principal: claims.principal(),
459        })
460    }
461
462    pub(crate) fn principal_in(&self, area: &str) -> Option<Uuid> {
463        self.claims
464            .as_ref()
465            .filter(|claims| claims.area() == area)
466            .map(SessionClaims::principal)
467    }
468
469    pub(crate) fn committed(&self) {
470        unpoisoned::lock(&self.changes).committed = true;
471    }
472
473    pub(crate) fn signed_in_area(&self) -> Option<&'static str> {
474        match self.committed_change() {
475            Some(Change::SignIn { area, .. }) => Some(area),
476            _ => None,
477        }
478    }
479
480    #[cfg(feature = "flows")]
481    fn begun_flow(&self) -> Option<String> {
482        let changes = unpoisoned::lock(&self.changes);
483        changes.begun_flow.clone().filter(|_| changes.committed)
484    }
485
486    fn committed_change(&self) -> Option<Change> {
487        let changes = unpoisoned::lock(&self.changes);
488        changes.requested.filter(|_| changes.committed)
489    }
490
491    pub(crate) fn finish(
492        &self,
493        mut response: Response,
494        sessions: &Sessions,
495        now: Timestamp,
496        caller: Caller<'_>,
497    ) -> Response {
498        if self.is_bearer() {
499            return response;
500        }
501        #[cfg(feature = "flows")]
502        if let Some(flow) = self.begun_flow() {
503            match sessions.cookies.begun_flow(&flow) {
504                Ok(cookie) => response.headers_mut().append(SET_COOKIE, cookie),
505                Err(error) => return answer::failure(error, caller),
506            };
507        }
508        match self.cookie(sessions, now) {
509            Ok(Some(cookie)) => {
510                response.headers_mut().append(SET_COOKIE, cookie);
511                response
512            }
513            Ok(None) => response,
514            Err(error) => answer::failure(error, caller),
515        }
516    }
517
518    fn cookie(&self, sessions: &Sessions, now: Timestamp) -> Result<Option<HeaderValue>> {
519        let (keys, cookies) = (&sessions.keys, &sessions.cookies);
520        match self.committed_change() {
521            Some(Change::SignIn {
522                session,
523                area,
524                principal,
525            }) => cookies
526                .sealed_session(
527                    keys,
528                    &SessionClaims::new(session, area, principal, now),
529                    now,
530                )
531                .map(Some),
532            Some(Change::SignOut) => cookies.session_removal().map(Some),
533            None => self.refreshed_cookie(sessions, now),
534        }
535    }
536
537    fn refreshed_cookie(&self, sessions: &Sessions, now: Timestamp) -> Result<Option<HeaderValue>> {
538        let cookies = &sessions.cookies;
539        match &self.claims {
540            Some(claims) if claims.needs_refresh(now) => cookies
541                .sealed_session(&sessions.keys, &claims.clone().seen_at(now), now)
542                .map(Some),
543            None if self.is_dead => cookies.session_removal().map(Some),
544            Some(_) | None => Ok(None),
545        }
546    }
547}