feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,243 @@
|
||||
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/hosting"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/service"
|
||||
"sea-vhost/internal/store"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHostingFeaturesMySQL(t *testing.T) {
|
||||
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("disposable MySQL schema not supplied")
|
||||
}
|
||||
parsed, e := mysql.ParseDSN(dsn)
|
||||
if e != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") {
|
||||
t.Fatal("refusing a non-test schema")
|
||||
}
|
||||
db, e := store.Open(dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
ctx := context.Background()
|
||||
if e = db.Migrate(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = db.BootstrapAdmin(ctx, "features-admin@example.invalid", "功能测试管理员", "features-admin-password-123"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
root := t.TempDir()
|
||||
if e = db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
admin, _ := db.UserByLogin(ctx, "features-admin@example.invalid")
|
||||
secret := "features-test-secret-longer-than-thirty-two-characters"
|
||||
native := panel.NewMock()
|
||||
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)
|
||||
handler := server.Handler()
|
||||
session := func(u store.User) string {
|
||||
token, e := auth.NewSessionToken(secret)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = db.CreateSession(ctx, u.ID, token, time.Now().Add(time.Hour)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return token
|
||||
}
|
||||
adminToken := session(admin)
|
||||
call := func(method, path string, body any, token, bearer, idempotency string) *httptest.ResponseRecorder {
|
||||
var b bytes.Buffer
|
||||
if body != nil {
|
||||
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 token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: "sea_session", Value: token})
|
||||
}
|
||||
if bearer != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
if idempotency != "" {
|
||||
r.Header.Set("Idempotency-Key", idempotency)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
expect := func(w *httptest.ResponseRecorder, status int) {
|
||||
t.Helper()
|
||||
if w.Code != status {
|
||||
t.Fatalf("got %d want %d: %s", w.Code, status, w.Body.String())
|
||||
}
|
||||
}
|
||||
plans, _ := db.ListPlans(ctx)
|
||||
user := func(slug string) store.User {
|
||||
w := call("POST", "/api/v1/admin/tenants", map[string]any{"slug": slug, "name": slug, "displayName": slug, "planId": plans[0].ID, "email": slug + "@example.invalid", "password": "features-user-password-123"}, adminToken, "", "")
|
||||
expect(w, 201)
|
||||
u, e := db.UserByLogin(ctx, slug+"@example.invalid")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return u
|
||||
}
|
||||
a, b := user("features-a"), user("features-b")
|
||||
aToken, bToken := session(a), session(b)
|
||||
created, e := projects.CreateManagedHost(ctx, *a.TenantID, service.CreateProjectInput{Name: "features-host", NodeID: 1, PlanID: plans[0].ID, Runtime: "PHP", Version: "8.4", RunPath: "/public"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
p := created.Project
|
||||
scoped := scope.WithProject(scope.WithAccount(ctx, *a.TenantID), p.ID, p.NodeID)
|
||||
sites, e := db.ListSites(scoped, p.TenantID, p.ID)
|
||||
if e != nil || len(sites) != 1 {
|
||||
t.Fatal("site missing", e)
|
||||
}
|
||||
site := sites[0]
|
||||
base := fmt.Sprintf("/api/v1/projects/%d", p.ID)
|
||||
hostUser, e := db.UserByLogin(ctx, p.HostName)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hostToken := session(hostUser)
|
||||
settings := hosting.DefaultWebsite()
|
||||
settings.Index = []string{"home.html", "index.php"}
|
||||
settings.Maintenance = true
|
||||
expect(call("PUT", fmt.Sprintf("%s/sites/%d/settings", base, site.ID), settings, aToken, "", ""), 204)
|
||||
expect(call("GET", fmt.Sprintf("%s/sites/%d/settings", base, site.ID), nil, bToken, "", ""), 404)
|
||||
startup := hosting.Startup{WorkDir: ".", Environment: map[string]string{"APP_SECRET": "features-encrypted-marker"}}
|
||||
expect(call("PUT", fmt.Sprintf("%s/sites/%d/startup", base, site.ID), startup, aToken, "", ""), 204)
|
||||
cipher, e := db.StartupCipher(ctx, site.ID)
|
||||
if e != nil || bytes.Contains(cipher, []byte("features-encrypted-marker")) {
|
||||
t.Fatal("environment not encrypted")
|
||||
}
|
||||
startup.Environment["LD_PRELOAD"] = "evil.so"
|
||||
expect(call("PUT", fmt.Sprintf("%s/sites/%d/startup", base, site.ID), startup, aToken, "", ""), 422)
|
||||
expect(call("POST", base+"/ftp", map[string]string{"action": "disable"}, aToken, "", ""), 200)
|
||||
ftp, e := db.ListFTPResources(scoped, p.TenantID, &p.ID)
|
||||
if e != nil || ftp[0].Enabled {
|
||||
t.Fatal("FTP disable not persisted", e)
|
||||
}
|
||||
expect(call("POST", base+"/ftp", map[string]string{"action": "reset"}, aToken, "", ""), 200)
|
||||
expect(call("POST", base+"/ftp", map[string]string{"action": "enable"}, aToken, "", ""), 200)
|
||||
expect(call("GET", base+"/database-admin/", nil, aToken, "", ""), 200)
|
||||
expect(call("GET", base+"/database-admin/", nil, bToken, "", ""), 404)
|
||||
task := store.UserSchedule{ProjectID: p.ID, SiteID: site.ID, Name: "功能测试任务", Cron: "*/5 * * * *", Timezone: "Asia/Shanghai", Kind: "php", Version: "8.4", Target: "task.php", Arguments: []string{"features-task-secret"}, Enabled: false}
|
||||
expect(call("GET", "/api/v1/schedules", nil, hostToken, "", ""), 403)
|
||||
expect(call("POST", "/api/v1/schedules", task, hostToken, "", ""), 403)
|
||||
w := call("POST", "/api/v1/schedules", task, aToken, "", "")
|
||||
expect(w, 200)
|
||||
var id struct {
|
||||
ID uint64 `json:"id"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &id)
|
||||
taskID := id.ID
|
||||
saved, e := db.UserSchedule(ctx, a.ID, taskID)
|
||||
if e != nil || bytes.Contains(saved.ConfigCipher, []byte("features-task-secret")) || saved.Target != "" {
|
||||
t.Fatal("task inputs not encrypted", e)
|
||||
}
|
||||
expect(call("GET", fmt.Sprintf("/api/v1/schedules/%d/runs", taskID), nil, bToken, "", ""), 404)
|
||||
expect(call("POST", fmt.Sprintf("/api/v1/schedules/%d/run", taskID), nil, aToken, "", ""), 200)
|
||||
if e = projects.DispatchUserSchedules(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
runs, e := projects.ScheduleRuns(ctx, a, taskID)
|
||||
if e != nil || len(runs) != 1 || runs[0].State != "succeeded" {
|
||||
t.Fatalf("scheduled run %+v %v", runs, e)
|
||||
}
|
||||
for i := 0; i < 9; i++ {
|
||||
task.Name = fmt.Sprint("任务", i)
|
||||
expect(call("POST", "/api/v1/schedules", task, aToken, "", ""), 200)
|
||||
}
|
||||
expect(call("POST", "/api/v1/schedules", task, aToken, "", ""), 422)
|
||||
version, _ := db.ProjectOwnershipVersion(ctx, p.ID)
|
||||
if _, e = db.BeginOwnershipChange(ctx, p.ID, version, *b.TenantID, "preserve", false, false, nil); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
saved, e = db.UserSchedule(ctx, a.ID, taskID)
|
||||
if e != nil || saved.Enabled || saved.LastState != "ownership_paused" {
|
||||
t.Fatal("ownership change failed to pause task", e)
|
||||
}
|
||||
expect(call("POST", fmt.Sprintf("/api/v1/schedules/%d/run", taskID), nil, aToken, "", ""), 422)
|
||||
makeKey := func(scopes []string) (uint64, string) {
|
||||
w := call("POST", "/api/v1/admin/integration-keys", map[string]any{"name": "测试 API", "scopes": scopes, "expiresAt": time.Now().Add(time.Hour)}, adminToken, "", "")
|
||||
expect(w, 201)
|
||||
var v struct {
|
||||
ID uint64 `json:"id"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &v)
|
||||
return v.ID, v.Token
|
||||
}
|
||||
_, readKey := makeKey([]string{"hosts:read", "tasks:read"})
|
||||
expect(call("GET", "/api/integration/v1/hosts", nil, "", readKey, ""), 200)
|
||||
expect(call("GET", "/api/integration/v1/users", nil, "", readKey, ""), 403)
|
||||
expect(call("GET", "/api/integration/v1/hosts", nil, adminToken, "", ""), 401)
|
||||
expect(call("POST", "/api/v1/admin/integration-keys", map[string]any{}, aToken, "", ""), 403)
|
||||
keyID, key := makeKey([]string{"users:write", "users:read", "tasks:read", "credentials:read"})
|
||||
input := map[string]any{"rows": []map[string]string{{"slug": "api-user", "name": "API 用户", "email": "api-user@example.invalid"}}}
|
||||
expect(call("POST", "/api/integration/v1/users", input, "", key, ""), 400)
|
||||
w = call("POST", "/api/integration/v1/users", input, "", key, "feature-idempotency-1")
|
||||
expect(w, 202)
|
||||
var job struct {
|
||||
Batch store.AdminBatch `json:"batch"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &job)
|
||||
batchID := job.Batch.ID
|
||||
w = call("POST", "/api/integration/v1/users", input, "", key, "feature-idempotency-1")
|
||||
expect(w, 202)
|
||||
json.Unmarshal(w.Body.Bytes(), &job)
|
||||
if job.Batch.ID != batchID {
|
||||
t.Fatal("idempotency duplicated batch")
|
||||
}
|
||||
expect(call("POST", "/api/integration/v1/users", map[string]any{"rows": []batchRow{{Slug: "changed-user", Name: "changed", Email: "changed@example.invalid"}}}, "", key, "feature-idempotency-1"), 409)
|
||||
expect(call("GET", fmt.Sprintf("/api/integration/v1/tasks/%d", batchID), nil, "", readKey, ""), 404)
|
||||
expect(call("GET", fmt.Sprintf("/api/integration/v1/tasks/%d", batchID), nil, "", key, ""), 200)
|
||||
expect(call("DELETE", fmt.Sprintf("/api/v1/admin/integration-keys/%d", keyID), nil, adminToken, "", ""), 204)
|
||||
expect(call("GET", "/api/integration/v1/users", nil, "", key, ""), 401)
|
||||
jobRecord, item, e := db.NextAdminBatchItem(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
server.executeBatchItem(ctx, jobRecord, item)
|
||||
jobRecord, e = db.AdminBatch(ctx, batchID, false)
|
||||
if e != nil || jobRecord.Items[0].State != "failed" {
|
||||
t.Fatal("revoked key still executed queued work", e)
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(scope.WithProject(ctx, p.ID, p.NodeID))
|
||||
cancel()
|
||||
db.Log(cancelled, &p.TenantID, a.ID, "update", "file", "cancel-audit", "", true, "completed-before-disconnect")
|
||||
logs, e := db.AdminActivities(ctx, 100)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
found := false
|
||||
for _, log := range logs {
|
||||
if log.Detail == "completed-before-disconnect" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("request cancellation discarded a completed operation audit")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user