fix: add CSRF protection to API v1 routes (closes #112)
All checks were successful
Check / check (pull_request) Successful in 12m25s
All checks were successful
Check / check (pull_request) Successful in 12m25s
Add APICSRFProtection middleware that requires X-Requested-With header on all state-changing (non-GET/HEAD/OPTIONS) API requests. This prevents CSRF attacks since browsers won't send custom headers in cross-origin simple requests (form posts, navigations). Changes: - Add APICSRFProtection() middleware in internal/middleware/middleware.go - Apply middleware to /api/v1 route group in routes.go - Add X-Requested-With to CORS allowed headers - Add unit tests for the middleware (csrf_test.go) - Add integration tests for CSRF rejection/allowance (api_test.go) - Update existing API tests to include the required header
This commit is contained in:
87
internal/middleware/csrf_test.go
Normal file
87
internal/middleware/csrf_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package middleware //nolint:testpackage // tests internal CSRF behavior
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAPICSRFProtection_BlocksPostWithoutHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := &Middleware{}
|
||||
handler := mw.APICSRFProtection()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/apps", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rr.Code)
|
||||
assert.Contains(t, rr.Body.String(), "X-Requested-With")
|
||||
}
|
||||
|
||||
func TestAPICSRFProtection_AllowsPostWithHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := &Middleware{}
|
||||
handler := mw.APICSRFProtection()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/apps", nil)
|
||||
req.Header.Set("X-Requested-With", "XMLHttpRequest")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
}
|
||||
|
||||
func TestAPICSRFProtection_AllowsGetWithoutHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := &Middleware{}
|
||||
handler := mw.APICSRFProtection()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/apps", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
}
|
||||
|
||||
func TestAPICSRFProtection_BlocksDeleteWithoutHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := &Middleware{}
|
||||
handler := mw.APICSRFProtection()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/apps/123", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rr.Code)
|
||||
}
|
||||
|
||||
func TestAPICSRFProtection_AllowsHeadWithoutHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := &Middleware{}
|
||||
handler := mw.APICSRFProtection()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodHead, "/api/v1/apps", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
}
|
||||
@@ -193,7 +193,7 @@ func (m *Middleware) CORS() func(http.Handler) http.Handler {
|
||||
return cors.Handler(cors.Options{
|
||||
AllowedOrigins: origins,
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "X-Requested-With"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: corsMaxAge,
|
||||
@@ -370,6 +370,43 @@ func (m *Middleware) LoginRateLimit() func(http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
// apiCSRFSafeMethods are HTTP methods that do not require CSRF protection.
|
||||
//
|
||||
//nolint:gochecknoglobals // package-level constant set
|
||||
var apiCSRFSafeMethods = map[string]bool{
|
||||
http.MethodGet: true,
|
||||
http.MethodHead: true,
|
||||
http.MethodOptions: true,
|
||||
}
|
||||
|
||||
// APICSRFProtection returns middleware that protects API routes against CSRF attacks
|
||||
// by requiring a custom header (X-Requested-With) on all state-changing requests.
|
||||
// Browsers will not send custom headers in cross-origin simple requests (form posts,
|
||||
// navigations), so this blocks CSRF attacks without requiring tokens.
|
||||
func (m *Middleware) APICSRFProtection() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
) {
|
||||
if !apiCSRFSafeMethods[request.Method] {
|
||||
if request.Header.Get("X-Requested-With") == "" {
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
http.Error(
|
||||
writer,
|
||||
`{"error":"missing X-Requested-With header"}`,
|
||||
http.StatusForbidden,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
next.ServeHTTP(writer, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// APISessionAuth returns middleware that requires session authentication for API routes.
|
||||
// Unlike SessionAuth, it returns JSON 401 responses instead of redirecting to /login.
|
||||
func (m *Middleware) APISessionAuth() func(http.Handler) http.Handler {
|
||||
|
||||
Reference in New Issue
Block a user