package httpapi import ( "context" "io" "log/slog" "net/http" "net/http/httptest" "testing" "speech-learning-api/internal/config" "speech-learning-api/internal/domain" "speech-learning-api/internal/services" ) type adminTestStore struct { DataStore role string } func (s *adminTestStore) GetUser(_ context.Context, id string) (domain.User, error) { return domain.User{ID: id, Role: s.role}, nil } func (s *adminTestStore) AdminOverview(_ context.Context) (domain.AdminOverview, error) { return domain.AdminOverview{UsersTotal: 3}, nil } func (s *adminTestStore) AdminUsers(_ context.Context, _ string, page int) (domain.AdminUserPage, error) { return domain.AdminUserPage{Page: page}, nil } func (s *adminTestStore) DebugStatus(_ context.Context) domain.DebugDBStatus { return domain.DebugDBStatus{OK: true} } func TestAdminRoutesRequireCurrentAdminRole(t *testing.T) { data := &adminTestStore{role: "learner"} auth := services.NewAuthService(nil, "test-secret") server := &Server{ cfg: config.Config{DebugEnabled: true}, store: data, auth: auth, logger: slog.New(slog.NewTextHandler(io.Discard, nil)), } token, err := auth.IssueToken("usr_1") if err != nil { t.Fatal(err) } for _, testCase := range []struct { path string }{ {"/admin/overview"}, {"/admin/users"}, {"/debug/status"}, } { t.Run(testCase.path, func(t *testing.T) { handler := server.Routes() request := func(withToken bool) int { req := httptest.NewRequest(http.MethodGet, testCase.path, nil) if withToken { req.Header.Set("Authorization", "Bearer "+token) } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) return recorder.Code } data.role = "learner" if got := request(false); got != http.StatusUnauthorized { t.Fatalf("anonymous status = %d, want 401", got) } if got := request(true); got != http.StatusForbidden { t.Fatalf("learner status = %d, want 403", got) } data.role = "admin" if got := request(true); got != http.StatusOK { t.Fatalf("admin status = %d, want 200", got) } data.role = "learner" if got := request(true); got != http.StatusForbidden { t.Fatalf("demoted admin status = %d, want 403", got) } }) } }