Skip to main content

rust_web_utils/
cookieutil.rs

1//! 带安全默认值的认证 Cookie 与 CSRF double-submit 防护。
2//!
3//! 安全基线:
4//!
5//! - 认证 Cookie 强制 `HttpOnly`, 前端脚本不可读, 防 XSS 窃取
6//! - 生产环境设 `secure: true`, 仅走 HTTPS
7//! - `SameSite` 默认 `Lax`, 跨站场景显式指定
8//! - CSRF 用 double-submit: 随机 token 同时写入可读 Cookie `csrf_token` 与请求头
9//!   `X-CSRF-Token`, 服务端恒定时间比较两者
10//!
11//! 函数直接写 `http::HeaderMap` (追加 `Set-Cookie`), Axum 里可与响应体组成元组返回:
12//!
13//! ```
14//! use std::time::Duration;
15//! use http::HeaderMap;
16//! use rust_web_utils::cookieutil::{self, Options};
17//!
18//! let opts = Options { secure: true, max_age: Some(Duration::from_secs(7 * 86400)), ..Default::default() };
19//! let mut headers = HeaderMap::new();
20//! cookieutil::set_auth(&mut headers, "session_id", "s3cr3t", &opts).unwrap();
21//!
22//! let token = cookieutil::new_csrf_token().unwrap();
23//! cookieutil::set_csrf(&mut headers, &token, &opts).unwrap();
24//! assert_eq!(headers.get_all("set-cookie").iter().count(), 2);
25//! ```
26//!
27//! 完整文档: <https://rust-web-utils.czl.net/docs/cookieutil>
28
29use 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
38/// CSRF token 的默认 Cookie 名
39pub const DEFAULT_CSRF_COOKIE: &str = "csrf_token";
40
41/// CSRF token 的默认请求头名
42pub const DEFAULT_CSRF_HEADER: &str = "X-CSRF-Token";
43
44/// Cookie 错误
45#[derive(Debug, thiserror::Error)]
46pub enum Error {
47    /// Cookie 名不是合法 token
48    #[error("cookieutil: invalid cookie name {0:?}")]
49    InvalidName(String),
50    /// Domain / Path 含非法字符
51    #[error("cookieutil: invalid cookie attribute {0:?}")]
52    InvalidAttribute(String),
53    /// 系统随机数源不可用
54    #[error("cookieutil: generate csrf token: {0}")]
55    Random(String),
56}
57
58/// `SameSite` 属性
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum SameSite {
61    /// `SameSite=Lax` (默认)
62    #[default]
63    Lax,
64    /// `SameSite=Strict`
65    Strict,
66    /// `SameSite=None`; 浏览器要求同时 `secure: true`
67    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/// Cookie 下发选项; `Default` 即 `Path=/`、`SameSite=Lax`、会话级有效期
81#[derive(Debug, Clone, Default, PartialEq, Eq)]
82pub struct Options {
83    /// `Domain`; 空串不写
84    pub domain: String,
85    /// `Path`; 空串默认 `/`
86    pub path: String,
87    /// `Secure`; 生产环境必须为 `true`
88    pub secure: bool,
89    /// `SameSite`
90    pub same_site: SameSite,
91    /// 有效期 (按整秒截断); `None` 或不足 1 秒为会话 Cookie (随浏览器关闭失效)
92    pub max_age: Option<Duration>,
93}
94
95/// 下发认证 Cookie, 强制 `HttpOnly` (调用方无法关闭), 用于 session id / 登录凭证等敏感值
96pub 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
107/// 清除 Cookie (`Max-Age=0` + 过期时间置于 1970); `domain` / `path` 必须与下发时一致才能生效
108pub fn clear(headers: &mut HeaderMap, name: &str, opts: &Options) -> Result<(), Error> {
109    append(headers, name, "", opts, true, Some(Expiry::Expired))
110}
111
112/// 生成 32 字节加密随机 CSRF token (base64url 无填充编码)
113pub 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
119/// 下发 CSRF Cookie (名为 [`DEFAULT_CSRF_COOKIE`]); 特意不设 `HttpOnly`,
120/// 前端读取它并在写操作请求时放入 [`DEFAULT_CSRF_HEADER`] 请求头
121pub 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
132/// 按默认 Cookie 名与请求头名做 double-submit 校验
133pub fn validate_csrf(headers: &HeaderMap) -> bool {
134    validate_csrf_names(headers, DEFAULT_CSRF_COOKIE, DEFAULT_CSRF_HEADER)
135}
136
137/// 校验 CSRF token: Cookie 与请求头都存在、非空且恒定时间比较一致时通过; 任一缺失即失败
138pub 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
152/// 读取请求 `Cookie` 头中名为 `name` 的首个值 (去掉一层双引号); 缺失时返回 `None`
153pub 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
225/// RFC 7230 token 字符
226fn is_token_byte(b: u8) -> bool {
227    b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
228}
229
230/// 与 Go `http.SetCookie` 一致: 丢弃 cookie-octet 之外的字符; 含空格或逗号时整体加双引号
231fn 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}