use std::borrow::Cow;
use std::fmt;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
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 from_environment_or_create_development(
path: impl AsRef<Path>,
) -> Result<Self, SessionKeyEnvironmentError> {
match ch_config::environment::value("SESSION_KEY")? {
Some(encoded) => Ok(Self::decode(&encoded)?),
None if cfg!(debug_assertions) => load_or_create_development_key(path.as_ref()),
None => Err(SessionKeyEnvironmentError::Missing),
}
}
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("failed to access development session key at {path}")]
Persistence {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("SESSION_KEY or SESSION_KEY_FILE is required outside debug builds")]
Missing,
}
fn load_or_create_development_key(path: &Path) -> Result<SessionKey, SessionKeyEnvironmentError> {
match fs::read_to_string(path) {
Ok(encoded) => return Ok(SessionKey::decode(&encoded)?),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(source) => {
return Err(SessionKeyEnvironmentError::Persistence {
path: path.to_path_buf(),
source,
});
}
}
let key = SessionKey::generate_ephemeral()?;
let encoded = Zeroizing::new(STANDARD.encode(key.0.as_slice()));
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let persistence = |source| SessionKeyEnvironmentError::Persistence {
path: path.to_path_buf(),
source,
};
fs::create_dir_all(parent).map_err(persistence)?;
let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(persistence)?;
temporary
.write_all(encoded.as_bytes())
.map_err(persistence)?;
temporary.write_all(b"\n").map_err(persistence)?;
temporary.as_file().sync_all().map_err(persistence)?;
match temporary.persist_noclobber(path) {
Ok(_file) => Ok(key),
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {
let encoded = fs::read_to_string(path).map_err(persistence)?;
Ok(SessionKey::decode(&encoded)?)
}
Err(error) => Err(persistence(error.error)),
}
}
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, Sessions = SessionNullPool, Identifier = String> =
AxumAuthSession<User, Identifier, Sessions, Database>;
#[cfg(test)]
mod tests {
use axum_session::SameSite;
use base64::Engine;
use tempfile::tempdir;
use super::{
SessionKey, SessionKeyEnvironmentError, SessionKeyError, SessionPolicy, SessionPolicyError,
build_session_config, load_or_create_development_key, resolve_session_key,
};
#[test]
fn concurrent_development_startups_publish_one_complete_private_key() {
let directory = tempdir().expect("temporary key directory");
let path = directory.path().join("session-key");
let barrier = std::sync::Barrier::new(16);
let keys = std::thread::scope(|scope| {
let handles: Vec<_> = (0..16)
.map(|_| {
scope.spawn(|| {
barrier.wait();
load_or_create_development_key(&path).expect("concurrent startup")
})
})
.collect();
handles
.into_iter()
.map(|handle| handle.join().expect("startup thread"))
.collect::<Vec<_>>()
});
assert!(
keys.iter()
.all(|key| key.0.as_slice() == keys[0].0.as_slice())
);
assert_eq!(
std::fs::read_dir(directory.path())
.expect("list key directory")
.count(),
1
);
let encoded = std::fs::read_to_string(&path).expect("published key");
assert_eq!(
SessionKey::decode(&encoded)
.expect("complete key")
.0
.as_slice(),
keys[0].0.as_slice()
);
}
#[test]
fn invalid_existing_key_is_rejected_without_replacement() {
let directory = tempdir().expect("temporary key directory");
let path = directory.path().join("session-key");
std::fs::write(&path, "broken-key").expect("write invalid fixture");
assert!(load_or_create_development_key(&path).is_err());
assert_eq!(
std::fs::read_to_string(path).expect("original file"),
"broken-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 development_session_key_survives_process_restarts() {
let directory = tempdir().expect("temporary key directory should be created");
let path = directory.path().join("session-key");
let first = load_or_create_development_key(&path)
.expect("first startup should persist a session key");
let second = load_or_create_development_key(&path)
.expect("subsequent startup should reuse the session key");
assert_eq!(first.0.as_slice(), second.0.as_slice());
assert_eq!(
SessionKey::decode(
&std::fs::read_to_string(&path).expect("persisted key should remain readable")
)
.expect("persisted material should remain valid")
.0
.as_slice(),
first.0.as_slice()
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
assert_eq!(
std::fs::metadata(path)
.expect("persisted key metadata should be readable")
.permissions()
.mode()
& 0o077,
0
);
}
}
#[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])));
}
}