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

+18
View File
@@ -0,0 +1,18 @@
SEA_ADDR=127.0.0.1:8080
SEA_CONFIG_FILE=/var/lib/sea-vhost/config.json
# deploy/install.sh 会生成至少 32 字节的随机值。首次安装写接口必须携带该令牌。
SEA_SETUP_TOKEN=replace-with-at-least-24-random-characters
SEA_COOKIE_SECURE=true
# 下列路径由管理员固定,不允许通过 Web 安装页改写。
SEA_TENANT_ROOT=/www/wwwroot/seavHost/vHost
SEA_UPLOAD_LIMIT=20971520
SEA_AGENT_SOCKET=/run/sea-vhost/agent.sock
SEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock
SEA_PANEL_BROKER_STATE=/var/lib/sea-vhost-panel
SEA_QUOTA_MOUNT=/www
SEA_AGENT_GROUP=sea-vhost-files
# 兼容旧版纯环境变量部署:仅当 SEA_CONFIG_FILE 不存在且设置了
# SEA_SESSION_SECRET 时生效。新安装请使用 Web 安装向导。
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"sea-vhost/internal/isolation"
)
func main() {
socket := env("SEA_AGENT_SOCKET", "/run/sea-vhost/agent.sock")
root := env("SEA_TENANT_ROOT", "/www/wwwroot/seavHost/vHost")
backupRoot := env("SEA_BACKUP_ROOT", "/www/backup/sea-vhost")
legacyRoot := env("SEA_LEGACY_SITE_ROOT", "/www/wwwroot")
fileOwner := env("SEA_FILE_OWNER", "sea-vhost")
nodePIDRoot := env("SEA_NODE_PID_ROOT", "/www/server/nodejs/vhost/pids")
nginxVhostRoot := env("SEA_NGINX_VHOST_ROOT", "/www/server/panel/vhost/nginx")
nginxBinary := env("SEA_NGINX_BINARY", "/www/server/nginx/sbin/nginx")
purePWBinary := env("SEA_PURE_PW_BINARY", "/www/server/pure-ftpd/bin/pure-pw")
phpStateRoot := env("SEA_PHP_IDENTITY_STATE", "/var/lib/sea-vhost-agent/php")
phpRunRoot := env("SEA_PHP_IDENTITY_RUN", "/run/sea-vhost-php")
usageStatePath := env("SEA_USAGE_STATE", "/var/lib/sea-vhost-agent/traffic.json")
nginxLogRoot := env("SEA_NGINX_LOG_ROOT", "/www/wwwlogs")
certificateRoot := env("SEA_CERT_ROOT", "/www/server/panel/vhost/cert")
pureFTPConfig := env("SEA_PURE_FTP_CONFIG", "/www/server/pure-ftpd/etc/pure-ftpd.conf")
pureFTPPem := env("SEA_PURE_FTP_PEM", "/www/server/pure-ftpd/etc/pure-ftpd.pem")
if err := os.MkdirAll(filepath.Dir(socket), 0750); err != nil {
slog.Error("cannot create socket directory", "error", err)
os.Exit(1)
}
_ = os.Remove(socket)
listener, err := net.Listen("unix", socket)
if err != nil {
slog.Error("cannot listen", "error", err)
os.Exit(1)
}
defer listener.Close()
if err = os.Chmod(socket, 0660); err != nil {
slog.Error("cannot secure socket", "error", err)
os.Exit(1)
}
agent := isolation.Agent{Root: root, BackupRoot: backupRoot, LegacyRoot: legacyRoot, FileOwner: fileOwner, NodePIDRoot: nodePIDRoot, NginxVhostRoot: nginxVhostRoot, NginxBinary: nginxBinary, PurePWBinary: purePWBinary, PHPStateRoot: phpStateRoot, PHPRunRoot: phpRunRoot, UsageStatePath: usageStatePath, NginxLogRoot: nginxLogRoot, CertificateRoot: certificateRoot, PureFTPConfig: pureFTPConfig, PureFTPPem: pureFTPPem, InternalToken: os.Getenv("SEA_INTERNAL_AUTH_TOKEN")}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if os.Getenv("SEA_NODE_STATELESS") != "true" {
go agent.RunRuntimeBackupExpiry(ctx)
}
server := &http.Server{Handler: agent.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 2 * time.Hour, IdleTimeout: 30 * time.Second}
go func() {
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("agent failed", "error", err)
os.Exit(1)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
_ = server.Close()
}
func env(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/executor"
)
type configuration struct {
Identity controlwire.ServerIdentity `json:"identity"`
Address string `json:"address"`
TenantRoot string `json:"tenantRoot"`
BrokerSocket string `json:"brokerSocket"`
AgentSocket string `json:"agentSocket"`
}
func main() {
path := os.Getenv("SEA_NODE_CONFIG")
if path == "" {
path = "/etc/sea-vhost-node/config.json"
}
data, err := os.ReadFile(path)
if err != nil {
slog.Error("cannot read node configuration")
os.Exit(1)
}
var cfg configuration
if json.Unmarshal(data, &cfg) != nil || cfg.Identity.NodeID == 0 || cfg.Address == "" || cfg.TenantRoot == "" {
slog.Error("invalid node configuration")
os.Exit(1)
}
if !filepath.IsAbs(cfg.TenantRoot) || filepath.Clean(cfg.TenantRoot) != cfg.TenantRoot {
slog.Error("invalid node root")
os.Exit(1)
}
tlsConfig, err := controlwire.ServerTLS(cfg.Identity)
if err != nil {
slog.Error("invalid node TLS identity")
os.Exit(1)
}
token := os.Getenv("SEA_INTERNAL_AUTH_TOKEN")
if len(token) < 32 {
slog.Error("node local execution token is missing")
os.Exit(1)
}
gateway := &executor.Gateway{NodeID: cfg.Identity.NodeID, TenantRoot: cfg.TenantRoot, BrokerSocket: cfg.BrokerSocket, AgentSocket: cfg.AgentSocket, InternalToken: token}
server := &http.Server{Addr: cfg.Address, Handler: gateway.Handler(), TLSConfig: tlsConfig, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 2 * time.Hour, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
failed := make(chan error, 1)
go func() { failed <- server.ListenAndServeTLS("", "") }()
stop, done := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer done()
select {
case <-stop.Done():
case err := <-failed:
if !errors.Is(err, http.ErrServerClosed) {
slog.Error("node service stopped", "error", err)
os.Exit(1)
}
}
shutdown, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = server.Shutdown(shutdown)
}
+69
View File
@@ -0,0 +1,69 @@
package main
import (
"errors"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"sea-vhost/internal/panel"
)
func main() {
socket := env("SEA_PANEL_BROKER_SOCKET", "/run/sea-vhost-panel/broker.sock")
stateDir := env("SEA_PANEL_BROKER_STATE", "/var/lib/sea-vhost-panel")
tenantRoot := env("SEA_TENANT_ROOT", "/www/wwwroot/seavHost/vHost")
serverHandler, err := panel.NewBrokerServer(stateDir, tenantRoot, os.Getenv("SEA_SETUP_TOKEN"), os.Getenv("SEA_INTERNAL_AUTH_TOKEN"))
if err != nil {
slog.Error("cannot initialize panel broker", "error", err)
os.Exit(1)
}
if os.Getenv("SEA_NODE_STATELESS") == "true" {
if err = serverHandler.EnableStateless(); err != nil {
slog.Error("cannot start stateless node broker", "error", err)
os.Exit(1)
}
}
if err := os.MkdirAll(filepath.Dir(socket), 0750); err != nil {
slog.Error("cannot create broker socket directory", "error", err)
os.Exit(1)
}
_ = os.Remove(socket)
listener, err := net.Listen("unix", socket)
if err != nil {
slog.Error("cannot listen on panel broker socket", "error", err)
os.Exit(1)
}
defer listener.Close()
if err = os.Chmod(socket, 0660); err != nil {
slog.Error("cannot secure panel broker socket", "error", err)
os.Exit(1)
}
server := &http.Server{
Handler: serverHandler.Handler(), ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 30 * time.Second, WriteTimeout: 5 * time.Minute, IdleTimeout: 30 * time.Second,
}
go func() {
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("panel broker failed", "error", err)
os.Exit(1)
}
}()
slog.Info("Sea vHost panel broker listening", "socket", socket)
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
_ = server.Close()
}
func env(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
+116
View File
@@ -0,0 +1,116 @@
//go:build linux
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"sea-vhost/internal/hosting"
"sync"
"syscall"
)
func main() {
if e := run(); e != nil {
fmt.Fprintln(os.Stderr, "Sea vHost: application launch failed")
os.Exit(1)
}
}
func run() error {
if (len(os.Args) != 2 && len(os.Args) != 5) || !regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`).MatchString(os.Args[1]) {
return fmt.Errorf("invalid site")
}
f, e := os.Open("/var/lib/sea-vhost-agent/startup/" + os.Args[1] + ".json")
if e != nil {
return e
}
defer f.Close()
i, e := f.Stat()
if e != nil {
return e
}
stat, ok := i.Sys().(*syscall.Stat_t)
if !ok || stat.Uid != 0 || i.Mode().Perm()&0022 != 0 {
return fmt.Errorf("unsafe launcher state")
}
var v hosting.RunnerConfig
if e = json.NewDecoder(io.LimitReader(f, 128<<10)).Decode(&v); e != nil {
return e
}
if v.UID == 0 || uint32(os.Getuid()) != v.UID || v.SiteName != os.Args[1] {
return fmt.Errorf("wrong identity")
}
if !validInvocation(os.Args, v) {
return fmt.Errorf("launcher arguments do not match protected state")
}
cmd := exec.Command(v.Binary, v.Arguments...)
cmd.Dir = v.WorkDir
cmd.Env = []string{"PATH=" + filepath.Dir(v.Binary) + ":/usr/bin:/bin", "HOME=/nonexistent", "LANG=C.UTF-8"}
for k, value := range v.Environment {
cmd.Env = append(cmd.Env, k+"="+value)
}
root, e := os.OpenRoot(v.LogDir)
if e != nil {
return e
}
defer root.Close()
logger := &rollingLog{root: root, name: v.SiteName + ".log"}
cmd.Stdout = logger
cmd.Stderr = logger
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL}
if e = cmd.Start(); e != nil {
return e
}
signals := make(chan os.Signal, 2)
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
defer signal.Stop(signals)
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case e = <-done:
return e
case <-signals:
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
return <-done
}
}
func validInvocation(args []string, v hosting.RunnerConfig) bool {
if len(args) == 2 {
return true
}
return len(args) == 5 && args[2] == "--java" && args[3] == v.Binary && filepath.Base(v.Binary) == "java" && len(v.Arguments) >= 2 && v.Arguments[0] == "-jar" && args[4] == v.Arguments[1]
}
type rollingLog struct {
root *os.Root
name string
mu sync.Mutex
}
func (l *rollingLog) Write(v []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
if i, e := l.root.Lstat(l.name); e == nil {
if !i.Mode().IsRegular() {
return len(v), nil
}
if i.Size() > 8<<20 {
_ = l.root.Remove(l.name + ".1")
_ = l.root.Rename(l.name, l.name+".1")
}
}
f, e := l.root.OpenFile(l.name, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0660)
if e != nil {
return len(v), nil
}
defer f.Close()
_, _ = f.Write(v)
return len(v), nil
}
+21
View File
@@ -0,0 +1,21 @@
//go:build linux
package main
import (
"sea-vhost/internal/hosting"
"testing"
)
func TestJavaInvocationOnlyUsesProtectedState(t *testing.T) {
v := hosting.RunnerConfig{Binary: "/www/server/java/jdk-25/bin/java", Arguments: []string{"-jar", "/www/wwwroot/host/app.jar"}}
good := []string{"runner", "sv0123456789", "--java", v.Binary, v.Arguments[1]}
if !validInvocation(good, v) {
t.Fatal("expected matching Java invocation")
}
for _, args := range [][]string{{"runner", "sv0123456789", "--java", "/bin/sh", v.Arguments[1]}, {"runner", "sv0123456789", "--java", v.Binary, "/tmp/foreign.jar"}, {"runner", "sv0123456789", "--command", v.Binary, v.Arguments[1]}} {
if validInvocation(args, v) {
t.Fatal("accepted foreign launcher command")
}
}
}
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"sea-vhost/internal/schedulerbridge"
"strconv"
"strings"
"time"
)
func main() {
if e := tick(); e != nil {
fmt.Fprintln(os.Stderr, "Sea vHost 调度触发失败")
os.Exit(1)
}
}
func tick() error {
if len(os.Args) != 2 || os.Args[1] != "tick" {
return fmt.Errorf("usage: sea-vhost-scheduler tick")
}
raw, e := os.ReadFile(schedulerbridge.ConfigPath)
if e != nil {
return e
}
var cfg schedulerbridge.Config
if json.Unmarshal(raw, &cfg) != nil || cfg.Validate() != nil {
return fmt.Errorf("invalid configuration")
}
nonce := make([]byte, 16)
if _, e = rand.Read(nonce); e != nil {
return e
}
node := strconv.FormatUint(cfg.NodeID, 10)
stamp := strconv.FormatInt(time.Now().Unix(), 10)
n := hex.EncodeToString(nonce)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
r, e := http.NewRequestWithContext(ctx, "POST", strings.TrimRight(cfg.Controller, "/")+schedulerbridge.TickPath, nil)
if e != nil {
return e
}
r.Header.Set("X-Sea-Node", node)
r.Header.Set("X-Sea-Time", stamp)
r.Header.Set("X-Sea-Nonce", n)
r.Header.Set("X-Sea-Signature", schedulerbridge.Signature(cfg.Key, node, stamp, n))
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, e := client.Do(r)
if e != nil {
return e
}
res.Body.Close()
if res.StatusCode != 202 && res.StatusCode != 204 {
return fmt.Errorf("trigger rejected")
}
return nil
}
+194
View File
@@ -0,0 +1,194 @@
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"sea-vhost/internal/cluster"
"sea-vhost/internal/config"
"sea-vhost/internal/httpapi"
"sea-vhost/internal/isolation"
"sea-vhost/internal/notify"
"sea-vhost/internal/panel"
"sea-vhost/internal/secrets"
"sea-vhost/internal/service"
setupserver "sea-vhost/internal/setup"
"sea-vhost/internal/store"
)
func main() {
for {
cfg, err := config.Load()
if errors.Is(err, config.ErrSetupRequired) {
installed, setupErr := runSetupServer()
if setupErr != nil {
slog.Error("setup server failed", "error", setupErr)
os.Exit(1)
}
if installed {
continue
}
return
}
if err != nil {
slog.Error("configuration error", "error", err)
os.Exit(1)
}
if err := runApplication(cfg); err != nil {
slog.Error("application failed", "error", err)
os.Exit(1)
}
return
}
}
func runSetupServer() (bool, error) {
setup, err := setupserver.New(os.Getenv("SEA_SETUP_TOKEN"))
if err != nil {
return false, err
}
server := newHTTPServer(config.SetupAddr(), setup.Handler())
serverErrors := make(chan error, 1)
go func() {
slog.Warn("Sea vHost requires installation", "address", config.SetupAddr(), "config", config.Path())
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
serverErrors <- err
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(stop)
installed := false
select {
case <-setup.Done():
installed = true
case <-stop:
case err := <-serverErrors:
return false, err
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
return false, err
}
return installed, nil
}
func runApplication(cfg config.Config) error {
database, err := store.Open(cfg.DatabaseDSN)
if err != nil {
return err
}
defer database.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
if err = database.Migrate(ctx); err == nil {
err = database.BootstrapAdmin(ctx, os.Getenv("SEA_BOOTSTRAP_ADMIN_EMAIL"), os.Getenv("SEA_BOOTSTRAP_ADMIN_NAME"), os.Getenv("SEA_BOOTSTRAP_ADMIN_PASSWORD"))
}
cancel()
if err != nil {
return err
}
var panelClient panel.Interface
if err = database.RecoverControlTasks(context.Background()); err != nil {
return err
}
manager := &cluster.Manager{Store: database, Box: secrets.New(cfg.SessionSecret), PanelSocket: cfg.PanelBrokerSocket, AgentSocket: cfg.AgentSocket, LocalToken: cfg.InternalAuthToken}
if err = database.InitializeLocalNode(context.Background(), cfg.RootDomain, cfg.TenantRoot, cfg.FTPDomain); err != nil {
return err
}
if cfg.ControllerOnly {
if err = database.SetNodeEnabled(context.Background(), 1, false); err != nil {
return err
}
}
if cfg.PanelMock {
panelClient = panel.NewMock()
slog.Warn("panel mock mode is active; do not use in production")
} else {
panelClient = manager.Panel()
}
var isolator isolation.Interface
if cfg.AgentMock {
isolator = isolation.Mock{Root: cfg.TenantRoot}
slog.Warn("isolation agent mock mode is active; do not use in production")
} else {
isolator = manager.Isolation()
}
reservedDomains := append([]string{cfg.ManagementDomain, cfg.FTPDomain}, cfg.ReservedDomains...)
projectService := service.NewProjects(database, panelClient, isolator, cfg.RootDomain, cfg.TenantRoot, cfg.DomainApproval, cfg.SessionSecret, cfg.FTPDomain, reservedDomains...)
if !cfg.AgentMock {
projectService.WithFileOpener(manager.OpenFiles)
}
reconcileContext, stopReconcile := context.WithTimeout(context.Background(), 5*time.Minute)
err = projectService.ReconcileIdentities(reconcileContext)
stopReconcile()
if err != nil {
slog.Error("host identity reconciliation needs attention", "error", err)
_ = database.EnqueueAdminNotification(context.Background(), "critical", "node", "主机身份核验未完成", err.Error())
}
quotaContext, stopQuotaMonitor := context.WithCancel(context.Background())
defer stopQuotaMonitor()
go projectService.RunStorageQuotaMonitor(quotaContext, time.Minute)
go projectService.RunCertificateRenewalMonitor(quotaContext, 12*time.Hour)
go runSessionCleanup(quotaContext, database)
go projectService.RunLifecycleMonitor(quotaContext, time.Minute)
go projectService.RunRuntimeMaintenance(quotaContext)
go projectService.RunRuntimeUpdateChecks(quotaContext)
go notify.New(database, cfg.SessionSecret).Run(quotaContext, time.Minute)
apiServer := httpapi.New(cfg, database, projectService).WithCluster(manager)
go apiServer.RunAdminBatches(quotaContext)
server := newHTTPServer(cfg.Addr, apiServer.Handler())
serverErrors := make(chan error, 1)
go func() {
slog.Info("Sea vHost API listening", "address", cfg.Addr)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
serverErrors <- err
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(stop)
select {
case <-stop:
case err := <-serverErrors:
return err
}
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer shutdownCancel()
return server.Shutdown(shutdownCtx)
}
func runSessionCleanup(ctx context.Context, database *store.Store) {
cleanup := func() {
cleanupCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
if err := database.DeleteExpiredSessions(cleanupCtx); err != nil && !errors.Is(err, context.Canceled) {
slog.Error("expired session cleanup failed", "error", err)
}
}
cleanup()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
cleanup()
}
}
}
func newHTTPServer(address string, handler http.Handler) *http.Server {
return &http.Server{
Addr: address, Handler: handler, ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second, WriteTimeout: 5 * time.Minute,
IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 1 << 20,
}
}
+15
View File
@@ -0,0 +1,15 @@
module sea-vhost
go 1.27.3
require (
github.com/go-sql-driver/mysql v1.10.1
golang.org/x/crypto v0.58.0
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/coreos/go-oidc/v3 v3.21.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
golang.org/x/oauth2 v0.37.0 // indirect
)
+12
View File
@@ -0,0 +1,12 @@
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
+56
View File
@@ -0,0 +1,56 @@
package auth
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"golang.org/x/crypto/bcrypt"
)
func VerifyPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
var dummyPasswordHash = func() string {
hash, _ := bcrypt.GenerateFromPassword([]byte("sea-vhost-dummy-credential"), bcrypt.DefaultCost)
return string(hash)
}()
func VerifyPasswordConstantWork(hash, password string) bool {
if hash == "" {
_ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password))
return false
}
return VerifyPassword(hash, password)
}
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(hash), err
}
func NewSessionToken(secret string) (string, error) {
random := make([]byte, 32)
if _, err := rand.Read(random); err != nil {
return "", err
}
mac := hmac.New(sha256.New, []byte(secret))
_, _ = mac.Write(random)
payload := append(random, mac.Sum(nil)...)
return base64.RawURLEncoding.EncodeToString(payload), nil
}
func ValidateSessionToken(secret, token string) bool {
payload, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(payload) != 64 {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
_, _ = mac.Write(payload[:32])
return hmac.Equal(payload[32:], mac.Sum(nil))
}
var ErrInvalidCredentials = errors.New("invalid credentials")
+86
View File
@@ -0,0 +1,86 @@
package auth
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base32"
"encoding/binary"
"fmt"
"net/url"
"strconv"
"strings"
"time"
)
const (
totpPeriod = int64(30)
totpDigits = 6
)
func NewTOTPSecret() (string, error) {
random := make([]byte, 20)
if _, err := rand.Read(random); err != nil {
return "", err
}
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(random), nil
}
func TOTPURI(secret, account string) string {
label := url.PathEscape("Sea vHost:" + account)
query := url.Values{"secret": {secret}, "issuer": {"Sea vHost"}, "algorithm": {"SHA1"}, "digits": {strconv.Itoa(totpDigits)}, "period": {strconv.FormatInt(totpPeriod, 10)}}
return "otpauth://totp/" + label + "?" + query.Encode()
}
func VerifyTOTP(secret, code string, now time.Time) bool {
code = strings.TrimSpace(code)
if len(code) != totpDigits {
return false
}
for _, character := range code {
if character < '0' || character > '9' {
return false
}
}
for offset := int64(-1); offset <= 1; offset++ {
if hmac.Equal([]byte(code), []byte(totpAt(secret, now.Unix()/totpPeriod+offset))) {
return true
}
}
return false
}
func totpAt(secret string, counter int64) string {
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(secret))
if err != nil {
return ""
}
message := make([]byte, 8)
binary.BigEndian.PutUint64(message, uint64(counter))
mac := hmac.New(sha1.New, key)
_, _ = mac.Write(message)
digest := mac.Sum(nil)
offset := digest[len(digest)-1] & 0x0f
value := binary.BigEndian.Uint32(digest[offset:offset+4]) & 0x7fffffff
return fmt.Sprintf("%0*d", totpDigits, value%1000000)
}
func NewRecoveryCodes(count int) ([]string, error) {
codes := make([]string, 0, count)
for len(codes) < count {
random := make([]byte, 8)
if _, err := rand.Read(random); err != nil {
return nil, err
}
encoded := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(random))
codes = append(codes, encoded[:4]+"-"+encoded[4:8]+"-"+encoded[8:12])
}
return codes, nil
}
func RecoveryCodeHash(code string) []byte {
normalized := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))
hash := sha256.Sum256([]byte("sea-vhost/mfa-recovery/v1\x00" + normalized))
return hash[:]
}
+25
View File
@@ -0,0 +1,25 @@
package auth
import (
"bytes"
"testing"
"time"
)
func TestTOTPVerificationWindow(t *testing.T) {
secret := "JBSWY3DPEHPK3PXP"
now := time.Unix(1_700_000_000, 0)
code := totpAt(secret, now.Unix()/totpPeriod)
if !VerifyTOTP(secret, code, now) {
t.Fatal("current TOTP code was rejected")
}
if VerifyTOTP(secret, "0000000", now) || VerifyTOTP(secret, "abcdef", now) {
t.Fatal("malformed TOTP code was accepted")
}
}
func TestRecoveryCodeHashNormalizesFormatting(t *testing.T) {
if !bytes.Equal(RecoveryCodeHash("abcd-efgh-ijkl"), RecoveryCodeHash(" ABCDEFGHIJKL ")) {
t.Fatal("equivalent recovery codes produced different hashes")
}
}
+59
View File
@@ -0,0 +1,59 @@
package cluster
import (
"context"
"encoding/json"
"errors"
"io"
"path"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/nodefiles"
)
func (m *Manager) OpenFiles(ctx context.Context, root string) (*nodefiles.Root, error) {
host := path.Base(root)
node, err := m.Resolve(ctx, []byte(`{"hostName":"`+host+`"}`))
if err != nil {
return nil, err
}
if !hostPrefix.MatchString(host) || len(host) != 12 || path.Clean(root) != path.Join(node.TenantRoot, host) {
return nil, errors.New("文件目录与节点不符")
}
return nodefiles.New(ctx, host, func(ctx context.Context, q nodefiles.Request) (nodefiles.Response, error) {
if node.Transport == "local" {
return nodefiles.Execute(root, q), nil
}
raw, err := json.Marshal(q)
if err != nil {
return nodefiles.Response{}, err
}
id, err := requestID()
if err != nil {
return nodefiles.Response{}, err
}
req, err := controlwire.NewRequest("POST", node.Endpoint, "/v1/files", node.ID, id, raw)
if err != nil {
return nodefiles.Response{}, err
}
client, err := m.client(node)
if err != nil {
return nodefiles.Response{}, err
}
defer client.CloseIdleConnections()
response, err := client.Do(req.WithContext(ctx))
if err != nil {
return nodefiles.Response{}, ErrUncertain
}
defer response.Body.Close()
if response.StatusCode != 200 {
return nodefiles.Response{}, errors.New("节点文件操作未完成,请核对后再操作")
}
var result nodefiles.Response
decoder := json.NewDecoder(io.LimitReader(response.Body, nodefiles.MaxMessageBytes+1))
decoder.DisallowUnknownFields()
if decoder.Decode(&result) != nil || decoder.Decode(&struct{}{}) != io.EOF {
return result, ErrUncertain
}
return result, nil
}), nil
}
+358
View File
@@ -0,0 +1,358 @@
// Package cluster is controller-only: node selection, credentials, resource
// snapshots and operation history stay in the controller MySQL database.
package cluster
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strings"
"time"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/isolation"
"sea-vhost/internal/panel"
"sea-vhost/internal/scope"
"sea-vhost/internal/secrets"
"sea-vhost/internal/store"
)
var ErrUncertain = errors.New("节点操作结果待核验,未自动重试")
type Manager struct {
Store *store.Store
Box *secrets.Box
PanelSocket, AgentSocket, LocalToken string
}
type transport struct {
manager *Manager
kind string
}
func (m *Manager) Panel() *panel.BrokerClient {
return panel.NewTransportClient(&transport{manager: m, kind: "panel"}, 2*time.Hour)
}
func (m *Manager) Isolation() *isolation.Client {
return isolation.NewTransportClient(&transport{manager: m, kind: "isolation"})
}
func (m *Manager) CredentialLabel(id uint64) string { return fmt.Sprintf("node/%d/transport/v1", id) }
func (m *Manager) Pair(ctx context.Context, id uint64) (controlwire.ServerIdentity, error) {
node, err := m.Store.Node(ctx, id)
if err != nil {
return controlwire.ServerIdentity{}, err
}
credentials, identity, err := controlwire.Pair(id, node.Endpoint)
if err != nil {
return identity, err
}
raw, err := json.Marshal(credentials)
if err != nil {
return identity, err
}
cipher, err := m.Box.Seal(m.CredentialLabel(id), string(raw))
if err != nil {
return identity, err
}
return identity, m.Store.SetNodeCredentials(ctx, id, cipher)
}
func (m *Manager) client(node store.Node) (*http.Client, error) {
raw, err := m.Box.Open(m.CredentialLabel(node.ID), node.Credentials)
if err != nil {
return nil, errors.New("node transport credentials are unavailable")
}
var credentials controlwire.Credentials
if json.Unmarshal([]byte(raw), &credentials) != nil {
return nil, errors.New("node transport credentials are invalid")
}
tls, err := controlwire.ClientTLS(credentials)
if err != nil {
return nil, err
}
return &http.Client{Transport: &http.Transport{TLSClientConfig: tls, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 10 * time.Second, MaxIdleConnsPerHost: 4, ResponseHeaderTimeout: 2 * time.Hour}, Timeout: 2 * time.Hour, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("node redirect denied") }}, nil
}
func requestID() (string, error) {
raw := make([]byte, 16)
_, err := rand.Read(raw)
return hex.EncodeToString(raw), err
}
func (m *Manager) Probe(ctx context.Context, id uint64) error {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
node, err := m.Store.Node(ctx, id)
if err != nil {
return err
}
if node.Transport == "local" {
return errors.New("local node is verified through its local services")
}
client, err := m.client(node)
if err != nil {
return err
}
defer client.CloseIdleConnections()
requestID, err := requestID()
if err != nil {
return err
}
req, err := controlwire.NewRequest("GET", node.Endpoint, "/v1/status", id, requestID, nil)
if err != nil {
return err
}
response, err := client.Do(req.WithContext(ctx))
if err != nil {
_ = m.Store.RecordNodeProbe(context.WithoutCancel(ctx), id, "节点连接或双向 TLS 校验失败")
return errors.New("节点连接或双向 TLS 校验失败")
}
defer response.Body.Close()
var status struct {
NodeID uint64 `json:"nodeId"`
Protocol string `json:"protocol"`
}
if response.StatusCode != 200 || json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&status) != nil || status.NodeID != id || status.Protocol != controlwire.Version {
return errors.New("node identity or protocol mismatch")
}
return m.Store.RecordNodeProbe(ctx, id, "")
}
var hostPrefix = regexp.MustCompile(`^sv[a-f0-9]{10}(?:$|[._-])`)
func hostFromValue(value any) string {
switch v := value.(type) {
case map[string]any:
for _, key := range []string{"hostName", "HostName", "ProjectName", "projectName", "Name", "name", "Username", "username"} {
if text, ok := v[key].(string); ok && hostPrefix.MatchString(text) && (len(text) == 12 || (strings.EqualFold(key, "projectName") && strings.HasPrefix(text[12:], "_"))) {
return text[:12]
}
}
for _, key := range []string{"project", "Project", "site", "Site", "runtime", "Runtime", "spec"} {
if child, ok := v[key]; ok {
if host := hostFromValue(child); host != "" {
return host
}
}
}
}
return ""
}
func (m *Manager) Resolve(ctx context.Context, body []byte) (store.Node, error) {
id, explicit := scope.ExplicitNode(ctx)
if id == 0 {
id = 1
}
var value any
if len(body) > 0 && json.Unmarshal(body, &value) != nil {
return store.Node{}, errors.New("invalid execution request")
}
if host := hostFromValue(value); host != "" {
resolved, err := m.Store.NodeForHost(ctx, host)
if err != nil {
return store.Node{}, err
}
if explicit && id != resolved {
return store.Node{}, errors.New("resource belongs to another node")
}
id = resolved
}
node, err := m.Store.Node(ctx, id)
if err != nil {
return node, err
}
if !node.Enabled {
return node, errors.New("节点已停用")
}
return node, nil
}
func executionOperation(kind, route string, body []byte) (string, bool) {
if kind == "panel" {
var q struct {
Operation string `json:"operation"`
}
_ = json.Unmarshal(body, &q)
read := map[string]bool{"ping": true, "runtime_catalog": true, "runtime_capabilities": true, "runtime_environments": true, "list_unmanaged_sites": true, "managed_runtime": true, "php_update_pending": true, "database_size": true}
return "panel/" + q.Operation, read[q.Operation]
}
read := route == "/v1/database/phpmyadmin" || route == "/v1/site/log" || route == "/healthz" || route == "/v1/resources/usage" || route == "/v1/runtime/probe" || route == "/v1/runtime/backups/prune" || route == "/v1/lifecycle/backup/verify"
return "agent" + route, read
}
func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
var body []byte
var err error
if r.Body != nil {
body, err = io.ReadAll(io.LimitReader(r.Body, controlwire.MaxEnvelopeBytes+1))
}
if r.Body != nil {
_ = r.Body.Close()
}
if err != nil || len(body) > controlwire.MaxEnvelopeBytes {
return nil, errors.New("execution request exceeds limit")
}
node, err := t.manager.Resolve(r.Context(), body)
if t.kind == "isolation" && r.URL.Path == "/v1/lifecycle/backup/delete" {
if id, explicit := scope.ExplicitNode(r.Context()); explicit {
node, err = t.manager.Store.Node(r.Context(), id)
if err == nil && !node.Enabled {
err = errors.New("节点已停用")
}
}
}
if err != nil {
return nil, err
}
if node.Transport == "local" {
socket := t.manager.PanelSocket
if t.kind == "isolation" {
socket = t.manager.AgentSocket
}
if socket == "" || t.manager.LocalToken == "" {
return nil, errors.New("local node is not configured")
}
local := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}}
defer local.CloseIdleConnections()
req := r.Clone(r.Context())
req.Body = io.NopCloser(bytes.NewReader(body))
req.ContentLength = int64(len(body))
req.Header.Set("Authorization", "Bearer "+t.manager.LocalToken)
return local.RoundTrip(req)
}
if t.kind == "panel" && r.URL.Path != "/v1/operations" {
return nil, errors.New("remote node does not expose panel setup endpoints")
}
operation, readOnly := executionOperation(t.kind, r.URL.Path, body)
if operation == "agent/v1/ftp/tls" || operation == "agent/v1/runtime/python/install" || operation == "agent/v1/runtime/php/maintenance" || operation == "panel/install_runtime_component" || operation == "panel/install_runtime_environment" || operation == "panel/update_php_runtime" {
r = r.WithContext(scope.WithProject(r.Context(), 0, node.ID))
}
if !readOnly {
blocked, e := t.manager.Store.NodeHasUnresolvedTask(r.Context(), node.ID)
if e != nil {
return nil, e
}
if blocked {
return nil, ErrUncertain
}
}
route := "/v1/isolation" + r.URL.Path
if t.kind == "isolation" && r.Method == http.MethodGet && r.URL.Path == "/healthz" {
route = "/v1/status"
}
var lease *store.NodeRegistryLease
if t.kind == "panel" {
lease, err = t.manager.Store.LockNodeRegistry(r.Context(), node.ID)
if err != nil {
return nil, err
}
defer lease.Close()
if !readOnly {
blocked, e := t.manager.Store.NodeHasUnresolvedTask(r.Context(), node.ID)
if e != nil {
return nil, e
}
if blocked {
return nil, ErrUncertain
}
}
snapshot, e := lease.Read(r.Context())
if e != nil {
return nil, e
}
body, e = json.Marshal(panel.ScopedExecution{Request: body, Registry: snapshot})
if e != nil {
return nil, e
}
route = "/v1/panel"
}
id, err := requestID()
if err != nil {
return nil, err
}
var task uint64
if !readOnly {
task, err = t.manager.Store.StartControlTask(r.Context(), node.ID, scope.Project(r.Context()), operation, id)
if err != nil {
return nil, err
}
}
finish := func(state, detail string) {
if task == 0 {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = t.manager.Store.FinishControlTask(ctx, task, state, detail)
}
client, err := t.manager.client(node)
if err != nil {
finish("failed", "节点身份配置无效")
return nil, err
}
defer client.CloseIdleConnections()
req, err := controlwire.NewRequest(r.Method, node.Endpoint, route, node.ID, id, body)
if err != nil {
finish("failed", "节点请求配置无效")
return nil, err
}
response, err := client.Do(req.WithContext(r.Context()))
if err != nil {
finish("uncertain", "连接中断,需要核对被控实际状态")
return nil, ErrUncertain
}
defer response.Body.Close()
result, err := io.ReadAll(io.LimitReader(response.Body, controlwire.MaxEnvelopeBytes+1))
if err != nil || len(result) > controlwire.MaxEnvelopeBytes {
finish("uncertain", "节点响应不完整")
return nil, ErrUncertain
}
if response.StatusCode != 200 {
detail := []rune(strings.TrimSpace(string(result)))
if len(detail) > 300 {
detail = detail[:300]
}
if !readOnly {
finish("uncertain", fmt.Sprintf("节点返回 HTTP %d:%s;请核对实际状态", response.StatusCode, string(detail)))
return nil, ErrUncertain
}
finish("uncertain", fmt.Sprintf("节点返回 HTTP %d,需要核对实际状态", response.StatusCode))
return &http.Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: io.NopCloser(bytes.NewReader(result)), Request: r}, nil
}
if lease != nil {
var out panel.ScopedResult
if json.Unmarshal(result, &out) != nil || len(out.Registry) == 0 || !json.Valid(out.Registry) {
finish("uncertain", "节点资源响应待核验")
return nil, ErrUncertain
}
if err = lease.Save(r.Context(), out.Registry); err != nil {
finish("uncertain", "资源登记回写失败")
return nil, ErrUncertain
}
result = out.Response
}
finish("succeeded", "")
_ = t.manager.Store.RecordNodeProbe(r.Context(), node.ID, "")
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(bytes.NewReader(result)), Request: r}, nil
}
func (m *Manager) NodeDomains(ctx context.Context) ([]string, error) {
nodes, err := m.Store.Nodes(ctx)
if err != nil {
return nil, err
}
domains := []string{}
for _, node := range nodes {
if strings.TrimSpace(node.RootDomain) != "" {
domains = append(domains, node.RootDomain)
}
if node.FTPCertificateDomain != "" {
domains = append(domains, node.FTPCertificateDomain)
}
}
return domains, nil
}
@@ -0,0 +1,210 @@
package cluster
import (
"context"
"encoding/json"
"errors"
"github.com/go-sql-driver/mysql"
"io"
"log"
"net/http/httptest"
"os"
"path/filepath"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/executor"
"sea-vhost/internal/panel"
"sea-vhost/internal/scope"
"sea-vhost/internal/secrets"
"sea-vhost/internal/store"
"strings"
"testing"
"time"
)
func TestControllerTwoNodesMySQL(t *testing.T) {
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
if dsn == "" {
t.Skip("dedicated MySQL schema not supplied")
}
cfg, err := mysql.ParseDSN(dsn)
if err != nil || !strings.HasPrefix(cfg.DBName, "svh_cluster_test_") {
t.Fatal("non-test schema denied")
}
database, err := store.Open(dsn)
if err != nil {
t.Fatal(err)
}
defer database.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
if err = database.Migrate(ctx); err != nil {
t.Fatal(err)
}
plans, err := database.ListPlans(ctx)
if err != nil || len(plans) == 0 {
t.Fatal("plans unavailable")
}
tenant, err := database.CreateTenant(ctx, store.NewTenant{Slug: "rpc-test", Name: "RPC 测试用户", Email: "rpc@example.invalid", DisplayName: "RPC 测试", Password: "RPC-test-only-123456", PlanID: plans[0].ID})
if err != nil {
t.Fatal(err)
}
manager := &Manager{Store: database, Box: secrets.New(strings.Repeat("test-only-secret", 4))}
client := manager.Panel()
type host struct {
node, project uint64
name, root, domain string
site, ftp, db int64
}
hosts := []host{}
for _, name := range []string{"sv1111111111", "sv2222222222"} {
root := filepath.ToSlash(t.TempDir())
if err = os.Mkdir(filepath.Join(root, name), 0750); err != nil {
t.Fatal(err)
}
server := httptest.NewUnstartedServer(nil)
server.Config.ErrorLog = log.New(io.Discard, "", 0)
endpoint := "https://" + server.Listener.Addr().String()
node, err := database.CreateNode(ctx, store.Node{Name: name, Endpoint: endpoint, RootDomain: name + ".example.invalid", TenantRoot: root, FTPCertificateDomain: "ftp.example.invalid"})
if err != nil {
t.Fatal(err)
}
identity, err := manager.Pair(ctx, node)
if err != nil {
t.Fatal(err)
}
server.TLS, err = controlwire.ServerTLS(identity)
if err != nil {
t.Fatal(err)
}
server.Config.Handler = (&executor.Gateway{NodeID: node, TenantRoot: root, Direct: panel.NewMock()}).Handler()
server.StartTLS()
t.Cleanup(server.Close)
if err = manager.Probe(ctx, node); err != nil {
t.Fatal(err)
}
if err = database.SetNodeEnabled(ctx, node, true); err != nil {
t.Fatal(err)
}
project, err := database.InsertProject(ctx, store.NewProject{TenantID: tenant, NodeID: node, PlanID: plans[0].ID, HostName: name, Slug: name, Path: root + "/" + name, RunPath: "/public", Runtime: "PHP", Version: "8.4", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-only"})
if err != nil {
t.Fatal(err)
}
h := host{node: node, project: project, name: name, root: root + "/" + name, domain: name + ".example.invalid"}
op := scope.WithProject(ctx, project, node)
h.site, err = client.CreateSite(op, panel.SiteSpec{Name: name, Domain: h.domain, Path: h.root, RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: name, Port: 20000, ProcessLimit: 10})
if err != nil {
t.Fatal(err)
}
h.ftp, err = client.CreateFTP(op, name, "TestPassword123456789", h.root, 1<<20)
if err != nil {
t.Fatal(err)
}
h.db, err = client.CreateDatabase(op, name, name, "TestPassword123456789", h.site)
if err != nil {
t.Fatal(err)
}
if err = database.CompleteProject(op, project, h.site, h.ftp, h.db, name, name, name, []byte("cipher"), []byte("cipher"), "running", "", "", false); err != nil {
t.Fatal(err)
}
rootFiles, err := manager.OpenFiles(op, h.root)
if err != nil {
t.Fatal(err)
}
file, err := rootFiles.OpenFile("marker.txt", os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0660)
if err != nil {
t.Fatal(err)
}
if _, err = file.Write([]byte(name)); err != nil {
t.Fatal(err)
}
if err = file.Close(); err != nil {
t.Fatal(err)
}
if err = manager.Isolation().Ping(op); err != nil {
t.Fatalf("remote GET health routing: %v", err)
}
hosts = append(hosts, h)
}
if hosts[0].site != hosts[1].site || hosts[0].ftp != hosts[1].ftp || hosts[0].db != hosts[1].db {
t.Fatal("native ID collision was not exercised")
}
for _, h := range hosts {
op := scope.WithProject(ctx, h.project, h.node)
lease, err := database.LockNodeRegistry(op, h.node)
if err != nil {
t.Fatal(err)
}
raw, err := lease.Read(op)
lease.Close()
if err != nil {
t.Fatal(err)
}
var registry struct {
Sites map[string]json.RawMessage `json:"sites"`
}
if json.Unmarshal(raw, &registry) != nil || len(registry.Sites) != 1 || !strings.Contains(string(raw), h.domain) {
t.Fatalf("controller registry mismatch: %s", raw)
}
targets, err := database.RuntimeTargets(op)
if err != nil || len(targets) != 1 || targets[0].Project.NodeID != h.node {
t.Fatalf("runtime target placement: %+v %v", targets, err)
}
if err = client.SetSiteState(op, h.site, h.domain, false); err != nil {
t.Fatal(err)
}
}
a := hosts[0]
b := hosts[1]
opA := scope.WithProject(ctx, a.project, a.node)
opB := scope.WithProject(ctx, b.project, b.node)
if _, err = client.CreateSite(opA, panel.SiteSpec{Name: a.name, Domain: "invalid.example.invalid", Path: "/outside/namespace", RunPath: "/", Runtime: "PHP", Version: "8.4", RunUser: a.name, Port: 20001, ProcessLimit: 10}); !errors.Is(err, ErrUncertain) {
t.Fatalf("write rejection should preserve an uncertain task: %v", err)
}
if err = client.SetSiteState(opA, a.site, a.domain, true); !errors.Is(err, ErrUncertain) {
t.Fatalf("unresolved node mutation was allowed: %v", err)
}
if _, err = database.CreateRuntimeJob(opA, store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}); err == nil {
t.Fatal("node-wide maintenance ignored unresolved host state")
}
// A tenant-triggered failure must not freeze another host on the same node.
peerName := "sv4444444444"
peerRoot := filepath.Join(filepath.Dir(a.root), peerName)
if err = os.Mkdir(peerRoot, 0750); err != nil {
t.Fatal(err)
}
peer, err := database.InsertProject(ctx, store.NewProject{TenantID: tenant, NodeID: a.node, PlanID: plans[0].ID, HostName: peerName, Slug: peerName, Path: peerRoot, RunPath: "/public", Runtime: "PHP", Version: "8.4", Domain: peerName + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-only"})
if err != nil {
t.Fatal(err)
}
peerCtx := scope.WithProject(ctx, peer, a.node)
peerSite, err := client.CreateSite(peerCtx, panel.SiteSpec{Name: peerName, Domain: peerName + ".example.invalid", Path: peerRoot, RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: peerName, Port: 20020, ProcessLimit: 10})
if err != nil {
t.Fatalf("host A failure blocked another host on the same node: %v", err)
}
if err = client.SetSiteState(peerCtx, peerSite, peerName+".example.invalid", true); err != nil {
t.Fatal(err)
}
if err = client.SetSiteState(opB, b.site, b.domain, true); err != nil {
t.Fatalf("node A failure blocked node B: %v", err)
}
tasks, err := database.ControlTasks(ctx, a.node)
if err != nil {
t.Fatal(err)
}
resolved := false
for _, task := range tasks {
if task.State == "uncertain" {
if err = database.ResolveControlTask(ctx, a.node, task.ID, "测试已核对拒绝发生在变更之前"); err != nil {
t.Fatal(err)
}
resolved = true
}
}
if !resolved {
t.Fatal("uncertain operation was not recorded centrally")
}
if err = client.SetSiteState(opA, a.site, a.domain, true); err != nil {
t.Fatal(err)
}
t.Log("controller MySQL + two mTLS gateways: native ID collision, central snapshots, site/FTP/database operations, file routing, health routing, maintenance placement and independent failure recovery passed")
}
+20
View File
@@ -0,0 +1,20 @@
package cluster
import "testing"
func TestRoutingIgnoresCustomerDomainPrefixes(t *testing.T) {
cases := []struct {
body map[string]any
host string
}{
{map[string]any{"name": "sv0123456789.customer.example", "domain": "svabcdef0123.example"}, ""},
{map[string]any{"hostName": "sv0123456789"}, "sv0123456789"},
{map[string]any{"site": map[string]any{"Name": "svabcdef0123", "Domain": "sv0123456789.customer.example"}}, "svabcdef0123"},
{map[string]any{"runtime": map[string]any{"ProjectName": "svabcdef0123_42"}}, "svabcdef0123"},
}
for _, tc := range cases {
if got := hostFromValue(tc.body); got != tc.host {
t.Fatalf("route identity = %q, want %q", got, tc.host)
}
}
}
+267
View File
@@ -0,0 +1,267 @@
package config
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
var ErrSetupRequired = errors.New("Sea vHost has not been installed")
type Config struct {
ControllerOnly bool
Addr string
DatabaseDSN string
SessionSecret string
CookieSecure bool
PanelBrokerSocket string
PanelMock bool
RootDomain string
TenantRoot string
UploadLimitBytes int64
DomainApproval bool
SessionTTL time.Duration
ProvisionTimeout time.Duration
AgentSocket string
AgentMock bool
InternalAuthToken string
ManagementDomain string
FTPDomain string
ReservedDomains []string
}
type persistedConfig struct {
ControllerOnly bool `json:"controller_only,omitempty"`
Version int `json:"version"`
DatabaseDSN string `json:"database_dsn"`
SessionSecret string `json:"session_secret"`
CookieSecure bool `json:"cookie_secure"`
PanelBrokerSocket string `json:"panel_broker_socket"`
PanelMock bool `json:"panel_mock"`
RootDomain string `json:"root_domain"`
TenantRoot string `json:"tenant_root"`
UploadLimitBytes int64 `json:"upload_limit_bytes"`
DomainApproval bool `json:"domain_approval"`
AgentSocket string `json:"agent_socket"`
AgentMock bool `json:"agent_mock"`
ManagementDomain string `json:"management_domain,omitempty"`
FTPDomain string `json:"ftp_domain,omitempty"`
ReservedDomains []string `json:"reserved_domains,omitempty"`
}
func Path() string { return env("SEA_CONFIG_FILE", "/var/lib/sea-vhost/config.json") }
func SetupAddr() string { return env("SEA_ADDR", "127.0.0.1:8080") }
func AgentSocketPath() string { return env("SEA_AGENT_SOCKET", "/run/sea-vhost/agent.sock") }
func PanelBrokerSocketPath() string {
return env("SEA_PANEL_BROKER_SOCKET", "/run/sea-vhost-panel/broker.sock")
}
func Load() (Config, error) {
data, err := os.ReadFile(Path())
if err == nil {
var stored persistedConfig
if err := json.Unmarshal(data, &stored); err != nil {
return Config{}, fmt.Errorf("read installed configuration: %w", err)
}
cfg := defaults()
cfg.ControllerOnly = stored.ControllerOnly || envBool("SEA_CONTROLLER_ONLY", false)
cfg.DatabaseDSN = stored.DatabaseDSN
cfg.SessionSecret = stored.SessionSecret
cfg.CookieSecure = stored.CookieSecure
cfg.PanelBrokerSocket = stored.PanelBrokerSocket
if strings.TrimSpace(cfg.PanelBrokerSocket) == "" {
cfg.PanelBrokerSocket = PanelBrokerSocketPath()
}
cfg.PanelMock = stored.PanelMock
cfg.RootDomain = strings.ToLower(stored.RootDomain)
cfg.TenantRoot = stored.TenantRoot
cfg.UploadLimitBytes = stored.UploadLimitBytes
cfg.DomainApproval = stored.DomainApproval
cfg.AgentSocket = stored.AgentSocket
cfg.AgentMock = stored.AgentMock
cfg.ManagementDomain = strings.ToLower(strings.TrimSuffix(stored.ManagementDomain, "."))
cfg.FTPDomain = strings.ToLower(strings.TrimSuffix(stored.FTPDomain, "."))
cfg.ReservedDomains = normalizeDomains(stored.ReservedDomains)
cfg.InternalAuthToken = InternalAuthToken()
// Operational values may be changed without rewriting stored secrets.
cfg.Addr = SetupAddr()
return cfg, Validate(cfg)
}
if !errors.Is(err, os.ErrNotExist) {
return Config{}, fmt.Errorf("read configuration: %w", err)
}
// Keep the legacy environment-only path for development and upgrades.
if strings.TrimSpace(os.Getenv("SEA_SESSION_SECRET")) == "" {
return Config{}, ErrSetupRequired
}
cfg := fromEnvironment()
return cfg, Validate(cfg)
}
func NewInstalled(databaseDSN, sessionSecret, rootDomain, managementDomain, ftpDomain string, reservedDomains []string, domainApproval bool) Config {
cfg := defaults()
cfg.DatabaseDSN = databaseDSN
cfg.SessionSecret = sessionSecret
cfg.PanelMock = false
cfg.RootDomain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(rootDomain)), ".")
cfg.AgentMock = false
cfg.DomainApproval = domainApproval
cfg.ManagementDomain = normalizeDomain(managementDomain)
cfg.FTPDomain = normalizeDomain(ftpDomain)
cfg.ReservedDomains = normalizeDomains(reservedDomains)
return cfg
}
func Save(cfg Config) error {
if err := Validate(cfg); err != nil {
return err
}
stored := persistedConfig{
ControllerOnly: cfg.ControllerOnly,
Version: 1, DatabaseDSN: cfg.DatabaseDSN, SessionSecret: cfg.SessionSecret,
CookieSecure: cfg.CookieSecure, PanelBrokerSocket: cfg.PanelBrokerSocket,
PanelMock: cfg.PanelMock, RootDomain: cfg.RootDomain,
TenantRoot: cfg.TenantRoot, UploadLimitBytes: cfg.UploadLimitBytes, DomainApproval: cfg.DomainApproval,
AgentSocket: cfg.AgentSocket, AgentMock: cfg.AgentMock,
ManagementDomain: cfg.ManagementDomain, FTPDomain: cfg.FTPDomain,
ReservedDomains: cfg.ReservedDomains,
}
data, err := json.MarshalIndent(stored, "", " ")
if err != nil {
return err
}
path := Path()
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
temporary, err := os.CreateTemp(filepath.Dir(path), ".config-*.tmp")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err = temporary.Chmod(0600); err == nil {
_, err = temporary.Write(append(data, '\n'))
}
if err == nil {
err = temporary.Sync()
}
closeErr := temporary.Close()
if err != nil {
return err
}
if closeErr != nil {
return closeErr
}
// Hard-linking is atomic and fails if another installer already won the race.
if err := os.Link(temporaryPath, path); err != nil {
if errors.Is(err, os.ErrExist) {
return fmt.Errorf("configuration already exists")
}
return err
}
return nil
}
func Validate(cfg Config) error {
if len(cfg.SessionSecret) < 32 {
return fmt.Errorf("session secret must contain at least 32 characters")
}
if strings.TrimSpace(cfg.DatabaseDSN) == "" {
return fmt.Errorf("database DSN is required")
}
if !cfg.ControllerOnly && !cfg.PanelMock && strings.TrimSpace(cfg.PanelBrokerSocket) == "" {
return fmt.Errorf("panel broker socket is required")
}
if cfg.UploadLimitBytes <= 0 {
return fmt.Errorf("upload limit must be positive")
}
if !cfg.ControllerOnly && (!cfg.PanelMock || !cfg.AgentMock) && len(strings.TrimSpace(cfg.InternalAuthToken)) < 32 {
return fmt.Errorf("internal authentication token must contain at least 32 characters")
}
return nil
}
func defaults() Config {
return Config{
ControllerOnly: envBool("SEA_CONTROLLER_ONLY", false),
Addr: SetupAddr(), CookieSecure: envBool("SEA_COOKIE_SECURE", true),
PanelBrokerSocket: PanelBrokerSocketPath(), RootDomain: "vhost.ser888.cn",
TenantRoot: env("SEA_TENANT_ROOT", "/www/wwwroot/seavHost/vHost"), UploadLimitBytes: envInt64("SEA_UPLOAD_LIMIT", 20*1024*1024),
DomainApproval: true, SessionTTL: 12 * time.Hour, ProvisionTimeout: 4 * time.Minute,
AgentSocket: AgentSocketPath(),
InternalAuthToken: InternalAuthToken(),
}
}
func fromEnvironment() Config {
cfg := defaults()
cfg.DatabaseDSN = env("SEA_DATABASE_DSN", "sea_vhost:change-me@tcp(127.0.0.1:3306)/sea_vhost?parseTime=true&charset=utf8mb4&collation=utf8mb4_unicode_ci")
cfg.SessionSecret = os.Getenv("SEA_SESSION_SECRET")
cfg.PanelMock = envBool("SEA_PANEL_MOCK", true)
cfg.RootDomain = strings.ToLower(env("SEA_ROOT_DOMAIN", cfg.RootDomain))
cfg.DomainApproval = envBool("SEA_DOMAIN_APPROVAL", true)
cfg.AgentMock = envBool("SEA_AGENT_MOCK", true)
cfg.ManagementDomain = normalizeDomain(os.Getenv("SEA_MANAGEMENT_DOMAIN"))
cfg.FTPDomain = normalizeDomain(os.Getenv("SEA_FTP_DOMAIN"))
cfg.ReservedDomains = normalizeDomains(strings.Split(os.Getenv("SEA_RESERVED_DOMAINS"), ","))
return cfg
}
func InternalAuthToken() string { return strings.TrimSpace(os.Getenv("SEA_INTERNAL_AUTH_TOKEN")) }
func normalizeDomain(value string) string {
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
}
func normalizeDomains(values []string) []string {
result := make([]string, 0, len(values))
seen := make(map[string]bool, len(values))
for _, value := range values {
value = normalizeDomain(value)
if value != "" && !seen[value] {
seen[value] = true
result = append(result, value)
}
}
return result
}
func env(name, fallback string) string {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
return fallback
}
func envBool(name string, fallback bool) bool {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return fallback
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return fallback
}
return parsed
}
func envInt64(name string, fallback int64) int64 {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return fallback
}
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil || parsed <= 0 {
return fallback
}
return parsed
}
+53
View File
@@ -0,0 +1,53 @@
package config
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSaveAndLoadInstalledConfiguration(t *testing.T) {
path := filepath.Join(t.TempDir(), "state", "config.json")
t.Setenv("SEA_CONFIG_FILE", path)
t.Setenv("SEA_SESSION_SECRET", "")
t.Setenv("SEA_INTERNAL_AUTH_TOKEN", strings.Repeat("i", 48))
cfg := NewInstalled(
"sea_vhost:secret@tcp(127.0.0.1:3306)/sea_vhost?parseTime=true",
"012345678901234567890123456789012345678901234567",
"hosts.example.com", "console.example.com", "ftp.example.com", []string{"panel.example.com"}, false,
)
if err := Save(cfg); err != nil {
t.Fatalf("Save() error = %v", err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), "panel_api_key") {
t.Fatal("Web API configuration contains a panel API key")
}
loaded, err := Load()
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if loaded.DatabaseDSN != cfg.DatabaseDSN || loaded.PanelBrokerSocket != cfg.PanelBrokerSocket || loaded.RootDomain != cfg.RootDomain || loaded.ManagementDomain != cfg.ManagementDomain || loaded.FTPDomain != cfg.FTPDomain {
t.Fatalf("Load() did not preserve installed configuration")
}
if loaded.PanelMock || loaded.AgentMock || loaded.DomainApproval {
t.Fatalf("production flags were not preserved")
}
if err := Save(cfg); err == nil {
t.Fatal("Save() unexpectedly overwrote an installed configuration")
}
}
func TestLoadRequiresSetupWithoutConfigOrLegacySecret(t *testing.T) {
t.Setenv("SEA_CONFIG_FILE", filepath.Join(t.TempDir(), "missing.json"))
t.Setenv("SEA_SESSION_SECRET", "")
_, err := Load()
if !errors.Is(err, ErrSetupRequired) {
t.Fatalf("Load() error = %v, want ErrSetupRequired", err)
}
}
+86
View File
@@ -0,0 +1,86 @@
package controlwire
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"errors"
"math/big"
"net"
"time"
)
func Pair(nodeID uint64, endpoint string) (Credentials, ServerIdentity, error) {
if nodeID == 0 {
return Credentials{}, ServerIdentity{}, errors.New("node identity required")
}
u, err := ValidateEndpoint(endpoint)
if err != nil {
return Credentials{}, ServerIdentity{}, err
}
serial := func() (*big.Int, error) { return rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120)) }
caSerial, err := serial()
if err != nil {
return Credentials{}, ServerIdentity{}, err
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return Credentials{}, ServerIdentity{}, err
}
now := time.Now()
ca := &x509.Certificate{SerialNumber: caSerial, Subject: pkix.Name{CommonName: "Sea vHost node trust"}, NotBefore: now.Add(-5 * time.Minute), NotAfter: now.AddDate(2, 0, 0), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign}
caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key)
if err != nil {
return Credentials{}, ServerIdentity{}, err
}
caPEM := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}))
issue := func(client bool) (string, string, *ecdsa.PrivateKey, error) {
k, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if e != nil {
return "", "", nil, e
}
certSerial, e := serial()
if e != nil {
return "", "", nil, e
}
cert := &x509.Certificate{SerialNumber: certSerial, Subject: pkix.Name{CommonName: "Sea vHost paired identity"}, NotBefore: now.Add(-5 * time.Minute), NotAfter: now.AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature}
if client {
cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
} else {
cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
if ip := net.ParseIP(u.Hostname()); ip != nil {
cert.IPAddresses = []net.IP{ip}
} else {
cert.DNSNames = []string{u.Hostname()}
}
}
der, e := x509.CreateCertificate(rand.Reader, cert, ca, &k.PublicKey, key)
if e != nil {
return "", "", nil, e
}
private, e := x509.MarshalPKCS8PrivateKey(k)
if e != nil {
return "", "", nil, e
}
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})), string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: private})), k, nil
}
clientCert, clientKey, client, e := issue(true)
if e != nil {
return Credentials{}, ServerIdentity{}, e
}
serverCert, serverKey, _, e := issue(false)
if e != nil {
return Credentials{}, ServerIdentity{}, e
}
spki, e := x509.MarshalPKIXPublicKey(&client.PublicKey)
if e != nil {
return Credentials{}, ServerIdentity{}, e
}
digest := sha256.Sum256(spki)
return Credentials{CAPEM: caPEM, ClientCertificate: clientCert, ClientPrivateKey: clientKey}, ServerIdentity{NodeID: nodeID, CAPEM: caPEM, Certificate: serverCert, PrivateKey: serverKey, ClientSPKI: hex.EncodeToString(digest[:])}, nil
}
+176
View File
@@ -0,0 +1,176 @@
// Package controlwire defines the versioned controller-initiated node wire
// protocol. It has no store, scheduler or business database dependency.
package controlwire
import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
const Version = "sea-vhost-node/1"
const MaxEnvelopeBytes = 4 << 20
type Credentials struct {
CAPEM string `json:"caPem"`
ClientCertificate string `json:"clientCertificate"`
ClientPrivateKey string `json:"clientPrivateKey"`
}
type ServerIdentity struct {
NodeID uint64 `json:"nodeId"`
CAPEM string `json:"caPem"`
Certificate string `json:"certificate"`
PrivateKey string `json:"privateKey"`
ClientSPKI string `json:"clientSpki"`
}
func ValidateEndpoint(endpoint string) (*url.URL, error) {
u, err := url.Parse(endpoint)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
return nil, errors.New("node endpoint must be an HTTPS origin without credentials, path, query or fragment")
}
return u, nil
}
func ClientTLS(credentials Credentials) (*tls.Config, error) {
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM([]byte(credentials.CAPEM)) {
return nil, errors.New("invalid node CA")
}
certificate, err := tls.X509KeyPair([]byte(credentials.ClientCertificate), []byte(credentials.ClientPrivateKey))
if err != nil {
return nil, errors.New("invalid controller client identity")
}
return &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{certificate}}, nil
}
func ServerTLS(identity ServerIdentity) (*tls.Config, error) {
if identity.NodeID == 0 || len(identity.ClientSPKI) != 64 {
return nil, errors.New("invalid node identity")
}
expected, err := hex.DecodeString(identity.ClientSPKI)
if err != nil {
return nil, err
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM([]byte(identity.CAPEM)) {
return nil, errors.New("invalid controller trust CA")
}
certificate, err := tls.X509KeyPair([]byte(identity.Certificate), []byte(identity.PrivateKey))
if err != nil {
return nil, errors.New("invalid node TLS keypair")
}
return &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{certificate}, ClientCAs: roots, ClientAuth: tls.RequireAndVerifyClientCert, VerifyConnection: func(state tls.ConnectionState) error {
if len(state.PeerCertificates) == 0 {
return errors.New("controller identity missing")
}
actual := sha256.Sum256(state.PeerCertificates[0].RawSubjectPublicKeyInfo)
if subtle.ConstantTimeCompare(actual[:], expected) != 1 {
return errors.New("controller identity is not paired to this node")
}
return nil
}}, nil
}
func Decode(w http.ResponseWriter, r *http.Request, out any) error {
r.Body = http.MaxBytesReader(w, r.Body, MaxEnvelopeBytes)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(out); err != nil {
return errors.New("invalid node request")
}
if decoder.Decode(&struct{}{}) != io.EOF {
return errors.New("trailing node request data")
}
return nil
}
func Encode(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
// Authenticated also binds the destination node and protocol. Credentials for
// one node cannot be silently reused against a different node endpoint.
func Authenticated(nodeID uint64, next http.Handler) http.Handler {
var mu sync.Mutex
seen := map[string]int64{}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS == nil || len(r.TLS.VerifiedChains) == 0 {
http.Error(w, "mutual TLS required", 401)
return
}
if r.Header.Get("X-Sea-Protocol") != Version || r.Header.Get("X-Sea-Node") != strconv.FormatUint(nodeID, 10) {
http.Error(w, "wrong node or protocol", 403)
return
}
expiry, err := strconv.ParseInt(r.Header.Get("X-Sea-Expires"), 10, 64)
now := time.Now().Unix()
if err != nil || expiry < now || expiry > now+300 {
http.Error(w, "expired node request", 403)
return
}
requestID := r.Header.Get("X-Sea-Request")
if len(requestID) != 32 {
http.Error(w, "invalid request identity", 400)
return
}
if _, err := hex.DecodeString(requestID); err != nil {
http.Error(w, "invalid request identity", 400)
return
}
if r.Method != http.MethodGet {
mu.Lock()
for id, until := range seen {
if until < now {
delete(seen, id)
}
}
_, duplicate := seen[requestID]
full := len(seen) >= 20000
if !duplicate && !full {
seen[requestID] = expiry
}
mu.Unlock()
if duplicate {
http.Error(w, "request already received; reconcile actual state", 409)
return
}
if full {
http.Error(w, "node request capacity reached", 503)
return
}
}
next.ServeHTTP(w, r)
})
}
func NewRequest(method, endpoint, route string, nodeID uint64, requestID string, body []byte) (*http.Request, error) {
base, err := ValidateEndpoint(endpoint)
if err != nil {
return nil, err
}
if !strings.HasPrefix(route, "/v1/") || strings.Contains(route, "..") || strings.ContainsAny(route, "?#") {
return nil, errors.New("invalid node route")
}
base.Path = route
request, err := http.NewRequest(method, base.String(), bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Sea-Protocol", Version)
request.Header.Set("X-Sea-Node", strconv.FormatUint(nodeID, 10))
request.Header.Set("X-Sea-Request", requestID)
request.Header.Set("X-Sea-Expires", strconv.FormatInt(time.Now().Add(2*time.Minute).Unix(), 10))
return request, nil
}
+184
View File
@@ -0,0 +1,184 @@
package dnsprovider
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type dnsmgr struct {
client *http.Client
zone string
credential Credential
now func() time.Time
}
func positiveID(s string) bool {
id, e := strconv.ParseUint(s, 10, 64)
return e == nil && id > 0 && strconv.FormatUint(id, 10) == s
}
func md5Hex(v string) string { sum := md5.Sum([]byte(v)); return hex.EncodeToString(sum[:]) }
func (p *dnsmgr) call(ctx context.Context, path string, values url.Values, output any) error {
stamp := strconv.FormatInt(p.now().Unix(), 10)
values.Set("uid", p.credential.UserID)
values.Set("timestamp", stamp)
values.Set("sign", md5Hex(p.credential.UserID+stamp+p.credential.APIKey))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(p.credential.Endpoint, "/")+"/api/"+path, strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// List APIs use {total,rows}; mutation/info APIs require an explicit successful code.
var raw json.RawMessage
if err = doJSON(p.client, req, &raw); err != nil {
return err
}
var status struct {
Code *int `json:"code"`
}
if json.Unmarshal(raw, &status) != nil {
return errors.New("彩虹 DNS 响应无效")
}
if status.Code != nil && *status.Code != 0 {
return errors.New("彩虹 DNS 拒绝请求,请检查 API 权限与票据")
}
if !strings.HasSuffix(path, "domain") && !strings.HasPrefix(path, "record/data/") && status.Code == nil {
return errors.New("彩虹 DNS 未确认操作结果")
}
return json.Unmarshal(raw, output)
}
func (p *dnsmgr) Present(ctx context.Context, fqdn, value string) (string, error) {
return p.CreateRecord(ctx, fqdn, "TXT", value)
}
type mgrRecord struct {
ID json.RawMessage `json:"RecordId"`
Name string `json:"Name"`
Type string `json:"Type"`
Value json.RawMessage `json:"Value"`
}
func rawID(raw json.RawMessage) string {
var s string
if json.Unmarshal(raw, &s) == nil {
return s
}
var n json.Number
if json.Unmarshal(raw, &n) == nil {
return n.String()
}
return ""
}
func rawValueContains(raw json.RawMessage, value string) bool {
var s string
if json.Unmarshal(raw, &s) == nil {
return s == value
}
var all []string
if json.Unmarshal(raw, &all) == nil {
for _, s := range all {
if s == value {
return true
}
}
}
return false
}
func (p *dnsmgr) records(ctx context.Context, rr, kind, value string) ([]mgrRecord, error) {
var out struct {
Total *int `json:"total"`
Rows []mgrRecord `json:"rows"`
}
if err := p.call(ctx, "record/data/"+p.credential.ZoneID, url.Values{"subdomain": {rr}, "type": {kind}, "value": {value}, "offset": {"0"}, "limit": {"100"}}, &out); err != nil {
return nil, err
}
if out.Total == nil || *out.Total > 100 {
return nil, errors.New("彩虹 DNS 记录响应不完整")
}
return out.Rows, nil
}
func (p *dnsmgr) CreateRecord(ctx context.Context, fqdn, kind, value string) (string, error) {
if err := validateRecord(kind, value); err != nil {
return "", err
}
rr, err := relativeRecordName(fqdn, p.zone)
if err != nil {
return "", err
}
if !positiveID(p.credential.ZoneID) {
return "", errors.New("彩虹 DNS 域名编号无效")
}
before, err := p.records(ctx, rr, kind, value)
if err != nil {
return "", err
}
old := map[string]bool{}
for _, r := range before {
old[rawID(r.ID)] = true
}
var info struct {
Code int `json:"code"`
Data struct {
RecordLine []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"recordLine"`
MinTTL json.Number `json:"minTTL"`
} `json:"data"`
}
if err = p.call(ctx, "domain/"+p.credential.ZoneID, url.Values{}, &info); err != nil {
return "", err
}
minTTL := int64(0)
if info.Data.MinTTL != "" {
minTTL, err = info.Data.MinTTL.Int64()
if err != nil || minTTL < 0 || minTTL > 2147483647 {
return "", errors.New("彩虹 DNS 返回了无效的最小 TTL")
}
}
line := ""
found := false
for _, l := range info.Data.RecordLine {
if l.Name == "默认" || strings.EqualFold(l.Name, "default") {
line = l.ID
found = true
break
}
}
if !found {
return "", errors.New("彩虹 DNS 未提供默认解析线路")
}
var response struct {
Code int `json:"code"`
}
if err = p.call(ctx, "record/add/"+p.credential.ZoneID, url.Values{"name": {rr}, "type": {kind}, "value": {value}, "line": {line}, "ttl": {strconv.FormatInt(max(int64(600), minTTL), 10)}}, &response); err != nil {
return "", err
}
after, err := p.records(ctx, rr, kind, value)
if err != nil {
return "", err
}
for _, r := range after {
id := rawID(r.ID)
if validIdentifier(id, 1, 128) && !old[id] && (r.Name == rr || r.Name == fqdn) && r.Type == kind && rawValueContains(r.Value, value) {
return id, nil
}
}
return "", errors.New("彩虹 DNS 已接受创建,但未能核对新增记录编号,请管理员核验")
}
func (p *dnsmgr) Cleanup(ctx context.Context, id string) error {
if !positiveID(p.credential.ZoneID) || !validIdentifier(id, 1, 128) {
return errors.New("彩虹 DNS 记录编号无效")
}
var out struct {
Code int `json:"code"`
}
return p.call(ctx, "record/delete/"+p.credential.ZoneID, url.Values{"recordid": {id}}, &out)
}
@@ -0,0 +1,36 @@
package dnsprovider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestDNSManagerRejectsInvalidTTLBeforeCreatingRecord(t *testing.T) {
for _, ttl := range []any{"-1", "1.5", "invalid", "2147483648", false} {
t.Run(stringJSON(ttl), func(t *testing.T) {
writes := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/record/data/7":
_, _ = w.Write([]byte(`{"total":0,"rows":[]}`))
case "/api/domain/7":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"minTTL": ttl, "recordLine": []map[string]any{{"id": "default", "name": "默认"}}}})
default:
writes++
_, _ = w.Write([]byte(`{"code":0}`))
}
}))
defer server.Close()
provider := &dnsmgr{client: server.Client(), zone: "example.com", credential: Credential{Endpoint: server.URL, UserID: "12", APIKey: "fixture-api-key", ZoneID: "7"}, now: time.Now}
if _, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof"); err == nil || writes != 0 {
t.Fatal("invalid TTL reached mutation", err, writes)
}
})
}
}
func stringJSON(v any) string { raw, _ := json.Marshal(v); return string(raw) }
@@ -0,0 +1,128 @@
package dnsprovider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"testing"
"time"
)
func TestDNSManagerPreservesExistingRecordsAndSignsRequests(t *testing.T) {
for _, tc := range []struct {
name string
ttl any
want string
}{{"numeric", 600, "600"}, {"string-low", "60", "600"}, {"string-high", "1800", "1800"}} {
t.Run(tc.name, func(t *testing.T) {
created := false
deleted := ""
stamp := time.Unix(1780000000, 0)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Error("wrong method")
}
_ = r.ParseForm()
if r.Form.Get("uid") != "12" || r.Form.Get("timestamp") != strconv.FormatInt(stamp.Unix(), 10) || r.Form.Get("sign") != md5Hex("12"+strconv.FormatInt(stamp.Unix(), 10)+"fixture-api-key") {
t.Error("invalid API signature")
}
if r.Form.Get("key") != "" {
t.Error("plaintext key transmitted")
}
switch r.URL.Path {
case "/api/domain/7":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"recordLine": []map[string]any{{"id": "default", "name": "默认"}}, "minTTL": tc.ttl}})
case "/api/record/data/7":
rows := []map[string]any{{"RecordId": "9", "Name": "_acme-challenge", "Type": "TXT", "Value": "proof"}}
if created {
rows = append(rows, map[string]any{"RecordId": "10", "Name": "_acme-challenge", "Type": "TXT", "Value": "proof"})
}
_ = json.NewEncoder(w).Encode(map[string]any{"total": len(rows), "rows": rows})
case "/api/record/add/7":
if r.Form.Get("line") != "default" || r.Form.Get("name") != "_acme-challenge" || r.Form.Get("ttl") != tc.want {
t.Error("wrong record target")
}
created = true
_, _ = w.Write([]byte(`{"code":0}`))
case "/api/record/delete/7":
deleted = r.Form.Get("recordid")
_, _ = w.Write([]byte(`{"code":0}`))
default:
t.Error("unexpected endpoint", r.URL.Path)
w.WriteHeader(404)
}
}))
defer srv.Close()
p := &dnsmgr{client: srv.Client(), zone: "example.com", credential: Credential{Endpoint: srv.URL, UserID: "12", APIKey: "fixture-api-key", ZoneID: "7"}, now: func() time.Time { return stamp }}
id, e := p.Present(context.Background(), "_acme-challenge.example.com", "proof")
if e != nil || id != "10" {
t.Fatal(id, e)
}
if e = p.Cleanup(context.Background(), id); e != nil {
t.Fatal(e)
}
if deleted != "10" {
t.Fatal("deleted pre-existing record", deleted)
}
if _, e = p.Present(context.Background(), "outside.example.net", "proof"); e == nil {
t.Fatal("zone escape accepted")
}
})
}
}
func TestWestAccountUsesReadOnlyDiscoveryAndExactRecordDeletion(t *testing.T) {
deleted := ""
stamp := time.Unix(1780000000, 0)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
if r.Form.Get("token") != md5Hex("fixture-user"+"fixture-api-key"+strconv.FormatInt(stamp.UnixMilli(), 10)) {
t.Error("bad account signature")
}
switch r.Form.Get("act") {
case "adddnsrecord":
if r.Form.Get("domain") != "example.com" || r.Form.Get("host") != "_acme-challenge" {
t.Error("wrong zone")
}
_, _ = w.Write([]byte(`{"result":200,"data":{"id":55}}`))
case "deldnsrecord":
deleted = r.Form.Get("id")
_, _ = w.Write([]byte(`{"result":200,"data":{}}`))
default:
t.Error("unexpected operation")
w.WriteHeader(404)
}
}))
defer srv.Close()
p := &west{client: srv.Client(), baseURL: srv.URL, zone: "example.com", credential: Credential{Username: "fixture-user", APIKey: "fixture-api-key"}, now: func() time.Time { return stamp }}
id, e := p.Present(context.Background(), "_acme-challenge.example.com", "proof")
if e != nil || id != "55" {
t.Fatal(id, e)
}
if e = p.Cleanup(context.Background(), id); e != nil {
t.Fatal(e)
}
if deleted != "55" {
t.Fatal(deleted)
}
}
func TestDNSCustomEndpointCannotReachPrivateNetworks(t *testing.T) {
for _, s := range []string{"http://dns.example.com", "https://127.0.0.1", "https://[::1]", "https://10.0.0.1", "https://dns.example.com:9443", "https://user:key@dns.example.com", "https://dns.example.com?a=b", "https://100.64.0.1", "https://[64:ff9b::7f00:1]"} {
if _, e := publicEndpoint(s); e == nil {
t.Error("unsafe endpoint", s)
}
}
if _, e := publicEndpoint("https://dns.example.com/subdir"); e != nil {
t.Fatal(e)
}
for _, s := range []string{"127.0.0.1", "::1", "::ffff:127.0.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "64:ff9b::7f00:1", "2002:7f00:1::"} {
if publicIP(netip.MustParseAddr(s)) {
t.Error("restricted IP accepted", s)
}
}
if !publicIP(netip.MustParseAddr("1.1.1.1")) {
t.Fatal("public DNS address rejected")
}
}
+472
View File
@@ -0,0 +1,472 @@
package dnsprovider
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const maxResponseBytes = 64 << 10
type Provider interface {
Present(context.Context, string, string) (string, error)
CreateRecord(context.Context, string, string, string) (string, error)
Cleanup(context.Context, string) error
}
type Credential struct {
Endpoint string `json:"endpoint,omitempty"`
UserID string `json:"userId,omitempty"`
APIKey string `json:"apiKey,omitempty"`
Username string `json:"username,omitempty"`
DomainKey string `json:"domainKey,omitempty"`
APIToken string `json:"apiToken,omitempty"`
ZoneID string `json:"zoneId,omitempty"`
AccessKeyID string `json:"accessKeyId,omitempty"`
AccessKeySecret string `json:"accessKeySecret,omitempty"`
SecretID string `json:"secretId,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
}
func Validate(provider string, credential Credential) error {
provider = strings.ToLower(strings.TrimSpace(provider))
switch provider {
case "cloudflare":
if !validSecret(credential.APIToken, 20, 512) || !validIdentifier(credential.ZoneID, 8, 128) {
return errors.New("Cloudflare API Token 或 Zone ID 格式无效")
}
case "aliyun":
if !validIdentifier(credential.AccessKeyID, 8, 128) || !validSecret(credential.AccessKeySecret, 16, 512) {
return errors.New("阿里云 AccessKey ID 或 Secret 格式无效")
}
case "tencent":
if !validIdentifier(credential.SecretID, 8, 128) || !validSecret(credential.SecretKey, 16, 512) {
return errors.New("腾讯云 SecretId 或 SecretKey 格式无效")
}
case "west":
if credential.DomainKey != "" {
if !validSecret(credential.DomainKey, 8, 512) {
return errors.New("西部数码单域名密钥格式无效")
}
} else if !validSecret(credential.Username, 1, 128) || !validSecret(credential.APIKey, 8, 512) {
return errors.New("西部数码 API 用户名或 API 密码无效")
}
case "dnsmgr":
if !positiveID(credential.UserID) || !validSecret(credential.APIKey, 8, 512) {
return errors.New("彩虹 DNS 用户 ID 或密钥无效")
}
if _, err := publicEndpoint(credential.Endpoint); err != nil {
return err
}
default:
return errors.New("不支持的 DNS 服务商")
}
return nil
}
func New(provider, zone string, credential Credential) (Provider, error) {
if err := Validate(provider, credential); err != nil {
return nil, err
}
client := &http.Client{
Timeout: 20 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
switch strings.ToLower(strings.TrimSpace(provider)) {
case "cloudflare":
return &cloudflare{client: client, token: credential.APIToken, zoneID: credential.ZoneID}, nil
case "aliyun":
return &aliyun{client: client, accessKeyID: credential.AccessKeyID, accessKeySecret: credential.AccessKeySecret, zone: zone, now: time.Now}, nil
case "tencent":
return &tencent{client: client, secretID: credential.SecretID, secretKey: credential.SecretKey, zone: zone, now: time.Now}, nil
case "west":
return &west{client: client, zone: zone, credential: credential, now: time.Now}, nil
case "dnsmgr":
return &dnsmgr{client: publicClient(), zone: zone, credential: credential, now: time.Now}, nil
default:
return nil, errors.New("不支持的 DNS 服务商")
}
}
func validSecret(value string, min, max int) bool {
if value != strings.TrimSpace(value) || strings.ContainsAny(value, "\r\n\x00") {
return false
}
return len(value) >= min && len(value) <= max && !strings.ContainsAny(value, "\r\n\x00")
}
func validIdentifier(value string, min, max int) bool {
if value != strings.TrimSpace(value) {
return false
}
if len(value) < min || len(value) > max {
return false
}
for _, char := range value {
if !(char >= 'a' && char <= 'z') && !(char >= 'A' && char <= 'Z') && !(char >= '0' && char <= '9') && char != '-' && char != '_' {
return false
}
}
return true
}
func relativeRecordName(fqdn, zone string) (string, error) {
fqdn = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(fqdn), "."))
zone = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(zone), "."))
if fqdn == zone {
return "@", nil
}
suffix := "." + zone
if !strings.HasSuffix(fqdn, suffix) {
return "", errors.New("DNS 记录不属于凭据区域")
}
return strings.TrimSuffix(fqdn, suffix), nil
}
type cloudflare struct {
client *http.Client
token string
zoneID string
baseURL string
}
func (p *cloudflare) endpoint(path string) string {
base := p.baseURL
if base == "" {
base = "https://api.cloudflare.com/client/v4"
}
return strings.TrimSuffix(base, "/") + "/zones/" + url.PathEscape(p.zoneID) + "/dns_records" + path
}
func (p *cloudflare) Present(ctx context.Context, fqdn, value string) (string, error) {
return p.CreateRecord(ctx, fqdn, "TXT", value)
}
func (p *cloudflare) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
if err := validateRecord(recordType, value); err != nil {
return "", err
}
payload, _ := json.Marshal(map[string]any{"type": recordType, "name": fqdn, "content": value, "ttl": 120, "proxied": false})
request, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint(""), bytes.NewReader(payload))
if err != nil {
return "", err
}
request.Header.Set("Authorization", "Bearer "+p.token)
request.Header.Set("Content-Type", "application/json")
var response struct {
Success bool `json:"success"`
Result struct {
ID string `json:"id"`
} `json:"result"`
}
if err = doJSON(p.client, request, &response); err != nil || !response.Success || response.Result.ID == "" {
if err == nil {
err = errors.New("Cloudflare 未返回记录编号")
}
return "", err
}
return response.Result.ID, nil
}
func (p *cloudflare) Cleanup(ctx context.Context, recordID string) error {
if !validIdentifier(recordID, 1, 128) {
return errors.New("Cloudflare 记录编号无效")
}
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, p.endpoint("/"+url.PathEscape(recordID)), nil)
if err != nil {
return err
}
request.Header.Set("Authorization", "Bearer "+p.token)
request.Header.Set("Content-Type", "application/json")
var response struct {
Success bool `json:"success"`
}
if err = doJSON(p.client, request, &response); err != nil {
return err
}
if !response.Success {
return errors.New("Cloudflare 删除 DNS 记录失败")
}
return nil
}
type aliyun struct {
client *http.Client
accessKeyID, accessKeySecret string
zone, baseURL string
now func() time.Time
}
func (p *aliyun) Present(ctx context.Context, fqdn, value string) (string, error) {
return p.CreateRecord(ctx, fqdn, "TXT", value)
}
func (p *aliyun) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
if err := validateRecord(recordType, value); err != nil {
return "", err
}
rr, err := relativeRecordName(fqdn, p.zone)
if err != nil {
return "", err
}
var response struct {
RecordID string `json:"RecordId"`
}
err = p.call(ctx, "AddDomainRecord", url.Values{"DomainName": {p.zone}, "RR": {rr}, "Type": {recordType}, "Value": {value}, "TTL": {"600"}}, &response)
if err != nil {
return "", err
}
if response.RecordID == "" {
return "", errors.New("阿里云未返回记录编号")
}
return response.RecordID, nil
}
func (p *aliyun) Cleanup(ctx context.Context, recordID string) error {
if !validIdentifier(recordID, 1, 128) {
return errors.New("阿里云记录编号无效")
}
var response struct {
Code string `json:"Code"`
Message string `json:"Message"`
}
if err := p.call(ctx, "DeleteDomainRecord", url.Values{"RecordId": {recordID}}, &response); err != nil {
return err
}
if response.Code != "" {
return &providerError{Code: response.Code, Message: response.Message}
}
return nil
}
func (p *aliyun) call(ctx context.Context, action string, query url.Values, output any) error {
host := "dns.aliyuncs.com"
base := p.baseURL
if base == "" {
base = "https://" + host
}
parsed, err := url.Parse(base)
if err != nil {
return err
}
if parsed.Host != "" {
host = parsed.Host
}
now := p.now().UTC()
nonceBytes := make([]byte, 16)
if _, err = rand.Read(nonceBytes); err != nil {
return err
}
payloadHash := sha256Hex(nil)
headers := map[string]string{
"host": host,
"x-acs-action": action,
"x-acs-content-sha256": payloadHash,
"x-acs-date": now.Format("2006-01-02T15:04:05Z"),
"x-acs-signature-nonce": hex.EncodeToString(nonceBytes),
"x-acs-version": "2015-01-09",
}
signed := "host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version"
canonicalHeaders := "host:" + headers["host"] + "\n" + "x-acs-action:" + headers["x-acs-action"] + "\n" + "x-acs-content-sha256:" + headers["x-acs-content-sha256"] + "\n" + "x-acs-date:" + headers["x-acs-date"] + "\n" + "x-acs-signature-nonce:" + headers["x-acs-signature-nonce"] + "\n" + "x-acs-version:" + headers["x-acs-version"] + "\n"
canonical := "POST\n/\n" + query.Encode() + "\n" + canonicalHeaders + "\n" + signed + "\n" + payloadHash
stringToSign := "ACS3-HMAC-SHA256\n" + sha256Hex([]byte(canonical))
signature := hmacHex([]byte(p.accessKeySecret), stringToSign)
parsed.RawQuery = query.Encode()
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), http.NoBody)
if err != nil {
return err
}
for name, value := range headers {
request.Header.Set(name, value)
}
request.Header.Set("Authorization", "ACS3-HMAC-SHA256 Credential="+p.accessKeyID+",SignedHeaders="+signed+",Signature="+signature)
return doJSON(p.client, request, output)
}
type tencent struct {
client *http.Client
secretID, secretKey string
zone, baseURL string
now func() time.Time
}
func (p *tencent) Present(ctx context.Context, fqdn, value string) (string, error) {
return p.CreateRecord(ctx, fqdn, "TXT", value)
}
func (p *tencent) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
if err := validateRecord(recordType, value); err != nil {
return "", err
}
rr, err := relativeRecordName(fqdn, p.zone)
if err != nil {
return "", err
}
var response struct {
Response struct {
RecordID uint64 `json:"RecordId"`
Error *providerError `json:"Error"`
} `json:"Response"`
}
err = p.call(ctx, "CreateRecord", map[string]any{"Domain": p.zone, "SubDomain": rr, "RecordType": recordType, "RecordLine": "默认", "Value": value, "TTL": 600}, &response)
if err != nil {
return "", err
}
if response.Response.Error != nil {
return "", response.Response.Error
}
if response.Response.RecordID == 0 {
return "", errors.New("腾讯云未返回记录编号")
}
return strconv.FormatUint(response.Response.RecordID, 10), nil
}
func (p *tencent) Cleanup(ctx context.Context, recordID string) error {
id, err := strconv.ParseUint(recordID, 10, 64)
if err != nil || id == 0 {
return errors.New("腾讯云记录编号无效")
}
var response struct {
Response struct {
Error *providerError `json:"Error"`
} `json:"Response"`
}
if err = p.call(ctx, "DeleteRecord", map[string]any{"Domain": p.zone, "RecordId": id}, &response); err != nil {
return err
}
if response.Response.Error != nil {
return response.Response.Error
}
return nil
}
func (p *tencent) call(ctx context.Context, action string, input any, output any) error {
payload, err := json.Marshal(input)
if err != nil {
return err
}
host := "dnspod.tencentcloudapi.com"
endpoint := p.baseURL
if endpoint == "" {
endpoint = "https://" + host
}
parsed, err := url.Parse(endpoint)
if err != nil {
return err
}
if parsed.Host != "" {
host = parsed.Host
}
now := p.now().UTC()
timestamp := strconv.FormatInt(now.Unix(), 10)
contentType := "application/json; charset=utf-8"
canonicalHeaders := "content-type:" + contentType + "\n" + "host:" + host + "\n" + "x-tc-action:" + strings.ToLower(action) + "\n"
signedHeaders := "content-type;host;x-tc-action"
canonical := "POST\n/\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + sha256Hex(payload)
date := now.Format("2006-01-02")
scope := date + "/dnspod/tc3_request"
stringToSign := "TC3-HMAC-SHA256\n" + timestamp + "\n" + scope + "\n" + sha256Hex([]byte(canonical))
secretDate := hmacBytes([]byte("TC3"+p.secretKey), date)
secretService := hmacBytes(secretDate, "dnspod")
secretSigning := hmacBytes(secretService, "tc3_request")
signature := hmacHex(secretSigning, stringToSign)
authorization := "TC3-HMAC-SHA256 Credential=" + p.secretID + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), bytes.NewReader(payload))
if err != nil {
return err
}
request.Header.Set("Authorization", authorization)
request.Header.Set("Content-Type", contentType)
request.Header.Set("X-TC-Action", action)
request.Header.Set("X-TC-Timestamp", timestamp)
request.Header.Set("X-TC-Version", "2021-03-23")
return doJSON(p.client, request, output)
}
type providerError struct{ Code, Message string }
func (e *providerError) Error() string {
if e == nil {
return ""
}
if e.Code == "" {
return "DNS 服务商拒绝请求"
}
return "DNS 服务商返回错误 " + e.Code
}
func doJSON(client *http.Client, request *http.Request, output any) error {
response, err := client.Do(request)
if err != nil {
return errors.New("无法连接 DNS 服务商")
}
defer response.Body.Close()
body, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1))
if err != nil {
return errors.New("读取 DNS 服务商响应失败")
}
if len(body) > maxResponseBytes {
return errors.New("DNS 服务商响应过大")
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("DNS 服务商返回 HTTP %d", response.StatusCode)
}
if err = json.Unmarshal(body, output); err != nil {
return errors.New("DNS 服务商响应格式无效")
}
return nil
}
func sha256Hex(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
func hmacBytes(key []byte, value string) []byte {
mac := hmac.New(sha256.New, key)
_, _ = mac.Write([]byte(value))
return mac.Sum(nil)
}
func hmacHex(key []byte, value string) string { return hex.EncodeToString(hmacBytes(key, value)) }
func validateRecord(recordType, value string) error {
recordType = strings.ToUpper(strings.TrimSpace(recordType))
value = strings.TrimSpace(value)
if recordType != "TXT" && recordType != "A" && recordType != "AAAA" && recordType != "CNAME" {
return errors.New("DNS record type is not supported")
}
if value == "" || len(value) > 1024 || strings.ContainsAny(value, "\r\n\x00") {
return errors.New("DNS record value is invalid")
}
if recordType == "A" && net.ParseIP(value).To4() == nil {
return errors.New("DNS A record requires IPv4")
}
if recordType == "AAAA" {
ip := net.ParseIP(value)
if ip == nil || ip.To4() != nil {
return errors.New("DNS AAAA record requires IPv6")
}
}
if recordType == "CNAME" && !brokerCompatibleDomainValue(value) {
return errors.New("DNS CNAME value is invalid")
}
return nil
}
func brokerCompatibleDomainValue(value string) bool {
value = strings.ToLower(strings.TrimSuffix(value, "."))
if len(value) < 3 || len(value) > 253 || strings.ContainsAny(value, " /\\:\t") {
return false
}
return strings.Contains(value, ".")
}
@@ -0,0 +1,155 @@
package dnsprovider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestRelativeRecordName(t *testing.T) {
name, err := relativeRecordName("_acme-challenge.app.example.com", "example.com")
if err != nil || name != "_acme-challenge.app" {
t.Fatalf("name=%q err=%v", name, err)
}
if _, err = relativeRecordName("_acme-challenge.evil.example", "example.com"); err == nil {
t.Fatal("expected zone boundary error")
}
}
func TestAliyunCleanupDoesNotTreatProviderRejectionAsSuccess(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"Code":"Forbidden","Message":"denied"}`))
}))
defer server.Close()
provider := &aliyun{client: server.Client(), accessKeyID: "test", accessKeySecret: "test", zone: "example.com", baseURL: server.URL, now: time.Now}
if err := provider.Cleanup(context.Background(), "record_123"); err == nil {
t.Fatal("provider rejection treated as successful deletion")
}
}
func TestCloudflarePresentAndCleanup(t *testing.T) {
var created bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 24) {
t.Error("missing bearer token")
}
switch r.Method {
case http.MethodPost:
created = true
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["name"] != "_acme-challenge.example.com" || body["type"] != "TXT" {
t.Errorf("unexpected body: %#v", body)
}
_, _ = w.Write([]byte(`{"success":true,"result":{"id":"record_123"}}`))
case http.MethodDelete:
if !created || !strings.HasSuffix(r.URL.Path, "/record_123") {
t.Errorf("unexpected cleanup path: %s", r.URL.Path)
}
_, _ = w.Write([]byte(`{"success":true}`))
}
}))
defer server.Close()
provider := &cloudflare{client: server.Client(), token: strings.Repeat("t", 24), zoneID: "zone_123456", baseURL: server.URL}
recordID, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof")
if err != nil || recordID != "record_123" {
t.Fatalf("record=%q err=%v", recordID, err)
}
if err = provider.Cleanup(context.Background(), recordID); err != nil {
t.Fatal(err)
}
}
func TestCloudflareCreatesCNAMEWithoutProxying(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["name"] != "app.example.com" || body["type"] != "CNAME" || body["content"] != "target.vhost.example" || body["proxied"] != false {
t.Errorf("unexpected body: %#v", body)
}
_, _ = w.Write([]byte(`{"success":true,"result":{"id":"cname_123"}}`))
}))
defer server.Close()
provider := &cloudflare{client: server.Client(), token: strings.Repeat("t", 24), zoneID: "zone_123456", baseURL: server.URL}
recordID, err := provider.CreateRecord(context.Background(), "app.example.com", "CNAME", "target.vhost.example")
if err != nil || recordID != "cname_123" {
t.Fatalf("record=%q err=%v", recordID, err)
}
}
func TestValidateRecordRejectsInvalidAddressAndCNAME(t *testing.T) {
for _, input := range []struct{ recordType, value string }{{"A", "2001:db8::1"}, {"AAAA", "192.0.2.1"}, {"CNAME", "not-a-domain"}, {"MX", "mail.example.com"}} {
if err := validateRecord(input.recordType, input.value); err == nil {
t.Fatalf("accepted invalid %s value %q", input.recordType, input.value)
}
}
}
func TestAliyunSignedRequests(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.Header.Get("Authorization"), "ACS3-HMAC-SHA256 Credential=accessKey123") {
t.Error("missing Aliyun V3 signature")
}
switch r.Header.Get("x-acs-action") {
case "AddDomainRecord":
if r.URL.Query().Get("RR") != "_acme-challenge.app" || r.URL.Query().Get("DomainName") != "example.com" {
t.Errorf("unexpected query: %s", r.URL.RawQuery)
}
_, _ = w.Write([]byte(`{"RecordId":"9988"}`))
case "DeleteDomainRecord":
if r.URL.Query().Get("RecordId") != "9988" {
t.Errorf("unexpected record id")
}
_, _ = w.Write([]byte(`{"RequestId":"ok"}`))
default:
t.Errorf("unexpected action")
}
}))
defer server.Close()
provider := &aliyun{client: server.Client(), accessKeyID: "accessKey123", accessKeySecret: strings.Repeat("s", 20), zone: "example.com", baseURL: server.URL, now: func() time.Time { return time.Unix(1700000000, 0) }}
recordID, err := provider.Present(context.Background(), "_acme-challenge.app.example.com", "proof")
if err != nil || recordID != "9988" {
t.Fatalf("record=%q err=%v", recordID, err)
}
if err = provider.Cleanup(context.Background(), recordID); err != nil {
t.Fatal(err)
}
}
func TestTencentSignedRequests(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.Header.Get("Authorization"), "TC3-HMAC-SHA256 Credential=secretId123/") {
t.Error("missing Tencent V3 signature")
}
switch r.Header.Get("X-Tc-Action") {
case "CreateRecord":
_, _ = w.Write([]byte(`{"Response":{"RecordId":7788,"RequestId":"ok"}}`))
case "DeleteRecord":
_, _ = w.Write([]byte(`{"Response":{"RequestId":"ok"}}`))
default:
t.Errorf("unexpected action %q", r.Header.Get("X-Tc-Action"))
}
}))
defer server.Close()
provider := &tencent{client: server.Client(), secretID: "secretId123", secretKey: strings.Repeat("k", 20), zone: "example.com", baseURL: server.URL, now: func() time.Time { return time.Unix(1700000000, 0) }}
recordID, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof")
if err != nil || recordID != "7788" {
t.Fatalf("record=%q err=%v", recordID, err)
}
if err = provider.Cleanup(context.Background(), recordID); err != nil {
t.Fatal(err)
}
}
func TestValidateRejectsUnknownProviderAndHeaderInjection(t *testing.T) {
if err := Validate("unknown", Credential{}); err == nil {
t.Fatal("expected provider error")
}
if err := Validate("cloudflare", Credential{ZoneID: "zone_123456", APIToken: strings.Repeat("x", 20) + "\n"}); err == nil {
t.Fatal("expected secret validation error")
}
}
@@ -0,0 +1,62 @@
package dnsprovider
import (
"context"
"errors"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"time"
)
func publicEndpoint(raw string) (*url.URL, error) {
u, e := url.Parse(raw)
if e != nil || len(raw) > 512 || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") || strings.ContainsAny(raw, "\r\n\x00") || strings.ContainsAny(u.Path, "?#\\") || strings.EqualFold(u.Hostname(), "localhost") {
return nil, errors.New("DNS API 地址必须为 HTTPS 公网地址,端口为 443,不能包含查询参数或身份信息")
}
if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicIP(ip) {
return nil, errors.New("DNS API 禁止访问内网或保留地址")
}
return u, nil
}
func publicIP(ip netip.Addr) bool {
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return false
}
for _, v := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "::/96", "64:ff9b::/96", "64:ff9b:1::/48", "2001:db8::/32", "2001::/32", "2002::/16"} {
if netip.MustParsePrefix(v).Contains(ip) {
return false
}
}
return true
}
func publicClient() *http.Client {
transport := &http.Transport{Proxy: nil, TLSHandshakeTimeout: 8 * time.Second, ResponseHeaderTimeout: 15 * time.Second, MaxIdleConnsPerHost: 2, IdleConnTimeout: 20 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, e := net.SplitHostPort(address)
if e != nil || port != "443" {
return nil, errors.New("restricted DNS endpoint")
}
ips, e := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
if e != nil || len(ips) == 0 {
return nil, errors.New("DNS API 域名无法解析")
}
for _, ip := range ips {
if !publicIP(ip) {
return nil, errors.New("DNS API 域名解析到受限地址")
}
}
var last error
for _, ip := range ips {
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), port))
if e == nil {
return conn, nil
}
last = e
}
return nil, last
}}
return &http.Client{Transport: transport, Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
}
+167
View File
@@ -0,0 +1,167 @@
package dnsprovider
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type west struct {
client *http.Client
zone, baseURL string
credential Credential
now func() time.Time
}
func (p *west) call(ctx context.Context, action string, v url.Values, out any) error {
base := p.baseURL
if base == "" {
base = "https://api.west.cn/API/v2"
}
endpoint := base + "/domain/"
v.Set("act", action)
if p.credential.DomainKey != "" {
endpoint += "dns/"
v.Set("apidomainkey", p.credential.DomainKey)
} else {
stamp := strconv.FormatInt(p.now().UnixMilli(), 10)
v.Set("username", p.credential.Username)
v.Set("time", stamp)
v.Set("token", md5Hex(p.credential.Username+p.credential.APIKey+stamp))
}
req, e := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(v.Encode()))
if e != nil {
return e
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var response struct {
Result int `json:"result"`
Data json.RawMessage `json:"data"`
}
if e = doJSON(p.client, req, &response); e != nil {
return e
}
if response.Result != 200 {
return errors.New("西部数码拒绝请求,请检查 API 密码、单域名密钥或白名单")
}
if out == nil {
return nil
}
return json.Unmarshal(response.Data, out)
}
func (p *west) Present(ctx context.Context, fqdn, value string) (string, error) {
return p.CreateRecord(ctx, fqdn, "TXT", value)
}
type westRecord struct {
ID json.RawMessage `json:"record_id"`
Hostname string `json:"hostname"`
Type string `json:"record_type"`
Value string `json:"record_value"`
}
func (p *west) modernRecords(ctx context.Context, fqdn, kind string) ([]westRecord, error) {
var data json.RawMessage
if e := p.call(ctx, "dnsrec.list", url.Values{"domain": {p.zone}, "hostname": {fqdn}, "record_type": {kind}}, &data); e != nil {
return nil, e
}
var list []westRecord
if json.Unmarshal(data, &list) == nil {
return list, nil
}
var wrapped struct {
Items []westRecord `json:"items"`
List []westRecord `json:"list"`
Records []westRecord `json:"records"`
}
if json.Unmarshal(data, &wrapped) != nil {
return nil, errors.New("西部数码记录响应无效")
}
if wrapped.Items != nil {
return wrapped.Items, nil
}
if wrapped.List != nil {
return wrapped.List, nil
}
if wrapped.Records != nil {
return wrapped.Records, nil
}
return nil, errors.New("西部数码未返回解析记录列表")
}
func (p *west) CreateRecord(ctx context.Context, fqdn, kind, value string) (string, error) {
if e := validateRecord(kind, value); e != nil {
return "", e
}
rr, e := relativeRecordName(fqdn, p.zone)
if e != nil {
return "", e
}
if p.credential.DomainKey == "" {
var out struct {
ID json.RawMessage `json:"id"`
}
if e = p.call(ctx, "adddnsrecord", url.Values{"domain": {p.zone}, "host": {rr}, "type": {kind}, "value": {value}, "ttl": {"600"}, "line": {""}}, &out); e != nil {
return "", e
}
id := rawID(out.ID)
if !validIdentifier(id, 1, 128) {
return "", errors.New("西部数码未返回新增记录编号")
}
return id, nil
}
before, e := p.modernRecords(ctx, fqdn, kind)
if e != nil {
return "", e
}
old := map[string]bool{}
for _, r := range before {
old[rawID(r.ID)] = true
}
if e = p.call(ctx, "dnsrec.add", url.Values{"domain": {p.zone}, "hostname": {fqdn}, "record_type": {kind}, "record_value": {value}, "ttl": {"600"}}, nil); e != nil {
return "", e
}
after, e := p.modernRecords(ctx, fqdn, kind)
if e != nil {
return "", e
}
for _, r := range after {
id := rawID(r.ID)
if !old[id] && validIdentifier(id, 1, 128) && r.Hostname == fqdn && r.Type == kind && r.Value == value {
return base64.RawURLEncoding.EncodeToString([]byte(fqdn + "|" + id)), nil
}
}
return "", errors.New("西部数码已接受创建,但未能核对新增记录编号,请管理员核验")
}
func (p *west) Cleanup(ctx context.Context, id string) error {
v := url.Values{"domain": {p.zone}}
action := "deldnsrecord"
if p.credential.DomainKey != "" {
raw, e := base64.RawURLEncoding.DecodeString(id)
if e != nil {
return errors.New("西部数码记录标识无效")
}
parts := strings.Split(string(raw), "|")
if len(parts) != 2 {
return errors.New("西部数码记录标识无效")
}
if _, e = relativeRecordName(parts[0], p.zone); e != nil {
return e
}
id = parts[1]
action = "dnsrec.remove"
v.Set("hostname", parts[0])
v.Set("record_id", id)
} else {
v.Set("id", id)
}
if !validIdentifier(id, 1, 128) {
return errors.New("西部数码记录编号无效")
}
return p.call(ctx, action, v, nil)
}
+174
View File
@@ -0,0 +1,174 @@
package dnsprovider
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type Zone struct {
ID string `json:"id"`
Name string `json:"name"`
}
func DiscoverZones(ctx context.Context, name string, c Credential, hint string) ([]Zone, error) {
if name == "cloudflare" && c.ZoneID == "" {
c.ZoneID = "discovery"
}
provider, err := New(name, hint, c)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 40*time.Second)
defer cancel()
all := []Zone{}
for page := 1; page <= 20; page++ {
total := 0
switch p := provider.(type) {
case *cloudflare:
var out struct {
Success bool `json:"success"`
Result []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"result"`
Info struct {
TotalCount int `json:"total_count"`
} `json:"result_info"`
}
req, e := http.NewRequestWithContext(ctx, "GET", "https://api.cloudflare.com/client/v4/zones?per_page=100&page="+strconv.Itoa(page), nil)
if e != nil {
return nil, e
}
req.Header.Set("Authorization", "Bearer "+c.APIToken)
if e = doJSON(p.client, req, &out); e != nil {
return nil, e
}
if !out.Success {
return nil, errors.New("Cloudflare 未授权读取 DNS 区域")
}
for _, z := range out.Result {
all = append(all, Zone{z.ID, z.Name})
}
total = out.Info.TotalCount
case *aliyun:
var out struct {
Code string `json:"Code"`
TotalCount int `json:"TotalCount"`
Domains struct {
Domain []struct {
Name string `json:"DomainName"`
} `json:"Domain"`
} `json:"Domains"`
}
if e := p.call(ctx, "DescribeDomains", url.Values{"PageNumber": {strconv.Itoa(page)}, "PageSize": {"100"}}, &out); e != nil {
return nil, e
}
if out.Code != "" {
return nil, errors.New("阿里云未授权读取域名列表")
}
for _, z := range out.Domains.Domain {
all = append(all, Zone{z.Name, z.Name})
}
total = out.TotalCount
case *tencent:
var out struct {
Response struct {
Error *providerError `json:"Error"`
Count int `json:"DomainCountInfoAll"`
DomainCount struct {
All int `json:"AllTotal"`
} `json:"DomainCountInfo"`
Domains []struct {
ID uint64 `json:"DomainId"`
Name string `json:"Name"`
} `json:"DomainList"`
} `json:"Response"`
}
if e := p.call(ctx, "DescribeDomainList", map[string]any{"Offset": (page - 1) * 100, "Limit": 100}, &out); e != nil {
return nil, e
}
if out.Response.Error != nil {
return nil, out.Response.Error
}
for _, z := range out.Response.Domains {
all = append(all, Zone{strconv.FormatUint(z.ID, 10), z.Name})
}
total = out.Response.DomainCount.All
case *west:
if c.DomainKey != "" {
if hint == "" {
return nil, errors.New("单域名密钥请先填写指定域名")
}
if _, e := p.modernRecords(ctx, hint, "TXT"); e != nil {
return nil, e
}
return []Zone{{hint, hint}}, nil
}
var out struct {
Total int `json:"total"`
Items []struct {
Domain string `json:"domain"`
} `json:"items"`
}
if e := p.call(ctx, "getdomains", url.Values{"page": {strconv.Itoa(page)}, "limit": {"100"}}, &out); e != nil {
return nil, e
}
for _, z := range out.Items {
all = append(all, Zone{z.Domain, z.Domain})
}
total = out.Total
case *dnsmgr:
var out struct {
Total *int `json:"total"`
Rows []struct {
ID jsonID `json:"id"`
Name string `json:"name"`
} `json:"rows"`
}
if e := p.call(ctx, "domain", url.Values{"offset": {strconv.Itoa((page - 1) * 100)}, "limit": {"100"}}, &out); e != nil {
return nil, e
}
if out.Total == nil {
return nil, errors.New("彩虹 DNS 未返回域名列表")
}
for _, z := range out.Rows {
all = append(all, Zone{string(z.ID), z.Name})
}
total = *out.Total
default:
return nil, errors.New("服务商不支持读取区域列表")
}
if len(all) >= total {
return normalizeZones(all), nil
}
}
return nil, errors.New("域名数量超过 2000,请使用权限更小的 API 票据")
}
type jsonID string
func (v *jsonID) UnmarshalJSON(raw []byte) error {
id := rawID(raw)
if !positiveID(id) {
return errors.New("域名编号无效")
}
*v = jsonID(id)
return nil
}
func normalizeZones(items []Zone) []Zone {
out := []Zone{}
seen := map[string]bool{}
for _, z := range items {
z.Name = strings.ToLower(strings.TrimSuffix(z.Name, "."))
if z.ID != "" && z.Name != "" && !seen[z.Name] {
out = append(out, z)
seen[z.Name] = true
}
}
return out
}
+182
View File
@@ -0,0 +1,182 @@
// Package executor is the node-side execution surface. It intentionally has
// no import of store/service/httpapi and cannot schedule control-plane work.
package executor
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/nodefiles"
"sea-vhost/internal/panel"
)
type Gateway struct {
NodeID uint64
TenantRoot string
BrokerSocket string
AgentSocket string
InternalToken string
// Direct is reserved for in-process tests; deployment always uses the
// independent, unprivileged credential broker over a Unix socket.
Direct panel.Interface
mu sync.Mutex
fileGate sync.Mutex
}
var nodeHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`)
var agentRoutes = map[string]bool{
"/v1/database/phpmyadmin":true,
"/v1/scheduler/configure":true,
"/v1/schedule/execute":true,
"/v1/ftp/disconnect":true,
"/v1/site/startup": true,
"/v1/site/settings": true, "/v1/site/log": true,
"/v1/runtime/backups/prune": true,
"/v1/prepare": true, "/v1/quarantine": true, "/v1/web-protection/apply": true, "/v1/web-protection/remove": true,
"/v1/runtime/executable": true, "/v1/runtime/panel-state": true, "/v1/runtime/python/install": true,
"/v1/resources/runtime/terminate": true, "/v1/run-path/release": true, "/v1/trash/prepare": true,
"/v1/ftp/identity": true, "/v1/php/identity": true, "/v1/php/identity/start": true, "/v1/php/identity/stop": true, "/v1/php/identity/remove": true,
"/v1/resources/usage": true, "/v1/resources/processes/terminate": true, "/v1/project/freeze-writes": true, "/v1/ftp/tls": true, "/v1/nginx/network": true,
"/v1/lifecycle/backup": true, "/v1/lifecycle/backup/delete": true, "/v1/lifecycle/project/purge": true, "/v1/import/project": true,
"/v1/database/access": true,
"/v1/credentials/disconnect": true,
"/v1/resources/limits": true,
"/v1/lifecycle/backup/verify": true,
"/v1/runtime/probe": true, "/v1/runtime/php/maintenance": true, "/v1/runtime/python/dependencies": true,
}
func (g *Gateway) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) {
controlwire.Encode(w, 200, map[string]any{"nodeId": g.NodeID, "protocol": controlwire.Version, "businessDatabase": false, "taskScheduler": false})
})
mux.HandleFunc("POST /v1/panel", g.panel)
mux.HandleFunc("POST /v1/files", g.files)
mux.HandleFunc("POST /v1/isolation/", g.isolation)
return controlwire.Authenticated(g.NodeID, mux)
}
func (g *Gateway) files(w http.ResponseWriter, r *http.Request) {
if !g.fileGate.TryLock() {
http.Error(w, "node file transfer busy", 429)
return
}
defer g.fileGate.Unlock()
var q nodefiles.Request
r.Body = http.MaxBytesReader(w, r.Body, nodefiles.MaxMessageBytes)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&q) != nil || decoder.Decode(&struct{}{}) != io.EOF || !nodeHostPattern.MatchString(q.HostName) {
http.Error(w, "invalid host file request", 400)
return
}
controlwire.Encode(w, 200, nodefiles.Execute(filepath.Join(g.TenantRoot, q.HostName), q))
}
func (g *Gateway) panel(w http.ResponseWriter, r *http.Request) {
var input panel.ScopedExecution
if controlwire.Decode(w, r, &input) != nil {
http.Error(w, "invalid scoped panel request", 400)
return
}
g.mu.Lock()
defer g.mu.Unlock()
if g.Direct != nil {
result, err := panel.ExecuteScoped(r.Context(), g.Direct, g.TenantRoot, input)
if err != nil {
http.Error(w, err.Error(), 422)
return
}
controlwire.Encode(w, 200, result)
return
}
body, err := json.Marshal(input)
if err != nil {
http.Error(w, "invalid request", 400)
return
}
g.forward(w, r, g.BrokerSocket, "/v1/scoped-operations", body)
}
func (g *Gateway) isolation(w http.ResponseWriter, r *http.Request) {
route := strings.TrimPrefix(r.URL.Path, "/v1/isolation")
if !agentRoutes[route] {
http.Error(w, "operation is not in the node allowlist", 403)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, controlwire.MaxEnvelopeBytes+1))
if err != nil || len(body) > controlwire.MaxEnvelopeBytes {
http.Error(w, "invalid node payload", 413)
return
}
var value any
if json.Unmarshal(body, &value) != nil || !validHostIdentities(value) {
http.Error(w, "invalid node host scope", 400)
return
}
g.forward(w, r, g.AgentSocket, route, body)
}
func validHostIdentities(value any) bool {
switch v := value.(type) {
case map[string]any:
for key, item := range v {
if strings.EqualFold(key, "hostName") {
name, ok := item.(string)
if !ok || !nodeHostPattern.MatchString(name) {
return false
}
}
if !validHostIdentities(item) {
return false
}
}
case []any:
for _, item := range v {
if !validHostIdentities(item) {
return false
}
}
}
return true
}
func (g *Gateway) forward(w http.ResponseWriter, r *http.Request, socket, route string, body []byte) {
if socket == "" || g.InternalToken == "" {
http.Error(w, "node execution service is not configured", 503)
return
}
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}}
defer transport.CloseIdleConnections()
req, err := http.NewRequestWithContext(r.Context(), "POST", "http://unix"+route, bytes.NewReader(body))
if err != nil {
http.Error(w, "invalid local operation", 400)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+g.InternalToken)
response, err := (&http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect denied") }}).Do(req)
if err != nil {
http.Error(w, "node local execution service unavailable", 502)
return
}
defer response.Body.Close()
output, err := io.ReadAll(io.LimitReader(response.Body, controlwire.MaxEnvelopeBytes+1))
if err != nil || len(output) > controlwire.MaxEnvelopeBytes {
http.Error(w, "node execution response exceeded limit", 502)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(response.StatusCode)
_, _ = w.Write(output)
}
+178
View File
@@ -0,0 +1,178 @@
package executor_test
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/executor"
"sea-vhost/internal/nodefiles"
"sea-vhost/internal/panel"
"strings"
"testing"
"time"
)
type testNode struct {
server *httptest.Server
client *http.Client
id uint64
credentials controlwire.Credentials
sequence int
}
func startNode(t *testing.T, id uint64, root string) *testNode {
t.Helper()
g := &executor.Gateway{NodeID: id, TenantRoot: root, Direct: panel.NewMock()}
s := httptest.NewUnstartedServer(g.Handler())
s.Config.ErrorLog = log.New(io.Discard, "", 0)
credentials, identity, err := controlwire.Pair(id, "https://"+s.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
s.TLS, err = controlwire.ServerTLS(identity)
if err != nil {
t.Fatal(err)
}
s.StartTLS()
t.Cleanup(s.Close)
config, err := controlwire.ClientTLS(credentials)
if err != nil {
t.Fatal(err)
}
client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}, Timeout: 10 * time.Second}
t.Cleanup(client.CloseIdleConnections)
return &testNode{server: s, client: client, id: id, credentials: credentials}
}
func (n *testNode) request(t *testing.T, route string, body any) (int, []byte) {
t.Helper()
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
n.sequence++
r, err := controlwire.NewRequest("POST", n.server.URL, route, n.id, fmt.Sprintf("%032x", n.sequence), raw)
if err != nil {
t.Fatal(err)
}
response, err := n.client.Do(r)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
out, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
return response.StatusCode, out
}
func TestTwoNodesArePairedAndStateless(t *testing.T) {
rootA := filepath.ToSlash(t.TempDir())
rootB := filepath.ToSlash(t.TempDir())
for _, root := range []string{rootA, rootB} {
if err := os.Mkdir(filepath.Join(root, "sv0123456789"), 0750); err != nil {
t.Fatal(err)
}
}
a := startNode(t, 2, rootA)
b := startNode(t, 3, rootB)
empty := json.RawMessage(`{"version":1,"sites":{},"ftp":{},"databases":{}}`)
create := func(n *testNode, root, domain string) panel.ScopedResult {
t.Helper()
request, _ := json.Marshal(map[string]any{"operation": "create_site", "site": panel.SiteSpec{Name: "sv0123456789", Domain: domain, Path: root + "/sv0123456789", RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: "sv0123456789", Port: 20000, ProcessLimit: 10}})
status, raw := n.request(t, "/v1/panel", panel.ScopedExecution{Request: request, Registry: empty})
if status != 200 {
t.Fatalf("create: %d %s", status, raw)
}
var out panel.ScopedResult
if json.Unmarshal(raw, &out) != nil {
t.Fatal("invalid scoped result")
}
return out
}
first := create(a, rootA, "sv0123456789.a.example.com")
second := create(b, rootB, "sv0123456789.b.example.com")
if string(first.Response) != string(second.Response) {
t.Fatalf("expected colliding native IDs across nodes: %s %s", first.Response, second.Response)
}
req, _ := json.Marshal(map[string]any{"operation": "set_site_state", "id": 1001, "name": "sv0123456789.a.example.com", "enabled": false})
status, _ := b.request(t, "/v1/panel", panel.ScopedExecution{Request: req, Registry: first.Registry})
if status == 200 {
t.Fatal("node B accepted node A root snapshot")
}
status, _ = a.request(t, "/v1/panel", panel.ScopedExecution{Request: req, Registry: empty})
if status == 200 {
t.Fatal("node persisted the previous request registry")
}
status, _ = a.request(t, "/v1/isolation/v1/shell", map[string]any{"command": "id"})
if status != 403 {
t.Fatalf("shell route: %d", status)
}
status, _ = a.request(t, "/v1/isolation/v1/prepare", map[string]any{"hostName": "root"})
if status != 400 {
t.Fatalf("root identity: %d", status)
}
r, _ := controlwire.NewRequest("GET", b.server.URL, "/v1/status", b.id, strings.Repeat("a", 32), nil)
if response, err := a.client.Do(r); err == nil {
response.Body.Close()
t.Fatal("node A credentials authenticated to node B")
}
r, _ = controlwire.NewRequest("GET", a.server.URL, "/v1/status", b.id, strings.Repeat("b", 32), nil)
response, err := a.client.Do(r)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
if response.StatusCode != 403 {
t.Fatal("destination identity not checked")
}
}
func TestFilesStayOnTargetNodeAndRejectReplay(t *testing.T) {
rootA := t.TempDir()
rootB := t.TempDir()
host := "sv0123456789"
for _, root := range []string{rootA, rootB} {
if err := os.Mkdir(filepath.Join(root, host), 0750); err != nil {
t.Fatal(err)
}
}
a := startNode(t, 2, rootA)
b := startNode(t, 3, rootB)
status, raw := a.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "write", Path: "marker.txt", Data: []byte("node-A-only")})
if status != 200 {
t.Fatalf("write %d %s", status, raw)
}
status, raw = b.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "read", Path: "marker.txt"})
if status != 200 || !strings.Contains(string(raw), "not_found") {
t.Fatalf("cross-node read: %d %s", status, raw)
}
for _, name := range []string{"../marker.txt", "/etc/passwd", "a/../../x", "x\\..\\y"} {
_, raw = a.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "read", Path: name})
if !strings.Contains(string(raw), "denied") {
t.Fatalf("unsafe path accepted %q: %s", name, raw)
}
}
body, _ := json.Marshal(nodefiles.Request{HostName: host, Operation: "stat", Path: "marker.txt"})
r, _ := controlwire.NewRequest("POST", a.server.URL, "/v1/files", 2, strings.Repeat("e", 32), body)
response, err := a.client.Do(r)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
r, _ = controlwire.NewRequest("POST", a.server.URL, "/v1/files", 2, strings.Repeat("e", 32), body)
response, err = a.client.Do(r)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
if response.StatusCode != 409 {
t.Fatalf("replay accepted: %d", response.StatusCode)
}
}
+151
View File
@@ -0,0 +1,151 @@
package files
import (
"errors"
"os"
pathpkg "path"
"path/filepath"
"strings"
)
var ErrOutsideRoot = errors.New("path escapes project root")
var ErrNotRegular = errors.New("path is not a regular file")
func Resolve(root, requested string) (string, error) {
rootAbs, err := filepath.Abs(root)
if err != nil {
return "", err
}
if strings.ContainsRune(requested, '\x00') || strings.Contains(requested, "\\") || strings.HasPrefix(requested, "/") {
return "", ErrOutsideRoot
}
cleanRequested := pathpkg.Clean(requested)
if requested == "" {
cleanRequested = "."
} else if cleanRequested != requested {
return "", ErrOutsideRoot
}
for _, part := range strings.Split(cleanRequested, "/") {
if part == ".." {
return "", ErrOutsideRoot
}
}
candidate := filepath.Join(rootAbs, filepath.FromSlash(cleanRequested))
candidateAbs, err := filepath.Abs(candidate)
if err != nil {
return "", err
}
relative, err := filepath.Rel(rootAbs, candidateAbs)
if err != nil {
return "", err
}
if relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) {
return "", ErrOutsideRoot
}
return candidateAbs, nil
}
// RejectSymlinks prevents an existing path component from redirecting an operation outside the tenant root.
func RejectSymlinks(root, target string) error {
rootAbs, err := filepath.Abs(root)
if err != nil {
return err
}
targetAbs, err := filepath.Abs(target)
if err != nil {
return err
}
rel, err := filepath.Rel(rootAbs, targetAbs)
if err != nil {
return err
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
return ErrOutsideRoot
}
current := rootAbs
for _, part := range strings.Split(rel, string(os.PathSeparator)) {
if part == "." || part == "" {
continue
}
current = filepath.Join(current, part)
info, statErr := os.Lstat(current)
if os.IsNotExist(statErr) {
return nil
}
if statErr != nil {
return statErr
}
if info.Mode()&os.ModeSymlink != 0 {
return ErrOutsideRoot
}
}
return nil
}
// InspectRegular opens a file through os.Root after rejecting every symlink in
// its path. Deployment checks use this instead of os.Stat so an uploaded link
// can never redirect a privileged panel operation outside the virtual host.
func InspectRegular(root, requested string) (os.FileInfo, error) {
target, err := Resolve(root, requested)
if err != nil {
return nil, err
}
if err = RejectSymlinks(root, target); err != nil {
return nil, err
}
relative, err := filepath.Rel(root, target)
if err != nil {
return nil, err
}
projectRoot, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer projectRoot.Close()
file, err := projectRoot.Open(relative)
if err != nil {
return nil, err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() {
return nil, ErrNotRegular
}
return info, nil
}
// EnsureDirectory creates one final directory below an already prepared
// project path using os.Root. It is used for aaPanel compatibility shims, not
// arbitrary tenant path creation, and refuses links or non-directory targets.
func EnsureDirectory(root, requested string, mode os.FileMode) error {
target, err := Resolve(root, requested)
if err != nil {
return err
}
if err = RejectSymlinks(root, target); err != nil {
return err
}
relative, err := filepath.Rel(root, target)
if err != nil || relative == "." {
return ErrOutsideRoot
}
projectRoot, err := os.OpenRoot(root)
if err != nil {
return err
}
defer projectRoot.Close()
info, statErr := projectRoot.Lstat(relative)
if statErr == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("path is not a physical directory")
}
return nil
}
if !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
return projectRoot.Mkdir(relative, mode)
}
+72
View File
@@ -0,0 +1,72 @@
package files
import (
"errors"
"os"
"path/filepath"
"testing"
)
func TestResolveBlocksTraversal(t *testing.T) {
root := filepath.Join(t.TempDir(), "project")
for _, requested := range []string{
"../../etc/passwd",
`..\..\secret`,
"/../../outside",
"public/../secret",
"public//index.html",
"public/./index.html",
} {
if _, err := Resolve(root, requested); !errors.Is(err, ErrOutsideRoot) {
t.Errorf("Resolve(%q) error = %v, want ErrOutsideRoot", requested, err)
}
}
}
func TestInspectRegularRejectsDirectoriesAndReadsFiles(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "app"), 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "app", "server.js"), []byte("ok"), 0640); err != nil {
t.Fatal(err)
}
info, err := InspectRegular(root, "app/server.js")
if err != nil || info.Size() != 2 {
t.Fatalf("InspectRegular(file) = %v, %v", info, err)
}
if _, err = InspectRegular(root, "app"); !errors.Is(err, ErrNotRegular) {
t.Fatalf("InspectRegular(directory) error = %v", err)
}
}
func TestResolveNormalizesInsideRoot(t *testing.T) {
root := filepath.Join(t.TempDir(), "project")
got, err := Resolve(root, "public/assets/app.js")
if err != nil {
t.Fatal(err)
}
want := filepath.Join(root, "public", "assets", "app.js")
if got != want {
t.Fatalf("got %q want %q", got, want)
}
}
func TestEnsureDirectoryStaysInsidePhysicalProjectPath(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "app"), 0750); err != nil {
t.Fatal(err)
}
if err := EnsureDirectory(root, "app/node_modules", 0770); err != nil {
t.Fatal(err)
}
if info, err := os.Lstat(filepath.Join(root, "app", "node_modules")); err != nil || !info.IsDir() {
t.Fatalf("compatibility directory was not created: info=%v err=%v", info, err)
}
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(root, "linked")); err == nil {
if err = EnsureDirectory(root, "linked/node_modules", 0770); err == nil {
t.Fatal("EnsureDirectory followed a symlink outside the project root")
}
}
}
+95
View File
@@ -0,0 +1,95 @@
package hosting
import (
"errors"
"strconv"
"strings"
"time"
_ "time/tzdata"
)
type Cron struct {
fields [5]map[int]bool
any [5]bool
location *time.Location
}
func ParseCron(expression, zone string) (Cron, error) {
var c Cron
loc, e := time.LoadLocation(zone)
if e != nil {
return c, errors.New("时区无效")
}
c.location = loc
parts := strings.Fields(expression)
if len(parts) != 5 {
return c, errors.New("计划时间需要五段:分钟 小时 日期 月份 星期")
}
mins := []int{0, 0, 1, 1, 0}
maxs := []int{59, 23, 31, 12, 7}
for i, part := range parts {
c.fields[i] = map[int]bool{}
c.any[i] = strings.HasPrefix(part, "*")
for _, piece := range strings.Split(part, ",") {
step := 1
rangePart := piece
if strings.Contains(piece, "/") {
items := strings.Split(piece, "/")
if len(items) != 2 {
return c, errors.New("计划时间格式无效")
}
rangePart = items[0]
step, e = strconv.Atoi(items[1])
if e != nil || step < 1 || step > 60 {
return c, errors.New("计划间隔无效")
}
}
start, end := mins[i], maxs[i]
if rangePart != "*" {
items := strings.Split(rangePart, "-")
if len(items) > 2 {
return c, errors.New("计划范围无效")
}
start, e = strconv.Atoi(items[0])
if e != nil {
return c, errors.New("计划时间只支持数字、星号、范围和步长")
}
end = start
if len(items) == 2 {
end, e = strconv.Atoi(items[1])
if e != nil {
return c, errors.New("计划范围无效")
}
}
}
if start < mins[i] || end > maxs[i] || start > end {
return c, errors.New("计划时间超出范围")
}
for n := start; n <= end; n += step {
value := n
if i == 4 && n == 7 {
value = 0
}
c.fields[i][value] = true
}
}
}
return c, nil
}
func (c Cron) Next(after time.Time) (time.Time, error) {
t := after.UTC().Truncate(time.Minute).Add(time.Minute)
for i := 0; i < 366*24*60; i++ {
local := t.In(c.location)
day := c.fields[2][local.Day()]
week := c.fields[4][int(local.Weekday())]
matchDay := day && week
if !c.any[2] && !c.any[4] {
matchDay = day || week
}
if c.fields[0][local.Minute()] && c.fields[1][local.Hour()] && c.fields[3][int(local.Month())] && matchDay {
return t, nil
}
t = t.Add(time.Minute)
}
return time.Time{}, errors.New("未来一年没有可执行时间")
}
+12
View File
@@ -0,0 +1,12 @@
package hosting
type RunnerConfig struct {
UID uint32 `json:"uid"`
HostName string `json:"hostName"`
Binary string `json:"binary"`
Arguments []string `json:"arguments"`
Environment map[string]string `json:"environment"`
WorkDir string `json:"workDir"`
LogDir string `json:"logDir"`
SiteName string `json:"siteName"`
}
+94
View File
@@ -0,0 +1,94 @@
package hosting
import (
"encoding/json"
"errors"
"net/url"
"path"
"regexp"
"strings"
)
type WebsiteSettings struct {
Rewrite string `json:"rewrite"`
RedirectURL string `json:"redirectURL"`
RedirectCode int `json:"redirectCode"`
ForceHTTPS bool `json:"forceHTTPS"`
Index []string `json:"index"`
Error404 string `json:"error404"`
Error503 string `json:"error503"`
Maintenance bool `json:"maintenance"`
}
type Startup struct {
EntryFile string `json:"entryFile"`
WorkDir string `json:"workDir"`
Arguments []string `json:"arguments"`
Environment map[string]string `json:"environment"`
}
var simpleFile = regexp.MustCompile(`^[A-Za-z0-9_./-]+$`)
var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,63}$`)
func DefaultWebsite() WebsiteSettings {
return WebsiteSettings{Rewrite: "none", RedirectCode: 301, Index: []string{"index.php", "index.html", "index.htm"}}
}
func ValidRelative(v string) bool {
return v != "" && v != "." && len(v) <= 255 && simpleFile.MatchString(v) && !strings.HasPrefix(v, "/") && path.Clean(v) == v && !strings.HasPrefix(v, "../") && !strings.Contains(v, "/.sea-") && !strings.HasPrefix(v, ".sea-") && path.Base(v) != ".user.ini"
}
func (v *WebsiteSettings) Validate() error {
if !map[string]bool{"none": true, "wordpress": true, "laravel": true, "thinkphp": true, "spa": true}[v.Rewrite] {
return errors.New("伪静态模板无效")
}
if len(v.Index) < 1 || len(v.Index) > 10 {
return errors.New("请设置 1–10 个默认首页")
}
for _, name := range v.Index {
if !ValidRelative(name) || strings.Contains(name, "/") {
return errors.New("默认首页只能填写文件名")
}
}
for _, name := range []string{v.Error404, v.Error503} {
if name != "" && (!ValidRelative(name) || (!strings.HasSuffix(name, ".html") && !strings.HasSuffix(name, ".htm"))) {
return errors.New("错误页应为网站目录内的 HTML 文件")
}
}
if v.RedirectCode != 301 && v.RedirectCode != 302 {
return errors.New("跳转状态码应为 301 或 302")
}
if v.RedirectURL != "" {
u, e := url.Parse(v.RedirectURL)
if e != nil || u.Hostname() == "" || u.User != nil || (u.Scheme != "http" && u.Scheme != "https") || len(v.RedirectURL) > 2048 || strings.ContainsAny(v.RedirectURL, "\x00\r\n\t \"'{};$\\") {
return errors.New("跳转地址无效")
}
}
return nil
}
func (v *Startup) Validate() error {
if raw, e := json.Marshal(v); e != nil || len(raw) > 24<<10 {
return errors.New("启动配置不能超过 24 KiB")
}
if v.EntryFile != "" && !ValidRelative(v.EntryFile) {
return errors.New("启动入口必须位于网站目录内")
}
if v.WorkDir == "" {
v.WorkDir = "."
}
if v.WorkDir != "." && !ValidRelative(v.WorkDir) {
return errors.New("工作目录必须位于网站目录内")
}
if len(v.Arguments) > 64 || len(v.Environment) > 64 {
return errors.New("启动参数或环境变量过多")
}
for _, arg := range v.Arguments {
if len(arg) > 2048 || strings.ContainsAny(arg, "\x00\r\n") {
return errors.New("启动参数无效")
}
}
for k, value := range v.Environment {
upper := strings.ToUpper(k)
if !envName.MatchString(k) || strings.HasPrefix(upper, "LD_") || strings.HasPrefix(upper, "DYLD_") || map[string]bool{"PORT": true, "PATH": true, "HOME": true, "USER": true, "LOGNAME": true, "SHELL": true, "BASH_ENV": true, "ENV": true}[upper] || len(value) > 4096 || strings.ContainsAny(value, "\x00\r\n") {
return errors.New("环境变量名称被保留,或值包含换行/超过限制")
}
}
return nil
}
+60
View File
@@ -0,0 +1,60 @@
package hosting
import (
"testing"
"time"
)
func TestCronTimeZonesAndCalendar(t *testing.T) {
for _, v := range []struct{ expression, zone, after, want string }{{"*/5 * * * *", "Asia/Shanghai", "2026-10-28T00:01:17Z", "2026-10-28T00:05:00Z"}, {"0 8 * * *", "Asia/Shanghai", "2026-10-28T00:00:00Z", "2026-10-29T00:00:00Z"}, {"0 0 * * 7", "UTC", "2026-10-28T00:00:00Z", "2026-11-01T00:00:00Z"}, {"0 0 1 * 1", "UTC", "2026-10-28T00:00:00Z", "2026-11-01T00:00:00Z"}, {"0 0 */2 * 1", "UTC", "2026-10-28T00:00:00Z", "2026-11-09T00:00:00Z"}} {
c, e := ParseCron(v.expression, v.zone)
if e != nil {
t.Fatal(e)
}
after, _ := time.Parse(time.RFC3339, v.after)
got, e := c.Next(after)
if e != nil || got.Format(time.RFC3339) != v.want {
t.Fatalf("%s: %s %v", v.expression, got, e)
}
}
for _, expression := range []string{"@hourly", "60 * * * *", "*/0 * * * *", "* * * * 8", "* * 0 * *", "* * * * */-1", "1-2-3 * * * *", "* * * * ;id"} {
if _, e := ParseCron(expression, "UTC"); e == nil {
t.Fatalf("accepted %q", expression)
}
}
if _, e := ParseCron("* * * * *", "Missing/Zone"); e == nil {
t.Fatal("invalid timezone accepted")
}
}
func TestStartupRejectsControlEnvironmentAndPaths(t *testing.T) {
for _, key := range []string{"LD_PRELOAD", "ld_library_path", "DYLD_INSERT_LIBRARIES", "PATH", "BASH_ENV", "PORT", "A=B"} {
v := Startup{Environment: map[string]string{key: "x"}}
if v.Validate() == nil {
t.Fatalf("accepted %s", key)
}
}
for _, entry := range []string{"../other/app.py", "/etc/passwd", ".sea-runtime/config", "app;id", "a/../../secret"} {
v := Startup{EntryFile: entry}
if v.Validate() == nil {
t.Fatalf("accepted %s", entry)
}
}
v := Startup{Environment: map[string]string{"APP_KEY": "a'$(id)`x`"}, Arguments: []string{"a b", "$(id)"}}
if e := v.Validate(); e != nil {
t.Fatal("literal values should not be shell parsed", e)
}
}
func TestWebsiteRejectsNginxInjection(t *testing.T) {
for _, value := range []string{"https://example.com/;root /etc;", "https://user:pass@example.com/", "https://example.com/$request_uri", "https://example.com/\nreturn 200"} {
v := DefaultWebsite()
v.RedirectURL = value
if v.Validate() == nil {
t.Fatalf("accepted %s", value)
}
}
v := DefaultWebsite()
v.Error503 = "../other/secret.html"
if v.Validate() == nil {
t.Fatal("traversing error page accepted")
}
}
+164
View File
@@ -0,0 +1,164 @@
package httpapi
import (
"fmt"
"net/http"
"strings"
"time"
"sea-vhost/internal/auth"
)
func mfaSecretLabel(userID uint64) string {
return fmt.Sprintf("mfa-user:%d", userID)
}
func (s *Server) accountSecurity(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
security, err := s.store.UserSecurity(r.Context(), user.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取账号安全设置")
return
}
writeJSON(w, http.StatusOK, map[string]any{"mfaEnabled": security.TOTPEnabled})
}
func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
var input struct {
CurrentPassword string `json:"currentPassword"`
NewPassword string `json:"newPassword"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
if len(input.NewPassword) < 12 || len(input.NewPassword) > 128 || input.NewPassword == input.CurrentPassword {
writeError(w, http.StatusUnprocessableEntity, "新密码应为 12–128 个字符且不能与原密码相同")
return
}
user := currentUser(r)
security, err := s.store.UserSecurity(r.Context(), user.ID)
if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) {
writeError(w, http.StatusUnauthorized, "当前密码不正确")
return
}
hash, err := auth.HashPassword(input.NewPassword)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法更新密码")
return
}
cookie, _ := r.Cookie("sea_session")
if cookie == nil || s.store.ChangePassword(r.Context(), user.ID, hash, cookie.Value) != nil {
writeError(w, http.StatusInternalServerError, "无法更新密码")
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "update", "account_password", "", requestClientIP(r), true, "修改账号密码并注销其他会话")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) setupMFA(w http.ResponseWriter, r *http.Request) {
var input struct {
CurrentPassword string `json:"currentPassword"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
security, err := s.store.UserSecurity(r.Context(), user.ID)
if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) {
writeError(w, http.StatusUnauthorized, "当前密码不正确")
return
}
if security.TOTPEnabled {
writeError(w, http.StatusConflict, "双重认证已经启用")
return
}
secret, err := auth.NewTOTPSecret()
if err != nil {
writeError(w, http.StatusInternalServerError, "无法生成双重认证密钥")
return
}
ciphertext, err := s.secretBox.Seal(mfaSecretLabel(user.ID), secret)
if err != nil || s.store.SetPendingTOTP(r.Context(), user.ID, ciphertext) != nil {
writeError(w, http.StatusInternalServerError, "无法保存双重认证设置")
return
}
writeJSON(w, http.StatusOK, map[string]any{"secret": secret, "otpauthURI": auth.TOTPURI(secret, user.LoginName)})
}
func (s *Server) enableMFA(w http.ResponseWriter, r *http.Request) {
var input struct {
Code string `json:"code"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
security, err := s.store.UserSecurity(r.Context(), user.ID)
secret := ""
if err == nil && len(security.TOTPSecretCiphertext) > 0 {
secret, err = s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext)
}
if err != nil || secret == "" {
writeError(w, http.StatusConflict, "请先生成双重认证密钥")
return
}
if !auth.VerifyTOTP(secret, input.Code, time.Now()) {
writeError(w, http.StatusUnprocessableEntity, "动态验证码无效")
return
}
codes, err := auth.NewRecoveryCodes(10)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法生成恢复码")
return
}
hashes := make([][]byte, 0, len(codes))
for _, code := range codes {
hashes = append(hashes, auth.RecoveryCodeHash(code))
}
if err = s.store.EnableTOTP(r.Context(), user.ID, hashes); err != nil {
writeError(w, http.StatusInternalServerError, "无法启用双重认证")
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "enable", "account_mfa", "", requestClientIP(r), true, "启用 TOTP 双重认证")
writeJSON(w, http.StatusOK, map[string]any{"recoveryCodes": codes})
}
func (s *Server) disableMFA(w http.ResponseWriter, r *http.Request) {
var input struct {
CurrentPassword string `json:"currentPassword"`
Code string `json:"code"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
security, err := s.store.UserSecurity(r.Context(), user.ID)
if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) {
writeError(w, http.StatusUnauthorized, "当前密码不正确")
return
}
if !security.TOTPEnabled {
writeError(w, http.StatusConflict, "双重认证尚未启用")
return
}
secret, err := s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext)
validCode := err == nil && auth.VerifyTOTP(secret, input.Code, time.Now())
if !validCode && strings.TrimSpace(input.Code) != "" {
validCode, err = s.store.ConsumeRecoveryCode(r.Context(), user.ID, auth.RecoveryCodeHash(input.Code))
}
if err != nil || !validCode {
writeError(w, http.StatusUnprocessableEntity, "动态验证码或恢复码无效")
return
}
if err = s.store.DisableTOTP(r.Context(), user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "无法关闭双重认证")
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "disable", "account_mfa", "", requestClientIP(r), true, "关闭 TOTP 双重认证并注销全部会话")
http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1})
w.WriteHeader(http.StatusNoContent)
}
+186
View File
@@ -0,0 +1,186 @@
package httpapi
import (
"errors"
"net/http"
"net/mail"
"regexp"
"strconv"
"strings"
"time"
"sea-vhost/internal/store"
)
var tenantSlugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,46}[a-z0-9]$`)
type adminPlanInput struct {
Name string `json:"name"`
StorageBytes uint64 `json:"storageBytes"`
DatabaseBytes uint64 `json:"databaseBytes"`
BandwidthBytes uint64 `json:"bandwidthBytes"`
BandwidthMbps uint32 `json:"bandwidthMbps"`
ProcessLimit uint32 `json:"processLimit"`
FTPLimit uint32 `json:"ftpLimit"`
DatabaseLimit uint32 `json:"databaseLimit"`
ProjectLimit uint32 `json:"projectLimit"`
}
func (s *Server) adminPlans(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
plans, err := s.store.ListPlans(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取套餐")
return
}
writeJSON(w, http.StatusOK, map[string]any{"plans": plans})
return
}
var input adminPlanInput
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
input.Name = strings.TrimSpace(input.Name)
if err := validatePlan(input); err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
id, err := s.store.CreatePlan(r.Context(), store.NewPlan{Name: input.Name, StorageBytes: input.StorageBytes, DatabaseBytes: input.DatabaseBytes, BandwidthBytes: input.BandwidthBytes, BandwidthMbps: input.BandwidthMbps, ProcessLimit: input.ProcessLimit, FTPLimit: input.FTPLimit, DatabaseLimit: input.DatabaseLimit, ProjectLimit: input.ProjectLimit})
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法创建套餐,请检查名称是否重复")
return
}
user := currentUser(r)
s.store.Log(r.Context(), nil, user.ID, "create", "plan", input.Name, requestClientIP(r), true, "创建套餐 "+input.Name)
writeJSON(w, http.StatusCreated, map[string]any{"id": id})
}
func validatePlan(input adminPlanInput) error {
if input.BandwidthMbps > 10000 {
return errors.New("限速应在 0–10000 Mbps 之间,0 为不限速")
}
const maxBytes = uint64(1 << 50)
if len([]rune(input.Name)) < 1 || len([]rune(input.Name)) > 80 {
return errors.New("套餐名称应为 1–80 个字符")
}
if input.StorageBytes < 1<<20 || input.StorageBytes > maxBytes || input.DatabaseBytes < 1<<20 || input.DatabaseBytes > maxBytes || input.BandwidthBytes < 1<<20 || input.BandwidthBytes > maxBytes {
return errors.New("资源容量必须在 1 MB 至 1 PB 之间")
}
if input.ProcessLimit < 1 || input.ProcessLimit > 100000 || input.FTPLimit < 1 || input.FTPLimit > 10000 || input.DatabaseLimit < 1 || input.DatabaseLimit > 10000 || input.ProjectLimit < 1 || input.ProjectLimit > 10000 {
return errors.New("资源数量限制超出允许范围")
}
return nil
}
func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
items, err := s.store.ListTenants(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取用户")
return
}
writeJSON(w, http.StatusOK, map[string]any{"tenants": items})
return
}
var input struct {
Slug string `json:"slug"`
Name string `json:"name"`
Email string `json:"email"`
DisplayName string `json:"displayName"`
Password string `json:"password"`
PlanID uint64 `json:"planId"`
ExpiresAt *time.Time `json:"expiresAt"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
input.Slug = strings.ToLower(strings.TrimSpace(input.Slug))
if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || len(input.Password) < 12 {
writeError(w, http.StatusUnprocessableEntity, "用户标识、名称或密码不符合要求")
return
}
address, err := mail.ParseAddress(strings.TrimSpace(input.Email))
if err != nil || !strings.EqualFold(address.Address, strings.TrimSpace(input.Email)) {
writeError(w, http.StatusUnprocessableEntity, "邮箱格式不正确")
return
}
input.Name = strings.TrimSpace(input.Name)
input.DisplayName = strings.TrimSpace(input.DisplayName)
if len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || input.PlanID == 0 {
writeError(w, http.StatusUnprocessableEntity, "用户名称、管理员名称或套餐无效")
return
}
if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil {
writeError(w, http.StatusUnprocessableEntity, "所选套餐不存在")
return
}
id, err := s.store.CreateTenant(r.Context(), store.NewTenant{Slug: input.Slug, Name: input.Name, Email: strings.TrimSpace(input.Email), DisplayName: input.DisplayName, Password: input.Password, PlanID: input.PlanID, ExpiresAt: input.ExpiresAt})
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查标识或邮箱是否重复")
return
}
user := currentUser(r)
s.store.Log(r.Context(), nil, user.ID, "create", "tenant", input.Slug, requestClientIP(r), true, "创建用户 "+input.Name)
writeJSON(w, http.StatusCreated, map[string]any{"id": id})
}
func (s *Server) domainApprovalSetting(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
writeJSON(w, http.StatusOK, map[string]any{"enabled": s.store.DomainApproval(r.Context(), s.cfg.DomainApproval)})
return
}
var input struct {
Enabled bool `json:"enabled"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
if err := s.store.SetDomainApproval(r.Context(), input.Enabled); err != nil {
writeError(w, http.StatusInternalServerError, "无法保存设置")
return
}
user := currentUser(r)
s.store.Log(r.Context(), nil, user.ID, "update", "domain_approval", "", requestClientIP(r), true, map[bool]string{true: "开启域名审核", false: "关闭域名审核"}[input.Enabled])
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) adminPendingDomains(w http.ResponseWriter, r *http.Request) {
items, err := s.store.PendingDomains(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取待审核域名")
return
}
writeJSON(w, http.StatusOK, map[string]any{"domains": items})
}
func (s *Server) adminReviewDomain(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "域名编号无效")
return
}
var input struct {
Approved bool `json:"approved"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
item, err := s.projects.ReviewDomain(r.Context(), id, input.Approved)
if err != nil {
s.store.Log(r.Context(), nil, user.ID, "review", "domain", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
tenantID := item.TenantID
detail := "拒绝域名 " + item.Domain
if input.Approved {
detail = "批准域名 " + item.Domain
}
s.store.Log(r.Context(), &tenantID, user.ID, "review", "domain", strconv.FormatUint(id, 10), requestClientIP(r), true, detail)
writeJSON(w, http.StatusOK, map[string]any{"domain": item})
}
+708
View File
@@ -0,0 +1,708 @@
package httpapi
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/mail"
"regexp"
"strconv"
"strings"
"time"
"sea-vhost/internal/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
type batchRow struct {
Name string `json:"name,omitempty"`
Slug string `json:"slug,omitempty"`
Email string `json:"email,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Password string `json:"password,omitempty"`
AccountID uint64 `json:"accountId,omitempty"`
Account string `json:"account,omitempty"`
Owner string `json:"owner,omitempty"`
TenantID uint64 `json:"tenantId,omitempty"`
HostID uint64 `json:"hostId,omitempty"`
Host string `json:"host,omitempty"`
OwnershipVersion uint64 `json:"ownershipVersion,omitempty"`
CredentialMode string `json:"credentialMode,omitempty"`
StopServices *bool `json:"stopServices,omitempty"`
ResumeOwnership bool `json:"resumeOwnership,omitempty"`
NodeID uint64 `json:"nodeId,omitempty"`
PlanID uint64 `json:"planId,omitempty"`
Runtime string `json:"runtime,omitempty"`
Version string `json:"version,omitempty"`
RunPath string `json:"runPath,omitempty"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
SetExpiry bool `json:"setExpiry,omitempty"`
AutoSSL bool `json:"autoSSL,omitempty"`
}
type batchRequest struct {
RequestKey string `json:"requestKey"`
Operation string `json:"operation"`
Rows []batchRow `json:"rows"`
}
type batchPreviewRow struct {
Row int `json:"row"`
Label string `json:"label"`
Valid bool `json:"valid"`
Detail string `json:"detail"`
}
type batchResult struct {
ResourceID uint64 `json:"resourceId"`
Login string `json:"login,omitempty"`
Password string `json:"password,omitempty"`
HostLogin string `json:"hostLogin,omitempty"`
FTPHost string `json:"ftpHost,omitempty"`
FTPUsername string `json:"ftpUsername,omitempty"`
FTPPassword string `json:"ftpPassword,omitempty"`
DatabaseName string `json:"databaseName,omitempty"`
DatabaseUsername string `json:"databaseUsername,omitempty"`
DatabasePassword string `json:"databasePassword,omitempty"`
}
var batchKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
var batchHostNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`)
var batchOperations = map[string]bool{"create_users": true, "create_hosts": true, "assign_hosts": true, "host_subscription": true, "host_start": true, "host_stop": true, "host_password_reset": true, "user_enable": true, "user_disable": true}
func randomBatchKey() (string, error) {
var raw [16]byte
_, err := rand.Read(raw[:])
return hex.EncodeToString(raw[:]), err
}
func randomBatchPassword() (string, error) {
var raw [24]byte
_, err := rand.Read(raw[:])
return "Sv-" + base64.RawURLEncoding.EncodeToString(raw[:]) + "9a", err
}
func batchCipherLabel(ref, kind string, row int) string {
return fmt.Sprintf("admin-batch:%s:%s:%d", ref, kind, row)
}
func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]batchPreviewRow, error) {
if !batchOperations[input.Operation] {
return nil, errors.New("不支持此批量操作")
}
limit := 200
if input.Operation == "create_users" {
limit = 100
}
if input.Operation == "create_hosts" {
limit = 50
}
if len(input.Rows) == 0 || len(input.Rows) > limit {
return nil, fmt.Errorf("该操作每批需要 1–%d 条数据", limit)
}
plans, err := s.store.ListPlans(ctx)
if err != nil {
return nil, err
}
if len(plans) == 0 {
return nil, errors.New("请先创建套餐")
}
hosts, err := s.store.ListAdminProjects(ctx)
if err != nil {
return nil, err
}
accounts, err := s.store.ListTenants(ctx)
if err != nil {
return nil, err
}
result := make([]batchPreviewRow, len(input.Rows))
seen := map[string]bool{}
for index := range input.Rows {
row := &input.Rows[index]
preview := batchPreviewRow{Row: index + 1, Valid: true}
var validation error
switch input.Operation {
case "create_users":
row.Slug = strings.ToLower(strings.TrimSpace(row.Slug))
row.Email = strings.ToLower(strings.TrimSpace(row.Email))
row.Name = strings.TrimSpace(row.Name)
row.DisplayName = strings.TrimSpace(row.DisplayName)
if row.PlanID == 0 {
row.PlanID = plans[0].ID
}
if row.DisplayName == "" {
row.DisplayName = row.Name
}
address, e := mail.ParseAddress(row.Email)
if !tenantSlugPattern.MatchString(row.Slug) || len([]rune(row.Name)) < 2 || len([]rune(row.Name)) > 120 || len([]rune(row.DisplayName)) < 2 || len([]rune(row.DisplayName)) > 80 {
validation = errors.New("用户标识、名称或显示名称格式无效")
} else if e != nil || address.Address != row.Email {
validation = errors.New("登录邮箱格式无效")
} else if row.Password != "" && (len(row.Password) < 12 || len(row.Password) > 72) {
validation = errors.New("密码应为 12–72 字节,留空将独立随机生成")
} else if _, e = s.store.Plan(ctx, row.PlanID); e != nil {
validation = errors.New("套餐不存在")
}
key := "user:" + row.Email
slugKey := "slug:" + row.Slug
if validation == nil && (seen[key] || seen[slugKey]) {
validation = errors.New("同批邮箱或用户标识重复")
}
seen[key] = true
seen[slugKey] = true
if validation == nil {
exists, e := s.store.AccountIdentityExists(ctx, row.Slug, row.Email)
if e != nil {
validation = errors.New("无法核对现有账号")
} else if exists {
validation = errors.New("邮箱或用户标识已存在")
}
}
preview.Label = row.Email
case "create_hosts":
row.Name = strings.ToLower(strings.TrimSpace(row.Name))
row.Runtime = strings.TrimSpace(row.Runtime)
row.Version = strings.TrimSpace(row.Version)
if row.RunPath == "" {
row.RunPath = "/public"
}
if row.Owner != "" {
row.TenantID, validation = s.store.ResolveAccount(ctx, row.Owner)
}
if validation == nil && row.TenantID > 0 {
_, validation = s.store.TenantOwner(ctx, row.TenantID)
}
if validation == nil && !batchHostNamePattern.MatchString(row.Name) {
validation = errors.New("主机名称应为 3–50 位小写字母、数字或连字符")
}
if validation == nil {
node, e := s.store.Node(ctx, row.NodeID)
if e != nil || !node.Enabled {
validation = errors.New("节点不存在或未启用")
}
}
if validation == nil {
if _, e := s.store.Plan(ctx, row.PlanID); e != nil {
validation = errors.New("套餐不存在")
}
}
if validation == nil && !map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true}[row.Runtime] {
validation = errors.New("运行环境无效")
}
if validation == nil && (row.Version == "" || len(row.Version) > 80) {
validation = errors.New("请选择已安装版本")
}
if validation == nil && (strings.Contains(row.RunPath, "..") || strings.ContainsAny(row.RunPath, "\\\x00") || len(row.RunPath) > 255) {
validation = errors.New("运行目录无效")
}
preview.Label = row.Name
case "user_enable", "user_disable":
if row.Account != "" {
row.AccountID, validation = s.store.ResolveAnyAccount(ctx, row.Account)
}
found := false
for _, account := range accounts {
if account.ID == row.AccountID {
preview.Label = account.Name
found = true
}
}
if !found {
validation = errors.New("用户账号不存在")
}
key := "account:" + strconv.FormatUint(row.AccountID, 10)
if seen[key] {
validation = errors.New("同批账号重复")
}
seen[key] = true
default:
var host *store.AdminProject
for i := range hosts {
if (row.HostID > 0 && hosts[i].ID == row.HostID) || (row.Host != "" && (hosts[i].HostName == row.Host || strconv.FormatUint(hosts[i].ID, 10) == row.Host)) {
host = &hosts[i]
break
}
}
if host == nil {
validation = errors.New("主机不存在,请使用主机 ID 或随机主机名")
break
}
row.HostID = host.ID
preview.Label = host.HostName
if row.OwnershipVersion != 0 && row.OwnershipVersion != host.OwnershipVersion {
validation = errors.New("主机归属已变化,请刷新后重新预览")
}
row.OwnershipVersion = host.OwnershipVersion
if host.ManagementLocked && !(input.Operation == "assign_hosts" && row.ResumeOwnership) {
validation = store.ErrManagementLocked
}
if host.Status == "failed" || host.Status == "provisioning" {
validation = errors.New("主机尚未完成开通,不能批量管理")
}
key := "host:" + strconv.FormatUint(row.HostID, 10)
if seen[key] {
validation = errors.New("同批主机重复")
}
seen[key] = true
if input.Operation == "assign_hosts" {
if row.CredentialMode == "" {
row.CredentialMode = "preserve"
}
if row.StopServices == nil {
value := true
row.StopServices = &value
}
if row.CredentialMode != "preserve" && row.CredentialMode != "reset" {
validation = errors.New("凭据策略必须为 preserve 或 reset")
}
if row.Owner != "" {
row.TenantID, err = s.store.ResolveAccount(ctx, row.Owner)
if err != nil {
validation = err
}
}
if row.TenantID > 0 {
if _, e := s.store.TenantOwner(ctx, row.TenantID); e != nil {
validation = errors.New("目标用户不存在或已停用")
}
}
if host.ManagementLocked && row.ResumeOwnership {
pending, e := s.store.OwnershipChange(ctx, host.ID)
matches := pending.TargetOwnerID == nil && row.TenantID == 0 || pending.TargetOwnerID != nil && *pending.TargetOwnerID == row.TenantID
if e != nil || pending.State != "pending" || !matches || pending.ExpectedVersion != row.OwnershipVersion || pending.CredentialMode != row.CredentialMode || pending.StopServices != *row.StopServices {
validation = errors.New("恢复操作必须使用未完成任务原有的目标用户、凭据和停站策略")
}
}
}
if input.Operation == "host_subscription" {
if row.PlanID == 0 {
row.PlanID = host.PlanID
}
if _, e := s.store.Plan(ctx, row.PlanID); e != nil {
validation = errors.New("套餐不存在")
}
if !row.SetExpiry {
row.ExpiresAt = host.ExpiresAt
}
}
}
if row.ExpiresAt != nil && (row.ExpiresAt.Year() < 2000 || row.ExpiresAt.Year() > 9999) {
validation = errors.New("到期时间超出允许范围")
}
if preview.Label == "" {
preview.Label = fmt.Sprintf("第 %d 条", index+1)
}
if validation != nil {
preview.Valid = false
preview.Detail = validation.Error()
} else {
preview.Detail = "可以执行"
if input.Operation == "assign_hosts" {
credential := "保留三类密码(旧持有者仍可登录主机、FTP 和数据库)"
if row.CredentialMode == "reset" {
credential = "随机重置主机、FTP、数据库密码并断开旧连接"
}
state := "先停止全部网站"
if row.StopServices != nil && !*row.StopServices {
state = "保持网站当前运行状态"
}
preview.Detail = state + ";" + credential + ";注销旧主机管理会话"
for _, host := range hosts {
if host.ID == row.HostID && !host.ManagementLocked && ((host.OwnerTenantID == nil && row.TenantID == 0) || (host.OwnerTenantID != nil && *host.OwnerTenantID == row.TenantID)) {
preview.Detail = "归属相同,将跳过,不停站也不重置密码"
break
}
}
}
}
result[index] = preview
}
return result, nil
}
func (s *Server) adminBatchPreview(w http.ResponseWriter, r *http.Request) {
var input batchRequest
if decodeJSON(r, &input) != nil {
writeError(w, 400, "批量数据格式无效")
return
}
rows, err := s.normalizeBatch(r.Context(), &input)
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 200, map[string]any{"rows": rows})
}
func (s *Server) adminBatches(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
jobs, err := s.store.AdminBatches(r.Context())
if err != nil {
writeError(w, 500, "无法读取批量任务")
return
}
writeJSON(w, 200, map[string]any{"batches": jobs})
return
}
var input batchRequest
if decodeJSON(r, &input) != nil || !batchKeyPattern.MatchString(input.RequestKey) {
writeError(w, 400, "批量数据或请求标识无效")
return
}
original, _ := json.Marshal(input)
mac := hmac.New(sha256.New, []byte(s.cfg.SessionSecret))
_, _ = mac.Write([]byte("admin-batch-request\x00"))
_, _ = mac.Write(original)
digest := hex.EncodeToString(mac.Sum(nil))
existing, e := s.store.ExistingAdminBatch(r.Context(), input.RequestKey, digest)
if e != nil {
writeError(w, 409, e.Error())
return
}
if existing > 0 {
job, e := s.store.AdminBatch(r.Context(), existing, false)
if e != nil {
writeError(w, 500, "无法读取已有批次")
return
}
writeJSON(w, 202, map[string]any{"batch": job})
return
}
rows, err := s.normalizeBatch(r.Context(), &input)
if err != nil {
writeError(w, 422, err.Error())
return
}
ref, err := randomBatchKey()
if err != nil {
writeError(w, 500, "无法建立批量任务")
return
}
items := make([]store.AdminBatchItem, len(rows))
valid := 0
for index, preview := range rows {
item := store.AdminBatchItem{Row: index + 1, Label: preview.Label, State: "pending"}
if !preview.Valid {
item.State = "failed"
item.Detail = preview.Detail
} else {
valid++
if input.Operation != "create_users" && input.Operation != "create_hosts" {
target := input.Rows[index].HostID
if input.Operation == "user_enable" || input.Operation == "user_disable" {
target = input.Rows[index].AccountID
}
if target > 0 {
item.ResourceID = &target
}
}
}
raw, _ := json.Marshal(input.Rows[index])
cipher, e := s.secretBox.Seal(batchCipherLabel(ref, "input", index+1), string(raw))
if e != nil {
writeError(w, 500, "无法加密任务数据")
return
}
item.InputCipher = cipher
items[index] = item
}
if valid == 0 {
writeJSON(w, 422, map[string]any{"error": map[string]string{"message": "没有可执行的条目,请先修正预览错误"}, "rows": rows})
return
}
id, err := s.store.CreateAdminBatch(r.Context(), currentUser(r).ID, input.RequestKey, digest, input.Operation, ref, items)
if err != nil {
status := 422
if errors.Is(err, store.ErrBatchKeyConflict) {
status = 409
}
writeError(w, status, err.Error())
return
}
s.store.Log(r.Context(), nil, currentUser(r).ID, "create", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, fmt.Sprintf("提交批量任务 %s,共 %d 项", input.Operation, len(rows)))
job, err := s.store.AdminBatch(r.Context(), id, false)
if err != nil {
writeError(w, 500, "任务已保存,请刷新任务列表")
return
}
writeJSON(w, 202, map[string]any{"batch": job})
}
func (s *Server) adminBatch(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "批次编号无效")
return
}
job, err := s.store.AdminBatch(r.Context(), id, false)
if err != nil {
writeError(w, 404, "批次不存在")
return
}
writeJSON(w, 200, map[string]any{"batch": job})
}
func (s *Server) adminCancelBatch(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
if id == 0 {
writeError(w, 400, "批次编号无效")
return
}
if err := s.store.CancelAdminBatch(r.Context(), id); err != nil {
writeError(w, 500, "无法取消任务")
return
}
_ = s.store.RefreshAdminBatches(r.Context())
s.store.Log(r.Context(), nil, currentUser(r).ID, "cancel", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, "取消批次未执行项,执行中条目继续完成")
w.WriteHeader(204)
}
func (s *Server) adminBatchDownload(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
job, err := s.store.AdminBatch(r.Context(), id, true)
if err != nil {
writeError(w, 404, "批次不存在")
return
}
if job.Pending > 0 {
writeError(w, 409, "请等待批次执行完成再下载")
return
}
if job.SecretsExpireAt == nil || !job.SecretsExpireAt.After(time.Now()) {
writeError(w, 410, "批次凭据已过期;FTP 和数据库凭据仍可在对应主机查看,登录密码可重置")
return
}
type downloadItem struct {
Row int `json:"row"`
Label string `json:"label"`
State string `json:"state"`
ResourceID *uint64 `json:"resourceId,omitempty"`
Detail string `json:"detail"`
Result *batchResult `json:"result,omitempty"`
}
items := make([]downloadItem, 0, len(job.Items))
for _, item := range job.Items {
record := downloadItem{Row: item.Row, Label: item.Label, State: item.State, ResourceID: item.ResourceID, Detail: item.Detail}
if len(item.ResultCipher) > 0 {
var result batchResult
raw, e := s.secretBox.Open(batchCipherLabel(job.SecretRef, "result", item.Row), item.ResultCipher)
if e != nil || json.Unmarshal([]byte(raw), &result) != nil {
writeError(w, 500, "无法解密批次结果")
return
}
record.Result = &result
}
items = append(items, record)
}
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="sea-vhost-batch-%d.json"`, id))
job.Items = nil
writeJSON(w, 200, map[string]any{"format": "sea-vhost.batch-result", "version": 1, "batch": job, "items": items})
s.store.Log(r.Context(), nil, currentUser(r).ID, "download", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, "下载批次凭据结果")
}
// RunAdminBatches runs on the controller; the browser never drives the queue.
func (s *Server) RunAdminBatches(ctx context.Context) {
var release func()
for ctx.Err() == nil {
var err error
release, err = s.store.LockBatchWorker(ctx)
if err == nil {
break
}
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
}
}
if release == nil {
return
}
defer release()
go s.runIntegrationWebhooks(ctx)
if err := s.store.RecoverAdminBatches(ctx); err != nil {
slog.Error("batch recovery failed", "error", err)
return
}
for ctx.Err() == nil {
_ = s.store.RefreshAdminBatches(ctx)
job, item, err := s.store.NextAdminBatchItem(ctx)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) && ctx.Err() == nil {
slog.Error("batch queue read failed", "error", err)
}
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
continue
}
s.executeBatchItem(ctx, job, item)
}
}
func (s *Server) executeBatchItem(parent context.Context, job store.AdminBatch, item store.AdminBatchItem) {
ctx, cancel := context.WithTimeout(scope.WithBatchItem(parent, item.ID), 10*time.Minute)
defer cancel()
state, detail := "succeeded", "已完成"
resource := uint64(0)
var result batchResult
administrator, err := s.store.UserByID(ctx, job.AdministratorID)
apiKey, keyErr := s.store.BatchIntegrationKey(ctx, job.ID)
if keyErr != nil || (apiKey > 0 && !s.store.IntegrationKeyActive(ctx, apiKey)) {
err = errors.New("对接 API 密钥已吊销、过期或不可用")
}
if err != nil || administrator.Role != "admin" {
err = errors.New("创建该批次的管理员已不可用")
detail = err.Error()
} else {
var raw string
raw, err = s.secretBox.Open(batchCipherLabel(job.SecretRef, "input", item.Row), item.InputCipher)
var row batchRow
if err == nil {
err = json.Unmarshal([]byte(raw), &row)
}
if err == nil {
result, err = s.performBatchRow(ctx, job.Operation, row)
resource = result.ResourceID
if err == nil && job.Operation == "assign_hosts" {
detail = fmt.Sprintf("主机 #%d → 用户 #%d(0 为未绑定);凭据 %s;停站 %t", row.HostID, row.TenantID, row.CredentialMode, row.StopServices == nil || *row.StopServices)
}
}
if err != nil {
detail = "执行未完成,请核对目标资源及管理员审计"
if errors.Is(err, service.ErrOwnershipIncomplete) {
detail = err.Error()
}
}
}
var cipher []byte
if err == nil {
raw, _ := json.Marshal(result)
cipher, err = s.secretBox.Seal(batchCipherLabel(job.SecretRef, "result", item.Row), string(raw))
if err != nil {
detail = "操作已执行但凭据保存未完成,需按资源 ID 核验"
state = "uncertain"
}
}
if err != nil && state != "uncertain" {
state = "failed"
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
state = "uncertain"
detail = "执行超时或被中断,请核验资源,禁止直接重复开通"
}
}
save, cancelSave := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelSave()
if e := s.store.FinishAdminBatchItem(save, item.ID, state, detail, cipher, resource); e != nil {
slog.Error("batch outcome persistence failed", "batch_id", job.ID, "item_id", item.ID)
}
s.store.Log(save, nil, job.AdministratorID, "execute", "admin_batch", strconv.FormatUint(job.ID, 10), "batch", state == "succeeded", fmt.Sprintf("批次 #%d 第 %d 项 %s:%s", job.ID, item.Row, job.Operation, detail))
}
func (s *Server) performBatchRow(ctx context.Context, operation string, row batchRow) (batchResult, error) {
var result batchResult
if operation == "create_users" {
if row.Password == "" {
var err error
row.Password, err = randomBatchPassword()
if err != nil {
return result, err
}
}
id, err := s.store.CreateTenant(ctx, store.NewTenant{Slug: row.Slug, Name: row.Name, Email: row.Email, DisplayName: row.DisplayName, Password: row.Password, PlanID: row.PlanID})
result.ResourceID = id
result.Login = row.Email
result.Password = row.Password
return result, err
}
if operation == "user_enable" || operation == "user_disable" {
result.ResourceID = row.AccountID
return result, s.store.SetAccountEnabled(ctx, row.AccountID, operation == "user_enable")
}
if operation == "create_hosts" {
ctx = scope.WithNode(ctx, row.NodeID)
release, err := s.projects.BeginRuntimeMutation(ctx)
if err != nil {
return result, err
}
defer release()
created, err := s.projects.CreateManagedHost(ctx, row.TenantID, service.CreateProjectInput{NodeID: row.NodeID, PlanID: row.PlanID, Name: row.Name, Runtime: row.Runtime, Version: row.Version, RunPath: row.RunPath, AutoSSL: row.AutoSSL})
if err != nil {
return result, err
}
result = batchResult{ResourceID: created.Project.ID, HostLogin: created.Credentials.HostLogin, Password: created.Credentials.HostPassword, FTPHost: created.Credentials.FTPHost, FTPUsername: created.Credentials.FTPUsername, FTPPassword: created.Credentials.FTPPassword, DatabaseName: created.Credentials.DatabaseName, DatabaseUsername: created.Credentials.DatabaseUsername, DatabasePassword: created.Credentials.DatabasePassword}
err = s.store.SetHostSubscription(ctx, created.Project.ID, row.PlanID, row.ExpiresAt)
return result, err
}
hosts, err := s.store.ListAdminProjects(ctx)
if err != nil {
return result, err
}
var host *store.AdminProject
for i := range hosts {
if hosts[i].ID == row.HostID {
host = &hosts[i]
break
}
}
if host == nil {
return result, store.ErrNotFound
}
result.ResourceID = host.ID
if host.ManualRecycledAt != nil {
return result, errors.New("主机已手动回收,请先恢复")
}
if host.ManagementLocked && !(operation == "assign_hosts" && row.ResumeOwnership) {
return result, store.ErrManagementLocked
}
if host.OwnershipVersion != row.OwnershipVersion {
return result, errors.New("主机归属已变更,拒绝执行旧批次")
}
ctx = scope.WithProject(ctx, host.ID, host.NodeID)
if operation == "host_subscription" {
return result, s.projects.ApplyHostSubscription(ctx, host.ID, row.PlanID, row.ExpiresAt)
}
if operation == "assign_hosts" {
stop := true
if row.StopServices != nil {
stop = *row.StopServices
}
mode := row.CredentialMode
if mode == "" {
mode = "preserve"
}
credentials, e := s.projects.ChangeHostOwner(ctx, host.ID, row.OwnershipVersion, row.TenantID, mode, stop, row.ResumeOwnership)
result.HostLogin = host.HostName
result.Password = credentials.HostPassword
result.FTPUsername = host.HostName
result.FTPHost = host.Domain
result.FTPPassword = credentials.FTPPassword
result.DatabaseName = host.HostName
result.DatabaseUsername = host.HostName
result.DatabasePassword = credentials.DatabasePassword
return result, e
}
if operation == "host_password_reset" {
result.HostLogin = host.HostName
result.Password, err = s.projects.ResetManagedHostLogin(ctx, host.ID, row.OwnershipVersion)
return result, err
}
release, err := s.projects.BeginRuntimeMutation(ctx)
if err != nil {
return result, err
}
defer release()
namespace, project := host.TenantID, host.ID
user := store.User{Role: "host", TenantID: &namespace, ProjectID: &project}
sites, err := s.store.ListSites(ctx, namespace, project)
if err != nil {
return result, err
}
for _, site := range sites {
if _, err = s.projects.SetSiteState(ctx, user, project, site.ID, operation == "host_start"); err != nil {
return result, err
}
}
return result, nil
}
@@ -0,0 +1,460 @@
package httpapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/go-sql-driver/mysql"
"sea-vhost/internal/auth"
"sea-vhost/internal/config"
"sea-vhost/internal/isolation"
"sea-vhost/internal/panel"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
type ownershipTestPanel struct {
*panel.Mock
mu sync.Mutex
failDatabase bool
ftpPasswords []string
}
func (p *ownershipTestPanel) SetFTPPassword(ctx context.Context, id int64, name, password string) error {
p.mu.Lock()
defer p.mu.Unlock()
p.ftpPasswords = append(p.ftpPasswords, password)
return nil
}
func (p *ownershipTestPanel) SetDatabasePassword(ctx context.Context, id int64, name, password string) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.failDatabase {
p.failDatabase = false
return errors.New("injected native database failure")
}
return nil
}
func TestAdminBatchOwnershipMySQL(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, "batch-admin@example.invalid", "批量测试管理员", "batch-admin-password-123"); err != nil {
t.Fatal(err)
}
root := t.TempDir()
if err = db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"); err != nil {
t.Fatal(err)
}
admin, err := db.UserByLogin(ctx, "batch-admin@example.invalid")
if err != nil {
t.Fatal(err)
}
secret := "batch-test-session-secret-at-least-thirty-two-characters"
native := &ownershipTestPanel{Mock: panel.NewMock()}
projectService := service.NewProjects(db, native, isolation.Mock{Root: root}, "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, projectService)
handler := api.Handler()
token, err := auth.NewSessionToken(secret)
if err != nil {
t.Fatal(err)
}
if err = db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
call := func(method, path string, body any, session 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 session != "" {
request.AddCookie(&http.Cookie{Name: "sea_session", Value: session})
}
response := httptest.NewRecorder()
handler.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())
}
}
path := func(id uint64) string { return "/api/v1/admin/batches/" + strconv.FormatUint(id, 10) }
requestKey := func() string {
key, e := randomBatchKey()
if e != nil {
t.Fatal(e)
}
return key
}
submit := func(input batchRequest) uint64 {
t.Helper()
response := call("POST", "/api/v1/admin/batches", input, token)
expect(response, 202)
var result struct {
Batch store.AdminBatch `json:"batch"`
}
if e := json.Unmarshal(response.Body.Bytes(), &result); e != nil {
t.Fatal(e)
}
return result.Batch.ID
}
var stop context.CancelFunc
var done chan struct{}
startWorker := func() {
worker, cancel := context.WithCancel(ctx)
stop = cancel
done = make(chan struct{})
go func() { defer close(done); api.RunAdminBatches(worker) }()
}
stopWorker := func() {
if stop != nil {
stop()
select {
case <-done:
case <-time.After(20 * time.Second):
t.Fatal("worker did not stop")
}
stop = nil
}
}
defer stopWorker()
wait := func(id uint64) store.AdminBatch {
t.Helper()
deadline := time.Now().Add(90 * time.Second)
for time.Now().Before(deadline) {
job, e := db.AdminBatch(ctx, id, false)
if e != nil {
t.Fatal(e)
}
if job.Pending == 0 && (job.State == "completed" || job.State == "partial") {
return job
}
time.Sleep(25 * time.Millisecond)
}
t.Fatal("batch did not finish")
return store.AdminBatch{}
}
download := func(id uint64) [][]string {
t.Helper()
response := call("GET", path(id)+"/download", nil, token)
expect(response, 200)
var export struct {
Format string `json:"format"`
Version int `json:"version"`
Items []struct {
Row int `json:"row"`
State string `json:"state"`
Label string `json:"label"`
ResourceID *uint64 `json:"resourceId"`
Detail string `json:"detail"`
Result batchResult `json:"result"`
} `json:"items"`
}
if err := json.Unmarshal(response.Body.Bytes(), &export); err != nil {
t.Fatal(err)
}
if export.Format != "sea-vhost.batch-result" || export.Version != 1 || !strings.Contains(response.Header().Get("Content-Disposition"), ".json") {
t.Fatal("JSON download format mismatch")
}
records := [][]string{{"batch", "row", "state", "label", "resource", "login", "password", "ftpHost", "ftpUser", "ftpPassword", "database", "databaseUser", "databasePassword", "detail"}}
for _, item := range export.Items {
r := item.Result
login := r.Login
if login == "" {
login = r.HostLogin
}
resource := ""
if item.ResourceID != nil {
resource = strconv.FormatUint(*item.ResourceID, 10)
}
records = append(records, []string{strconv.FormatUint(id, 10), strconv.Itoa(item.Row), item.State, item.Label, resource, login, r.Password, r.FTPHost, r.FTPUsername, r.FTPPassword, r.DatabaseName, r.DatabaseUsername, r.DatabasePassword, item.Detail})
}
return records
}
login := func(identifier, password string) string {
t.Helper()
response := call("POST", "/api/v1/auth/login", map[string]string{"identifier": identifier, "password": password}, "")
expect(response, 200)
for _, cookie := range response.Result().Cookies() {
if cookie.Name == "sea_session" {
return cookie.Value
}
}
t.Fatal("no session cookie")
return ""
}
expect(call("POST", "/api/v1/admin/batches/preview", batchRequest{Operation: "create_users", Rows: []batchRow{{}}}, ""), 401)
users := batchRequest{RequestKey: requestKey(), Operation: "create_users", Rows: []batchRow{{Slug: "batch-user-a", Name: "批量用户甲", Email: "batch-a@example.invalid", DisplayName: "批量用户甲"}, {Slug: "batch-user-b", Name: "批量用户乙", Email: "batch-b@example.invalid", DisplayName: "批量用户乙"}, {Slug: "batch-user-a", Name: "重复用户甲", Email: "batch-a@example.invalid", DisplayName: "重复用户甲"}}}
preview := call("POST", "/api/v1/admin/batches/preview", users, token)
expect(preview, 200)
if !strings.Contains(preview.Body.String(), "同批邮箱或用户标识重复") {
t.Fatal("duplicate import did not fail preview")
}
batchID := submit(users)
startWorker()
job := wait(batchID)
if job.Succeeded != 2 || job.Failed != 1 {
t.Fatalf("partial user batch: %+v", job)
}
records := download(batchID)
if len(records) != 4 || records[1][6] == "" || records[1][6] == records[2][6] {
t.Fatal("missing independent random passwords")
}
aToken, bToken := login(records[1][5], records[1][6]), login(records[2][5], records[2][6])
userA, err := db.UserByLogin(ctx, records[1][5])
if err != nil {
t.Fatal(err)
}
userB, err := db.UserByLogin(ctx, records[2][5])
if err != nil {
t.Fatal(err)
}
if userB.TenantID == nil || *userB.TenantID == *userA.TenantID {
t.Fatal("batch accounts share an identity")
}
if retry := submit(users); retry != batchID {
t.Fatal("same request duplicated the batch")
}
changed := users
changed.Rows = append([]batchRow(nil), users.Rows...)
changed.Rows[0].Name = "不同请求"
expect(call("POST", "/api/v1/admin/batches", changed, token), 409)
for _, endpoint := range []string{"/api/v1/admin/batches", path(batchID), path(batchID) + "/download"} {
expect(call("GET", endpoint, nil, aToken), 403)
}
expect(call("POST", "/api/v1/admin/batches", users, bToken), 403)
stored, err := db.AdminBatch(ctx, batchID, true)
if err != nil {
t.Fatal(err)
}
for _, item := range stored.Items {
if bytes.Contains(item.ResultCipher, []byte(records[1][6])) {
t.Fatal("plaintext password persisted")
}
}
plans, err := db.ListPlans(ctx)
if err != nil {
t.Fatal(err)
}
hostsInput := batchRequest{RequestKey: requestKey(), Operation: "create_hosts", Rows: []batchRow{{Name: "batch-host-a", TenantID: *userA.TenantID, NodeID: 1, PlanID: plans[0].ID, Runtime: "PHP", Version: "8.4", RunPath: "/public"}, {Name: "batch-host-independent", NodeID: 1, PlanID: plans[0].ID, Runtime: "PHP", Version: "8.4", RunPath: "/public"}}}
hostBatch := submit(hostsInput)
job = wait(hostBatch)
if job.Succeeded != 2 {
t.Fatalf("host batch: %+v", job)
}
hostRows := download(hostBatch)
var aHost, independent uint64
aHost, _ = strconv.ParseUint(hostRows[1][4], 10, 64)
independent, _ = strconv.ParseUint(hostRows[2][4], 10, 64)
hostToken := login(hostRows[1][5], hostRows[1][6])
independentToken := login(hostRows[2][5], hostRows[2][6])
resetBatch := submit(batchRequest{RequestKey: requestKey(), Operation: "host_password_reset", Rows: []batchRow{{HostID: independent}}})
if wait(resetBatch).Succeeded != 1 {
t.Fatal("administrator could not reset independent host login")
}
resetRows := download(resetBatch)
expect(call("GET", "/api/v1/me", nil, independentToken), 401)
independentToken = login(resetRows[1][5], resetRows[1][6])
dashboard := call("GET", "/api/v1/dashboard", nil, aToken)
expect(dashboard, 200)
var view struct {
Projects []store.Project `json:"projects"`
}
if err = json.Unmarshal(dashboard.Body.Bytes(), &view); err != nil {
t.Fatal(err)
}
if len(view.Projects) != 1 || view.Projects[0].ID != aHost {
t.Fatal("account view leaked independent host")
}
expect(call("GET", "/api/v1/resources", nil, aToken), 200)
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(aHost, 10)+"/credentials", nil, aToken), 200)
for _, session := range []string{aToken, bToken, hostToken} {
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, session), 404)
}
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, independentToken), 200)
independentUser, e := db.UserByLogin(ctx, hostRows[2][5])
if e != nil {
t.Fatal(e)
}
namespaceBefore := *independentUser.TenantID
bound := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, TenantID: *userB.TenantID}}})
if wait(bound).Succeeded != 1 {
t.Fatal("initial optional binding failed")
}
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, bToken), 200)
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, aToken), 404)
independentUser, e = db.UserByLogin(ctx, hostRows[2][5])
if e != nil || *independentUser.TenantID != namespaceBefore || independentUser.TenantName != "批量用户乙" {
t.Fatal("initial binding changed resource identity or failed to update displayed owner")
}
stale := batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, TenantID: *userB.TenantID, OwnershipVersion: 1}}}
expect(call("POST", "/api/v1/admin/batches", stale, token), 422)
expect(call("GET", "/api/v1/me", nil, independentToken), 401)
independentToken = login(resetRows[1][5], resetRows[1][6])
started := submit(batchRequest{RequestKey: requestKey(), Operation: "host_start", Rows: []batchRow{{HostID: independent}}})
if wait(started).Succeeded != 1 {
t.Fatal("cannot start bound host")
}
keepRunning := false
transferred := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, TenantID: *userA.TenantID, CredentialMode: "preserve", StopServices: &keepRunning}}})
if wait(transferred).Succeeded != 1 {
t.Fatal("preserve credentials transfer failed")
}
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, bToken), 404)
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, aToken), 200)
expect(call("GET", "/api/v1/me", nil, independentToken), 401)
independentToken = login(resetRows[1][5], resetRows[1][6])
current, e := db.Project(ctx, namespaceBefore, independent)
if e != nil || current.Status != "running" {
t.Fatal("keep-running transfer stopped the website")
}
native.mu.Lock()
native.failDatabase = true
native.mu.Unlock()
interrupted := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, CredentialMode: "reset"}}})
if wait(interrupted).Failed != 1 {
t.Fatal("injected native failure did not stop transfer")
}
pending, e := db.OwnershipChange(ctx, independent)
if e != nil || pending.State != "pending" || len(pending.CredentialsCipher) == 0 {
t.Fatal("failed transition not staged for recovery")
}
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, aToken), 423)
expect(call("GET", "/api/v1/me", nil, independentToken), 401)
expect(call("POST", "/api/v1/admin/batches", batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, CredentialMode: "preserve", ResumeOwnership: true}}}, token), 422)
recoveredBatch := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, CredentialMode: "reset", ResumeOwnership: true}}})
if wait(recoveredBatch).Succeeded != 1 {
t.Fatal("explicit ownership recovery failed")
}
native.mu.Lock()
sameStagedPassword := len(native.ftpPasswords) == 2 && native.ftpPasswords[0] == native.ftpPasswords[1]
native.mu.Unlock()
if !sameStagedPassword {
t.Fatal("recovery generated different native credentials")
}
rotated := download(recoveredBatch)
if rotated[1][6] == "" || rotated[1][9] == "" || rotated[1][12] == "" {
t.Fatal("reset result missing credentials")
}
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": resetRows[1][5], "password": resetRows[1][6]}, ""), 401)
independentToken = login(rotated[1][5], rotated[1][6])
expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, independentToken), 200)
current, e = db.Project(ctx, namespaceBefore, independent)
if e != nil || current.Status != "stopped" {
t.Fatal("default ownership stop was not applied")
}
pending, e = db.OwnershipChange(ctx, independent)
if e != nil || pending.State != "completed" || len(pending.CredentialsCipher) != 0 || pending.TargetOwnerID != nil {
t.Fatal("completed unbind retained staged secrets or owner")
}
filePath := "/api/v1/projects/" + strconv.FormatUint(aHost, 10) + "/files"
expect(call("PUT", filePath, map[string]any{"path": "../must-not-write", "content": "ignored"}, aToken), 400)
for _, session := range []string{aToken, hostToken} {
response := call("GET", "/api/v1/activities?projectId="+strconv.FormatUint(aHost, 10), nil, session)
expect(response, 200)
var logs struct {
Activities []store.Activity `json:"activities"`
}
if e = json.Unmarshal(response.Body.Bytes(), &logs); e != nil {
t.Fatal(e)
}
found := false
for _, event := range logs.Activities {
if event.Actor == "管理员" {
t.Fatal("administrator batch event leaked to customer logs")
}
if event.ResourceType == "file" && event.ProjectID != nil && *event.ProjectID == aHost {
found = true
}
}
if !found {
t.Fatal("resource namespace detached customer host logs")
}
}
expect(call("GET", "/api/v1/activities?projectId="+strconv.FormatUint(aHost, 10), nil, bToken), 404)
summaries, err := db.ListTenants(ctx)
if err != nil || len(summaries) != 2 {
t.Fatalf("resource namespaces leaked into user list: %d %v", len(summaries), err)
}
expiry := time.Now().Add(time.Hour)
sub := submit(batchRequest{RequestKey: requestKey(), Operation: "host_subscription", Rows: []batchRow{{HostID: aHost, PlanID: plans[0].ID, SetExpiry: true, ExpiresAt: &expiry}}})
if wait(sub).Succeeded != 1 {
t.Fatal("subscription batch failed")
}
disabled := submit(batchRequest{RequestKey: requestKey(), Operation: "user_disable", Rows: []batchRow{{AccountID: *userA.TenantID}}})
if wait(disabled).Succeeded != 1 {
t.Fatal("disable batch failed")
}
expect(call("GET", "/api/v1/me", nil, aToken), 401)
expect(call("GET", "/api/v1/me", nil, hostToken), 200)
enabled := submit(batchRequest{RequestKey: requestKey(), Operation: "user_enable", Rows: []batchRow{{Account: records[1][5]}}})
if wait(enabled).Succeeded != 1 {
t.Fatal("enable disabled account by JSON email failed")
}
aToken = login(records[1][5], records[1][6])
expect(call("GET", "/api/v1/dashboard", nil, aToken), 200)
for _, operation := range []string{"host_stop", "host_start"} {
id := submit(batchRequest{RequestKey: requestKey(), Operation: operation, Rows: []batchRow{{HostID: aHost}}})
if wait(id).Succeeded != 1 {
t.Fatalf("%s batch failed", operation)
}
}
stopWorker()
cancelInput := batchRequest{RequestKey: requestKey(), Operation: "create_users", Rows: []batchRow{{Slug: "batch-cancelled", Name: "应取消用户", Email: "cancelled@example.invalid", DisplayName: "应取消用户"}}}
cancelled := submit(cancelInput)
expect(call("POST", path(cancelled)+"/cancel", map[string]string{}, token), 204)
if job, e := db.AdminBatch(ctx, cancelled, false); e != nil || job.Pending != 0 || job.Failed != 1 {
t.Fatal("cancel did not stop pending row")
}
recoveryInput := cancelInput
recoveryInput.RequestKey = requestKey()
recoverID := submit(recoveryInput)
_, item, err := db.NextAdminBatchItem(ctx)
if err != nil {
t.Fatal(err)
}
if err = db.RecoverAdminBatches(ctx); err != nil {
t.Fatal(err)
}
if err = db.RefreshAdminBatches(ctx); err != nil {
t.Fatal(err)
}
recovered, err := db.AdminBatch(ctx, recoverID, false)
if err != nil || recovered.Uncertain != 1 || recovered.Pending != 0 || recovered.Items[0].ID != item.ID {
t.Fatal("restart did not preserve uncertain state")
}
if _, err = db.UserByLogin(ctx, "cancelled@example.invalid"); err == nil {
t.Fatal("cancelled/uncertain operation executed")
}
t.Log("real MySQL batch queue, random credentials, idempotency, JSON access, optional owners, account aggregation, enable/disable, subscription, start/stop, cancellation and restart uncertainty passed")
}
@@ -0,0 +1,468 @@
package httpapi
import (
"encoding/base64"
"encoding/json"
"errors"
"net"
"net/http"
"net/mail"
"net/url"
"sea-vhost/internal/scope"
"strconv"
"strings"
"time"
"sea-vhost/internal/service"
)
type secretServiceConfig struct {
AutoCreate bool `json:"autoCreate,omitempty"`
UserPasswordLogin *bool `json:"userPasswordLogin,omitempty"`
AdminPasswordLogin *bool `json:"adminPasswordLogin,omitempty"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
Username string `json:"username,omitempty"`
Secret string `json:"secret,omitempty"`
From string `json:"from,omitempty"`
AdminRecipients string `json:"adminRecipients,omitempty"`
StartTLS bool `json:"startTls,omitempty"`
Issuer string `json:"issuer,omitempty"`
ClientID string `json:"clientId,omitempty"`
RedirectURI string `json:"redirectUri,omitempty"`
Enabled bool `json:"enabled,omitempty"`
}
func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
users, err := s.store.ListTenants(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取用户")
return
}
projects, err := s.store.ListAdminProjects(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取虚拟主机")
return
}
domains, err := s.store.AllDomains(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取域名")
return
}
ips, err := s.store.ListIPAddresses(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取 IP 地址池")
return
}
logs, err := s.store.AdminActivities(r.Context(), 100)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取操作日志")
return
}
writeJSON(w, http.StatusOK, map[string]any{"users": users, "projects": projects, "domains": domains, "ipAddresses": ips, "logs": logs})
}
func (s *Server) adminSettings(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
smtp := s.readServiceConfig(r, "smtp_config")
oidc := s.readServiceConfig(r, "oidc_config")
writeJSON(w, http.StatusOK, map[string]any{
"domainApproval": s.store.DomainApproval(r.Context(), s.cfg.DomainApproval),
"filingRequired": s.store.Setting(r.Context(), "filing_required", "false") == "true",
"cdnCnameTarget": s.store.Setting(r.Context(), "cdn_cname_target", ""),
"graceDays": settingInt(s.store.Setting(r.Context(), "lifecycle_grace_days", "3"), 3),
"recycleDays": settingInt(s.store.Setting(r.Context(), "lifecycle_recycle_days", "7"), 7),
"backupRetentionDays": settingInt(s.store.Setting(r.Context(), "backup_retention_days", "14"), 14),
"smtp": map[string]any{"enabled": smtp.Enabled, "host": smtp.Host, "port": smtp.Port, "username": smtp.Username, "from": smtp.From, "adminRecipients": smtp.AdminRecipients, "startTls": smtp.StartTLS, "secretConfigured": smtp.Secret != ""},
"oidc": map[string]any{"enabled": oidc.Enabled, "issuer": oidc.Issuer, "clientId": oidc.ClientID, "redirectUri": oidc.RedirectURI, "secretConfigured": oidc.Secret != "", "bindingOnly": !oidc.AutoCreate, "autoCreate": oidc.AutoCreate, "userPasswordLogin": oidcPasswordAllowed(oidc, "tenant"), "adminPasswordLogin": oidcPasswordAllowed(oidc, "admin"), "passwordLogin": oidcPasswordAllowed(oidc, "tenant")},
})
return
}
var input struct {
DomainApproval bool `json:"domainApproval"`
FilingRequired bool `json:"filingRequired"`
CDNCnameTarget string `json:"cdnCnameTarget"`
GraceDays int `json:"graceDays"`
RecycleDays int `json:"recycleDays"`
BackupRetentionDays int `json:"backupRetentionDays"`
SMTP secretServiceConfig `json:"smtp"`
OIDC secretServiceConfig `json:"oidc"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
input.CDNCnameTarget = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.CDNCnameTarget), "."))
if input.GraceDays != 3 || input.RecycleDays != 7 || input.BackupRetentionDays != 14 {
writeError(w, http.StatusUnprocessableEntity, "当前生命周期固定为宽限 3 天、回收保留 7 天、备份保留 14 天")
return
}
if input.CDNCnameTarget != "" && net.ParseIP(input.CDNCnameTarget) == nil && !validHostname(input.CDNCnameTarget) {
writeError(w, http.StatusUnprocessableEntity, "CDN CNAME 目标无效")
return
}
if err := s.validateServiceConfigs(r, &input.SMTP, &input.OIDC); err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
if err := s.store.SetDomainApproval(r.Context(), input.DomainApproval); err != nil {
writeError(w, http.StatusInternalServerError, "无法保存设置")
return
}
for key, value := range map[string]string{"filing_required": strconv.FormatBool(input.FilingRequired), "cdn_cname_target": input.CDNCnameTarget, "lifecycle_grace_days": "3", "lifecycle_recycle_days": "7", "backup_retention_days": "14"} {
if err := s.store.SetSetting(r.Context(), key, value); err != nil {
writeError(w, http.StatusInternalServerError, "无法保存设置")
return
}
}
if err := s.writeServiceConfig(r, "smtp_config", input.SMTP); err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
if err := s.writeServiceConfig(r, "oidc_config", input.OIDC); err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
user := currentUser(r)
s.store.Log(r.Context(), nil, user.ID, "update", "system_settings", "", requestClientIP(r), true, "更新系统、通知与 SSO 设置")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) validateServiceConfigs(r *http.Request, smtpConfig, oidcConfig *secretServiceConfig) error {
smtpConfig.Host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(smtpConfig.Host), "."))
smtpConfig.Username = strings.TrimSpace(smtpConfig.Username)
smtpConfig.From = strings.TrimSpace(smtpConfig.From)
smtpConfig.AdminRecipients = strings.TrimSpace(smtpConfig.AdminRecipients)
issuer := strings.TrimSuffix(strings.TrimSpace(oidcConfig.Issuer), "/")
oidcConfig.Issuer = issuer
oidcConfig.ClientID = strings.TrimSpace(oidcConfig.ClientID)
oidcConfig.RedirectURI = strings.TrimSpace(oidcConfig.RedirectURI)
if smtpConfig.Enabled {
if net.ParseIP(smtpConfig.Host) == nil && !validHostname(smtpConfig.Host) {
return errors.New("SMTP 主机无效")
}
if smtpConfig.Port < 1 || smtpConfig.Port > 65535 {
return errors.New("SMTP 端口无效")
}
if parsed, err := mail.ParseAddress(smtpConfig.From); err != nil || parsed.Address != smtpConfig.From {
return errors.New("SMTP 发件地址无效")
}
addresses := strings.FieldsFunc(smtpConfig.AdminRecipients, func(char rune) bool { return char == ',' || char == ';' || char == '\n' })
if len(addresses) == 0 {
return errors.New("至少需要一个管理员收件地址")
}
for _, address := range addresses {
address = strings.TrimSpace(address)
if parsed, err := mail.ParseAddress(address); err != nil || parsed.Address != address {
return errors.New("管理员收件地址格式无效")
}
}
existing := s.readServiceConfig(r, "smtp_config")
if smtpConfig.Username != "" && strings.TrimSpace(smtpConfig.Secret) == "" && existing.Secret == "" {
return errors.New("SMTP 认证密码不能为空")
}
if smtpConfig.Username != "" && smtpConfig.Port != 465 && !smtpConfig.StartTLS {
return errors.New("SMTP 认证必须启用 TLS")
}
}
existingOIDC := s.readServiceConfig(r, "oidc_config")
if oidcConfig.UserPasswordLogin == nil {
oidcConfig.UserPasswordLogin = existingOIDC.UserPasswordLogin
}
if oidcConfig.AdminPasswordLogin == nil {
oidcConfig.AdminPasswordLogin = existingOIDC.AdminPasswordLogin
}
if !oidcPasswordAllowed(*oidcConfig, "tenant") || !oidcPasswordAllowed(*oidcConfig, "admin") {
candidate := *oidcConfig
if candidate.Secret == "" {
candidate.Secret = existingOIDC.Secret
}
if !validOIDCConfig(candidate) {
return errors.New("关闭密码登录前必须启用并完整配置 SSO")
}
if !oidcPasswordAllowed(candidate, "admin") {
current := currentUser(r)
if _, err := s.store.OIDCIdentity(r.Context(), current.ID, oidcProviderKey(candidate)); err != nil {
return errors.New("请先为当前管理员绑定该 SSO 身份,再关闭管理员密码登录")
}
}
}
if oidcConfig.Enabled {
issuerURL, err := url.Parse(oidcConfig.Issuer)
if err != nil || issuerURL.Scheme != "https" || issuerURL.Host == "" || issuerURL.User != nil || issuerURL.RawQuery != "" || issuerURL.Fragment != "" {
return errors.New("OIDC Issuer 必须是有效的 HTTPS 地址")
}
redirectURL, err := url.Parse(oidcConfig.RedirectURI)
managementDomain := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(s.cfg.ManagementDomain), "."))
if err != nil || redirectURL.Scheme != "https" || !strings.EqualFold(redirectURL.Hostname(), managementDomain) || redirectURL.Path != "/api/v1/auth/oidc/callback" || redirectURL.RawQuery != "" || redirectURL.Fragment != "" || redirectURL.User != nil {
return errors.New("OIDC 回调地址必须是管理域名下的 /api/v1/auth/oidc/callback")
}
if oidcConfig.ClientID == "" || len(oidcConfig.ClientID) > 255 {
return errors.New("OIDC Client ID 无效")
}
existing := s.readServiceConfig(r, "oidc_config")
if strings.TrimSpace(oidcConfig.Secret) == "" && existing.Secret == "" {
return errors.New("OIDC Client Secret 不能为空")
}
}
return nil
}
func (s *Server) readServiceConfig(r *http.Request, key string) secretServiceConfig {
raw := s.store.Setting(r.Context(), key, "{}")
var cfg secretServiceConfig
if json.Unmarshal([]byte(raw), &cfg) != nil {
return secretServiceConfig{}
}
if cfg.Secret != "" {
encrypted, err := base64.RawStdEncoding.DecodeString(cfg.Secret)
if err == nil {
if value, openErr := s.secretBox.Open("system/"+key, encrypted); openErr == nil {
cfg.Secret = value
} else {
cfg.Secret = ""
}
}
}
return cfg
}
func (s *Server) writeServiceConfig(r *http.Request, key string, cfg secretServiceConfig) error {
existing := s.readServiceConfig(r, key)
if strings.TrimSpace(cfg.Secret) == "" {
cfg.Secret = existing.Secret
}
if cfg.Secret != "" {
encrypted, err := s.secretBox.Seal("system/"+key, cfg.Secret)
if err != nil {
return err
}
cfg.Secret = base64.RawStdEncoding.EncodeToString(encrypted)
}
data, err := json.Marshal(cfg)
if err != nil {
return err
}
return s.store.SetSetting(r.Context(), key, string(data))
}
func (s *Server) adminIPs(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
items, err := s.store.ListIPAddresses(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取 IP 地址池")
return
}
writeJSON(w, http.StatusOK, map[string]any{"ipAddresses": items})
return
}
var input struct {
Address string `json:"address"`
AllocationMode string `json:"allocationMode"`
Label string `json:"label"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
ip := net.ParseIP(strings.TrimSpace(input.Address))
if ip == nil {
writeError(w, http.StatusUnprocessableEntity, "IP 地址无效")
return
}
family := "ipv6"
if ip.To4() != nil {
family = "ipv4"
}
if input.AllocationMode != "shared" && input.AllocationMode != "dedicated" {
writeError(w, http.StatusUnprocessableEntity, "IP 分配方式无效")
return
}
id, err := s.store.CreateIPAddress(r.Context(), ip.String(), family, input.AllocationMode, strings.TrimSpace(input.Label))
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "IP 已存在或无法添加")
return
}
writeJSON(w, http.StatusCreated, map[string]any{"id": id})
}
func (s *Server) adminIP(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "IP 编号无效")
return
}
if err = s.store.DeleteIPAddress(r.Context(), id); err != nil {
writeError(w, http.StatusConflict, "已分配的 IP 不能删除")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) adminProjectNetwork(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "虚拟主机编号无效")
return
}
var input struct {
IPID *uint64 `json:"ipId"`
Dedicated bool `json:"dedicated"`
HTTPPort int `json:"httpPort"`
HTTPSPort int `json:"httpsPort"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
if input.HTTPPort < 1 || input.HTTPPort > 65535 || input.HTTPSPort < 1 || input.HTTPSPort > 65535 || input.HTTPPort == input.HTTPSPort {
writeError(w, http.StatusUnprocessableEntity, "HTTP/HTTPS 端口无效")
return
}
if input.Dedicated && input.IPID == nil {
writeError(w, http.StatusUnprocessableEntity, "独立 IP 模式必须选择 IP")
return
}
if err = s.projects.ConfigureProjectNetwork(r.Context(), id, input.IPID, input.Dedicated, input.HTTPPort, input.HTTPSPort); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法更新网络配置")
return
}
user := currentUser(r)
s.store.Log(r.Context(), nil, user.ID, "update", "project_network", strconv.FormatUint(id, 10), requestClientIP(r), true, "更新虚拟主机 IP 与公开端口")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) adminPanelSites(w http.ResponseWriter, r *http.Request) {
items, err := s.projects.UnmanagedPanelSites(r.Context())
if err != nil {
writeError(w, http.StatusBadGateway, "无法读取宝塔站点")
return
}
catalog, err := s.projects.RuntimeCatalog(r.Context())
if err != nil {
writeError(w, http.StatusBadGateway, "无法读取运行环境")
return
}
writeJSON(w, http.StatusOK, map[string]any{"sites": items, "versions": catalog})
}
func (s *Server) adminAdoptPanelSite(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeError(w, http.StatusBadRequest, "宝塔站点编号无效")
return
}
var input struct {
PlanID uint64 `json:"planId"`
TenantID uint64 `json:"tenantId"`
Name string `json:"name"`
Runtime string `json:"runtime"`
Version string `json:"version"`
RunPath string `json:"runPath"`
AutoSSL bool `json:"autoSSL"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
created, err := s.projects.Adopt(r.Context(), service.AdoptProjectInput{NodeID: scope.Node(r.Context()), PlanID: input.PlanID, TenantID: input.TenantID, PanelSiteID: id, Name: input.Name, Runtime: input.Runtime, Version: input.Version, RunPath: input.RunPath, AutoSSL: input.AutoSSL})
user := currentUser(r)
if err != nil {
s.store.Log(r.Context(), nil, user.ID, "adopt", "panel_site", strconv.FormatInt(id, 10), requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(scope.WithProject(r.Context(), created.Project.ID, created.Project.NodeID), &created.Project.TenantID, user.ID, "adopt", "panel_site", strconv.FormatInt(id, 10), requestClientIP(r), true, "接管宝塔站点到虚拟主机 "+created.Project.HostName)
writeJSON(w, http.StatusCreated, created)
}
func (s *Server) adminDomainMetadata(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "域名编号无效")
return
}
var input struct {
ResolutionMode string `json:"resolutionMode"`
CNAMETarget string `json:"cnameTarget"`
FilingStatus string `json:"filingStatus"`
FilingNumber string `json:"filingNumber"`
FilingNote string `json:"filingNote"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
if input.ResolutionMode != "direct" && input.ResolutionMode != "cname" && input.ResolutionMode != "cdn" {
writeError(w, http.StatusUnprocessableEntity, "解析模式无效")
return
}
if input.FilingStatus != "exempt" && input.FilingStatus != "pending" && input.FilingStatus != "approved" && input.FilingStatus != "rejected" {
writeError(w, http.StatusUnprocessableEntity, "备案状态无效")
return
}
input.CNAMETarget = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.CNAMETarget), "."))
input.FilingNumber = strings.TrimSpace(input.FilingNumber)
input.FilingNote = strings.TrimSpace(input.FilingNote)
if input.ResolutionMode == "cdn" && input.CNAMETarget == "" {
input.CNAMETarget = s.store.Setting(r.Context(), "cdn_cname_target", "")
}
if input.ResolutionMode == "direct" {
input.CNAMETarget = ""
}
if (input.ResolutionMode != "direct" && !validNodeDomain(input.CNAMETarget)) || len([]rune(input.FilingNumber)) > 80 || len([]rune(input.FilingNote)) > 500 || strings.ContainsAny(input.FilingNumber+input.FilingNote, "\x00") {
writeError(w, 422, "请检查 CNAME 目标、备案号和备注长度;CDN 模式需配置目标域名")
return
}
err = s.store.UpdateDomainPolicy(r.Context(), id, input.ResolutionMode, input.CNAMETarget, input.FilingStatus, input.FilingNumber, input.FilingNote)
s.resourceAudit(r, "update", "domain_policy", id, err, "更新自定义域名解析指引与备案信息")
if err != nil {
writeError(w, 422, "域名配置未保存,请检查是否为可管理的自定义域名")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) adminTenantExpiry(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "用户编号无效")
return
}
var input struct {
ExpiresAt *time.Time `json:"expiresAt"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
if err = s.store.SetTenantExpiry(r.Context(), id, input.ExpiresAt); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法更新到期时间")
return
}
w.WriteHeader(http.StatusNoContent)
}
func settingInt(value string, fallback int) int {
parsed, err := strconv.Atoi(value)
if err != nil || parsed < 0 {
return fallback
}
return parsed
}
func validHostname(value string) bool {
if len(value) > 253 || value == "" {
return false
}
for _, label := range strings.Split(value, ".") {
if len(label) < 1 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
return false
}
for _, r := range label {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
return false
}
}
}
return true
}
+24
View File
@@ -0,0 +1,24 @@
package httpapi
import "testing"
func TestValidatePlanBoundaries(t *testing.T) {
valid := adminPlanInput{Name: "标准套餐", StorageBytes: 50 << 30, DatabaseBytes: 20 << 30, BandwidthBytes: 500 << 30, ProcessLimit: 100, FTPLimit: 10, DatabaseLimit: 10, ProjectLimit: 10}
if err := validatePlan(valid); err != nil {
t.Fatalf("valid plan rejected: %v", err)
}
invalid := valid
invalid.ProcessLimit = 0
if err := validatePlan(invalid); err == nil {
t.Fatal("zero process limit was accepted")
}
invalid = valid
invalid.StorageBytes = 1 << 50
if err := validatePlan(invalid); err != nil {
t.Fatalf("maximum supported capacity rejected: %v", err)
}
invalid.StorageBytes++
if err := validatePlan(invalid); err == nil {
t.Fatal("capacity above the supported maximum was accepted")
}
}
+59
View File
@@ -0,0 +1,59 @@
package httpapi
import (
"net/http"
"sea-vhost/internal/store"
"strconv"
"time"
)
func (s *Server) adminAudit(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
page, _ := strconv.Atoi(q.Get("page"))
if limit == 0 {
limit = 100
}
if page == 0 {
page = 1
}
if limit < 1 || limit > 500 || page < 1 || page > 100000 || len(q.Get("q")) > 200 || len(q.Get("action")) > 64 {
writeError(w, 422, "筛选范围无效")
return
}
maxID, e := strconv.ParseUint(q.Get("maxId"), 10, 64)
if q.Get("maxId") != "" && e != nil {
writeError(w, 422, "记录范围无效")
return
}
f := store.AuditFilter{MaxID: maxID, Query: q.Get("q"), Action: q.Get("action"), Result: q.Get("result"), Limit: limit, Page: page}
if f.Result != "" && f.Result != "success" && f.Result != "failure" {
writeError(w, 422, "结果筛选无效")
return
}
for _, field := range []string{"from", "to"} {
if value := q.Get(field); value != "" {
t, err := time.Parse(time.RFC3339, value)
if err != nil {
writeError(w, 422, "时间筛选无效")
return
}
if field == "from" {
f.From = &t
} else {
f.To = &t
}
}
}
if f.From != nil && f.To != nil && !f.From.Before(*f.To) {
writeError(w, 422, "结束时间必须晚于开始时间")
return
}
items, total, err := s.store.FilterAdminActivities(r.Context(), f)
if err != nil {
writeError(w, 500, "无法读取操作日志")
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, 200, map[string]any{"logs": items, "total": total, "page": page, "limit": limit})
}
+148
View File
@@ -0,0 +1,148 @@
package httpapi
import (
"crypto/sha256"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"sea-vhost/internal/auth"
"sea-vhost/internal/store"
)
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
started := time.Now()
var input struct {
Identifier string `json:"identifier"`
Email string `json:"email"`
Password string `json:"password"`
TOTPCode string `json:"totpCode"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
identifier := strings.TrimSpace(input.Identifier)
if identifier == "" {
identifier = strings.TrimSpace(input.Email)
}
identifier = strings.ToLower(identifier)
clientIP := requestClientIP(r)
ipKey := "ip:" + clientIP
now := time.Now()
if allowed, retryAfter := s.loginLimiter.allow(ipKey, now, loginIPBurst); !allowed {
writeLoginRateLimit(w, retryAfter)
return
}
validInput := len(identifier) >= 3 && len(identifier) <= 254 && len(input.Password) >= 1 && len(input.Password) <= 128
identifierKey := ""
if validInput {
digest := sha256.Sum256([]byte(identifier))
identifierKey = "identifier:" + clientIP + ":" + fmt.Sprintf("%x", digest[:12])
if allowed, retryAfter := s.loginLimiter.allow(identifierKey, now, loginIdentifierBurst); !allowed {
writeLoginRateLimit(w, retryAfter)
return
}
}
user, err := s.store.UserByLogin(r.Context(), identifier)
validPassword := validInput && err == nil && auth.VerifyPasswordConstantWork(user.PasswordHash, input.Password)
if err != nil || !validInput {
validPassword = auth.VerifyPasswordConstantWork("", input.Password) && validPassword
}
if !validPassword {
s.auditLoginFailure(r, user, identifier, "invalid_credentials")
minimumLoginDelay(started)
writeError(w, http.StatusUnauthorized, "账号、主机名或密码不正确")
return
}
if !oidcPasswordAllowed(s.readServiceConfig(r, "oidc_config"), user.Role) {
s.auditLoginFailure(r, user, identifier, "password_login_disabled")
minimumLoginDelay(started)
writeCodedError(w, 403, "password_login_disabled", "该类账号已关闭密码登录,请使用 SSO 登录")
return
}
if user.MFAEnabled {
security, securityErr := s.store.UserSecurity(r.Context(), user.ID)
if securityErr != nil {
writeError(w, http.StatusInternalServerError, "无法验证双重认证")
return
}
secret, openErr := s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext)
validSecondFactor := openErr == nil && auth.VerifyTOTP(secret, input.TOTPCode, time.Now())
if !validSecondFactor && strings.TrimSpace(input.TOTPCode) != "" {
validSecondFactor, securityErr = s.store.ConsumeRecoveryCode(r.Context(), user.ID, auth.RecoveryCodeHash(input.TOTPCode))
}
if securityErr != nil {
writeError(w, http.StatusInternalServerError, "无法验证双重认证")
return
}
if !validSecondFactor {
s.auditLoginFailure(r, user, identifier, "mfa_required")
minimumLoginDelay(started)
writeCodedError(w, http.StatusUnauthorized, "mfa_required", "请输入动态验证码或恢复码")
return
}
}
if err = s.issueSession(w, r, user); err != nil {
writeError(w, http.StatusInternalServerError, "无法创建会话")
return
}
s.clearImpersonation(w)
s.loginLimiter.reset(ipKey, identifierKey)
s.store.Log(r.Context(), user.TenantID, user.ID, "login", "session", "", clientIP, true, "登录 Sea vHost")
writeJSON(w, http.StatusOK, map[string]any{"user": user})
}
func (s *Server) issueSession(w http.ResponseWriter, r *http.Request, user store.User) error {
token, err := auth.NewSessionToken(s.cfg.SessionSecret)
if err != nil {
return err
}
expires := time.Now().Add(s.cfg.SessionTTL)
if err = s.store.CreateSession(r.Context(), user.ID, token, expires); err != nil {
return err
}
http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: token, Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, Expires: expires, MaxAge: int(s.cfg.SessionTTL.Seconds())})
return nil
}
func minimumLoginDelay(started time.Time) {
if remaining := 350*time.Millisecond - time.Since(started); remaining > 0 {
time.Sleep(remaining)
}
}
func (s *Server) auditLoginFailure(r *http.Request, user store.User, identifier, reason string) {
digest := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(identifier))))
resourceID := fmt.Sprintf("%x", digest[:12])
var userID *uint64
if user.ID != 0 {
userID = &user.ID
}
s.store.LogEvent(r.Context(), user.TenantID, userID, "login", "session", resourceID, requestClientIP(r), false, reason)
}
func writeLoginRateLimit(w http.ResponseWriter, retryAfter time.Duration) {
seconds := (retryAfter + time.Second - 1) / time.Second
if seconds < 1 {
seconds = 1
}
w.Header().Set("Retry-After", strconv.FormatInt(int64(seconds), 10))
writeError(w, http.StatusTooManyRequests, "登录尝试过于频繁,请稍后再试")
}
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
s.store.Log(r.Context(), user.TenantID, user.ID, "logout", "session", "", requestClientIP(r), true, "退出 Sea vHost")
if cookie, err := r.Cookie("sea_session"); err == nil {
_ = s.store.DeleteSession(r.Context(), cookie.Value)
}
http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1})
s.clearImpersonation(w)
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"user": currentUser(r)})
}
+81
View File
@@ -0,0 +1,81 @@
package httpapi
import (
"errors"
"net/http"
"strconv"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
func (s *Server) requestAutoCertificate(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
user := currentUser(r)
site, err := s.projects.RequestAutoCertificate(r.Context(), user, projectID, siteID)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "automatic_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "自动证书签发或部署失败")
switch {
case errors.Is(err, service.ErrQuotaSuspended):
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
case errors.Is(err, store.ErrNotFound):
writeError(w, http.StatusNotFound, "虚拟主机或网站不存在")
default:
writeError(w, http.StatusUnprocessableEntity, "自动证书申请失败,请确认全部已启用域名均已解析到本服务器,且公网可访问 80 端口")
}
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "automatic_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "自动证书已签发并部署到网站")
writeJSON(w, http.StatusOK, map[string]any{"site": site})
}
func (s *Server) installManualCertificate(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
var input struct {
Certificate string `json:"certificate"`
PrivateKey string `json:"privateKey"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
site, err := s.projects.InstallManualCertificate(r.Context(), user, projectID, siteID, input.Certificate, input.PrivateKey)
if err != nil {
// Deliberately record no certificate or private-key material. The resource
// id is enough to correlate this operation with broker/system logs.
s.store.Log(r.Context(), user.TenantID, user.ID, "install", "manual_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "手动证书校验或安装失败")
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "install", "manual_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "安装用户提供的网站证书并关闭自动续签")
writeJSON(w, http.StatusOK, map[string]any{"site": site})
}
func (s *Server) disableCertificate(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
user := currentUser(r)
site, err := s.projects.DisableCertificate(r.Context(), user, projectID, siteID)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "disable", "certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "关闭网站证书失败")
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "disable", "certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "关闭网站 SSL 与自动续签")
writeJSON(w, http.StatusOK, map[string]any{"site": site})
}
@@ -0,0 +1,79 @@
package httpapi
import (
"errors"
"net/http"
"sea-vhost/internal/store"
"strconv"
)
func (s *Server) deletePlan(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "套餐编号无效")
return
}
var input struct {
Confirmation string `json:"confirmation"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
err = s.store.DeleteUnusedPlan(r.Context(), id, input.Confirmation)
if err != nil {
status := 409
if errors.Is(err, store.ErrNotFound) {
status = 404
}
writeError(w, status, err.Error())
return
}
user := currentUser(r)
s.store.Log(r.Context(), nil, user.ID, "delete", "plan", strconv.FormatUint(id, 10), requestClientIP(r), true, "删除未使用套餐 "+input.Confirmation)
w.WriteHeader(204)
}
func (s *Server) unbindDomain(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "域名编号无效")
return
}
var input struct {
Confirmation string `json:"confirmation"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
// Authorize before revealing the name or validating confirmation.
user := currentUser(r)
item, err := s.store.DomainByID(r.Context(), id)
if err != nil {
writeError(w, 404, "域名不存在")
return
}
if user.Role != "admin" {
if _, err = s.store.ProjectForUser(r.Context(), user, item.ProjectID); err != nil {
writeError(w, 404, "域名不存在")
return
}
}
if input.Confirmation != item.Domain {
writeError(w, 422, "请准确输入要解绑的域名")
return
}
err = s.projects.UnbindDomain(r.Context(), user, id)
if err != nil {
status := 422
if errors.Is(err, store.ErrNotFound) {
status = 404
}
s.store.Log(r.Context(), &item.TenantID, user.ID, "unbind", "domain", item.Domain, requestClientIP(r), false, err.Error())
writeError(w, status, err.Error())
return
}
s.store.Log(r.Context(), &item.TenantID, user.ID, "unbind", "domain", item.Domain, requestClientIP(r), true, "解绑自定义域名,保留网站文件、数据库和其他域名")
w.WriteHeader(204)
}
+245
View File
@@ -0,0 +1,245 @@
package httpapi
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
func (s *Server) dnsCredentials(w http.ResponseWriter, r *http.Request) {
s.handleDNSCredentials(w, r, false)
}
func (s *Server) adminDNSCredentials(w http.ResponseWriter, r *http.Request) {
s.handleDNSCredentials(w, r, true)
}
func (s *Server) handleDNSCredentials(w http.ResponseWriter, r *http.Request, platform bool) {
user := currentUser(r)
switch r.Method {
case http.MethodGet:
items, err := s.projects.ListDNSCredentials(r.Context(), user, platform)
if err != nil {
writeError(w, http.StatusForbidden, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"credentials": items})
case http.MethodPost:
var input service.DNSCredentialInput
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
item, err := s.projects.SaveDNSCredential(r.Context(), user, platform, 0, input)
if err != nil {
writeDNSCredentialError(w, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "create", "dns_credential", strconv.FormatUint(item.ID, 10), requestClientIP(r), true, "新增加密 DNS 凭据 "+item.Provider+" / "+item.ZoneName)
writeJSON(w, http.StatusCreated, map[string]any{"credential": item})
default:
w.Header().Set("Allow", "GET, POST")
writeError(w, http.StatusMethodNotAllowed, "不支持的请求方法")
}
}
func (s *Server) dnsCredential(w http.ResponseWriter, r *http.Request) {
s.handleDNSCredential(w, r, false)
}
func (s *Server) adminDNSCredential(w http.ResponseWriter, r *http.Request) {
s.handleDNSCredential(w, r, true)
}
func (s *Server) testDNSCredential(w http.ResponseWriter, r *http.Request) {
s.handleTestDNSCredential(w, r, false)
}
func (s *Server) testAdminDNSCredential(w http.ResponseWriter, r *http.Request) {
s.handleTestDNSCredential(w, r, true)
}
func (s *Server) handleTestDNSCredential(w http.ResponseWriter, r *http.Request, platform bool) {
id, err := strconv.ParseUint(r.PathValue("credentialID"), 10, 64)
if err != nil || id == 0 {
writeError(w, http.StatusBadRequest, "凭据编号无效")
return
}
user := currentUser(r)
item, testErr := s.projects.TestDNSCredential(r.Context(), user, platform, id)
if testErr != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "test", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), false, "DNS 凭据连通性测试失败")
switch {
case errors.Is(testErr, store.ErrNotFound):
writeError(w, http.StatusNotFound, "DNS 凭据不存在")
case errors.Is(testErr, store.ErrDNSCredentialTestCooldown):
w.Header().Set("Retry-After", "60")
writeError(w, http.StatusTooManyRequests, "DNS 凭据刚刚测试过,请一分钟后重试")
default:
writeError(w, http.StatusUnprocessableEntity, testErr.Error())
}
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "test", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), true, "随机 TXT 记录已创建并按记录编号删除")
writeJSON(w, http.StatusOK, map[string]any{"credential": item})
}
func (s *Server) handleDNSCredential(w http.ResponseWriter, r *http.Request, platform bool) {
id, err := strconv.ParseUint(r.PathValue("credentialID"), 10, 64)
if err != nil || id == 0 {
writeError(w, http.StatusBadRequest, "凭据编号无效")
return
}
user := currentUser(r)
switch r.Method {
case http.MethodPut:
var input service.DNSCredentialInput
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
item, saveErr := s.projects.SaveDNSCredential(r.Context(), user, platform, id, input)
if saveErr != nil {
writeDNSCredentialError(w, saveErr)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "update", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), true, "替换加密 DNS 凭据 "+item.Provider+" / "+item.ZoneName)
writeJSON(w, http.StatusOK, map[string]any{"credential": item})
case http.MethodDelete:
if err = s.projects.DeleteDNSCredential(r.Context(), user, platform, id); err != nil {
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "DNS 凭据不存在")
return
}
if errors.Is(err, store.ErrDNSCredentialInUse) {
writeError(w, http.StatusConflict, "该凭据仍被托管 DNS 记录使用,请先删除对应解析记录")
return
}
writeError(w, http.StatusUnprocessableEntity, "删除 DNS 凭据失败")
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "delete", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), true, "删除 DNS 凭据;已签发证书不受影响")
w.WriteHeader(http.StatusNoContent)
default:
w.Header().Set("Allow", "PUT, DELETE")
writeError(w, http.StatusMethodNotAllowed, "不支持的请求方法")
}
}
func (s *Server) domainDNS(w http.ResponseWriter, r *http.Request) {
s.handleDomainDNS(w, r)
}
func (s *Server) adminDomainDNS(w http.ResponseWriter, r *http.Request) {
s.handleDomainDNS(w, r)
}
func (s *Server) handleDomainDNS(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil || id == 0 {
writeError(w, http.StatusBadRequest, "域名编号无效")
return
}
user := currentUser(r)
var item store.DomainResource
if r.Method == http.MethodPost {
item, err = s.projects.ProvisionDomainDNS(r.Context(), user, id)
} else if r.Method == http.MethodDelete {
item, err = s.projects.RemoveDomainDNS(r.Context(), user, id)
} else {
w.Header().Set("Allow", "POST, DELETE")
writeError(w, http.StatusMethodNotAllowed, "不支持的请求方法")
return
}
if err != nil {
status := http.StatusUnprocessableEntity
if errors.Is(err, store.ErrNotFound) {
status = http.StatusNotFound
}
s.store.Log(r.Context(), user.TenantID, user.ID, strings.ToLower(r.Method), "domain_dns", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error())
writeError(w, status, err.Error())
return
}
action := "创建"
if r.Method == http.MethodDelete {
action = "删除"
}
s.store.Log(r.Context(), user.TenantID, user.ID, strings.ToLower(r.Method), "domain_dns", strconv.FormatUint(id, 10), requestClientIP(r), true, action+"托管 CNAME 记录")
writeJSON(w, http.StatusOK, map[string]any{"domain": item})
}
func writeDNSCredentialError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrNotFound):
writeError(w, http.StatusNotFound, "DNS 凭据不存在")
case strings.Contains(err.Error(), "保存 DNS 凭据失败"):
writeError(w, http.StatusUnprocessableEntity, "该作用域下已存在相同 DNS 区域,或凭据保存失败")
case strings.Contains(err.Error(), "权限") || strings.Contains(err.Error(), "用户账号"):
writeError(w, http.StatusForbidden, err.Error())
default:
writeError(w, http.StatusUnprocessableEntity, err.Error())
}
}
func (s *Server) requestDNSCertificate(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
user := currentUser(r)
site, automation, err := s.projects.RequestDNSCertificate(r.Context(), user, projectID, siteID)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "dns_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "DNS-01 证书签发失败")
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "dns_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "DNS-01 证书已按域名路由签发并部署")
writeJSON(w, http.StatusOK, map[string]any{"site": site, "automation": automation})
}
func (s *Server) certificateAutomation(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
item, err := s.projects.CertificateAutomation(r.Context(), currentUser(r), projectID, siteID)
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "证书续期配置不存在")
return
}
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法读取证书续期状态")
return
}
writeJSON(w, http.StatusOK, map[string]any{"automation": item})
}
func (s *Server) discoverDNSZones(w http.ResponseWriter, r *http.Request) {
u := currentUser(r)
if allowed, _ := s.catalogLimiter.allow(fmt.Sprintf("dns-zones:%d", u.ID), time.Now(), 10); !allowed {
writeError(w, 429, "域名读取过于频繁,请稍后再试")
return
}
var input service.DNSCredentialInput
if decodeJSON(r, &input) != nil {
writeError(w, 400, "DNS 票据格式无效")
return
}
zones, err := s.projects.DiscoverDNSZones(r.Context(), u, u.Role == "admin", input)
if err != nil {
writeError(w, 422, err.Error())
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, 200, map[string]any{"zones": zones})
}
+102
View File
@@ -0,0 +1,102 @@
package httpapi
import (
"net/http"
"path/filepath"
"sea-vhost/internal/nodefiles"
"strings"
)
func (s *Server) fileActions(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, 400, "主机编号无效")
return
}
user := currentUser(r)
project, err := s.store.Project(r.Context(), *user.TenantID, id)
if err != nil {
writeError(w, 404, "主机不存在")
return
}
root, err := s.projects.OpenFiles(r.Context(), project.Path)
if err != nil {
writeError(w, 503, "文件服务不可用")
return
}
defer root.Close()
if r.Method == "GET" {
out, e := root.Action(nodefiles.Request{Operation: "trash_list"})
if e != nil {
writeError(w, 422, "无法读取回收站")
return
}
writeJSON(w, 200, map[string]any{"entries": out.Trash})
return
}
var input struct {
Action string `json:"action"`
Path string `json:"path"`
To string `json:"to"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "文件操作格式无效")
return
}
if !map[string]bool{"mkdir": true, "move": true, "copy": true, "zip": true, "extract": true, "restore": true}[input.Action] {
writeError(w, 422, "不支持此操作")
return
}
if input.Action != "restore" {
source, e := safeProjectName(project.Path, input.Path)
if e != nil || source == "." {
writeError(w, 400, "源路径无效")
return
}
input.Path = filepath.ToSlash(source)
if input.Action=="mkdir"{for _,part:=range strings.Split(input.Path,"/"){if strings.HasPrefix(part,".sea-")||part==".user.ini"{writeError(w,400,"不能创建系统保留目录");return}}}
}
if input.Action != "mkdir" {
dest, e := safeProjectName(project.Path, input.To)
if e != nil || dest == "." {
writeError(w, 400, "目标路径无效")
return
}
input.To = filepath.ToSlash(dest)
}
if input.Action == "move" {
sites, e := s.store.ListSites(r.Context(), project.TenantID, id)
if e != nil {
writeError(w, 503, "无法核对运行目录")
return
}
for _, site := range sites {
run := strings.TrimPrefix(site.RunPath, "/")
if run == input.Path || strings.HasPrefix(run, input.Path+"/") {
writeError(w, 409, "该目录仍被网站使用,请先修改网站运行目录")
return
}
}
}
if err = s.projects.CheckStorageWrite(r.Context(), project.TenantID, 0); err != nil {
writeFileQuotaError(w, err)
return
}
plan, usage, err := s.store.PlanAndUsage(r.Context(), project.TenantID)
if err != nil {
writeError(w, 503, "无法读取主机限额")
return
}
budget := uint64(0)
if usage.StorageBytes < plan.StorageBytes {
budget = plan.StorageBytes - usage.StorageBytes
}
_, err = root.Action(nodefiles.Request{Operation: input.Action, Path: input.Path, To: input.To, Budget: budget})
if err != nil {
writeError(w, 422, "文件操作未完成:目标必须不存在,路径须在主机目录内;复制/解压总量不得超过剩余空间及 256 MiB")
return
}
_ = s.projects.CheckStorageWrite(r.Context(), project.TenantID, 0)
s.logFile(r, project.TenantID, input.Action, "文件操作 "+input.Action+":"+input.Path)
w.WriteHeader(204)
}
+422
View File
@@ -0,0 +1,422 @@
package httpapi
import (
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
pathpkg "path"
"path/filepath"
"strconv"
"strings"
"time"
fileguard "sea-vhost/internal/files"
"sea-vhost/internal/nodefiles"
"sea-vhost/internal/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
type fileEntry struct {
Name string `json:"name"`
Path string `json:"path"`
Directory bool `json:"directory"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
func (s *Server) files(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "项目编号无效")
return
}
user := currentUser(r)
if user.ProjectID != nil && *user.ProjectID != id {
writeError(w, http.StatusNotFound, "项目不存在")
return
}
project, err := s.store.Project(r.Context(), *user.TenantID, id)
if err != nil {
writeError(w, http.StatusNotFound, "项目不存在")
return
}
if r.Method != http.MethodGet {
tracked := &fileAuditResponse{ResponseWriter: w}
w = tracked
defer func() {
if tracked.status >= 400 {
s.logFile(r, project.TenantID, "file_operation", fmt.Sprintf("文件操作失败(HTTP %d)", tracked.status))
}
}()
}
switch r.Method {
case http.MethodGet:
s.listFiles(w, r, project.Path)
case http.MethodPost:
s.uploadFile(w, r, project.TenantID, project.Path)
case http.MethodPut:
s.writeTextFile(w, r, project.TenantID, project.Path)
case http.MethodDelete:
s.trashFile(w, r, user, project.ID, project.TenantID, project.Path)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
type fileAuditResponse struct {
http.ResponseWriter
status int
}
func (w *fileAuditResponse) WriteHeader(status int) {
if w.status == 0 {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
}
func (w *fileAuditResponse) Write(body []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(body)
}
func (s *Server) logFile(r *http.Request, tenantID uint64, action, detail string) {
user := currentUser(r)
s.store.Log(r.Context(), &tenantID, user.ID, action, "file", strconv.FormatUint(scope.Project(r.Context()), 10), requestClientIP(r), action != "file_operation", detail)
}
func safeProjectPath(root, requested string) (string, error) {
path, err := fileguard.Resolve(root, requested)
if err != nil {
return "", err
}
if err = fileguard.RejectSymlinks(root, path); err != nil {
return "", err
}
return path, nil
}
func safeProjectName(root, requested string) (string, error) {
absolute, err := fileguard.Resolve(root, requested)
if err != nil {
return "", err
}
relative, err := filepath.Rel(root, absolute)
if err != nil {
return "", err
}
if relative == "." {
return ".", nil
}
virtualPath := filepath.ToSlash(relative)
if nodefiles.IsProtectedPath(virtualPath) {
return "", fileguard.ErrOutsideRoot
}
return relative, nil
}
func displayProjectName(name string) string {
if name == "." {
return ""
}
return filepath.ToSlash(name)
}
func (s *Server) listFiles(w http.ResponseWriter, r *http.Request, root string) {
requested := r.URL.Query().Get("path")
name, err := safeProjectName(root, requested)
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if r.URL.Query().Get("download") == "1" {
s.downloadFile(w, r, projectRoot, name)
return
}
directory, err := projectRoot.Open(name)
if err != nil {
writeError(w, http.StatusNotFound, "目录不存在")
return
}
defer directory.Close()
entries, err := directory.ReadDir(-1)
if err != nil {
writeError(w, http.StatusNotFound, "目录不存在")
return
}
result := make([]fileEntry, 0, len(entries))
for _, entry := range entries {
if nodefiles.IsProtectedPath(entry.Name()) {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
result = append(result, fileEntry{Name: entry.Name(), Path: displayProjectName(filepath.Join(name, entry.Name())), Directory: entry.IsDir(), Size: info.Size(), Modified: info.ModTime()})
}
writeJSON(w, http.StatusOK, map[string]any{"path": displayProjectName(name), "entries": result, "uploadLimit": s.cfg.UploadLimitBytes})
}
func (s *Server) downloadFile(w http.ResponseWriter, r *http.Request, root *nodefiles.Root, name string) {
file, err := root.Open(name)
if err != nil {
writeError(w, http.StatusNotFound, "文件不存在")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
writeError(w, http.StatusNotFound, "文件不存在")
return
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filepath.Base(name)))
http.ServeContent(w, r, filepath.Base(name), info.ModTime(), file)
}
func (s *Server) uploadFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadLimitBytes+1<<20)
if err := r.ParseMultipartForm(s.cfg.UploadLimitBytes); err != nil {
writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes))
return
}
if r.MultipartForm != nil {
defer r.MultipartForm.RemoveAll()
}
source, header, err := r.FormFile("file")
if err != nil {
writeError(w, http.StatusBadRequest, "缺少上传文件")
return
}
defer source.Close()
dir, err := safeProjectName(root, r.FormValue("path"))
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
name := filepath.Base(strings.ReplaceAll(header.Filename, "\\", "/"))
if name == "." || name == ".." || name == "" {
writeError(w, http.StatusBadRequest, "文件名无效")
return
}
target, err := safeProjectName(root, pathpkg.Join(dir, name))
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
if r.FormValue("overwrite") == "true" {
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if header.Size < 0 || header.Size > s.cfg.UploadLimitBytes {
writeError(w, http.StatusBadRequest, "无法确定上传文件大小")
return
}
additionalBytes := uint64(header.Size)
if r.FormValue("overwrite") == "true" {
if existing, statErr := projectRoot.Lstat(target); statErr == nil && existing.Mode().IsRegular() && existing.Size() > 0 {
oldSize := uint64(existing.Size())
if oldSize >= additionalBytes {
additionalBytes = 0
} else {
additionalBytes -= oldSize
}
}
}
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additionalBytes); err != nil {
writeFileQuotaError(w, err)
return
}
destination, err := projectRoot.OpenFile(target, flag, 0660)
if err != nil {
writeError(w, http.StatusConflict, "文件已存在或不可写")
return
}
defer destination.Abort()
written, err := io.Copy(destination, io.LimitReader(source, s.cfg.UploadLimitBytes+1))
if err != nil || written > s.cfg.UploadLimitBytes {
writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes))
return
}
if err = destination.Close(); err != nil {
writeFileCommitError(w, err)
return
}
s.logFile(r, tenantID, "upload", "上传文件:"+filepath.ToSlash(target))
writeJSON(w, http.StatusCreated, map[string]any{"name": name, "size": written})
}
func uploadLimitMessage(limit int64) string {
return fmt.Sprintf("单文件不能超过 %d MB", (limit+(1024*1024)-1)/(1024*1024))
}
func (s *Server) writeTextFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
var input struct {
Path string `json:"path"`
Content string `json:"content"`
Overwrite bool `json:"overwrite"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误或文本文件超过 1 MB")
return
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
path, err := safeProjectName(root, input.Path)
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
additionalBytes := uint64(len(input.Content))
if input.Overwrite {
if existing, statErr := projectRoot.Lstat(path); statErr == nil && existing.Mode().IsRegular() && existing.Size() > 0 {
oldSize := uint64(existing.Size())
if oldSize >= additionalBytes {
additionalBytes = 0
} else {
additionalBytes -= oldSize
}
}
}
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additionalBytes); err != nil {
writeFileQuotaError(w, err)
return
}
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
if input.Overwrite {
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
}
destination, err := projectRoot.OpenFile(path, flag, 0660)
if err != nil {
writeError(w, http.StatusConflict, "文件已存在或不可写")
return
}
defer destination.Abort()
if _, err = destination.Write([]byte(input.Content)); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法保存文件")
return
}
if err = destination.Close(); err != nil {
writeFileCommitError(w, err)
return
}
s.logFile(r, tenantID, "write", "保存文本文件:"+filepath.ToSlash(path))
w.WriteHeader(http.StatusNoContent)
}
func writeFileCommitError(w http.ResponseWriter, err error) {
if errors.Is(err, os.ErrExist) {
writeError(w, http.StatusConflict, "文件已存在,确认后才可覆盖")
return
}
writeError(w, http.StatusUnprocessableEntity, "文件提交失败,请刷新目录核对后再操作")
}
func writeFileQuotaError(w http.ResponseWriter, err error) {
if errors.Is(err, store.ErrManagementLocked) {
writeCodedError(w, 423, "management_locked", err.Error())
return
}
if errors.Is(err, store.ErrHostNotWritable) {
writeCodedError(w, http.StatusLocked, "host_not_writable", err.Error())
return
}
if errors.Is(err, service.ErrQuotaSuspended) {
writeCodedError(w, http.StatusLocked, "quota_suspended", "资源套餐已超额,当前仅允许读取或永久清理数据")
return
}
if errors.Is(err, service.ErrStorageQuotaExceeded) {
writeCodedError(w, http.StatusInsufficientStorage, "storage_quota_exceeded", "存储空间不足,请先永久删除文件或清空回收站")
return
}
slog.Warn("file quota verification unavailable", "error", err)
w.Header().Set("Retry-After", "3")
writeCodedError(w, http.StatusServiceUnavailable, "resource_check_unavailable", "暂时无法核对资源用量,请稍后重试")
}
func (s *Server) trashFile(w http.ResponseWriter, r *http.Request, user store.User, projectID, tenantID uint64, root string) {
if r.URL.Query().Get("emptyTrash") == "1" {
if err := s.projects.PrepareTrash(r.Context(), user, projectID); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法安全清空回收站")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if err = projectRoot.RemoveAll(".sea-trash"); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法清空回收站")
return
}
// Refresh immediately so a tenant that has cleaned enough data does not
// have to wait for the next one-minute monitor cycle.
_ = s.projects.CheckStorageWrite(r.Context(), tenantID, 0)
s.logFile(r, tenantID, "empty_trash", "清空主机回收站")
w.WriteHeader(http.StatusNoContent)
return
}
path, err := safeProjectName(root, r.URL.Query().Get("path"))
if err != nil || path == "." {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
path = filepath.ToSlash(path)
if path == ".sea-trash" || strings.HasPrefix(path, ".sea-trash/") {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
sites, err := s.store.ListSites(r.Context(), tenantID, projectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法核对网站运行目录")
return
}
candidate := "/" + strings.TrimPrefix(path, "/")
for _, site := range sites {
runPath := filepath.ToSlash(filepath.Clean(site.RunPath))
if candidate == runPath || strings.HasPrefix(runPath, candidate+"/") {
writeError(w, http.StatusConflict, "该目录仍被网站使用,请先删除或修改网站")
return
}
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if _, err = projectRoot.Action(nodefiles.Request{Operation: "trash", Path: path}); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法移动到回收站")
return
}
s.logFile(r, tenantID, "trash", "移入回收站:"+path)
w.WriteHeader(http.StatusNoContent)
}
+126
View File
@@ -0,0 +1,126 @@
package httpapi
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
fileguard "sea-vhost/internal/files"
"sea-vhost/internal/nodefiles"
"sea-vhost/internal/service"
)
func TestBufferedFileCommitConflictReturns409WithoutOverwriting(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "existing.txt")
if err := os.WriteFile(path, []byte("original-content"), 0600); err != nil {
t.Fatal(err)
}
root := nodefiles.New(context.Background(), "sv0123456789", func(_ context.Context, request nodefiles.Request) (nodefiles.Response, error) {
return nodefiles.Execute(dir, request), nil
})
file, err := root.OpenFile("existing.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
t.Fatal(err)
}
defer file.Abort()
if _, err = file.Write([]byte("unconfirmed-replacement")); err != nil {
t.Fatal(err)
}
err = file.Close()
if !errors.Is(err, os.ErrExist) {
t.Fatalf("expected a commit-time conflict, got %v", err)
}
response := httptest.NewRecorder()
writeFileCommitError(response, err)
if response.Code != http.StatusConflict {
t.Fatalf("commit conflict must be HTTP 409, got %d", response.Code)
}
data, err := os.ReadFile(path)
if err != nil || string(data) != "original-content" {
t.Fatalf("unconfirmed upload changed existing content: %v", err)
}
}
func TestFileCommitFailureDoesNotExposeInternalDetails(t *testing.T) {
response := httptest.NewRecorder()
writeFileCommitError(response, errors.New("private-path-and-diagnostic"))
if response.Code != http.StatusUnprocessableEntity || strings.Contains(response.Body.String(), "private-path-and-diagnostic") {
t.Fatalf("unsafe commit failure: %d %s", response.Code, response.Body.String())
}
}
func TestFileQuotaFailureRemainsClosedAndDoesNotExposeInternalError(t *testing.T) {
for _, test := range []struct {
err error
want int
}{
{service.ErrQuotaSuspended, http.StatusLocked},
{service.ErrStorageQuotaExceeded, http.StatusInsufficientStorage},
{errors.New("internal database diagnostic"), http.StatusServiceUnavailable},
} {
response := httptest.NewRecorder()
writeFileQuotaError(response, test.err)
if response.Code != test.want || strings.Contains(response.Body.String(), "internal database diagnostic") {
t.Fatalf("unsafe quota response: %d %s", response.Code, response.Body.String())
}
if test.want == http.StatusServiceUnavailable && response.Header().Get("Retry-After") != "3" {
t.Fatal("temporarily unavailable verification must indicate when to retry")
}
}
}
func TestSafeProjectNameRejectsAmbiguousAndInternalPaths(t *testing.T) {
root := t.TempDir()
for _, requested := range []string{
"../outside",
"public/../outside",
"public//index.html",
`.sea-trash`,
`.sea-trash/deleted.txt`,
} {
if _, err := safeProjectName(root, requested); !errors.Is(err, fileguard.ErrOutsideRoot) {
t.Errorf("safeProjectName(%q) error = %v, want ErrOutsideRoot", requested, err)
}
}
}
func TestProjectRootBlocksSymlinkSwapOutsideTenant(t *testing.T) {
base := t.TempDir()
root := filepath.Join(base, "project")
outside := filepath.Join(base, "outside.txt")
if err := os.Mkdir(root, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(outside, []byte("root-equivalent-secret"), 0600); err != nil {
t.Fatal(err)
}
victim := filepath.Join(root, "config.txt")
if err := os.WriteFile(victim, []byte("tenant-data"), 0640); err != nil {
t.Fatal(err)
}
name, err := safeProjectName(root, "config.txt")
if err != nil {
t.Fatal(err)
}
if err = os.Remove(victim); err != nil {
t.Fatal(err)
}
if err = os.Symlink(outside, victim); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
projectRoot, err := os.OpenRoot(root)
if err != nil {
t.Fatal(err)
}
defer projectRoot.Close()
if _, err = projectRoot.ReadFile(name); err == nil {
t.Fatal("directory-scoped file operation followed a swapped symlink outside the tenant root")
}
}
@@ -0,0 +1,3 @@
package httpapi
import("net/http";"strconv")
func(s *Server)manageFTP(w http.ResponseWriter,r *http.Request){id,_:=projectID(r);var input struct{Action string `json:"action"`};if decodeJSON(r,&input)!=nil{writeError(w,400,"操作格式无效");return};password,e:=s.projects.ManageFTP(r.Context(),currentUser(r),id,input.Action);u:=currentUser(r);s.store.Log(r.Context(),u.TenantID,u.ID,input.Action,"ftp",strconv.FormatUint(id,10),requestClientIP(r),e==nil,"管理主机 FTP:"+input.Action);if e!=nil{writeError(w,422,e.Error());return};writeJSON(w,200,map[string]any{"password":password})}
@@ -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")
}
}
+78
View File
@@ -0,0 +1,78 @@
package httpapi
import (
"context"
"net/http"
"sea-vhost/internal/auth"
"sea-vhost/internal/store"
"strconv"
"time"
)
const realAdministratorKey contextKey = "real_administrator"
const impersonationCookie = "sea_impersonation"
func (s *Server) startImpersonation(w http.ResponseWriter, r *http.Request) {
var input struct {
TenantID uint64 `json:"tenantId"`
ProjectID uint64 `json:"projectId"`
}
if decodeJSON(r, &input) != nil || (input.TenantID == 0) == (input.ProjectID == 0) {
writeError(w, 400, "请选择一个用户或主机")
return
}
target, err := s.store.ImpersonationTarget(r.Context(), input.TenantID, input.ProjectID)
if err != nil {
writeError(w, 404, "目标账号不存在或不可用")
return
}
parent, err := r.Cookie("sea_session")
if err != nil {
writeError(w, 401, "管理员登录已失效")
return
}
token, err := auth.NewSessionToken(s.cfg.SessionSecret)
if err != nil {
writeError(w, 500, "无法建立代入会话")
return
}
administrator := currentUser(r)
expires := time.Now().Add(30 * time.Minute)
if err = s.store.CreateImpersonation(r.Context(), parent.Value, token, administrator.ID, target.ID, expires); err != nil {
writeError(w, 500, "无法建立代入会话")
return
}
target, err = s.store.ImpersonationUser(r.Context(), parent.Value, token, administrator.ID)
if err != nil {
writeError(w, 500, "无法核对代入权限")
return
}
http.SetCookie(w, &http.Cookie{Name: impersonationCookie, Value: token, Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, Expires: *target.ImpersonationExpiresAt, MaxAge: int(time.Until(*target.ImpersonationExpiresAt).Seconds())})
s.store.Log(r.Context(), target.TenantID, administrator.ID, "start", "impersonation", strconv.FormatUint(target.ID, 10), requestClientIP(r), true, "管理员快捷进入 "+target.Role+" 账号 "+target.LoginName)
writeJSON(w, 200, map[string]any{"user": target})
}
func (s *Server) stopImpersonation(w http.ResponseWriter, r *http.Request) {
administrator, ok := r.Context().Value(realAdministratorKey).(store.User)
if !ok {
administrator = currentUser(r)
}
if administrator.Role != "admin" {
writeError(w, 403, "需要原管理员会话")
return
}
parent, _ := r.Cookie("sea_session")
child, _ := r.Cookie(impersonationCookie)
if parent != nil && child != nil {
if err := s.store.StopImpersonation(r.Context(), parent.Value, child.Value); err != nil {
writeError(w, 500, "无法退出代入会话")
return
}
}
s.clearImpersonation(w)
s.store.Log(context.WithoutCancel(r.Context()), nil, administrator.ID, "stop", "impersonation", "", requestClientIP(r), true, "管理员退出代入模式")
writeJSON(w, 200, map[string]any{"user": administrator})
}
func (s *Server) clearImpersonation(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: impersonationCookie, Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1})
}
@@ -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)
}
}
+210
View File
@@ -0,0 +1,210 @@
package httpapi
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"sea-vhost/internal/scope"
"sea-vhost/internal/store"
"slices"
"strconv"
"strings"
"time"
)
const integrationKeyContext contextKey = "integration-key"
var integrationScopes = []string{"users:read", "users:write", "hosts:read", "hosts:write", "tasks:read", "credentials:read"}
func tokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func (s *Server) adminIntegrationKeys(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
rows, e := s.store.IntegrationKeys(r.Context())
if e != nil {
writeError(w, 503, "无法读取 API 密钥")
return
}
deliveries, e := s.store.IntegrationWebhooks(r.Context(), false)
if e != nil {
writeError(w, 503, "无法读取回调记录")
return
}
writeJSON(w, 200, map[string]any{"keys": rows, "scopes": integrationScopes, "webhooks": deliveries})
return
}
u := currentUser(r)
if r.Method == "DELETE" {
id, _ := strconv.ParseUint(r.PathValue("keyID"), 10, 64)
if e := s.store.RevokeIntegrationKey(r.Context(), id); e != nil {
writeError(w, 503, "吊销失败")
return
}
s.store.Log(r.Context(), nil, u.ID, "revoke", "integration_key", fmt.Sprint(id), requestClientIP(r), true, "吊销管理端 API 密钥")
w.WriteHeader(204)
return
}
var input struct {
Name string `json:"name"`
Scopes []string `json:"scopes"`
ExpiresAt time.Time `json:"expiresAt"`
WebhookURL string `json:"webhookURL"`
}
if decodeJSON(r, &input) != nil || strings.TrimSpace(input.Name) == "" || len(input.Name) > 120 || len(input.Scopes) < 1 || len(input.Scopes) > len(integrationScopes) || !input.ExpiresAt.After(time.Now()) || input.ExpiresAt.After(time.Now().AddDate(1, 0, 0)) {
writeError(w, 400, "名称、权限或有效期无效;有效期最长一年")
return
}
for _, v := range input.Scopes {
if !slices.Contains(integrationScopes, v) {
writeError(w, 400, "权限范围无效")
return
}
}
if input.WebhookURL != "" {
if _, e := validateWebhookURL(input.WebhookURL); e != nil {
writeError(w, 422, e.Error())
return
}
}
raw := make([]byte, 32)
if _, e := rand.Read(raw); e != nil {
writeError(w, 500, "无法生成密钥")
return
}
token := "svh_live_" + hex.EncodeToString(raw)
prefix := token[:21]
secret := ""
var cipher []byte
if input.WebhookURL != "" {
if _, e := rand.Read(raw); e != nil {
writeError(w, 500, "无法生成回调密钥")
return
}
secret = hex.EncodeToString(raw)
var e error
cipher, e = s.secretBox.Seal("integration-webhook:"+prefix, secret)
if e != nil {
writeError(w, 500, "无法保存回调密钥")
return
}
}
id, e := s.store.CreateIntegrationKey(r.Context(), store.IntegrationKey{AdministratorID: u.ID, Name: input.Name, Prefix: prefix, Scopes: input.Scopes, ExpiresAt: input.ExpiresAt, WebhookURL: input.WebhookURL, WebhookSecret: cipher}, tokenHash(token))
if e != nil {
writeError(w, 503, "无法保存 API 密钥")
return
}
s.store.Log(r.Context(), nil, u.ID, "create", "integration_key", fmt.Sprint(id), requestClientIP(r), true, "签发管理端 API 密钥")
writeJSON(w, 201, map[string]any{"id": id, "token": token, "webhookSecret": secret})
}
func (s *Server) requireIntegration(scopeName string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, "Bearer ") || len(header) != len("Bearer svh_live_")+64 {
writeError(w, 401, "需要管理端 API 密钥")
return
}
key, e := s.store.IntegrationKeyByToken(r.Context(), tokenHash(strings.TrimPrefix(header, "Bearer ")))
if e != nil {
writeError(w, 401, "API 密钥无效、过期或已吊销")
return
}
if !slices.Contains(key.Scopes, scopeName) {
writeError(w, 403, "API 密钥缺少权限:"+scopeName)
return
}
u, e := s.store.UserByID(r.Context(), key.AdministratorID)
if e != nil || u.Role != "admin" {
writeError(w, 401, "管理账号已失效")
return
}
s.store.TouchIntegrationKey(r.Context(), key.ID)
ctx := context.WithValue(context.WithValue(r.Context(), userKey, u), integrationKeyContext, key)
ctx = scope.WithIntegrationKey(ctx, key.ID)
next(w, r.WithContext(ctx))
}
}
func (s *Server) integrationList(w http.ResponseWriter, r *http.Request) {
if r.PathValue("resource") == "users" {
rows, e := s.store.ListTenants(r.Context())
if e != nil {
writeError(w, 503, "无法读取用户")
return
}
writeJSON(w, 200, map[string]any{"users": rows})
return
}
rows, e := s.store.ListAdminProjects(r.Context())
if e != nil {
writeError(w, 503, "无法读取主机")
return
}
writeJSON(w, 200, map[string]any{"hosts": rows})
}
func (s *Server) integrationWrite(w http.ResponseWriter, r *http.Request) {
key := r.Context().Value(integrationKeyContext).(store.IntegrationKey)
idempotency := r.Header.Get("Idempotency-Key")
if len(idempotency) < 8 || len(idempotency) > 128 || strings.ContainsAny(idempotency, "\x00\r\n") {
writeError(w, 400, "写请求必须提供 8–128 字节的 Idempotency-Key")
return
}
var input struct {
Operation string `json:"operation"`
Rows []batchRow `json:"rows"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式无效")
return
}
kind := r.PathValue("resource")
if kind == "users" {
if input.Operation == "" {
input.Operation = "create_users"
}
if !slices.Contains([]string{"create_users", "user_enable", "user_disable"}, input.Operation) {
writeError(w, 403, "用户接口不支持此操作")
return
}
} else {
if input.Operation == "" {
input.Operation = "create_hosts"
}
if !slices.Contains([]string{"create_hosts", "assign_hosts", "host_subscription", "host_start", "host_stop", "host_password_reset"}, input.Operation) {
writeError(w, 403, "主机接口不支持此操作")
return
}
}
sum := sha256.Sum256([]byte(fmt.Sprintf("integration:%d:%s", key.ID, idempotency)))
raw, _ := json.Marshal(batchRequest{RequestKey: hex.EncodeToString(sum[:16]), Operation: input.Operation, Rows: input.Rows})
r.Body = io.NopCloser(bytes.NewReader(raw))
r.ContentLength = int64(len(raw))
s.adminBatches(w, r)
}
func (s *Server) integrationTask(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
key := r.Context().Value(integrationKeyContext).(store.IntegrationKey)
owner, e := s.store.BatchIntegrationKey(r.Context(), id)
if e != nil || owner != key.ID {
writeError(w, 404, "任务不存在")
return
}
if strings.HasSuffix(r.URL.Path, "/download") {
s.adminBatchDownload(w, r)
} else {
s.adminBatch(w, r)
}
}
func webhookSignature(secret, stamp, event string, body []byte) string {
mac := hmac.New(sha256.New, []byte(secret))
fmt.Fprintf(mac, "%s.%s.", stamp, event)
mac.Write(body)
return hex.EncodeToString(mac.Sum(nil))
}
@@ -0,0 +1,49 @@
package httpapi
import "net/http"
const integrationAPIDocs = `# Sea vHost 管理端对接 API v1
管理端“对接 API”签发密钥。请求头:Authorization: Bearer <token>。
不使用浏览器登录 Cookie。所有请求与返回均为 JSON。
GET /api/integration/v1/users(users:read)
GET /api/integration/v1/hosts(hosts:read)
POST /api/integration/v1/users(users:write)
POST /api/integration/v1/hosts(hosts:write)
GET /api/integration/v1/tasks/{id}(tasks:read)
GET /api/integration/v1/tasks/{id}/download(credentials:read)
写入必须带 Idempotency-Key: <8–128 字节的唯一标识>。相同密钥和标识重试返回原任务;数据不同返回 409。
POST 返回 202 {"batch":{"id":123,...}};主控后台执行,可轮询 tasks/{id}。
任务仅能由提交该任务的 API 密钥读取。吊销、过期后无法调用,队列剩余条目停止;已开始的操作会完成并保存结果。
请求示例:
{"operation":"create_users","rows":[{"slug":"customer01","name":"客户一","email":"user@example.com"}]}
{"operation":"create_hosts","rows":[{"name":"站点一","tenantId":123,"nodeId":1,"planId":1,"runtime":"PHP","version":"8.4","runPath":"/public","autoSSL":false}]}
密码留空独立随机生成。tenantId 为 0 时不绑定用户,仍可使用独立主机账号。
用户操作:create_users / user_enable / user_disable。
主机操作:create_hosts / assign_hosts / host_subscription / host_start / host_stop / host_password_reset。
批量最多:用户 100;主机创建 50;管理 200。
管理 rows 使用 hostId,建议包含查询返回的 ownershipVersion,避免误操作已转移主机。
assign_hosts: tenantId(0 解绑)、credentialMode(preserve/reset)、stopServices(默认 true)。
host_subscription: planId、setExpiry:true、expiresAt(RFC3339 或 null,null 为长期)。
user_enable/user_disable: accountId 为用户归属账号编号。
所有操作拒绝任意宝塔 API、系统路径或 shell 命令。
下载为 sea-vhost.batch-result v1 JSON;凭据结果仅保留 24 小时。
回调不包含密码或输入,仅有批次状态与成功/失败计数。
回调请求:POST HTTPS 地址(443),禁止内网与保留地址,禁止重定向。
X-Sea-Event: 唯一事件 ID;X-Sea-Timestamp: Unix 秒;
X-Sea-Signature: sha256=<HMAC-SHA256 十六进制>。
签名内容:timestamp + "." + eventId + "." + 原始 JSON 字节。
使用创建时显示的独立 webhookSecret,验证时间偏差不超过 5 分钟,以事件 ID 去重。
回调有至少一次投递语义;返回 2xx 确认。重试间隔 1/2/4/8/16/32/64 分钟,总计最多 8 次。
吊销或过期后停止投递。`
func integrationDocs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte(integrationAPIDocs))
}
@@ -0,0 +1,136 @@
package httpapi
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"sea-vhost/internal/store"
"strconv"
"strings"
"time"
)
func validateWebhookURL(raw string) (*url.URL, error) {
u, e := url.Parse(raw)
if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Port() != "" && u.Port() != "443") || len(raw) > 2048 || strings.ContainsAny(raw, "\r\n\x00") {
return nil, errors.New("回调地址必须为 HTTPS 公网地址,端口为 443,不能包含凭据或查询参数")
}
if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicWebhookIP(ip) {
return nil, errors.New("回调禁止使用内网或保留地址")
}
if strings.EqualFold(u.Hostname(), "localhost") {
return nil, errors.New("回调禁止使用本机地址")
}
return u, nil
}
func publicWebhookIP(ip netip.Addr) bool {
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return false
}
for _, cidr := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "2001::/32", "2002::/16"} {
if netip.MustParsePrefix(cidr).Contains(ip) {
return false
}
}
return true
}
func webhookClient(ctx context.Context, u *url.URL) (*http.Client, error) {
resolved, e := net.DefaultResolver.LookupNetIP(ctx, "ip", u.Hostname())
if e != nil || len(resolved) == 0 {
return nil, errors.New("DNS unavailable")
}
for _, ip := range resolved {
if !publicWebhookIP(ip) {
return nil, errors.New("DNS resolved to a restricted address")
}
}
transport := &http.Transport{Proxy: nil, TLSClientConfig: &tls.Config{ServerName: u.Hostname(), MinVersion: tls.VersionTLS12}, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
var last error
for _, ip := range resolved {
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), "443"))
if e == nil {
return conn, nil
}
last = e
}
return nil, last
}}
return &http.Client{Transport: transport, Timeout: 12 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, nil
}
func (s *Server) runIntegrationWebhooks(ctx context.Context) {
for ctx.Err() == nil {
_ = s.store.QueueIntegrationWebhooks(ctx)
rows, e := s.store.IntegrationWebhooks(ctx, true)
if e == nil {
for _, v := range rows {
if ctx.Err() != nil {
return
}
s.deliverIntegrationWebhook(ctx, v)
}
}
select {
case <-ctx.Done():
return
case <-time.After(30 * time.Second):
}
}
}
func (s *Server) deliverIntegrationWebhook(ctx context.Context, v store.IntegrationWebhook) {
task, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
delivered := false
status := 0
defer func() {
done, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = s.store.FinishIntegrationWebhook(done, v, delivered, status)
}()
u, e := validateWebhookURL(v.URL)
if e != nil {
return
}
secret, e := s.secretBox.Open("integration-webhook:"+v.Prefix, v.Secret)
if e != nil {
return
}
job, e := s.store.AdminBatch(task, v.BatchID, false)
if e != nil {
return
}
job.Items = nil
body, _ := json.Marshal(map[string]any{"event": "batch.completed", "eventId": v.EventID, "batch": job})
stamp := strconv.FormatInt(time.Now().Unix(), 10)
client, e := webhookClient(task, u)
if e != nil {
return
}
defer client.CloseIdleConnections()
request, e := http.NewRequestWithContext(task, "POST", v.URL, bytes.NewReader(body))
if e != nil {
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Sea-Event", v.EventID)
request.Header.Set("X-Sea-Timestamp", stamp)
request.Header.Set("X-Sea-Signature", "sha256="+webhookSignature(secret, stamp, v.EventID, body))
if !s.store.IntegrationKeyActive(task, v.KeyID) {
return
}
response, e := client.Do(request)
if e != nil {
return
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
status = response.StatusCode
delivered = status >= 200 && status < 300
}
@@ -0,0 +1,30 @@
package httpapi
import (
"net/netip"
"testing"
)
func TestWebhookNetworkRestrictions(t *testing.T) {
for _, raw := range []string{"http://example.com/callback", "https://127.0.0.1/cb", "https://[::1]/cb", "https://[::ffff:127.0.0.1]/cb", "https://10.0.0.1/cb", "https://100.64.1.2/cb", "https://169.254.169.254/latest", "https://user:password@example.com/cb", "https://example.com:9443/cb", "https://example.com/cb?token=secret", "https://localhost/cb"} {
if _, e := validateWebhookURL(raw); e == nil {
t.Fatalf("accepted unsafe callback %q", raw)
}
}
if _, e := validateWebhookURL("https://billing.example.com/callback"); e != nil {
t.Fatal(e)
}
for _, ip := range []string{"192.168.1.2", "0.0.0.0", "224.0.0.1", "198.18.0.1", "2001:db8::1", "fc00::1"} {
if publicWebhookIP(netip.MustParseAddr(ip)) {
t.Fatalf("accepted %s", ip)
}
}
}
func TestWebhookSignatureBindsTimeEventAndExactBody(t *testing.T) {
signature := webhookSignature("secret", "100", "event", []byte(`{"id":1}`))
for _, s := range []string{webhookSignature("other", "100", "event", []byte(`{"id":1}`)), webhookSignature("secret", "101", "event", []byte(`{"id":1}`)), webhookSignature("secret", "100", "another", []byte(`{"id":1}`)), webhookSignature("secret", "100", "event", []byte(`{ "id":1}`))} {
if signature == s {
t.Fatal("signature failed to bind request")
}
}
}
+32
View File
@@ -0,0 +1,32 @@
package httpapi
import (
"encoding/json"
"errors"
"io"
"net/http"
)
func decodeJSON(r *http.Request, destination any) error {
decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return err
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("request body must contain one JSON object")
}
return nil
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]any{"error": map[string]string{"message": message}})
}
func writeCodedError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
}
+55
View File
@@ -0,0 +1,55 @@
package httpapi
import (
"net/http"
"sea-vhost/internal/scope"
"strconv"
"strings"
)
func (s *Server) adminNodeTasks(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
if err != nil || id < 2 {
writeError(w, 400, "远程节点编号无效")
return
}
items, err := s.store.ControlTasks(r.Context(), id)
if err != nil {
writeError(w, 500, "无法读取节点执行记录")
return
}
writeJSON(w, 200, map[string]any{"tasks": items})
}
func (s *Server) adminResolveNodeTask(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
task, e := strconv.ParseUint(r.PathValue("taskID"), 10, 64)
if err != nil || e != nil {
writeError(w, 400, "任务编号无效")
return
}
var input struct {
Note string `json:"note"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
if err = s.store.ResolveControlTask(r.Context(), id, task, strings.TrimSpace(input.Note)); err != nil {
writeError(w, 422, err.Error())
return
}
s.store.Log(r.Context(), nil, currentUser(r).ID, "reconcile", "node_task", strconv.FormatUint(task, 10), requestClientIP(r), true, input.Note)
w.WriteHeader(204)
}
func (s *Server) adminReconcileNode(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
if err != nil {
writeError(w, 400, "节点编号无效")
return
}
if err = s.projects.ReconcileNodeIdentities(scope.WithNode(r.Context(), id)); err != nil {
writeError(w, 422, err.Error())
return
}
w.WriteHeader(204)
}
+232
View File
@@ -0,0 +1,232 @@
package httpapi
import (
"errors"
"net/http"
"path"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
"strconv"
"strings"
"time"
)
func (s *Server) adminNodes(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
items, err := s.store.Nodes(r.Context())
if err != nil {
writeError(w, 500, "无法读取节点")
return
}
writeJSON(w, 200, map[string]any{"nodes": items})
return
}
var input store.Node
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
normalizeNodeMetadata(&input)
if err := validateNodeMetadata(input, false); err != nil {
writeError(w, 422, err.Error())
return
}
id, err := s.store.CreateNode(r.Context(), input)
if err != nil {
writeError(w, 422, "无法新增节点,请检查地址是否重复")
return
}
s.resourceAudit(r, "create", "node", id, nil, "新增节点 "+input.Name)
writeJSON(w, 201, map[string]any{"id": id})
}
func validNodeDomain(s string) bool {
if len(s) > 253 {
return false
}
for _, p := range strings.Split(s, ".") {
if len(p) < 1 || len(p) > 63 || p[0] == '-' || p[len(p)-1] == '-' {
return false
}
for _, c := range p {
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
return false
}
}
}
return strings.Contains(s, ".")
}
func nodeID(r *http.Request) (uint64, error) { return strconv.ParseUint(r.PathValue("nodeID"), 10, 64) }
func (s *Server) adminPairNode(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
if err != nil || id < 2 {
writeError(w, 400, "请选择远程节点")
return
}
if s.cluster == nil {
writeError(w, 503, "节点管理未初始化")
return
}
identity, err := s.cluster.Pair(r.Context(), id)
if err != nil {
writeError(w, 422, "无法生成节点配对材料")
return
}
node, _ := s.store.Node(r.Context(), id)
s.store.Log(r.Context(), nil, currentUser(r).ID, "pair", "node", strconv.FormatUint(id, 10), requestClientIP(r), true, "重新签发节点身份,节点已停用,部署后需探测启用")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Disposition", "attachment; filename=sea-node-config.json")
writeJSON(w, 200, map[string]any{"identity": identity, "address": ":9443", "tenantRoot": node.TenantRoot, "brokerSocket": "/run/sea-vhost-panel/broker.sock", "agentSocket": "/run/sea-vhost/agent.sock"})
}
func (s *Server) adminProbeNode(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
if err != nil || s.cluster == nil {
writeError(w, 400, "节点编号无效")
return
}
if err = s.cluster.Probe(r.Context(), id); err != nil {
writeError(w, 502, err.Error())
return
}
w.WriteHeader(204)
}
func (s *Server) adminNode(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
if err != nil {
writeError(w, 400, "节点编号无效")
return
}
var input struct {
Enabled bool `json:"enabled"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
if id == 1 && input.Enabled && s.cfg.ControllerOnly {
writeError(w, 422, "独立主控不提供本机托管功能,请新增被控节点")
return
}
if input.Enabled && id != 1 {
if s.cluster == nil {
writeError(w, 503, "节点管理未初始化")
return
}
if err = s.cluster.Probe(r.Context(), id); err != nil {
writeError(w, 422, "双向 TLS 和节点身份探测通过后才能启用")
return
}
}
existing, lookupErr := s.store.Node(r.Context(), id)
if lookupErr != nil {
writeError(w, 404, "节点不存在")
return
}
if existing.Enabled == input.Enabled {
w.WriteHeader(204)
return
}
if s.store.SetNodeEnabled(r.Context(), id, input.Enabled) != nil {
writeError(w, 422, "无法更新节点状态")
return
}
if input.Enabled {
nodeCtx := scope.WithNode(r.Context(), id)
blocked, checkErr := s.store.RuntimeMutationBlocked(nodeCtx)
if checkErr != nil {
writeError(w, 500, "无法核对节点维护状态")
return
}
if !blocked {
if err = s.projects.ReconcileNodeIdentities(nodeCtx); err != nil {
_ = s.store.SetNodeEnabled(r.Context(), id, false)
writeError(w, 422, "节点已连接,但主机身份核验未通过:"+err.Error())
return
}
}
}
w.WriteHeader(204)
}
func (s *Server) adminCreateHost(w http.ResponseWriter, r *http.Request) {
var input struct {
TenantID uint64 `json:"tenantId"`
NodeID uint64 `json:"nodeId"`
PlanID uint64 `json:"planId"`
Name string `json:"name"`
Runtime string `json:"runtime"`
Version string `json:"version"`
RunPath string `json:"runPath"`
CustomDomain string `json:"customDomain"`
AutoSSL bool `json:"autoSSL"`
ExpiresAt *time.Time `json:"expiresAt"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
ctx := scope.WithNode(r.Context(), input.NodeID)
release, err := s.projects.BeginRuntimeMutation(ctx)
if err != nil {
writeError(w, 423, err.Error())
return
}
defer release()
result, err := s.projects.CreateManagedHost(ctx, input.TenantID, service.CreateProjectInput{NodeID: input.NodeID, PlanID: input.PlanID, Name: input.Name, Runtime: input.Runtime, Version: input.Version, RunPath: input.RunPath, CustomDomain: input.CustomDomain, AutoSSL: input.AutoSSL})
if err != nil {
writeError(w, 422, err.Error())
return
}
if err = s.store.SetHostSubscription(r.Context(), result.Project.ID, input.PlanID, input.ExpiresAt); err != nil {
writeError(w, 500, "主机已创建,但到期设置保存失败,请在主机管理中重新设置")
return
}
s.store.Log(scope.WithProject(r.Context(), result.Project.ID, result.Project.NodeID), &result.Project.TenantID, currentUser(r).ID, "create", "project", strconv.FormatUint(result.Project.ID, 10), requestClientIP(r), true, "管理员开通主机")
writeJSON(w, 201, result)
}
func (s *Server) adminHostSubscription(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, 400, "主机编号无效")
return
}
var input struct {
PlanID uint64 `json:"planId"`
ExpiresAt *time.Time `json:"expiresAt"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil {
writeError(w, 422, "套餐不存在")
return
}
if err = s.projects.ApplyHostSubscription(r.Context(), id, input.PlanID, input.ExpiresAt); err != nil {
s.store.Log(r.Context(), nil, currentUser(r).ID, "update", "host_subscription", strconv.FormatUint(id, 10), requestClientIP(r), false, "主机套餐或身份核验未完成")
writeError(w, 422, "套餐保存或节点身份核验未完成:"+err.Error())
return
}
s.store.Log(r.Context(), nil, currentUser(r).ID, "update", "host_subscription", strconv.FormatUint(id, 10), requestClientIP(r), true, "更新主机套餐与到期时间")
w.WriteHeader(204)
}
func normalizeNodeMetadata(n *store.Node) {
n.Name = strings.TrimSpace(n.Name)
n.RootDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(n.RootDomain), "."))
n.FTPCertificateDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(n.FTPCertificateDomain), "."))
}
func validateNodeMetadata(n store.Node, local bool) error {
if !local {
if _, err := controlwire.ValidateEndpoint(n.Endpoint); err != nil {
return err
}
} else if n.Endpoint != "local" {
return errors.New("本机执行入口不可修改")
}
if n.Name == "" || len([]rune(n.Name)) > 80 || strings.ContainsAny(n.Name, "\x00\r\n") || !validNodeDomain(n.RootDomain) || !validNodeDomain(n.FTPCertificateDomain) || !path.IsAbs(n.TenantRoot) || path.Clean(n.TenantRoot) != n.TenantRoot || !strings.HasPrefix(n.TenantRoot, "/www/wwwroot/") || len(n.TenantRoot) > 500 || strings.ContainsAny(n.TenantRoot, "\\\x00\r\n") {
return errors.New("节点名称、域名或主机根目录无效")
}
return nil
}
+272
View File
@@ -0,0 +1,272 @@
package httpapi
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"net/http"
"net/url"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
"sea-vhost/internal/auth"
"sea-vhost/internal/store"
)
const oidcProviderName = "oidc"
func (s *Server) oidcStatus(w http.ResponseWriter, r *http.Request) {
cfg := s.readServiceConfig(r, "oidc_config")
writeJSON(w, http.StatusOK, map[string]any{"enabled": validOIDCConfig(cfg), "autoCreate": cfg.AutoCreate, "userPasswordLogin": oidcPasswordAllowed(cfg, "tenant"), "adminPasswordLogin": oidcPasswordAllowed(cfg, "admin"), "hostPasswordLogin": true})
}
func (s *Server) oidcStart(w http.ResponseWriter, r *http.Request) {
if _, err := r.Cookie(impersonationCookie); err == nil {
writeError(w, 403, "请先退出代入模式再进行第三方登录或绑定")
return
}
cfg := s.readServiceConfig(r, "oidc_config")
if !validOIDCConfig(cfg) {
writeError(w, http.StatusServiceUnavailable, "OIDC 登录尚未启用")
return
}
mode := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("mode")))
if mode == "" {
mode = "login"
}
var userID *uint64
var parentSession string
if mode == "bind" {
cookie, err := r.Cookie("sea_session")
if err != nil {
writeError(w, http.StatusUnauthorized, "请先使用密码登录后绑定")
return
}
user, err := s.userFromToken(r.Context(), cookie.Value)
if err != nil {
writeError(w, http.StatusUnauthorized, "登录已失效")
return
}
if user.Role == "host" {
writeError(w, 403, "主机账号不可绑定 SSO")
return
}
userID = &user.ID
parentSession = cookie.Value
} else if mode != "login" {
writeError(w, http.StatusBadRequest, "OIDC 模式无效")
return
}
provider, oauth, err := oidcClient(r.Context(), cfg)
if err != nil {
writeError(w, http.StatusBadGateway, "无法连接 OIDC 服务")
return
}
_ = provider
state, err := randomURLToken(32)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法创建 OIDC 状态")
return
}
verifier, err := randomURLToken(48)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法创建 OIDC 校验参数")
return
}
nonce, err := randomURLToken(32)
if err != nil || s.store.CreateScopedOIDCState(r.Context(), state, userID, mode, verifier, nonce, oidcProviderKey(cfg), parentSession, time.Now().Add(10*time.Minute)) != nil {
writeError(w, http.StatusInternalServerError, "无法保存 OIDC 状态")
return
}
challenge := sha256.Sum256([]byte(verifier))
authorizationURL := oauth.AuthCodeURL(state,
oidc.Nonce(nonce),
oauth2.SetAuthURLParam("code_challenge", base64.RawURLEncoding.EncodeToString(challenge[:])),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
setOIDCCookie(w, "sea_oidc_flow", state, 600)
writeJSON(w, http.StatusOK, map[string]string{"url": authorizationURL})
}
func (s *Server) oidcCallback(w http.ResponseWriter, r *http.Request) {
if _, err := r.Cookie(impersonationCookie); err == nil {
writeError(w, 403, "请先退出代入模式再进行第三方登录或绑定")
return
}
stateValue := strings.TrimSpace(r.URL.Query().Get("state"))
code := strings.TrimSpace(r.URL.Query().Get("code"))
if stateValue == "" || code == "" || len(stateValue) > 256 || len(code) > 4096 {
redirectOIDCResult(w, r, "error")
return
}
flow, flowErr := r.Cookie("sea_oidc_flow")
if flowErr != nil || flow.Value != stateValue {
redirectOIDCResult(w, r, "expired")
return
}
setOIDCCookie(w, "sea_oidc_flow", "", -1)
state, err := s.store.ConsumeOIDCState(r.Context(), stateValue)
if err != nil {
redirectOIDCResult(w, r, "expired")
return
}
cfg := s.readServiceConfig(r, "oidc_config")
if state.ProviderKey != oidcProviderKey(cfg) {
redirectOIDCResult(w, r, "provider_changed")
return
}
if state.Mode == "bind" && state.UserID != nil && !s.store.ActiveOIDCBindSession(r.Context(), state.SessionHash, *state.UserID) {
redirectOIDCResult(w, r, "expired")
return
}
provider, oauth, err := oidcClient(r.Context(), cfg)
if err != nil {
redirectOIDCResult(w, r, "provider")
return
}
token, err := oauth.Exchange(r.Context(), code, oauth2.SetAuthURLParam("code_verifier", state.Verifier))
if err != nil {
redirectOIDCResult(w, r, "exchange")
return
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok || rawIDToken == "" {
redirectOIDCResult(w, r, "token")
return
}
idToken, err := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID}).Verify(r.Context(), rawIDToken)
if err != nil {
redirectOIDCResult(w, r, "verify")
return
}
var claims struct {
Subject string `json:"sub"`
Name string `json:"name"`
EmailVerified bool `json:"email_verified"`
Email string `json:"email"`
Nonce string `json:"nonce"`
}
if idToken.Claims(&claims) != nil || claims.Subject == "" || claims.Nonce != state.Nonce || len(claims.Subject) > 255 || len(claims.Email) > 190 {
redirectOIDCResult(w, r, "claims")
return
}
if state.Mode == "bind" && state.UserID != nil {
if err = s.store.BindOIDCIdentity(r.Context(), *state.UserID, oidcProviderKey(cfg), claims.Subject, claims.Email); err != nil {
redirectOIDCResult(w, r, "conflict")
return
}
user, _ := s.store.UserByID(r.Context(), *state.UserID)
s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "oidc_identity", "", requestClientIP(r), true, "绑定第三方 OIDC 身份")
redirectOIDCResult(w, r, "bound")
return
}
user, err := s.store.UserByOIDC(r.Context(), oidcProviderKey(cfg), claims.Subject)
if err != nil {
if !errors.Is(err, store.ErrNotFound) {
redirectOIDCResult(w, r, "session")
return
}
ticket, e := randomURLToken(32)
if e != nil {
redirectOIDCResult(w, r, "session")
return
}
pending := store.PendingOIDCLogin{Provider: oidcProviderKey(cfg), Subject: claims.Subject, Email: strings.ToLower(strings.TrimSpace(claims.Email)), DisplayName: truncateOIDCName(claims.Name), EmailVerified: claims.EmailVerified, ExpiresAt: time.Now().UTC().Add(5 * time.Minute)}
if e = s.store.CreatePendingOIDCLogin(r.Context(), ticket, pending); e != nil {
redirectOIDCResult(w, r, "session")
return
}
setOIDCCookie(w, "sea_oidc_pending", ticket, 300)
redirectOIDCResult(w, r, "complete")
return
}
if user.Role == "host" {
redirectOIDCResult(w, r, "host_not_allowed")
return
}
if err = s.issueSession(w, r, user); err != nil {
redirectOIDCResult(w, r, "session")
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "login", "oidc_session", "", requestClientIP(r), true, "通过已绑定的 OIDC 身份登录")
redirectOIDCResult(w, r, "login")
}
func (s *Server) accountOIDC(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
cfg := s.readServiceConfig(r, "oidc_config")
if user.Role == "host" {
if r.Method == http.MethodGet {
writeJSON(w, 200, map[string]any{"enabled": false, "bound": false, "email": ""})
return
}
writeError(w, 403, "主机账号不可绑定 SSO")
return
}
if r.Method == http.MethodGet {
identity, err := s.store.OIDCIdentity(r.Context(), user.ID, oidcProviderKey(cfg))
writeJSON(w, http.StatusOK, map[string]any{"enabled": validOIDCConfig(cfg), "bound": err == nil, "email": identity.Email, "canUnbind": oidcPasswordAllowed(cfg, user.Role)})
return
}
if !oidcPasswordAllowed(cfg, user.Role) {
writeError(w, 409, "请先恢复该类账号的密码登录,再解除 SSO 绑定")
return
}
var input struct {
CurrentPassword string `json:"currentPassword"`
}
if decodeJSON(r, &input) != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
security, err := s.store.UserSecurity(r.Context(), user.ID)
if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) {
writeError(w, http.StatusUnauthorized, "当前密码不正确")
return
}
if err = s.store.DeleteOIDCIdentity(r.Context(), user.ID, oidcProviderKey(cfg)); err != nil && !errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusInternalServerError, "无法解除 OIDC 绑定")
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "unbind", "oidc_identity", "", requestClientIP(r), true, "解除第三方 OIDC 身份绑定")
w.WriteHeader(http.StatusNoContent)
}
func oidcClient(ctx context.Context, cfg secretServiceConfig) (*oidc.Provider, *oauth2.Config, error) {
if !validOIDCConfig(cfg) {
return nil, nil, errors.New("invalid OIDC config")
}
provider, err := oidc.NewProvider(ctx, strings.TrimSuffix(cfg.Issuer, "/"))
if err != nil {
return nil, nil, err
}
oauth := &oauth2.Config{ClientID: cfg.ClientID, ClientSecret: cfg.Secret, Endpoint: provider.Endpoint(), RedirectURL: cfg.RedirectURI, Scopes: []string{oidc.ScopeOpenID, "profile", "email"}}
return provider, oauth, nil
}
func validOIDCConfig(cfg secretServiceConfig) bool {
if !cfg.Enabled || cfg.Secret == "" || cfg.ClientID == "" || cfg.Issuer == "" || cfg.RedirectURI == "" {
return false
}
issuer, issuerErr := url.Parse(cfg.Issuer)
redirect, redirectErr := url.Parse(cfg.RedirectURI)
return issuerErr == nil && redirectErr == nil && issuer.Scheme == "https" && issuer.Host != "" && issuer.User == nil && redirect.Scheme == "https" && redirect.Host != "" && redirect.User == nil
}
func randomURLToken(size int) (string, error) {
data := make([]byte, size)
if _, err := rand.Read(data); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(data), nil
}
func redirectOIDCResult(w http.ResponseWriter, r *http.Request, result string) {
http.Redirect(w, r, "/?oidc="+url.QueryEscape(result), http.StatusSeeOther)
}
+175
View File
@@ -0,0 +1,175 @@
package httpapi
import (
"crypto/sha256"
"encoding/hex"
"net/http"
"net/mail"
"strings"
"time"
"sea-vhost/internal/auth"
"sea-vhost/internal/store"
)
func oidcProviderKey(c secretServiceConfig) string {
digest := sha256.Sum256([]byte(strings.TrimSuffix(strings.TrimSpace(c.Issuer), "/")))
return "oidc:" + hex.EncodeToString(digest[:16])
}
func oidcPasswordAllowed(c secretServiceConfig, role string) bool {
var v *bool
switch role {
case "admin":
v = c.AdminPasswordLogin
case "tenant":
v = c.UserPasswordLogin
default:
return true
}
return v == nil || *v
}
func setOIDCCookie(w http.ResponseWriter, name, value string, age int) {
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/api/v1/auth/oidc", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age})
}
func truncateOIDCName(v string) string {
chars := []rune(strings.TrimSpace(v))
if len(chars) > 80 {
chars = chars[:80]
}
return string(chars)
}
func validSSOEmail(p store.PendingOIDCLogin) bool {
m, e := mail.ParseAddress(p.Email)
return p.EmailVerified && e == nil && m.Address == p.Email && len(p.Email) <= 190
}
func (s *Server) pendingOIDCLogin(w http.ResponseWriter, r *http.Request) {
cookie, e := r.Cookie("sea_oidc_pending")
if e != nil {
writeJSON(w, 200, map[string]any{"pending": false})
return
}
p, e := s.store.PendingOIDCLogin(r.Context(), cookie.Value)
cfg := s.readServiceConfig(r, "oidc_config")
if e != nil || !validOIDCConfig(cfg) || p.Provider != oidcProviderKey(cfg) {
setOIDCCookie(w, "sea_oidc_pending", "", -1)
writeJSON(w, 200, map[string]any{"pending": false})
return
}
writeJSON(w, 200, map[string]any{"pending": true, "allowCreate": cfg.AutoCreate && validSSOEmail(p), "email": p.Email, "displayName": p.DisplayName})
}
func (s *Server) completeOIDCLogin(w http.ResponseWriter, r *http.Request) {
if _, e := r.Cookie(impersonationCookie); e == nil {
writeError(w, 403, "请先返回管理视图")
return
}
var input struct {
Action string `json:"action"`
Identifier string `json:"identifier"`
Password string `json:"password"`
TOTPCode string `json:"totpCode"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
cookie, e := r.Cookie("sea_oidc_pending")
if e != nil {
writeError(w, 401, "SSO 登录请求已失效,请重新登录")
return
}
p, e := s.store.PendingOIDCLogin(r.Context(), cookie.Value)
cfg := s.readServiceConfig(r, "oidc_config")
if e != nil || !validOIDCConfig(cfg) || p.Provider != oidcProviderKey(cfg) {
writeError(w, 401, "SSO 登录请求已失效,请重新登录")
return
}
if allowed, retry := s.loginLimiter.allow("oidc-complete:"+requestClientIP(r), time.Now(), loginIPBurst); !allowed {
writeLoginRateLimit(w, retry)
return
}
var target uint64
var created *store.NewTenant
switch input.Action {
case "bind":
started := time.Now()
u, err := s.store.UserByLogin(r.Context(), strings.ToLower(strings.TrimSpace(input.Identifier)))
hash := ""
if err == nil {
hash = u.PasswordHash
}
ok := auth.VerifyPasswordConstantWork(hash, input.Password)
if err != nil || !ok || u.Role == "host" || len(input.Password) > 128 {
minimumLoginDelay(started)
writeError(w, 401, "账号或密码不正确,主机账号不可绑定 SSO")
return
}
if !oidcPasswordAllowed(cfg, u.Role) {
writeError(w, 403, "该账号已关闭密码登录,请通过已绑定的 SSO 身份登录")
return
}
if u.MFAEnabled {
security, e := s.store.UserSecurity(r.Context(), u.ID)
if e != nil {
writeError(w, 500, "无法验证双重认证")
return
}
secret, e := s.secretBox.Open(mfaSecretLabel(u.ID), security.TOTPSecretCiphertext)
valid := e == nil && auth.VerifyTOTP(secret, input.TOTPCode, time.Now())
if !valid && strings.TrimSpace(input.TOTPCode) != "" {
valid, e = s.store.ConsumeRecoveryCode(r.Context(), u.ID, auth.RecoveryCodeHash(input.TOTPCode))
}
if e != nil || !valid {
writeCodedError(w, 401, "mfa_required", "请输入有效的动态验证码或恢复码")
return
}
}
target = u.ID
case "create":
if !cfg.AutoCreate || !validSSOEmail(p) {
writeError(w, 403, "当前不允许创建 SSO 用户,或第三方邮箱尚未验证")
return
}
random, e := randomURLToken(32)
if e != nil {
writeError(w, 500, "无法创建账号")
return
}
password, e := auth.HashPassword(random)
if e != nil {
writeError(w, 500, "无法创建账号")
return
}
name := p.DisplayName
if name == "" {
name = "SSO 用户"
}
digest := sha256.Sum256([]byte(random))
created = &store.NewTenant{Slug: "sso-" + hex.EncodeToString(digest[:10]), Name: name, DisplayName: name, Email: p.Email, Password: password, PlanID: 1}
default:
writeError(w, 422, "请选择绑定账号或创建账号")
return
}
target, e = s.store.CompletePendingOIDC(r.Context(), cookie.Value, oidcProviderKey(cfg), target, created)
if e != nil {
writeError(w, 409, "无法完成绑定或建号:请求可能已使用,或账号邮箱/SSO 身份已被绑定;相同邮箱不会自动合并")
return
}
setOIDCCookie(w, "sea_oidc_pending", "", -1)
u, e := s.store.UserByID(r.Context(), target)
if e != nil {
writeError(w, 401, "账号不可用")
return
}
if e = s.issueSession(w, r, u); e != nil {
writeError(w, 500, "绑定已完成,请重新使用 SSO 登录")
return
}
detail := "SSO 登录时绑定已有用户"
if created != nil {
detail = "SSO 首次登录创建普通用户,未开通虚拟主机"
}
s.store.Log(r.Context(), u.TenantID, u.ID, "login", "oidc_session", "", requestClientIP(r), true, detail)
writeJSON(w, 200, map[string]any{"completed": true})
}
@@ -0,0 +1,33 @@
package httpapi
import (
"sea-vhost/internal/store"
"testing"
)
func TestOIDCPasswordPolicyDoesNotAffectHosts(t *testing.T) {
off := false
c := secretServiceConfig{UserPasswordLogin: &off, AdminPasswordLogin: &off}
if !oidcPasswordAllowed(c, "host") || oidcPasswordAllowed(c, "admin") || oidcPasswordAllowed(c, "tenant") {
t.Fatal("password policy scope incorrect")
}
if !oidcPasswordAllowed(secretServiceConfig{}, "admin") || !oidcPasswordAllowed(secretServiceConfig{}, "tenant") {
t.Fatal("old settings must preserve password login")
}
}
func TestOIDCProviderIdentityIncludesIssuer(t *testing.T) {
a := oidcProviderKey(secretServiceConfig{Issuer: "https://id.example.com"})
if a != oidcProviderKey(secretServiceConfig{Issuer: "https://id.example.com/"}) || a == oidcProviderKey(secretServiceConfig{Issuer: "https://other.example.com"}) || len(a) > 40 {
t.Fatal("issuer isolation invalid")
}
}
func TestSSOAutomaticCreationRequiresVerifiedEmail(t *testing.T) {
for _, p := range []store.PendingOIDCLogin{{Email: "a@example.com"}, {Email: "not-an-email", EmailVerified: true}, {Email: "Name <a@example.com>", EmailVerified: true}} {
if validSSOEmail(p) {
t.Fatal("untrusted email accepted")
}
}
if !validSSOEmail(store.PendingOIDCLogin{Email: "a@example.com", EmailVerified: true}) {
t.Fatal("verified email rejected")
}
}
+93
View File
@@ -0,0 +1,93 @@
package httpapi
import (
"io"
"net/http"
"net/url"
"sea-vhost/internal/isolation"
"strconv"
"strings"
)
func (s *Server) phpMyAdmin(w http.ResponseWriter, r *http.Request) {
id, _ := projectID(r)
base := "/api/v1/projects/" + strconv.FormatUint(id, 10) + "/database-admin/"
relative := r.PathValue("pmaPath")
if r.Method != "GET" && r.Method != "POST" && r.Method != "HEAD" {
writeError(w, 405, "不支持的请求方法")
return
}
if s.cfg.ManagementDomain == "" {
writeError(w, 503, "未设置管理域名")
return
}
body, e := io.ReadAll(io.LimitReader(r.Body, (2<<20)+1))
if e != nil || len(body) > 2<<20 {
writeError(w, 413, "phpMyAdmin 单次请求上限为 2 MiB")
return
}
var cookies []string
for _, c := range r.Cookies() {
if !strings.HasPrefix(strings.ToLower(c.Name), "sea_") {
cookies = append(cookies, c.Name+"="+c.Value)
}
}
out, e := s.projects.PHPMyAdmin(r.Context(), currentUser(r), id, isolation.PHPMyAdminRequest{Method: r.Method, Path: relative, Query: r.URL.RawQuery, Body: body, Cookie: strings.Join(cookies, "; "), ContentType: r.Header.Get("Content-Type"), BaseURI: "https://" + s.cfg.ManagementDomain + base})
if e != nil {
writeError(w, 502, "phpMyAdmin 暂不可用,请检查节点上的 phpMyAdmin / PHP 安装")
return
}
for _, name := range []string{"Content-Type", "Content-Disposition", "Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP"} {
if value := out.Header.Get(name); value != "" {
w.Header().Set(name, value)
}
}
for _, cookie := range (&http.Response{Header: out.Header}).Cookies() {
if strings.HasPrefix(strings.ToLower(cookie.Name), "sea_") {
continue
}
cookie.Domain = ""
cookie.Path = base
cookie.Secure = true
cookie.HttpOnly = true
cookie.SameSite = http.SameSiteStrictMode
http.SetCookie(w, cookie)
}
if location := out.Header.Get("Location"); location != "" {
u, e := url.Parse(location)
if e != nil || u.User != nil || (u.Host != "" && !strings.EqualFold(u.Host, s.cfg.ManagementDomain)) || (u.Scheme != "" && u.Scheme != "https") {
writeError(w, 502, "phpMyAdmin 返回了无效跳转")
return
}
if u.IsAbs() || strings.HasPrefix(u.Path, "/") {
if !strings.HasPrefix(u.Path, base) {
writeError(w, 502, "phpMyAdmin 跳转超出数据库管理范围")
return
}
} else {
u.Path = base + strings.TrimPrefix(u.Path, "./")
}
w.Header().Set("Location", u.String())
}
if pmaNeedsAudit(r) {
u := currentUser(r)
s.store.Log(r.Context(), u.TenantID, u.ID, "manage", "database", strconv.FormatUint(id, 10), requestClientIP(r), out.Status < 400, "使用 phpMyAdmin 管理主机数据库")
}
w.WriteHeader(out.Status)
if r.Method != "HEAD" {
_, _ = w.Write(out.Body)
}
}
func pmaNeedsAudit(r *http.Request) bool {
if r.Method != http.MethodPost {
return false
}
// These are phpMyAdmin's automatic UI preferences/tree requests. Unknown
// routes, SQL execution, imports and other POSTs remain auditable.
switch r.URL.Query().Get("route") {
case "/config/get", "/config/set", "/navigation":
return false
}
return true
}
@@ -0,0 +1,18 @@
package httpapi
import (
"net/http/httptest"
"testing"
)
func TestPMAAuditKeepsSQLAndUnknownWrites(t *testing.T) {
for _, tc := range []struct {
method, route string
want bool
}{{"POST", "/config/get", false}, {"POST", "/config/set", false}, {"POST", "/navigation", false}, {"POST", "/sql", true}, {"POST", "/import", true}, {"POST", "/unrecognized", true}, {"POST", "", true}, {"GET", "/sql", false}} {
r := httptest.NewRequest(tc.method, "https://control.vhost.ser888.cn/?route="+tc.route, nil)
if pmaNeedsAudit(r) != tc.want {
t.Fatalf("audit %s %s", tc.method, tc.route)
}
}
}
+387
View File
@@ -0,0 +1,387 @@
package httpapi
import (
"errors"
"fmt"
"net/http"
"sea-vhost/internal/scope"
"strconv"
"strings"
"time"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
plan, usage, err := s.store.PlanAndUsage(r.Context(), *user.TenantID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取套餐信息")
return
}
projects, err := s.projectsForUser(r, user)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取项目")
return
}
activities, err := s.store.Activities(r.Context(), *user.TenantID, 10)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取操作日志")
return
}
writeJSON(w, http.StatusOK, map[string]any{"plan": plan, "usage": usage, "projects": projects, "activities": activities, "hostScoped": user.ProjectID != nil, "domainApproval": s.store.DomainApproval(r.Context(), s.cfg.DomainApproval), "rootDomain": s.cfg.RootDomain, "projectRoot": s.cfg.TenantRoot})
}
func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if value := r.URL.Query().Get("projectId"); value != "" {
id, err := strconv.ParseUint(value, 10, 64)
if err != nil || id != scope.Project(r.Context()) {
writeError(w, http.StatusNotFound, "主机不存在")
return
}
}
items, err := s.store.Activities(r.Context(), *user.TenantID, 100)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取操作日志")
return
}
writeJSON(w, http.StatusOK, map[string]any{"activities": items})
}
func (s *Server) runtimeCatalog(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if allowed, retryAfter := s.catalogLimiter.allow(fmt.Sprintf("runtime:%d", user.ID), time.Now(), 30); !allowed {
seconds := (retryAfter + time.Second - 1) / time.Second
w.Header().Set("Retry-After", strconv.FormatInt(int64(seconds), 10))
writeError(w, http.StatusTooManyRequests, "运行环境查询过于频繁,请稍后再试")
return
}
catalog, err := s.projects.RuntimeCatalog(r.Context())
if err != nil {
writeError(w, http.StatusBadGateway, "无法读取宝塔运行环境")
return
}
writeJSON(w, http.StatusOK, map[string]any{"versions": catalog})
}
func (s *Server) listProjects(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
projects, err := s.projectsForUser(r, user)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取项目")
return
}
writeJSON(w, http.StatusOK, map[string]any{"projects": projects})
}
func (s *Server) projectsForUser(r *http.Request, user store.User) ([]store.Project, error) {
if user.ProjectID != nil {
project, err := s.store.Project(r.Context(), *user.TenantID, *user.ProjectID)
if err != nil {
return nil, err
}
projects := []store.Project{project}
return projects, s.store.FillProjectBandwidth(r.Context(), projects)
}
projects, err := s.store.ListProjects(r.Context(), *user.TenantID)
if err != nil {
return nil, err
}
return projects, s.store.FillProjectBandwidth(r.Context(), projects)
}
func (s *Server) createProject(w http.ResponseWriter, r *http.Request) {
var input service.CreateProjectInput
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
result, err := s.projects.Create(r.Context(), user, input)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "create", "project", input.Name, requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(scope.WithProject(r.Context(), result.Project.ID, result.Project.NodeID), user.TenantID, user.ID, "create", "project", strconv.FormatUint(result.Project.ID, 10), requestClientIP(r), true, "创建项目 "+result.Project.Slug)
writeJSON(w, http.StatusCreated, result)
}
func projectID(r *http.Request) (uint64, error) { return strconv.ParseUint(r.PathValue("id"), 10, 64) }
func writeProjectMutationError(w http.ResponseWriter, status int, err error) {
if errors.Is(err, store.ErrManagementLocked) {
writeCodedError(w, 423, "management_locked", err.Error())
return
}
if errors.Is(err, store.ErrHostNotWritable) {
writeCodedError(w, http.StatusLocked, "host_not_writable", err.Error())
return
}
if errors.Is(err, service.ErrQuotaSuspended) {
writeCodedError(w, http.StatusLocked, "quota_suspended", "资源套餐已超额,当前仅允许读取、停止服务或清理数据")
return
}
writeError(w, status, err.Error())
}
func (s *Server) setProjectState(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "项目编号无效")
return
}
var input struct {
Enabled bool `json:"enabled"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
if err = s.projects.SetState(r.Context(), user, id, input.Enabled); err != nil {
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "state", "project", strconv.FormatUint(id, 10), requestClientIP(r), true, map[bool]string{true: "启动项目", false: "停止项目"}[input.Enabled])
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) setProjectRunPath(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "项目编号无效")
return
}
var input struct {
RunPath string `json:"runPath"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
project, err := s.projects.SetRunPath(r.Context(), user, id, input.RunPath)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "update", "run_path", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "update", "run_path", strconv.FormatUint(id, 10), requestClientIP(r), true, "运行目录改为 "+project.RunPath)
writeJSON(w, http.StatusOK, map[string]any{"project": project})
}
func (s *Server) projectCredentials(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "主机编号无效")
return
}
result, err := s.projects.Credentials(r.Context(), currentUser(r), id)
if err != nil {
status := http.StatusUnprocessableEntity
if errors.Is(err, store.ErrNotFound) {
status = http.StatusNotFound
}
writeError(w, status, "无法读取主机凭据")
return
}
writeJSON(w, http.StatusOK, map[string]any{"credentials": result.Credentials})
}
func (s *Server) resetHostPassword(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "主机编号无效")
return
}
user := currentUser(r)
password, err := s.projects.ResetHostPassword(r.Context(), user, id)
if err != nil {
status := http.StatusUnprocessableEntity
if errors.Is(err, store.ErrNotFound) {
status = http.StatusNotFound
}
s.store.Log(r.Context(), user.TenantID, user.ID, "reset", "host_password", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error())
writeError(w, status, err.Error())
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "reset", "host_password", strconv.FormatUint(id, 10), requestClientIP(r), true, "重置主机登录密码并注销旧会话")
writeJSON(w, http.StatusOK, map[string]string{"password": password})
}
func (s *Server) projectSites(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "主机编号无效")
return
}
user := currentUser(r)
if r.Method == http.MethodGet {
sites, readErr := s.projects.Sites(r.Context(), user, id)
if readErr != nil {
writeError(w, http.StatusNotFound, "虚拟主机不存在")
return
}
writeJSON(w, http.StatusOK, map[string]any{"sites": sites})
return
}
var input service.CreateSiteInput
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
site, err := s.projects.CreateSite(r.Context(), user, id, input)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "create", "site", input.Name, requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "create", "site", strconv.FormatUint(site.ID, 10), requestClientIP(r), true, "创建网站 "+site.Name)
writeJSON(w, http.StatusCreated, map[string]any{"site": site})
}
func siteID(r *http.Request) (uint64, error) {
return strconv.ParseUint(r.PathValue("siteID"), 10, 64)
}
func (s *Server) setSiteState(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
var input struct {
Enabled bool `json:"enabled"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
site, err := s.projects.SetSiteState(r.Context(), user, projectID, siteID, input.Enabled)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "state", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "state", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), true, map[bool]string{true: "启动网站", false: "停止网站"}[input.Enabled])
writeJSON(w, http.StatusOK, map[string]any{"site": site})
}
func (s *Server) checkSiteDeployment(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
var input struct {
EntryFile string `json:"entryFile"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
check, err := s.projects.CheckDeployment(r.Context(), user, projectID, siteID, input.EntryFile)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "check", "deployment", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error())
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "check", "deployment", strconv.FormatUint(siteID, 10), requestClientIP(r), check.Ready, check.Message)
writeJSON(w, http.StatusOK, map[string]any{"check": check})
}
func (s *Server) deploySite(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
var input struct {
EntryFile string `json:"entryFile"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
site, err := s.projects.DeploySite(r.Context(), user, projectID, siteID, input.EntryFile)
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "deploy", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "deploy", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "语言项目已启动并接入 Nginx")
writeJSON(w, http.StatusOK, map[string]any{"site": site})
}
func (s *Server) deleteSite(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
user := currentUser(r)
if err := s.projects.DeleteSite(r.Context(), user, projectID, siteID); err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "delete", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error())
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "delete", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "删除网站配置,保留主机目录文件")
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) bindDomain(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "项目编号无效")
return
}
var input struct {
Domain string `json:"domain"`
}
if err = decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
domain, err := s.projects.BindDomain(r.Context(), user, id, strings.TrimSpace(input.Domain))
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), true, "绑定自定义域名")
writeJSON(w, http.StatusAccepted, map[string]any{"domain": domain})
}
func (s *Server) bindSiteDomain(w http.ResponseWriter, r *http.Request) {
projectID, projectErr := projectID(r)
siteID, siteErr := siteID(r)
if projectErr != nil || siteErr != nil {
writeError(w, http.StatusBadRequest, "网站编号无效")
return
}
var input struct {
Domain string `json:"domain"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
user := currentUser(r)
domain, err := s.projects.BindSiteDomain(r.Context(), user, projectID, siteID, strings.TrimSpace(input.Domain))
if err != nil {
s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), false, err.Error())
writeProjectMutationError(w, http.StatusUnprocessableEntity, err)
return
}
s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), true, "为网站 "+strconv.FormatUint(siteID, 10)+" 绑定自定义域名")
writeJSON(w, http.StatusAccepted, map[string]any{"domain": domain})
}
+220
View File
@@ -0,0 +1,220 @@
package httpapi
import (
"errors"
"net/http"
"net/mail"
"sea-vhost/internal/store"
"strconv"
"strings"
)
func (s *Server) resourceAudit(r *http.Request, action, kind string, id uint64, err error, detail string) {
s.store.Log(r.Context(), nil, currentUser(r).ID, action, kind, strconv.FormatUint(id, 10), requestClientIP(r), err == nil, detail)
}
func (s *Server) adminAccount(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "用户编号无效")
return
}
p, err := s.store.AccountProfile(r.Context(), id)
if err != nil {
writeError(w, 404, "用户不存在或已删除")
return
}
if r.Method == http.MethodGet {
writeJSON(w, 200, p)
return
}
if r.Method == http.MethodDelete {
var input struct {
Confirmation string `json:"confirmation"`
}
if decodeJSON(r, &input) != nil || input.Confirmation != p.Slug {
writeError(w, 422, "请输入用户标识确认删除")
return
}
err = s.store.DeleteAccount(r.Context(), id)
s.resourceAudit(r, "delete", "account", id, err, "删除用户 "+p.Slug+",保留审计记录")
if err != nil {
writeError(w, 409, "无法删除用户:请先解绑或转移全部主机,并确认没有正在执行的归属变更")
return
}
w.WriteHeader(204)
return
}
var input store.AccountProfile
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
input.Name = strings.TrimSpace(input.Name)
input.DisplayName = strings.TrimSpace(input.DisplayName)
input.Email = strings.ToLower(strings.TrimSpace(input.Email))
address, e := mail.ParseAddress(input.Email)
if input.Name == "" || len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || e != nil || address.Address != input.Email || len(input.Email) > 190 {
writeError(w, 422, "请检查用户名称、联系人姓名和登录邮箱")
return
}
err = s.store.UpdateAccount(r.Context(), id, input)
s.resourceAudit(r, "update", "account", id, err, "更新用户资料 "+p.Slug)
if err != nil {
writeError(w, 422, "无法保存用户资料,请检查登录邮箱是否重复")
return
}
w.WriteHeader(204)
}
func (s *Server) adminHostRecord(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, 400, "主机编号无效")
return
}
hosts, err := s.store.ListAdminProjects(r.Context())
if err != nil {
writeError(w, 500, "无法读取主机")
return
}
var host *store.AdminProject
for i := range hosts {
if hosts[i].ID == id {
host = &hosts[i]
break
}
}
if host == nil {
writeError(w, 404, "主机不存在")
return
}
if r.Method == http.MethodGet {
writeJSON(w, 200, host)
return
}
if r.Method == http.MethodDelete {
var input struct {
Confirmation string `json:"confirmation"`
}
if decodeJSON(r, &input) != nil || input.Confirmation != host.HostName {
writeError(w, 422, "请输入主机名确认回收")
return
}
err = s.projects.RecycleManagedHost(r.Context(), id)
s.resourceAudit(r, "recycle", "project", id, err, "手动回收主机 "+host.HostName+";7 天后清理,备份保留 14 天")
if err != nil {
writeError(w, 409, err.Error())
return
}
w.WriteHeader(204)
return
}
var input struct {
Name string `json:"name"`
AllowRuntimeChange *bool `json:"allowRuntimeChange"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
input.Name = strings.TrimSpace(input.Name)
if len([]rune(input.Name)) < 1 || len([]rune(input.Name)) > 50 || strings.ContainsAny(input.Name, "\x00\r\n") {
writeError(w, 422, "主机显示名称应为 1–50 个字符")
return
}
err = s.store.RenameHost(r.Context(), id, input.Name)
if err == nil && input.AllowRuntimeChange != nil {
err = s.store.SetRuntimePolicy(r.Context(), id, *input.AllowRuntimeChange)
}
s.resourceAudit(r, "update", "project", id, err, "修改主机显示名称 "+host.HostName)
if err != nil {
writeError(w, 409, "无法修改名称,请检查主机是否正在回收或处理归属变更")
return
}
w.WriteHeader(204)
}
func (s *Server) adminRestoreHost(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, 400, "主机编号无效")
return
}
err = s.projects.RestoreManagedHost(r.Context(), id)
s.resourceAudit(r, "restore", "project", id, err, "恢复手动回收主机;网站和 FTP 保持停止,计划任务保持暂停")
if err != nil {
writeError(w, 409, err.Error())
return
}
w.WriteHeader(204)
}
func (s *Server) adminNodeRecord(w http.ResponseWriter, r *http.Request) {
id, err := nodeID(r)
if err != nil || id == 0 {
writeError(w, 400, "节点编号无效")
return
}
existing, err := s.store.Node(r.Context(), id)
if err != nil {
writeError(w, 404, "节点不存在或已删除")
return
}
if r.Method == http.MethodGet {
writeJSON(w, 200, existing)
return
}
if r.Method == http.MethodDelete {
var input struct {
Confirmation string `json:"confirmation"`
}
if decodeJSON(r, &input) != nil || input.Confirmation != existing.Name {
writeError(w, 422, "请输入节点名称确认删除")
return
}
err = s.projects.DeleteManagedNode(r.Context(), id)
s.resourceAudit(r, "delete", "node", id, err, "删除节点 "+existing.Name+",撤销主控保存的连接凭据")
} else {
var input store.Node
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
normalizeNodeMetadata(&input)
if err = validateNodeMetadata(input, existing.Transport == "local"); err != nil {
writeError(w, 422, err.Error())
return
}
err = s.projects.UpdateManagedNode(r.Context(), id, input)
s.resourceAudit(r, "update", "node", id, err, "更新节点配置 "+existing.Name)
}
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeError(w, 404, "节点不存在或已删除")
} else {
writeError(w, 409, err.Error())
}
return
}
w.WriteHeader(204)
}
func (s *Server) adminDetachRecycledHost(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, 400, "主机编号无效")
return
}
var input struct {
Version uint64 `json:"ownershipVersion"`
Confirmation string `json:"confirmation"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请求格式错误")
return
}
err = s.store.DetachRecycledHost(r.Context(), id, input.Version, input.Confirmation)
s.resourceAudit(r, "unbind", "project", id, err, "手动解绑回收主机的用户,保持回收状态与保留期限")
if err != nil {
writeError(w, 409, err.Error())
return
}
w.WriteHeader(204)
}
@@ -0,0 +1,521 @@
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 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"))
})
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 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
}
+29
View File
@@ -0,0 +1,29 @@
package httpapi
import "net/http"
func (s *Server) resources(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
tenantID := *user.TenantID
domains, err := s.store.ListDomains(r.Context(), tenantID, user.ProjectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取域名资源")
return
}
ftpAccounts, err := s.store.ListFTPResources(r.Context(), tenantID, user.ProjectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取 FTP 资源")
return
}
databases, err := s.store.ListDatabaseResources(r.Context(), tenantID, user.ProjectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取数据库资源")
return
}
sites, err := s.store.ListTenantSites(r.Context(), tenantID, user.ProjectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法读取网站资源")
return
}
writeJSON(w, http.StatusOK, map[string]any{"domains": domains, "ftpAccounts": ftpAccounts, "databases": databases, "sites": sites})
}
@@ -0,0 +1,59 @@
package httpapi
import (
"net/http"
"slices"
"strings"
)
var installableRuntimes = []string{"Node.js", "Python", "Go", "Java"}
var installableRuntimeComponents = []string{"Node.js", "Python"}
func (s *Server) adminRuntimeEnvironments(w http.ResponseWriter, r *http.Request) {
items, err := s.projects.RuntimeEnvironments(r.Context())
if err != nil {
writeError(w, http.StatusBadGateway, "无法读取宝塔运行环境")
return
}
writeJSON(w, http.StatusOK, map[string]any{"environments": items})
}
func (s *Server) adminInstallRuntimeComponent(w http.ResponseWriter, r *http.Request) {
runtimeName := strings.TrimSpace(r.PathValue("runtime"))
if !slices.Contains(installableRuntimeComponents, runtimeName) {
writeError(w, http.StatusUnprocessableEntity, "仅支持安装官方免费 Node.js 或 Python 管理组件")
return
}
user := currentUser(r)
if err := s.projects.InstallRuntimeComponent(r.Context(), runtimeName); err != nil {
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_component", runtimeName, requestClientIP(r), false, err.Error())
writeError(w, http.StatusBadGateway, "运行环境组件安装失败")
return
}
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_component", runtimeName, requestClientIP(r), true, "安装官方免费 "+runtimeName+" 管理组件")
writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true})
}
func (s *Server) adminInstallRuntimeEnvironment(w http.ResponseWriter, r *http.Request) {
runtimeName := strings.TrimSpace(r.PathValue("runtime"))
if !slices.Contains(installableRuntimes, runtimeName) {
writeError(w, http.StatusUnprocessableEntity, "不支持安装该运行环境")
return
}
var input struct {
Version string `json:"version"`
}
if err := decodeJSON(r, &input); err != nil || strings.TrimSpace(input.Version) == "" {
writeError(w, http.StatusBadRequest, "请选择运行环境版本")
return
}
input.Version = strings.TrimSpace(input.Version)
user := currentUser(r)
if err := s.projects.InstallRuntimeEnvironment(r.Context(), runtimeName, input.Version); err != nil {
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), false, err.Error())
writeError(w, http.StatusBadGateway, "运行环境安装任务提交失败")
return
}
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), true, "提交 "+runtimeName+" "+input.Version+" 安装任务")
writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true})
}
@@ -0,0 +1,84 @@
package httpapi
import (
"net/http"
"strconv"
)
func (s *Server) adminRuntimeMaintenance(w http.ResponseWriter, r *http.Request) {
targets, jobs, err := s.projects.RuntimeMaintenanceState(r.Context())
if err != nil {
writeError(w, 502, "无法读取运行环境维护状态")
return
}
writeJSON(w, 200, map[string]any{"sites": targets, "jobs": jobs})
}
func (s *Server) adminUpdatePHPPatch(w http.ResponseWriter, r *http.Request) {
var input struct {
Branch string `json:"branch"`
Target string `json:"target"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "请选择 PHP 分支与目标补丁版本")
return
}
id, err := s.projects.SubmitPHPPatch(r.Context(), input.Branch, input.Target)
s.logRuntimeMaintenance(r, "php_patch", "PHP/"+input.Target, err)
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 202, map[string]any{"jobId": id})
}
func (s *Server) adminMigrateSiteRuntime(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("siteID"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "站点编号无效")
return
}
var input struct {
Version string `json:"version"`
AllowBranchChange bool `json:"allowBranchChange"`
EntryFile string `json:"entryFile"`
}
if decodeJSON(r, &input) != nil || input.Version == "" {
writeError(w, 400, "请选择目标版本")
return
}
jobID, err := s.projects.SubmitRuntimeMigration(r.Context(), id, input.Version, input.AllowBranchChange, input.EntryFile)
s.logRuntimeMaintenance(r, "migrate", r.PathValue("siteID")+"/"+input.Version, err)
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 202, map[string]any{"jobId": jobID})
}
func (s *Server) adminResumeRuntimeMaintenance(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("jobID"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "任务编号无效")
return
}
err = s.projects.ResumeRuntimeMaintenance(r.Context(), id)
s.logRuntimeMaintenance(r, "resume", r.PathValue("jobID"), err)
if err != nil {
writeError(w, 409, "任务无法恢复,或已有其他维护任务正在执行")
return
}
writeJSON(w, 202, map[string]bool{"ok": true})
}
func (s *Server) adminCheckRuntimeUpdates(w http.ResponseWriter, r *http.Request) {
id, err := s.projects.SubmitRuntimeCheck(r.Context())
if err != nil {
writeError(w, 409, err.Error())
return
}
writeJSON(w, 202, map[string]any{"jobId": id})
}
func (s *Server) logRuntimeMaintenance(r *http.Request, action, target string, err error) {
detail := "已提交运行环境维护任务"
if err != nil {
detail = err.Error()
}
s.store.Log(r.Context(), nil, currentUser(r).ID, action, "runtime_maintenance", target, requestClientIP(r), err == nil, detail)
}
@@ -0,0 +1,117 @@
package httpapi
import (
"context"
"crypto/hmac"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net/http"
"sea-vhost/internal/schedulerbridge"
"sea-vhost/internal/store"
"strconv"
"time"
)
func (s *Server) schedulerKey(ctx context.Context, node uint64, create bool) (string, error) {
label := fmt.Sprintf("scheduler-trigger:%d", node)
raw, e := s.store.SystemSecret(ctx, label)
if e != nil && !errors.Is(e, store.ErrNotFound) {
return "", e
}
if len(raw) == 0 && create {
key := make([]byte, 32)
if _, e = rand.Read(key); e != nil {
return "", e
}
cipher, e := s.secretBox.Seal(label, hex.EncodeToString(key))
if e != nil {
return "", e
}
if e = s.store.InsertSystemSecretIfAbsent(ctx, label, cipher); e != nil {
return "", e
}
raw, e = s.store.SystemSecret(ctx, label)
if e != nil {
return "", e
}
}
if len(raw) == 0 {
return "", fmt.Errorf("not configured")
}
return s.secretBox.Open(label, raw)
}
func (s *Server) adminScheduler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
node, _ := strconv.ParseUint(s.store.Setting(r.Context(), "scheduler_node_id", "0"), 10, 64)
last, _ := s.store.LastSchedulerTick(r.Context())
writeJSON(w, 200, map[string]any{"nodeId": node, "lastTick": last})
return
}
var v struct {
NodeID uint64 `json:"nodeId"`
}
if decodeJSON(r, &v) != nil || v.NodeID == 0 {
writeError(w, 400, "请选择调度触发节点")
return
}
if s.cfg.ManagementDomain == "" {
writeError(w, 422, "请先设置管理域名")
return
}
key, e := s.schedulerKey(r.Context(), v.NodeID, true)
if e == nil {
e = s.projects.ConfigureSystemScheduler(r.Context(), schedulerbridge.Config{NodeID: v.NodeID, Controller: "https://" + s.cfg.ManagementDomain, Key: key})
}
if e == nil {
e = s.store.SetSetting(r.Context(), "scheduler_node_id", fmt.Sprint(v.NodeID))
}
if e != nil {
writeError(w, 422, "调度器配置失败:"+e.Error())
return
}
u := currentUser(r)
s.store.Log(r.Context(), nil, u.ID, "configure", "scheduler", "", requestClientIP(r), true, "配置宝塔每分钟系统调度器")
w.WriteHeader(204)
}
func (s *Server) schedulerTick(w http.ResponseWriter, r *http.Request) {
nodeText := r.Header.Get("X-Sea-Node")
stamp := r.Header.Get("X-Sea-Time")
nonce := r.Header.Get("X-Sea-Nonce")
signature := r.Header.Get("X-Sea-Signature")
node, e := strconv.ParseUint(nodeText, 10, 64)
when, te := strconv.ParseInt(stamp, 10, 64)
nonceRaw, ne := hex.DecodeString(nonce)
if e != nil || te != nil || ne != nil || len(nonceRaw) != 16 || time.Since(time.Unix(when, 0)) > 30*time.Second || time.Until(time.Unix(when, 0)) > 30*time.Second || s.store.Setting(r.Context(), "scheduler_node_id", "0") != nodeText {
writeError(w, 401, "调度身份无效")
return
}
n, e := s.store.Node(r.Context(), node)
key, ke := s.schedulerKey(r.Context(), node, false)
if e != nil || !n.Enabled || ke != nil || !hmac.Equal([]byte(signature), []byte(schedulerbridge.Signature(key, nodeText, stamp, nonce))) {
writeError(w, 401, "调度身份无效")
return
}
if !s.schedulerRunning.TryLock() {
w.WriteHeader(204)
return
}
claimed, e := s.store.ClaimSchedulerTick(r.Context(), node)
if e != nil || !claimed {
s.schedulerRunning.Unlock()
if e != nil {
writeError(w, 503, "调度暂不可用")
} else {
w.WriteHeader(204)
}
return
}
go func() {
defer s.schedulerRunning.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
_ = s.projects.QueueUserSchedules(ctx)
}()
w.WriteHeader(202)
}
+593
View File
@@ -0,0 +1,593 @@
package httpapi
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"sea-vhost/internal/auth"
"sea-vhost/internal/cluster"
"sea-vhost/internal/config"
"sea-vhost/internal/scope"
"sea-vhost/internal/secrets"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
"strconv"
)
type contextKey string
const userKey contextKey = "user"
type Server struct {
cfg config.Config
store *store.Store
projects *service.Projects
mux *http.ServeMux
loginLimiter *loginLimiter
catalogLimiter *loginLimiter
secretBox *secrets.Box
cluster *cluster.Manager
schedulerRunning sync.Mutex
}
func New(cfg config.Config, database *store.Store, projects *service.Projects) *Server {
s := &Server{cfg: cfg, store: database, projects: projects, mux: http.NewServeMux(), loginLimiter: newLoginLimiter(), catalogLimiter: newLoginLimiter(), secretBox: secrets.New(cfg.SessionSecret)}
s.routes()
return s
}
func (s *Server) Handler() http.Handler { return s.security(s.mux) }
func (s *Server) WithCluster(manager *cluster.Manager) *Server { s.cluster = manager; return s }
func (s *Server) routes() {
s.mux.HandleFunc("GET /api/integration/v1/docs", integrationDocs)
s.mux.HandleFunc("/api/v1/projects/{id}/database-admin/{pmaPath...}", s.requireTenant(s.phpMyAdmin))
s.mux.HandleFunc("GET /api/v1/admin/integration-keys", s.requireAdmin(s.adminIntegrationKeys))
s.mux.HandleFunc("POST /api/v1/admin/integration-keys", s.requireAdmin(s.adminIntegrationKeys))
s.mux.HandleFunc("DELETE /api/v1/admin/integration-keys/{keyID}", s.requireAdmin(s.adminIntegrationKeys))
s.mux.HandleFunc("GET /api/integration/v1/{resource}", func(w http.ResponseWriter, r *http.Request) {
kind := r.PathValue("resource")
if kind != "users" && kind != "hosts" {
writeError(w, 404, "接口不存在")
return
}
s.requireIntegration(kind+":read", s.integrationList)(w, r)
})
s.mux.HandleFunc("POST /api/integration/v1/{resource}", func(w http.ResponseWriter, r *http.Request) {
kind := r.PathValue("resource")
if kind != "users" && kind != "hosts" {
writeError(w, 404, "接口不存在")
return
}
s.requireIntegration(kind+":write", s.integrationWrite)(w, r)
})
s.mux.HandleFunc("GET /api/integration/v1/tasks/{batchID}", s.requireIntegration("tasks:read", s.integrationTask))
s.mux.HandleFunc("GET /api/integration/v1/tasks/{batchID}/download", s.requireIntegration("credentials:read", s.integrationTask))
s.mux.HandleFunc("POST /api/v1/system/scheduler/tick", s.schedulerTick)
s.mux.HandleFunc("GET /api/v1/admin/scheduler", s.requireAdmin(s.adminScheduler))
s.mux.HandleFunc("POST /api/v1/admin/scheduler", s.requireAdmin(s.adminScheduler))
s.mux.HandleFunc("GET /api/v1/schedules", s.requireUserAccount(s.userSchedules))
s.mux.HandleFunc("POST /api/v1/schedules", s.requireUserAccount(s.userSchedules))
s.mux.HandleFunc("PUT /api/v1/schedules/{scheduleID}", s.requireUserAccount(s.userSchedules))
s.mux.HandleFunc("DELETE /api/v1/schedules/{scheduleID}", s.requireUserAccount(s.userSchedules))
s.mux.HandleFunc("POST /api/v1/schedules/{scheduleID}/{action}", s.requireUserAccount(s.userSchedules))
s.mux.HandleFunc("GET /api/v1/schedules/{scheduleID}/runs", s.requireUserAccount(s.userSchedules))
s.mux.HandleFunc("POST /api/v1/projects/{id}/ftp", s.requireTenant(s.manageFTP))
s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/runtime", s.requireTenant(s.siteRuntime))
s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/runtime", s.requireTenant(s.siteRuntime))
s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/startup", s.requireTenant(s.siteStartup))
s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/startup", s.requireTenant(s.siteStartup))
s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/settings", s.requireTenant(s.siteSettings))
s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/settings", s.requireTenant(s.siteSettings))
s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/logs", s.requireTenant(s.siteLog))
s.mux.HandleFunc("GET /api/v1/projects/{id}/metrics", s.requireTenant(s.hostMetrics))
s.mux.HandleFunc("GET /api/v1/projects/{id}/file-actions", s.requireTenant(s.fileActions))
s.mux.HandleFunc("POST /api/v1/projects/{id}/file-actions", s.requireTenant(s.fileActions))
s.mux.HandleFunc("POST /api/v1/admin/batches/preview", s.requireAdmin(s.adminBatchPreview))
s.mux.HandleFunc("GET /api/v1/admin/batches", s.requireAdmin(s.adminBatches))
s.mux.HandleFunc("POST /api/v1/admin/batches", s.requireAdmin(s.adminBatches))
s.mux.HandleFunc("GET /api/v1/admin/batches/{batchID}", s.requireAdmin(s.adminBatch))
s.mux.HandleFunc("POST /api/v1/admin/batches/{batchID}/cancel", s.requireAdmin(s.adminCancelBatch))
s.mux.HandleFunc("GET /api/v1/admin/batches/{batchID}/download", s.requireAdmin(s.adminBatchDownload))
s.mux.HandleFunc("POST /api/v1/admin/impersonation", s.requireAdmin(s.startImpersonation))
s.mux.HandleFunc("POST /api/v1/auth/impersonation/stop", s.requireAuth(s.stopImpersonation))
s.mux.HandleFunc("GET /api/v1/activities", s.requireTenant(s.activities))
s.mux.HandleFunc("GET /api/v1/admin/nodes/{nodeID}/tasks", s.requireAdmin(s.adminNodeTasks))
s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/tasks/{taskID}/resolve", s.requireAdmin(s.adminResolveNodeTask))
s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/reconcile", s.requireAdmin(s.adminReconcileNode))
s.mux.HandleFunc("GET /api/v1/admin/nodes", s.requireAdmin(s.adminNodes))
s.mux.HandleFunc("POST /api/v1/admin/nodes", s.requireAdmin(s.adminNodes))
s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/pair", s.requireAdmin(s.adminPairNode))
s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/probe", s.requireAdmin(s.adminProbeNode))
s.mux.HandleFunc("PUT /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNode))
s.mux.HandleFunc("GET /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNodeRecord))
s.mux.HandleFunc("PATCH /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNodeRecord))
s.mux.HandleFunc("DELETE /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNodeRecord))
s.mux.HandleFunc("GET /api/v1/admin/projects/{id}", s.requireAdmin(s.adminHostRecord))
s.mux.HandleFunc("PUT /api/v1/admin/projects/{id}", s.requireAdmin(s.adminHostRecord))
s.mux.HandleFunc("DELETE /api/v1/admin/projects/{id}", s.requireAdmin(s.adminHostRecord))
s.mux.HandleFunc("POST /api/v1/admin/projects/{id}/restore", s.requireAdmin(s.adminRestoreHost))
s.mux.HandleFunc("GET /api/v1/admin/tenants/{id}", s.requireAdmin(s.adminAccount))
s.mux.HandleFunc("PUT /api/v1/admin/tenants/{id}", s.requireAdmin(s.adminAccount))
s.mux.HandleFunc("DELETE /api/v1/admin/tenants/{id}", s.requireAdmin(s.adminAccount))
s.mux.HandleFunc("POST /api/v1/admin/projects", s.requireAdmin(s.adminCreateHost))
s.mux.HandleFunc("PUT /api/v1/admin/projects/{id}/subscription", s.requireAdmin(s.adminHostSubscription))
s.mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
})
s.mux.HandleFunc("GET /api/v1/setup/status", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"required": false})
})
s.mux.HandleFunc("POST /api/v1/auth/login", s.login)
s.mux.HandleFunc("GET /api/v1/auth/oidc/status", s.oidcStatus)
s.mux.HandleFunc("GET /api/v1/auth/oidc/pending", s.pendingOIDCLogin)
s.mux.HandleFunc("POST /api/v1/auth/oidc/complete", s.completeOIDCLogin)
s.mux.HandleFunc("GET /api/v1/auth/oidc/start", s.oidcStart)
s.mux.HandleFunc("GET /api/v1/auth/oidc/callback", s.oidcCallback)
s.mux.HandleFunc("POST /api/v1/auth/logout", s.requireAuth(s.logout))
s.mux.HandleFunc("GET /api/v1/me", s.requireAuth(s.me))
s.mux.HandleFunc("GET /api/v1/account/security", s.requireAuth(s.accountSecurity))
s.mux.HandleFunc("PUT /api/v1/account/password", s.requireAuth(s.changePassword))
s.mux.HandleFunc("POST /api/v1/account/mfa/setup", s.requireAuth(s.setupMFA))
s.mux.HandleFunc("POST /api/v1/account/mfa/enable", s.requireAuth(s.enableMFA))
s.mux.HandleFunc("POST /api/v1/account/mfa/disable", s.requireAuth(s.disableMFA))
s.mux.HandleFunc("GET /api/v1/account/oidc", s.requireAuth(s.accountOIDC))
s.mux.HandleFunc("DELETE /api/v1/account/oidc", s.requireAuth(s.accountOIDC))
s.mux.HandleFunc("GET /api/v1/dashboard", s.requireTenant(s.dashboard))
s.mux.HandleFunc("GET /api/v1/runtime-catalog", s.requireTenant(s.runtimeCatalog))
s.mux.HandleFunc("GET /api/v1/projects", s.requireTenant(s.listProjects))
s.mux.HandleFunc("POST /api/v1/projects", s.requireTenant(s.createProject))
s.mux.HandleFunc("POST /api/v1/projects/{id}/state", s.requireTenant(s.setProjectState))
s.mux.HandleFunc("PUT /api/v1/projects/{id}/run-path", s.requireTenant(s.setProjectRunPath))
s.mux.HandleFunc("GET /api/v1/projects/{id}/credentials", s.requireTenant(s.projectCredentials))
s.mux.HandleFunc("POST /api/v1/projects/{id}/host-password/reset", s.requireTenant(s.resetHostPassword))
s.mux.HandleFunc("GET /api/v1/projects/{id}/sites", s.requireTenant(s.projectSites))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites", s.requireTenant(s.projectSites))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/state", s.requireTenant(s.setSiteState))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/deployment/check", s.requireTenant(s.checkSiteDeployment))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/deployment", s.requireTenant(s.deploySite))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/certificate/auto", s.requireTenant(s.requestAutoCertificate))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/certificate/dns", s.requireTenant(s.requestDNSCertificate))
s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/certificate", s.requireTenant(s.certificateAutomation))
s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/certificate/manual", s.requireTenant(s.installManualCertificate))
s.mux.HandleFunc("DELETE /api/v1/projects/{id}/sites/{siteID}/certificate", s.requireTenant(s.disableCertificate))
s.mux.HandleFunc("POST /api/v1/dns-credentials/discover", s.requireTenantAdmin(s.discoverDNSZones))
s.mux.HandleFunc("GET /api/v1/dns-credentials", s.requireTenantAdmin(s.dnsCredentials))
s.mux.HandleFunc("POST /api/v1/dns-credentials", s.requireTenantAdmin(s.dnsCredentials))
s.mux.HandleFunc("PUT /api/v1/dns-credentials/{credentialID}", s.requireTenantAdmin(s.dnsCredential))
s.mux.HandleFunc("DELETE /api/v1/dns-credentials/{credentialID}", s.requireTenantAdmin(s.dnsCredential))
s.mux.HandleFunc("POST /api/v1/dns-credentials/{credentialID}/test", s.requireTenantAdmin(s.testDNSCredential))
s.mux.HandleFunc("DELETE /api/v1/projects/{id}/sites/{siteID}", s.requireTenant(s.deleteSite))
s.mux.HandleFunc("POST /api/v1/projects/{id}/domains", s.requireTenant(s.bindDomain))
s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/domains", s.requireTenant(s.bindSiteDomain))
s.mux.HandleFunc("POST /api/v1/domains/{id}/dns", s.requireTenant(s.domainDNS))
s.mux.HandleFunc("DELETE /api/v1/domains/{id}/dns", s.requireTenant(s.domainDNS))
s.mux.HandleFunc("DELETE /api/v1/domains/{id}", s.requireTenant(s.unbindDomain))
s.mux.HandleFunc("GET /api/v1/resources", s.requireTenant(s.resources))
s.mux.HandleFunc("GET /api/v1/projects/{id}/files", s.requireTenant(s.files))
s.mux.HandleFunc("POST /api/v1/projects/{id}/files", s.requireTenant(s.files))
s.mux.HandleFunc("PUT /api/v1/projects/{id}/files", s.requireTenant(s.files))
s.mux.HandleFunc("DELETE /api/v1/projects/{id}/files", s.requireTenant(s.files))
s.mux.HandleFunc("GET /api/v1/admin/tenants", s.requireAdmin(s.adminTenants))
s.mux.HandleFunc("POST /api/v1/admin/tenants", s.requireAdmin(s.adminTenants))
s.mux.HandleFunc("GET /api/v1/admin/plans", s.requireAdmin(s.adminPlans))
s.mux.HandleFunc("POST /api/v1/admin/plans", s.requireAdmin(s.adminPlans))
s.mux.HandleFunc("DELETE /api/v1/admin/plans/{id}", s.requireAdmin(s.deletePlan))
s.mux.HandleFunc("DELETE /api/v1/admin/domains/{id}", s.requireAdmin(s.unbindDomain))
s.mux.HandleFunc("GET /api/v1/admin/settings/domain-approval", s.requireAdmin(s.domainApprovalSetting))
s.mux.HandleFunc("PUT /api/v1/admin/settings/domain-approval", s.requireAdmin(s.domainApprovalSetting))
s.mux.HandleFunc("GET /api/v1/admin/domains/pending", s.requireAdmin(s.adminPendingDomains))
s.mux.HandleFunc("POST /api/v1/admin/domains/{id}/review", s.requireAdmin(s.adminReviewDomain))
s.mux.HandleFunc("POST /api/v1/admin/domains/{id}/dns", s.requireAdmin(s.adminDomainDNS))
s.mux.HandleFunc("DELETE /api/v1/admin/domains/{id}/dns", s.requireAdmin(s.adminDomainDNS))
s.mux.HandleFunc("POST /api/v1/admin/dns-credentials/discover", s.requireAdmin(s.discoverDNSZones))
s.mux.HandleFunc("GET /api/v1/admin/dns-credentials", s.requireAdmin(s.adminDNSCredentials))
s.mux.HandleFunc("POST /api/v1/admin/dns-credentials", s.requireAdmin(s.adminDNSCredentials))
s.mux.HandleFunc("PUT /api/v1/admin/dns-credentials/{credentialID}", s.requireAdmin(s.adminDNSCredential))
s.mux.HandleFunc("DELETE /api/v1/admin/dns-credentials/{credentialID}", s.requireAdmin(s.adminDNSCredential))
s.mux.HandleFunc("POST /api/v1/admin/dns-credentials/{credentialID}/test", s.requireAdmin(s.testAdminDNSCredential))
s.mux.HandleFunc("GET /api/v1/admin/overview", s.requireAdmin(s.adminOverview))
s.mux.HandleFunc("GET /api/v1/admin/settings", s.requireAdmin(s.adminSettings))
s.mux.HandleFunc("PUT /api/v1/admin/settings", s.requireAdmin(s.adminSettings))
s.mux.HandleFunc("GET /api/v1/admin/ip-addresses", s.requireAdmin(s.adminIPs))
s.mux.HandleFunc("POST /api/v1/admin/ip-addresses", s.requireAdmin(s.adminIPs))
s.mux.HandleFunc("DELETE /api/v1/admin/ip-addresses/{id}", s.requireAdmin(s.adminIP))
s.mux.HandleFunc("PUT /api/v1/admin/projects/{id}/network", s.requireAdmin(s.adminProjectNetwork))
s.mux.HandleFunc("GET /api/v1/admin/panel-sites", s.requireAdmin(s.adminPanelSites))
s.mux.HandleFunc("POST /api/v1/admin/panel-sites/{id}/adopt", s.requireAdmin(s.adminAdoptPanelSite))
s.mux.HandleFunc("DELETE /api/v1/admin/projects/{id}/recycled-owner", s.requireAdmin(s.adminDetachRecycledHost))
s.mux.HandleFunc("GET /api/v1/admin/audit", s.requireAdmin(s.adminAudit))
s.mux.HandleFunc("GET /api/v1/admin/runtime-environments", s.requireAdmin(s.adminRuntimeEnvironments))
s.mux.HandleFunc("GET /api/v1/admin/runtime-maintenance", s.requireAdmin(s.adminRuntimeMaintenance))
s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/check", s.requireAdmin(s.adminCheckRuntimeUpdates))
s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/php", s.requireAdmin(s.adminUpdatePHPPatch))
s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/sites/{siteID}", s.requireAdmin(s.adminMigrateSiteRuntime))
s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/jobs/{jobID}/resume", s.requireAdmin(s.adminResumeRuntimeMaintenance))
s.mux.HandleFunc("POST /api/v1/admin/runtime-components/{runtime}/install", s.requireAdmin(s.adminInstallRuntimeComponent))
s.mux.HandleFunc("POST /api/v1/admin/runtime-environments/{runtime}/install", s.requireAdmin(s.adminInstallRuntimeEnvironment))
s.mux.HandleFunc("PUT /api/v1/admin/domains/{id}/metadata", s.requireAdmin(s.adminDomainMetadata))
s.mux.HandleFunc("PUT /api/v1/admin/tenants/{id}/expiry", s.requireAdmin(s.adminTenantExpiry))
}
func (s *Server) security(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
if !s.allowedRequestHost(r) {
writeError(w, http.StatusMisdirectedRequest, "请求主机不在管理域名白名单")
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions && !sameOrigin(r) {
writeError(w, http.StatusForbidden, "不允许跨站请求")
return
}
defer func() {
if recovered := recover(); recovered != nil {
slog.Error("HTTP panic", "error", recovered)
writeError(w, http.StatusInternalServerError, "服务器内部错误")
}
}()
next.ServeHTTP(w, r)
})
}
func (s *Server) allowedRequestHost(r *http.Request) bool {
wanted := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(s.cfg.ManagementDomain), "."))
if wanted == "" {
return true
}
host := remoteHost(r.Host)
if strings.EqualFold(strings.TrimSuffix(host, "."), wanted) {
return true
}
if r.URL.Path == "/healthz" && isLoopbackRemote(r.RemoteAddr) {
ip := net.ParseIP(strings.Trim(host, "[]"))
return strings.EqualFold(host, "localhost") || (ip != nil && ip.IsLoopback())
}
return false
}
func sameOrigin(r *http.Request) bool {
if strings.EqualFold(r.Header.Get("Sec-Fetch-Site"), "cross-site") {
return false
}
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
parsed, err := url.Parse(origin)
if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
return false
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return false
}
return strings.EqualFold(parsed.Scheme, requestScheme(r)) && strings.EqualFold(parsed.Host, r.Host)
}
func requestScheme(r *http.Request) string {
if r.TLS != nil {
return "https"
}
if isLoopbackRemote(r.RemoteAddr) {
forwarded := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0]))
if forwarded == "http" || forwarded == "https" {
return forwarded
}
}
return "http"
}
func requestClientIP(r *http.Request) string {
if isLoopbackRemote(r.RemoteAddr) {
if forwarded := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP"))); forwarded != nil {
return forwarded.String()
}
}
host := remoteHost(r.RemoteAddr)
if parsed := net.ParseIP(host); parsed != nil {
return parsed.String()
}
return "unknown"
}
func isLoopbackRemote(remote string) bool {
ip := net.ParseIP(remoteHost(remote))
return ip != nil && ip.IsLoopback()
}
func remoteHost(remote string) string {
if host, _, err := net.SplitHostPort(remote); err == nil {
return strings.Trim(host, "[]")
}
return strings.Trim(remote, "[]")
}
const (
loginWindow = 5 * time.Minute
loginIPBurst = 60
loginIdentifierBurst = 20
loginLimiterMaxKeys = 4096
)
type loginAttempt struct {
windowStart time.Time
count int
}
type loginLimiter struct {
mu sync.Mutex
attempts map[string]loginAttempt
lastSweep time.Time
}
func newLoginLimiter() *loginLimiter {
return &loginLimiter{attempts: make(map[string]loginAttempt)}
}
func (l *loginLimiter) allow(key string, now time.Time, limit int) (bool, time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
if l.lastSweep.IsZero() || now.Sub(l.lastSweep) >= time.Minute || now.Before(l.lastSweep) {
for candidate, attempt := range l.attempts {
if now.Before(attempt.windowStart) || now.Sub(attempt.windowStart) >= loginWindow {
delete(l.attempts, candidate)
}
}
for candidate := range l.attempts {
if len(l.attempts) <= loginLimiterMaxKeys {
break
}
delete(l.attempts, candidate)
}
l.lastSweep = now
}
attempt, found := l.attempts[key]
if !found || now.Before(attempt.windowStart) || now.Sub(attempt.windowStart) >= loginWindow {
if !found && len(l.attempts) >= loginLimiterMaxKeys {
for candidate := range l.attempts {
delete(l.attempts, candidate)
break
}
}
l.attempts[key] = loginAttempt{windowStart: now, count: 1}
return true, 0
}
if attempt.count >= limit {
return false, loginWindow - now.Sub(attempt.windowStart)
}
attempt.count++
l.attempts[key] = attempt
return true, 0
}
func (l *loginLimiter) reset(keys ...string) {
l.mu.Lock()
defer l.mu.Unlock()
for _, key := range keys {
delete(l.attempts, key)
}
}
func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("sea_session")
if err != nil {
writeError(w, http.StatusUnauthorized, "请先登录")
return
}
user, err := s.userFromToken(r.Context(), cookie.Value)
if err != nil {
writeError(w, http.StatusUnauthorized, "登录已失效")
return
}
ctx := context.WithValue(r.Context(), userKey, user)
if child, err := r.Cookie(impersonationCookie); err == nil {
if user.Role != "admin" {
s.clearImpersonation(w)
writeError(w, 403, "代入会话必须绑定原管理员登录")
return
}
ctx = context.WithValue(ctx, realAdministratorKey, user)
if r.URL.Path != "/api/v1/auth/impersonation/stop" {
if !auth.ValidateSessionToken(s.cfg.SessionSecret, child.Value) {
s.clearImpersonation(w)
writeError(w, 401, "代入会话已失效,请返回管理员")
return
}
effective, err := s.store.ImpersonationUser(ctx, cookie.Value, child.Value, user.ID)
if err != nil {
s.clearImpersonation(w)
writeError(w, 401, "代入会话已失效,请返回管理员")
return
}
ctx = context.WithValue(scope.WithAdministrator(ctx, user.ID), userKey, effective)
if strings.HasPrefix(r.URL.Path, "/api/v1/account/") {
writeError(w, 403, "代入期间不能修改或绑定账号登录安全设置")
return
}
}
}
next(w, r.WithContext(ctx))
}
}
func (s *Server) requireTenant(next http.HandlerFunc) http.HandlerFunc {
return s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if user.TenantID == nil {
writeError(w, http.StatusForbidden, "该接口仅供用户或主机账号使用")
return
}
if user.Role == "tenant" {
r = r.WithContext(scope.WithAccount(r.Context(), *user.TenantID))
}
if r.Method == "POST" && r.URL.Path == "/api/v1/projects" {
writeError(w, 403, "请联系管理员开通虚拟主机")
return
}
projectID := uint64(0)
if strings.HasPrefix(r.URL.Path, "/api/v1/projects/") {
projectID, _ = strconv.ParseUint(r.PathValue("id"), 10, 64)
if projectID == 0 {
writeError(w, 400, "主机编号无效")
return
}
}
if value := r.URL.Query().Get("projectId"); value != "" {
requestedID, err := strconv.ParseUint(value, 10, 64)
if err != nil || requestedID == 0 {
writeError(w, 400, "主机编号无效")
return
}
if projectID != 0 && requestedID != projectID {
writeError(w, 404, "主机不存在")
return
}
projectID = requestedID
}
if projectID == 0 && user.ProjectID != nil {
projectID = *user.ProjectID
}
if strings.HasPrefix(r.URL.Path, "/api/v1/domains/") {
id, _ := strconv.ParseUint(r.PathValue("id"), 10, 64)
d, err := s.store.DomainByID(r.Context(), id)
if err != nil {
writeError(w, 404, "域名不存在")
return
}
projectID = d.ProjectID
}
if projectID > 0 {
p, err := s.store.ProjectForUser(r.Context(), user, projectID)
if err != nil || (user.ProjectID != nil && *user.ProjectID != projectID) {
if errors.Is(err, store.ErrManagementLocked) {
writeError(w, 423, err.Error())
return
}
writeError(w, 404, "主机不存在")
return
}
user.TenantID = &p.TenantID
r = r.WithContext(context.WithValue(scope.WithProject(r.Context(), p.ID, p.NodeID), userKey, user))
if !(r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/runtime")) {
accessRelease, accessErr := s.projects.BeginHostAccess(p.ID)
if accessErr != nil {
writeError(w, 423, accessErr.Error())
return
}
defer accessRelease()
// Recheck sessions and ownership after acquiring the host gate.
parent, _ := r.Cookie("sea_session")
if parent == nil {
writeError(w, 401, "登录已失效")
return
}
effective, authErr := s.userFromToken(r.Context(), parent.Value)
if child, childErr := r.Cookie(impersonationCookie); childErr == nil && authErr == nil {
effective, authErr = s.store.ImpersonationUser(r.Context(), parent.Value, child.Value, effective.ID)
}
if authErr != nil || effective.ID != user.ID {
writeError(w, 401, "登录已失效")
return
}
if _, accessErr = s.store.ProjectForUser(r.Context(), user, p.ID); accessErr != nil {
writeError(w, 404, "主机不存在或归属已变化")
return
}
}
}
if r.Method != "GET" && strings.HasPrefix(r.URL.Path, "/api/v1/projects") {
release, err := s.projects.BeginRuntimeMutation(r.Context())
if err != nil {
if !errors.Is(err, service.ErrRuntimeSwitchPending) && !errors.Is(err, service.ErrNodeConfigurationBusy) {
writeError(w, http.StatusInternalServerError, "无法核对主机操作状态,请稍后重试")
return
}
w.Header().Set("Retry-After", "10")
writeError(w, http.StatusLocked, err.Error())
return
}
defer release()
}
next(w, r)
})
}
func (s *Server) requireTenantAdmin(next http.HandlerFunc) http.HandlerFunc {
return s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if user.Role != "tenant" || user.TenantID == nil {
writeError(w, http.StatusForbidden, "只有用户账号可以管理 DNS 凭据")
return
}
next(w, r)
})
}
func (s *Server) requireAdmin(next http.HandlerFunc) http.HandlerFunc {
return s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
if currentUser(r).Role != "admin" {
writeError(w, http.StatusForbidden, "需要管理员权限")
return
}
ctx := r.Context()
if value := r.URL.Query().Get("nodeId"); value != "" {
id, err := strconv.ParseUint(value, 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "节点编号无效")
return
}
ctx = scope.WithNode(ctx, id)
}
if strings.HasPrefix(r.URL.Path, "/api/v1/admin/projects/") {
id, _ := strconv.ParseUint(r.PathValue("id"), 10, 64)
node, _, err := s.store.ProjectPlacement(ctx, id)
if err != nil {
writeError(w, 404, "主机不存在")
return
}
ctx = scope.WithProject(ctx, id, node)
}
if strings.HasPrefix(r.URL.Path, "/api/v1/admin/domains/") && r.PathValue("id") != "" {
id, _ := strconv.ParseUint(r.PathValue("id"), 10, 64)
d, err := s.store.DomainByID(ctx, id)
if err != nil {
writeError(w, 404, "域名不存在")
return
}
node, _, err := s.store.ProjectPlacement(ctx, d.ProjectID)
if err != nil {
writeError(w, 404, "主机不存在")
return
}
ctx = scope.WithProject(ctx, d.ProjectID, node)
}
if value := r.PathValue("siteID"); value != "" {
id, _ := strconv.ParseUint(value, 10, 64)
node, err := s.store.NodeForSite(ctx, id)
if err != nil {
writeError(w, 404, "网站不存在")
return
}
ctx = scope.WithNode(ctx, node)
}
r = r.WithContext(ctx)
next(w, r)
})
}
func (s *Server) userFromToken(ctx context.Context, token string) (store.User, error) {
if !auth.ValidateSessionToken(s.cfg.SessionSecret, token) {
return store.User{}, errors.New("invalid token")
}
return s.store.UserBySession(ctx, token)
}
func currentUser(r *http.Request) store.User { return r.Context().Value(userKey).(store.User) }
+91
View File
@@ -0,0 +1,91 @@
package httpapi
import (
"net/http/httptest"
"testing"
"time"
)
func TestSameOriginRequiresMatchingSchemeAndHost(t *testing.T) {
request := httptest.NewRequest("POST", "http://console.example/api/v1/auth/login", nil)
request.RemoteAddr = "127.0.0.1:42000"
request.Header.Set("X-Forwarded-Proto", "https")
tests := []struct {
name string
origin string
fetchSite string
wantAllowed bool
}{
{name: "matching", origin: "https://console.example", wantAllowed: true},
{name: "matching trailing slash", origin: "https://console.example/", wantAllowed: true},
{name: "missing origin", wantAllowed: true},
{name: "wrong scheme", origin: "http://console.example", wantAllowed: false},
{name: "wrong host", origin: "https://attacker.example", wantAllowed: false},
{name: "origin path", origin: "https://console.example/path", wantAllowed: false},
{name: "null origin", origin: "null", wantAllowed: false},
{name: "cross site fetch", origin: "https://console.example", fetchSite: "cross-site", wantAllowed: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
request.Header.Set("Origin", test.origin)
request.Header.Set("Sec-Fetch-Site", test.fetchSite)
if got := sameOrigin(request); got != test.wantAllowed {
t.Fatalf("sameOrigin() = %v, want %v", got, test.wantAllowed)
}
})
}
}
func TestForwardedHeadersAreTrustedOnlyFromLoopback(t *testing.T) {
request := httptest.NewRequest("GET", "http://console.example/", nil)
request.Header.Set("X-Forwarded-Proto", "https")
request.Header.Set("X-Real-IP", "203.0.113.77")
request.RemoteAddr = "198.51.100.8:44000"
if got := requestScheme(request); got != "http" {
t.Fatalf("untrusted request scheme = %q", got)
}
if got := requestClientIP(request); got != "198.51.100.8" {
t.Fatalf("untrusted client IP = %q", got)
}
request.RemoteAddr = "[::1]:44000"
if got := requestScheme(request); got != "https" {
t.Fatalf("trusted request scheme = %q", got)
}
if got := requestClientIP(request); got != "203.0.113.77" {
t.Fatalf("trusted client IP = %q", got)
}
}
func TestLoginLimiterBlocksExpiresAndResets(t *testing.T) {
limiter := newLoginLimiter()
now := time.Date(2026, time.October, 14, 8, 0, 0, 0, time.UTC)
for attempt := 0; attempt < 2; attempt++ {
if allowed, _ := limiter.allow("identifier:user@example.test", now, 2); !allowed {
t.Fatalf("attempt %d was unexpectedly blocked", attempt+1)
}
}
if allowed, retryAfter := limiter.allow("identifier:user@example.test", now, 2); allowed || retryAfter != loginWindow {
t.Fatalf("blocked attempt = (%v, %v), want (false, %v)", allowed, retryAfter, loginWindow)
}
if allowed, _ := limiter.allow("identifier:user@example.test", now.Add(loginWindow), 2); !allowed {
t.Fatal("attempt was not allowed after the window expired")
}
limiter.reset("identifier:user@example.test")
if allowed, _ := limiter.allow("identifier:user@example.test", now, 2); !allowed {
t.Fatal("attempt was not allowed after reset")
}
}
func TestLoginLimiterBoundsTrackedKeys(t *testing.T) {
limiter := newLoginLimiter()
now := time.Date(2026, time.October, 14, 8, 0, 0, 0, time.UTC)
for index := 0; index < loginLimiterMaxKeys+100; index++ {
limiter.allow(string(rune(index+1)), now, 1)
}
if got := len(limiter.attempts); got > loginLimiterMaxKeys {
t.Fatalf("tracked keys = %d, want at most %d", got, loginLimiterMaxKeys)
}
}
+62
View File
@@ -0,0 +1,62 @@
package httpapi
import (
"net/http"
"sea-vhost/internal/scope"
"sea-vhost/internal/store"
"strconv"
)
func (s *Server) siteRuntime(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
sid, e := siteID(r)
if err != nil || e != nil {
writeError(w, 400, "网站编号无效")
return
}
u := currentUser(r)
if r.Method == "GET" {
p, e := s.store.ProjectForUser(r.Context(), u, id)
if e != nil {
writeError(w, 404, "主机不存在")
return
}
if _, e = s.store.Site(r.Context(), p.TenantID, id, sid); e != nil {
writeError(w, 404, "网站不存在")
return
}
jobs, e := s.store.RuntimeJobs(scope.WithNode(r.Context(), p.NodeID))
if e != nil {
writeError(w, 500, "无法读取环境任务")
return
}
own := []store.RuntimeJob{}
for _, j := range jobs {
if j.SiteID != nil && *j.SiteID == sid {
own = append(own, j)
}
}
writeJSON(w, 200, map[string]any{"jobs": own})
return
}
var input struct {
Runtime string `json:"runtime"`
Version string `json:"version"`
EntryFile string `json:"entryFile"`
}
if decodeJSON(r, &input) != nil {
writeError(w, 400, "环境设置格式无效")
return
}
job, err := s.projects.SubmitSiteRuntime(r.Context(), u, id, sid, input.Runtime, input.Version, input.EntryFile)
detail := "提交网站运行环境切换任务"
if err != nil {
detail = err.Error()
}
s.store.Log(r.Context(), u.TenantID, u.ID, "update", "site_runtime", strconv.FormatUint(sid, 10), requestClientIP(r), err == nil, detail)
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 202, map[string]any{"jobId": job})
}
+54
View File
@@ -0,0 +1,54 @@
package httpapi
import (
"net/http"
"sea-vhost/internal/hosting"
"strconv"
)
func (s *Server) siteSettings(w http.ResponseWriter, r *http.Request) {
project, _ := projectID(r)
site, _ := strconv.ParseUint(r.PathValue("siteID"), 10, 64)
if r.Method == "GET" {
v, e := s.projects.WebsiteSettings(r.Context(), currentUser(r), project, site)
if e != nil {
writeError(w, 404, "网站不存在或无法读取设置")
return
}
writeJSON(w, 200, map[string]any{"settings": v})
return
}
var v hosting.WebsiteSettings
if decodeJSON(r, &v) != nil {
writeError(w, 400, "设置格式无效")
return
}
if e := s.projects.SetWebsiteSettings(r.Context(), currentUser(r), project, site, v); e != nil {
writeError(w, 422, e.Error())
return
}
u := currentUser(r)
s.store.Log(r.Context(), u.TenantID, u.ID, "update", "site", strconv.FormatUint(site, 10), requestClientIP(r), true, "更新网站基础设置")
w.WriteHeader(204)
}
func (s *Server) siteLog(w http.ResponseWriter, r *http.Request) {
project, _ := projectID(r)
site, _ := strconv.ParseUint(r.PathValue("siteID"), 10, 64)
lines, _ := strconv.Atoi(r.URL.Query().Get("lines"))
v, e := s.projects.SiteLog(r.Context(), currentUser(r), project, site, r.URL.Query().Get("kind"), r.URL.Query().Get("search"), lines)
if e != nil {
writeError(w, 422, "无法读取该网站日志")
return
}
writeJSON(w, 200, v)
}
func (s *Server) hostMetrics(w http.ResponseWriter, r *http.Request) {
project, _ := projectID(r)
days, _ := strconv.Atoi(r.URL.Query().Get("days"))
v, e := s.store.HostMetrics(r.Context(), project, days)
if e != nil {
writeError(w, 503, "无法读取资源历史")
return
}
writeJSON(w, 200, map[string]any{"samples": v, "retentionDays": 30, "cpuUnit": "100% = 一个 CPU 核心"})
}
@@ -0,0 +1,324 @@
package httpapi
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-sql-driver/mysql"
"net/http"
"net/http/httptest"
"net/url"
"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 TestSSOLoginMySQL(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 non-test schema")
}
db, e := store.Open(dsn)
if e != nil {
t.Fatal(e)
}
defer db.Close()
ctx := context.Background()
must := func(e error) {
t.Helper()
if e != nil {
t.Fatal(e)
}
}
must(db.Migrate(ctx))
must(db.Migrate(ctx))
raw, e := sql.Open("mysql", dsn)
must(e)
defer raw.Close()
must(db.BootstrapAdmin(ctx, "sso-admin@example.invalid", "SSO 管理员", "sso-admin-password-123"))
admin, e := db.UserByLogin(ctx, "sso-admin@example.invalid")
must(e)
root := t.TempDir()
must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"))
secret := "sso-test-session-key-at-least-thirty-two-characters"
projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
app := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects)
key, e := rsa.GenerateKey(rand.Reader, 2048)
must(e)
var issuer, nonce, subject, email string
verified := true
idp := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/.well-known/openid-configuration":
json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "jwks_uri": issuer + "/keys", "id_token_signing_alg_values_supported": []string{"RS256"}})
case "/keys":
json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]any{"kty": "RSA", "use": "sig", "alg": "RS256", "kid": "test", "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": "AQAB"}}})
case "/token":
_ = r.ParseForm()
if r.Form.Get("code_verifier") == "" {
t.Error("PKCE verifier missing")
}
encode := func(v any) string { b, _ := json.Marshal(v); return base64.RawURLEncoding.EncodeToString(b) }
message := encode(map[string]any{"alg": "RS256", "kid": "test"}) + "." + encode(map[string]any{"iss": issuer, "sub": subject, "aud": "sso-client", "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Unix(), "nonce": nonce, "email": email, "email_verified": verified, "name": "SSO 测试用户"})
sum := sha256.Sum256([]byte(message))
signature, e := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:])
if e != nil {
t.Error(e)
}
json.NewEncoder(w).Encode(map[string]any{"access_token": "test-access", "token_type": "Bearer", "expires_in": 3600, "id_token": message + "." + base64.RawURLEncoding.EncodeToString(signature)})
default:
w.WriteHeader(404)
}
}))
defer idp.Close()
issuer = idp.URL
cfg := secretServiceConfig{Enabled: true, Issuer: issuer, ClientID: "sso-client", Secret: "test-client-secret", RedirectURI: "https://control.example.invalid/api/v1/auth/oidc/callback", AutoCreate: true}
must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg))
type jar map[string]string
count := 0
call := func(method, path string, body any, cookies jar) *httptest.ResponseRecorder {
t.Helper()
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("Content-Type", "application/json")
r.Header.Set("Origin", "https://control.example.invalid")
count++
r.RemoteAddr = fmt.Sprintf("192.0.2.%d:1234", 1+count%200)
r = r.WithContext(oidc.ClientContext(r.Context(), idp.Client()))
for name, value := range cookies {
r.AddCookie(&http.Cookie{Name: name, Value: value})
}
w := httptest.NewRecorder()
app.Handler().ServeHTTP(w, r)
for _, c := range w.Result().Cookies() {
if c.MaxAge < 0 {
delete(cookies, c.Name)
} else {
cookies[c.Name] = c.Value
}
}
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())
}
}
session := func(u store.User) jar {
token, e := auth.NewSessionToken(secret)
must(e)
must(db.CreateSession(ctx, u.ID, token, time.Now().Add(time.Hour)))
return jar{"sea_session": token}
}
startMode := func(c jar, mode string) string {
w := call("GET", "/api/v1/auth/oidc/start?mode="+mode, nil, c)
expect(w, 200)
var out map[string]string
must(json.Unmarshal(w.Body.Bytes(), &out))
u, e := url.Parse(out["url"])
must(e)
nonce = u.Query().Get("nonce")
if u.Query().Get("code_challenge_method") != "S256" {
t.Fatal("PKCE not enabled")
}
return u.Query().Get("state")
}
start := func(c jar) string { return startMode(c, "login") }
callback := func(c jar, state string) *httptest.ResponseRecorder {
return call("GET", "/api/v1/auth/oidc/callback?state="+url.QueryEscape(state)+"&code=test-code", nil, c)
}
off := false
localID, e := db.CreateTenant(ctx, store.NewTenant{Slug: "sso-existing", Name: "已有用户", DisplayName: "已有用户", Email: "existing@example.invalid", Password: "existing-password-123", PlanID: 1})
must(e)
_ = localID
local, e := db.UserByLogin(ctx, "existing@example.invalid")
must(e)
t.Run("authenticated frontend binding does not merge by email", func(t *testing.T) {
c := jar{}
subject = "external-local"
email = "existing@example.invalid"
state := start(c)
absent := jar{}
w := callback(absent, state)
expect(w, 303)
if strings.Contains(w.Header().Get("Location"), "complete") {
t.Fatal("callback accepted without browser state")
}
w = callback(c, state)
expect(w, 303)
if !strings.Contains(w.Header().Get("Location"), "complete") {
t.Fatal(w.Header().Get("Location"))
}
if _, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject); e == nil {
t.Fatal("email silently linked")
}
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 409)
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "bind", "identifier": local.Email, "password": "wrong"}, c), 401)
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "bind", "identifier": local.Email, "password": "existing-password-123"}, c), 200)
linked, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject)
must(e)
if linked.ID != local.ID {
t.Fatal("wrong account binding")
}
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 401)
c = jar{}
w = callback(c, start(c))
expect(w, 303)
if !strings.Contains(w.Header().Get("Location"), "login") {
t.Fatal("bound identity could not login")
}
})
t.Run("ordinary account creation has no host and is single use", func(t *testing.T) {
c := jar{}
subject = "fresh-subject"
email = "new-sso@example.invalid"
expect(callback(c, start(c)), 303)
oldTicket := c["sea_oidc_pending"]
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 200)
u, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject)
must(e)
if u.Role != "tenant" || u.ProjectID != nil {
t.Fatal("SSO granted unexpected privileges")
}
n, e := db.CountProjects(ctx, *u.TenantID)
must(e)
if n != 0 {
t.Fatal("SSO created a host")
}
replay := jar{"sea_oidc_pending": oldTicket}
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, replay), 401)
if _, e = db.UserByOIDC(ctx, oidcProviderKey(cfg), "FRESH-SUBJECT"); e == nil {
t.Fatal("subject lookup is case insensitive")
}
})
t.Run("new users need verified email and enabled creation", func(t *testing.T) {
c := jar{}
subject = "unverified"
email = "notverified@example.invalid"
verified = false
expect(callback(c, start(c)), 303)
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 403)
verified = true
cfg.AutoCreate = false
must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg))
c = jar{}
subject = "registration-off"
email = "off@example.invalid"
expect(callback(c, start(c)), 303)
expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 403)
})
t.Run("host SSO is rejected and password policy is enforced by API", func(t *testing.T) {
hash, e := auth.HashPassword("host-test-password-123")
must(e)
result, e := raw.Exec(`INSERT INTO users(email,login_name,display_name,password_hash,role) VALUES('host-sso@example.invalid','host-sso','主机账号',?,'host')`, hash)
must(e)
id, e := result.LastInsertId()
must(e)
host, e := db.UserByID(ctx, uint64(id))
must(e)
expect(call("GET", "/api/v1/auth/oidc/start?mode=bind", nil, session(host)), 403)
cfg.UserPasswordLogin = &off
cfg.AdminPasswordLogin = &off
must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg))
expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": local.Email, "password": "existing-password-123"}, jar{}), 403)
expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": admin.Email, "password": "sso-admin-password-123"}, jar{}), 403)
expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": "host-sso", "password": "host-test-password-123"}, jar{}), 200)
expect(call("DELETE", "/api/v1/account/oidc", map[string]any{"currentPassword": "existing-password-123"}, session(local)), 409)
c := jar{}
subject = "external-local"
email = local.Email
expect(callback(c, start(c)), 303)
if c["sea_session"] == "" {
t.Fatal("password restriction blocked SSO")
}
})
t.Run("nonce mismatch and consumed state are rejected", func(t *testing.T) {
c := jar{}
state := start(c)
nonce = "wrong-nonce"
w := callback(c, state)
expect(w, 303)
if !strings.Contains(w.Header().Get("Location"), "claims") {
t.Fatal("wrong nonce accepted")
}
if c["sea_oidc_pending"] != "" {
t.Fatal("invalid token created continuation")
}
expect(callback(c, state), 303)
})
t.Run("issuer changes invalidate pending login", func(t *testing.T) {
c := jar{}
state := start(c)
changed := cfg
changed.Issuer = "https://other.example.invalid"
must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", changed))
w := callback(c, state)
expect(w, 303)
if !strings.Contains(w.Header().Get("Location"), "provider_changed") {
t.Fatal(w.Header().Get("Location"))
}
must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg))
})
t.Run("settings reject disabling SSO while passwords closed", func(t *testing.T) {
body := map[string]any{"graceDays": 3, "recycleDays": 7, "backupRetentionDays": 14, "smtp": secretServiceConfig{}, "oidc": secretServiceConfig{Enabled: false, UserPasswordLogin: &off, AdminPasswordLogin: &off}}
expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 422)
body["oidc"] = cfg
expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 422)
})
t.Run("bind callback tolerates Strict session cookie but requires live parent", func(t *testing.T) {
c := session(admin)
subject = "admin-binding"
email = admin.Email
state := startMode(c, "bind")
delete(c, "sea_session")
w := callback(c, state)
expect(w, 303)
if !strings.Contains(w.Header().Get("Location"), "bound") {
t.Fatal(w.Header().Get("Location"))
}
bound, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject)
must(e)
if bound.ID != admin.ID {
t.Fatal("wrong administrator identity")
}
body := map[string]any{"graceDays": 3, "recycleDays": 7, "backupRetentionDays": 14, "smtp": secretServiceConfig{}, "oidc": cfg}
expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 204)
c = session(admin)
subject = "revoked-parent"
state = startMode(c, "bind")
hash := sha256.Sum256([]byte(c["sea_session"]))
_, e = raw.Exec(`DELETE FROM sessions WHERE token_hash=?`, hash[:])
must(e)
delete(c, "sea_session")
w = callback(c, state)
expect(w, 303)
if !strings.Contains(w.Header().Get("Location"), "expired") {
t.Fatal("revoked initiating session accepted")
}
})
}
+33
View File
@@ -0,0 +1,33 @@
package httpapi
import (
"net/http"
"sea-vhost/internal/hosting"
"strconv"
)
func (s *Server) siteStartup(w http.ResponseWriter, r *http.Request) {
id, _ := projectID(r)
site, _ := strconv.ParseUint(r.PathValue("siteID"), 10, 64)
u := currentUser(r)
if r.Method == "GET" {
v, e := s.projects.Startup(r.Context(), u, id, site)
if e != nil {
writeError(w, 404, "无法读取启动配置")
return
}
writeJSON(w, 200, map[string]any{"startup": v})
return
}
var v hosting.Startup
if decodeJSON(r, &v) != nil {
writeError(w, 400, "启动设置格式无效")
return
}
if e := s.projects.SetStartup(r.Context(), u, id, site, v); e != nil {
writeError(w, 422, e.Error())
return
}
s.store.Log(r.Context(), u.TenantID, u.ID, "update", "site", strconv.FormatUint(site, 10), requestClientIP(r), true, "更新网站环境变量与启动配置")
w.WriteHeader(204)
}
@@ -0,0 +1,72 @@
package httpapi
import (
"net/http"
"sea-vhost/internal/scope"
"sea-vhost/internal/store"
"strconv"
)
func (s *Server) requireUserAccount(next http.HandlerFunc) http.HandlerFunc {
return s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
u := currentUser(r)
if u.Role != "tenant" || u.TenantID == nil {
writeError(w, 403, "计划任务仅供用户账号使用")
return
}
next(w, r.WithContext(scope.WithAccount(r.Context(), *u.TenantID)))
})
}
func (s *Server) userSchedules(w http.ResponseWriter, r *http.Request) {
if action := r.PathValue("action"); action != "" && action != "run" {
writeError(w, 404, "操作不存在")
return
}
u := currentUser(r)
id, _ := strconv.ParseUint(r.PathValue("scheduleID"), 10, 64)
if r.Method == "GET" {
if r.PathValue("scheduleID") != "" {
items, e := s.projects.ScheduleRuns(r.Context(), u, id)
if e != nil {
writeError(w, 404, "任务不存在")
return
}
writeJSON(w, 200, map[string]any{"runs": items})
return
}
items, e := s.projects.UserSchedules(r.Context(), u)
if e != nil {
writeError(w, 503, "无法读取计划任务")
return
}
writeJSON(w, 200, map[string]any{"schedules": items})
return
}
var err error
action := "update"
if r.Method == "DELETE" {
err = s.store.DeleteUserSchedule(r.Context(), u.ID, id)
action = "delete"
} else if r.PathValue("action") == "run" {
err = s.store.RequestUserScheduleRun(r.Context(), u.ID, id)
action = "queue"
} else {
var input store.UserSchedule
if decodeJSON(r, &input) != nil {
writeError(w, 400, "任务配置格式无效")
return
}
input.ID = id
var saved uint64
saved, err = s.projects.SaveUserSchedule(r.Context(), u, input)
if err == nil {
id = saved
}
}
s.store.Log(r.Context(), u.TenantID, u.ID, action, "schedule", strconv.FormatUint(id, 10), requestClientIP(r), err == nil, "管理用户计划任务")
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 200, map[string]any{"id": id})
}
+14
View File
@@ -0,0 +1,14 @@
package identity
import (
"crypto/rand"
"encoding/hex"
)
func New(prefix string) (string, error) {
data := make([]byte, 16)
if _, err := rand.Read(data); err != nil {
return "", err
}
return prefix + "_" + hex.EncodeToString(data), nil
}
+671
View File
@@ -0,0 +1,671 @@
package isolation
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
var safeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`)
type Agent struct {
Root string
BackupRoot string
LegacyRoot string
FileOwner string
NodePIDRoot string
NginxVhostRoot, NginxBinary string
PurePWBinary string
PHPStateRoot, PHPRunRoot string
PythonManagerRoot string
PythonBuildRoot string
PythonMetadataBaseURL string
PythonMetadataCacheRoot string
PythonSourceBaseURLs []string
UsageStatePath, NginxLogRoot string
CertificateRoot, PureFTPConfig, PureFTPPem string
runCommand func(context.Context, string, ...string) error
lookupUID func(string) (uint64, error)
InternalToken string
databaseAdminDSN string
FTPLogPath string
}
func (a Agent) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/database/phpmyadmin",a.authorizeInternal(a.phpMyAdmin))
mux.HandleFunc("POST /v1/scheduler/configure",a.authorizeInternal(a.configureSchedulerBridge))
mux.HandleFunc("POST /v1/schedule/execute",a.authorizeInternal(a.executeSchedule))
mux.HandleFunc("POST /v1/ftp/disconnect",a.authorizeInternal(a.disconnectFTP))
mux.HandleFunc("POST /v1/site/startup",a.authorizeInternal(a.configureStartup))
mux.HandleFunc("POST /v1/site/settings",a.authorizeInternal(a.configureWebsite))
mux.HandleFunc("POST /v1/site/log",a.authorizeInternal(a.readSiteLog))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write([]byte(`{"status":"ok"}`))
})
mux.HandleFunc("POST /v1/prepare", a.authorizeInternal(a.prepare))
mux.HandleFunc("POST /v1/quarantine", a.authorizeInternal(a.quarantine))
mux.HandleFunc("POST /v1/web-protection/apply", a.authorizeInternal(a.applyWebProtection))
mux.HandleFunc("POST /v1/web-protection/remove", a.authorizeInternal(a.removeWebProtection))
mux.HandleFunc("POST /v1/runtime/executable", a.authorizeInternal(a.prepareExecutable))
mux.HandleFunc("POST /v1/runtime/panel-state", a.authorizeInternal(a.preparePanelRuntime))
mux.HandleFunc("POST /v1/runtime/python/install", a.authorizeInternal(a.installPythonRuntime))
mux.HandleFunc("POST /v1/runtime/probe", a.authorizeInternal(a.probeRuntime))
mux.HandleFunc("POST /v1/runtime/php/maintenance", a.authorizeInternal(a.maintainPHP))
mux.HandleFunc("POST /v1/runtime/backups/prune", a.authorizeInternal(a.pruneRuntimeBackups))
mux.HandleFunc("POST /v1/runtime/python/dependencies", a.authorizeInternal(a.copyPythonDependencies))
mux.HandleFunc("POST /v1/run-path/release", a.authorizeInternal(a.releaseRunPath))
mux.HandleFunc("POST /v1/trash/prepare", a.authorizeInternal(a.prepareTrash))
mux.HandleFunc("POST /v1/ftp/identity", a.authorizeInternal(a.configureFTPIdentity))
mux.HandleFunc("POST /v1/credentials/disconnect",a.authorizeInternal(a.disconnectCredentialSessions))
mux.HandleFunc("POST /v1/php/identity", a.authorizeInternal(a.configurePHPIdentity))
mux.HandleFunc("POST /v1/php/identity/start", a.authorizeInternal(a.startPHPIdentity))
mux.HandleFunc("POST /v1/php/identity/stop", a.authorizeInternal(a.stopPHPIdentity))
mux.HandleFunc("POST /v1/php/identity/remove", a.authorizeInternal(a.removePHPIdentity))
mux.HandleFunc("POST /v1/resources/usage", a.authorizeInternal(a.resourceUsage))
mux.HandleFunc("POST /v1/resources/processes/terminate", a.authorizeInternal(a.terminateProcesses))
mux.HandleFunc("POST /v1/resources/runtime/terminate", a.authorizeInternal(a.terminateRuntime))
mux.HandleFunc("POST /v1/project/freeze-writes", a.authorizeInternal(a.freezeWrites))
mux.HandleFunc("POST /v1/ftp/tls", a.authorizeInternal(a.configureFTPTLS))
mux.HandleFunc("POST /v1/nginx/network", a.authorizeInternal(a.configureNginxNetwork))
mux.HandleFunc("POST /v1/database/access", a.authorizeInternal(a.configureDatabaseAccess))
mux.HandleFunc("POST /v1/resources/limits", a.authorizeInternal(a.configureTrafficLimits))
mux.HandleFunc("POST /v1/lifecycle/backup", a.authorizeInternal(a.createProjectBackup))
mux.HandleFunc("POST /v1/lifecycle/backup/delete", a.authorizeInternal(a.deleteProjectBackup))
mux.HandleFunc("POST /v1/lifecycle/backup/verify", a.authorizeInternal(a.verifyProjectBackup))
mux.HandleFunc("POST /v1/lifecycle/project/purge", a.authorizeInternal(a.purgeProject))
mux.HandleFunc("POST /v1/import/project", a.authorizeInternal(a.importLegacyProject))
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){limit:=int64(64<<10);if r.URL.Path=="/v1/database/phpmyadmin"{limit=4<<20};r.Body=http.MaxBytesReader(w,r.Body,limit);mux.ServeHTTP(w,r)})
}
// freezeWrites leaves the unprivileged Sea vHost file service as owner so the
// tenant can delete content and recover below quota, while removing write
// access from the per-host runtime/FTP identity. Existing runtime-created
// files are first reclaimed because their owner may be the host identity.
func (a Agent) freezeWrites(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
if err = requirePhysicalDirectory(projectRoot); err != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
fileOwner := a.FileOwner
if fileOwner == "" {
fileOwner = "sea-vhost"
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
// aaPanel's immutable .user.ini is already root-owned and read-only. Exclude
// it from recursive ownership/ACL operations so the quota transition never
// needs to relax PHP's open_basedir guard.
if err = a.command(ctx, "find", projectRoot, "-xdev", "!", "-name", ".user.ini", "-exec", "chown", "-h", fileOwner+":"+spec.HostName, "{}", "+"); err != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "chmod", "u+rwx,g+rX,g-w,o-rwx", "{}", "+") != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "!", "-name", ".user.ini", "-exec", "chmod", "u+rw,g+r,g-w,o-rwx", "{}", "+") != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", "u:www:r-x,m::r-x,d:u:"+fileOwner+":rwx,d:u:www:r-x,d:g::r-x,d:m::r-x,d:o::---", "{}", "+") != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "!", "-name", ".user.ini", "-exec", "setfacl", "-m", "u:www:r--,m::r--,o::---", "{}", "+") != nil {
http.Error(w, "cannot freeze project writes", http.StatusInternalServerError)
return
}
runtimeRoot := filepath.Join(projectRoot, ".sea-runtime")
if err = requirePhysicalDirectory(runtimeRoot); err == nil {
if err = a.command(ctx, "find", runtimeRoot, "-xdev", "-exec", "setfacl", "-m", "u:www:---", "{}", "+"); err != nil {
http.Error(w, "cannot preserve private runtime directory", http.StatusInternalServerError)
return
}
} else if !errors.Is(err, os.ErrNotExist) {
http.Error(w, "unsafe private runtime directory", http.StatusPreconditionFailed)
return
}
if err = a.freezeFTPLogin(ctx, spec.HostName); err != nil {
http.Error(w, "cannot freeze FTP login", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) authorizeInternal(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if a.InternalToken != "" {
supplied := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if len(supplied) != len(a.InternalToken) || subtle.ConstantTimeCompare([]byte(supplied), []byte(a.InternalToken)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
}
next(w, r)
}
}
// releaseRunPath removes only aaPanel's immutable PHP isolation file from an
// exact managed run directory after its site has been deleted. Source files
// are deliberately retained and remain owned by the Sea vHost file service.
func (a Agent) releaseRunPath(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
runDirectory, err := physicalRunDirectory(projectRoot, spec.RunPath)
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(http.StatusOK)
return
}
if err != nil {
http.Error(w, "unsafe project run directory", http.StatusPreconditionFailed)
return
}
if err = a.removeUserINI(r.Context(), filepath.Join(runDirectory, ".user.ini")); err != nil {
http.Error(w, "cannot release PHP isolation file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// prepareTrash makes interrupted/deleted-site trash removable by the
// unprivileged API process. It may only unlock and remove regular .user.ini
// files below the fixed .sea-trash directory; it never deletes tenant data.
func (a Agent) prepareTrash(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
trash := filepath.Join(projectRoot, ".sea-trash")
info, err := os.Lstat(trash)
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(http.StatusOK)
return
}
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "unsafe trash directory", http.StatusPreconditionFailed)
return
}
files, err := findProjectUserINIFiles(trash, 128)
if err != nil {
http.Error(w, "unsafe PHP isolation file in trash", http.StatusPreconditionFailed)
return
}
for _, file := range files {
if err = a.removeUserINI(r.Context(), file); err != nil {
http.Error(w, "cannot release PHP isolation file in trash", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) removeUserINI(parent context.Context, file string) error {
info, err := os.Lstat(file)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("PHP isolation file is not a regular file")
}
ctx, cancel := context.WithTimeout(parent, 10*time.Second)
defer cancel()
if err = a.command(ctx, "chattr", "-i", file); err != nil {
return err
}
return os.Remove(file)
}
func (a Agent) command(ctx context.Context, name string, args ...string) error {
if a.runCommand != nil {
return a.runCommand(ctx, name, args...)
}
return command(ctx, name, args...)
}
func (a Agent) commandAt(ctx context.Context, directory, name string, args ...string) error {
if a.runCommand != nil {
return a.runCommand(ctx, name, args...)
}
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = directory
cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"}
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output)))
}
return nil
}
func (a Agent) prepareExecutable(w http.ResponseWriter, r *http.Request) {
var input ExecutableSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) || input.Project.TenantID == 0 || input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 || !validExecutablePath(input.RelativePath) {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(input.Project)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
root, err := os.OpenRoot(projectRoot)
if err != nil {
http.Error(w, "project root unavailable", http.StatusPreconditionFailed)
return
}
defer root.Close()
info, err := root.Lstat(input.RelativePath)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "runtime entry is not a regular file", http.StatusPreconditionFailed)
return
}
if err = root.Chmod(input.RelativePath, 0750); err != nil {
http.Error(w, "cannot mark runtime entry executable", http.StatusInternalServerError)
return
}
if err = a.command(r.Context(), "setfacl", "-m", "u:www:r--,g::r-x,m::r-x,o::---", filepath.Join(projectRoot, filepath.FromSlash(input.RelativePath))); err != nil {
http.Error(w, "cannot apply executable identity ACL", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func validExecutablePath(value string) bool {
if value == "" || len(value) > 255 || strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || filepath.ToSlash(filepath.Clean("/"+value)) != "/"+value {
return false
}
for _, segment := range strings.Split(value, "/") {
if segment == "" || segment == "." || segment == ".." || len(segment) > 100 {
return false
}
for _, character := range segment {
if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) {
return false
}
}
}
return true
}
func (a Agent) decode(w http.ResponseWriter, r *http.Request) (ProjectSpec, bool) {
var spec ProjectSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if spec.RunPath == "" {
spec.RunPath = "/"
}
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(spec.HostName) || !validProjectRunPath(spec.RunPath) || spec.TenantID == 0 || spec.TenantID > 9_999_999_999 || spec.StorageBytes == 0 || spec.ProcessLimit == 0 || spec.ProcessLimit > 100_000 {
http.Error(w, "invalid request", http.StatusBadRequest)
return ProjectSpec{}, false
}
return spec, true
}
func (a Agent) projectPath(spec ProjectSpec) (string, error) {
base, err := filepath.Abs(a.Root)
if err != nil {
return "", err
}
projectRoot := filepath.Join(base, spec.HostName)
relative, err := filepath.Rel(base, projectRoot)
if err != nil || relative != spec.HostName || strings.Contains(relative, string(os.PathSeparator)) {
return "", errors.New("path outside root")
}
return projectRoot, nil
}
func (a Agent) prepare(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
runtimeUser := spec.HostName
fileOwner := a.FileOwner
if fileOwner == "" {
fileOwner = "sea-vhost"
}
runtimeGroup := runtimeUser
base := filepath.Dir(projectRoot)
if err = ensureDirectory(base, 0755); err != nil {
http.Error(w, "unsafe tenant root", http.StatusPreconditionFailed)
return
}
if err = a.ensureHostIdentity(ctx, spec, projectRoot); err != nil {
http.Error(w, "cannot create isolated project identity", http.StatusInternalServerError)
return
}
// /www/wwwroot is shared with aaPanel and may already contain sites. Never
// change its owner or mode; Sea vHost only mutates its random host directory.
if err = ensureDirectory(projectRoot, 0770); err != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
if err = ensureProjectRunDirectory(projectRoot, spec.RunPath); err != nil {
http.Error(w, "unsafe project run directory", http.StatusPreconditionFailed)
return
}
userINIFiles, err := findProjectUserINIFiles(projectRoot, 64)
if err != nil {
http.Error(w, "unsafe PHP isolation file", http.StatusPreconditionFailed)
return
}
unlockedUserINI := make([]string, 0, len(userINIFiles))
defer func() {
if len(unlockedUserINI) == 0 {
return
}
lockCtx, cancelLock := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelLock()
for _, userINI := range unlockedUserINI {
_ = command(lockCtx, "chattr", "+i", userINI)
}
}()
for _, userINI := range userINIFiles {
if err = command(ctx, "chattr", "-i", userINI); err != nil {
http.Error(w, "cannot unlock PHP isolation file", http.StatusInternalServerError)
return
}
unlockedUserINI = append(unlockedUserINI, userINI)
}
if err = a.command(ctx, "setfacl", "-Rb", projectRoot); err != nil {
http.Error(w, "cannot reset project ACL", http.StatusInternalServerError)
return
}
if err = a.command(ctx, "chown", "-hR", fileOwner+":"+runtimeGroup, projectRoot); err != nil {
http.Error(w, "cannot set project owner", http.StatusInternalServerError)
return
}
if err = a.command(ctx, "chmod", "-R", "u+rwX,g+rwX,o-rwx", projectRoot); err != nil || a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "chmod", "g+s", "{}", "+") != nil {
http.Error(w, "cannot set project permissions", http.StatusInternalServerError)
return
}
if err = a.applyProjectACL(ctx, projectRoot, fileOwner); err != nil {
http.Error(w, "cannot apply isolated project ACL", http.StatusInternalServerError)
return
}
for _, userINI := range userINIFiles {
if err = a.command(ctx, "chown", "root:root", userINI); err != nil || a.command(ctx, "chmod", "0644", userINI) != nil || a.command(ctx, "chattr", "+i", userINI) != nil {
http.Error(w, "cannot secure PHP isolation file", http.StatusInternalServerError)
return
}
}
unlockedUserINI = nil
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(Prepared{RootPath: filepath.ToSlash(projectRoot), RunUser: runtimeUser})
}
func (a Agent) ensureHostIdentity(ctx context.Context, spec ProjectSpec, projectRoot string) error {
name := spec.HostName
if err := a.command(ctx, "getent", "group", name); err != nil {
if err = a.command(ctx, "groupadd", "--system", name); err != nil {
return err
}
}
// The OS identity is only a process/ownership boundary. It deliberately has
// no usable home directory; FTP keeps its independent Pure-FTPd chroot at
// projectRoot and does not rely on the passwd home field.
const disabledHome = "/nonexistent"
if err := a.command(ctx, "id", "-u", name); err != nil {
// aaPanel's built-in Python project model intentionally ignores system
// accounts below UID_MIN. Allocate from the normal UID range while still
// disabling login, passwords and home-directory creation. This preserves
// process isolation without depending on a panel-version-specific user
// whitelist.
if err = a.command(ctx, "useradd", "--gid", name, "--home-dir", disabledHome, "--no-create-home", "--shell", "/usr/sbin/nologin", name); err != nil {
return err
}
}
if err := a.command(ctx, "usermod", "--gid", name, "--groups", name, "--home", disabledHome, "--shell", "/usr/sbin/nologin", name); err != nil {
return err
}
return a.command(ctx, "passwd", "--lock", name)
}
func (a Agent) applyProjectACL(ctx context.Context, projectRoot, fileOwner string) error {
directoryACL := "u:www:r-x,m::rwx,d:u:" + fileOwner + ":rwx,d:u:www:r-x,d:g::rwx,d:m::rwx,d:o::---"
if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", directoryACL, "{}", "+"); err != nil {
return err
}
if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "-exec", "setfacl", "-m", "u:www:r--,m::rw-,o::---", "{}", "+"); err != nil {
return err
}
// A directory repair must not revoke execution from existing Go binaries,
// venv tools or tenant scripts. www remains read-only even on these files.
if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "-perm", "/111", "-exec", "setfacl", "-m", "u:www:r--,m::rwx,o::---", "{}", "+"); err != nil {
return err
}
// Every website can use its own run directory. Preserve private runtime
// trees at all depths, and never follow venv executable symlinks while
// applying ACLs (those may point to shared server-owned interpreters).
return filepath.WalkDir(projectRoot, func(current string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() && entry.Name() == ".sea-runtime" {
if err := a.securePythonRuntimeACL(ctx, current); err != nil {
return err
}
return filepath.SkipDir
}
return nil
})
}
func findProjectUserINIFiles(projectRoot string, limit int) ([]string, error) {
files := make([]string, 0, 2)
err := filepath.WalkDir(projectRoot, func(current string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.Type()&os.ModeSymlink != 0 {
if entry.Name() == ".user.ini" {
return errors.New("PHP isolation file is a symlink")
}
return nil
}
if entry.Name() != ".user.ini" {
return nil
}
info, err := entry.Info()
if err != nil || !info.Mode().IsRegular() {
return errors.New("PHP isolation file is not regular")
}
files = append(files, current)
if len(files) > limit {
return errors.New("too many PHP isolation files")
}
return nil
})
return files, err
}
func (a Agent) quarantine(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
source := projectRoot
info, statErr := os.Lstat(source)
if statErr != nil && os.IsNotExist(statErr) {
w.WriteHeader(http.StatusOK)
return
}
if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
trash := filepath.Join(a.Root, ".sea-vhost-quarantine")
if err = ensureDirectory(trash, 0700); err != nil || a.command(ctx, "chown", "root:root", trash) != nil || a.command(ctx, "chmod", "0700", trash) != nil {
http.Error(w, "cannot create quarantine", http.StatusInternalServerError)
return
}
target := filepath.Join(trash, fmt.Sprintf("%s-%d", spec.HostName, time.Now().Unix()))
if err = os.Rename(source, target); err != nil {
http.Error(w, "cannot quarantine", http.StatusInternalServerError)
return
}
// Named ACL entries are stored by numeric UID. Remove any Node.js PID
// access before deleting the account so a future UID reuse cannot inherit
// access to another host's process state. Restore the project directory if
// revocation fails so deletion remains safely retryable.
if err = a.revokeNodePIDAccess(ctx, spec.HostName); err != nil {
_ = os.Rename(target, source)
http.Error(w, "cannot revoke isolated Node.js PID access", http.StatusInternalServerError)
return
}
if a.command(ctx, "id", "-u", spec.HostName) == nil {
if err = a.command(ctx, "userdel", spec.HostName); err != nil {
http.Error(w, "cannot remove isolated project identity", http.StatusInternalServerError)
return
}
}
if a.command(ctx, "getent", "group", spec.HostName) == nil {
if err = a.command(ctx, "groupdel", spec.HostName); err != nil {
http.Error(w, "cannot remove isolated project group", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}
func command(ctx context.Context, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"}
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output)))
}
return nil
}
func ensureDirectory(path string, mode os.FileMode) error {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
if err = os.Mkdir(path, mode); err != nil {
return err
}
info, err = os.Lstat(path)
}
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("path is not a physical directory")
}
return nil
}
func ensureProjectRunDirectory(projectRoot, runPath string) error {
if !validProjectRunPath(runPath) {
return errors.New("invalid run path")
}
if runPath == "/" {
return nil
}
root, err := os.OpenRoot(projectRoot)
if err != nil {
return err
}
defer root.Close()
current := ""
for _, segment := range strings.Split(strings.TrimPrefix(runPath, "/"), "/") {
if current == "" {
current = segment
} else {
current += "/" + segment
}
info, statErr := root.Lstat(current)
if errors.Is(statErr, os.ErrNotExist) {
if err = root.Mkdir(current, 0770); err != nil {
return err
}
info, statErr = root.Lstat(current)
}
if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("run path is not a physical directory")
}
}
return nil
}
func physicalRunDirectory(projectRoot, runPath string) (string, error) {
if !validProjectRunPath(runPath) {
return "", errors.New("invalid run path")
}
root, err := os.OpenRoot(projectRoot)
if err != nil {
return "", err
}
defer root.Close()
if runPath == "/" {
return projectRoot, nil
}
current := ""
for _, segment := range strings.Split(strings.TrimPrefix(runPath, "/"), "/") {
if current == "" {
current = segment
} else {
current += "/" + segment
}
info, statErr := root.Lstat(current)
if statErr != nil {
return "", statErr
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return "", errors.New("run path is not a physical directory")
}
}
return filepath.Join(projectRoot, filepath.FromSlash(strings.TrimPrefix(runPath, "/"))), nil
}
func validProjectRunPath(value string) bool {
if value == "/" {
return true
}
if len(value) < 2 || len(value) > 255 || !strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || filepath.ToSlash(filepath.Clean(value)) != value {
return false
}
for _, segment := range strings.Split(strings.TrimPrefix(value, "/"), "/") {
if segment == "" || segment == "." || segment == ".." || len(segment) > 80 {
return false
}
for _, character := range segment {
if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) {
return false
}
}
}
return true
}
+657
View File
@@ -0,0 +1,657 @@
package isolation
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func lifecycleRequest(t *testing.T, agent Agent, route string, value any) *httptest.ResponseRecorder {
t.Helper()
body, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(body))
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
return response
}
func TestLifecycleBackupArchivesOnlyManagedProject(t *testing.T) {
root, backupRoot := t.TempDir(), t.TempDir()
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(filepath.Join(projectRoot, "public"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(projectRoot, "public", "marker.txt"), []byte("tenant-marker"), 0600); err != nil {
t.Fatal(err)
}
response := lifecycleRequest(t, Agent{Root: root, BackupRoot: backupRoot}, "/v1/lifecycle/backup", ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1})
if response.Code != http.StatusOK {
t.Fatalf("backup status=%d body=%s", response.Code, response.Body.String())
}
var backup ProjectBackup
if err := json.Unmarshal(response.Body.Bytes(), &backup); err != nil {
t.Fatal(err)
}
file, err := os.Open(backup.ArchivePath)
if err != nil {
t.Fatal(err)
}
defer file.Close()
gzipReader, err := gzip.NewReader(file)
if err != nil {
t.Fatal(err)
}
tarReader := tar.NewReader(gzipReader)
found := false
for {
header, nextErr := tarReader.Next()
if errors.Is(nextErr, io.EOF) {
break
}
if nextErr != nil {
t.Fatal(nextErr)
}
if header.Name == hostName+"/public/marker.txt" {
found = true
}
if strings.Contains(header.Name, "..") || strings.HasPrefix(header.Name, "/") {
t.Fatalf("unsafe archive path %q", header.Name)
}
}
if !found {
t.Fatal("managed marker was not archived")
}
}
func TestLifecyclePurgeIsIdempotentAndRemovesIdentity(t *testing.T) {
root := t.TempDir()
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(projectRoot, 0700); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 4)
agent := Agent{Root: root, runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
if name == "id" || name == "getent" {
return nil
}
return nil
}}
spec := ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
response := lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec)
if response.Code != http.StatusOK {
t.Fatalf("purge status=%d body=%s", response.Code, response.Body.String())
}
if _, err := os.Stat(projectRoot); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("project directory still exists: %v", err)
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "userdel "+hostName) || !strings.Contains(joined, "groupdel "+hostName) {
t.Fatalf("identity cleanup missing: %s", joined)
}
commands = nil
agent.runCommand = func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return errors.New("missing")
}
response = lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec)
if response.Code != http.StatusOK || strings.Contains(strings.Join(commands, "\n"), "userdel") {
t.Fatalf("retry was not idempotent: status=%d commands=%v", response.Code, commands)
}
}
func TestAgentHealthCheck(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
response := httptest.NewRecorder()
Agent{}.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"status":"ok"`) {
t.Fatalf("unexpected health response: %d %s", response.Code, response.Body.String())
}
}
func TestAgentMutationRequiresInternalToken(t *testing.T) {
agent := Agent{InternalToken: strings.Repeat("i", 32)}
request := httptest.NewRequest(http.MethodPost, "/v1/prepare", strings.NewReader(`{}`))
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated mutation status = %d, want 401", response.Code)
}
}
func TestHostIdentityHasNoUsableHomeDirectory(t *testing.T) {
commands := make([]string, 0, 2)
agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
if name == "getent" || name == "id" {
return errors.New("not found")
}
return nil
}}
if err := agent.ensureHostIdentity(context.Background(), ProjectSpec{HostName: "sv0123456789"}, "/www/wwwroot/seavHost/vHost/sv0123456789"); err != nil {
t.Fatal(err)
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "usermod --gid sv0123456789 --groups sv0123456789 --home /nonexistent --shell /usr/sbin/nologin sv0123456789") {
t.Fatalf("identity did not use the disabled home: %s", joined)
}
if strings.Contains(joined, "--home /www/wwwroot") {
t.Fatalf("project root was used as an OS home: %s", joined)
}
if !strings.Contains(joined, "useradd --gid sv0123456789 --home-dir /nonexistent --no-create-home --shell /usr/sbin/nologin sv0123456789") {
t.Fatalf("identity was not allocated from the normal UID range: %s", joined)
}
if strings.Contains(joined, "useradd --system") {
t.Fatalf("identity used a system UID rejected by aaPanel Python: %s", joined)
}
}
func TestPreparePanelRuntimeGrantsOnlyNodePIDDirectoryAccess(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
pidRoot := filepath.Join(t.TempDir(), "pids")
hostName := "sv0123456789"
if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(pidRoot, 0755); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 2)
agent := Agent{
Root: root, NodePIDRoot: pidRoot,
lookupUID: func(string) (uint64, error) { return 1001, nil },
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
},
}
spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Node.js"}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String())
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "chmod +t "+pidRoot) || !strings.Contains(joined, "setfacl -m u:"+hostName+":rwx,m::rwx "+pidRoot) {
t.Fatalf("unexpected Node.js compatibility commands: %s", joined)
}
if strings.Contains(joined, filepath.Join(root, hostName)+" ") {
t.Fatalf("Node.js compatibility grant escaped the fixed PID directory: %s", joined)
}
}
func TestPreparePanelRuntimeRejectsLegacyPythonUID(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil {
t.Fatal(err)
}
agent := Agent{Root: root, lookupUID: func(string) (uint64, error) { return 999, nil }}
spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body)))
if response.Code != http.StatusPreconditionFailed || !strings.Contains(response.Body.String(), "legacy host UID") {
t.Fatalf("legacy Python UID status = %d, body = %s", response.Code, response.Body.String())
}
}
func TestPreparePanelRuntimeCreatesIsolatedPythonVirtualEnvironment(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
managerRoot := filepath.Join(t.TempDir(), "versions")
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
basePython := filepath.Join(managerRoot, "3.12.0", "bin", "python3")
if err := os.MkdirAll(projectRoot, 0770); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(basePython), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(basePython, []byte("test"), 0755); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 3)
agent := Agent{
Root: root, FileOwner: "sea-vhost", PythonManagerRoot: managerRoot,
lookupUID: func(string) (uint64, error) { return 1001, nil },
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
if name == "runuser" {
venvPath := args[len(args)-1]
if err := os.MkdirAll(filepath.Join(venvPath, "bin"), 0770); err != nil {
return err
}
return os.WriteFile(filepath.Join(venvPath, "bin", "python3"), []byte("test"), 0755)
}
return nil
},
}
spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String())
}
venvPath := filepath.Join(projectRoot, ".sea-runtime", "python", hostName+"-3.12.0")
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "runuser -u "+hostName+" -- "+basePython+" -m venv --system-site-packages "+venvPath) {
t.Fatalf("Python venv command was not confined: %s", joined)
}
if !strings.Contains(joined, "-xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") {
t.Fatalf("Python ACL command did not exclude virtualenv symlinks: %s", joined)
}
}
func TestFreezeWritesReclaimsOwnershipAndRemovesRuntimeWriteAccess(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(projectRoot, 0770); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 5)
agent := Agent{Root: root, FileOwner: "sea-vhost", PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String())
}
joined := strings.Join(commands, "\n")
for _, expected := range []string{
"chown -h sea-vhost:" + hostName,
"chmod u+rwx,g+rX,g-w,o-rwx",
"chmod u+rw,g+r,g-w,o-rwx",
"d:g::r-x,d:m::r-x",
"u:www:r--,m::r--",
} {
if !strings.Contains(joined, expected) {
t.Fatalf("freeze commands missing %q: %s", expected, joined)
}
}
if !strings.Contains(joined, "! -name .user.ini") {
t.Fatalf("freeze commands did not preserve immutable .user.ini: %s", joined)
}
}
func TestFreezeWritesKeepsRuntimeDirectoryPrivate(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(filepath.Join(projectRoot, ".sea-runtime"), 0770); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 6)
agent := Agent{Root: root, PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String())
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, filepath.Join(projectRoot, ".sea-runtime")+" -xdev -exec setfacl -m u:www:---") {
t.Fatalf("freeze did not restore the runtime privacy ACL: %s", joined)
}
}
func TestBandwidthMeterCountsOnlyCompleteCurrentMonthLines(t *testing.T) {
root := t.TempDir()
logPath := filepath.Join(root, "example.test.log")
initial := "127.0.0.1 - - [30/Sep/2026:23:59:59 +0800] \"GET /old HTTP/1.1\" 200 90 \"-\" \"test\"\n" +
"127.0.0.1 - - [18/Oct/2026:10:00:00 +0800] \"GET / HTTP/1.1\" 200 120 \"-\" \"test\"\n"
if err := os.WriteFile(logPath, []byte(initial), 0600); err != nil {
t.Fatal(err)
}
cursor, err := measureDomainLog(logPath, trafficCursor{Month: "2026-10"}, "2026-10")
if err != nil || cursor.Bytes != 120 {
t.Fatalf("cursor=%+v err=%v", cursor, err)
}
completeOffset := cursor.Offset
file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
_, _ = file.WriteString("127.0.0.1 - - [18/Oct/2026:10:00:01 +0800] \"GET /next HTTP/1.1\" 200 45")
_ = file.Close()
cursor, err = measureDomainLog(logPath, cursor, "2026-10")
if err != nil || cursor.Bytes != 120 || cursor.Offset != completeOffset {
t.Fatalf("partial cursor=%+v err=%v", cursor, err)
}
file, _ = os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600)
_, _ = file.WriteString(" \"-\" \"test\"\n")
_ = file.Close()
cursor, err = measureDomainLog(logPath, cursor, "2026-10")
if err != nil || cursor.Bytes != 165 {
t.Fatalf("completed cursor=%+v err=%v", cursor, err)
}
}
func TestMeasureProjectStorageCountsManagedTreeWithoutFollowingSymlinks(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "private", "nested"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "index.html"), []byte("12345"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "private", "nested", "data.bin"), []byte("1234567"), 0600); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "outside.bin")
if err := os.WriteFile(outside, make([]byte, 1024*1024), 0600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "outside-link")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
usage, err := measureProjectStorage(root)
if err != nil {
t.Fatal(err)
}
linkInfo, err := os.Lstat(link)
if err != nil {
t.Fatal(err)
}
want := uint64(12 + linkInfo.Size())
if usage != want {
t.Fatalf("usage = %d, want %d", usage, want)
}
}
func TestMeasureProjectStorageRejectsSymlinkRoot(t *testing.T) {
realRoot := t.TempDir()
link := filepath.Join(t.TempDir(), "host-link")
if err := os.Symlink(realRoot, link); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
if _, err := measureProjectStorage(link); err == nil {
t.Fatal("symlink project root was accepted")
}
}
func TestPHPAdapterUsesPrivateSocketWithoutDuplicatingAAPanelLocation(t *testing.T) {
adapter := renderPHPNginxAdapter("/run/sea-vhost-php/sv0123456789.sock")
if strings.Contains(adapter, "location ~ [^/]\\.php(/|$)") {
t.Fatal("adapter duplicates aaPanel's shared PHP location")
}
if !strings.Contains(adapter, "location ~ ^.+\\.php(?:/|$)") ||
!strings.Contains(adapter, "fastcgi_pass unix:/run/sea-vhost-php/sv0123456789.sock;") {
t.Fatalf("adapter does not route PHP to the private socket:\n%s", adapter)
}
}
func TestPHPConfigRunsMasterAsPreselectedHostIdentity(t *testing.T) {
paths := phpIdentityPaths{
config: "/var/lib/sea-vhost-agent/php/sv0123456789.conf",
pid: "/run/sea-vhost-php/sv0123456789/php-fpm.pid",
socket: "/run/sea-vhost-php/sv0123456789/php-fpm.sock",
}
spec := PHPIdentitySpec{
Project: ProjectSpec{HostName: "sv0123456789"},
SiteName: "sv0123456789", ProcessLimit: 4,
}
config := renderPHPIdentityConfig(spec, "/www/wwwroot/seavHost/vHost/sv0123456789", "/www/wwwroot/seavHost/vHost/sv0123456789/.sea-runtime/php", paths)
for _, forbidden := range []string{"listen.owner", "listen.group"} {
if strings.Contains(config, forbidden) {
t.Fatalf("non-root PHP master config contains root-only directive %q", forbidden)
}
}
for _, required := range []string{paths.pid, paths.socket, "/.sea-runtime/php/fpm-error.log", "user = sv0123456789", "group = sv0123456789"} {
if !strings.Contains(config, required) {
t.Fatalf("PHP config is missing %q:\n%s", required, config)
}
}
}
func TestEnsureProjectRunDirectoryCreatesOnlyPhysicalChildren(t *testing.T) {
root := t.TempDir()
if err := ensureProjectRunDirectory(root, "/apps/web/public"); err != nil {
t.Fatal(err)
}
if info, err := os.Lstat(filepath.Join(root, "apps", "web", "public")); err != nil || !info.IsDir() {
t.Fatalf("run directory was not created: info=%v err=%v", info, err)
}
if err := os.Symlink(filepath.Join(root, "apps"), filepath.Join(root, "linked")); err == nil {
if err = ensureProjectRunDirectory(root, "/linked/public"); err == nil {
t.Fatal("symlinked run directory was accepted")
}
}
for _, unsafe := range []string{"/../etc", "/public/../etc", "/has space", `C:\\Windows`} {
if ensureProjectRunDirectory(root, unsafe) == nil {
t.Fatalf("unsafe run path %q was accepted", unsafe)
}
}
}
func TestFindProjectUserINIFilesIncludesNestedFilesAndRejectsSymlinks(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "public")
if err := os.MkdirAll(public, 0750); err != nil {
t.Fatal(err)
}
for _, name := range []string{filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")} {
if err := os.WriteFile(name, []byte("open_basedir=/tmp"), 0644); err != nil {
t.Fatal(err)
}
}
files, err := findProjectUserINIFiles(root, 4)
if err != nil || len(files) != 2 {
t.Fatalf("files=%#v err=%v", files, err)
}
if err = os.Remove(filepath.Join(public, ".user.ini")); err != nil {
t.Fatal(err)
}
if err = os.Symlink(filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
if _, err = findProjectUserINIFiles(root, 4); err == nil {
t.Fatal("symlinked .user.ini was accepted")
}
}
func TestReleaseRunPathRemovesOnlyExactIsolationFile(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
runDirectory := filepath.Join(root, hostName, "apps", "web")
if err := os.MkdirAll(runDirectory, 0770); err != nil {
t.Fatal(err)
}
userINI := filepath.Join(runDirectory, ".user.ini")
source := filepath.Join(runDirectory, "index.php")
if err := os.WriteFile(userINI, []byte("open_basedir=/tmp"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(source, []byte("<?php"), 0660); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 1)
agent := Agent{Root: root, runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/apps/web", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/run-path/release", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("release status = %d, body = %s", response.Code, response.Body.String())
}
if _, err := os.Stat(userINI); !os.IsNotExist(err) {
t.Fatalf(".user.ini still exists: %v", err)
}
if _, err := os.Stat(source); err != nil {
t.Fatalf("source was changed: %v", err)
}
if len(commands) != 1 || !strings.HasPrefix(commands[0], "chattr -i ") {
t.Fatalf("commands = %#v", commands)
}
}
func TestPrepareTrashReleasesNestedIsolationFiles(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "svabcdef0123"
trash := filepath.Join(root, hostName, ".sea-trash", "old-public")
if err := os.MkdirAll(trash, 0770); err != nil {
t.Fatal(err)
}
userINI := filepath.Join(trash, ".user.ini")
if err := os.WriteFile(userINI, []byte("open_basedir=/tmp"), 0644); err != nil {
t.Fatal(err)
}
agent := Agent{Root: root, runCommand: func(context.Context, string, ...string) error { return nil }}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/trash/prepare", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("prepare trash status = %d, body = %s", response.Code, response.Body.String())
}
if _, err := os.Stat(userINI); !os.IsNotExist(err) {
t.Fatalf("trash .user.ini still exists: %v", err)
}
}
func TestWebProtectionUsesFixedAaPanelExtensionAndReloadsSafely(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
vhostRoot := filepath.Join(t.TempDir(), "nginx")
hostName := "sv0123456789"
domain := hostName + ".hosts.example.com"
if err := os.MkdirAll(filepath.Join(root, hostName, "public"), 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(vhostRoot, "extension"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(vhostRoot, "sea-vhost-security-global.conf"), []byte(globalWebProtectionConfig), 0644); err != nil {
t.Fatal(err)
}
extensionGlob := filepath.ToSlash(filepath.Join(vhostRoot, "extension", domain, "*.conf"))
if err := os.WriteFile(filepath.Join(vhostRoot, domain+".conf"), []byte("server { include "+extensionGlob+"; }"), 0644); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 2)
agent := Agent{
Root: root, NginxVhostRoot: vhostRoot, NginxBinary: filepath.Join(t.TempDir(), "nginx"),
runCommand: func(_ context.Context, _ string, args ...string) error {
commands = append(commands, strings.Join(args, " "))
return nil
},
}
spec := WebProtectionSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/public", StorageBytes: 1 << 30, ProcessLimit: 10}, Domain: domain}
body, _ := json.Marshal(spec)
request := httptest.NewRequest(http.MethodPost, "/v1/web-protection/apply", bytes.NewReader(body))
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("apply status = %d, body = %s", response.Code, response.Body.String())
}
siteFile := filepath.Join(vhostRoot, "extension", domain, "sea-vhost-security.conf")
content, err := os.ReadFile(siteFile)
if err != nil {
t.Fatal(err)
}
for _, expected := range []string{"root \"" + filepath.ToSlash(filepath.Join(root, hostName, "public")) + "\";", "limit_req zone=sea_vhost_per_ip", "client_max_body_size 64m", "X-Content-Type-Options", "TRACE|TRACK"} {
if !strings.Contains(string(content), expected) {
t.Fatalf("site protection is missing %q", expected)
}
}
if len(commands) != 2 || commands[0] != "-t" || commands[1] != "-s reload" {
t.Fatalf("nginx commands = %#v", commands)
}
request = httptest.NewRequest(http.MethodPost, "/v1/web-protection/remove", bytes.NewReader(body))
response = httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("remove status = %d, body = %s", response.Code, response.Body.String())
}
if _, err = os.Stat(siteFile); !os.IsNotExist(err) {
t.Fatalf("site protection still exists after removal: %v", err)
}
}
func TestWebProtectionRejectsUnmanagedIdentity(t *testing.T) {
spec := WebProtectionSpec{Project: ProjectSpec{TenantID: 1, HostName: "tenant-site", StorageBytes: 1024, ProcessLimit: 1}, Domain: "outside.example.com"}
body, _ := json.Marshal(spec)
request := httptest.NewRequest(http.MethodPost, "/v1/web-protection/apply", bytes.NewReader(body))
response := httptest.NewRecorder()
Agent{}.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("unmanaged identity status = %d, want 400", response.Code)
}
}
func TestWebProtectionRestoresFilesWhenNginxRejectsConfig(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
vhostRoot := filepath.Join(t.TempDir(), "nginx")
hostName := "svabcdef0123"
domain := hostName + ".hosts.example.com"
siteDirectory := filepath.Join(vhostRoot, "extension", domain)
if err := os.MkdirAll(filepath.Join(root, hostName), 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(siteDirectory, 0755); err != nil {
t.Fatal(err)
}
extensionGlob := filepath.ToSlash(filepath.Join(siteDirectory, "*.conf"))
if err := os.WriteFile(filepath.Join(vhostRoot, domain+".conf"), []byte("server { include "+extensionGlob+"; }"), 0644); err != nil {
t.Fatal(err)
}
globalFile := filepath.Join(vhostRoot, "sea-vhost-security-global.conf")
siteFile := filepath.Join(siteDirectory, "sea-vhost-security.conf")
if err := os.WriteFile(globalFile, []byte(globalWebProtectionConfig), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(siteFile, []byte("old-site"), 0644); err != nil {
t.Fatal(err)
}
agent := Agent{
Root: root, NginxVhostRoot: vhostRoot, NginxBinary: filepath.Join(t.TempDir(), "nginx"),
runCommand: func(_ context.Context, _ string, args ...string) error {
if len(args) == 1 && args[0] == "-t" {
return errors.New("invalid nginx config")
}
return nil
},
}
spec := WebProtectionSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, StorageBytes: 1024, ProcessLimit: 1}, Domain: domain}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/web-protection/apply", bytes.NewReader(body)))
if response.Code != http.StatusPreconditionFailed {
t.Fatalf("apply status = %d, want 412", response.Code)
}
globalContent, _ := os.ReadFile(globalFile)
siteContent, _ := os.ReadFile(siteFile)
if string(globalContent) != globalWebProtectionConfig || string(siteContent) != "old-site" {
t.Fatalf("rollback failed: global=%q site=%q", globalContent, siteContent)
}
}
+120
View File
@@ -0,0 +1,120 @@
package isolation
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
func (a Agent) verifyProjectBackup(w http.ResponseWriter, r *http.Request) {
var backup ProjectBackup
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&backup) != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(backup.HostName) || backup.TenantID == 0 || backup.DatabaseCount < 0 || backup.DatabaseCount > 1 {
http.Error(w, "invalid backup verification", 400)
return
}
directory, err := a.backupDirectory(backup.TenantID)
path := filepath.Clean(backup.ArchivePath)
if err != nil || filepath.Dir(path) != directory || !strings.HasPrefix(filepath.Base(path), backup.HostName+"-") || !strings.HasSuffix(path, ".tar.gz") {
http.Error(w, "unsafe backup path", 400)
return
}
if err = verifyRecoveryArchive(r.Context(), path, backup.HostName, backup.DatabaseCount); err != nil {
http.Error(w, "recovery archive is missing, incomplete or corrupt", 412)
return
}
w.WriteHeader(200)
}
func verifyRecoveryArchive(ctx context.Context, path, hostName string, count int) error {
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("unsafe recovery archive")
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
compressed, err := gzip.NewReader(file)
if err != nil {
return err
}
defer compressed.Close()
reader := tar.NewReader(compressed)
type database struct {
Name, Path, SHA256 string
Bytes int64
}
var manifest struct {
Format int
HostName string
Databases []database
}
hashes := map[string]string{}
sizes := map[string]int64{}
hasManifest := false
for {
if ctx.Err() != nil {
return ctx.Err()
}
header, nextErr := reader.Next()
if nextErr == io.EOF {
break
}
if nextErr != nil {
return nextErr
}
if header.Name == ".sea-vhost-backup/manifest.json" {
if hasManifest || header.Size > 64<<10 {
return errors.New("invalid recovery manifest")
}
data, readErr := io.ReadAll(reader)
if readErr != nil {
return readErr
}
if json.Unmarshal(data, &manifest) != nil {
return errors.New("invalid recovery manifest")
}
hasManifest = true
} else if strings.HasPrefix(header.Name, ".sea-vhost-backup/databases/") {
if header.Name != ".sea-vhost-backup/databases/"+hostName+".sql" || header.Typeflag != tar.TypeReg || hashes[header.Name] != "" {
return errors.New("invalid database archive entry")
}
digest := sha256.New()
size, copyErr := io.Copy(digest, reader)
if copyErr != nil {
return copyErr
}
hashes[header.Name] = fmt.Sprintf("%x", digest.Sum(nil))
sizes[header.Name] = size
} else {
if _, err = io.Copy(io.Discard, reader); err != nil {
return err
}
}
}
// Read the gzip trailer as well; tar's end marker alone does not validate CRC.
if _, err = io.Copy(io.Discard, compressed); err != nil {
return err
}
if !hasManifest || manifest.Format != 2 || manifest.HostName != hostName || len(manifest.Databases) != count || len(hashes) != count {
return errors.New("incomplete recovery archive")
}
for _, db := range manifest.Databases {
if db.Name != hostName || db.SHA256 != hashes[db.Path] || db.Bytes != sizes[db.Path] || db.Bytes == 0 {
return errors.New("database recovery checksum mismatch")
}
}
return nil
}
+184
View File
@@ -0,0 +1,184 @@
package isolation
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
type Client struct {
http *http.Client
longHTTP *http.Client
internalToken string
}
func NewTransportClient(transport http.RoundTripper) *Client {
return &Client{http: &http.Client{Transport: transport, Timeout: 30 * time.Second}, longHTTP: &http.Client{Transport: transport, Timeout: 2 * time.Hour}}
}
func NewClient(socket string, internalToken ...string) *Client {
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}}
token := ""
if len(internalToken) > 0 {
token = strings.TrimSpace(internalToken[0])
}
return &Client{http: &http.Client{Transport: transport, Timeout: 30 * time.Second}, longHTTP: &http.Client{Transport: transport, Timeout: 2 * time.Hour}, internalToken: token}
}
func (c *Client) Ping(ctx context.Context) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://unix/healthz", nil)
if err != nil {
return err
}
if c.internalToken != "" {
request.Header.Set("Authorization", "Bearer "+c.internalToken)
}
response, err := c.http.Do(request)
if err != nil {
return fmt.Errorf("isolation agent: %w", err)
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4<<10))
if response.StatusCode != http.StatusOK {
return fmt.Errorf("isolation agent health check failed (%d)", response.StatusCode)
}
return nil
}
func (c *Client) request(ctx context.Context, path string, input any, out any) error {
return c.requestWithClient(ctx, c.http, path, input, out)
}
func (c *Client) requestLong(ctx context.Context, path string, input any, out any) error {
return c.requestWithClient(ctx, c.longHTTP, path, input, out)
}
func (c *Client) requestWithClient(ctx context.Context, client *http.Client, path string, input any, out any) error {
body, err := json.Marshal(input)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://unix"+path, bytes.NewReader(body))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
if c.internalToken != "" {
request.Header.Set("Authorization", "Bearer "+c.internalToken)
}
response, err := client.Do(request)
if err != nil {
return fmt.Errorf("isolation agent: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
message, _ := io.ReadAll(io.LimitReader(response.Body, 512))
detail := strings.TrimSpace(string(message))
if detail == "" {
detail = "unspecified error"
}
return fmt.Errorf("isolation agent rejected request (%d): %s", response.StatusCode, detail)
}
if out != nil {
return json.NewDecoder(response.Body).Decode(out)
}
return nil
}
func (c *Client) Prepare(ctx context.Context, spec ProjectSpec) (Prepared, error) {
var result Prepared
err := c.request(ctx, "/v1/prepare", spec, &result)
return result, err
}
func (c *Client) Quarantine(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/quarantine", spec, nil)
}
func (c *Client) ApplyWebProtection(ctx context.Context, spec WebProtectionSpec) error {
return c.request(ctx, "/v1/web-protection/apply", spec, nil)
}
func (c *Client) RemoveWebProtection(ctx context.Context, spec WebProtectionSpec) error {
return c.request(ctx, "/v1/web-protection/remove", spec, nil)
}
func (c *Client) PrepareExecutable(ctx context.Context, spec ExecutableSpec) error {
return c.request(ctx, "/v1/runtime/executable", spec, nil)
}
func (c *Client) PreparePanelRuntime(ctx context.Context, spec PanelRuntimeSpec) error {
return c.request(ctx, "/v1/runtime/panel-state", spec, nil)
}
func (c *Client) InstallPythonRuntime(ctx context.Context, version string) error {
return c.requestLong(ctx, "/v1/runtime/python/install", PythonRuntimeInstallSpec{Version: version}, nil)
}
func (c *Client) TerminateRuntime(ctx context.Context, spec RuntimeProcessSpec) error {
return c.request(ctx, "/v1/resources/runtime/terminate", spec, nil)
}
func (c *Client) ReleaseRunPath(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/run-path/release", spec, nil)
}
func (c *Client) PrepareTrash(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/trash/prepare", spec, nil)
}
func (c *Client) ConfigureFTPIdentity(ctx context.Context, spec FTPIdentitySpec) error {
return c.request(ctx, "/v1/ftp/identity", spec, nil)
}
func (c *Client) ConfigurePHPIdentity(ctx context.Context, spec PHPIdentitySpec) error {
return c.request(ctx, "/v1/php/identity", spec, nil)
}
func (c *Client) SetPHPIdentityState(ctx context.Context, spec PHPIdentitySpec, enabled bool) error {
path := "/v1/php/identity/stop"
if enabled {
path = "/v1/php/identity/start"
}
return c.request(ctx, path, spec, nil)
}
func (c *Client) RemovePHPIdentity(ctx context.Context, spec PHPIdentitySpec) error {
return c.request(ctx, "/v1/php/identity/remove", spec, nil)
}
func (c *Client) ResourceUsage(ctx context.Context, spec ResourceUsageSpec) (ResourceUsage, error) {
var result ResourceUsage
err := c.request(ctx, "/v1/resources/usage", spec, &result)
return result, err
}
func (c *Client) TerminateProcesses(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/resources/processes/terminate", spec, nil)
}
func (c *Client) FreezeWrites(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/project/freeze-writes", spec, nil)
}
func (c *Client) ConfigureDatabaseAccess(ctx context.Context, spec DatabaseAccessSpec) error {
return c.request(ctx, "/v1/database/access", spec, nil)
}
func (c *Client) ConfigureTrafficLimits(ctx context.Context, spec TrafficLimitSpec) error {
return c.request(ctx, "/v1/resources/limits", spec, nil)
}
func (c *Client) ConfigureFTPTLS(ctx context.Context, domain string) (string, error) {
var result struct {
Policy string `json:"policy"`
}
err := c.request(ctx, "/v1/ftp/tls", map[string]string{"domain": domain}, &result)
return result.Policy, err
}
func (c *Client) ConfigureNginxNetwork(ctx context.Context, spec NginxNetworkSpec) error {
return c.request(ctx, "/v1/nginx/network", spec, nil)
}
func (c *Client) CreateProjectBackup(ctx context.Context, spec ProjectSpec) (ProjectBackup, error) {
var result ProjectBackup
err := c.requestLong(ctx, "/v1/lifecycle/backup", spec, &result)
return result, err
}
func (c *Client) DeleteProjectBackup(ctx context.Context, backup ProjectBackup) error {
return c.request(ctx, "/v1/lifecycle/backup/delete", backup, nil)
}
func (c *Client) VerifyProjectBackup(ctx context.Context, backup ProjectBackup) error {
return c.requestLong(ctx, "/v1/lifecycle/backup/verify", backup, nil)
}
func (c *Client) PurgeProject(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/lifecycle/project/purge", spec, nil)
}
func (c *Client) ImportLegacyProject(ctx context.Context, spec LegacyImportSpec) error {
return c.requestLong(ctx, "/v1/import/project", spec, nil)
}
@@ -0,0 +1,77 @@
package isolation
import (
"context"
"database/sql"
"errors"
"github.com/go-sql-driver/mysql"
"net/http"
"strconv"
)
type CredentialSessions interface {
DisconnectCredentialSessions(context.Context, ProjectSpec) error
}
func (c *Client) DisconnectCredentialSessions(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/credentials/disconnect", spec, nil)
}
func (Mock) DisconnectCredentialSessions(context.Context, ProjectSpec) error { return nil }
func (a Agent) disconnectCredentialSessions(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
root, err := a.projectPath(spec)
if err != nil || !managedWebHostPattern.MatchString(spec.HostName) || requirePhysicalDirectory(root) != nil {
http.Error(w, "invalid managed identity", 412)
return
}
db, err := a.openMySQL(r.Context())
if err != nil {
http.Error(w, "database session inspection unavailable", 412)
return
}
defer db.Close()
if err = disconnectManagedDatabaseSessions(r.Context(), db, spec.HostName); err != nil {
http.Error(w, "cannot revoke managed database sessions", 412)
return
}
if err = disconnectFTPSessions(r.Context(), spec.HostName); err != nil {
http.Error(w, "cannot revoke managed FTP sessions", 412)
return
}
w.WriteHeader(200)
}
func disconnectManagedDatabaseSessions(ctx context.Context, db *sql.DB, name string) error {
if !managedWebHostPattern.MatchString(name) {
return errors.New("invalid database identity")
}
rows, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name)
if err != nil {
return err
}
var ids []uint64
for rows.Next() {
var id uint64
if err = rows.Scan(&id); err != nil {
rows.Close()
return err
}
ids = append(ids, id)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, id := range ids {
if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil {
var native *mysql.MySQLError
if !errors.As(err, &native) || native.Number != 1094 {
return err
}
}
}
return nil
}
@@ -0,0 +1,60 @@
//go:build linux
package isolation
import (
"context"
"errors"
"os"
"strconv"
"strings"
"syscall"
)
func disconnectFTPSessions(ctx context.Context, identity string) error {
uid, err := identityUID(identity)
if err != nil {
return err
}
pids, err := identityPIDs(identity)
if err != nil {
return err
}
for _, pid := range pids {
if ctx.Err() != nil {
return ctx.Err()
}
process, e := os.FindProcess(pid)
if e != nil {
continue
}
base := "/proc/" + strconv.Itoa(pid)
exe, exeErr := os.Readlink(base + "/exe")
status, readErr := os.ReadFile(base + "/status")
// CAP_SYS_PTRACE is intentionally absent from the agent. Linux can deny
// /proc/<pid>/exe across UIDs; status Name/Uid remain readable. Restrict the
// fallback to this host's UID and the exact FTP daemon name, with the pidfd
// acquired before either read so a recycled PID cannot target another task.
if readErr == nil && statusHasUID(status, uid) && managedFTPProcess(status, exe, exeErr != nil) {
e = process.Kill()
if e != nil && !errors.Is(e, os.ErrProcessDone) && !errors.Is(e, syscall.ESRCH) {
process.Release()
return e
}
}
process.Release()
}
return nil
}
func managedFTPProcess(status []byte, exe string, unreadable bool) bool {
if !unreadable {
return strings.HasPrefix(exe, "/www/server/pure-ftpd/") && strings.HasSuffix(exe, "/pure-ftpd")
}
for _, line := range strings.Split(string(status), "\n") {
if strings.HasPrefix(line, "Name:") {
return strings.TrimSpace(strings.TrimPrefix(line, "Name:")) == "pure-ftpd"
}
}
return false
}
@@ -0,0 +1,16 @@
//go:build linux
package isolation
import "testing"
func TestFTPSessionIdentificationDoesNotSelectRuntimeProcesses(t *testing.T) {
for _, test := range []struct {
name, exe string
unreadable, want bool
}{{"pure-ftpd", "/www/server/pure-ftpd/sbin/pure-ftpd", false, true}, {"node", "/www/server/nodejs/node", false, false}, {"node", "", true, false}, {"pure-ftpd", "/usr/bin/node", false, false}, {"pure-ftpd", "", true, true}, {"pure-ftpd-other", "", true, false}} {
if got := managedFTPProcess([]byte("Name:\t"+test.name+"\nUid:\t1001\t1001\t1001\t1001\n"), test.exe, test.unreadable); got != test.want {
t.Errorf("FTP match %s: %t", test.name, got)
}
}
}
@@ -0,0 +1,12 @@
//go:build !linux
package isolation
import (
"context"
"errors"
)
func disconnectFTPSessions(context.Context, string) error {
return errors.New("credential sessions require Linux")
}
@@ -0,0 +1,211 @@
package isolation
import (
"context"
"database/sql"
"encoding/json"
"errors"
"io"
"net/http"
"os/exec"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
)
// Root credentials stay inside the root agent. The fixed, isolated Python
// program reads only aaPanel's local configuration; no shell or supplied code.
func (a Agent) mysqlConfig(ctx context.Context) (*mysql.Config, error) {
if a.databaseAdminDSN != "" {
return mysql.ParseDSN(a.databaseAdminDSN)
}
command := exec.CommandContext(ctx, "/www/server/panel/pyenv/bin/python3", "-I", "-c", `import os,sys,json,re
from pathlib import Path
os.chdir('/www/server/panel');sys.path.insert(0,'/www/server/panel/class');import public
password=public.M('config').where('id=?',(1,)).getField('mysql_root')
assert isinstance(password,str) and password
port=3306
socket='/tmp/mysql.sock'
p=Path('/etc/my.cnf')
if p.is_file():
text=p.read_text();section=False
for line in text.splitlines():
line=line.strip()
if line.startswith('['):section=line.lower()=='[mysqld]'
elif section:
m=re.fullmatch(r'port\s*=\s*(\d+)\s*(?:[#;].*)?',line)
if m:port=int(m.group(1))
m=re.fullmatch(r'socket\s*=\s*(/[^\s#;]+)\s*(?:[#;].*)?',line)
if m:socket=m.group(1)
assert 1<=port<=65535
print(json.dumps({'password':password,'port':port,'socket':socket}))`)
data, err := command.Output()
if err != nil || len(data) > 64<<10 {
return nil, errors.New("cannot read local MySQL administrator configuration")
}
var value struct {
Password string
Port int
Socket string
}
if json.Unmarshal(data, &value) != nil || value.Password == "" || value.Port < 1 || value.Port > 65535 {
return nil, errors.New("invalid local MySQL administrator configuration")
}
cfg := mysql.NewConfig()
cfg.User = "root"
cfg.Passwd = value.Password
cfg.Net = "unix"
cfg.Addr = value.Socket
if !strings.HasPrefix(cfg.Addr, "/") || strings.ContainsAny(cfg.Addr, "\r\n\x00") {
return nil, errors.New("invalid MySQL socket path")
}
if strings.HasPrefix(cfg.Addr, "/tmp/") {
cfg.Addr = "/etc/sea-vhost-mysql/host-tmp/" + strings.TrimPrefix(cfg.Addr, "/tmp/")
}
cfg.Timeout = 5 * time.Second
cfg.ReadTimeout = 30 * time.Second
cfg.WriteTimeout = 30 * time.Second
return cfg, nil
}
func (a Agent) openMySQL(ctx context.Context) (*sql.DB, error) {
cfg, err := a.mysqlConfig(ctx)
if err != nil {
return nil, err
}
db, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, errors.New("cannot initialize local MySQL administrator connection")
}
db.SetMaxOpenConns(1)
if db.PingContext(ctx) != nil {
db.Close()
return nil, errors.New("cannot connect to local MySQL administrator")
}
return db, nil
}
func (a Agent) configureDatabaseAccess(w http.ResponseWriter, r *http.Request) {
var spec DatabaseAccessSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Database != spec.Project.HostName || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 {
http.Error(w, "invalid managed database identity", 400)
return
}
root, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(root) != nil {
http.Error(w, "managed project root unavailable", 412)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
db, err := a.openMySQL(ctx)
if err == nil {
defer db.Close()
err = setDatabaseAccess(ctx, db, spec.Database, spec.ReadOnly, spec.BlockCleanup)
}
if err != nil {
http.Error(w, "cannot enforce managed database access: "+err.Error(), 412)
return
}
w.WriteHeader(200)
}
func setDatabaseAccess(ctx context.Context, db *sql.DB, name string, readOnly, blockCleanup bool) error {
if !managedWebHostPattern.MatchString(name) {
return errors.New("invalid database name")
}
cleanupPrivilege := "Y"
if blockCleanup {
cleanupPrivilege = "N"
}
rows, err := db.QueryContext(ctx, `SELECT u.Host,COALESCE(d.Insert_priv,'N'),COALESCE(d.Select_priv='Y' AND d.Delete_priv=? AND d.Drop_priv=? AND d.Insert_priv='N' AND d.Update_priv='N' AND d.Create_priv='N' AND d.Grant_priv='N' AND d.References_priv='N' AND d.Index_priv='N' AND d.Alter_priv='N' AND d.Create_tmp_table_priv='N' AND d.Lock_tables_priv='N' AND d.Create_view_priv='N' AND d.Show_view_priv='N' AND d.Create_routine_priv='N' AND d.Alter_routine_priv='N' AND d.Execute_priv='N' AND d.Event_priv='N' AND d.Trigger_priv='N',FALSE) FROM mysql.user u LEFT JOIN mysql.db d ON d.User=u.User AND d.Host=u.Host AND d.Db=? WHERE u.User=?`, cleanupPrivilege, cleanupPrivilege, name, name)
if err != nil {
return errors.New("cannot inspect managed account")
}
type account struct {
host, insert string
readOnly bool
}
var accounts []account
for rows.Next() {
var item account
if err = rows.Scan(&item.host, &item.insert, &item.readOnly); err != nil {
rows.Close()
return err
}
if item.host != "localhost" && item.host != "127.0.0.1" && item.host != "::1" && item.host != "%" {
rows.Close()
return errors.New("unexpected managed account host")
}
accounts = append(accounts, item)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
if len(accounts) == 0 {
return errors.New("managed account not found")
}
changed := false
for _, item := range accounts {
if (readOnly && item.readOnly) || (!readOnly && item.insert == "Y") {
continue
}
accountSQL := "'" + name + "'@'" + item.host + "'"
if _, err = db.ExecContext(ctx, "REVOKE ALL PRIVILEGES, GRANT OPTION FROM "+accountSQL); err != nil {
return errors.New("cannot revoke managed account privileges")
}
privileges := "ALL PRIVILEGES"
if readOnly {
privileges = "SELECT, DELETE, DROP"
if blockCleanup {
privileges = "SELECT"
}
}
if _, err = db.ExecContext(ctx, "GRANT "+privileges+" ON `"+name+"`.* TO "+accountSQL); err != nil {
return errors.New("cannot grant managed account recovery privileges")
}
changed = true
}
if !changed && !readOnly {
return nil
}
// Existing sessions cache database grants. Disconnect only this exact user,
// so pooled connections and transactions cannot retain the old write access.
sessions, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name)
if err != nil {
return errors.New("cannot inspect managed database sessions")
}
var ids []uint64
for sessions.Next() {
var id uint64
if err = sessions.Scan(&id); err != nil {
sessions.Close()
return err
}
ids = append(ids, id)
}
err = sessions.Err()
sessions.Close()
if err != nil {
return err
}
for _, id := range ids {
if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil {
var mysqlErr *mysql.MySQLError
if !errors.As(err, &mysqlErr) || mysqlErr.Number != 1094 {
return errors.New("cannot disconnect managed database session")
}
}
}
return nil
}
func mysqlOptionValue(value string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`, "\r", `\r`).Replace(value) + `"`
}
@@ -0,0 +1,112 @@
package isolation
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"testing"
)
func TestDatabaseBackupManifestAndSQLAreInSameArchive(t *testing.T) {
root := t.TempDir()
sql := []byte("CREATE TABLE marker(value TEXT); INSERT INTO marker VALUES ('SEA-BACKUP-SENTINEL');\n")
file := filepath.Join(t.TempDir(), "db.sql")
if err := os.WriteFile(file, sql, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "index.php"), []byte("<?php echo 'site';"), 0600); err != nil {
t.Fatal(err)
}
digest := fmt.Sprintf("%x", sha256.Sum256(sql))
var output bytes.Buffer
err := writeTarGzipDatabase(context.Background(), &output, root, "sv0123456789", []backupDatabaseFile{{name: "sv0123456789", path: file, size: int64(len(sql)), digest: digest}})
if err != nil {
t.Fatal(err)
}
gz, err := gzip.NewReader(&output)
if err != nil {
t.Fatal(err)
}
defer gz.Close()
reader := tar.NewReader(gz)
foundSQL, foundManifest, foundSite := false, false, false
for {
header, err := reader.Next()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(reader)
if err != nil {
t.Fatal(err)
}
switch header.Name {
case "sv0123456789/index.php":
foundSite = true
case ".sea-vhost-backup/databases/sv0123456789.sql":
foundSQL = bytes.Equal(data, sql)
if header.Mode != 0600 {
t.Fatal("SQL backup is not private")
}
case ".sea-vhost-backup/manifest.json":
var value struct {
Format int
Databases []struct {
Name, Path, SHA256 string
Bytes int64
}
}
if err = json.Unmarshal(data, &value); err != nil {
t.Fatal(err)
}
foundManifest = value.Format == 2 && len(value.Databases) == 1 && value.Databases[0].SHA256 == digest && value.Databases[0].Bytes == int64(len(sql))
}
}
if !foundSQL || !foundManifest || !foundSite {
t.Fatal("incomplete recovery archive")
}
archivePath := filepath.Join(t.TempDir(), "backup.tar.gz")
// output was consumed by gzip.NewReader; generate a fresh archive for CRC checks.
var complete bytes.Buffer
if err = writeTarGzipDatabase(context.Background(), &complete, root, "sv0123456789", []backupDatabaseFile{{name: "sv0123456789", path: file, size: int64(len(sql)), digest: digest}}); err != nil {
t.Fatal(err)
}
if err = os.WriteFile(archivePath, complete.Bytes(), 0600); err != nil {
t.Fatal(err)
}
if err = verifyRecoveryArchive(context.Background(), archivePath, "sv0123456789", 1); err != nil {
t.Fatal(err)
}
corrupt := append([]byte(nil), complete.Bytes()...)
corrupt[len(corrupt)-4] ^= 0xff
if err = os.WriteFile(archivePath, corrupt, 0600); err != nil {
t.Fatal(err)
}
if verifyRecoveryArchive(context.Background(), archivePath, "sv0123456789", 1) == nil {
t.Fatal("corrupt recovery archive accepted")
}
}
func TestDatabaseBackupRejectsForeignDatabaseBeforeExecution(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "sv0123456789"), 0700); err != nil {
t.Fatal(err)
}
response := lifecycleRequest(t, Agent{Root: root, BackupRoot: t.TempDir()}, "/v1/lifecycle/backup", ProjectSpec{TenantID: 1, HostName: "sv0123456789", RunPath: "/", StorageBytes: 1024, ProcessLimit: 1, Databases: []string{"mysql"}})
if response.Code != 400 {
t.Fatalf("foreign database status=%d", response.Code)
}
response = lifecycleRequest(t, Agent{Root: root}, "/v1/database/access", DatabaseAccessSpec{Project: ProjectSpec{TenantID: 1, HostName: "sv0123456789", StorageBytes: 1024, ProcessLimit: 1}, Database: "mysql", ReadOnly: true})
if response.Code != 400 {
t.Fatalf("foreign account status=%d", response.Code)
}
}
@@ -0,0 +1,128 @@
package isolation
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"io"
"net"
"net/http"
"net/textproto"
"strconv"
"time"
)
// The socket is private; all FastCGI parameters are assembled by the agent.
func callFastCGI(ctx context.Context, socket string, params map[string]string, body []byte) (int, http.Header, []byte, error) {
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
if e != nil {
return 0, nil, nil, e
}
defer conn.Close()
deadline := time.Now().Add(120 * time.Second)
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
deadline = d
}
conn.SetDeadline(deadline)
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
conn.Close()
case <-done:
}
}()
record := func(kind byte, data []byte) error {
for len(data) > 0 {
n := min(len(data), 65535)
header := []byte{1, kind, 0, 1, byte(n >> 8), byte(n), 0, 0}
if _, e := conn.Write(header); e != nil {
return e
}
if _, e := conn.Write(data[:n]); e != nil {
return e
}
data = data[n:]
}
return nil
}
empty := func(kind byte) error { _, e := conn.Write([]byte{1, kind, 0, 1, 0, 0, 0, 0}); return e }
if e = record(1, []byte{0, 1, 0, 0, 0, 0, 0, 0}); e != nil {
return 0, nil, nil, e
}
var encoded bytes.Buffer
length := func(n int) {
if n < 128 {
encoded.WriteByte(byte(n))
} else {
var value [4]byte
binary.BigEndian.PutUint32(value[:], uint32(n)|0x80000000)
encoded.Write(value[:])
}
}
for name, value := range params {
length(len(name))
length(len(value))
encoded.WriteString(name)
encoded.WriteString(value)
}
if e = record(4, encoded.Bytes()); e == nil {
e = empty(4)
}
if e == nil {
e = record(5, body)
}
if e == nil {
e = empty(5)
}
if e != nil {
return 0, nil, nil, e
}
var output bytes.Buffer
for {
var header [8]byte
if _, e = io.ReadFull(conn, header[:]); e != nil {
return 0, nil, nil, e
}
if header[0] != 1 || header[2] != 0 || header[3] != 1 {
return 0, nil, nil, errors.New("invalid FastCGI record")
}
n := int(binary.BigEndian.Uint16(header[4:6]))
content := make([]byte, n+int(header[6]))
if _, e = io.ReadFull(conn, content); e != nil {
return 0, nil, nil, e
}
switch header[1] {
case 6:
if output.Len()+n > 2<<20 {
return 0, nil, nil, errors.New("phpMyAdmin response exceeds 2 MiB")
}
output.Write(content[:n])
case 3:
if n < 8 || binary.BigEndian.Uint32(content[:4]) != 0 || content[4] != 0 {
return 0, nil, nil, errors.New("phpMyAdmin process failed")
}
reader := bufio.NewReader(bytes.NewReader(output.Bytes()))
headers, e := textproto.NewReader(reader).ReadMIMEHeader()
if e != nil {
return 0, nil, nil, e
}
status := 200
if raw := headers.Get("Status"); raw != "" {
if len(raw) < 3 {
return 0, nil, nil, errors.New("invalid CGI status")
}
status, e = strconv.Atoi(raw[:3])
if e != nil || status < 100 || status > 599 {
return 0, nil, nil, errors.New("invalid CGI status")
}
}
headers.Del("Status")
data, e := io.ReadAll(reader)
return status, http.Header(headers), data, e
}
}
}
+63
View File
@@ -0,0 +1,63 @@
package isolation
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
)
// The panel's disabled state still permits 127.0.0.1. A suspended host must
// also reject local FTP clients; normal TCP peers cannot originate at 0.0.0.0.
// The panel's enable operation clears this source restriction on recovery.
func (a Agent) freezeFTPLogin(ctx context.Context, username string) error {
binary := a.PurePWBinary
if binary == "" {
binary = "/www/server/pure-ftpd/bin/pure-pw"
}
if !filepath.IsAbs(binary) || filepath.Base(binary) != "pure-pw" || !safeName.MatchString(username) {
return errors.New("invalid FTP freeze identity")
}
directory := filepath.Join(filepath.Dir(filepath.Dir(binary)), "etc")
if a.PureFTPConfig != "" {
directory = filepath.Dir(a.PureFTPConfig)
}
if _, err := os.Lstat(directory); errors.Is(err, os.ErrNotExist) {
return nil
}
if err := requirePhysicalDirectory(directory); err != nil {
return err
}
root, err := os.OpenRoot(directory)
if err != nil {
return err
}
defer root.Close()
info, err := root.Lstat("pureftpd.passwd")
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 {
return errors.New("unsafe FTP account database")
}
file, err := root.Open("pureftpd.passwd")
if err != nil {
return err
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, (16<<20)+1))
if err != nil {
return err
}
if len(data) > 16<<20 {
return errors.New("FTP account database exceeds limit")
}
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, username+":") {
return a.command(ctx, binary, "usermod", username, "-r", "0.0.0.0", "-m")
}
}
return nil
}
@@ -0,0 +1,47 @@
package isolation
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
func TestFTPFreezeOnlyChangesMatchingManagedAccount(t *testing.T) {
root := t.TempDir()
directory := filepath.Join(root, "etc")
if err := os.Mkdir(directory, 0700); err != nil {
t.Fatal(err)
}
file := filepath.Join(directory, "pureftpd.passwd")
if err := os.WriteFile(file, []byte("other-user:private-hash:1001\nsv0123456789:private-hash:1002\n"), 0600); err != nil {
t.Fatal(err)
}
var calls []string
a := Agent{PurePWBinary: filepath.Join(root, "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error {
calls = append(calls, strings.Join(args, " "))
return nil
}}
if err := a.freezeFTPLogin(context.Background(), "sv0123456789"); err != nil {
t.Fatal(err)
}
if len(calls) != 1 || calls[0] != "usermod sv0123456789 -r 0.0.0.0 -m" {
t.Fatalf("unexpected FTP changes: %v", calls)
}
if err := a.freezeFTPLogin(context.Background(), "sv1111111111"); err != nil {
t.Fatal(err)
}
if len(calls) != 1 {
t.Fatal("missing account changed unrelated FTP resources")
}
if err := os.Remove(file); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "outside"), file); err != nil {
t.Skip("symlink unavailable")
}
if err := a.freezeFTPLogin(context.Background(), "sv0123456789"); err == nil {
t.Fatal("symlink account database accepted")
}
}
@@ -0,0 +1,43 @@
package isolation
import (
"context"
"encoding/json"
"io"
"net/http"
"path/filepath"
"strings"
"time"
)
func (a Agent) configureFTPIdentity(w http.ResponseWriter, r *http.Request) {
var spec FTPIdentitySpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!safeName.MatchString(spec.Project.HostName) || spec.Username != spec.Project.HostName ||
spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
http.Error(w, "project root unavailable", http.StatusPreconditionFailed)
return
}
binary := strings.TrimSpace(a.PurePWBinary)
if binary == "" {
binary = "/www/server/pure-ftpd/bin/pure-pw"
}
if !filepath.IsAbs(binary) || filepath.Base(binary) != "pure-pw" {
http.Error(w, "invalid Pure-FTPd identity tool", http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err = a.command(ctx, binary, "usermod", spec.Username, "-u", spec.Project.HostName, "-g", spec.Project.HostName, "-d", projectRoot, "-m"); err != nil {
http.Error(w, "cannot bind FTP account to isolated identity", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
@@ -0,0 +1,6 @@
package isolation
import("context";"net/http")
type FTPManager interface{DisconnectFTP(context.Context,ProjectSpec)error}
func(c *Client)DisconnectFTP(ctx context.Context,p ProjectSpec)error{return c.request(ctx,"/v1/ftp/disconnect",p,nil)}
func(Mock)DisconnectFTP(context.Context,ProjectSpec)error{return nil}
func(a Agent)disconnectFTP(w http.ResponseWriter,r *http.Request){p,ok:=a.decode(w,r);if !ok{return};root,e:=a.projectPath(p);if e!=nil||!managedWebHostPattern.MatchString(p.HostName)||requirePhysicalDirectory(root)!=nil{http.Error(w,"invalid managed identity",412);return};if e=disconnectFTPSessions(r.Context(),p.HostName);e!=nil{http.Error(w,"cannot disconnect FTP",422);return};w.WriteHeader(200)}
+187
View File
@@ -0,0 +1,187 @@
package isolation
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
var pureFTPTLSLine = regexp.MustCompile(`(?m)^[ \t]*TLS[ \t]+[0-9]+[ \t]*\r?$`)
var pureFTPCertFileLine = regexp.MustCompile(`(?m)^[ \t]*CertFile[ \t]+[^\r\n]+\r?$`)
func (a Agent) configureFTPTLS(w http.ResponseWriter, r *http.Request) {
var input struct {
Domain string `json:"domain"`
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
input.Domain = strings.ToLower(strings.TrimSpace(input.Domain))
if !webDomainPattern.MatchString(input.Domain) {
http.Error(w, "invalid FTP domain", http.StatusBadRequest)
return
}
policy, err := a.applyFTPTLSPolicy(r.Context(), input.Domain)
if err != nil {
http.Error(w, "cannot configure FTP TLS", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"policy": policy})
}
func (a Agent) applyFTPTLSPolicy(ctx context.Context, domain string) (string, error) {
certRoot := a.CertificateRoot
if certRoot == "" {
certRoot = "/www/server/panel/vhost/cert"
}
configPath := a.PureFTPConfig
if configPath == "" {
configPath = "/www/server/pure-ftpd/etc/pure-ftpd.conf"
}
pemPath := a.PureFTPPem
if pemPath == "" {
pemPath = "/www/server/pure-ftpd/etc/pure-ftpd.pem"
}
certPath := filepath.Join(certRoot, domain, "fullchain.pem")
keyPath := filepath.Join(certRoot, domain, "privkey.pem")
certInfo, certErr := os.Lstat(certPath)
keyInfo, keyErr := os.Lstat(keyPath)
hasCert := certErr == nil && keyErr == nil
if (certErr == nil) != (keyErr == nil) || (certErr != nil && !errors.Is(certErr, os.ErrNotExist)) || (keyErr != nil && !errors.Is(keyErr, os.ErrNotExist)) {
return "", errors.New("incomplete FTP certificate")
}
if hasCert && (!certInfo.Mode().IsRegular() || certInfo.Mode()&os.ModeSymlink != 0 || !keyInfo.Mode().IsRegular() || keyInfo.Mode()&os.ModeSymlink != 0) {
return "", errors.New("unsafe FTP certificate")
}
configInfo, err := os.Lstat(configPath)
if err != nil || !configInfo.Mode().IsRegular() || configInfo.Mode()&os.ModeSymlink != 0 {
return "", errors.New("unsafe Pure-FTPd configuration")
}
config, err := os.ReadFile(configPath)
if err != nil {
return "", err
}
wantedTLS := "TLS 0"
policy := "plain_allowed_no_certificate"
changed := false
if hasCert {
pair, pairErr := tls.LoadX509KeyPair(certPath, keyPath)
if pairErr != nil || len(pair.Certificate) == 0 {
return "", errors.New("invalid FTP certificate pair")
}
leaf, parseErr := x509.ParseCertificate(pair.Certificate[0])
if parseErr != nil || time.Now().Before(leaf.NotBefore) || !time.Now().Before(leaf.NotAfter) {
return "", errors.New("FTP certificate is not currently valid")
}
if err = leaf.VerifyHostname(domain); err != nil {
return "", errors.New("FTP certificate does not match the configured domain")
}
certPEM, readCertErr := os.ReadFile(certPath)
keyPEM, readKeyErr := os.ReadFile(keyPath)
if readCertErr != nil || readKeyErr != nil {
return "", errors.Join(readCertErr, readKeyErr)
}
combined := append(bytes.TrimSpace(certPEM), '\n')
combined = append(combined, bytes.TrimSpace(keyPEM)...)
combined = append(combined, '\n')
existing, _ := os.ReadFile(pemPath)
if !bytes.Equal(existing, combined) {
if err = writeSecureFile(pemPath, combined, 0600); err != nil {
return "", err
}
changed = true
}
wantedTLS = "TLS 2"
policy = "explicit_tls_required"
}
directiveCount := 0
updated := pureFTPTLSLine.ReplaceAllFunc(config, func([]byte) []byte {
directiveCount++
if directiveCount == 1 {
return []byte(wantedTLS)
}
return nil
})
if directiveCount == 0 {
updated = append(bytes.TrimRight(config, "\r\n"), []byte("\n"+wantedTLS+"\n")...)
}
if hasCert {
wantedCertFile := []byte("CertFile " + pemPath)
certFileCount := 0
updated = pureFTPCertFileLine.ReplaceAllFunc(updated, func([]byte) []byte {
certFileCount++
if certFileCount == 1 {
return wantedCertFile
}
return nil
})
if certFileCount == 0 {
updated = append(bytes.TrimRight(updated, "\r\n"), '\n')
updated = append(updated, wantedCertFile...)
updated = append(updated, '\n')
}
}
if !bytes.Equal(updated, config) {
if err = writeSecureFile(configPath, updated, configInfo.Mode().Perm()); err != nil {
return "", err
}
changed = true
}
if changed {
// Pure-FTPd turns the configuration into daemon command-line flags at
// process start. A SysV-generated unit may report a successful reload
// without replacing those flags, so TLS policy changes require a full
// restart rather than reload-or-restart.
if err = a.restartPureFTP(ctx, configPath); err != nil {
return "", err
}
}
return policy, nil
}
func (a Agent) restartPureFTP(ctx context.Context, configPath string) error {
if err := a.command(ctx, "systemctl", "stop", "pure-ftpd.service"); err != nil {
return err
}
binaryPath := filepath.Join(filepath.Dir(filepath.Dir(configPath)), "sbin", "pure-ftpd")
if err := terminatePureFTPDaemons(ctx, binaryPath); err != nil {
return err
}
return a.command(ctx, "systemctl", "start", "pure-ftpd.service")
}
func writeSecureFile(path string, data []byte, mode os.FileMode) error {
temporary, err := os.CreateTemp(filepath.Dir(path), ".sea-vhost-*.tmp")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err = temporary.Chmod(mode); err == nil {
_, err = temporary.Write(data)
}
if err == nil {
err = temporary.Sync()
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return err
}
return os.Rename(temporaryPath, path)
}
+129
View File
@@ -0,0 +1,129 @@
package isolation
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestApplyFTPTLSPolicyRejectsCertificateForAnotherDomain(t *testing.T) {
root := t.TempDir()
certRoot := filepath.Join(root, "cert")
domain := "ftp.example.com"
certDir := filepath.Join(certRoot, domain)
if err := os.MkdirAll(certDir, 0700); err != nil {
t.Fatal(err)
}
certificate, privateKey := ftpTestCertificatePair(t, "other.example.com")
if err := os.WriteFile(filepath.Join(certDir, "fullchain.pem"), certificate, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(certDir, "privkey.pem"), privateKey, 0600); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(root, "pure-ftpd.conf")
if err := os.WriteFile(configPath, []byte("TLS 0\n"), 0600); err != nil {
t.Fatal(err)
}
pemPath := filepath.Join(root, "pure-ftpd.pem")
agent := Agent{
CertificateRoot: certRoot,
PureFTPConfig: configPath,
PureFTPPem: pemPath,
runCommand: func(context.Context, string, ...string) error {
t.Fatal("service restart must not run for a mismatched certificate")
return nil
},
}
_, err := agent.applyFTPTLSPolicy(context.Background(), domain)
if err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("mismatched certificate error = %v", err)
}
if _, statErr := os.Stat(pemPath); !os.IsNotExist(statErr) {
t.Fatalf("FTP PEM was written for a mismatched certificate: %v", statErr)
}
config, readErr := os.ReadFile(configPath)
if readErr != nil || string(config) != "TLS 0\n" {
t.Fatalf("FTP config changed after rejection: %q, %v", config, readErr)
}
}
func TestApplyFTPTLSPolicyNormalizesTLSAndRestartsDaemon(t *testing.T) {
root := t.TempDir()
certRoot := filepath.Join(root, "cert")
domain := "ftp.example.com"
certDir := filepath.Join(certRoot, domain)
if err := os.MkdirAll(certDir, 0700); err != nil {
t.Fatal(err)
}
certificate, privateKey := ftpTestCertificatePair(t, domain)
if err := os.WriteFile(filepath.Join(certDir, "fullchain.pem"), certificate, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(certDir, "privkey.pem"), privateKey, 0600); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(root, "pure-ftpd.conf")
if err := os.WriteFile(configPath, []byte("NoAnonymous yes\r\nTLS 1\r\nTLS 0\n"), 0600); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 1)
agent := Agent{
CertificateRoot: certRoot, PureFTPConfig: configPath, PureFTPPem: filepath.Join(root, "pure-ftpd.pem"),
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
},
}
policy, err := agent.applyFTPTLSPolicy(context.Background(), domain)
if err != nil || policy != "explicit_tls_required" {
t.Fatalf("policy = %q, error = %v", policy, err)
}
config, err := os.ReadFile(configPath)
if err != nil {
t.Fatal(err)
}
matches := pureFTPTLSLine.FindAll(config, -1)
if strings.Count(string(config), "TLS 2") != 1 || len(matches) != 1 {
t.Fatalf("TLS directives were not normalized: %q", config)
}
wantedCertFile := "CertFile " + filepath.Join(root, "pure-ftpd.pem")
if strings.Count(string(config), wantedCertFile) != 1 || len(pureFTPCertFileLine.FindAll(config, -1)) != 1 {
t.Fatalf("certificate file directive was not normalized: %q", config)
}
if len(commands) != 2 || commands[0] != "systemctl stop pure-ftpd.service" || commands[1] != "systemctl start pure-ftpd.service" {
t.Fatalf("Pure-FTPd was not fully restarted: %#v", commands)
}
}
func ftpTestCertificatePair(t *testing.T, domain string) ([]byte, []byte) {
t.Helper()
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: domain}, DNSNames: []string{domain},
NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
t.Fatal(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
}
+59
View File
@@ -0,0 +1,59 @@
package isolation
import (
"errors"
"path/filepath"
"strconv"
"strings"
"time"
)
// Pure-FTPd's documented stats format:
// epoch session username ip U|D bytes duration filename (last field unquoted).
func parseFTPStats(line, username, month string, location *time.Location) (uint64, bool) {
fields := strings.Fields(line)
if len(fields) < 8 || fields[2] != username || (fields[4] != "U" && fields[4] != "D") {
return 0, false
}
epoch, err := strconv.ParseInt(fields[0], 10, 64)
if err != nil || epoch <= 0 || time.Unix(epoch, 0).In(location).Format("2006-01") != month {
return 0, false
}
bytes, err := strconv.ParseUint(fields[5], 10, 64)
return bytes, err == nil
}
func (a Agent) measureFTPBandwidth(username string, now time.Time) (uint64, error) {
if !managedWebHostPattern.MatchString(username) {
return 0, errors.New("invalid FTP usage identity")
}
trafficStateMu.Lock()
defer trafficStateMu.Unlock()
statePath := a.UsageStatePath
if statePath == "" {
statePath = "/var/lib/sea-vhost-agent/traffic.json"
}
if !filepath.IsAbs(statePath) {
return 0, errors.New("invalid traffic state path")
}
state, err := loadTrafficState(statePath)
if err != nil {
return 0, err
}
key := "ftp:" + username
cursor := state.Domains[key]
month := now.Format("2006-01")
if cursor.Month != month {
cursor.Month = month
cursor.Bytes = 0
}
cursor, err = measureTransferLog(a.ftpTransferLogPath(), cursor, month, func(line string) (uint64, bool) { return parseFTPStats(line, username, month, now.Location()) })
if err != nil {
return 0, err
}
state.Domains[key] = cursor
if err = saveTrafficState(statePath, state); err != nil {
return 0, err
}
return cursor.Bytes, nil
}
Loaded 100 of 441 files, more files were not shown because too many files have changed in this diff. Show more