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}
293
294#[async_trait]
295impl Middleware for CsrfMiddleware {
296    fn name(&self) -> &'static str {
297        "csrf"
298    }
299
300    async fn before_request(&self, req: &AuthRequest) -> AuthResult<Option<AuthResponse>> {
301        if !self.config.enabled || !Self::is_state_changing(req.method()) {
302            return Ok(None);
303        }
304
305        let path = self.normalized_path(req.path());
306        let result = if Self::is_form_csrf_path(path) {
307            self.validate_form_csrf(req)
308        } else {
309            self.validate_origin(req, false)
310        }
311        .and_then(|()| self.validate_redirect_targets(req));
312        Ok(result.err().map(AuthError::to_auth_response))
313    }
314}
315
316// LCOV_EXCL_START
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn make_request(
322        path: &str,
323        origin: Option<&str>,
324        cookie: bool,
325        extra_headers: &[(&str, &str)],
326    ) -> AuthRequest {
327        let mut headers = HashMap::new();
328        headers.insert("content-type".to_owned(), "application/json".to_owned());
329        if let Some(origin) = origin {
330            headers.insert("origin".to_owned(), origin.to_owned());
331        }
332        if cookie {
333            headers.insert(
334                "cookie".to_owned(),
335                "better-auth.session_token=test-token".to_owned(),
336            );
337        }
338        for (name, value) in extra_headers {
339            headers.insert((*name).to_owned(), (*value).to_owned());
340        }
341        AuthRequest::from_parts(
342            HttpMethod::Post,
343            path.to_owned(),
344            headers,
345            None,
346            HashMap::new(),
347        )
348    }
349
350    fn test_auth_config(trusted_origins: Vec<String>) -> Arc<AuthConfig> {
351        Arc::new(
352            AuthConfig::new("test-secret-key-that-is-at-least-32-characters-long")
353                .base_url("http://localhost:3000")
354                .trusted_origins(trusted_origins),
355        )
356    }
357
358    fn forbidden_message(response: Option<AuthResponse>) -> String {
359        let response = response.expect("expected rejection response");
360        assert_eq!(response.status, 403);
361        let body = serde_json::from_slice::<serde_json::Value>(&response.body).unwrap();
362        (*(body).get("message").unwrap_or(&serde_json::Value::Null))
363            .as_str()
364            .unwrap()
365            .to_owned()
366    }
367
368    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
369    #[tokio::test]
370    async fn cookie_backed_requests_require_a_trusted_origin() {
371        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
372        let req = make_request("/sign-out", Some("http://evil.com"), true, &[]);
373        let message = forbidden_message(mw.before_request(&req).await.unwrap());
374        assert_eq!(message, INVALID_ORIGIN);
375    }
376
377    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
378    #[tokio::test]
379    async fn cookie_backed_requests_require_origin_or_referer() {
380        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
381        let req = make_request("/sign-out", None, true, &[]);
382        let message = forbidden_message(mw.before_request(&req).await.unwrap());
383        assert_eq!(message, MISSING_OR_NULL_ORIGIN);
384    }
385
386    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
387    #[tokio::test]
388    async fn sign_in_allows_same_origin_fetch_metadata_requests() {
389        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
390        let req = make_request(
391            "/sign-in/email",
392            Some("http://localhost:3000"),
393            false,
394            &[
395                ("sec-fetch-site", "same-origin"),
396                ("sec-fetch-mode", "cors"),
397            ],
398        );
399        assert!(mw.before_request(&req).await.unwrap().is_none());
400    }
401
402    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
403    #[tokio::test]
404    async fn sign_in_blocks_cross_site_navigation_login_attempts() {
405        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
406        let req = make_request(
407            "/sign-in/email",
408            Some("http://evil.com"),
409            false,
410            &[
411                ("sec-fetch-site", "cross-site"),
412                ("sec-fetch-mode", "navigate"),
413            ],
414        );
415        let message = forbidden_message(mw.before_request(&req).await.unwrap());
416        assert_eq!(message, CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);
417    }
418
419    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
420    #[tokio::test]
421    async fn sign_up_rejects_untrusted_origin_without_metadata() {
422        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
423        let req = make_request("/sign-up/email", Some("http://evil.com"), false, &[]);
424        assert_eq!(
425            forbidden_message(mw.before_request(&req).await.unwrap()),
426            "Invalid origin"
427        );
428    }
429
430    // Pinned origin-check middleware applies JavaScript truthiness, then checks
431    // each redirect field's type before route schema parsing.
432    #[tokio::test]
433    async fn redirect_targets_enforce_types_origins_and_callback_precedence() {
434        let mw = CsrfMiddleware::new(CsrfConfig::new(), test_auth_config(vec![]));
435        for (field, label) in [
436            ("callbackURL", "callbackURL"),
437            ("redirectTo", "redirectURL"),
438            ("errorCallbackURL", "errorCallbackURL"),
439            ("newUserCallbackURL", "newUserCallbackURL"),
440        ] {
441            for value in [
442                serde_json::json!(5),
443                serde_json::json!(true),
444                serde_json::json!([]),
445                serde_json::json!({}),
446            ] {
447                let mut req = make_request("/send-verification-email", None, false, &[]);
448                req.body = Some(serde_json::json!({field:value}).to_string().into_bytes());
449                let response = mw
450                    .before_request(&req)
451                    .await
452                    .unwrap()
453                    .expect("truthy non-string redirect must be rejected before the route");
454                assert_eq!(response.status, 400);
455                assert_eq!(
456                    serde_json::from_slice::<serde_json::Value>(&response.body).unwrap(),
457                    serde_json::json!({"message":format!("Invalid {label}: expected a string")})
458                );
459            }
460            for value in [
461                serde_json::Value::Null,
462                serde_json::json!(false),
463                serde_json::json!(0),
464                serde_json::json!(""),
465            ] {
466                let mut req = make_request("/send-verification-email", None, false, &[]);
467                req.body = Some(serde_json::json!({field:value}).to_string().into_bytes());
468                assert!(mw.before_request(&req).await.unwrap().is_none());
469            }
470        }
471        let mut request = make_request("/send-verification-email", None, false, &[]);
472        request.query.insert(
473            "callbackURL".to_owned(),
474            "http://evil.com/dashboard".to_owned(),
475        );
476        request.body = Some(
477            serde_json::json!({"callbackURL":"/safe"})
478                .to_string()
479                .into_bytes(),
480        );
481        assert!(
482            mw.before_request(&request).await.unwrap().is_none(),
483            "the body callback overrides the query callback"
484        );
485        request.body = Some(
486            serde_json::json!({"callbackURL":null})
487                .to_string()
488                .into_bytes(),
489        );
490        let message = forbidden_message(mw.before_request(&request).await.unwrap());
491        assert_eq!(
492            message, INVALID_CALLBACK_URL,
493            "a falsy body callback falls back to the query"
494        );
495        request.query.clear();
496        request.query.insert(
497            "redirectTo".to_owned(),
498            "http://evil.com/ignored".to_owned(),
499        );
500        assert!(
501            mw.before_request(&request).await.unwrap().is_none(),
502            "upstream reads other redirects from the body only"
503        );
504    }
505
506    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
507    #[tokio::test]
508    async fn csrf_can_be_disabled_explicitly() {
509        let mw = CsrfMiddleware::new(CsrfConfig::new().enabled(false), test_auth_config(vec![]));
510        let req = make_request("/sign-out", Some("http://evil.com"), true, &[]);
511        assert!(mw.before_request(&req).await.unwrap().is_none());
512    }
513
514    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
515    #[tokio::test]
516    async fn advanced_disable_origin_check_skips_callback_url_validation() {
517        let mut config = AuthConfig::new("test-secret-key-that-is-at-least-32-characters-long")
518            .base_url("http://localhost:3000")
519            .disable_origin_check(true);
520        config.trusted_origins = vec![];
521        let mw = CsrfMiddleware::new(CsrfConfig::new(), Arc::new(config));
522        let mut req = make_request("/sign-in/social", None, false, &[]);
523        req.body = Some(
524            serde_json::json!({
525                "provider": "google",
526                "callbackURL": "http://evil.com/dashboard"
527            })
528            .to_string()
529            .into_bytes(),
530        );
531
532        assert!(mw.before_request(&req).await.unwrap().is_none());
533    }
534
535    // Rust-specific surface: Rust middleware implementations are library-specific behavior with no direct TS analogue.
536    #[test]
537    fn extract_origin_still_handles_paths() {
538        assert_eq!(
539            extract_origin("https://example.com/path"),
540            Some("https://example.com".to_owned())
541        );
542        assert_eq!(
543            extract_origin("http://localhost:3000"),
544            Some("http://localhost:3000".to_owned())
545        );
546        assert_eq!(extract_origin("not-a-url"), None);
547    }
548}
549// LCOV_EXCL_STOP