ch-auth 0.3.2

Authentication and session primitives with explicit security policies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
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;

/// Secret key material used to sign and encrypt session cookies.
///
/// The wrapper deliberately does not expose the decoded bytes. Its backing
/// allocation is cleared when it is dropped, including after
/// [`build_session_config`] has transferred the material into `axum_session`.
pub struct SessionKey(Zeroizing<Vec<u8>>);

impl SessionKey {
    /// Decodes an exactly 64-byte key from standard or URL-safe base64.
    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))
    }

    /// Loads the conventional `SESSION_KEY` value or its `SESSION_KEY_FILE`
    /// companion.
    ///
    /// Non-debug builds require a persistent key. Debug builds generate a
    /// process-local cryptographic key when neither source is configured, so
    /// restarting the process invalidates its development sessions.
    pub fn from_environment() -> Result<Self, SessionKeyEnvironmentError> {
        resolve_session_key(
            ch_config::environment::value("SESSION_KEY")?,
            cfg!(debug_assertions),
        )
    }

    /// Loads the configured key or persists one local development key at
    /// `path` when no key is configured.
    ///
    /// Release builds never create key material and retain the same mandatory
    /// `SESSION_KEY`/`SESSION_KEY_FILE` contract as [`Self::from_environment`].
    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),
        }
    }

    /// Generates a process-local key for explicitly ephemeral sessions.
    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()
    }
}

/// Failure to decode or generate session key material.
#[derive(Debug, Error)]
pub enum SessionKeyError {
    /// The configured value is not valid supported base64.
    #[error("session key must be valid base64")]
    InvalidBase64,
    /// The decoded key does not have the required size.
    #[error("session key must decode to exactly 64 bytes, got {actual}")]
    InvalidLength {
        /// Number of bytes produced by decoding the configured value.
        actual: usize,
    },
    /// The operating system could not provide cryptographic randomness.
    #[error("failed to generate an ephemeral session key")]
    Generation(#[source] getrandom::Error),
}

/// Failure to load session key material from the process environment.
#[derive(Debug, Error)]
pub enum SessionKeyEnvironmentError {
    /// The configured environment source could not be resolved safely.
    #[error(transparent)]
    Configuration(#[from] ch_config::config::ConfigError),
    /// The configured or generated key material is invalid.
    #[error(transparent)]
    Key(#[from] SessionKeyError),
    /// A local development key could not be read or persisted.
    #[error("failed to access development session key at {path}")]
    Persistence {
        /// Path selected by the application for its local key.
        path: PathBuf,
        /// Filesystem failure returned by the operating system.
        #[source]
        source: io::Error,
    },
    /// A persistent key is mandatory outside debug builds.
    #[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),
    }
}

/// Explicit cookie policy for authenticated sessions.
///
/// There is intentionally no default implementation: each application owns
/// its cookie name and transport policy.
#[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 {
    /// Validates and constructs a complete session-cookie policy.
    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,
        })
    }

    /// Returns the session cookie name.
    pub fn cookie_name(&self) -> &str {
        self.cookie_name.as_ref()
    }

    /// Returns the cookie's `SameSite` policy.
    pub fn same_site(&self) -> SameSite {
        self.same_site
    }

    /// Reports whether the cookie is restricted to secure transports.
    pub fn secure(&self) -> bool {
        self.secure
    }

    /// Reports whether browser scripts are denied cookie access.
    pub fn http_only(&self) -> bool {
        self.http_only
    }

    /// Returns the URL path to which the cookie is scoped.
    pub fn path(&self) -> &str {
        self.path.as_ref()
    }
}

/// Failure to construct a valid session-cookie policy.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
pub enum SessionPolicyError {
    /// The cookie name is empty or contains a forbidden separator/control.
    #[error("session cookie name is invalid")]
    InvalidCookieName,
    /// The cookie path is not an absolute, header-safe path.
    #[error("session cookie path must be absolute and header-safe")]
    InvalidCookiePath,
    /// Browsers require secure transport for `SameSite=None` cookies.
    #[error("SameSite=None requires a secure session cookie")]
    SameSiteNoneRequiresSecure,
    /// The standard `__Secure-` prefix requires secure transport.
    #[error("a __Secure- cookie name requires a secure session cookie")]
    SecurePrefixRequiresSecure,
    /// The standard `__Host-` prefix requires secure transport and root scope.
    #[error("a __Host- cookie name requires a secure session cookie scoped to /")]
    HostPrefixRequiresSecureRootPath,
}

/// Builds the shared Axum session configuration from application-owned inputs.
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)
        // Transport metadata is unstable for clients behind proxies. Cookie
        // integrity is owned by the signing key instead.
        .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';')
}

/// Authenticated Axum session using the application's selected session store.
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])));
    }
}