Skip to main content

vcon_server/
session.rs

1//! What a request by session carries: the cookie, the CSRF token and the
2//! origin it must come from.
3//!
4//! A session is a row in the registry (`crate::tenants`), found by the
5//! SHA-256 of a random 256-bit id. The id travels in the cookie
6//! [`COOKIE`] and nowhere else. The CSRF token is made from the id
7//! (`csrf_token`), so `GET /session` can hand it to the page again while
8//! the registry keeps only its hash; page script cannot read the cookie,
9//! and the token does not show the id.
10
11use std::fmt;
12
13use aws_lc_rs::constant_time;
14use aws_lc_rs::digest::{SHA256, digest};
15use axum::http::header::{COOKIE as COOKIE_HEADER, ORIGIN};
16use axum::http::{HeaderMap, HeaderValue};
17use base64::Engine;
18use base64::engine::general_purpose::URL_SAFE_NO_PAD;
19
20/// The session cookie's name. The `__Host-` prefix has a browser refuse
21/// the cookie unless it is `Secure`, has `Path=/` and names no domain, so
22/// no other host and no plain-HTTP page can set or read it.
23pub const COOKIE: &str = "__Host-vcs_session";
24
25/// The request header that carries the session's CSRF token.
26pub const CSRF_HEADER: &str = "x-csrf-token";
27
28/// The request header a browser sets to say where a fetch came from.
29const FETCH_SITE: &str = "sec-fetch-site";
30
31/// The bytes of a session id, and of the CSRF token made from it.
32const SECRET_LEN: usize = 32;
33
34/// The characters [`SECRET_LEN`] bytes take in base64url with no padding.
35const SECRET_CHARS: usize = 43;
36
37/// What the SHA-256 that makes a CSRF token starts with, so the token is
38/// not the hash the registry finds the session by.
39const CSRF_DOMAIN: &[u8] = b"vcon-server session csrf token\0";
40
41/// The attributes of the cookie, set and cleared alike.
42const ATTRIBUTES: &str = "Path=/; Secure; HttpOnly; SameSite=Strict";
43
44/// The most authentication methods a session keeps, and the most
45/// characters of one.
46const AMR_MOST: usize = 8;
47const AMR_LONGEST: usize = 32;
48
49/// The longest host name of an origin, as DNS limits a name.
50const HOST_LONGEST: usize = 253;
51
52/// A listener's public origin (`public_origin`, `operator.public_origin`):
53/// `https://` and a host, with a port when it is not 443, as a browser
54/// writes it in the `Origin` header of a request from the listener's
55/// pages.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Origin(String);
58
59impl Origin {
60    /// Reads an origin: `https://host` or `https://host:port`, the host in
61    /// lower case, an IPv6 address in brackets, and nothing after it.
62    #[must_use]
63    pub fn parse(text: &str) -> Option<Origin> {
64        let rest = text.strip_prefix("https://")?;
65        let (host, port) = match rest.strip_prefix('[') {
66            Some(inner) => {
67                let (address, after) = inner.split_once(']')?;
68                address.parse::<std::net::Ipv6Addr>().ok()?;
69                let host = &rest[..address.len() + 2];
70                match after {
71                    "" => (host, None),
72                    after => (host, Some(after.strip_prefix(':')?)),
73                }
74            }
75            None => match rest.split_once(':') {
76                Some((host, port)) => (host, Some(port)),
77                None => (rest, None),
78            },
79        };
80        let named = host.starts_with('[')
81            || (!host.is_empty()
82                && host.len() <= HOST_LONGEST
83                && host.bytes().all(|b| {
84                    b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-'
85                }));
86        let numbered = port.is_none_or(|port| {
87            !port.is_empty()
88                && port.bytes().all(|b| b.is_ascii_digit())
89                && port.parse::<u16>().is_ok_and(|port| port != 0)
90        });
91        (named && numbered).then(|| Origin(text.to_owned()))
92    }
93
94    /// The origin as written.
95    #[must_use]
96    pub fn as_str(&self) -> &str {
97        &self.0
98    }
99
100    /// The origin's host, without the scheme and the port. A browser keeps
101    /// a cookie by host alone, so two listeners on one host share one.
102    #[must_use]
103    pub fn host(&self) -> &str {
104        let rest = &self.0["https://".len()..];
105        if rest.starts_with('[') {
106            let end = rest.find(']').map_or(rest.len(), |at| at + 1);
107            &rest[..end]
108        } else {
109            rest.split_once(':').map_or(rest, |(host, _)| host)
110        }
111    }
112}
113
114impl fmt::Display for Origin {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.write_str(&self.0)
117    }
118}
119
120/// A new session id: 256 random bits in base64url.
121pub(crate) fn new_secret() -> String {
122    let mut secret = [0; SECRET_LEN];
123    // AWS-LC's RAND_bytes aborts the process when it cannot get enough
124    // randomness, so `fill` never returns its error.
125    aws_lc_rs::rand::fill(&mut secret).expect("AWS-LC aborts instead of failing");
126    URL_SAFE_NO_PAD.encode(secret)
127}
128
129/// Whether `secret` is written as a session id or a CSRF token is: 43
130/// characters of the base64url alphabet.
131pub(crate) fn well_formed(secret: &str) -> bool {
132    secret.len() == SECRET_CHARS
133        && secret
134            .bytes()
135            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
136}
137
138/// The SHA-256 of a session id or a CSRF token, as the registry keeps it.
139pub(crate) fn hash(text: &str) -> [u8; 32] {
140    digest(&SHA256, text.as_bytes())
141        .as_ref()
142        .try_into()
143        .expect("SHA-256 is 32 bytes")
144}
145
146/// The CSRF token of the session with this id: a SHA-256 over a fixed
147/// start and the id, in base64url. Whoever holds the id can make it; the
148/// token gives no way back to the id.
149pub(crate) fn csrf_token(id: &str) -> String {
150    let made = digest(&SHA256, &[CSRF_DOMAIN, id.as_bytes()].concat());
151    URL_SAFE_NO_PAD.encode(made.as_ref())
152}
153
154/// Whether two byte strings are equal, in time that does not depend on
155/// where they differ.
156pub(crate) fn same(one: &[u8], other: &[u8]) -> bool {
157    constant_time::verify_slices_are_equal(one, other).is_ok()
158}
159
160/// The session cookie of a request.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub(crate) enum Cookie<'a> {
163    /// The request has none.
164    Absent,
165    /// The request has more than one, one whose value no session id has,
166    /// or a `Cookie` header that is not text.
167    Bad,
168    /// The one cookie's value, written as a session id is.
169    Id(&'a str),
170}
171
172/// Reads the session cookie from a request's `Cookie` headers. A name is
173/// matched whole and in its case.
174pub(crate) fn cookie(headers: &HeaderMap) -> Cookie<'_> {
175    let mut found = Cookie::Absent;
176    for header in headers.get_all(COOKIE_HEADER) {
177        let Ok(text) = header.to_str() else {
178            return Cookie::Bad;
179        };
180        for pair in text.split(';') {
181            let Some((name, value)) = pair.trim().split_once('=') else {
182                continue;
183            };
184            if name != COOKIE {
185                continue;
186            }
187            if found != Cookie::Absent || !well_formed(value) {
188                return Cookie::Bad;
189            }
190            found = Cookie::Id(value);
191        }
192    }
193    found
194}
195
196/// The `Set-Cookie` value that gives a browser the session with this id.
197/// It names no lifetime: the browser drops it when it closes, and the
198/// registry holds the limits. A sign-in method answers with it once
199/// `Tenants::start_session` has given it the id; none is built yet.
200///
201/// # Panics
202///
203/// If `id` holds a character a header value cannot; a session id never
204/// does.
205#[must_use]
206pub fn set_cookie(id: &str) -> HeaderValue {
207    HeaderValue::from_str(&format!("{COOKIE}={id}; {ATTRIBUTES}"))
208        .expect("a session id is visible ASCII")
209}
210
211/// The `Set-Cookie` value that removes the session cookie from a browser.
212pub(crate) fn clear_cookie() -> HeaderValue {
213    HeaderValue::from_str(&format!("{COOKIE}=; {ATTRIBUTES}; Max-Age=0"))
214        .expect("the cookie's name and attributes are visible ASCII")
215}
216
217/// The one value of a header, or None for no header, two, or one that is
218/// not text.
219fn one<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
220    let mut all = headers.get_all(name).iter();
221    match (all.next(), all.next()) {
222        (Some(value), None) => value.to_str().ok(),
223        _ => None,
224    }
225}
226
227/// Whether a request by session comes from the listener's own pages.
228///
229/// Every request but the hand-out needs one `Origin` header equal to the
230/// listener's public origin. The hand-out (`GET /session`) is a GET a page
231/// makes to its own origin, which a browser sends with no `Origin`: it
232/// needs one `Sec-Fetch-Site: same-origin`, a header page script cannot
233/// set, and an `Origin`, when there is one, equal as on any other request.
234/// A listener with no public origin passes nothing.
235pub(crate) fn from_origin(headers: &HeaderMap, origin: Option<&Origin>, hand_out: bool) -> bool {
236    let Some(origin) = origin else {
237        return false;
238    };
239    let equal = || one(headers, ORIGIN.as_str()) == Some(origin.as_str());
240    if hand_out {
241        one(headers, FETCH_SITE) == Some("same-origin")
242            && (!headers.contains_key(ORIGIN) || equal())
243    } else {
244        equal()
245    }
246}
247
248/// The authentication methods a sign-in showed (RFC 8176 names such as
249/// `hwk` or `mfa`), as a session keeps them: joined with spaces, in the
250/// order given. None unless there are 1 to 8, each 1 to 32 characters of
251/// lower-case letters, digits, `-` and `_`, and no two alike.
252pub(crate) fn amr_text(methods: &[&str]) -> Option<String> {
253    let good = |method: &&str| {
254        (1..=AMR_LONGEST).contains(&method.len())
255            && method
256                .bytes()
257                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
258    };
259    let distinct = methods
260        .iter()
261        .enumerate()
262        .all(|(at, method)| !methods[..at].contains(method));
263    ((1..=AMR_MOST).contains(&methods.len()) && methods.iter().all(good) && distinct)
264        .then(|| methods.join(" "))
265}
266
267#[cfg(test)]
268mod tests;