43 lines
1.4 KiB
Go
43 lines
1.4 KiB
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"net/http/httptest"
|
||
|
|
"testing"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestCorsAllowsConfiguredOriginPreflight(t *testing.T) {
|
||
|
|
m := NewCorsMiddleware([]string{"http://10.0.0.9:5173"})
|
||
|
|
r := httptest.NewRequest(http.MethodOptions, "/api/v1/settings/ai", nil)
|
||
|
|
r.Header.Set("Origin", "http://10.0.0.9:5173")
|
||
|
|
w := httptest.NewRecorder()
|
||
|
|
|
||
|
|
m.Handle(func(http.ResponseWriter, *http.Request) { t.Fatal("OPTIONS must not reach next handler") })(w, r)
|
||
|
|
|
||
|
|
if w.Code != http.StatusNoContent {
|
||
|
|
t.Fatalf("status = %d, want %d", w.Code, http.StatusNoContent)
|
||
|
|
}
|
||
|
|
if got := w.Header().Get("Access-Control-Allow-Origin"); got != "http://10.0.0.9:5173" {
|
||
|
|
t.Fatalf("allow origin = %q", got)
|
||
|
|
}
|
||
|
|
if got := w.Header().Get("Access-Control-Max-Age"); got != "600" {
|
||
|
|
t.Fatalf("max age = %q", got)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestCorsRejectsUnknownOriginWithEnvelope(t *testing.T) {
|
||
|
|
m := NewCorsMiddleware([]string{"http://10.0.0.9:5173"})
|
||
|
|
r := httptest.NewRequest(http.MethodPut, "/api/v1/settings/ai", nil)
|
||
|
|
r.Header.Set("Origin", "http://untrusted.example")
|
||
|
|
w := httptest.NewRecorder()
|
||
|
|
|
||
|
|
m.Handle(func(http.ResponseWriter, *http.Request) { t.Fatal("rejected origin reached next handler") })(w, r)
|
||
|
|
|
||
|
|
if w.Code != http.StatusForbidden {
|
||
|
|
t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
|
||
|
|
}
|
||
|
|
if got := w.Header().Get("Content-Type"); got != "application/json" {
|
||
|
|
t.Fatalf("content type = %q", got)
|
||
|
|
}
|
||
|
|
}
|