auth.rs
⎇
Raw
1use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
2use argon2::Argon2;
3
4pub const COOKIE_NAME: &str = "fbng_session";
5/// 30 days.
6pub const SESSION_MAX_AGE: u64 = 60 * 60 * 24 * 30;
7
8pub fn hash_password(password: &str) -> anyhow::Result<String> {
9 let salt = SaltString::generate(&mut rand::thread_rng());
10 let hash = Argon2::default()
11 .hash_password(password.as_bytes(), &salt)
12 .map_err(|e| anyhow::anyhow!("password hashing failed: {e}"))?;
13 Ok(hash.to_string())
14}
15
16pub fn verify_password(password: &str, hash: &str) -> bool {
17 let Ok(parsed) = PasswordHash::new(hash) else {
18 return false;
19 };
20 Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok()
21}
22
23/// 32 random bytes, hex-encoded (64 chars).
24pub fn random_token() -> String {
25 hex_token(32)
26}
27
28/// 16 random bytes, hex-encoded (32 chars). Used for public share links.
29pub fn share_token() -> String {
30 hex_token(16)
31}
32
33fn hex_token(bytes: usize) -> String {
34 use rand::RngCore;
35 let mut b = [0u8; 64];
36 rand::thread_rng().fill_bytes(&mut b[..bytes.min(64)]);
37 let mut s = String::with_capacity(bytes * 2);
38 for x in b[..bytes.min(64)].iter() {
39 s.push_str(&format!("{x:02x}"));
40 }
41 s
42}
43
44pub fn session_cookie(token: &str, https: bool) -> String {
45 let mut c = format!(
46 "{COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age={SESSION_MAX_AGE}"
47 );
48 if https {
49 c.push_str("; Secure");
50 }
51 c
52}
53
54pub fn clear_session_cookie(https: bool) -> String {
55 let mut c = format!("{COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
56 if https {
57 c.push_str("; Secure");
58 }
59 c
60}
61
62/// Extract the session token from the Cookie header, if present.
63pub fn parse_session_cookie(headers: &axum::http::HeaderMap) -> Option<String> {
64 let header = headers.get(axum::http::header::COOKIE)?.to_str().ok()?;
65 for part in header.split(';') {
66 let part = part.trim();
67 if let Some((k, v)) = part.split_once('=') {
68 if k == COOKIE_NAME && !v.is_empty() {
69 return Some(v.to_string());
70 }
71 }
72 }
73 None
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79 use axum::http::{header, HeaderMap};
80
81 #[test]
82 fn password_hash_round_trip() {
83 let h = hash_password("hunter22").unwrap();
84 assert!(verify_password("hunter22", &h));
85 assert!(!verify_password("wrong-password", &h));
86 assert!(!verify_password("hunter23", &h));
87 // Fresh salt on every hash.
88 assert_ne!(h, hash_password("hunter22").unwrap());
89 // Argon2id marker is present.
90 assert!(h.starts_with("$argon2id$"));
91 }
92
93 #[test]
94 fn verify_rejects_garbage_hashes() {
95 assert!(!verify_password("x", ""));
96 assert!(!verify_password("x", "not-a-hash"));
97 assert!(!verify_password("x", "$argon2id$"));
98 }
99
100 #[test]
101 fn token_shapes_and_uniqueness() {
102 let t = random_token();
103 assert_eq!(t.len(), 64);
104 assert!(t.chars().all(|c| c.is_ascii_hexdigit()));
105
106 let s = share_token();
107 assert_eq!(s.len(), 32);
108 assert!(s.chars().all(|c| c.is_ascii_hexdigit()));
109
110 let mut seen = std::collections::HashSet::new();
111 for _ in 0..100 {
112 assert!(seen.insert(random_token()), "session token collision");
113 assert!(seen.insert(share_token()), "share token collision");
114 }
115 }
116
117 #[test]
118 fn session_cookie_shape() {
119 let c = session_cookie("tok123", false);
120 assert!(c.starts_with("fbng_session=tok123;"));
121 assert!(c.contains("Path=/"));
122 assert!(c.contains("HttpOnly"));
123 assert!(c.contains("SameSite=Lax"));
124 assert!(c.contains(&format!("Max-Age={SESSION_MAX_AGE}")));
125 assert!(!c.contains("Secure"));
126
127 let c = session_cookie("tok123", true);
128 assert!(c.ends_with("; Secure"));
129
130 let c = clear_session_cookie(true);
131 assert!(c.starts_with("fbng_session=;"));
132 assert!(c.contains("Max-Age=0"));
133 assert!(c.contains("Secure"));
134 assert!(!clear_session_cookie(false).contains("Secure"));
135 }
136
137 #[test]
138 fn parse_session_cookie_variants() {
139 let mut h = HeaderMap::new();
140 h.insert(header::COOKIE, "other=1; fbng_session=abc123; x=y".parse().unwrap());
141 assert_eq!(parse_session_cookie(&h).as_deref(), Some("abc123"));
142
143 let mut h = HeaderMap::new();
144 h.insert(header::COOKIE, "other=1".parse().unwrap());
145 assert_eq!(parse_session_cookie(&h), None);
146
147 // Empty value → treated as absent.
148 let mut h = HeaderMap::new();
149 h.insert(header::COOKIE, "fbng_session=".parse().unwrap());
150 assert_eq!(parse_session_cookie(&h), None);
151
152 assert_eq!(parse_session_cookie(&HeaderMap::new()), None);
153
154 // First occurrence wins.
155 let mut h = HeaderMap::new();
156 h.insert(
157 header::COOKIE,
158 "fbng_session=first; fbng_session=second".parse().unwrap(),
159 );
160 assert_eq!(parse_session_cookie(&h).as_deref(), Some("first"));
161
162 // Cookie name must match exactly.
163 let mut h = HeaderMap::new();
164 h.insert(header::COOKIE, "fbng_session2=x; Xfbng_session=y".parse().unwrap());
165 assert_eq!(parse_session_cookie(&h), None);
166 }
167}
168