Skip to main content

alibi_core/middleware/csrf/
mod.rs

1use super::Middleware;
2use crate::config::{AuthConfig, extract_origin};
3use crate::error::{AuthError, AuthResult};
4use crate::types::{AuthRequest, AuthResponse, HttpMethod};
5use async_trait::async_trait;
6#[cfg(test)]
7use std::collections::HashMap;
8use std::sync::Arc;
9
10const CROSS_SITE_NAVIGATION_LOGIN_BLOCKED: &str =
11    "Cross-site navigation login blocked. This request appears to be a CSRF attack.";
12const INVALID_CALLBACK_URL: &str = "Invalid callbackURL";
13const INVALID_ERROR_CALLBACK_URL: &str = "Invalid errorCallbackURL";
14const INVALID_NEW_USER_CALLBACK_URL: &str = "Invalid newUserCallbackURL";
15const INVALID_REDIRECT_URL: &str = "Invalid redirectURL";
16const INVALID_ORIGIN: &str = "Invalid origin";
17const MISSING_OR_NULL_ORIGIN: &str = "Missing or null Origin";
18
19/// Configuration for Better Auth request-origin and CSRF protection.
20#[derive(Debug, Clone)]
21pub struct CsrfConfig {
22    /// Whether the request protection middleware is enabled. Defaults to `true`.
23    pub enabled: bool,
24}
25
26impl Default for CsrfConfig {
27    fn default() -> Self {
28        Self { enabled: true }
29    }
30}
31
32impl CsrfConfig {
33    #[must_use]
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    #[must_use]
39    pub const fn enabled(mut self, enabled: bool) -> Self {
40        self.enabled = enabled;
41        self
42    }
43}
44
45/// Better Auth request protection middleware.
46///
47/// This mirrors the upstream TypeScript behavior:
48/// - mutating requests with cookies require a trusted `Origin` / `Referer`
49/// - first-login `POST /sign-up/email` and `POST /sign-in/email` also use
50///   Fetch Metadata headers to block cross-site navigation attacks
51/// - callback / redirect targets are validated against trusted origins unless
52///   `advanced.disable_origin_check` is set
53#[derive(Debug)]
54pub struct CsrfMiddleware {
55    config: CsrfConfig,
56    auth_config: Arc<AuthConfig>,
57}
58
59impl CsrfMiddleware {
60    #[must_use]
61    pub const fn new(config: CsrfConfig, auth_config: Arc<AuthConfig>) -> Self {
62        Self {
63            config,
64            auth_config,
65        }
66    }
67
68    /// Retain protection settings with the effective request-local URL policy.
69    #[must_use]
70    pub fn with_auth_config(&self, auth_config: Arc<AuthConfig>) -> Self {
71        Self::new(self.config.clone(), auth_config)
72    }
73
74    const fn is_state_changing(method: &HttpMethod) -> bool {
75        matches!(
76            method,
77            HttpMethod::Post | HttpMethod::Put | HttpMethod::Delete | HttpMethod::Patch
78        )
79    }
80
81    fn normalized_path<'a>(&self, path: &'a str) -> &'a str {
82        let base_path = self.auth_config.base_path.as_str();
83        if !base_path.is_empty() && base_path != "/" {
84            path.strip_prefix(base_path).unwrap_or(path)
85        } else {
86            path
87        }
88    }
89
90    fn is_form_csrf_path(path: &str) -> bool {
91        matches!(path, "/sign-in/email" | "/sign-up/email")
92    }
93
94    fn header<'a>(req: &'a AuthRequest, name: &str) -> Option<&'a str> {
95        req.headers
96            .iter()
97            .find_map(|(key, value)| key.eq_ignore_ascii_case(name).then_some(value.as_str()))
98    }
99
100    fn has_cookies(req: &AuthRequest) -> bool {
101        Self::header(req, "cookie").is_some()
102    }
103
104    fn has_fetch_metadata(req: &AuthRequest) -> bool {
105        ["sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest"]
106            .into_iter()
107            .any(|name| Self::header(req, name).is_some_and(|value| !value.trim().is_empty()))
108    }
109
110    fn validate_origin(&self, req: &AuthRequest, force_validate: bool) -> Result<(), AuthError> {
111        if self.auth_config.advanced.disable_csrf_check == Some(true)
112            || self.auth_config.origin_check_disabled_for(req.path())
113        {
114            return Ok(());
115        }
116
117        if !force_validate && !Self::has_cookies(req) {
118            return Ok(());
119        }
120
121        let inferred = (Self::header(req, "origin") == Some("null")
122            && Self::header(req, "sec-fetch-site") == Some("same-origin"))
123        .then(|| req.url().and_then(|url| extract_origin(url.as_str())))
124        .flatten();
125        let origin = inferred
126            .or_else(|| {
127                Self::header(req, "origin")
128                    .filter(|value| !value.is_empty())
129                    .map(ToOwned::to_owned)
130                    .or_else(|| Self::header(req, "referer").and_then(extract_origin))
131            })
132            .filter(|value| value != "null")
133            .ok_or_else(|| AuthError::forbidden(MISSING_OR_NULL_ORIGIN))?;
134
135        if self.auth_config.is_origin_trusted(&origin) {
136            Ok(())
137        } else {
138            Err(AuthError::forbidden(INVALID_ORIGIN))
139        }
140    }
141
142    fn validate_form_csrf(&self, req: &AuthRequest) -> Result<(), AuthError> {
143        if self.auth_config.advanced.disable_csrf_check == Some(true)
144            || self.auth_config.advanced.disable_origin_check
145                && self.auth_config.advanced.disable_csrf_check.is_none()
146        {
147            return Ok(());
148        }
149
150        if Self::has_cookies(req) {
151            return self.validate_origin(req, false);
152        }
153
154        if Self::has_fetch_metadata(req) {
155            let is_cross_site_navigation = matches!(
156                (
157                    Self::header(req, "sec-fetch-site"),
158                    Self::header(req, "sec-fetch-mode"),
159                ),
160                (Some("cross-site"), Some("navigate"))
161            );
162
163            if is_cross_site_navigation {
164                return Err(AuthError::forbidden(CROSS_SITE_NAVIGATION_LOGIN_BLOCKED));
165            }
166
167            return self.validate_origin(req, true);
168        }
169
170        if Self::header(req, "origin").is_some_and(|value| !value.is_empty())
171            || Self::header(req, "referer").is_some_and(|value| !value.is_empty())
172        {
173            return self.validate_origin(req, true);
174        }
175        Ok(())
176    }
177
178    fn validate_redirect_targets(&self, req: &AuthRequest) -> Result<(), AuthError> {
179        if self.auth_config.origin_check_disabled_for(req.path()) {
180            return Ok(());
181        }
182
183        for (name, value) in Self::request_target_values(req)? {
184            if !self.auth_config.is_redirect_target_trusted(&value) {
185                return Err(AuthError::forbidden(Self::target_error_message(name)));
186            }
187        }
188
189        Ok(())
190    }
191
192    fn request_target_values(req: &AuthRequest) -> Result<Vec<(&'static str, String)>, AuthError> {
193        let body = Self::request_body_map(req).unwrap_or_default();
194        let mut targets = Vec::new();
195        for (key, label) in [
196            ("callbackURL", "callbackURL"),
197            ("redirectTo", "redirectURL"),
198            ("errorCallbackURL", "errorCallbackURL"),
199            ("newUserCallbackURL", "newUserCallbackURL"),
200        ] {
201            let value = body
202                .get(key)
203                .filter(|value| Self::is_truthy(value))
204                .cloned()
205                .or_else(|| {
206                    (key == "callbackURL")
207                        .then(|| req.query.get(key))
208                        .flatten()
209                        .filter(|value| !value.is_empty())
210                        .cloned()
211                        .map(serde_json::Value::String)
212                });
213            let Some(value) = value else {
214                continue;
215            };
216            let Some(value) = value.as_str() else {
217                return Err(AuthError::bad_request(format!(
218                    "Invalid {label}: expected a string"
219                )));
220            };
221            targets.push((key, value.to_owned()));
222        }
223        Ok(targets)
224    }
225
226    fn is_truthy(value: &serde_json::Value) -> bool {
227        match value {
228            serde_json::Value::Null => false,
229            serde_json::Value::Bool(value) => *value,
230            serde_json::Value::Number(value) => value.as_f64() != Some(0.0),
231            serde_json::Value::String(value) => !value.is_empty(),
232            serde_json::Value::Array(_) | serde_json::Value::Object(_) => true,
233        }
234    }
235
236    fn request_body_map(req: &AuthRequest) -> Option<serde_json::Map<String, serde_json::Value>> {
237        let content_type = Self::header(req, "content-type").unwrap_or_default();
238        if content_type.contains("application/x-www-form-urlencoded") {
239            let body = req.body.as_ref()?;
240            return Some(
241                url::form_urlencoded::parse(body)
242                    .map(|(key, value)| {
243                        (
244                            key.into_owned(),
245                            serde_json::Value::String(value.into_owned()),
246                        )
247                    })
248                    .collect(),
249            );
250        }
251        req.body_as_json::<serde_json::Value>()
252            .ok()?
253            .as_object()
254            .cloned()
255    }
256
257    fn target_error_message(name: &str) -> &'static str {
258        match name {
259            "callbackURL" => INVALID_CALLBACK_URL,
260            "redirectTo" => INVALID_REDIRECT_URL,
261            "errorCallbackURL" => INVALID_ERROR_CALLBACK_URL,
262            "newUserCallbackURL" => INVALID_NEW_USER_CALLBACK_URL,
263            _ => INVALID_ORIGIN,
264        }
265    }
266
267    /// Router protection after route/body resolution and before application hooks.
268    ///
269    /// # Errors
270    /// Rejects untrusted request origins and redirect targets.
271    pub fn check_request_origin(&self, req: &AuthRequest) -> AuthResult<()> {
272        if !self.config.enabled || !Self::is_state_changing(req.method()) {
273            return Ok(());
274        }
275        self.validate_origin(req, false)?;
276        self.validate_redirect_targets(req)
277    }
278
279    /// Endpoint-local first-login protection, after application before hooks.
280    ///
281    /// # Errors
282    /// Rejects cross-site navigation or untrusted first-login origins.
283    pub fn check_form_origin(&self, req: &AuthRequest) -> AuthResult<()> {
284        if self.config.enabled
285            && Self::is_state_changing(req.method())
286            && Self::is_form_csrf_path(self.normalized_path(req.path()))
287        {
288            self.validate_form_csrf(req)?;
289        }
290        Ok(())
291    }
292    /// Check an explicitly selected login operation using its genuine incoming request.
293    /// The request URL need not be an auth route for a public server API call.
294    ///
295    /// # Errors
296    /// Rejects cross-site navigation or untrusted login origins.
297    pub fn check_login_origin(&self, req: &AuthRequest) -> AuthResult<()> {
298        if self.config.enabled {
299            self.validate_form_csrf(req)?;
300        }
301        Ok(())
302    }
303}
304
305#[async_trait]
306impl Middleware for CsrfMiddleware {
307    fn name(&self) -> &'static str {
308        "csrf"
309    }
310
311    async fn before_request(&self, req: &AuthRequest) -> AuthResult<Option<AuthResponse>> {
312        if !self.config.enabled || !Self::is_state_changing(req.method()) {
313            return Ok(None);
314        }
315
316        let path = self.normalized_path(req.path());
317        let result = if Self::is_form_csrf_path(path) {
318            self.validate_form_csrf(req)
319        } else {
320            self.validate_origin(req, false)
321        }
322        .and_then(|()| self.validate_redirect_targets(req));
323        Ok(result.err().map(AuthError::to_auth_response))
324    }
325}
326
327// LCOV_EXCL_START
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    fn make_request(
333        path: &str,
334        origin: Option<&str>,
335        cookie: bool,
336        extra_headers: &[(&str, &str)],
337    ) -> AuthRequest {
338        let mut headers = HashMap::new();
339        headers.insert("content-type".to_owned(), "application/json".to_owned());
340        if let Some(origin) = origin {
341            headers.insert("origin".to_owned(), origin.to_owned());
342        }
343        if cookie {
344            headers.insert(
345                "cookie".to_owned(),
346                "better-auth.session_token=test-token".to_owned(),
347            );
348        }
349        for (name, value) in extra_headers {
350            headers.insert((*name).to_owned(), (*value).to_owned());
351        }
352        AuthRequest::from_parts(
353            HttpMethod::Post,
354            path.to_owned(),
355            headers,
356            None,
357            HashMap::new(),
358        )
359    }
360
361    fn test_auth_config(trusted_origins: Vec<String>) -> Arc<AuthConfig> {
362        Arc::new(
363            AuthConfig::new("test-secret-key-that-is-at-least-32-characters-long")
364                .base_url("http://localhost:3000")
365                .trusted_origins(trusted_origins),
366        )
367    }
368
369    fn forbidden_message(response: Option<AuthResponse>) -> String {
370        let response = response.expect("expected rejection response");
371        assert_eq!(response.status, 403);
372        let body = serde_json::from_slice::<serde_json::Value>(&response.body).unwrap();
373        (*(body).get("message").unwrap_or(&serde_json::Value::Null))
374            .as_str()
375            .unwrap()
376            .to_owned()
377    }
378
379    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
380    #[tokio::test]
381    async fn cookie_backed_requests_require_a_trusted_origin() {
382        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
383        let req = make_request("/sign-out", Some("http://evil.com"), true, &[]);
384        let message = forbidden_message(mw.before_request(&req).await.unwrap());
385        assert_eq!(message, INVALID_ORIGIN);
386    }
387
388    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
389    #[tokio::test]
390    async fn cookie_backed_requests_require_origin_or_referer() {
391        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
392        let req = make_request("/sign-out", None, true, &[]);
393        let message = forbidden_message(mw.before_request(&req).await.unwrap());
394        assert_eq!(message, MISSING_OR_NULL_ORIGIN);
395    }
396
397    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
398    #[tokio::test]
399    async fn sign_in_allows_same_origin_fetch_metadata_requests() {
400        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
401        let req = make_request(
402            "/sign-in/email",
403            Some("http://localhost:3000"),
404            false,
405            &[
406                ("sec-fetch-site", "same-origin"),
407                ("sec-fetch-mode", "cors"),
408            ],
409        );
410        assert!(mw.before_request(&req).await.unwrap().is_none());
411    }
412
413    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
414    #[tokio::test]
415    async fn sign_in_blocks_cross_site_navigation_login_attempts() {
416        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
417        let req = make_request(
418            "/sign-in/email",
419            Some("http://evil.com"),
420            false,
421            &[
422                ("sec-fetch-site", "cross-site"),
423                ("sec-fetch-mode", "navigate"),
424            ],
425        );
426        let message = forbidden_message(mw.before_request(&req).await.unwrap());
427        assert_eq!(message, CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);
428    }
429
430    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
431    #[tokio::test]
432    async fn sign_up_rejects_untrusted_origin_without_metadata() {
433        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
434        let req = make_request("/sign-up/email", Some("http://evil.com"), false, &[]);
435        assert_eq!(
436            forbidden_message(mw.before_request(&req).await.unwrap()),
437            "Invalid origin"
438        );
439    }
440
441    // Pinned origin-check middleware applies JavaScript truthiness, then checks
442    // each redirect field's type before route schema parsing.
443    #[tokio::test]
444    async fn redirect_targets_enforce_types_origins_and_callback_precedence() {
445        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
446        for (field, label) in [
447            ("callbackURL", "callbackURL"),
448            ("redirectTo", "redirectURL"),
449            ("errorCallbackURL", "errorCallbackURL"),
450            ("newUserCallbackURL", "newUserCallbackURL"),
451        ] {
452            for value in [
453                serde_json::json!(5),
454                serde_json::json!(true),
455                serde_json::json!([]),
456                serde_json::json!({}),
457            ] {
458                let mut req = make_request("/send-verification-email", None, false, &[]);
459                req.body = Some(serde_json::json!({field:value}).to_string().into_bytes());
460                let response = mw
461                    .before_request(&req)
462                    .await
463                    .unwrap()
464                    .expect("truthy non-string redirect must be rejected before the route");
465                assert_eq!(response.status, 400);
466                assert_eq!(
467                    serde_json::from_slice::<serde_json::Value>(&response.body).unwrap(),
468                    serde_json::json!({"message":format!("Invalid {label}: expected a string")})
469                );
470            }
471            for value in [
472                serde_json::Value::Null,
473                serde_json::json!(false),
474                serde_json::json!(0),
475                serde_json::json!(""),
476            ] {
477                let mut req = make_request("/send-verification-email", None, false, &[]);
478                req.body = Some(serde_json::json!({field:value}).to_string().into_bytes());
479                assert!(mw.before_request(&req).await.unwrap().is_none());
480            }
481        }
482        let mut request = make_request("/send-verification-email", None, false, &[]);
483        request.query.insert(
484            "callbackURL".to_owned(),
485            "http://evil.com/dashboard".to_owned(),
486        );
487        request.body = Some(
488            serde_json::json!({"callbackURL":"/safe"})
489                .to_string()
490                .into_bytes(),
491        );
492        assert!(
493            mw.before_request(&request).await.unwrap().is_none(),
494            "the body callback overrides the query callback"
495        );
496        request.body = Some(
497            serde_json::json!({"callbackURL":null})
498                .to_string()
499                .into_bytes(),
500        );
501        let message = forbidden_message(mw.before_request(&request).await.unwrap());
502        assert_eq!(
503            message, INVALID_CALLBACK_URL,
504            "a falsy body callback falls back to the query"
505        );
506        request.query.clear();
507        request.query.insert(
508            "redirectTo".to_owned(),
509            "http://evil.com/ignored".to_owned(),
510        );
511        assert!(
512            mw.before_request(&request).await.unwrap().is_none(),
513            "upstream reads other redirects from the body only"
514        );
515    }
516
517    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
518    #[tokio::test]
519    async fn csrf_can_be_disabled_explicitly() {
520        let mw = CsrfMiddleware::new(CsrfConfig::new().enabled(false), test_auth_config(vec![]));
521        let req = make_request("/sign-out", Some("http://evil.com"), true, &[]);
522        assert!(mw.before_request(&req).await.unwrap().is_none());
523    }
524
525    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
526    #[tokio::test]
527    async fn advanced_disable_origin_check_skips_callback_url_validation() {
528        let mut config = AuthConfig::new("test-secret-key-that-is-at-least-32-characters-long")
529            .base_url("http://localhost:3000")
530            .disable_origin_check(true);
531        config.trusted_origins = vec![];
532        let mw = CsrfMiddleware::new(CsrfConfig::new(), Arc::new(config));
533        let mut req = make_request("/sign-in/social", None, false, &[]);
534        req.body = Some(
535            serde_json::json!({
536                "provider": "google",
537                "callbackURL": "http://evil.com/dashboard"
538            })
539            .to_string()
540            .into_bytes(),
541        );
542
543        assert!(mw.before_request(&req).await.unwrap().is_none());
544    }
545
546    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
547    #[test]
548    fn extract_origin_still_handles_paths() {
549        assert_eq!(
550            extract_origin("https://example.com/path"),
551            Some("https://example.com".to_owned())
552        );
553        assert_eq!(
554            extract_origin("http://localhost:3000"),
555            Some("http://localhost:3000".to_owned())
556        );
557        assert_eq!(extract_origin("not-a-url"), None);
558    }
559}
560// LCOV_EXCL_STOP