use std::borrow::Cow;
use std::fmt;
use axum_session::databases::SessionNullPool;
use axum_session::{Key, SameSite, SessionConfig, SessionMode};
use axum_session_auth::AuthSession as AxumAuthSession;
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
use getrandom::fill;
use thiserror::Error;
use zeroize::Zeroizing;
const SESSION_KEY_LENGTH: usize = 64;
pub struct SessionKey(Zeroizing<Vec<u8>>);
impl SessionKey {
pub fn decode(encoded: &str) -> Result<Self, SessionKeyError> {
let encoded = encoded.trim();
let decoded = Zeroizing::new(
[STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD]
.into_iter()
.find_map(|engine| engine.decode(encoded).ok())
.ok_or(SessionKeyError::InvalidBase64)?,
);
if decoded.len() != SESSION_KEY_LENGTH {
return Err(SessionKeyError::InvalidLength {
actual: decoded.len(),
});
}
Ok(Self(decoded))
}
pub fn from_environment() -> Result<Self, SessionKeyEnvironmentError> {
resolve_session_key(
ch_config::environment::value("SESSION_KEY")?,
cfg!(debug_assertions),
)
}
pub fn generate_ephemeral() -> Result<Self, SessionKeyError> {
let mut bytes = Zeroizing::new(vec![0_u8; SESSION_KEY_LENGTH]);
fill(bytes.as_mut_slice()).map_err(SessionKeyError::Generation)?;
Ok(Self(bytes))
}
}
impl fmt::Debug for SessionKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("SessionKey").field(&"[REDACTED]").finish()
}
}
#[derive(Debug, Error)]
pub enum SessionKeyError {
#[error("session key must be valid base64")]
InvalidBase64,
#[error("session key must decode to exactly 64 bytes, got {actual}")]
InvalidLength {
actual: usize,
},
#[error("failed to generate an ephemeral session key")]
Generation(#[source] getrandom::Error),
}
#[derive(Debug, Error)]
pub enum SessionKeyEnvironmentError {
#[error(transparent)]
Configuration(#[from] ch_config::config::ConfigError),
#[error(transparent)]
Key(#[from] SessionKeyError),
#[error("SESSION_KEY or SESSION_KEY_FILE is required outside debug builds")]
Missing,
}
fn resolve_session_key(
configured: Option<String>,
allow_ephemeral: bool,
) -> Result<SessionKey, SessionKeyEnvironmentError> {
match configured {
Some(encoded) => Ok(SessionKey::decode(&encoded)?),
None if allow_ephemeral => {
tracing::warn!(
"SESSION_KEY is not configured; using an ephemeral development session key"
);
Ok(SessionKey::generate_ephemeral()?)
}
None => Err(SessionKeyEnvironmentError::Missing),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionPolicy {
cookie_name: Cow<'static, str>,
same_site: SameSite,
secure: bool,
http_only: bool,
path: Cow<'static, str>,
}
impl SessionPolicy {
pub fn new(
cookie_name: impl Into<Cow<'static, str>>,
same_site: SameSite,
secure: bool,
http_only: bool,
path: impl Into<Cow<'static, str>>,
) -> Result<Self, SessionPolicyError> {
let cookie_name = cookie_name.into();
let path = path.into();
if !is_cookie_name(cookie_name.as_ref()) {
return Err(SessionPolicyError::InvalidCookieName);
}
if !is_cookie_path(path.as_ref()) {
return Err(SessionPolicyError::InvalidCookiePath);
}
if same_site == SameSite::None && !secure {
return Err(SessionPolicyError::SameSiteNoneRequiresSecure);
}
if cookie_name.starts_with("__Secure-") && !secure {
return Err(SessionPolicyError::SecurePrefixRequiresSecure);
}
if cookie_name.starts_with("__Host-") && (!secure || path != "/") {
return Err(SessionPolicyError::HostPrefixRequiresSecureRootPath);
}
Ok(Self {
cookie_name,
same_site,
secure,
http_only,
path,
})
}
pub fn cookie_name(&self) -> &str {
self.cookie_name.as_ref()
}
pub fn same_site(&self) -> SameSite {
self.same_site
}
pub fn secure(&self) -> bool {
self.secure
}
pub fn http_only(&self) -> bool {
self.http_only
}
pub fn path(&self) -> &str {
self.path.as_ref()
}
}
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
pub enum SessionPolicyError {
#[error("session cookie name is invalid")]
InvalidCookieName,
#[error("session cookie path must be absolute and header-safe")]
InvalidCookiePath,
#[error("SameSite=None requires a secure session cookie")]
SameSiteNoneRequiresSecure,
#[error("a __Secure- cookie name requires a secure session cookie")]
SecurePrefixRequiresSecure,
#[error("a __Host- cookie name requires a secure session cookie scoped to /")]
HostPrefixRequiresSecureRootPath,
}
pub fn build_session_config(policy: SessionPolicy, key: SessionKey) -> SessionConfig {
let key = Key::try_from(key.0.as_slice())
.expect("SessionKey guarantees exactly 64 bytes of key material");
SessionConfig::default()
.with_session_name(policy.cookie_name)
.with_cookie_path(policy.path)
.with_cookie_same_site(policy.same_site)
.with_secure(policy.secure)
.with_http_only(policy.http_only)
.with_mode(SessionMode::OptIn)
.with_max_age(None)
.with_ip_and_user_agent(false)
.with_key(key)
}
fn is_cookie_name(value: &str) -> bool {
!value.is_empty()
&& value.bytes().all(|byte| {
byte.is_ascii()
&& !byte.is_ascii_control()
&& !matches!(
byte,
b' ' | b'('
| b')'
| b'<'
| b'>'
| b'@'
| b','
| b';'
| b':'
| b'\\'
| b'"'
| b'/'
| b'['
| b']'
| b'?'
| b'='
| b'{'
| b'}'
)
})
}
fn is_cookie_path(value: &str) -> bool {
value.starts_with('/')
&& value
.bytes()
.all(|byte| byte.is_ascii() && !byte.is_ascii_control() && byte != b';')
}
pub type AuthSession<User, Database> = AxumAuthSession<User, String, SessionNullPool, Database>;
#[cfg(test)]
mod tests {
use axum_session::SameSite;
use base64::Engine;
use super::{
SessionKey, SessionKeyEnvironmentError, SessionKeyError, SessionPolicy, SessionPolicyError,
build_session_config, resolve_session_key,
};
#[test]
fn session_key_accepts_supported_base64_without_exposing_material() {
let encoded = base64::engine::general_purpose::STANDARD.encode([7_u8; 64]);
let key = SessionKey::decode(&encoded).expect("64-byte key should decode");
assert_eq!(format!("{key:?}"), "SessionKey(\"[REDACTED]\")");
assert!(matches!(
SessionKey::decode("not-base64"),
Err(SessionKeyError::InvalidBase64)
));
assert!(matches!(
SessionKey::decode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9_u8; 32])
),
Err(SessionKeyError::InvalidLength { actual: 32 })
));
}
#[test]
fn environment_key_policy_requires_release_material_and_allows_debug_ephemeral_keys() {
assert!(matches!(
resolve_session_key(None, false),
Err(SessionKeyEnvironmentError::Missing)
));
assert!(resolve_session_key(None, true).is_ok());
let encoded = base64::engine::general_purpose::STANDARD.encode([5_u8; 64]);
assert!(resolve_session_key(Some(encoded), false).is_ok());
}
#[test]
fn session_policy_validates_cookie_invariants() {
let policy = SessionPolicy::new("session", SameSite::Lax, false, true, "/")
.expect("common local policy should be valid");
assert_eq!(policy.cookie_name(), "session");
assert_eq!(policy.same_site(), SameSite::Lax);
assert!(!policy.secure());
assert!(policy.http_only());
assert_eq!(policy.path(), "/");
assert_eq!(
SessionPolicy::new("bad cookie", SameSite::Lax, false, true, "/"),
Err(SessionPolicyError::InvalidCookieName)
);
assert_eq!(
SessionPolicy::new("session", SameSite::Lax, false, true, "relative"),
Err(SessionPolicyError::InvalidCookiePath)
);
assert_eq!(
SessionPolicy::new("session", SameSite::None, false, true, "/"),
Err(SessionPolicyError::SameSiteNoneRequiresSecure)
);
assert_eq!(
SessionPolicy::new("__Host-session", SameSite::Lax, true, true, "/account"),
Err(SessionPolicyError::HostPrefixRequiresSecureRootPath)
);
}
#[test]
fn session_config_is_built_only_from_explicit_inputs() {
let policy = SessionPolicy::new("session", SameSite::Strict, true, true, "/")
.expect("test policy should be valid");
let key = SessionKey::decode(&base64::engine::general_purpose::STANDARD.encode([3_u8; 64]))
.expect("test key should decode");
let config = build_session_config(policy, key);
let debug = format!("{config:?}");
assert_eq!(config.get_session_name(), "session");
assert!(debug.contains("cookie_http_only: true"));
assert!(debug.contains("cookie_path: \"/\""));
assert!(debug.contains("cookie_same_site: Strict"));
assert!(debug.contains("cookie_secure: true"));
assert!(!debug.contains(&base64::engine::general_purpose::STANDARD.encode([3_u8; 64])));
}
}