1use 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
20pub const COOKIE: &str = "__Host-vcs_session";
24
25pub const CSRF_HEADER: &str = "x-csrf-token";
27
28const FETCH_SITE: &str = "sec-fetch-site";
30
31const SECRET_LEN: usize = 32;
33
34const SECRET_CHARS: usize = 43;
36
37const CSRF_DOMAIN: &[u8] = b"vcon-server session csrf token\0";
40
41const ATTRIBUTES: &str = "Path=/; Secure; HttpOnly; SameSite=Strict";
43
44const AMR_MOST: usize = 8;
47const AMR_LONGEST: usize = 32;
48
49const HOST_LONGEST: usize = 253;
51
52#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Origin(String);
58
59impl Origin {
60 #[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 #[must_use]
96 pub fn as_str(&self) -> &str {
97 &self.0
98 }
99
100 #[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
120pub(crate) fn new_secret() -> String {
122 let mut secret = [0; SECRET_LEN];
123 aws_lc_rs::rand::fill(&mut secret).expect("AWS-LC aborts instead of failing");
126 URL_SAFE_NO_PAD.encode(secret)
127}
128
129pub(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
138pub(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
146pub(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
154pub(crate) fn same(one: &[u8], other: &[u8]) -> bool {
157 constant_time::verify_slices_are_equal(one, other).is_ok()
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub(crate) enum Cookie<'a> {
163 Absent,
165 Bad,
168 Id(&'a str),
170}
171
172pub(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#[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
211pub(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
217fn 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
227pub(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
248pub(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;