use std::fmt;
use aws_lc_rs::constant_time;
use aws_lc_rs::digest::{SHA256, digest};
use axum::http::header::{COOKIE as COOKIE_HEADER, ORIGIN};
use axum::http::{HeaderMap, HeaderValue};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
pub const COOKIE: &str = "__Host-vcs_session";
pub const CSRF_HEADER: &str = "x-csrf-token";
const FETCH_SITE: &str = "sec-fetch-site";
const SECRET_LEN: usize = 32;
const SECRET_CHARS: usize = 43;
const CSRF_DOMAIN: &[u8] = b"vcon-server session csrf token\0";
const ATTRIBUTES: &str = "Path=/; Secure; HttpOnly; SameSite=Strict";
const AMR_MOST: usize = 8;
const AMR_LONGEST: usize = 32;
const HOST_LONGEST: usize = 253;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Origin(String);
impl Origin {
#[must_use]
pub fn parse(text: &str) -> Option<Origin> {
let rest = text.strip_prefix("https://")?;
let (host, port) = match rest.strip_prefix('[') {
Some(inner) => {
let (address, after) = inner.split_once(']')?;
address.parse::<std::net::Ipv6Addr>().ok()?;
let host = &rest[..address.len() + 2];
match after {
"" => (host, None),
after => (host, Some(after.strip_prefix(':')?)),
}
}
None => match rest.split_once(':') {
Some((host, port)) => (host, Some(port)),
None => (rest, None),
},
};
let named = host.starts_with('[')
|| (!host.is_empty()
&& host.len() <= HOST_LONGEST
&& host.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-'
}));
let numbered = port.is_none_or(|port| {
!port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit())
&& port.parse::<u16>().is_ok_and(|port| port != 0)
});
(named && numbered).then(|| Origin(text.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn host(&self) -> &str {
let rest = &self.0["https://".len()..];
if rest.starts_with('[') {
let end = rest.find(']').map_or(rest.len(), |at| at + 1);
&rest[..end]
} else {
rest.split_once(':').map_or(rest, |(host, _)| host)
}
}
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
pub(crate) fn new_secret() -> String {
let mut secret = [0; SECRET_LEN];
aws_lc_rs::rand::fill(&mut secret).expect("AWS-LC aborts instead of failing");
URL_SAFE_NO_PAD.encode(secret)
}
pub(crate) fn well_formed(secret: &str) -> bool {
secret.len() == SECRET_CHARS
&& secret
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
pub(crate) fn hash(text: &str) -> [u8; 32] {
digest(&SHA256, text.as_bytes())
.as_ref()
.try_into()
.expect("SHA-256 is 32 bytes")
}
pub(crate) fn csrf_token(id: &str) -> String {
let made = digest(&SHA256, &[CSRF_DOMAIN, id.as_bytes()].concat());
URL_SAFE_NO_PAD.encode(made.as_ref())
}
pub(crate) fn same(one: &[u8], other: &[u8]) -> bool {
constant_time::verify_slices_are_equal(one, other).is_ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Cookie<'a> {
Absent,
Bad,
Id(&'a str),
}
pub(crate) fn cookie(headers: &HeaderMap) -> Cookie<'_> {
let mut found = Cookie::Absent;
for header in headers.get_all(COOKIE_HEADER) {
let Ok(text) = header.to_str() else {
return Cookie::Bad;
};
for pair in text.split(';') {
let Some((name, value)) = pair.trim().split_once('=') else {
continue;
};
if name != COOKIE {
continue;
}
if found != Cookie::Absent || !well_formed(value) {
return Cookie::Bad;
}
found = Cookie::Id(value);
}
}
found
}
#[must_use]
pub fn set_cookie(id: &str) -> HeaderValue {
HeaderValue::from_str(&format!("{COOKIE}={id}; {ATTRIBUTES}"))
.expect("a session id is visible ASCII")
}
pub(crate) fn clear_cookie() -> HeaderValue {
HeaderValue::from_str(&format!("{COOKIE}=; {ATTRIBUTES}; Max-Age=0"))
.expect("the cookie's name and attributes are visible ASCII")
}
fn one<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
let mut all = headers.get_all(name).iter();
match (all.next(), all.next()) {
(Some(value), None) => value.to_str().ok(),
_ => None,
}
}
pub(crate) fn from_origin(headers: &HeaderMap, origin: Option<&Origin>, hand_out: bool) -> bool {
let Some(origin) = origin else {
return false;
};
let equal = || one(headers, ORIGIN.as_str()) == Some(origin.as_str());
if hand_out {
one(headers, FETCH_SITE) == Some("same-origin")
&& (!headers.contains_key(ORIGIN) || equal())
} else {
equal()
}
}
pub(crate) fn amr_text(methods: &[&str]) -> Option<String> {
let good = |method: &&str| {
(1..=AMR_LONGEST).contains(&method.len())
&& method
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
};
let distinct = methods
.iter()
.enumerate()
.all(|(at, method)| !methods[..at].contains(method));
((1..=AMR_MOST).contains(&methods.len()) && methods.iter().all(good) && distinct)
.then(|| methods.join(" "))
}
#[cfg(test)]
mod tests;