99e5758d4c
- test: exercise register, login, empty listing, small-file upload, updated listing, and authenticated download through the HTTP router. - docs: mark the small-file integration flow as covered in the server roadmap.
376 lines
12 KiB
Go
376 lines
12 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"mime/multipart"
|
|
"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"
|
|
"github.com/dhao2001/mygo/internal/storage"
|
|
)
|
|
|
|
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())
|
|
}
|
|
}
|
|
|
|
func TestAuthenticatedFileFlow(t *testing.T) {
|
|
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)
|
|
fileRepo := repository.NewFileRepository(db)
|
|
credentialRepo := repository.NewCredentialRepository(db)
|
|
store, err := storage.NewLocalStorage(t.TempDir())
|
|
if err != nil {
|
|
t.Fatalf("create local storage: %v", err)
|
|
}
|
|
|
|
const maxUploadSize = 20 << 20
|
|
jwtSecret := []byte("test-secret")
|
|
authService := service.NewAuthService(
|
|
userRepo,
|
|
sessionRepo,
|
|
credentialRepo,
|
|
jwtSecret,
|
|
15*time.Minute,
|
|
168*time.Hour,
|
|
)
|
|
fileService := service.NewFileService(fileRepo, store, maxUploadSize, nil)
|
|
cfg := &config.Config{
|
|
JWT: config.JWTConfig{
|
|
Secret: string(jwtSecret),
|
|
AccessTTL: 15 * time.Minute,
|
|
RefreshTTL: 168 * time.Hour,
|
|
},
|
|
Storage: config.StorageConfig{MaxUploadSize: maxUploadSize},
|
|
}
|
|
webApp := app.NewWebApp(
|
|
cfg,
|
|
db,
|
|
userRepo,
|
|
sessionRepo,
|
|
fileRepo,
|
|
credentialRepo,
|
|
authService,
|
|
service.NewAdminService(userRepo),
|
|
fileService,
|
|
store,
|
|
)
|
|
t.Cleanup(func() {
|
|
if err := webApp.Close(); err != nil {
|
|
t.Errorf("close web app: %v", err)
|
|
}
|
|
})
|
|
router := NewRouter(webApp)
|
|
|
|
registerBody := []byte(`{"username":"web-user","email":"web@example.com","password":"password123"}`)
|
|
registerRequest := httptest.NewRequest(
|
|
http.MethodPost,
|
|
"/api/v1/auth/register",
|
|
bytes.NewReader(registerBody),
|
|
)
|
|
registerRequest.Header.Set("Content-Type", "application/json")
|
|
registerResponse := httptest.NewRecorder()
|
|
router.ServeHTTP(registerResponse, registerRequest)
|
|
if registerResponse.Code != http.StatusCreated {
|
|
t.Fatalf("register: status=%d, body=%s", registerResponse.Code, registerResponse.Body.String())
|
|
}
|
|
|
|
loginBody := []byte(`{"email":"web@example.com","password":"password123"}`)
|
|
loginRequest := httptest.NewRequest(
|
|
http.MethodPost,
|
|
"/api/v1/auth/login",
|
|
bytes.NewReader(loginBody),
|
|
)
|
|
loginRequest.Header.Set("Content-Type", "application/json")
|
|
loginResponse := httptest.NewRecorder()
|
|
router.ServeHTTP(loginResponse, loginRequest)
|
|
if loginResponse.Code != http.StatusOK {
|
|
t.Fatalf("login: status=%d, body=%s", loginResponse.Code, loginResponse.Body.String())
|
|
}
|
|
var tokens struct {
|
|
AccessToken string `json:"access_token"`
|
|
}
|
|
if err := json.Unmarshal(loginResponse.Body.Bytes(), &tokens); err != nil {
|
|
t.Fatalf("decode login response: %v", err)
|
|
}
|
|
if tokens.AccessToken == "" {
|
|
t.Fatal("login response has empty access token")
|
|
}
|
|
|
|
listRequest := httptest.NewRequest(http.MethodGet, "/api/v1/files?offset=0&limit=50", nil)
|
|
listRequest.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
|
|
listResponse := httptest.NewRecorder()
|
|
router.ServeHTTP(listResponse, listRequest)
|
|
if listResponse.Code != http.StatusOK {
|
|
t.Fatalf("initial list: status=%d, body=%s", listResponse.Code, listResponse.Body.String())
|
|
}
|
|
var initialList struct {
|
|
Total int64 `json:"total"`
|
|
}
|
|
if err := json.Unmarshal(listResponse.Body.Bytes(), &initialList); err != nil {
|
|
t.Fatalf("decode initial list: %v", err)
|
|
}
|
|
if initialList.Total != 0 {
|
|
t.Fatalf("initial total=%d, want 0", initialList.Total)
|
|
}
|
|
|
|
fileContent := []byte("MyGO browser milestone upload")
|
|
uploadBody := &bytes.Buffer{}
|
|
multipartWriter := multipart.NewWriter(uploadBody)
|
|
filePart, err := multipartWriter.CreateFormFile("file", "milestone.txt")
|
|
if err != nil {
|
|
t.Fatalf("create multipart file: %v", err)
|
|
}
|
|
if _, err := filePart.Write(fileContent); err != nil {
|
|
t.Fatalf("write multipart file: %v", err)
|
|
}
|
|
if err := multipartWriter.Close(); err != nil {
|
|
t.Fatalf("close multipart writer: %v", err)
|
|
}
|
|
uploadRequest := httptest.NewRequest(http.MethodPost, "/api/v1/files", uploadBody)
|
|
uploadRequest.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
|
|
uploadRequest.Header.Set("Content-Type", multipartWriter.FormDataContentType())
|
|
uploadResponse := httptest.NewRecorder()
|
|
router.ServeHTTP(uploadResponse, uploadRequest)
|
|
if uploadResponse.Code != http.StatusCreated {
|
|
t.Fatalf("upload: status=%d, body=%s", uploadResponse.Code, uploadResponse.Body.String())
|
|
}
|
|
var uploadedFile struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Size int64 `json:"size"`
|
|
}
|
|
if err := json.Unmarshal(uploadResponse.Body.Bytes(), &uploadedFile); err != nil {
|
|
t.Fatalf("decode upload response: %v", err)
|
|
}
|
|
if uploadedFile.Name != "milestone.txt" || uploadedFile.Size != int64(len(fileContent)) {
|
|
t.Fatalf("uploaded file=%+v, want name milestone.txt and size %d", uploadedFile, len(fileContent))
|
|
}
|
|
|
|
listRequest = httptest.NewRequest(http.MethodGet, "/api/v1/files?offset=0&limit=50", nil)
|
|
listRequest.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
|
|
listResponse = httptest.NewRecorder()
|
|
router.ServeHTTP(listResponse, listRequest)
|
|
if listResponse.Code != http.StatusOK {
|
|
t.Fatalf("list after upload: status=%d, body=%s", listResponse.Code, listResponse.Body.String())
|
|
}
|
|
var uploadedList struct {
|
|
Files []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
} `json:"files"`
|
|
Total int64 `json:"total"`
|
|
}
|
|
if err := json.Unmarshal(listResponse.Body.Bytes(), &uploadedList); err != nil {
|
|
t.Fatalf("decode uploaded list: %v", err)
|
|
}
|
|
if uploadedList.Total != 1 || len(uploadedList.Files) != 1 || uploadedList.Files[0].ID != uploadedFile.ID {
|
|
t.Fatalf("uploaded list=%+v, want the uploaded file", uploadedList)
|
|
}
|
|
|
|
downloadRequest := httptest.NewRequest(
|
|
http.MethodGet,
|
|
"/api/v1/files/"+uploadedFile.ID+"/content",
|
|
nil,
|
|
)
|
|
downloadRequest.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
|
|
downloadResponse := httptest.NewRecorder()
|
|
router.ServeHTTP(downloadResponse, downloadRequest)
|
|
if downloadResponse.Code != http.StatusOK {
|
|
t.Fatalf("download: status=%d, body=%s", downloadResponse.Code, downloadResponse.Body.String())
|
|
}
|
|
downloadedContent, err := io.ReadAll(downloadResponse.Body)
|
|
if err != nil {
|
|
t.Fatalf("read download response: %v", err)
|
|
}
|
|
if !bytes.Equal(downloadedContent, fileContent) {
|
|
t.Fatalf("downloaded content=%q, want %q", downloadedContent, fileContent)
|
|
}
|
|
if disposition := downloadResponse.Header().Get("Content-Disposition"); disposition == "" {
|
|
t.Fatal("download response has empty Content-Disposition")
|
|
}
|
|
}
|