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

+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})
}