diff options
Diffstat (limited to 'internal/middleware')
| -rw-r--r-- | internal/middleware/cors.go | 122 | ||||
| -rw-r--r-- | internal/middleware/cors_test.go | 305 |
2 files changed, 427 insertions, 0 deletions
diff --git a/internal/middleware/cors.go b/internal/middleware/cors.go new file mode 100644 index 0000000..182f9fc --- /dev/null +++ b/internal/middleware/cors.go @@ -0,0 +1,122 @@ +package middleware + +import ( + "log" + "net/http" + "strings" +) + +// CORSConfig holds the configuration for CORS middleware +type CORSConfig struct { + Domain string // Domain principal de l'API (si configuré) + AllowedOrigins []string // Origins autorisées pour CORS +} + +// CORSMiddleware creates a middleware that validates the Host header +// and sets appropriate CORS headers based on the allowed origins +func CORSMiddleware(config *CORSConfig) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Récupérer le Host header + host := r.Host + + // Récupérer l'Origin header (pour les requêtes CORS) + origin := r.Header.Get("Origin") + + // Extraire le hostname du Host (sans le port) + hostWithoutPort := strings.Split(host, ":")[0] + + // Vérification 1: Si un Domain principal est configuré, le Host doit correspondre + if config.Domain != "" { + // Autoriser localhost en développement même si un Domain est configuré + isLocalhost := hostWithoutPort == "localhost" || hostWithoutPort == "127.0.0.1" || strings.HasPrefix(host, "[::") + + if !isLocalhost && hostWithoutPort != config.Domain && host != config.Domain { + log.Printf("❌ Blocked request: host '%s' does not match configured domain '%s'", host, config.Domain) + http.Error(w, "Forbidden: Invalid domain", http.StatusForbidden) + return + } + + if isLocalhost { + log.Printf("⚠️ Allowing localhost/loopback address despite domain restriction: %s", host) + } + } + + // Vérification 2: CORS - vérifier les origins autorisées + // Si aucune restriction CORS n'est configurée, on autorise tout + if len(config.AllowedOrigins) == 0 { + if origin != "" { + log.Printf("⚠️ No CORS origins configured, allowing all origins") + } + log.Printf("✅ Allowed request from: %s (origin: %s)", host, origin) + next.ServeHTTP(w, r) + return + } + + // Vérifier les origins CORS (quand il y a un header Origin) + allowed := false + matchedOrigin := "" + + if origin != "" { + // Extraire le hostname de l'Origin (peut être avec protocole http:// ou https://) + originHost := strings.TrimPrefix(origin, "http://") + originHost = strings.TrimPrefix(originHost, "https://") + originHost = strings.Split(originHost, ":")[0] + + for _, allowedOrigin := range config.AllowedOrigins { + if originHost == allowedOrigin { + allowed = true + matchedOrigin = origin + break + } + } + + if !allowed { + log.Printf("❌ Blocked CORS request from unauthorized origin: %s (host: %s)", origin, host) + http.Error(w, "Forbidden: Invalid origin", http.StatusForbidden) + return + } + + // Définir les headers CORS appropriés + w.Header().Set("Access-Control-Allow-Origin", matchedOrigin) + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With") + w.Header().Set("Access-Control-Allow-Credentials", "true") + w.Header().Set("Access-Control-Max-Age", "3600") + + // Gérer les requêtes preflight OPTIONS + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + } else { + // Pas de header Origin - ce n'est pas une requête CORS + // Si un Domain est configuré, la vérification a déjà été faite plus haut + // Si pas de Domain, on vérifie que le Host correspond à un des AllowedOrigins + if config.Domain == "" { + for _, allowedOrigin := range config.AllowedOrigins { + if hostWithoutPort == allowedOrigin || host == allowedOrigin { + allowed = true + break + } + } + + // Si localhost est utilisé en développement, on peut l'autoriser + if !allowed && (hostWithoutPort == "localhost" || hostWithoutPort == "127.0.0.1" || strings.HasPrefix(host, "[::")) { + log.Printf("⚠️ Allowing localhost/loopback address: %s", host) + allowed = true + } + + if !allowed { + log.Printf("❌ Blocked request from unauthorized host: %s", host) + http.Error(w, "Forbidden: Invalid host", http.StatusForbidden) + return + } + } + } + + log.Printf("✅ Allowed request from: %s (origin: %s)", host, origin) + next.ServeHTTP(w, r) + }) + } +} diff --git a/internal/middleware/cors_test.go b/internal/middleware/cors_test.go new file mode 100644 index 0000000..c36b6ef --- /dev/null +++ b/internal/middleware/cors_test.go @@ -0,0 +1,305 @@ +package middleware + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +// handlerMock est un handler simple pour les tests +func handlerMock(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("OK")) +} + +func TestCORSMiddleware_AllowedHost(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{"example.com", "api.example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "example.com" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) + } + + expected := "OK" + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) + } +} + +func TestCORSMiddleware_UnauthorizedHost(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{"example.com", "api.example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "unauthorized.com" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusForbidden { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusForbidden) + } +} + +func TestCORSMiddleware_HostWithPort(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "example.com:3000" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code for host with port: got %v want %v", status, http.StatusOK) + } +} + +func TestCORSMiddleware_LocalhostAllowed(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + testCases := []string{ + "localhost", + "localhost:3000", + "127.0.0.1", + "127.0.0.1:8080", + "[::1]", + "[::1]:3000", + } + + for _, host := range testCases { + req := httptest.NewRequest("GET", "/", nil) + req.Host = host + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("localhost %s should be allowed: got %v want %v", host, status, http.StatusOK) + } + } +} + +func TestCORSMiddleware_CORSHeaders(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "api.example.com" + req.Header.Set("Origin", "https://example.com") + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) + } + + // Vérifier les headers CORS + if origin := rr.Header().Get("Access-Control-Allow-Origin"); origin != "https://example.com" { + t.Errorf("Access-Control-Allow-Origin = %v, want %v", origin, "https://example.com") + } + + if methods := rr.Header().Get("Access-Control-Allow-Methods"); methods == "" { + t.Error("Access-Control-Allow-Methods should be set") + } + + if headers := rr.Header().Get("Access-Control-Allow-Headers"); headers == "" { + t.Error("Access-Control-Allow-Headers should be set") + } + + if credentials := rr.Header().Get("Access-Control-Allow-Credentials"); credentials != "true" { + t.Errorf("Access-Control-Allow-Credentials = %v, want %v", credentials, "true") + } +} + +func TestCORSMiddleware_PreflightRequest(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("OPTIONS", "/", nil) + req.Host = "api.example.com" + req.Header.Set("Origin", "https://example.com") + req.Header.Set("Access-Control-Request-Method", "POST") + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("preflight request returned wrong status code: got %v want %v", status, http.StatusOK) + } + + // Le body ne devrait pas contenir "OK" car on répond directement à la preflight + if rr.Body.String() == "OK" { + t.Error("preflight request should not execute the handler") + } +} + +func TestCORSMiddleware_NoConfig(t *testing.T) { + config := &CORSConfig{ + AllowedOrigins: []string{}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "any-domain.com" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + // Sans configuration, tout devrait être autorisé + if status := rr.Code; status != http.StatusOK { + t.Errorf("with no config, all should be allowed: got %v want %v", status, http.StatusOK) + } +} + +// Tests pour la validation du Domain configuré + +func TestCORSMiddleware_DomainMatch(t *testing.T) { + config := &CORSConfig{ + Domain: "api.example.com", + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "api.example.com" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("request to configured domain should be allowed: got %v want %v", status, http.StatusOK) + } +} + +func TestCORSMiddleware_DomainMismatch(t *testing.T) { + config := &CORSConfig{ + Domain: "api.example.com", + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "wrong.example.com" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusForbidden { + t.Errorf("request to wrong domain should be blocked: got %v want %v", status, http.StatusForbidden) + } +} + +func TestCORSMiddleware_DomainWithPort(t *testing.T) { + config := &CORSConfig{ + Domain: "api.example.com", + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "api.example.com:3000" + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("request to configured domain with port should be allowed: got %v want %v", status, http.StatusOK) + } +} + +func TestCORSMiddleware_LocalhostWithDomainRestriction(t *testing.T) { + config := &CORSConfig{ + Domain: "api.example.com", + AllowedOrigins: []string{"example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + testCases := []string{ + "localhost", + "localhost:3000", + "127.0.0.1", + "[::1]", + } + + for _, host := range testCases { + req := httptest.NewRequest("GET", "/", nil) + req.Host = host + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("localhost %s should be allowed even with domain restriction: got %v want %v", host, status, http.StatusOK) + } + } +} + +func TestCORSMiddleware_DomainAndCORS(t *testing.T) { + config := &CORSConfig{ + Domain: "api.example.com", + AllowedOrigins: []string{"example.com", "app.example.com"}, + } + + middleware := CORSMiddleware(config) + handler := middleware(http.HandlerFunc(handlerMock)) + + req := httptest.NewRequest("GET", "/", nil) + req.Host = "api.example.com" + req.Header.Set("Origin", "https://example.com") + + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("request with valid domain and origin should be allowed: got %v want %v", status, http.StatusOK) + } + + // Vérifier les headers CORS + if origin := rr.Header().Get("Access-Control-Allow-Origin"); origin != "https://example.com" { + t.Errorf("Access-Control-Allow-Origin = %v, want %v", origin, "https://example.com") + } +} |
