Files
vHost/backend/internal/httpapi/resource_crud_integration_test.go
T

735 lines
31 KiB
Go

package httpapi
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"github.com/go-sql-driver/mysql"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sea-vhost/internal/auth"
"sea-vhost/internal/config"
"sea-vhost/internal/isolation"
"sea-vhost/internal/panel"
"sea-vhost/internal/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func TestResourceCRUDMySQL(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()
if err = db.Migrate(ctx); err != nil {
t.Fatal(err)
}
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(db.BootstrapAdmin(ctx, "crud-admin@example.invalid", "CRUD 管理员", "crud-admin-password-123"))
admin, err := db.UserByLogin(ctx, "crud-admin@example.invalid")
must(err)
root := t.TempDir()
must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"))
secret := "crud-test-session-secret-at-least-thirty-two-characters"
native := &pendingStatePanel{Mock: panel.NewMock(), states: map[int64]bool{}}
projects := service.NewProjects(db, native, 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, UploadLimitBytes: 20 << 20}, 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 b bytes.Buffer
if body != nil {
must(json.NewEncoder(&b).Encode(body))
}
r := httptest.NewRequest(method, "https://control.example.invalid"+path, &b)
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())
}
}
t.Run("node runtime queue is serial and permits unrelated submissions", func(t *testing.T) {
ids := []uint64{}
for _, v := range []string{"queue-a", "queue-b", "queue-c"} {
id, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: v})
must(e)
ids = append(ids, id)
}
if _, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "queue-a"}); e == nil {
t.Fatal("duplicate queued work accepted")
}
first, e := db.ClaimRuntimeJob(ctx)
must(e)
if first.ID != ids[0] {
t.Fatal("queue not FIFO")
}
if _, e = db.ClaimRuntimeJob(ctx); e == nil {
t.Fatal("two runtime jobs execute concurrently on one node")
}
must(db.UpdateRuntimeJob(ctx, first.ID, "completed", "verified", "test"))
second, e := db.ClaimRuntimeJob(ctx)
must(e)
if second.ID != ids[1] {
t.Fatal("wrong queued task")
}
must(db.UpdateRuntimeJob(ctx, second.ID, "interrupted", "installing", "test interruption"))
if _, e = db.ClaimRuntimeJob(ctx); e == nil {
t.Fatal("unverified task did not block later execution")
}
must(db.RetryRuntimeJob(scope.WithNode(ctx, 1), second.ID))
again, e := db.ClaimRuntimeJob(ctx)
must(e)
if again.ID != second.ID {
t.Fatal("resume skipped interrupted work")
}
must(db.UpdateRuntimeJob(ctx, again.ID, "completed", "verified", "test"))
last, e := db.ClaimRuntimeJob(ctx)
must(e)
must(db.UpdateRuntimeJob(ctx, last.ID, "completed", "verified", "test"))
})
t.Run("Python submission returns its job and uses only the source isolator", func(t *testing.T) {
p := &pythonInstallPanel{Mock: panel.NewMock()}
isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p}
svc := service.NewProjects(db, p, isolator, "hosts.example.invalid", root, true, secret, "control.example.invalid")
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, svc)
r := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/admin/runtime-environments/Python/install", strings.NewReader(`{"version":"3.13.1"}`))
r.Header.Set("Origin", "https://control.example.invalid")
r.Header.Set("Content-Type", "application/json")
r.AddCookie(&http.Cookie{Name: "sea_session", Value: token})
w := httptest.NewRecorder()
api.Handler().ServeHTTP(w, r)
var submitted struct {
OK bool `json:"ok"`
JobID uint64 `json:"jobId"`
}
if w.Code != 202 || json.Unmarshal(w.Body.Bytes(), &submitted) != nil || !submitted.OK || submitted.JobID == 0 {
t.Fatalf("missing correlated installation task: %d %s", w.Code, w.Body.String())
}
workerCtx, stop := context.WithCancel(ctx)
done := make(chan struct{})
go func() { defer close(done); svc.RunRuntimeMaintenance(workerCtx) }()
defer func() { stop(); <-done }()
deadline := time.Now().Add(7 * time.Second)
for {
job, e := db.RuntimeJob(ctx, submitted.JobID)
if e != nil {
t.Fatal(e)
}
if job.Status == "completed" {
p.mu.Lock()
calls, installed := p.sourceCalls, p.installed
p.mu.Unlock()
if calls != 1 || !installed || job.TargetVersion != "3.13.1" || !strings.Contains(job.Message, "已安装并核验") {
t.Fatalf("unexpected Python installation result: %#v", job)
}
break
}
if time.Now().After(deadline) || job.Status == "failed" || job.Status == "interrupted" {
t.Fatalf("Python installation did not complete through isolator: %#v", job)
}
time.Sleep(50 * time.Millisecond)
}
})
account, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-customer", Name: "CRUD 用户", Email: "crud-customer@example.invalid", DisplayName: "测试联系人", Password: "crud-customer-password-123", PlanID: 1})
must(err)
user, err := db.UserByLogin(ctx, "crud-customer@example.invalid")
must(err)
userToken, err := auth.NewSessionToken(secret)
must(err)
must(db.CreateSession(ctx, user.ID, userToken, time.Now().Add(time.Hour)))
ap := "/api/v1/admin/tenants/" + strconv.FormatUint(account, 10)
expect(call("GET", ap, nil, ""), 401)
expect(call("GET", ap, nil, userToken), 403)
expect(call("GET", "/api/v1/admin/audit", nil, userToken), 403)
db.Log(ctx, nil, admin.ID, "filter_test", "account", "test", "127.0.0.1", false, "ui19-audit-filter")
expect(call("GET", "/api/v1/admin/audit?q=ui19-audit-filter&result=failure&limit=50&page=1", nil, token), 200)
filtered, total, e := db.FilterAdminActivities(ctx, store.AuditFilter{Query: "ui19-audit-filter", Result: "failure", Limit: 50, Page: 1})
must(e)
if len(filtered) != 1 || total != 1 || filtered[0].Success {
t.Fatal("audit filter ignored criteria")
}
expect(call("GET", ap, nil, token), 200)
expect(call("PUT", ap, map[string]any{"name": "更新用户", "displayName": "更新联系人", "email": "crud-updated@example.invalid"}, token), 204)
if _, err = db.UserByLogin(ctx, "crud-customer@example.invalid"); err == nil {
t.Fatal("old email still authenticates")
}
if _, err = db.UserBySession(ctx, userToken); err == nil {
t.Fatal("email change did not revoke old session")
}
user, err = db.UserByLogin(ctx, "crud-updated@example.invalid")
must(err)
created, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), account, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "crud-host", Runtime: "PHP", Version: "8.4", RunPath: "/public"})
must(err)
id := created.Project.ID
t.Run("batch upload and archive formats", func(t *testing.T) {
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(os.MkdirAll(created.Project.Path, 0770))
fresh, err := auth.NewSessionToken(secret)
must(err)
must(db.CreateSession(ctx, user.ID, fresh, time.Now().Add(time.Hour)))
upload := func(files map[string][]byte, overwrite bool, folder ...bool) *httptest.ResponseRecorder {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
writer.WriteField("path", "")
writer.WriteField("batch", "true")
if overwrite {
writer.WriteField("overwrite", "true")
}
relative := []string{}
for name, data := range files {
relative = append(relative, name)
part, e := writer.CreateFormFile("file", name)
must(e)
_, e = part.Write(data)
must(e)
}
if len(folder) > 0 && folder[0] {
raw, e := json.Marshal(relative)
must(e)
must(writer.WriteField("relativePaths", string(raw)))
}
must(writer.Close())
request := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/projects/"+strconv.FormatUint(id, 10)+"/files", &body)
request.Header.Set("Origin", "https://control.example.invalid")
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(&http.Cookie{Name: "sea_session", Value: fresh})
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response
}
expect(upload(map[string][]byte{"folder/a/index.php": []byte("alpha"), "folder/b/index.php": []byte("beta")}, false, true), 207)
for name, want := range map[string]string{"folder/a/index.php": "alpha", "folder/b/index.php": "beta"} {
raw, e := os.ReadFile(filepath.Join(created.Project.Path, name))
must(e)
if string(raw) != want {
t.Fatal("folder structure lost")
}
}
expect(upload(map[string][]byte{"folder/../escape.txt": []byte("unsafe")}, false, true), 400)
if _, e := os.Stat(filepath.Join(created.Project.Path, "escape.txt")); !os.IsNotExist(e) {
t.Fatal("invalid folder path wrote a file")
}
valid := upload(map[string][]byte{"bulk-a.txt": []byte("alpha"), "bulk-b.txt": []byte("beta")}, false)
expect(valid, 207)
data, e := os.ReadFile(filepath.Join(created.Project.Path, "bulk-a.txt"))
must(e)
if string(data) != "alpha" {
t.Fatal("batch content mismatch")
}
conflict := upload(map[string][]byte{"bulk-a.txt": []byte("different"), "bulk-c.txt": []byte("gamma")}, false)
expect(conflict, 207)
var result struct {
Files []uploadItem `json:"files"`
}
must(json.Unmarshal(conflict.Body.Bytes(), &result))
success, duplicates := 0, 0
for _, item := range result.Files {
if item.Success {
success++
}
if item.Status == 409 {
duplicates++
}
}
if success != 1 || duplicates != 1 {
t.Fatalf("partial results: %+v", result.Files)
}
data, e = os.ReadFile(filepath.Join(created.Project.Path, "bulk-a.txt"))
must(e)
if string(data) != "alpha" {
t.Fatal("unconfirmed overwrite")
}
expect(upload(map[string][]byte{"bulk-a.txt": []byte("updated")}, true), 207)
expect(upload(map[string][]byte{"over-a.bin": make([]byte, 16<<20), "over-b.bin": make([]byte, 15<<20)}, false), 413)
if _, e = os.Stat(filepath.Join(created.Project.Path, "over-a.bin")); !os.IsNotExist(e) {
t.Fatal("oversized batch wrote a file")
}
expect(upload(map[string][]byte{"single-too-large.bin": make([]byte, (20<<20)+1)}, false), 413)
expect(upload(map[string][]byte{"exact-a.bin": make([]byte, 20<<20), "exact-b.bin": make([]byte, 10<<20)}, false), 207)
info, e := os.Stat(filepath.Join(created.Project.Path, "exact-a.bin"))
must(e)
if info.Size() != 20<<20 {
t.Fatal("boundary upload truncated")
}
for _, ext := range []string{".tar", ".tar.gz", ".tgz"} {
var raw bytes.Buffer
tw := tar.NewWriter(&raw)
must(tw.WriteHeader(&tar.Header{Name: "folder/index.txt", Mode: 0660, Size: 5}))
_, e = tw.Write([]byte("hello"))
must(e)
must(tw.Close())
content := raw.Bytes()
if ext != ".tar" {
var packed bytes.Buffer
gz := gzip.NewWriter(&packed)
_, e = gz.Write(content)
must(e)
must(gz.Close())
content = packed.Bytes()
}
name := "archive" + ext
expect(upload(map[string][]byte{name: content}, false), 207)
dest := "expanded" + strings.ReplaceAll(ext, ".", "-")
expect(call("POST", "/api/v1/projects/"+strconv.FormatUint(id, 10)+"/file-actions", map[string]string{"action": "extract", "path": name, "to": dest}, fresh), 204)
content, e = os.ReadFile(filepath.Join(created.Project.Path, dest, "folder/index.txt"))
must(e)
if string(content) != "hello" {
t.Fatal("archive content mismatch")
}
}
})
pending, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), 0, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "pending-runtime", Runtime: "Node.js", Version: "v22.23.3", RunPath: "/"})
must(err)
if enabled, ok := native.states[pending.Project.PanelSiteID]; !ok || enabled {
t.Fatal("unconfigured language site exposes its document root")
}
hp := "/api/v1/admin/projects/" + strconv.FormatUint(id, 10)
expect(call("PUT", hp, map[string]string{"name": "更新主机名称"}, token), 204)
host, err := db.Project(ctx, created.Project.TenantID, id)
must(err)
if host.HostName != created.Project.HostName || host.Path != created.Project.Path || host.Slug != "更新主机名称" {
t.Fatal("rename changed physical identity")
}
sites, err := db.ListSites(ctx, created.Project.TenantID, id)
must(err)
if len(sites) == 0 {
t.Fatal("missing primary site")
}
if _, e := projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "Node.js", "v22.23.3", ""); e == nil {
t.Fatal("cross-language change bypassed host policy")
}
runtimeJob, e := projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "PHP", "8.2", "")
must(e)
must(db.UpdateRuntimeJob(ctx, runtimeJob, "completed", "verified", "queue-only permission test"))
expect(call("PUT", hp, map[string]any{"name": host.Slug, "allowRuntimeChange": true}, token), 204)
policyHost, e := db.Project(ctx, host.TenantID, id)
must(e)
if !policyHost.AllowRuntimeChange {
t.Fatal("host runtime policy not persisted")
}
runtimeJob, e = projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "Node.js", "v22.23.3", "")
must(e)
must(db.UpdateRuntimeJob(ctx, runtimeJob, "completed", "verified", "queue-only permission test"))
// An unresolved tenant runtime job locks only its host; node-level recovery remains available.
localJob, e := projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "PHP", "8.2", "")
must(e)
must(db.UpdateRuntimeJob(ctx, localJob, "interrupted", "switching", "local recovery test"))
ownBlocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, id, 1))
must(e)
otherBlocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, pending.Project.ID, 1))
must(e)
nodeBlocked, e := db.RuntimeMutationBlocked(scope.WithNode(ctx, 1))
must(e)
if !ownBlocked || otherBlocked || nodeBlocked {
t.Fatal("tenant runtime recovery escaped its host scope")
}
independent, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "recovery-check"})
must(e)
claimed, e := db.ClaimRuntimeJob(ctx)
must(e)
if claimed.ID != independent {
t.Fatal("host recovery blocked other queued work")
}
must(db.UpdateRuntimeJob(ctx, independent, "completed", "verified", "test"))
must(db.UpdateRuntimeJob(ctx, localJob, "failed", "failed", "test cleanup"))
must(db.AddCustomDomainForSite(ctx, created.Project.TenantID, id, sites[0].ID, "crud-policy.example.invalid", "pending", 100))
domain, err := db.DomainByName(ctx, created.Project.TenantID, id, sites[0].ID, "crud-policy.example.invalid")
must(err)
policyPath := "/api/v1/admin/domains/" + strconv.FormatUint(domain.ID, 10) + "/metadata"
policy := map[string]string{"resolutionMode": "cname", "cnameTarget": host.Domain, "filingStatus": "approved", "filingNumber": "测试备案号", "filingNote": "事务验收"}
expect(call("PUT", policyPath, policy, token), 204)
expect(call("PUT", policyPath, policy, token), 204)
policy["filingStatus"] = "exempt"
expect(call("PUT", policyPath, policy, token), 204)
updatedDomain, err := db.DomainByID(ctx, domain.ID)
must(err)
if updatedDomain.FilingStatus != "exempt" || updatedDomain.CNAME != host.Domain {
t.Fatal("domain policy not saved atomically")
}
policy["cnameTarget"] = "https://invalid.example.invalid/path"
expect(call("PUT", policyPath, policy, token), 422)
// Removing pending/approved custom names never removes the assigned name or site.
unbindPath := "/api/v1/admin/domains/" + strconv.FormatUint(domain.ID, 10)
expect(call("DELETE", unbindPath, map[string]string{"confirmation": "wrong.example.invalid"}, token), 422)
expect(call("DELETE", unbindPath, map[string]string{"confirmation": domain.Domain}, token), 204)
if _, err = db.DomainByID(ctx, domain.ID); err == nil {
t.Fatal("unbound custom domain remains")
}
domains, err := db.ListDomains(ctx, host.TenantID, &id)
must(err)
for _, d := range domains {
if d.Kind == "assigned" {
expect(call("DELETE", "/api/v1/admin/domains/"+strconv.FormatUint(d.ID, 10), map[string]string{"confirmation": d.Domain}, token), 422)
}
}
// A host account can unbind its own approved custom name, while a user
// without ownership cannot reach the same operation.
must(db.AddCustomDomainForSite(ctx, host.TenantID, id, sites[0].ID, "crud-approved.example.invalid", "approved", 100))
approvedDomain, err := db.DomainByName(ctx, host.TenantID, id, sites[0].ID, "crud-approved.example.invalid")
must(err)
hostUser, err := db.UserByLogin(ctx, host.HostName)
must(err)
hostToken, err := auth.NewSessionToken(secret)
must(err)
must(db.CreateSession(ctx, hostUser.ID, hostToken, time.Now().Add(time.Hour)))
t.Run("panel updates never freeze host writes and migrations stay local", func(t *testing.T) {
// The isolation mock records a path without creating its directory.
if e := os.MkdirAll(host.Path, 0700); e != nil {
t.Fatal(e)
}
filePath := "/api/v1/projects/" + strconv.FormatUint(id, 10) + "/files"
patch, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: "7.4.33", TargetVersion: "7.4.34"})
must(e)
for _, status := range []string{"running", "interrupted"} {
must(db.UpdateRuntimeJob(ctx, patch, status, "installing", "panel update scope regression"))
for _, projectID := range []uint64{0, id, pending.Project.ID} {
blocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, projectID, 1))
must(e)
if blocked {
t.Fatalf("PHP component %s blocked project %d", status, projectID)
}
release, e := projects.BeginRuntimeMutation(scope.WithProject(ctx, projectID, 1))
must(e)
release()
}
expect(call("PUT", filePath, map[string]any{"path": "panel-update-" + status + ".txt", "content": "unrelated host remains writable"}, hostToken), 204)
}
must(db.UpdateRuntimeJob(ctx, patch, "completed", "verified", "test cleanup"))
// Exercise the actual worker while the panel is busy, not just SQL flags.
gatePanel := &busyPatchPanel{Mock: panel.NewMock(), entered: make(chan struct{})}
gateProjects := service.NewProjects(db, gatePanel, patchProbeIsolation{Mock: isolation.Mock{Root: root}}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
gateServer := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, gateProjects)
busyJob, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: "7.4.33", TargetVersion: "7.4.35"})
must(e)
workerCtx, stopWorker := context.WithCancel(ctx)
workerDone := make(chan struct{})
go func() { defer close(workerDone); gateProjects.RunRuntimeMaintenance(workerCtx) }()
defer func() {
stopWorker()
select {
case <-workerDone:
case <-time.After(5 * time.Second):
t.Error("runtime worker did not stop")
}
}()
select {
case <-gatePanel.entered:
case <-time.After(5 * time.Second):
t.Fatal("runtime worker never reached the panel queue")
}
body := strings.NewReader(`{"path":"panel-worker-busy.txt","content":"writes remain available"}`)
request := httptest.NewRequest("PUT", "https://control.example.invalid"+filePath, body)
request.Header.Set("Origin", "https://control.example.invalid")
request.Header.Set("Content-Type", "application/json")
request.AddCookie(&http.Cookie{Name: "sea_session", Value: hostToken})
response := httptest.NewRecorder()
gateServer.Handler().ServeHTTP(response, request)
if response.Code != 204 {
t.Fatalf("busy panel froze unrelated host writes: HTTP %d %s", response.Code, response.Body.String())
}
stopWorker()
select {
case <-workerDone:
case <-time.After(5 * time.Second):
t.Fatal("runtime worker did not stop")
}
must(db.UpdateRuntimeJob(ctx, busyJob, "failed", "failed", "test cleanup"))
for _, action := range []string{"migrate", "runtime_change"} {
siteID := sites[0].ID
job, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: action, Runtime: "PHP", FromVersion: "8.4", TargetVersion: "8.2", SiteID: &siteID})
must(e)
must(db.UpdateRuntimeJob(ctx, job, "interrupted", "switching", "target host only"))
for _, projectID := range []uint64{0, id, pending.Project.ID} {
blocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, projectID, 1))
must(e)
if blocked != (projectID == id) {
t.Fatalf("%s scope mismatch for project %d", action, projectID)
}
}
expect(call("PUT", filePath, map[string]any{"path": "conflicting-site-switch.txt", "content": "must be rejected"}, hostToken), 423)
must(db.UpdateRuntimeJob(ctx, job, "failed", "failed", "test cleanup"))
}
})
foreignAccount, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-foreign", Name: "外部用户", Email: "foreign@example.invalid", DisplayName: "外部", Password: "foreign-password-123", PlanID: 1})
must(err)
_ = foreignAccount
foreignUser, err := db.UserByLogin(ctx, "foreign@example.invalid")
must(err)
foreignToken, err := auth.NewSessionToken(secret)
must(err)
must(db.CreateSession(ctx, foreignUser.ID, foreignToken, time.Now().Add(time.Hour)))
userDomainPath := "/api/v1/domains/" + strconv.FormatUint(approvedDomain.ID, 10)
expect(call("DELETE", userDomainPath, map[string]string{"confirmation": approvedDomain.Domain}, foreignToken), 404)
expect(call("DELETE", userDomainPath, map[string]string{"confirmation": approvedDomain.Domain}, hostToken), 204)
must(db.UpdateQuotaMeasurement(scope.WithProject(ctx, id, 1), host.TenantID, store.Usage{BandwidthBytes: 36 << 20}, time.Now().UTC(), nil, false))
dashboardResponse := call("GET", "/api/v1/dashboard", nil, hostToken)
expect(dashboardResponse, 200)
var measured struct {
Projects []store.Project `json:"projects"`
}
must(json.Unmarshal(dashboardResponse.Body.Bytes(), &measured))
if len(measured.Projects) != 1 || measured.Projects[0].ID != id || measured.Projects[0].BandwidthBytes != 36<<20 {
t.Fatal("dashboard did not return scoped measured host traffic")
}
if _, err = db.Site(ctx, host.TenantID, id, sites[0].ID); err != nil {
t.Fatal("unbinding removed site")
}
planID, err := db.CreatePlan(ctx, store.NewPlan{Name: "unused-copy", StorageBytes: 1 << 30, DatabaseBytes: 1 << 30, BandwidthBytes: 1 << 30, ProcessLimit: 10, FTPLimit: 1, DatabaseLimit: 1, ProjectLimit: 1})
must(err)
pp := "/api/v1/admin/plans/" + strconv.FormatUint(planID, 10)
expect(call("DELETE", pp, map[string]string{"confirmation": "wrong"}, token), 409)
expect(call("DELETE", pp, map[string]string{"confirmation": "unused-copy"}, token), 204)
if _, err = db.Plan(ctx, planID); err == nil {
t.Fatal("deleted plan visible")
}
if err = db.DeleteUnusedPlan(ctx, 1, "基础套餐"); err == nil {
t.Fatal("default plan deleted")
}
expect(call("DELETE", ap, map[string]string{"confirmation": "crud-customer"}, token), 409)
expect(call("DELETE", hp, map[string]string{"confirmation": "wrong-host"}, token), 422)
expect(call("DELETE", hp, map[string]string{"confirmation": host.HostName}, token), 204)
first, err := db.HostLifecycle(ctx, id)
must(err)
if first.State != "recycle" || first.PurgeAfter == nil || time.Until(*first.PurgeAfter) < 167*time.Hour {
t.Fatal("incorrect manual recycle window")
}
expect(call("DELETE", hp, map[string]string{"confirmation": host.HostName}, token), 204)
second, err := db.HostLifecycle(ctx, id)
must(err)
if !first.PurgeAfter.Equal(*second.PurgeAfter) {
t.Fatal("retry extended retention")
}
if _, err = db.UserByLogin(ctx, host.HostName); err == nil {
t.Fatal("recycled host still authenticates")
}
if err = db.HostWritable(scope.WithProject(ctx, id, 1), host.TenantID); err == nil {
t.Fatal("recycled host writable")
}
if err = db.SetHostSubscription(ctx, id, 1, nil); err == nil {
t.Fatal("ordinary renewal restored manual deletion")
}
if _, err = db.ProjectForUser(scope.WithAccount(ctx, account), user, id); err == nil {
t.Fatal("recycled host visible to previous owner")
}
expect(call("DELETE", ap, map[string]string{"confirmation": "crud-customer"}, token), 409)
recycleHosts, e := db.ListAdminProjects(ctx)
must(e)
var recycledVersion uint64
for _, h := range recycleHosts {
if h.ID == id {
recycledVersion = h.OwnershipVersion
}
}
expect(call("DELETE", hp+"/recycled-owner", map[string]any{"ownershipVersion": recycledVersion + 1, "confirmation": host.HostName}, token), 409)
expect(call("DELETE", hp+"/recycled-owner", map[string]any{"ownershipVersion": recycledVersion, "confirmation": host.HostName}, token), 204)
explicitOwner, e := db.ProjectOwner(ctx, id)
must(e)
if explicitOwner != nil {
t.Fatal("explicit recycled detach failed")
}
expect(call("POST", hp+"/restore", nil, token), 204)
restored, err := db.Project(ctx, host.TenantID, id)
must(err)
if restored.Status == "running" {
t.Fatal("restore auto-started site")
}
must(db.HostWritable(scope.WithProject(ctx, id, 1), host.TenantID))
ftps, err := db.ListFTPResources(scope.WithProject(ctx, id, 1), host.TenantID, &id)
must(err)
for _, ftp := range ftps {
if ftp.Enabled {
t.Fatal("restore auto-enabled FTP")
}
}
// Reassigning away permits deleting the account while retaining host access.
hosts, err := db.ListAdminProjects(ctx)
must(err)
var version uint64
for _, h := range hosts {
if h.ID == id {
version = h.OwnershipVersion
}
}
_, err = projects.ChangeHostOwner(scope.WithProject(ctx, id, 1), id, version, 0, "preserve", true, false)
must(err)
expect(call("DELETE", ap, map[string]string{"confirmation": "crud-customer"}, token), 204)
if _, err = db.AccountProfile(ctx, account); err == nil {
t.Fatal("deleted account still visible")
}
if err = db.SetAccountEnabled(ctx, account, true); err == nil {
t.Fatal("batch re-enabled deleted account")
}
if err = db.SetTenantExpiry(ctx, account, nil); err == nil {
t.Fatal("legacy expiry re-enabled deleted account")
}
if _, err = db.UserByLogin(ctx, "crud-updated@example.invalid"); err == nil {
t.Fatal("deleted user authenticates")
}
// Local node cannot be deleted, and existing hosts prevent deleting a remote.
expect(call("DELETE", "/api/v1/admin/nodes/1", map[string]string{"confirmation": "本机节点"}, token), 409)
node := store.Node{Name: "CRUD 节点", Endpoint: "https://crud.example.invalid:9443", RootDomain: "hosts.example.invalid", TenantRoot: "/www/wwwroot/seavHost/vHost", FTPCertificateDomain: "control.example.invalid"}
nodeID, err := db.CreateNode(ctx, node)
must(err)
np := "/api/v1/admin/nodes/" + strconv.FormatUint(nodeID, 10)
expect(call("GET", np, nil, token), 200)
node.Name = "更新节点"
expect(call("PATCH", np, node, token), 204)
stored, err := db.Node(ctx, nodeID)
must(err)
if stored.Enabled || stored.Name != "更新节点" {
t.Fatal("metadata edit changed enable flag")
}
must(db.SetNodeEnabled(ctx, nodeID, true))
expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409)
must(db.SetNodeEnabled(ctx, nodeID, false))
// Backups and uncertain controller tasks both block deletion.
must(db.CreateTenantBackup(scope.WithNode(ctx, nodeID), host.TenantID, id, host.HostName, "/test/crud-backup.tar", 1, time.Now().Add(14*24*time.Hour), 1))
expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409)
backups, err := db.ExpiredTenantBackups(ctx, time.Now().Add(15*24*time.Hour), 100)
must(err)
for _, b := range backups {
if b.NodeID == nodeID {
must(db.MarkTenantBackupDeleted(ctx, b.ID))
}
}
taskID, err := db.StartControlTask(ctx, nodeID, 0, "crud/test", "11111111111111111111111111111111")
must(err)
expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409)
must(db.FinishControlTask(ctx, taskID, "uncertain", "test"))
expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409)
must(db.FinishControlTask(ctx, taskID, "succeeded", "verified"))
expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 204)
if _, err = db.Node(ctx, nodeID); err == nil {
t.Fatal("deleted node visible")
}
must(db.SetNodeCredentials(ctx, nodeID, []byte("revoked")))
if err = db.SetNodeEnabled(ctx, nodeID, true); err == nil {
t.Fatal("deleted node re-enabled")
}
expect(call("GET", np, nil, token), 404)
}
type pendingStatePanel struct {
*panel.Mock
states map[int64]bool
}
type pythonInstallPanel struct {
*panel.Mock
mu sync.Mutex
installed bool
sourceCalls int
}
func (p *pythonInstallPanel) RuntimeEnvironments(ctx context.Context) ([]panel.RuntimeEnvironment, error) {
items, err := p.Mock.RuntimeEnvironments(ctx)
p.mu.Lock()
installed := p.installed
p.mu.Unlock()
if installed {
for i := range items {
if items[i].Name == "Python" {
items[i].Installed = append(items[i].Installed, "3.13.1")
}
}
}
return items, err
}
func (p *pythonInstallPanel) InstallRuntimeEnvironment(context.Context, string, string) error {
return fmt.Errorf("unexpected panel installer; Python must use the source isolator")
}
type pythonInstallIsolation struct {
isolation.Mock
panel *pythonInstallPanel
}
func (i pythonInstallIsolation) InstallPythonRuntime(_ context.Context, version string) error {
if version != "3.13.1" {
return fmt.Errorf("unexpected Python version")
}
i.panel.mu.Lock()
defer i.panel.mu.Unlock()
i.panel.installed = true
i.panel.sourceCalls++
return nil
}
type busyPatchPanel struct {
*panel.Mock
entered chan struct{}
}
func (p *busyPatchPanel) PHPRuntimeUpdatePending(ctx context.Context, _ string) (bool, error) {
close(p.entered)
<-ctx.Done()
return false, ctx.Err()
}
func (*busyPatchPanel) UpdatePHPRuntime(context.Context, string, string) error { return nil }
func (*busyPatchPanel) ManagedRuntime(context.Context, int64) (panel.RuntimeSpec, error) {
return panel.RuntimeSpec{}, nil
}
func (*busyPatchPanel) ReplaceManagedRuntime(context.Context, int64, panel.RuntimeSpec) error {
return nil
}
type patchProbeIsolation struct{ isolation.Mock }
func (patchProbeIsolation) MaintainPHP(context.Context, isolation.PHPMaintenanceSpec) (isolation.PHPState, error) {
return isolation.PHPState{Version: "7.4.33"}, nil
}
func (patchProbeIsolation) ProbeRuntime(context.Context, isolation.RuntimeProbeSpec) (isolation.RuntimeObservation, error) {
return isolation.RuntimeObservation{Healthy: true}, nil
}
func (patchProbeIsolation) CopyPythonDependencies(context.Context, isolation.PanelRuntimeSpec, string) error {
return nil
}
func (p *pendingStatePanel) SetSiteState(_ context.Context, id int64, _ string, enabled bool) error {
p.states[id] = enabled
return nil
}