package httpapi import ( "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "speech-learning-api/internal/config" "speech-learning-api/internal/services" ) func TestAIAdminRoutesAreProtected(t *testing.T) { data := &adminTestStore{role: "learner"} auth := services.NewAuthService(nil, "ai-route-secret") token, _ := auth.IssueToken("admin-test") s := &Server{store: data, auth: auth, logger: slog.New(slog.NewTextHandler(io.Discard, nil))} handler := s.Routes() for _, route := range []struct{ method, path string }{{"GET", "settings"}, {"PUT", "profiles/evaluate_course_attempt"}, {"PUT", "budget"}, {"GET", "providers/mistral/models"}, {"GET", "usage"}, {"GET", "calls/test"}, {"POST", "calls/test/resolve"}, {"POST", "test"}, {"POST", "quality"}} { for _, role := range []string{"anonymous", "learner", "admin"} { data.role = role req := httptest.NewRequest(route.method, "/admin/ai/"+route.path, strings.NewReader("{}")) if role != "anonymous" { req.Header.Set("Authorization", "Bearer "+token) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) want := http.StatusForbidden if role == "anonymous" { want = 401 } if role == "admin" { want = 503 } if w.Code != want { t.Fatalf("%s %s %s: %d, expected %d", role, route.method, route.path, w.Code, want) } } } } func TestAISettingsCORSAllowsPUT(t *testing.T) { s := &Server{cfg: config.Config{CORSOrigins: []string{"http://localhost:15175"}}} req := httptest.NewRequest("OPTIONS", "/admin/ai/budget", nil) req.Header.Set("Origin", "http://localhost:15175") req.Header.Set("Access-Control-Request-Method", "PUT") w := httptest.NewRecorder() s.cors(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Fatal("preflight should terminate in middleware") })).ServeHTTP(w, req) if !strings.Contains(w.Header().Get("Access-Control-Allow-Methods"), "PUT") { t.Fatal("PUT settings blocked by CORS") } }