Files
mygo/internal/server/server_test.go
T
ld 63ede5c237 refactor(api): enforce protocol-neutral service boundaries
- refactor: move HTTP status and DTO concerns out of model and service
  layers into API and handler code.
- feat: add admin service boundary and route auth through services
  instead of direct repository access.
- test: add architecture and error tests covering package boundaries,
  redaction, and service behavior.
- docs: record the protocol-neutral boundary decision and update
  architecture and roadmap notes.
2026-07-05 23:30:17 +08:00

184 lines
5.5 KiB
Go

package server
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/dhao2001/mygo/internal/app"
"github.com/dhao2001/mygo/internal/auth"
"github.com/dhao2001/mygo/internal/config"
"github.com/dhao2001/mygo/internal/repository"
"github.com/dhao2001/mygo/internal/service"
)
func TestVersionRoute(t *testing.T) {
cfg := &config.Config{
JWT: config.JWTConfig{
Secret: "test-secret",
AccessTTL: 15 * time.Minute,
RefreshTTL: 168 * time.Hour,
},
}
authService := service.NewAuthService(nil, nil, nil, nil, 15*time.Minute, 7*24*time.Hour)
webApp := app.NewWebApp(cfg, nil, nil, nil, nil, nil, authService, nil, nil, nil)
router := NewRouter(webApp)
req := httptest.NewRequest(http.MethodGet, "/api/v1/version", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if got := rec.Header().Get("Content-Type"); got != "application/json; charset=utf-8" {
t.Fatalf("content-type = %q, want %q", got, "application/json; charset=utf-8")
}
var body struct {
Version string `json:"version"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if body.Version != app.AppVersion {
t.Errorf("version = %q, want %q", body.Version, app.AppVersion)
}
}
func TestAddress(t *testing.T) {
got := Address(config.ServerConfig{Host: "127.0.0.1", Port: 8080})
want := "127.0.0.1:8080"
if got != want {
t.Errorf("Address() = %q, want %q", got, want)
}
}
func TestAdminRoutes(t *testing.T) {
// Setup SQLite :memory:
dbCfg := config.DatabaseConfig{
Driver: "sqlite3",
SQLite: config.SQLiteConfig{Path: ":memory:"},
}
db, err := repository.Open(dbCfg)
if err != nil {
t.Fatalf("open db: %v", err)
}
if err := repository.AutoMigrate(db); err != nil {
t.Fatalf("migrate: %v", err)
}
userRepo := repository.NewUserRepository(db)
sessionRepo := repository.NewSessionRepository(db)
credentialRepo := repository.NewCredentialRepository(db)
jwtSecret := []byte("test-secret")
accessTTL := 15 * time.Minute
refreshTTL := 168 * time.Hour
authService := service.NewAuthService(userRepo, sessionRepo, credentialRepo, jwtSecret, accessTTL, refreshTTL)
adminService := service.NewAdminService(userRepo)
cfg := &config.Config{
JWT: config.JWTConfig{
Secret: "test-secret",
AccessTTL: accessTTL,
RefreshTTL: refreshTTL,
},
}
webApp := app.NewWebApp(cfg, db, userRepo, sessionRepo, nil, credentialRepo, authService, adminService, nil, nil)
router := NewRouter(webApp)
// Helper: register a user via POST /api/v1/auth/register and return the user ID.
register := func(username, email, password string) string {
body, _ := json.Marshal(map[string]string{
"username": username,
"email": email,
"password": password,
})
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("register %s: status=%d, body=%s", username, rec.Code, rec.Body.String())
}
var user struct {
ID string `json:"id"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &user); err != nil {
t.Fatalf("unmarshal register response: %v", err)
}
return user.ID
}
// Register admin user and promote to admin.
adminID := register("admin", "admin@test.local", "adminpass1")
adminUser, err := userRepo.FindByID(context.Background(), adminID)
if err != nil {
t.Fatalf("find admin user: %v", err)
}
adminUser.IsAdmin = true
if err := userRepo.Update(context.Background(), adminUser); err != nil {
t.Fatalf("promote to admin: %v", err)
}
// Generate admin JWT.
adminToken, err := auth.GenerateAccessToken(adminID, jwtSecret, accessTTL)
if err != nil {
t.Fatalf("generate admin token: %v", err)
}
// Register a regular (non-admin) user.
regularID := register("regular", "regular@test.local", "regularpass1")
regularToken, err := auth.GenerateAccessToken(regularID, jwtSecret, accessTTL)
if err != nil {
t.Fatalf("generate regular token: %v", err)
}
// Register a victim user to delete.
victimID := register("victim", "victim@test.local", "victimpass1")
// Helper: make a DELETE request with optional auth header.
deleteUser := func(userID, token string) *httptest.ResponseRecorder {
url := "/api/v1/admin/users/" + userID
req := httptest.NewRequest(http.MethodDelete, url, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
return rec
}
// Test 1: Admin can delete a user → 204.
rec := deleteUser(victimID, adminToken)
if rec.Code != http.StatusNoContent {
t.Errorf("admin delete: status=%d, want %d, body=%s", rec.Code, http.StatusNoContent, rec.Body.String())
}
// Register a second victim for the remaining tests (first victim is soft-deleted).
victim2ID := register("victim2", "victim2@test.local", "victim2pass1")
// Test 2: Non-admin JWT → 403.
rec = deleteUser(victim2ID, regularToken)
if rec.Code != http.StatusForbidden {
t.Errorf("non-admin delete: status=%d, want %d, body=%s", rec.Code, http.StatusForbidden, rec.Body.String())
}
// Test 3: No auth → 401.
rec = deleteUser(victim2ID, "")
if rec.Code != http.StatusUnauthorized {
t.Errorf("no-auth delete: status=%d, want %d, body=%s", rec.Code, http.StatusUnauthorized, rec.Body.String())
}
}