package httpapi import ( "bytes" "context" "encoding/json" "github.com/go-sql-driver/mysql" "net/http" "net/http/httptest" "os" "sea-vhost/internal/auth" "sea-vhost/internal/config" "sea-vhost/internal/isolation" "sea-vhost/internal/panel" "sea-vhost/internal/service" "sea-vhost/internal/store" "strings" "testing" "time" ) func TestNamedAccountMySQL(t *testing.T) { dsn := os.Getenv("SEA_TEST_MYSQL_DSN") if dsn == "" { t.Skip("disposable MySQL schema not supplied") } parsed, err := mysql.ParseDSN(dsn) if err != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") { t.Fatal("refusing a non-test schema") } db, err := store.Open(dsn) if err != nil { t.Fatal(err) } defer db.Close() ctx := context.Background() must := func(err error) { t.Helper() if err != nil { t.Fatal(err) } } must(db.Migrate(ctx)) must(db.BootstrapAdmin(ctx, "identity-admin@example.invalid", "测试管理员", "identity-admin-password-123")) admin, err := db.UserByLogin(ctx, "identity-admin@example.invalid") must(err) root := t.TempDir() must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid")) secret := "named-account-test-session-secret-at-least-thirty-two-characters" projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid") server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects) token, err := auth.NewSessionToken(secret) must(err) must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour))) call := func(method, path string, body any, session string) *httptest.ResponseRecorder { var buffer bytes.Buffer must(json.NewEncoder(&buffer).Encode(body)) r := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer) r.Header.Set("Origin", "https://control.example.invalid") r.Header.Set("Content-Type", "application/json") if session != "" { r.AddCookie(&http.Cookie{Name: "sea_session", Value: session}) } w := httptest.NewRecorder() server.Handler().ServeHTTP(w, r) return w } expect := func(w *httptest.ResponseRecorder, status int) { t.Helper() if w.Code != status { t.Fatalf("HTTP %d want %d: %s", w.Code, status, w.Body.String()) } } input := map[string]any{"loginName": "customer01", "displayName": "测试用户", "email": "customer01@example.invalid", "password": "identity-user-password-123", "planId": 1} created := call("POST", "/api/v1/admin/tenants", input, token) expect(created, 201) var value struct { ID uint64 `json:"id"` } must(json.Unmarshal(created.Body.Bytes(), &value)) profile, err := db.AccountProfile(ctx, value.ID) must(err) if profile.LoginName != "customer01" || profile.Name != "测试用户" || profile.DisplayName != "测试用户" || profile.Slug != accountSlug("customer01") { t.Fatalf("unexpected profile: %+v", profile) } for _, login := range []string{"customer01", "customer01@example.invalid"} { expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": login, "password": "identity-user-password-123"}, ""), 200) } expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": "customer01", "password": "incorrect-password"}, ""), 401) duplicate := map[string]any{"loginName": "customer01", "displayName": "重复用户", "email": "different@example.invalid", "password": "identity-user-password-123", "planId": 1} expect(call("POST", "/api/v1/admin/tenants", duplicate, token), 422) input["loginName"] = "another-user" expect(call("POST", "/api/v1/admin/tenants", input, token), 422) input["loginName"] = "bad@name" expect(call("POST", "/api/v1/admin/tenants", input, token), 422) list, err := db.ListTenants(ctx) must(err) if len(list) != 1 || list[0].LoginName != "customer01" { t.Fatalf("unexpected user list: %+v", list) } profile.Email = "updated@example.invalid" profile.Name = "修改名称" profile.DisplayName = profile.Name must(db.UpdateAccount(ctx, value.ID, profile)) updated, err := db.UserByLogin(ctx, "customer01") must(err) if updated.Email != profile.Email { t.Fatal("email update failed") } _, err = db.UserByLogin(ctx, "customer01@example.invalid") if err == nil { t.Fatal("old email still usable") } batch := batchRequest{Operation: "create_users", Rows: []batchRow{{LoginName: "batch-account", DisplayName: "批量用户", Email: "batch-account@example.invalid"}}} preview, err := server.normalizeBatch(ctx, &batch) must(err) if len(preview) != 1 || !preview[0].Valid { t.Fatalf("batch preview rejected: %+v", preview) } stable := batch.Rows[0].Slug preview, err = server.normalizeBatch(ctx, &batch) must(err) if !preview[0].Valid || stable != batch.Rows[0].Slug { t.Fatal("batch identity changed on retry") } result, err := server.performBatchRow(ctx, "create_users", batch.Rows[0]) must(err) if result.Login != "batch-account" || result.Password == "" { t.Fatal("batch credentials missing login account") } expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": result.Login, "password": result.Password}, ""), 200) preview, err = server.normalizeBatch(ctx, &batch) must(err) if preview[0].Valid { t.Fatal("duplicate batch account accepted") } t.Log("single creation, account/email login, password rejection, duplicate/invalid account rejection, stable batch identity, user listing and email update passed") }