kra-new/internal/server/gin_test.go

268 lines
12 KiB
Go

package server
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"kra/internal/config"
"kra/internal/routecatalog"
"kra/internal/server/handler"
"kra/internal/server/router"
systemservice "kra/internal/service/system"
"github.com/gin-gonic/gin"
)
func NewGinEngine(runtime *config.Store, access *systemservice.AccessControlService, handlers *handler.Set, auth *systemservice.AuthService, security *systemservice.SecurityService, audit *systemservice.AuditRecorder, logger *slog.Logger, version string) *gin.Engine {
return NewGinEngineWithRuntime(runtime, access, auth, security, audit, logger, version, router.NewRoutes(handlers), nil)
}
func emptyHandlers() *handler.Set {
return &handler.Set{
Authority: &handler.Authority{}, Menu: &handler.Menu{}, API: &handler.API{},
Permission: &handler.Permission{}, Organization: &handler.Organization{},
Announcement: &handler.Announcement{}, Email: &handler.Email{}, Payment: &handler.Payment{}, Task: &handler.Task{},
Media: &handler.Media{}, Audit: &handler.Audit{}, Export: &handler.Export{},
Version: &handler.Version{}, Dictionary: &handler.Dictionary{}, Parameter: &handler.Parameter{},
APIToken: &handler.APIToken{}, SystemConfig: &handler.SystemConfig{}, Public: &handler.Public{},
User: &handler.User{}, Navigation: &handler.Navigation{}, Session: &handler.Session{},
IntegrationConfig: &handler.IntegrationConfig{},
}
}
func TestGinRouteContract(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, nil, "test")
routes := engine.Routes()
actual := make([]string, 0, len(routes))
seen := make(map[string]struct{}, len(routes))
for _, route := range routes {
key := route.Method + " " + route.Path
if _, exists := seen[key]; exists {
t.Fatalf("duplicate route %s", key)
}
seen[key] = struct{}{}
actual = append(actual, key)
}
sort.Strings(actual)
value := strings.Join(actual, "\n")
for _, route := range []string{
"GET /integration/configs/:kind",
"GET /integration/configs/:kind/:provider",
"PUT /integration/configs/:kind/:provider",
"POST /integration/configs/:kind/:provider/test",
"DELETE /integration/configs/:kind/:provider",
"POST /payment/providers/:provider/test",
} {
if !strings.Contains(value, route) {
t.Fatalf("route contract missing %s:\n%s", route, value)
}
}
for _, removed := range []string{"GET /payment/configs", "POST /payment/config"} {
if strings.Contains(value, removed) {
t.Fatalf("legacy payment config route still registered: %s", removed)
}
}
}
func TestGinRoutesMatchSharedCatalog(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, nil, "test")
registered := make(map[string]struct{}, len(engine.Routes()))
for _, route := range engine.Routes() {
key := route.Method + " " + route.Path
registered[key] = struct{}{}
if _, ok := routecatalog.Lookup(route.Method, route.Path); !ok {
t.Errorf("registered route has no descriptor: %s", key)
}
}
for _, descriptor := range routecatalog.Descriptors() {
key := descriptor.Method + " " + descriptor.Path
if _, ok := registered[key]; !ok {
t.Errorf("route descriptor is not registered: %s", key)
}
}
}
func TestGinStartupLogsEveryRegisteredRoute(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&output, nil))
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, logger, "test")
text := output.String()
if got, want := strings.Count(text, `"msg":"router registered"`), len(engine.Routes()); got != want {
t.Fatalf("registered route log count = %d, want %d", got, want)
}
if !strings.Contains(text, `"msg":"router register success"`) || !strings.Contains(text, `"route_count":196`) {
t.Fatalf("startup route summary is missing: %s", text)
}
}
func TestSwaggerUsesRegisteredGinRoutes(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, nil, "v1.0.0")
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/swagger/doc.json", nil)
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("swagger document status = %d, body=%s", response.Code, response.Body.String())
}
body := response.Body.String()
for _, expected := range []string{`"swagger":"2.0"`, `"version":"v1.0.0"`, `"/base/login"`, `"/timedTask/triggerTimedTask"`, `"/mediaUpload/{uploadId}"`} {
if !strings.Contains(body, expected) {
t.Fatalf("swagger document missing %s", expected)
}
}
}
func TestSwaggerSupportsRouterPrefix(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{RouterPrefix: "/admin"}}), nil, emptyHandlers(), nil, nil, nil, nil, "v1.0.0")
for _, path := range []string{"/admin/swagger/index.html", "/admin/swagger/doc.json"} {
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, path, nil)
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("swagger path %s status = %d, body=%s", path, response.Code, response.Body.String())
}
if strings.HasSuffix(path, "/doc.json") && !strings.Contains(response.Body.String(), `"basePath":"/admin"`) {
t.Fatalf("swagger document does not use router prefix: %s", response.Body.String())
}
}
}
func TestHealthEndpointKeepsRootProbePathWithRouterPrefix(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{RouterPrefix: "/admin"}}), nil, emptyHandlers(), nil, nil, nil, nil, "test")
for _, path := range []string{"/health", "/admin/health"} {
response := httptest.NewRecorder()
engine.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
if response.Code != http.StatusOK || response.Body.String() != `"ok"` {
t.Fatalf("health path %s status=%d body=%s", path, response.Code, response.Body.String())
}
}
}
func TestSwaggerUsesRootBasePathWithoutRouterPrefix(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, nil, "v1.0.0")
response := httptest.NewRecorder()
engine.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/swagger/doc.json", nil))
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"basePath":"/"`) {
t.Fatalf("swagger basePath mismatch: status=%d body=%s", response.Code, response.Body.String())
}
}
func TestGinDoesNotTrustForwardedIPByDefault(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, nil, "test")
engine.GET("/client-ip", func(c *gin.Context) { c.String(http.StatusOK, c.ClientIP()) })
request := httptest.NewRequest(http.MethodGet, "/client-ip", nil)
request.RemoteAddr = "203.0.113.10:4321"
request.Header.Set("X-Forwarded-For", "198.51.100.20")
response := httptest.NewRecorder()
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK || response.Body.String() != "203.0.113.10" {
t.Fatalf("client IP = %q, status=%d", response.Body.String(), response.Code)
}
}
func TestAnnouncementDataSourceRequiresAuthentication(t *testing.T) {
engine := NewGinEngine(config.NewStore(&config.Config{Admin: &config.Admin{}}), nil, emptyHandlers(), nil, nil, nil, nil, "test")
response := httptest.NewRecorder()
engine.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/info/getInfoDataSource", nil))
if response.Code != http.StatusUnauthorized {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
}
func TestLocalStorageResponseHeaders(t *testing.T) {
root := t.TempDir()
for name, body := range map[string]string{"script.html": "<script>alert(1)</script>", "image.png": "png"} {
if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
runtime := config.NewStore(&config.Config{Admin: &config.Admin{Local: &config.Local{StorePath: root, PathPrefix: "uploads/file"}, Storage: &config.Storage{Type: "local"}}})
engine := NewGinEngine(runtime, nil, emptyHandlers(), nil, nil, nil, nil, "test")
for _, test := range []struct {
path string
attachment bool
}{
{path: "/uploads/file/script.html", attachment: true},
{path: "/uploads/file/image.png", attachment: false},
} {
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, test.path, nil)
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK || response.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("unexpected static response for %s: status=%d headers=%v", test.path, response.Code, response.Header())
}
hasAttachment := strings.Contains(response.Header().Get("Content-Disposition"), "attachment")
if hasAttachment != test.attachment {
t.Fatalf("attachment header for %s = %v, want %v", test.path, hasAttachment, test.attachment)
}
}
}
func TestLocalStorageRoutesAreRegistered(t *testing.T) {
runtime := config.NewStore(&config.Config{Admin: &config.Admin{Local: &config.Local{StorePath: t.TempDir(), PathPrefix: "uploads/file"}}})
engine := NewGinEngine(runtime, nil, emptyHandlers(), nil, nil, nil, nil, "test")
seen := map[string]bool{}
for _, route := range engine.Routes() {
seen[route.Method+" "+route.Path] = true
}
for _, expected := range []string{"GET /uploads/file/*filepath", "HEAD /uploads/file/*filepath"} {
if !seen[expected] {
t.Fatalf("missing registered static route %s", expected)
}
}
response := httptest.NewRecorder()
engine.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/swagger/doc.json", nil))
if strings.Contains(response.Body.String(), "/uploads/file/") {
t.Fatal("swagger document should not expose static file wildcard")
}
}
func TestLocalStorageOldPrefixStopsServingAfterReload(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "image.png"), []byte("png"), 0o600); err != nil {
t.Fatal(err)
}
runtime := config.NewStore(&config.Config{Admin: &config.Admin{Local: &config.Local{StorePath: root, PathPrefix: "uploads/file"}, Storage: &config.Storage{Type: "local"}}})
engine := NewGinEngine(runtime, nil, emptyHandlers(), nil, nil, nil, nil, "test")
runtime.Replace(&config.Config{Admin: &config.Admin{Local: &config.Local{StorePath: root, PathPrefix: "files"}, Storage: &config.Storage{Type: "local"}}})
oldResponse := httptest.NewRecorder()
engine.ServeHTTP(oldResponse, httptest.NewRequest(http.MethodGet, "/uploads/file/image.png", nil))
if oldResponse.Code != http.StatusNotFound {
t.Fatalf("old static prefix status = %d, want %d", oldResponse.Code, http.StatusNotFound)
}
newResponse := httptest.NewRecorder()
engine.ServeHTTP(newResponse, httptest.NewRequest(http.MethodGet, "/files/image.png", nil))
if newResponse.Code != http.StatusOK {
t.Fatalf("new static prefix status = %d, want %d", newResponse.Code, http.StatusOK)
}
}
func TestLocalStorageConflictingPrefixFallsBackWithoutStartupPanic(t *testing.T) {
runtime := config.NewStore(&config.Config{Admin: &config.Admin{Local: &config.Local{StorePath: t.TempDir(), PathPrefix: "api"}, Storage: &config.Storage{Type: "local"}}})
engine := NewGinEngine(runtime, nil, emptyHandlers(), nil, nil, nil, nil, "test")
for _, route := range engine.Routes() {
if route.Method == http.MethodGet && route.Path == "/api/*filepath" {
t.Fatal("conflicting static wildcard must not be registered")
}
}
}
func TestLocalStorageRouteIsNotRegisteredForRemoteStorage(t *testing.T) {
runtime := config.NewStore(&config.Config{Admin: &config.Admin{Local: &config.Local{StorePath: t.TempDir(), PathPrefix: "uploads/file"}, Storage: &config.Storage{Type: "s3"}}})
engine := NewGinEngine(runtime, nil, emptyHandlers(), nil, nil, nil, nil, "test")
for _, route := range engine.Routes() {
if strings.HasSuffix(route.Path, "/*filepath") && strings.HasPrefix(route.Path, "/uploads/file/") {
t.Fatalf("remote storage registered local route %s %s", route.Method, route.Path)
}
}
}