608 lines
27 KiB
Go
608 lines
27 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"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/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}, 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}, 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
|
|
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}, 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
|
|
}
|