Skip to main content

ch_auth/
session.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::fs;
4use std::io::{self, Write};
5use std::path::{Path, PathBuf};
6
7use axum_session::databases::SessionNullPool;
8use axum_session::{Key, SameSite, SessionConfig, SessionMode};
9use axum_session_auth::AuthSession as AxumAuthSession;
10use base64::Engine;
11use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
12use getrandom::fill;
13use thiserror::Error;
14use zeroize::Zeroizing;
15
16const SESSION_KEY_LENGTH: usize = 64;
17
18/// Secret key material used to sign and encrypt session cookies.
19///
20/// The wrapper deliberately does not expose the decoded bytes. Its backing
21/// allocation is cleared when it is dropped, including after
22/// [`build_session_config`] has transferred the material into `axum_session`.
23pub struct SessionKey(Zeroizing<Vec<u8>>);
24
25impl SessionKey {
26    /// Decodes an exactly 64-byte key from standard or URL-safe base64.
27    pub fn decode(encoded: &str) -> Result<Self, SessionKeyError> {
28        let encoded = encoded.trim();
29        let decoded = Zeroizing::new(
30            [STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD]
31                .into_iter()
32                .find_map(|engine| engine.decode(encoded).ok())
33                .ok_or(SessionKeyError::InvalidBase64)?,
34        );
35
36        if decoded.len() != SESSION_KEY_LENGTH {
37            return Err(SessionKeyError::InvalidLength {
38                actual: decoded.len(),
39            });
40        }
41
42        Ok(Self(decoded))
43    }
44
45    /// Loads the conventional `SESSION_KEY` value or its `SESSION_KEY_FILE`
46    /// companion.
47    ///
48    /// Non-debug builds require a persistent key. Debug builds generate a
49    /// process-local cryptographic key when neither source is configured, so
50    /// restarting the process invalidates its development sessions.
51    pub fn from_environment() -> Result<Self, SessionKeyEnvironmentError> {
52        resolve_session_key(
53            ch_config::environment::value("SESSION_KEY")?,
54            cfg!(debug_assertions),
55        )
56    }
57
58    /// Loads the configured key or persists one local development key at
59    /// `path` when no key is configured.
60    ///
61    /// Release builds never create key material and retain the same mandatory
62    /// `SESSION_KEY`/`SESSION_KEY_FILE` contract as [`Self::from_environment`].
63    pub fn from_environment_or_create_development(
64        path: impl AsRef<Path>,
65    ) -> Result<Self, SessionKeyEnvironmentError> {
66        match ch_config::environment::value("SESSION_KEY")? {
67            Some(encoded) => Ok(Self::decode(&encoded)?),
68            None if cfg!(debug_assertions) => load_or_create_development_key(path.as_ref()),
69            None => Err(SessionKeyEnvironmentError::Missing),
70        }
71    }
72
73    /// Generates a process-local key for explicitly ephemeral sessions.
74    pub fn generate_ephemeral() -> Result<Self, SessionKeyError> {
75        let mut bytes = Zeroizing::new(vec![0_u8; SESSION_KEY_LENGTH]);
76        fill(bytes.as_mut_slice()).map_err(SessionKeyError::Generation)?;
77        Ok(Self(bytes))
78    }
79}
80
81impl fmt::Debug for SessionKey {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.debug_tuple("SessionKey").field(&"[REDACTED]").finish()
84    }
85}
86
87/// Failure to decode or generate session key material.
88#[derive(Debug, Error)]
89pub enum SessionKeyError {
90    /// The configured value is not valid supported base64.
91    #[error("session key must be valid base64")]
92    InvalidBase64,
93    /// The decoded key does not have the required size.
94    #[error("session key must decode to exactly 64 bytes, got {actual}")]
95    InvalidLength {
96        /// Number of bytes produced by decoding the configured value.
97        actual: usize,
98    },
99    /// The operating system could not provide cryptographic randomness.
100    #[error("failed to generate an ephemeral session key")]
101    Generation(#[source] getrandom::Error),
102}
103
104/// Failure to load session key material from the process environment.
105#[derive(Debug, Error)]
106pub enum SessionKeyEnvironmentError {
107    /// The configured environment source could not be resolved safely.
108    #[error(transparent)]
109    Configuration(#[from] ch_config::config::ConfigError),
110    /// The configured or generated key material is invalid.
111    #[error(transparent)]
112    Key(#[from] SessionKeyError),
113    /// A local development key could not be read or persisted.
114    #[error("failed to access development session key at {path}")]
115    Persistence {
116        /// Path selected by the application for its local key.
117        path: PathBuf,
118        /// Filesystem failure returned by the operating system.
119        #[source]
120        source: io::Error,
121    },
122    /// A persistent key is mandatory outside debug builds.
123    #[error("SESSION_KEY or SESSION_KEY_FILE is required outside debug builds")]
124    Missing,
125}
126
127fn load_or_create_development_key(path: &Path) -> Result<SessionKey, SessionKeyEnvironmentError> {
128    match fs::read_to_string(path) {
129        Ok(encoded) => return Ok(SessionKey::decode(&encoded)?),
130        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
131        Err(source) => {
132            return Err(SessionKeyEnvironmentError::Persistence {
133                path: path.to_path_buf(),
134                source,
135            });
136        }
137    }
138
139    let key = SessionKey::generate_ephemeral()?;
140    let encoded = Zeroizing::new(STANDARD.encode(key.0.as_slice()));
141    let parent = path
142        .parent()
143        .filter(|parent| !parent.as_os_str().is_empty())
144        .unwrap_or_else(|| Path::new("."));
145    let persistence = |source| SessionKeyEnvironmentError::Persistence {
146        path: path.to_path_buf(),
147        source,
148    };
149    fs::create_dir_all(parent).map_err(persistence)?;
150    let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(persistence)?;
151    temporary
152        .write_all(encoded.as_bytes())
153        .map_err(persistence)?;
154    temporary.write_all(b"\n").map_err(persistence)?;
155    temporary.as_file().sync_all().map_err(persistence)?;
156    match temporary.persist_noclobber(path) {
157        Ok(_file) => Ok(key),
158        Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {
159            let encoded = fs::read_to_string(path).map_err(persistence)?;
160            Ok(SessionKey::decode(&encoded)?)
161        }
162        Err(error) => Err(persistence(error.error)),
163    }
164}
165
166fn resolve_session_key(
167    configured: Option<String>,
168    allow_ephemeral: bool,
169) -> Result<SessionKey, SessionKeyEnvironmentError> {
170    match configured {
171        Some(encoded) => Ok(SessionKey::decode(&encoded)?),
172        None if allow_ephemeral => {
173            tracing::warn!(
174                "SESSION_KEY is not configured; using an ephemeral development session key"
175            );
176            Ok(SessionKey::generate_ephemeral()?)
177        }
178        None => Err(SessionKeyEnvironmentError::Missing),
179    }
180}
181
182/// Explicit cookie policy for authenticated sessions.
183///
184/// There is intentionally no default implementation: each application owns
185/// its cookie name and transport policy.
186#[derive(Clone, Debug, Eq, PartialEq)]
187pub struct SessionPolicy {
188    cookie_name: Cow<'static, str>,
189    same_site: SameSite,
190    secure: bool,
191    http_only: bool,
192    path: Cow<'static, str>,
193}
194
195impl SessionPolicy {
196    /// Validates and constructs a complete session-cookie policy.
197    pub fn new(
198        cookie_name: impl Into<Cow<'static, str>>,
199        same_site: SameSite,
200        secure: bool,
201        http_only: bool,
202        path: impl Into<Cow<'static, str>>,
203    ) -> Result<Self, SessionPolicyError> {
204        let cookie_name = cookie_name.into();
205        let path = path.into();
206
207        if !is_cookie_name(cookie_name.as_ref()) {
208            return Err(SessionPolicyError::InvalidCookieName);
209        }
210        if !is_cookie_path(path.as_ref()) {
211            return Err(SessionPolicyError::InvalidCookiePath);
212        }
213        if same_site == SameSite::None && !secure {
214            return Err(SessionPolicyError::SameSiteNoneRequiresSecure);
215        }
216        if cookie_name.starts_with("__Secure-") && !secure {
217            return Err(SessionPolicyError::SecurePrefixRequiresSecure);
218        }
219        if cookie_name.starts_with("__Host-") && (!secure || path != "/") {
220            return Err(SessionPolicyError::HostPrefixRequiresSecureRootPath);
221        }
222
223        Ok(Self {
224            cookie_name,
225            same_site,
226            secure,
227            http_only,
228            path,
229        })
230    }
231
232    /// Returns the session cookie name.
233    pub fn cookie_name(&self) -> &str {
234        self.cookie_name.as_ref()
235    }
236
237    /// Returns the cookie's `SameSite` policy.
238    pub fn same_site(&self) -> SameSite {
239        self.same_site
240    }
241
242    /// Reports whether the cookie is restricted to secure transports.
243    pub fn secure(&self) -> bool {
244        self.secure
245    }
246
247    /// Reports whether browser scripts are denied cookie access.
248    pub fn http_only(&self) -> bool {
249        self.http_only
250    }
251
252    /// Returns the URL path to which the cookie is scoped.
253    pub fn path(&self) -> &str {
254        self.path.as_ref()
255    }
256}
257
258/// Failure to construct a valid session-cookie policy.
259#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
260pub enum SessionPolicyError {
261    /// The cookie name is empty or contains a forbidden separator/control.
262    #[error("session cookie name is invalid")]
263    InvalidCookieName,
264    /// The cookie path is not an absolute, header-safe path.
265    #[error("session cookie path must be absolute and header-safe")]
266    InvalidCookiePath,
267    /// Browsers require secure transport for `SameSite=None` cookies.
268    #[error("SameSite=None requires a secure session cookie")]
269    SameSiteNoneRequiresSecure,
270    /// The standard `__Secure-` prefix requires secure transport.
271    #[error("a __Secure- cookie name requires a secure session cookie")]
272    SecurePrefixRequiresSecure,
273    /// The standard `__Host-` prefix requires secure transport and root scope.
274    #[error("a __Host- cookie name requires a secure session cookie scoped to /")]
275    HostPrefixRequiresSecureRootPath,
276}
277
278/// Builds the shared Axum session configuration from application-owned inputs.
279pub fn build_session_config(policy: SessionPolicy, key: SessionKey) -> SessionConfig {
280    let key = Key::try_from(key.0.as_slice())
281        .expect("SessionKey guarantees exactly 64 bytes of key material");
282
283    SessionConfig::default()
284        .with_session_name(policy.cookie_name)
285        .with_cookie_path(policy.path)
286        .with_cookie_same_site(policy.same_site)
287        .with_secure(policy.secure)
288        .with_http_only(policy.http_only)
289        .with_mode(SessionMode::OptIn)
290        .with_max_age(None)
291        // Transport metadata is unstable for clients behind proxies. Cookie
292        // integrity is owned by the signing key instead.
293        .with_ip_and_user_agent(false)
294        .with_key(key)
295}
296
297fn is_cookie_name(value: &str) -> bool {
298    !value.is_empty()
299        && value.bytes().all(|byte| {
300            byte.is_ascii()
301                && !byte.is_ascii_control()
302                && !matches!(
303                    byte,
304                    b' ' | b'('
305                        | b')'
306                        | b'<'
307                        | b'>'
308                        | b'@'
309                        | b','
310                        | b';'
311                        | b':'
312                        | b'\\'
313                        | b'"'
314                        | b'/'
315                        | b'['
316                        | b']'
317                        | b'?'
318                        | b'='
319                        | b'{'
320                        | b'}'
321                )
322        })
323}
324
325fn is_cookie_path(value: &str) -> bool {
326    value.starts_with('/')
327        && value
328            .bytes()
329            .all(|byte| byte.is_ascii() && !byte.is_ascii_control() && byte != b';')
330}
331
332/// Authenticated Axum session using the application's selected session store.
333pub type AuthSession<User, Database, Sessions = SessionNullPool, Identifier = String> =
334    AxumAuthSession<User, Identifier, Sessions, Database>;
335
336#[cfg(test)]
337mod tests {
338    use axum_session::SameSite;
339    use base64::Engine;
340    use tempfile::tempdir;
341
342    use super::{
343        SessionKey, SessionKeyEnvironmentError, SessionKeyError, SessionPolicy, SessionPolicyError,
344        build_session_config, load_or_create_development_key, resolve_session_key,
345    };
346
347    #[test]
348    fn concurrent_development_startups_publish_one_complete_private_key() {
349        let directory = tempdir().expect("temporary key directory");
350        let path = directory.path().join("session-key");
351        let barrier = std::sync::Barrier::new(16);
352        let keys = std::thread::scope(|scope| {
353            let handles: Vec<_> = (0..16)
354                .map(|_| {
355                    scope.spawn(|| {
356                        barrier.wait();
357                        load_or_create_development_key(&path).expect("concurrent startup")
358                    })
359                })
360                .collect();
361            handles
362                .into_iter()
363                .map(|handle| handle.join().expect("startup thread"))
364                .collect::<Vec<_>>()
365        });
366        assert!(
367            keys.iter()
368                .all(|key| key.0.as_slice() == keys[0].0.as_slice())
369        );
370        assert_eq!(
371            std::fs::read_dir(directory.path())
372                .expect("list key directory")
373                .count(),
374            1
375        );
376        let encoded = std::fs::read_to_string(&path).expect("published key");
377        assert_eq!(
378            SessionKey::decode(&encoded)
379                .expect("complete key")
380                .0
381                .as_slice(),
382            keys[0].0.as_slice()
383        );
384    }
385
386    #[test]
387    fn invalid_existing_key_is_rejected_without_replacement() {
388        let directory = tempdir().expect("temporary key directory");
389        let path = directory.path().join("session-key");
390        std::fs::write(&path, "broken-key").expect("write invalid fixture");
391        assert!(load_or_create_development_key(&path).is_err());
392        assert_eq!(
393            std::fs::read_to_string(path).expect("original file"),
394            "broken-key"
395        );
396    }
397
398    #[test]
399    fn session_key_accepts_supported_base64_without_exposing_material() {
400        let encoded = base64::engine::general_purpose::STANDARD.encode([7_u8; 64]);
401        let key = SessionKey::decode(&encoded).expect("64-byte key should decode");
402
403        assert_eq!(format!("{key:?}"), "SessionKey(\"[REDACTED]\")");
404        assert!(matches!(
405            SessionKey::decode("not-base64"),
406            Err(SessionKeyError::InvalidBase64)
407        ));
408        assert!(matches!(
409            SessionKey::decode(
410                &base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9_u8; 32])
411            ),
412            Err(SessionKeyError::InvalidLength { actual: 32 })
413        ));
414    }
415
416    #[test]
417    fn environment_key_policy_requires_release_material_and_allows_debug_ephemeral_keys() {
418        assert!(matches!(
419            resolve_session_key(None, false),
420            Err(SessionKeyEnvironmentError::Missing)
421        ));
422        assert!(resolve_session_key(None, true).is_ok());
423
424        let encoded = base64::engine::general_purpose::STANDARD.encode([5_u8; 64]);
425        assert!(resolve_session_key(Some(encoded), false).is_ok());
426    }
427
428    #[test]
429    fn development_session_key_survives_process_restarts() {
430        let directory = tempdir().expect("temporary key directory should be created");
431        let path = directory.path().join("session-key");
432
433        let first = load_or_create_development_key(&path)
434            .expect("first startup should persist a session key");
435        let second = load_or_create_development_key(&path)
436            .expect("subsequent startup should reuse the session key");
437
438        assert_eq!(first.0.as_slice(), second.0.as_slice());
439        assert_eq!(
440            SessionKey::decode(
441                &std::fs::read_to_string(&path).expect("persisted key should remain readable")
442            )
443            .expect("persisted material should remain valid")
444            .0
445            .as_slice(),
446            first.0.as_slice()
447        );
448        #[cfg(unix)]
449        {
450            use std::os::unix::fs::PermissionsExt as _;
451            assert_eq!(
452                std::fs::metadata(path)
453                    .expect("persisted key metadata should be readable")
454                    .permissions()
455                    .mode()
456                    & 0o077,
457                0
458            );
459        }
460    }
461
462    #[test]
463    fn session_policy_validates_cookie_invariants() {
464        let policy = SessionPolicy::new("session", SameSite::Lax, false, true, "/")
465            .expect("common local policy should be valid");
466
467        assert_eq!(policy.cookie_name(), "session");
468        assert_eq!(policy.same_site(), SameSite::Lax);
469        assert!(!policy.secure());
470        assert!(policy.http_only());
471        assert_eq!(policy.path(), "/");
472        assert_eq!(
473            SessionPolicy::new("bad cookie", SameSite::Lax, false, true, "/"),
474            Err(SessionPolicyError::InvalidCookieName)
475        );
476        assert_eq!(
477            SessionPolicy::new("session", SameSite::Lax, false, true, "relative"),
478            Err(SessionPolicyError::InvalidCookiePath)
479        );
480        assert_eq!(
481            SessionPolicy::new("session", SameSite::None, false, true, "/"),
482            Err(SessionPolicyError::SameSiteNoneRequiresSecure)
483        );
484        assert_eq!(
485            SessionPolicy::new("__Host-session", SameSite::Lax, true, true, "/account"),
486            Err(SessionPolicyError::HostPrefixRequiresSecureRootPath)
487        );
488    }
489
490    #[test]
491    fn session_config_is_built_only_from_explicit_inputs() {
492        let policy = SessionPolicy::new("session", SameSite::Strict, true, true, "/")
493            .expect("test policy should be valid");
494        let key = SessionKey::decode(&base64::engine::general_purpose::STANDARD.encode([3_u8; 64]))
495            .expect("test key should decode");
496
497        let config = build_session_config(policy, key);
498        let debug = format!("{config:?}");
499
500        assert_eq!(config.get_session_name(), "session");
501        assert!(debug.contains("cookie_http_only: true"));
502        assert!(debug.contains("cookie_path: \"/\""));
503        assert!(debug.contains("cookie_same_site: Strict"));
504        assert!(debug.contains("cookie_secure: true"));
505        assert!(!debug.contains(&base64::engine::general_purpose::STANDARD.encode([3_u8; 64])));
506    }
507}