feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

@@ -0,0 +1,214 @@
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/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
"strconv"
"strings"
"testing"
"time"
)
func TestAdministratorImpersonationMySQL(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)
}
if err = db.BootstrapAdmin(ctx, "imp-admin@example.invalid", "测试管理员", "test-admin-password-123"); err != nil {
t.Fatal(err)
}
administrator, err := db.UserByLogin(ctx, "imp-admin@example.invalid")
if err != nil {
t.Fatal(err)
}
plans, _ := db.ListPlans(ctx)
tenant, err := db.CreateTenant(ctx, store.NewTenant{Slug: "imp-test", Name: "代入测试用户", Email: "imp-user@example.invalid", DisplayName: "测试用户", Password: "test-user-password-123", PlanID: plans[0].ID})
if err != nil {
t.Fatal(err)
}
customer, err := db.UserByLogin(ctx, "imp-user@example.invalid")
if err != nil {
t.Fatal(err)
}
hosts := []uint64{}
for _, name := range []string{"sv7777777777", "sv8888888888"} {
id, e := db.InsertProject(ctx, store.NewProject{NodeID: 1, PlanID: plans[0].ID, TenantID: tenant, HostName: name, Slug: name, Runtime: "PHP", Version: "8.4", Path: "/www/wwwroot/seavHost/vHost/" + name, RunPath: "/public", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-only-hash"})
if e != nil {
t.Fatal(e)
}
if e = db.CompleteProject(scope.WithProject(ctx, id, 1), id, int64(1000+id), int64(2000+id), int64(3000+id), name, name, name, []byte("test"), []byte("test"), "running", "", "", false); e != nil {
t.Fatal(e)
}
hosts = append(hosts, id)
}
secret := "integration-session-secret-at-least-32-characters"
makeSession := func(id uint64) string {
token, e := auth.NewSessionToken(secret)
if e != nil {
t.Fatal(e)
}
if e = db.CreateSession(ctx, id, token, time.Now().Add(time.Hour)); e != nil {
t.Fatal(e)
}
return token
}
parent, otherParent, userToken := makeSession(administrator.ID), makeSession(administrator.ID), makeSession(customer.ID)
projects := service.NewProjects(db, &panel.Mock{}, isolation.Mock{}, "hosts.example.invalid", "/www/wwwroot/seavHost/vHost", true, secret, "control.example.invalid")
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects).Handler()
call := func(path, method string, body any, parent, child string) *httptest.ResponseRecorder {
var buffer bytes.Buffer
if body != nil {
_ = json.NewEncoder(&buffer).Encode(body)
}
request := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer)
request.Header.Set("Origin", "https://control.example.invalid")
request.Header.Set("Content-Type", "application/json")
if parent != "" {
request.AddCookie(&http.Cookie{Name: "sea_session", Value: parent})
}
if child != "" {
request.AddCookie(&http.Cookie{Name: impersonationCookie, Value: child})
}
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
return response
}
expect := func(response *httptest.ResponseRecorder, status int) {
t.Helper()
if response.Code != status {
t.Fatalf("HTTP %d, want %d: %s", response.Code, status, response.Body.String())
}
}
childFrom := func(response *httptest.ResponseRecorder) string {
t.Helper()
for _, cookie := range response.Result().Cookies() {
if cookie.Name == impersonationCookie {
if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode {
t.Fatal("unsafe delegated cookie")
}
return cookie.Value
}
}
t.Fatal("missing delegated cookie")
return ""
}
expect(call("/api/v1/admin/impersonation", "POST", map[string]any{"tenantId": tenant}, "", ""), 401)
for _, path := range []string{"/api/v1/admin/tenants", "/api/v1/admin/plans", "/api/v1/admin/domains/pending", "/api/v1/admin/overview", "/api/v1/admin/settings/domain-approval"} {
expect(call(path, "GET", nil, parent, ""), 200)
}
expect(call("/api/v1/admin/impersonation", "POST", map[string]any{"tenantId": tenant}, userToken, ""), 403)
start := call("/api/v1/admin/impersonation", "POST", map[string]any{"tenantId": tenant}, parent, "")
expect(start, 200)
child := childFrom(start)
expect(call("/api/v1/admin/nodes", "GET", nil, parent, child), 403)
expect(call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, child), 403)
expect(call("/api/v1/account/password", "PUT", map[string]any{}, parent, child), 403)
expect(call("/api/v1/auth/oidc/start?mode=bind", "GET", nil, parent, child), 403)
expect(call("/api/v1/me", "GET", nil, child, ""), 401)
expect(call("/api/v1/me", "GET", nil, otherParent, child), 401)
expect(call("/api/v1/me", "GET", nil, userToken, child), 403)
expect(call("/api/v1/auth/impersonation/stop", "POST", map[string]any{}, parent, child), 200)
expect(call("/api/v1/me", "GET", nil, parent, child), 401)
start = call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, "")
expect(start, 200)
child = childFrom(start)
expect(call("/api/v1/projects/"+strconv.FormatUint(hosts[1], 10)+"/files", "GET", nil, parent, child), 404)
response := call("/api/v1/projects/"+strconv.FormatUint(hosts[0], 10)+"/files", "PUT", map[string]any{"path": "../invalid", "content": "must-not-write"}, parent, child)
expect(response, 400)
hostContext := scope.WithProject(ctx, hosts[0], 1)
items, e := db.Activities(hostContext, tenant, 100)
if e != nil {
t.Fatal(e)
}
for _, item := range items {
if item.ResourceType == "file" {
t.Fatal("delegated administrator file action leaked to host")
}
}
items, e = db.Activities(ctx, tenant, 100)
if e != nil {
t.Fatal(e)
}
for _, item := range items {
if item.ResourceType == "impersonation" || item.ResourceType == "file" {
t.Fatal("administrator action leaked to user")
}
}
audit, e := db.AdminActivities(ctx, 100)
if e != nil {
t.Fatal(e)
}
found := false
for _, item := range audit {
if item.ResourceType == "file" && item.AdministratorID != nil && *item.AdministratorID == administrator.ID && item.ImpersonatedUserID != nil {
found = true
}
}
if !found {
t.Fatal("real administrator and target missing from audit")
}
activeHost, err := db.UserByLogin(ctx, "sv7777777777")
if err != nil {
t.Fatal(err)
}
if err = db.ChangePassword(ctx, activeHost.ID, "test-changed-hash", "not-a-session"); err != nil {
t.Fatal(err)
}
expect(call("/api/v1/me", "GET", nil, parent, child), 401)
start = call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, "")
expect(start, 200)
child = childFrom(start)
expired, _ := auth.NewSessionToken(secret)
if err = db.CreateImpersonation(ctx, parent, expired, administrator.ID, activeHost.ID, time.Now().Add(-time.Minute)); err != nil {
t.Fatal(err)
}
expect(call("/api/v1/me", "GET", nil, parent, expired), 401)
if err = db.CreateImpersonation(ctx, parent, expired, administrator.ID, administrator.ID, time.Now().Add(time.Minute)); err == nil {
t.Fatal("administrator cannot be a delegated target")
}
start = call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, "")
expect(start, 200)
child = childFrom(start)
if e = db.DeleteSession(ctx, parent); e != nil {
t.Fatal(e)
}
expect(call("/api/v1/me", "GET", nil, parent, child), 401)
// Expiration is an expected host restriction, not a failed quota probe.
expires := time.Now().Add(-time.Minute)
if err = db.SetHostSubscription(ctx, hosts[0], plans[0].ID, &expires); err != nil {
t.Fatal(err)
}
response = call("/api/v1/projects/"+strconv.FormatUint(hosts[0], 10)+"/files", "PUT", map[string]any{"path": "expired.txt", "content": "must-not-write"}, userToken, "")
expect(response, http.StatusLocked)
if !strings.Contains(response.Body.String(), "host_not_writable") {
t.Fatal("expired write did not explain the host restriction")
}
if err = db.HostWritable(scope.WithProject(ctx, hosts[1], 1), tenant); err != nil {
t.Fatalf("expiration affected sibling host: %v", err)
}
}