Skip to main content

plexus_auth_core/oidc/
session.rs

1//! `OidcSessionValidator` — the framework [`SessionValidator`] over the
2//! OIDC validator (UT-1, UT-S01 D4 step 3).
3//!
4//! This is the type a backend registers at its WS-upgrade perimeter to
5//! replace a bespoke JWT path (e.g. trak's `TrakAuth::try_jwt`, the
6//! HS256 shared-secret path that issue 74103adf indicts). Fallback
7//! mechanisms that sit *beside* the OIDC surface (API keys, SRP) stay in
8//! the backend's own `SessionValidator` chain, per the UT-S01
9//! interchangeability bar.
10
11use async_trait::async_trait;
12
13use crate::auth::{AuthContext, SessionValidator};
14use crate::capabilities::CookieName;
15use crate::oidc::validator::OidcValidator;
16
17/// Default cookie carrying the access token — the convention shared with
18/// synapse's `_self` store and WS-upgrade cookie attach (`access_token=`).
19const DEFAULT_COOKIE: &str = "access_token";
20
21/// A [`SessionValidator`] that accepts RS256 OIDC tokens.
22///
23/// Extracts the token from the configured cookie in the upgrade request's
24/// Cookie header (or treats the input as a bare token when it contains no
25/// `=`, matching the trak reference's tolerance for raw `-t <jwt>`
26/// invocations), validates it via [`OidcValidator`], and converts the
27/// result into an [`AuthContext`] (see
28/// [`VerifiedToken::into_auth_context`](crate::oidc::VerifiedToken::into_auth_context)).
29///
30/// Per the `SessionValidator` contract, every rejection maps to `None`
31/// (the connection proceeds as anonymous); the precise [`OidcError`]
32/// (crate::oidc::OidcError) is logged at debug level under
33/// `target = "plexus::auth"` — never surfaced to the wire.
34pub struct OidcSessionValidator {
35    validator: OidcValidator,
36    cookie: CookieName,
37}
38
39impl OidcSessionValidator {
40    /// Wrap a validator; tokens are read from the `access_token` cookie.
41    pub fn new(validator: OidcValidator) -> Self {
42        Self {
43            validator,
44            cookie: CookieName::try_new(DEFAULT_COOKIE)
45                .expect("the literal \"access_token\" is a valid cookie name"),
46        }
47    }
48
49    /// Wrap a validator reading a custom cookie.
50    pub fn with_cookie(validator: OidcValidator, cookie: CookieName) -> Self {
51        Self { validator, cookie }
52    }
53
54    /// The wrapped validator (e.g. for direct `validate_token` calls on
55    /// non-cookie paths).
56    pub fn validator(&self) -> &OidcValidator {
57        &self.validator
58    }
59}
60
61/// Parse a Cookie header for the named cookie's value, or return the raw
62/// string when it looks like a bare token (no `=`). Extracted verbatim
63/// from the trak reference (`plexus-trak/src/auth.rs`,
64/// `extract_token_from_cookies`), parameterized by cookie name.
65fn extract_token<'a>(cookie_header: &'a str, cookie_name: &str) -> &'a str {
66    if !cookie_header.contains('=') {
67        return cookie_header.trim();
68    }
69    for pair in cookie_header.split(';') {
70        let pair = pair.trim();
71        if let Some(rest) = pair.strip_prefix(cookie_name) {
72            if let Some(val) = rest.strip_prefix('=') {
73                return val.trim();
74            }
75        }
76    }
77    cookie_header.trim()
78}
79
80#[async_trait]
81impl SessionValidator for OidcSessionValidator {
82    async fn validate(&self, cookie_value: &str) -> Option<AuthContext> {
83        let token = extract_token(cookie_value, self.cookie.as_str());
84        match self.validator.validate_token(token).await {
85            Ok(verified) => Some(verified.into_auth_context()),
86            Err(e) => {
87                tracing::debug!(
88                    target: "plexus::auth",
89                    error = %e,
90                    "OIDC session validation rejected token"
91                );
92                None
93            }
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn extracts_named_cookie_from_header() {
104        assert_eq!(
105            extract_token("access_token=eyJx; other=1", "access_token"),
106            "eyJx"
107        );
108        assert_eq!(
109            extract_token("first=0; access_token=eyJx", "access_token"),
110            "eyJx"
111        );
112    }
113
114    #[test]
115    fn bare_token_passes_through() {
116        assert_eq!(extract_token("  eyJhbGciOi  ", "access_token"), "eyJhbGciOi");
117    }
118
119    #[test]
120    fn custom_cookie_name_is_honored() {
121        assert_eq!(extract_token("session=abc; access_token=no", "session"), "abc");
122    }
123
124    #[test]
125    fn prefix_cookie_names_do_not_match() {
126        // `access_token_v2` must not satisfy a lookup for `access_token`.
127        assert_eq!(
128            extract_token("access_token_v2=evil; access_token=good", "access_token"),
129            "good"
130        );
131    }
132}