95 lines
2.6 KiB
Go
95 lines
2.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
)
|
|
|
|
func TestFrontendOriginWhitelist_DefaultAllowedOrigin(t *testing.T) {
|
|
os.Unsetenv("FRONTEND_ORIGINS")
|
|
|
|
called := false
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
called = true
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
|
|
handler := FrontendOriginWhitelist(next)
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/auth/forgot-password", nil)
|
|
req.Header.Set("Origin", defaultFrontendOrigin)
|
|
recorder := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(recorder, req)
|
|
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("expected status %d, got %d", http.StatusOK, recorder.Code)
|
|
}
|
|
if !called {
|
|
t.Fatal("expected next handler to be called")
|
|
}
|
|
}
|
|
|
|
func TestFrontendOriginWhitelist_RejectsMissingOrigin(t *testing.T) {
|
|
os.Unsetenv("FRONTEND_ORIGINS")
|
|
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
|
|
handler := FrontendOriginWhitelist(next)
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/auth/forgot-password", nil)
|
|
recorder := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(recorder, req)
|
|
|
|
if recorder.Code != http.StatusForbidden {
|
|
t.Fatalf("expected status %d, got %d", http.StatusForbidden, recorder.Code)
|
|
}
|
|
}
|
|
|
|
func TestFrontendOriginWhitelist_RejectsNonWhitelistedOrigin(t *testing.T) {
|
|
os.Unsetenv("FRONTEND_ORIGINS")
|
|
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
|
|
handler := FrontendOriginWhitelist(next)
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/auth/forgot-password", nil)
|
|
req.Header.Set("Origin", "http://malicious-site.example")
|
|
recorder := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(recorder, req)
|
|
|
|
if recorder.Code != http.StatusForbidden {
|
|
t.Fatalf("expected status %d, got %d", http.StatusForbidden, recorder.Code)
|
|
}
|
|
}
|
|
|
|
func TestFrontendOriginWhitelist_UsesConfiguredOrigins(t *testing.T) {
|
|
os.Setenv("FRONTEND_ORIGINS", "http://localhost:4173, http://localhost:5173")
|
|
defer os.Unsetenv("FRONTEND_ORIGINS")
|
|
|
|
called := false
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
called = true
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
|
|
handler := FrontendOriginWhitelist(next)
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/auth/forgot-password", nil)
|
|
req.Header.Set("Origin", "http://localhost:4173")
|
|
recorder := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(recorder, req)
|
|
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("expected status %d, got %d", http.StatusOK, recorder.Code)
|
|
}
|
|
if !called {
|
|
t.Fatal("expected next handler to be called")
|
|
}
|
|
}
|