This commit is contained in:
2026-08-13 21:01:49 +02:00
parent 593edf35fe
commit 58578fd010
5 changed files with 69 additions and 9 deletions
+8
View File
@@ -62,6 +62,14 @@ func TestCSRFAllowsSafeMethodsWithoutHeader(t *testing.T) {
if !found {
t.Fatal("expected non-HttpOnly CSRF cookie on first GET")
}
hdr := rec.Header().Get("X-CSRF-Token")
if hdr == "" {
t.Fatal("expected X-CSRF-Token response header on GET (cross-origin SPA seed)")
}
cookie := findCSRFCookie(rec.Result().Cookies())
if cookie == nil || cookie.Value != hdr {
t.Fatalf("X-CSRF-Token header %q must match cookie value", hdr)
}
}
func TestCSRFRejectsPOSTWithoutToken(t *testing.T) {
+3
View File
@@ -232,6 +232,9 @@ func (s *Server) CSRF(next http.Handler) http.Handler {
MaxAge: 7 * 24 * 60 * 60,
})
}
// Expose for cross-origin SPAs (api.* vs app host): document.cookie cannot
// read host-only API cookies; the client seeds via GET and mirrors this header.
w.Header().Set("X-CSRF-Token", token)
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions {
next.ServeHTTP(w, r)
@@ -137,6 +137,18 @@ func TestCORSAllowsConfiguredOriginOnly(t *testing.T) {
t.Fatalf("allow credentials = %q", got)
}
get := httptest.NewRecorder()
reqGet := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil)
reqGet.Header.Set("Origin", "http://localhost:5174")
h.ServeHTTP(get, reqGet)
exposed := get.Header().Get("Access-Control-Expose-Headers")
if !strings.Contains(strings.ToLower(exposed), "x-csrf-token") {
t.Fatalf("expose headers = %q, want X-CSRF-Token", exposed)
}
if tok := get.Header().Get("X-CSRF-Token"); tok == "" {
t.Fatal("expected X-CSRF-Token on credentialed GET (SPA cross-origin seed)")
}
twin := httptest.NewRecorder()
reqTwin := httptest.NewRequest(http.MethodOptions, "/api/auth/login", nil)
reqTwin.Header.Set("Origin", "http://127.0.0.1:5174")
+1
View File
@@ -263,6 +263,7 @@ func (s *Server) Router() http.Handler {
AllowedOrigins: config.CORSAllowedOrigins(s.Config.WebOrigin),
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Accept-Language", "Authorization", "Content-Type", "X-API-Key", "X-CSRF-Token", "X-Company-ID"},
ExposedHeaders: []string{"X-CSRF-Token", "X-Products-Exported"},
AllowCredentials: true,
MaxAge: 300,
}))