1use std::fmt::Write as _;
30use std::time::{Duration, SystemTime};
31
32use base64::Engine as _;
33use base64::engine::general_purpose::URL_SAFE_NO_PAD;
34use http::HeaderMap;
35use http::header::{COOKIE, HeaderValue, SET_COOKIE};
36use subtle::ConstantTimeEq;
37
38pub const DEFAULT_CSRF_COOKIE: &str = "csrf_token";
40
41pub const DEFAULT_CSRF_HEADER: &str = "X-CSRF-Token";
43
44#[derive(Debug, thiserror::Error)]
46pub enum Error {
47 #[error("cookieutil: invalid cookie name {0:?}")]
49 InvalidName(String),
50 #[error("cookieutil: invalid cookie attribute {0:?}")]
52 InvalidAttribute(String),
53 #[error("cookieutil: generate csrf token: {0}")]
55 Random(String),
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum SameSite {
61 #[default]
63 Lax,
64 Strict,
66 None,
68}
69
70impl SameSite {
71 fn as_str(self) -> &'static str {
72 match self {
73 SameSite::Lax => "Lax",
74 SameSite::Strict => "Strict",
75 SameSite::None => "None",
76 }
77 }
78}
79
80#[derive(Debug, Clone, Default, PartialEq, Eq)]
82pub struct Options {
83 pub domain: String,
85 pub path: String,
87 pub secure: bool,
89 pub same_site: SameSite,
91 pub max_age: Option<Duration>,
93}
94
95pub fn set_auth(headers: &mut HeaderMap, name: &str, value: &str, opts: &Options) -> Result<(), Error> {
97 append(
98 headers,
99 name,
100 value,
101 opts,
102 true,
103 opts.max_age.filter(|d| d.as_secs() > 0).map(Expiry::After),
104 )
105}
106
107pub fn clear(headers: &mut HeaderMap, name: &str, opts: &Options) -> Result<(), Error> {
109 append(headers, name, "", opts, true, Some(Expiry::Expired))
110}
111
112pub fn new_csrf_token() -> Result<String, Error> {
114 let mut buf = [0u8; 32];
115 getrandom::fill(&mut buf).map_err(|e| Error::Random(e.to_string()))?;
116 Ok(URL_SAFE_NO_PAD.encode(buf))
117}
118
119pub fn set_csrf(headers: &mut HeaderMap, token: &str, opts: &Options) -> Result<(), Error> {
122 append(
123 headers,
124 DEFAULT_CSRF_COOKIE,
125 token,
126 opts,
127 false,
128 opts.max_age.filter(|d| d.as_secs() > 0).map(Expiry::After),
129 )
130}
131
132pub fn validate_csrf(headers: &HeaderMap) -> bool {
134 validate_csrf_names(headers, DEFAULT_CSRF_COOKIE, DEFAULT_CSRF_HEADER)
135}
136
137pub fn validate_csrf_names(headers: &HeaderMap, cookie_name: &str, header_name: &str) -> bool {
139 let Some(cookie) = cookie_value(headers, cookie_name).filter(|v| !v.is_empty()) else {
140 return false;
141 };
142 let Some(header) = headers
143 .get(header_name)
144 .map(HeaderValue::as_bytes)
145 .filter(|v| !v.is_empty())
146 else {
147 return false;
148 };
149 cookie.as_bytes().ct_eq(header).into()
150}
151
152pub fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
154 headers
155 .get_all(COOKIE)
156 .iter()
157 .filter_map(|v| v.to_str().ok())
158 .flat_map(|v| v.split(';'))
159 .filter_map(|pair| pair.split_once('='))
160 .map(|(k, v)| (k.trim(), v.trim()))
161 .find(|(k, _)| *k == name)
162 .map(|(_, v)| v.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(v))
163}
164
165enum Expiry {
166 After(Duration),
167 Expired,
168}
169
170fn append(
171 headers: &mut HeaderMap,
172 name: &str,
173 value: &str,
174 opts: &Options,
175 http_only: bool,
176 expiry: Option<Expiry>,
177) -> Result<(), Error> {
178 if name.is_empty() || !name.bytes().all(is_token_byte) {
179 return Err(Error::InvalidName(name.to_owned()));
180 }
181 let path = if opts.path.is_empty() { "/" } else { opts.path.as_str() };
182 for attr in [path, opts.domain.as_str()] {
183 if attr.bytes().any(|b| b == b';' || !(0x20..0x7f).contains(&b)) {
184 return Err(Error::InvalidAttribute(attr.to_owned()));
185 }
186 }
187
188 let mut s = format!("{name}={}", sanitize_value(value));
189 let _ = write!(s, "; Path={path}");
190 if !opts.domain.is_empty() {
191 let _ = write!(s, "; Domain={}", opts.domain.trim_start_matches('.'));
192 }
193 match expiry {
194 Some(Expiry::After(d)) => {
195 let expires = SystemTime::now() + d;
196 let _ = write!(
197 s,
198 "; Expires={}; Max-Age={}",
199 httpdate::fmt_http_date(expires),
200 d.as_secs()
201 );
202 }
203 Some(Expiry::Expired) => {
204 let _ = write!(
205 s,
206 "; Expires={}; Max-Age=0",
207 httpdate::fmt_http_date(SystemTime::UNIX_EPOCH)
208 );
209 }
210 None => {}
211 }
212 if http_only {
213 s.push_str("; HttpOnly");
214 }
215 if opts.secure {
216 s.push_str("; Secure");
217 }
218 let _ = write!(s, "; SameSite={}", opts.same_site.as_str());
219
220 let value = HeaderValue::from_str(&s).map_err(|_| Error::InvalidAttribute(s.clone()))?;
221 headers.append(SET_COOKIE, value);
222 Ok(())
223}
224
225fn is_token_byte(b: u8) -> bool {
227 b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
228}
229
230fn sanitize_value(v: &str) -> String {
232 let ok = |c: char| {
233 c == ' ' || c == ',' || (c.is_ascii() && (0x21..0x7f).contains(&(c as u8)) && c != '"' && c != ';' && c != '\\')
234 };
235 let cleaned: String = v.chars().filter(|c| ok(*c)).collect();
236 if cleaned.contains(' ') || cleaned.contains(',') {
237 format!("\"{cleaned}\"")
238 } else {
239 cleaned
240 }
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 fn set_cookies(h: &HeaderMap) -> Vec<String> {
248 h.get_all(SET_COOKIE)
249 .iter()
250 .map(|v| v.to_str().unwrap().to_owned())
251 .collect()
252 }
253
254 #[test]
255 fn auth_cookie_defaults() {
256 let mut h = HeaderMap::new();
257 set_auth(&mut h, "sid", "abc", &Options::default()).unwrap();
258 assert_eq!(set_cookies(&h), ["sid=abc; Path=/; HttpOnly; SameSite=Lax"]);
259 }
260
261 #[test]
262 fn auth_cookie_full() {
263 let mut h = HeaderMap::new();
264 let opts = Options {
265 domain: ".example.com".into(),
266 path: "/app".into(),
267 secure: true,
268 same_site: SameSite::Strict,
269 max_age: Some(Duration::from_secs(3600)),
270 };
271 set_auth(&mut h, "sid", "abc", &opts).unwrap();
272 let c = &set_cookies(&h)[0];
273 assert!(c.starts_with("sid=abc; Path=/app; Domain=example.com; Expires="), "{c}");
274 assert!(c.ends_with("; Max-Age=3600; HttpOnly; Secure; SameSite=Strict"), "{c}");
275 }
276
277 #[test]
278 fn sub_second_max_age_is_session() {
279 let mut h = HeaderMap::new();
280 let opts = Options {
281 max_age: Some(Duration::from_millis(500)),
282 ..Default::default()
283 };
284 set_auth(&mut h, "sid", "abc", &opts).unwrap();
285 assert_eq!(set_cookies(&h), ["sid=abc; Path=/; HttpOnly; SameSite=Lax"]);
286 }
287
288 #[test]
289 fn clear_cookie() {
290 let mut h = HeaderMap::new();
291 clear(
292 &mut h,
293 "sid",
294 &Options {
295 secure: true,
296 ..Default::default()
297 },
298 )
299 .unwrap();
300 assert_eq!(
301 set_cookies(&h),
302 ["sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; HttpOnly; Secure; SameSite=Lax"]
303 );
304 }
305
306 #[test]
307 fn csrf_cookie_is_readable() {
308 let mut h = HeaderMap::new();
309 set_csrf(&mut h, "tok", &Options::default()).unwrap();
310 assert_eq!(set_cookies(&h), ["csrf_token=tok; Path=/; SameSite=Lax"]);
311 }
312
313 #[test]
314 fn rejects_invalid_input() {
315 let mut h = HeaderMap::new();
316 assert!(matches!(
317 set_auth(&mut h, "bad name", "v", &Options::default()),
318 Err(Error::InvalidName(_))
319 ));
320 assert!(matches!(
321 set_auth(&mut h, "", "v", &Options::default()),
322 Err(Error::InvalidName(_))
323 ));
324 let bad_path = Options {
325 path: "/a;b".into(),
326 ..Default::default()
327 };
328 assert!(matches!(
329 set_auth(&mut h, "sid", "v", &bad_path),
330 Err(Error::InvalidAttribute(_))
331 ));
332 assert!(h.is_empty());
333 }
334
335 #[test]
336 fn sanitizes_values() {
337 assert_eq!(sanitize_value("a;b\"c\\d"), "abcd");
338 assert_eq!(sanitize_value("a b"), "\"a b\"");
339 assert_eq!(sanitize_value("中文x"), "x");
340 }
341
342 #[test]
343 fn csrf_token_shape() {
344 let a = new_csrf_token().unwrap();
345 let b = new_csrf_token().unwrap();
346 assert_eq!(a.len(), 43);
347 assert_ne!(a, b);
348 assert!(a.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_'));
349 }
350
351 fn req(cookie: Option<&str>, header: Option<&str>) -> HeaderMap {
352 let mut h = HeaderMap::new();
353 if let Some(c) = cookie {
354 h.insert(COOKIE, c.parse().unwrap());
355 }
356 if let Some(v) = header {
357 h.insert("x-csrf-token", v.parse().unwrap());
358 }
359 h
360 }
361
362 #[test]
363 fn validate() {
364 let cases = [
365 (Some("sid=1; csrf_token=tok"), Some("tok"), true),
366 (Some("csrf_token=\"tok\""), Some("tok"), true),
367 (Some("csrf_token=tok"), Some("other"), false),
368 (Some("csrf_token=tok"), Some("tok2"), false),
369 (Some("csrf_token=tok"), None, false),
370 (None, Some("tok"), false),
371 (Some("csrf_token="), Some(""), false),
372 (Some("xcsrf_token=tok"), Some("tok"), false),
373 (Some("a=1; csrf_token = tok "), Some("tok"), true),
374 ];
375 for (cookie, header, want) in cases {
376 assert_eq!(validate_csrf(&req(cookie, header)), want, "{cookie:?} {header:?}");
377 }
378
379 let mut h = req(Some("my_csrf=t1"), None);
380 h.insert("x-my-csrf", "t1".parse().unwrap());
381 assert!(validate_csrf_names(&h, "my_csrf", "X-My-CSRF"));
382 }
383}