Add API CSRF protection via X-Requested-With header (closes #112)
All checks were successful
Check / check (pull_request) Successful in 11m36s

- Add APICSRFProtection middleware requiring X-Requested-With header on
  state-changing API requests (POST, PUT, DELETE, PATCH)
- Apply middleware to all /api/v1 routes
- Upgrade session cookie SameSite from Lax to Strict (defense-in-depth)
- Add X-Requested-With to CORS allowed headers
- Add tests for the new middleware

Browsers cannot send custom headers cross-origin without CORS preflight,
which effectively blocks CSRF attacks via cookie-based session auth.
This commit is contained in:
user
2026-02-20 05:33:33 -08:00
parent 4217e62f27
commit efa8f51310
4 changed files with 116 additions and 3 deletions

View File

@@ -102,8 +102,10 @@ func (s *Server) SetupRoutes() {
})
})
// API v1 routes (cookie-based session auth, no CSRF)
// API v1 routes (cookie-based session auth, CSRF protected via custom header)
s.router.Route("/api/v1", func(r chi.Router) {
r.Use(s.mw.APICSRFProtection())
// Login endpoint is public (returns session cookie)
r.With(s.mw.LoginRateLimit()).Post("/login", s.handlers.HandleAPILoginPOST())