use std::time::Duration;
use axum::http::{HeaderMap, HeaderValue, header};
use cookie::Cookie;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
result::{ClassifyError, ErrorCode, ErrorKind},
secret::SecretString,
};
pub use cookie::SameSite;
pub const MAX_COOKIE_HEADER_BYTES: usize = 4096;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CookieOptions {
pub path: String,
pub domain: Option<String>,
pub secure: bool,
pub http_only: bool,
#[serde(with = "SameSiteSerde")]
pub same_site: SameSite,
#[serde(with = "crate::settings::human_duration::option")]
pub max_age: Option<Duration>,
pub partitioned: bool,
}
impl Default for CookieOptions {
fn default() -> Self {
Self {
path: "/".to_owned(),
domain: None,
secure: true,
http_only: true,
same_site: SameSite::Lax,
max_age: None,
partitioned: false,
}
}
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "SameSite", rename_all = "lowercase")]
enum SameSiteSerde {
Strict,
Lax,
None,
}
impl CookieOptions {
pub fn build(self, name: impl Into<String>) -> Result<CookiePolicy, CookieError> {
let name = name.into();
if !valid_name(&name) {
return Err(CookieError::InvalidName);
}
if !self.path.starts_with('/')
|| self.path.len() > 1024
|| !self
.path
.bytes()
.all(|byte| byte.is_ascii_graphic() && byte != b';')
{
return Err(CookieError::InvalidPath);
}
if self
.domain
.as_deref()
.is_some_and(|domain| !valid_domain(domain))
{
return Err(CookieError::InvalidDomain);
}
if self.same_site == SameSite::None && !self.secure {
return Err(CookieError::InsecureSameSiteNone);
}
if self.partitioned && !self.secure {
return Err(CookieError::InsecurePartitioned);
}
let host_prefix = has_prefix(&name, "__Host-");
let http_prefix = has_prefix(&name, "__Http-") || has_prefix(&name, "__Host-Http-");
if (host_prefix || http_prefix || has_prefix(&name, "__Secure-")) && !self.secure {
return Err(CookieError::InsecurePrefix);
}
if host_prefix && (self.path != "/" || self.domain.is_some()) {
return Err(CookieError::InvalidHostPrefix);
}
if http_prefix && !self.http_only {
return Err(CookieError::NonHttpOnlyPrefix);
}
let max_age = self
.max_age
.map(|age| {
if age.is_zero() || age.subsec_nanos() != 0 {
return Err(CookieError::InvalidMaxAge);
}
i64::try_from(age.as_secs())
.map(cookie::time::Duration::seconds)
.map_err(|_| CookieError::InvalidMaxAge)
})
.transpose()?;
let mut template = Cookie::new(name, "");
template.set_path(self.path);
if let Some(domain) = self.domain {
template.set_domain(domain.to_ascii_lowercase());
}
template.set_secure(self.secure);
template.set_http_only(self.http_only);
template.set_same_site(self.same_site);
template.set_partitioned(self.partitioned);
template.set_max_age(max_age);
let empty_header = render(&template)?;
let mut removal = template.clone();
removal.set_max_age(cookie::time::Duration::ZERO);
removal.set_expires(cookie::time::OffsetDateTime::UNIX_EPOCH);
let removal = render(&removal)?;
Ok(CookiePolicy {
template,
removal,
max_value_bytes: MAX_COOKIE_HEADER_BYTES - empty_header.as_bytes().len(),
})
}
}
#[derive(Clone, Debug)]
pub struct CookiePolicy {
template: Cookie<'static>,
removal: HeaderValue,
max_value_bytes: usize,
}
impl CookiePolicy {
#[must_use]
pub fn name(&self) -> &str {
self.template.name()
}
pub fn set(&self, value: &str) -> Result<HeaderValue, CookieError> {
if value.len() > self.max_value_bytes {
return Err(CookieError::TooLarge);
}
if !valid_value(value) {
return Err(CookieError::InvalidValue);
}
let mut cookie = self.template.clone();
cookie.set_value(value);
render(&cookie)
}
#[must_use]
pub fn remove(&self) -> HeaderValue {
self.removal.clone()
}
pub fn read(&self, headers: &HeaderMap) -> Result<Option<SecretString>, CookieError> {
let mut value = None;
for header in headers.get_all(header::COOKIE) {
let text = header.to_str().map_err(|_| CookieError::MalformedRequest)?;
for parsed in Cookie::split_parse(text) {
let parsed = parsed.map_err(|_| CookieError::MalformedRequest)?;
let raw = parsed.value_trimmed();
if !valid_name(parsed.name()) || !valid_value(raw) {
return Err(CookieError::MalformedRequest);
}
if parsed.name() != self.name() {
continue;
}
if value.is_some() {
return Err(CookieError::Duplicate);
}
if self.name().len() + raw.len() > MAX_COOKIE_HEADER_BYTES {
return Err(CookieError::TooLarge);
}
value = Some(SecretString::new(raw));
}
}
Ok(value)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum CookieError {
#[error("cookie name must be a nonempty HTTP token")]
InvalidName,
#[error(
"cookie path must be absolute ASCII, at most 1024 bytes, without whitespace or semicolons"
)]
InvalidPath,
#[error(
"cookie domain must be an ASCII DNS name without dots at its ends, ports, or IP addresses"
)]
InvalidDomain,
#[error("cookie max_age must be a positive whole number of seconds fitting in i64")]
InvalidMaxAge,
#[error("SameSite=None requires Secure")]
InsecureSameSiteNone,
#[error("Partitioned requires Secure")]
InsecurePartitioned,
#[error("cookie name prefix requires Secure")]
InsecurePrefix,
#[error("host-prefixed cookies require Path=/ and no Domain")]
InvalidHostPrefix,
#[error("HTTP-prefixed cookies require HttpOnly")]
NonHttpOnlyPrefix,
#[error("cookie exceeds the supported size limit")]
TooLarge,
#[error("cookie value contains invalid bytes")]
InvalidValue,
#[error("malformed Cookie request header")]
MalformedRequest,
#[error("ambiguous duplicate cookie")]
Duplicate,
}
impl ClassifyError for CookieError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal(match self {
Self::InvalidName => "cookie_invalid_name",
Self::InvalidPath => "cookie_invalid_path",
Self::InvalidDomain => "cookie_invalid_domain",
Self::InvalidMaxAge => "cookie_invalid_max_age",
Self::InsecureSameSiteNone => "cookie_insecure_same_site_none",
Self::InsecurePartitioned => "cookie_insecure_partitioned",
Self::InsecurePrefix => "cookie_insecure_prefix",
Self::InvalidHostPrefix => "cookie_invalid_host_prefix",
Self::NonHttpOnlyPrefix => "cookie_non_http_only_prefix",
Self::TooLarge => "cookie_too_large",
Self::InvalidValue => "cookie_invalid_value",
Self::MalformedRequest => "cookie_malformed_request",
Self::Duplicate => "cookie_duplicate",
})
}
}
fn render(cookie: &Cookie<'_>) -> Result<HeaderValue, CookieError> {
let encoded = cookie.to_string();
if encoded.len() > MAX_COOKIE_HEADER_BYTES {
return Err(CookieError::TooLarge);
}
let mut header = HeaderValue::try_from(encoded).map_err(|_| CookieError::InvalidValue)?;
header.set_sensitive(true);
Ok(header)
}
fn valid_name(name: &str) -> bool {
!name.is_empty()
&& name.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
)
})
}
fn valid_value(value: &str) -> bool {
value
.bytes()
.all(|byte| matches!(byte, 0x21 | 0x23..=0x2b | 0x2d..=0x3a | 0x3c..=0x5b | 0x5d..=0x7e))
}
fn valid_domain(domain: &str) -> bool {
!domain.is_empty()
&& domain.len() <= 253
&& domain.parse::<std::net::IpAddr>().is_err()
&& domain.split('.').all(|label| {
let bytes = label.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 63
&& bytes[0].is_ascii_alphanumeric()
&& bytes[bytes.len() - 1].is_ascii_alphanumeric()
&& bytes
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
})
}
fn has_prefix(name: &str, prefix: &str) -> bool {
name.get(..prefix.len())
.is_some_and(|start| start.eq_ignore_ascii_case(prefix))
}