完善证书管理与初始化流程
This commit is contained in:
1 parent
07636abe44
commit
c74372284a
84 files changed
+10151
-3502
No files matched your search
@@ -1,67 +1,215 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base32"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
config config.Config
|
||||
http *http.Server
|
||||
const (
|
||||
ResetPath = "/reset"
|
||||
stateFileName = "scert-admin-reset.json"
|
||||
defaultLease = 90 * time.Second
|
||||
RefreshInterval = 30 * time.Second
|
||||
)
|
||||
|
||||
var ErrResetSessionClosed = errors.New("密码重置会话已关闭")
|
||||
|
||||
type State struct {
|
||||
Active bool `json:"active"`
|
||||
ResetURL string `json:"reset_url"`
|
||||
CodeHash string `json:"code_hash"`
|
||||
ProcessID int `json:"process_id"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func New(cfg config.Config) *Server {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/healthz", health)
|
||||
mux.HandleFunc("/api/v1/admin/status", func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodGet {
|
||||
writer.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
||||
"service": "scert-admin",
|
||||
"reset_enabled": false,
|
||||
"listen_scope": "local_only",
|
||||
"message": "密码重置协议尚未启用,当前仅提供受保护服务入口",
|
||||
})
|
||||
})
|
||||
return &Server{config: cfg, http: &http.Server{
|
||||
Addr: net.JoinHostPort(cfg.Admin.ResetServiceHost, strconv.Itoa(cfg.Admin.ResetServicePort)),
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}}
|
||||
type Session struct {
|
||||
State State
|
||||
Code string
|
||||
}
|
||||
|
||||
func (s *Server) ListenAndServe() error {
|
||||
if s.config.Admin.ResetServiceHost != "127.0.0.1" && s.config.Admin.ResetServiceHost != "::1" {
|
||||
return fmt.Errorf("Scert-admin 仅允许监听本机回环地址")
|
||||
type Controller struct {
|
||||
config config.Config
|
||||
statePath string
|
||||
leaseDuration time.Duration
|
||||
now func() time.Time
|
||||
state State
|
||||
}
|
||||
|
||||
func New(cfg config.Config) *Controller {
|
||||
return &Controller{
|
||||
config: cfg,
|
||||
statePath: StatePath(cfg.Paths.Data),
|
||||
leaseDuration: defaultLease,
|
||||
now: time.Now,
|
||||
}
|
||||
return s.http.ListenAndServe()
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
if s == nil || s.http == nil {
|
||||
func StatePath(dataDir string) string {
|
||||
return filepath.Join(dataDir, stateFileName)
|
||||
}
|
||||
|
||||
func (c *Controller) Start() (Session, error) {
|
||||
if c == nil {
|
||||
return Session{}, fmt.Errorf("Scert-admin 控制器不能为空")
|
||||
}
|
||||
if !c.config.SetupReady {
|
||||
return Session{}, fmt.Errorf("Scert 尚未完成初始化,不能启用密码重置入口")
|
||||
}
|
||||
resetURL := c.config.ResetURL()
|
||||
if resetURL == "" {
|
||||
return Session{}, fmt.Errorf("未配置管理页面域名或公网 IP,无法生成密码重置地址")
|
||||
}
|
||||
if active, err := IsActive(c.statePath, c.now()); err != nil {
|
||||
return Session{}, err
|
||||
} else if active {
|
||||
return Session{}, fmt.Errorf("密码重置入口已经启用")
|
||||
}
|
||||
code, err := generateCode()
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
now := c.now().UTC()
|
||||
c.state = State{
|
||||
Active: true, ResetURL: resetURL, CodeHash: hashCode(code), ProcessID: os.Getpid(),
|
||||
StartedAt: now, ExpiresAt: now.Add(c.leaseDuration),
|
||||
}
|
||||
if err := writeState(c.statePath, c.state); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
return Session{State: c.state, Code: code}, nil
|
||||
}
|
||||
|
||||
func (c *Controller) Refresh() error {
|
||||
if c == nil || !c.state.Active {
|
||||
return fmt.Errorf("密码重置入口尚未启用")
|
||||
}
|
||||
latest, err := ReadState(c.statePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !latest.Active || latest.CodeHash != c.state.CodeHash || !c.now().UTC().Before(latest.ExpiresAt) {
|
||||
c.state.Active = false
|
||||
return ErrResetSessionClosed
|
||||
}
|
||||
c.state = latest
|
||||
c.state.ExpiresAt = c.now().UTC().Add(c.leaseDuration)
|
||||
return writeState(c.statePath, c.state)
|
||||
}
|
||||
|
||||
func (c *Controller) Stop() error {
|
||||
if c == nil || !c.state.Active {
|
||||
return nil
|
||||
}
|
||||
return s.http.Shutdown(ctx)
|
||||
c.state.Active = false
|
||||
c.state.ExpiresAt = c.now().UTC()
|
||||
return writeState(c.statePath, c.state)
|
||||
}
|
||||
|
||||
func health(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodGet {
|
||||
writer.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
func IsActive(path string, now time.Time) (bool, error) {
|
||||
state, err := ReadState(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]string{"status": "ok", "service": "scert-admin"})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return state.Active && now.UTC().Before(state.ExpiresAt), nil
|
||||
}
|
||||
|
||||
func VerifyCode(path, code string, now time.Time) (State, error) {
|
||||
state, err := ReadState(path)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
if !state.Active || state.CodeHash == "" || !now.UTC().Before(state.ExpiresAt) {
|
||||
return State{}, ErrResetSessionClosed
|
||||
}
|
||||
expected := hashCode(code)
|
||||
if subtle.ConstantTimeCompare([]byte(expected), []byte(state.CodeHash)) != 1 {
|
||||
return State{}, ErrResetSessionClosed
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func Consume(path string, session State, now time.Time) error {
|
||||
latest, err := ReadState(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !latest.Active || latest.CodeHash == "" || !now.UTC().Before(latest.ExpiresAt) {
|
||||
return ErrResetSessionClosed
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(latest.CodeHash), []byte(session.CodeHash)) != 1 {
|
||||
return ErrResetSessionClosed
|
||||
}
|
||||
latest.Active = false
|
||||
latest.CodeHash = ""
|
||||
latest.ExpiresAt = now.UTC()
|
||||
return writeState(path, latest)
|
||||
}
|
||||
|
||||
func ReadState(path string) (State, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
var state State
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return State{}, fmt.Errorf("解析密码重置激活状态失败:%w", err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func writeState(path string, state State) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return fmt.Errorf("创建密码重置状态目录失败:%w", err)
|
||||
}
|
||||
data, err := json.MarshalIndent(state, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码密码重置激活状态失败:%w", err)
|
||||
}
|
||||
data = append(data, '\n')
|
||||
tmpPath := path + ".tmp"
|
||||
if err := os.WriteFile(tmpPath, data, 0o600); err != nil {
|
||||
return fmt.Errorf("保存密码重置临时状态失败:%w", err)
|
||||
}
|
||||
if err := os.Chmod(tmpPath, 0o600); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("设置密码重置临时状态权限失败:%w", err)
|
||||
}
|
||||
if err := os.Rename(tmpPath, path); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("保存密码重置激活状态失败:%w", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
return fmt.Errorf("设置密码重置状态文件权限失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateCode() (string, error) {
|
||||
buffer := make([]byte, 10)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", fmt.Errorf("生成一次性重置校验码失败:%w", err)
|
||||
}
|
||||
value := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buffer)
|
||||
return strings.ToUpper(value[:5] + "-" + value[5:10] + "-" + value[10:]), nil
|
||||
}
|
||||
|
||||
func hashCode(value string) string {
|
||||
sum := sha256.Sum256([]byte(strings.TrimSpace(strings.ToUpper(value))))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
@@ -28,9 +29,11 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
|
||||
"Group=Scert",
|
||||
"ExecStart=/scert/scert-admin --config /scert/conf/scert.json",
|
||||
"Restart=no",
|
||||
"RuntimeMaxSec=30min",
|
||||
"UMask=0077",
|
||||
"ProtectHome=yes",
|
||||
"NoNewPrivileges=yes",
|
||||
"RestrictAddressFamilies=AF_UNIX",
|
||||
} {
|
||||
if !strings.Contains(unit, required) {
|
||||
t.Errorf("Scert-admin systemd unit 缺少必要策略:%s", required)
|
||||
@@ -42,6 +45,8 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
|
||||
"Restart=always",
|
||||
"Restart=on-failure",
|
||||
"ExecReload=",
|
||||
"AF_INET",
|
||||
"AF_INET6",
|
||||
} {
|
||||
if strings.Contains(unit, forbidden) {
|
||||
t.Errorf("Scert-admin systemd unit 不得包含:%s", forbidden)
|
||||
@@ -49,20 +54,80 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListenAndServeRejectsNonLoopbackHost(t *testing.T) {
|
||||
func TestControllerActivatesAndStopsResetPath(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Admin.ResetServiceHost = "0.0.0.0"
|
||||
server := New(cfg)
|
||||
if err := server.ListenAndServe(); err == nil {
|
||||
t.Fatal("Scert-admin 必须拒绝非回环监听地址")
|
||||
cfg.SetupReady = true
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Server.Port = 8443
|
||||
controller := New(cfg)
|
||||
fixedNow := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
|
||||
controller.now = func() time.Time { return fixedNow }
|
||||
|
||||
session, err := controller.Start()
|
||||
if err != nil {
|
||||
t.Fatalf("启用密码重置入口失败:%v", err)
|
||||
}
|
||||
if session.State.ResetURL != "https://scert.example.test/reset" || session.Code == "" {
|
||||
t.Fatalf("密码重置会话内容不正确:%+v", session)
|
||||
}
|
||||
if session.State.CodeHash == session.Code || session.State.CodeHash == "" {
|
||||
t.Fatal("状态文件只能保存一次性校验码摘要")
|
||||
}
|
||||
active, err := IsActive(StatePath(cfg.Paths.Data), fixedNow.Add(time.Second))
|
||||
if err != nil || !active {
|
||||
t.Fatalf("密码重置入口应处于激活状态:active=%t err=%v", active, err)
|
||||
}
|
||||
if err := controller.Stop(); err != nil {
|
||||
t.Fatalf("关闭密码重置入口失败:%v", err)
|
||||
}
|
||||
active, err = IsActive(StatePath(cfg.Paths.Data), fixedNow.Add(time.Second))
|
||||
if err != nil || active {
|
||||
t.Fatalf("停止 Scert-admin 后入口必须关闭:active=%t err=%v", active, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigRejectsLocalhostAlias(t *testing.T) {
|
||||
func TestControllerRequiresCompletedSetup(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Admin.ResetServiceHost = "localhost"
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatal("Scert-admin 不得依赖 localhost 名称解析")
|
||||
if _, err := New(cfg).Start(); err == nil {
|
||||
t.Fatal("Scert 未初始化时不得启用密码重置入口")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredLeaseIsInactive(t *testing.T) {
|
||||
path := StatePath(t.TempDir())
|
||||
now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
|
||||
if err := writeState(path, State{Active: true, ExpiresAt: now.Add(-time.Second)}); err != nil {
|
||||
t.Fatalf("写入过期租约失败:%v", err)
|
||||
}
|
||||
active, err := IsActive(path, now)
|
||||
if err != nil || active {
|
||||
t.Fatalf("过期租约不得保持激活:active=%t err=%v", active, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetCodeCanOnlyBeConsumedOnce(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
controller := New(cfg)
|
||||
now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
|
||||
controller.now = func() time.Time { return now }
|
||||
session, err := controller.Start()
|
||||
if err != nil {
|
||||
t.Fatalf("启动密码重置会话失败:%v", err)
|
||||
}
|
||||
verified, err := VerifyCode(StatePath(cfg.Paths.Data), session.Code, now)
|
||||
if err != nil || verified.CodeHash != session.State.CodeHash {
|
||||
t.Fatalf("校验一次性校验码失败:state=%+v err=%v", verified, err)
|
||||
}
|
||||
if err := Consume(StatePath(cfg.Paths.Data), verified, now); err != nil {
|
||||
t.Fatalf("消费一次性校验码失败:%v", err)
|
||||
}
|
||||
if _, err := VerifyCode(StatePath(cfg.Paths.Data), session.Code, now); err != ErrResetSessionClosed {
|
||||
t.Fatalf("已消费校验码必须拒绝再次使用:%v", err)
|
||||
}
|
||||
if err := controller.Refresh(); err != ErrResetSessionClosed {
|
||||
t.Fatalf("Scert-admin 刷新已消费会话必须停止:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/httpapi"
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/setup"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
@@ -24,9 +27,13 @@ type App struct {
|
||||
Logger *logging.Logger
|
||||
Database *database.Database
|
||||
Repository *repository.SQLDomainRepository
|
||||
Servers *repository.SQLServerRepository
|
||||
Deployment *deployment.Service
|
||||
SecretStore *secretstore.Store
|
||||
SSHKeys *sshkey.Service
|
||||
DNSVerification *setup.DNSVerificationManager
|
||||
Certificates *certificate.Service
|
||||
Workflow *CertificateWorkflow
|
||||
Renewal *certificate.RenewalScheduler
|
||||
HTTP *httpapi.Server
|
||||
}
|
||||
@@ -67,17 +74,27 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
|
||||
dnsTester := dnsprovider.NewTester(dnsprovider.NewLegoFactory())
|
||||
dnsVerification := setup.NewDNSVerificationManager(dnsTester, secretStore)
|
||||
repo := repository.NewSQLDomainRepository(db.DB)
|
||||
serverRepo := repository.NewSQLServerRepository(db.DB)
|
||||
auditRepo := repository.NewSQLAuditRepository(db.DB)
|
||||
sshKeys := sshkey.NewService(secretStore)
|
||||
accounts := certificate.NewAccountRepository(secretStore)
|
||||
certificates := certificate.NewService(cfg, repo, secretStore, dnsprovider.NewLegoFactory(), accounts)
|
||||
renewal := certificate.NewRenewalScheduler(repo, certificates, cfg.ACME.RenewalThresholdDays)
|
||||
deploymentService := deployment.NewService(deployment.SSHFactory{Secrets: secretStore})
|
||||
workflow := &CertificateWorkflow{Certificates: certificates, Domains: repo, Servers: serverRepo, Deployment: deploymentService}
|
||||
renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays)
|
||||
server := httpapi.New(httpapi.Dependencies{
|
||||
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo,
|
||||
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, SSHKeys: sshKeys,
|
||||
SetupDNS: dnsVerification, Firewall: firewall.NewManager(),
|
||||
IssueCertificate: workflow.IssueForHTTP,
|
||||
ResetStatePath: admin.StatePath(cfg.Paths.Data),
|
||||
Audit: auditRepo,
|
||||
})
|
||||
return &App{
|
||||
Config: cfg, Logger: logger, Database: db, Repository: repo,
|
||||
SecretStore: secretStore, DNSVerification: dnsVerification, HTTP: server,
|
||||
Servers: serverRepo, Deployment: deploymentService,
|
||||
SecretStore: secretStore, SSHKeys: sshKeys, DNSVerification: dnsVerification, HTTP: server,
|
||||
Certificates: certificates,
|
||||
Workflow: workflow,
|
||||
Renewal: renewal,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
type CertificateWorkflow struct {
|
||||
Certificates certificateService
|
||||
Domains domainDeploymentRepository
|
||||
Servers serverLister
|
||||
Deployment savedDeployer
|
||||
}
|
||||
|
||||
type certificateService interface {
|
||||
Issue(context.Context, string) (certificate.IssueResult, error)
|
||||
Import(context.Context, certificate.ImportRequest) (certificate.IssueResult, error)
|
||||
}
|
||||
|
||||
type serverLister interface {
|
||||
ListServersByDomainID(context.Context, string) ([]deployment.Server, error)
|
||||
}
|
||||
|
||||
type savedDeployer interface {
|
||||
DeploySaved(context.Context, []deployment.Target, deployment.SavedFiles) (deployment.Report, error)
|
||||
}
|
||||
|
||||
type domainDeploymentRepository interface {
|
||||
GetByID(context.Context, string) (domain.Domain, error)
|
||||
UpdateCertificateState(context.Context, string, string, *time.Time) error
|
||||
}
|
||||
|
||||
type CertificateWorkflowResult struct {
|
||||
Certificate certificate.IssueResult `json:"certificate"`
|
||||
Deployment deployment.Report `json:"deployment"`
|
||||
}
|
||||
|
||||
func (w *CertificateWorkflow) Issue(ctx context.Context, domainID string) (certificate.IssueResult, error) {
|
||||
result, err := w.IssueWithReport(ctx, domainID)
|
||||
return result.Certificate, err
|
||||
}
|
||||
|
||||
func (w *CertificateWorkflow) IssueWithReport(ctx context.Context, domainID string) (CertificateWorkflowResult, error) {
|
||||
if w == nil || w.Certificates == nil || w.Domains == nil || w.Servers == nil || w.Deployment == nil {
|
||||
return CertificateWorkflowResult{}, errors.New("证书部署流程未初始化")
|
||||
}
|
||||
certificateResult, err := w.Certificates.Issue(ctx, domainID)
|
||||
if err != nil {
|
||||
return CertificateWorkflowResult{}, err
|
||||
}
|
||||
report, err := w.deploy(ctx, certificateResult)
|
||||
if err != nil {
|
||||
w.markDeploymentError(certificateResult)
|
||||
}
|
||||
return CertificateWorkflowResult{Certificate: certificateResult, Deployment: report}, err
|
||||
}
|
||||
|
||||
func (w *CertificateWorkflow) IssueForHTTP(ctx context.Context, domainID string) (certificate.IssueResult, deployment.Report, error) {
|
||||
result, err := w.IssueWithReport(ctx, domainID)
|
||||
return result.Certificate, result.Deployment, err
|
||||
}
|
||||
|
||||
func (w *CertificateWorkflow) Import(ctx context.Context, request certificate.ImportRequest) (CertificateWorkflowResult, error) {
|
||||
if w == nil || w.Certificates == nil || w.Domains == nil || w.Servers == nil || w.Deployment == nil {
|
||||
return CertificateWorkflowResult{}, errors.New("证书部署流程未初始化")
|
||||
}
|
||||
certificateResult, err := w.Certificates.Import(ctx, request)
|
||||
if err != nil {
|
||||
return CertificateWorkflowResult{}, err
|
||||
}
|
||||
report, err := w.deploy(ctx, certificateResult)
|
||||
if err != nil {
|
||||
w.markDeploymentError(certificateResult)
|
||||
}
|
||||
return CertificateWorkflowResult{Certificate: certificateResult, Deployment: report}, err
|
||||
}
|
||||
|
||||
func (w *CertificateWorkflow) deploy(ctx context.Context, result certificate.IssueResult) (deployment.Report, error) {
|
||||
domainItem, err := w.Domains.GetByID(ctx, result.DomainID)
|
||||
if err != nil {
|
||||
return deployment.Report{}, fmt.Errorf("查询域名配置失败:%w", err)
|
||||
}
|
||||
servers, err := w.Servers.ListServersByDomainID(ctx, result.DomainID)
|
||||
if err != nil {
|
||||
return deployment.Report{}, fmt.Errorf("查询域名部署服务器失败:%w", err)
|
||||
}
|
||||
targets := make([]deployment.Target, 0, len(servers))
|
||||
for _, server := range servers {
|
||||
resolved, resolveErr := deployment.ResolveServerPaths(server, domainItem.Name, string(domainItem.CertificateType))
|
||||
if resolveErr != nil {
|
||||
return deployment.Report{}, fmt.Errorf("解析服务器 %s 的证书路径失败:%w", server.Name, resolveErr)
|
||||
}
|
||||
targets = append(targets, deployment.Target{Server: resolved})
|
||||
}
|
||||
report, err := w.Deployment.DeploySaved(ctx, targets, deployment.SavedFiles{
|
||||
CertificatePath: result.Saved.CertificatePath,
|
||||
FullChainPath: result.Saved.FullChainPath,
|
||||
PrivateKeyPath: result.Saved.PrivateKeyPath,
|
||||
})
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if report.Status != "success" {
|
||||
return report, fmt.Errorf("证书部署未全部成功:成功 %d 台,失败 %d 台", report.Success, report.Failed)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func (w *CertificateWorkflow) markDeploymentError(result certificate.IssueResult) {
|
||||
if w == nil || w.Domains == nil {
|
||||
return
|
||||
}
|
||||
_ = w.Domains.UpdateCertificateState(context.Background(), result.DomainID, "error", &result.Saved.NotAfter)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
type workflowCertificateService struct {
|
||||
result certificate.IssueResult
|
||||
called bool
|
||||
}
|
||||
|
||||
func (s *workflowCertificateService) Issue(context.Context, string) (certificate.IssueResult, error) {
|
||||
s.called = true
|
||||
return s.result, nil
|
||||
}
|
||||
|
||||
func (s *workflowCertificateService) Import(context.Context, certificate.ImportRequest) (certificate.IssueResult, error) {
|
||||
s.called = true
|
||||
return s.result, nil
|
||||
}
|
||||
|
||||
type workflowServerLister struct {
|
||||
servers []deployment.Server
|
||||
}
|
||||
|
||||
func (s workflowServerLister) ListServersByDomainID(context.Context, string) ([]deployment.Server, error) {
|
||||
return s.servers, nil
|
||||
}
|
||||
|
||||
type workflowDeployer struct {
|
||||
targets []deployment.Target
|
||||
files deployment.SavedFiles
|
||||
report deployment.Report
|
||||
}
|
||||
|
||||
type workflowDomainState struct {
|
||||
id string
|
||||
status string
|
||||
item domain.Domain
|
||||
}
|
||||
|
||||
func (s *workflowDomainState) GetByID(_ context.Context, id string) (domain.Domain, error) {
|
||||
item := s.item
|
||||
if item.ID == "" {
|
||||
item.ID = id
|
||||
}
|
||||
if item.Name == "" {
|
||||
item.Name = "example.com"
|
||||
}
|
||||
if item.CertificateType == "" {
|
||||
item.CertificateType = domain.CertificateSingle
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (s *workflowDomainState) UpdateCertificateState(_ context.Context, id, status string, _ *time.Time) error {
|
||||
s.id, s.status = id, status
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *workflowDeployer) DeploySaved(_ context.Context, targets []deployment.Target, files deployment.SavedFiles) (deployment.Report, error) {
|
||||
d.targets = targets
|
||||
d.files = files
|
||||
return d.report, nil
|
||||
}
|
||||
|
||||
func TestCertificateWorkflowDeploysIssuedCertificateToAssociatedServers(t *testing.T) {
|
||||
certificateService := &workflowCertificateService{result: certificate.IssueResult{
|
||||
DomainID: "domain-1",
|
||||
Saved: certificate.SavedResource{CertificatePath: "cert.pem", FullChainPath: "fullchain.pem", PrivateKeyPath: "key.pem"},
|
||||
}}
|
||||
deployer := &workflowDeployer{report: deployment.Report{Total: 1, Success: 1, Status: "success"}}
|
||||
state := &workflowDomainState{item: domain.Domain{ID: "domain-1", Name: "example.com", CertificateType: domain.CertificateSingle}}
|
||||
workflow := &CertificateWorkflow{
|
||||
Certificates: certificateService,
|
||||
Domains: state,
|
||||
Servers: workflowServerLister{servers: []deployment.Server{{ID: "server-1", Name: "生产服务器"}}},
|
||||
Deployment: deployer,
|
||||
}
|
||||
result, err := workflow.IssueWithReport(context.Background(), "domain-1")
|
||||
if err != nil {
|
||||
t.Fatalf("证书工作流失败:%v", err)
|
||||
}
|
||||
if !certificateService.called || result.Deployment.Status != "success" || len(deployer.targets) != 1 {
|
||||
t.Fatalf("证书工作流结果错误:%+v %+v", result, deployer.targets)
|
||||
}
|
||||
if deployer.files.PrivateKeyPath != "key.pem" {
|
||||
t.Fatalf("部署文件路径错误:%+v", deployer.files)
|
||||
}
|
||||
if deployer.targets[0].Server.CertificatePath != "/ssl/example.com/single/cert.pem" || deployer.targets[0].Server.PrivateKeyPath != "/ssl/example.com/single/key.pem" {
|
||||
t.Fatalf("部署目标路径未按域名和证书类型解析:%+v", deployer.targets[0].Server)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateWorkflowReturnsPartialDeploymentError(t *testing.T) {
|
||||
deployer := &workflowDeployer{report: deployment.Report{Total: 2, Success: 1, Failed: 1, Status: "partial"}}
|
||||
state := &workflowDomainState{item: domain.Domain{ID: "domain-1", Name: "*.example.com", CertificateType: domain.CertificateWildcard}}
|
||||
workflow := &CertificateWorkflow{
|
||||
Certificates: &workflowCertificateService{result: certificate.IssueResult{DomainID: "domain-1"}},
|
||||
Domains: state,
|
||||
Servers: workflowServerLister{servers: []deployment.Server{{ID: "server-1"}, {ID: "server-2"}}},
|
||||
Deployment: deployer,
|
||||
}
|
||||
result, err := workflow.IssueWithReport(context.Background(), "domain-1")
|
||||
if err == nil || result.Deployment.Status != "partial" {
|
||||
t.Fatalf("部分部署应返回错误和报告:%+v %v", result, err)
|
||||
}
|
||||
if result.Certificate.DomainID != "domain-1" {
|
||||
t.Fatalf("证书结果未保留:%+v", result.Certificate)
|
||||
}
|
||||
if state.id != "domain-1" || state.status != "error" {
|
||||
t.Fatalf("部署失败后域名状态未标记为错误:%+v", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateWorkflowResolvesSameServerForDifferentDomains(t *testing.T) {
|
||||
server := deployment.Server{ID: "server-1", Name: "共享服务器"}
|
||||
deployer := &workflowDeployer{report: deployment.Report{Total: 1, Success: 1, Status: "success"}}
|
||||
state := &workflowDomainState{item: domain.Domain{ID: "domain-1", Name: "example.com", CertificateType: domain.CertificateSAN}}
|
||||
workflow := &CertificateWorkflow{
|
||||
Certificates: &workflowCertificateService{result: certificate.IssueResult{DomainID: "domain-1"}},
|
||||
Domains: state,
|
||||
Servers: workflowServerLister{servers: []deployment.Server{server}},
|
||||
Deployment: deployer,
|
||||
}
|
||||
if _, err := workflow.IssueWithReport(context.Background(), "domain-1"); err != nil {
|
||||
t.Fatalf("第一个域名部署失败:%v", err)
|
||||
}
|
||||
firstPath := deployer.targets[0].Server.CertificatePath
|
||||
state.item = domain.Domain{ID: "domain-2", Name: "api.example.net", CertificateType: domain.CertificateSingle}
|
||||
workflow.Certificates = &workflowCertificateService{result: certificate.IssueResult{DomainID: "domain-2"}}
|
||||
if _, err := workflow.IssueWithReport(context.Background(), "domain-2"); err != nil {
|
||||
t.Fatalf("第二个域名部署失败:%v", err)
|
||||
}
|
||||
secondPath := deployer.targets[0].Server.CertificatePath
|
||||
if firstPath != "/ssl/example.com/san/cert.pem" || secondPath != "/ssl/api.example.net/single/cert.pem" || firstPath == secondPath {
|
||||
t.Fatalf("共享服务器的域名部署路径发生覆盖:%s %s", firstPath, secondPath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/mail"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrInvalidIdentifier = errors.New("登录标识无效")
|
||||
var ErrInvalidCredentials = errors.New("账号或密码错误")
|
||||
|
||||
// NormalizeIdentifier 将用户名或邮箱统一为可比较的登录标识。
|
||||
func NormalizeIdentifier(identifier string) (string, error) {
|
||||
identifier = strings.TrimSpace(identifier)
|
||||
if identifier == "" || strings.ContainsAny(identifier, "\r\n") {
|
||||
return "", ErrInvalidIdentifier
|
||||
}
|
||||
if !strings.Contains(identifier, "@") {
|
||||
return strings.ToLower(identifier), nil
|
||||
}
|
||||
identifier = strings.ToLower(identifier)
|
||||
parsed, err := mail.ParseAddress(identifier)
|
||||
if err != nil || parsed.Address != identifier || parsed.Name != "" {
|
||||
return "", ErrInvalidIdentifier
|
||||
}
|
||||
parts := strings.Split(identifier, "@")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", ErrInvalidIdentifier
|
||||
}
|
||||
return identifier, nil
|
||||
}
|
||||
|
||||
// IsMatch 判断登录标识是否匹配指定的用户名或绑定邮箱。
|
||||
func IsMatch(identifier, username, email string) bool {
|
||||
normalized, err := NormalizeIdentifier(identifier)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
username = strings.ToLower(strings.TrimSpace(username))
|
||||
email = strings.ToLower(strings.TrimSpace(email))
|
||||
return normalized == username || (email != "" && normalized == email)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const dummyPasswordHash = "$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"
|
||||
|
||||
type AdminAccount struct {
|
||||
Username string
|
||||
Email string
|
||||
Role string
|
||||
}
|
||||
|
||||
// AuthenticateAdmin 统一执行用户名或邮箱登录,并只返回后端确认的真实权限。
|
||||
func AuthenticateAdmin(identifier, password, username, email, passwordHash string) (AdminAccount, error) {
|
||||
matched := IsMatch(identifier, username, email)
|
||||
if !matched || strings.TrimSpace(password) == "" || len([]byte(password)) > 256 {
|
||||
_ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password))
|
||||
return AdminAccount{}, ErrInvalidCredentials
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password)); err != nil {
|
||||
return AdminAccount{}, ErrInvalidCredentials
|
||||
}
|
||||
return AdminAccount{
|
||||
Username: strings.TrimSpace(username),
|
||||
Email: strings.TrimSpace(email),
|
||||
Role: "super_admin",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func IsInvalidCredentials(err error) bool {
|
||||
return errors.Is(err, ErrInvalidCredentials)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestNormalizeIdentifier(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
shouldErr bool
|
||||
}{
|
||||
{name: "username", input: " Admin ", expected: "admin"},
|
||||
{name: "email", input: " Admin@Example.COM ", expected: "admin@example.com"},
|
||||
{name: "display name rejected", input: "Admin <admin@example.com>", shouldErr: true},
|
||||
{name: "line break rejected", input: "admin\n@example.com", shouldErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
actual, err := NormalizeIdentifier(test.input)
|
||||
if test.shouldErr {
|
||||
if err == nil {
|
||||
t.Fatal("应拒绝无效登录标识")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || actual != test.expected {
|
||||
t.Fatalf("登录标识归一化结果错误:%q,错误:%v", actual, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateAdminByUsernameOrEmail(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("Password123"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
for _, identifier := range []string{"Admin", "admin@example.com"} {
|
||||
account, err := AuthenticateAdmin(identifier, "Password123", "admin", "admin@example.com", string(hash))
|
||||
if err != nil {
|
||||
t.Fatalf("使用 %s 登录失败:%v", identifier, err)
|
||||
}
|
||||
if account.Role != "super_admin" {
|
||||
t.Fatalf("登录权限错误:%s", account.Role)
|
||||
}
|
||||
}
|
||||
if _, err := AuthenticateAdmin("other@example.com", "Password123", "admin", "admin@example.com", string(hash)); !IsInvalidCredentials(err) {
|
||||
t.Fatalf("未匹配账号时应返回统一认证错误:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ func newRootCommand() *cobra.Command {
|
||||
root.PersistentFlags().StringVar(&baseDir, "base-dir", "", "Windows 默认安装根目录")
|
||||
root.AddCommand(
|
||||
&cobra.Command{Use: "version", Short: "显示版本信息", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("Scert %s\n", version) }},
|
||||
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(),
|
||||
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newServerCommand(), newSSHKeyCommand(),
|
||||
)
|
||||
localizeHelpFlags(root)
|
||||
return root
|
||||
@@ -111,11 +111,11 @@ func newInitCommand() *cobra.Command {
|
||||
|
||||
func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command {
|
||||
var (
|
||||
adminUsername, adminPassword, emailProvider, emailEndpoint string
|
||||
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
|
||||
webHostname, webPublicIP, httpsMode string
|
||||
serverPort, resetServicePort int
|
||||
dnsVerified, webEnabled bool
|
||||
adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string
|
||||
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
|
||||
webHostname, webPublicIP, httpsMode string
|
||||
serverPort int
|
||||
dnsVerified, webEnabled bool
|
||||
)
|
||||
command := &cobra.Command{Use: "init", Short: "交互式初始化配置", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := resolveConfigPath()
|
||||
@@ -126,8 +126,8 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
}
|
||||
cfg := config.Default(baseDir)
|
||||
input := setup.Input{
|
||||
AdminUsername: adminUsername, AdminPassword: adminPassword, ServerPort: serverPort,
|
||||
ResetServicePort: resetServicePort, EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
|
||||
AdminUsername: adminUsername, AdminEmail: adminEmail, AdminPassword: adminPassword, ServerPort: serverPort,
|
||||
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
|
||||
EmailRecipients: splitValues(recipients), DNSProvider: dnsProvider, DNSCredentialRef: dnsCredentialRef,
|
||||
DNSVerified: dnsVerified, CertificateRoot: certificateRoot, WebHostname: webHostname,
|
||||
WebPublicIP: webPublicIP, WebEnabled: webEnabled, HTTPSMode: httpsMode,
|
||||
@@ -147,13 +147,13 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "初始化配置已保存:%s\n", path)
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已标记为验证通过;真实 provider 连通性测试和 Web 证书申请将在后续任务接入。\n")
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "本机防火墙:%s\n", firewallResult.Message)
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d;密码重置服务仅监听本机 %s:%d,不创建对外入站规则。\n", cfg.Server.Port, cfg.Admin.ResetServiceHost, cfg.Admin.ResetServicePort)
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL())
|
||||
return nil
|
||||
}}
|
||||
command.Flags().StringVar(&adminUsername, "admin-username", "", "超级管理员用户名")
|
||||
command.Flags().StringVar(&adminEmail, "admin-email", "", "超级管理员绑定邮箱")
|
||||
command.Flags().StringVar(&adminPassword, "admin-password", "", "超级管理员密码(仅建议临时使用参数,优先交互输入)")
|
||||
command.Flags().IntVar(&serverPort, "server-port", 8080, "Scert 主服务端口")
|
||||
command.Flags().IntVar(&resetServicePort, "reset-service-port", 8091, "Scert-admin 密码重置端口")
|
||||
command.Flags().StringVar(&emailProvider, "email-provider", "", "第三方邮箱服务标识")
|
||||
command.Flags().StringVar(&emailEndpoint, "email-endpoint", "", "第三方邮箱 API 地址")
|
||||
command.Flags().StringVar(&recipients, "recipients", "", "通知收件人,多个地址用逗号分隔")
|
||||
@@ -161,9 +161,9 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用,不保存明文密钥")
|
||||
command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过外部验证测试")
|
||||
command.Flags().StringVar(&certificateRoot, "certificate-root", "", "证书部署根目录,默认使用系统目录")
|
||||
command.Flags().StringVar(&webHostname, "web-hostname", "", "Web 管理页面域名")
|
||||
command.Flags().StringVar(&webHostname, "web-hostname", "", "管理页面域名")
|
||||
command.Flags().StringVar(&webPublicIP, "web-public-ip", "", "没有域名时使用的公网 IP")
|
||||
command.Flags().BoolVar(&webEnabled, "web-enabled", true, "是否开启 Web 管理页面")
|
||||
command.Flags().BoolVar(&webEnabled, "web-enabled", true, "是否开启管理页面")
|
||||
command.Flags().StringVar(&httpsMode, "https-mode", "direct", "HTTPS 模式:direct、proxy")
|
||||
return command
|
||||
}
|
||||
@@ -204,6 +204,10 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.AdminEmail, err = ask(reader, output, "超级管理员绑定邮箱 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.AdminPassword, err = ask(reader, output, "超级管理员密码 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -213,11 +217,6 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
|
||||
return err
|
||||
}
|
||||
value.ServerPort = port
|
||||
port, err = askInt(reader, output, "Scert-admin 密码重置端口 *", cfg.Admin.ResetServicePort)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.ResetServicePort = port
|
||||
value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -247,17 +246,17 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.WebHostname, err = ask(reader, output, "Web 管理页面域名(无域名可留空)", "")
|
||||
value.WebHostname, err = ask(reader, output, "管理页面域名(无域名可留空)", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value.WebHostname == "" {
|
||||
value.WebPublicIP, err = ask(reader, output, "Web 管理页面公网 IP", "")
|
||||
value.WebPublicIP, err = ask(reader, output, "管理页面公网 IP", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
value.WebEnabled, err = askYesNo(reader, output, "是否开启 Web 管理页面?", true)
|
||||
value.WebEnabled, err = askYesNo(reader, output, "是否开启管理页面?", true)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -327,11 +326,11 @@ func newStatusCommand() *cobra.Command {
|
||||
}
|
||||
|
||||
func commandStatus(cfg config.Config) map[string]any {
|
||||
return map[string]any{"service": "scert", "version": buildinfo.Version, "config_version": cfg.Version, "setup_ready": cfg.SetupReady, "https_mode": cfg.Server.HTTPSMode, "database_driver": cfg.Database.Driver, "server_port": cfg.Server.Port, "reset_service_port": cfg.Admin.ResetServicePort, "web_enabled": cfg.Web.Enabled, "web_hostname": cfg.Web.Hostname, "web_public_ip": cfg.Web.PublicIP, "dns_verification_state": cfg.DNS.VerificationState}
|
||||
return map[string]any{"service": "scert", "version": buildinfo.Version, "config_version": cfg.Version, "setup_ready": cfg.SetupReady, "https_mode": cfg.Server.HTTPSMode, "database_driver": cfg.Database.Driver, "server_port": cfg.Server.Port, "reset_url": cfg.ResetURL(), "web_enabled": cfg.Web.Enabled, "web_hostname": cfg.Web.Hostname, "web_public_ip": cfg.Web.PublicIP, "dns_verification_state": cfg.DNS.VerificationState}
|
||||
}
|
||||
|
||||
func newServeCommand() *cobra.Command {
|
||||
return &cobra.Command{Use: "serve", Short: "启动 Web 服务", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return &cobra.Command{Use: "serve", Short: "启动网站服务", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -341,7 +340,7 @@ func newServeCommand() *cobra.Command {
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "系统尚未初始化,临时服务仅监听本机;请完成初始化后重启服务。")
|
||||
}
|
||||
if cfg.SetupReady && !cfg.Web.Enabled {
|
||||
return fmt.Errorf("Web 管理页面已关闭")
|
||||
return fmt.Errorf("管理页面已关闭")
|
||||
}
|
||||
service, err := app.NewWithConfigPath(cmd.Context(), cfg, resolveConfigPath())
|
||||
if err != nil {
|
||||
@@ -369,7 +368,7 @@ func newServeCommand() *cobra.Command {
|
||||
|
||||
func newDomainCommand() *cobra.Command {
|
||||
command := &cobra.Command{Use: "domain", Short: "管理托管域名"}
|
||||
command.AddCommand(newDomainListCommand(), newDomainAddCommand(), newDomainEditCommand(), newDomainDeleteCommand(), newDomainIssueCommand(), newDomainImportCommand())
|
||||
command.AddCommand(newDomainListCommand(), newDomainAddCommand(), newDomainEditCommand(), newDomainDeleteCommand(), newDomainIssueCommand(), newDomainImportCommand(), newDomainServersCommand())
|
||||
return command
|
||||
}
|
||||
|
||||
@@ -385,10 +384,10 @@ func newDomainIssueCommand() *cobra.Command {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
if service.Certificates == nil {
|
||||
if service.Workflow == nil {
|
||||
return fmt.Errorf("证书申请服务未初始化")
|
||||
}
|
||||
result, err := service.Certificates.Issue(cmd.Context(), id)
|
||||
result, err := service.Workflow.IssueWithReport(cmd.Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -411,10 +410,10 @@ func newDomainImportCommand() *cobra.Command {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
if service.Certificates == nil {
|
||||
if service.Workflow == nil {
|
||||
return fmt.Errorf("证书导入服务未初始化")
|
||||
}
|
||||
result, err := service.Certificates.Import(cmd.Context(), certificate.ImportRequest{
|
||||
result, err := service.Workflow.Import(cmd.Context(), certificate.ImportRequest{
|
||||
DomainID: id, Certificate: certificatePath, PrivateKey: privateKeyPath, IssuerBundle: issuerPath,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/buildinfo"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
|
||||
)
|
||||
|
||||
@@ -77,6 +78,58 @@ func TestHelpSupportsSubcommand(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpIncludesServerManagementCommands(t *testing.T) {
|
||||
root := newRootCommand()
|
||||
var output bytes.Buffer
|
||||
root.SetOut(&output)
|
||||
root.SetErr(&output)
|
||||
root.SetArgs([]string{"help", "server"})
|
||||
if err := root.Execute(); err != nil {
|
||||
t.Fatalf("查看服务器管理帮助失败:%v", err)
|
||||
}
|
||||
text := output.String()
|
||||
for _, expected := range []string{"管理部署服务器", "添加部署服务器", "编辑部署服务器", "删除部署服务器"} {
|
||||
if !strings.Contains(text, expected) {
|
||||
t.Fatalf("服务器管理帮助缺少 %q:%s", expected, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerCommandUsesDefaultCertificatePathTemplates(t *testing.T) {
|
||||
command := newServerAddCommand()
|
||||
tests := map[string]string{
|
||||
"certificate-path": deployment.DefaultCertificatePath,
|
||||
"chain-path": deployment.DefaultCertificateChainPath,
|
||||
"private-key-path": deployment.DefaultPrivateKeyPath,
|
||||
}
|
||||
for name, expected := range tests {
|
||||
flag := command.Flag(name)
|
||||
if flag == nil || flag.DefValue != expected {
|
||||
t.Fatalf("服务器命令参数 %s 的默认值错误:%v", name, flag)
|
||||
}
|
||||
if len(flag.Annotations) != 0 {
|
||||
t.Fatalf("服务器路径参数 %s 不应强制填写:%v", name, flag.Annotations)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpIncludesSSHKeyManagementCommands(t *testing.T) {
|
||||
root := newRootCommand()
|
||||
var output bytes.Buffer
|
||||
root.SetOut(&output)
|
||||
root.SetErr(&output)
|
||||
root.SetArgs([]string{"help", "ssh-key"})
|
||||
if err := root.Execute(); err != nil {
|
||||
t.Fatalf("查看 SSH 私钥管理帮助失败:%v", err)
|
||||
}
|
||||
text := output.String()
|
||||
for _, expected := range []string{"管理 SSH 部署私钥", "安全录入 SSH 私钥", "删除未被服务器使用的 SSH 私钥"} {
|
||||
if !strings.Contains(text, expected) {
|
||||
t.Fatalf("SSH 私钥管理帮助缺少 %q:%s", expected, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandStatusUsesApplicationVersion(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
status := commandStatus(cfg)
|
||||
@@ -88,7 +141,6 @@ func TestCommandStatusUsesApplicationVersion(t *testing.T) {
|
||||
func TestSaveSetupWithFirewallOpensOnlyMainPort(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Server.Port = 8443
|
||||
cfg.Admin.ResetServicePort = 8091
|
||||
manager := &cliFakeFirewallManager{result: firewall.Result{
|
||||
Backend: "windows", RuleName: "Scert Web TCP 8443", Created: true, Message: "已创建测试规则",
|
||||
}}
|
||||
@@ -105,6 +157,13 @@ func TestSaveSetupWithFirewallOpensOnlyMainPort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitCommandDoesNotExposeResetServicePort(t *testing.T) {
|
||||
command := newInitCommandWithFirewall(&cliFakeFirewallManager{})
|
||||
if command.Flag("reset-service-port") != nil {
|
||||
t.Fatal("初始化命令不应再提供独立密码重置端口")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
blockedParent := filepath.Join(baseDir, "blocked")
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/app"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
func newServerCommand() *cobra.Command {
|
||||
command := &cobra.Command{Use: "server", Short: "管理部署服务器"}
|
||||
command.AddCommand(newServerListCommand(), newServerShowCommand(), newServerAddCommand(), newServerEditCommand(), newServerDeleteCommand())
|
||||
return command
|
||||
}
|
||||
|
||||
func newServerListCommand() *cobra.Command {
|
||||
return &cobra.Command{Use: "list", Short: "查看部署服务器列表", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
items, err := service.Servers.ListServers(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, items)
|
||||
}}
|
||||
}
|
||||
|
||||
func newServerShowCommand() *cobra.Command {
|
||||
var id string
|
||||
command := &cobra.Command{Use: "show", Short: "查看部署服务器详情", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
item, err := service.Servers.GetServerByID(cmd.Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, item)
|
||||
}}
|
||||
command.Flags().StringVar(&id, "id", "", "服务器 ID")
|
||||
_ = command.MarkFlagRequired("id")
|
||||
return command
|
||||
}
|
||||
|
||||
func newServerAddCommand() *cobra.Command {
|
||||
var value serverFlags
|
||||
command := &cobra.Command{Use: "add", Short: "添加部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
item := value.server()
|
||||
item.ID = domain.NewID()
|
||||
if _, err := service.SSHKeys.ValidateReference(cmd.Context(), item.PrivateKeyRef); err != nil {
|
||||
return fmt.Errorf("SSH 私钥引用无效:%w", err)
|
||||
}
|
||||
if err := service.Servers.CreateServer(cmd.Context(), item); err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, item.Normalize())
|
||||
}}
|
||||
value.bind(command)
|
||||
return command
|
||||
}
|
||||
|
||||
func newServerEditCommand() *cobra.Command {
|
||||
var id string
|
||||
var value serverFlags
|
||||
command := &cobra.Command{Use: "edit", Short: "编辑部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
existing, err := service.Servers.GetServerByID(cmd.Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
item := value.server()
|
||||
item.ID = existing.ID
|
||||
item.CreatedAt = existing.CreatedAt
|
||||
if _, err := service.SSHKeys.ValidateReference(cmd.Context(), item.PrivateKeyRef); err != nil {
|
||||
return fmt.Errorf("SSH 私钥引用无效:%w", err)
|
||||
}
|
||||
if err := service.Servers.UpdateServer(cmd.Context(), item); err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, item.Normalize())
|
||||
}}
|
||||
command.Flags().StringVar(&id, "id", "", "服务器 ID")
|
||||
_ = command.MarkFlagRequired("id")
|
||||
value.bind(command)
|
||||
return command
|
||||
}
|
||||
|
||||
func newServerDeleteCommand() *cobra.Command {
|
||||
var id string
|
||||
command := &cobra.Command{Use: "delete", Short: "删除部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
if err := service.Servers.DeleteServer(cmd.Context(), id); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "部署服务器已删除:%s\n", id)
|
||||
return nil
|
||||
}}
|
||||
command.Flags().StringVar(&id, "id", "", "服务器 ID")
|
||||
_ = command.MarkFlagRequired("id")
|
||||
return command
|
||||
}
|
||||
|
||||
func newDomainServersCommand() *cobra.Command {
|
||||
command := &cobra.Command{Use: "servers", Short: "管理域名关联的部署服务器"}
|
||||
command.AddCommand(newDomainServersListCommand(), newDomainServersSetCommand())
|
||||
return command
|
||||
}
|
||||
|
||||
func newDomainServersListCommand() *cobra.Command {
|
||||
var domainID string
|
||||
command := &cobra.Command{Use: "list", Short: "查看域名关联的部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
if _, err := service.Repository.GetByID(cmd.Context(), domainID); err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := service.Servers.ListServersByDomainID(cmd.Context(), domainID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, items)
|
||||
}}
|
||||
command.Flags().StringVar(&domainID, "domain-id", "", "域名 ID")
|
||||
_ = command.MarkFlagRequired("domain-id")
|
||||
return command
|
||||
}
|
||||
|
||||
func newDomainServersSetCommand() *cobra.Command {
|
||||
var domainID string
|
||||
var serverIDs []string
|
||||
command := &cobra.Command{Use: "set", Short: "替换域名关联的部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
if _, err := service.Repository.GetByID(cmd.Context(), domainID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := service.Servers.ReplaceDomainServers(cmd.Context(), domainID, serverIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := service.Servers.ListServersByDomainID(cmd.Context(), domainID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, items)
|
||||
}}
|
||||
command.Flags().StringVar(&domainID, "domain-id", "", "域名 ID")
|
||||
command.Flags().StringSliceVar(&serverIDs, "server-ids", nil, "服务器 ID 列表;留空表示清除全部关联")
|
||||
_ = command.MarkFlagRequired("domain-id")
|
||||
return command
|
||||
}
|
||||
|
||||
type serverFlags struct {
|
||||
name, address, username, privateKeyRef, fingerprint string
|
||||
certificatePath, privateKeyPath, chainPath, webServer string
|
||||
reloadCommand []string
|
||||
port int
|
||||
}
|
||||
|
||||
func (f *serverFlags) bind(command *cobra.Command) {
|
||||
command.Flags().StringVar(&f.name, "name", "", "服务器名称")
|
||||
command.Flags().StringVar(&f.address, "address", "", "服务器地址")
|
||||
command.Flags().IntVar(&f.port, "port", 22, "SSH 端口")
|
||||
command.Flags().StringVar(&f.username, "username", "", "SSH 用户")
|
||||
command.Flags().StringVar(&f.privateKeyRef, "private-key-ref", "", "SSH 私钥的敏感信息引用")
|
||||
command.Flags().StringVar(&f.fingerprint, "host-key-fingerprint", "", "SSH 主机 SHA256 指纹")
|
||||
command.Flags().StringVar(&f.certificatePath, "certificate-path", deployment.DefaultCertificatePath, "远程证书文件路径模板")
|
||||
command.Flags().StringVar(&f.privateKeyPath, "private-key-path", deployment.DefaultPrivateKeyPath, "远程私钥文件路径模板")
|
||||
command.Flags().StringVar(&f.chainPath, "chain-path", deployment.DefaultCertificateChainPath, "远程完整证书链路径模板")
|
||||
command.Flags().StringVar(&f.webServer, "web-server", string(deployment.WebServerNginx), "Web 服务类型:nginx、caddy、apache、custom")
|
||||
command.Flags().StringSliceVar(&f.reloadCommand, "reload-command", nil, "自定义 reload 命令及参数")
|
||||
for _, name := range []string{"name", "address", "username", "private-key-ref", "host-key-fingerprint"} {
|
||||
_ = command.MarkFlagRequired(name)
|
||||
}
|
||||
}
|
||||
|
||||
func (f serverFlags) server() deployment.Server {
|
||||
command := make([]string, 0, len(f.reloadCommand))
|
||||
for _, value := range f.reloadCommand {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
command = append(command, value)
|
||||
}
|
||||
}
|
||||
return deployment.Server{
|
||||
Name: f.name, Address: f.address, Port: f.port, Username: f.username,
|
||||
PrivateKeyRef: f.privateKeyRef, HostKeyFingerprint: f.fingerprint,
|
||||
CertificatePath: f.certificatePath, PrivateKeyPath: f.privateKeyPath,
|
||||
CertificateChainPath: f.chainPath, WebServer: deployment.WebServer(f.webServer), ReloadCommand: command,
|
||||
}
|
||||
}
|
||||
|
||||
func openApplication(cmd *cobra.Command) (*app.App, error) {
|
||||
cfg, err := loadConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return app.New(cmd.Context(), cfg)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
|
||||
)
|
||||
|
||||
func newSSHKeyCommand() *cobra.Command {
|
||||
command := &cobra.Command{Use: "ssh-key", Short: "管理 SSH 部署私钥"}
|
||||
command.AddCommand(newSSHKeyListCommand(), newSSHKeyAddCommand(), newSSHKeyDeleteCommand())
|
||||
return command
|
||||
}
|
||||
|
||||
func newSSHKeyListCommand() *cobra.Command {
|
||||
return &cobra.Command{Use: "list", Short: "查看 SSH 私钥元数据", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
items, err := service.SSHKeys.List(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, items)
|
||||
}}
|
||||
}
|
||||
|
||||
func newSSHKeyAddCommand() *cobra.Command {
|
||||
var name, filePath, passphraseFile string
|
||||
command := &cobra.Command{Use: "add", Short: "从文件安全录入 SSH 私钥", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
privateKey, err := readLimitedFile(filePath, sshkey.MaxPrivateKeyBytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 SSH 私钥文件失败:%w", err)
|
||||
}
|
||||
passphrase := ""
|
||||
if strings.TrimSpace(passphraseFile) != "" {
|
||||
content, err := readLimitedFile(passphraseFile, 4096)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 SSH 私钥口令文件失败:%w", err)
|
||||
}
|
||||
passphrase = strings.TrimRight(content, "\r\n")
|
||||
}
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
item, err := service.SSHKeys.Create(cmd.Context(), name, privateKey, passphrase)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printJSON(cmd, item)
|
||||
}}
|
||||
command.Flags().StringVar(&name, "name", "", "SSH 私钥名称")
|
||||
command.Flags().StringVar(&filePath, "file", "", "SSH 私钥文件路径")
|
||||
command.Flags().StringVar(&passphraseFile, "passphrase-file", "", "可选的私钥口令文件路径")
|
||||
_ = command.MarkFlagRequired("name")
|
||||
_ = command.MarkFlagRequired("file")
|
||||
return command
|
||||
}
|
||||
|
||||
func newSSHKeyDeleteCommand() *cobra.Command {
|
||||
var id string
|
||||
command := &cobra.Command{Use: "delete", Short: "删除未被服务器使用的 SSH 私钥", RunE: func(cmd *cobra.Command, args []string) error {
|
||||
service, err := openApplication(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer service.Close()
|
||||
reference, err := service.SSHKeys.Reference(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
used, err := service.Servers.IsPrivateKeyRefUsed(cmd.Context(), reference)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if used {
|
||||
return errors.New("SSH 私钥仍被部署服务器使用,不能删除")
|
||||
}
|
||||
if err := service.SSHKeys.Delete(cmd.Context(), id); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "SSH 私钥已删除:%s\n", id)
|
||||
return nil
|
||||
}}
|
||||
command.Flags().StringVar(&id, "id", "", "SSH 私钥 ID")
|
||||
_ = command.MarkFlagRequired("id")
|
||||
return command
|
||||
}
|
||||
|
||||
func readLimitedFile(path string, limit int) (string, error) {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return "", errors.New("文件路径不能为空")
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
content, err := io.ReadAll(io.LimitReader(file, int64(limit)+1))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(content) > limit {
|
||||
return "", fmt.Errorf("文件不能超过 %d 字节", limit)
|
||||
}
|
||||
return string(content), nil
|
||||
}
|
||||
@@ -3,6 +3,9 @@ package config
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -31,10 +34,9 @@ type Config struct {
|
||||
}
|
||||
|
||||
type AdminConfig struct {
|
||||
Username string `json:"username"`
|
||||
PasswordHash string `json:"password_hash"`
|
||||
ResetServiceHost string `json:"reset_service_host"`
|
||||
ResetServicePort int `json:"reset_service_port"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
PasswordHash string `json:"password_hash"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -97,7 +99,7 @@ func Default(baseDir string) Config {
|
||||
return Config{
|
||||
Version: CurrentVersion,
|
||||
SetupReady: false,
|
||||
Admin: AdminConfig{ResetServiceHost: "127.0.0.1", ResetServicePort: 8091},
|
||||
Admin: AdminConfig{},
|
||||
Server: ServerConfig{Host: "0.0.0.0", Port: 8080, HTTPSMode: "direct"},
|
||||
Web: WebConfig{Enabled: true},
|
||||
Database: DatabaseConfig{
|
||||
@@ -171,12 +173,6 @@ func (c *Config) Normalize() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
if c.Admin.ResetServiceHost == "" {
|
||||
c.Admin.ResetServiceHost = "127.0.0.1"
|
||||
}
|
||||
if c.Admin.ResetServicePort == 0 {
|
||||
c.Admin.ResetServicePort = 8091
|
||||
}
|
||||
if c.Server.Host == "" {
|
||||
c.Server.Host = "0.0.0.0"
|
||||
}
|
||||
@@ -226,18 +222,6 @@ func (c Config) Validate() error {
|
||||
if c.Server.Port < 1 || c.Server.Port > 65535 {
|
||||
return fmt.Errorf("服务监听端口无效:%d", c.Server.Port)
|
||||
}
|
||||
if strings.TrimSpace(c.Admin.ResetServiceHost) == "" {
|
||||
return fmt.Errorf("密码重置服务监听地址不能为空")
|
||||
}
|
||||
if c.Admin.ResetServiceHost != "127.0.0.1" && c.Admin.ResetServiceHost != "::1" {
|
||||
return fmt.Errorf("密码重置服务仅允许使用 127.0.0.1 或 ::1")
|
||||
}
|
||||
if c.Admin.ResetServicePort < 1 || c.Admin.ResetServicePort > 65535 {
|
||||
return fmt.Errorf("密码重置服务监听端口无效:%d", c.Admin.ResetServicePort)
|
||||
}
|
||||
if c.Server.Port == c.Admin.ResetServicePort && c.Server.Host == c.Admin.ResetServiceHost {
|
||||
return fmt.Errorf("主服务和密码重置服务不能使用相同监听地址和端口")
|
||||
}
|
||||
if c.Server.HTTPSMode != "direct" && c.Server.HTTPSMode != "proxy" {
|
||||
return fmt.Errorf("HTTPS 模式无效:%s", c.Server.HTTPSMode)
|
||||
}
|
||||
@@ -277,11 +261,16 @@ func (c Config) Validate() error {
|
||||
if strings.TrimSpace(c.Admin.Username) == "" || strings.TrimSpace(c.Admin.PasswordHash) == "" {
|
||||
return fmt.Errorf("初始化完成时必须配置超级管理员账号")
|
||||
}
|
||||
adminEmail := strings.ToLower(strings.TrimSpace(c.Admin.Email))
|
||||
parsedEmail, emailErr := mail.ParseAddress(adminEmail)
|
||||
if adminEmail == "" || emailErr != nil || parsedEmail.Address != adminEmail || parsedEmail.Name != "" {
|
||||
return fmt.Errorf("初始化完成时必须配置合法的超级管理员绑定邮箱")
|
||||
}
|
||||
if c.DNS.VerificationState != "verified" {
|
||||
return fmt.Errorf("初始化完成时必须先通过 DNS API 验证")
|
||||
}
|
||||
if strings.TrimSpace(c.Web.Hostname) == "" && strings.TrimSpace(c.Web.PublicIP) == "" {
|
||||
return fmt.Errorf("初始化完成时必须配置 Web 域名或公网 IP")
|
||||
return fmt.Errorf("初始化完成时必须配置管理页面域名或公网 IP")
|
||||
}
|
||||
}
|
||||
if c.Notification.TimeoutSecs < 1 || c.Notification.RetryCount < 0 {
|
||||
@@ -289,3 +278,22 @@ func (c Config) Validate() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetURL 返回通过主 Web 服务访问密码重置入口的公开地址。
|
||||
func (c Config) ResetURL() string {
|
||||
host := strings.TrimSpace(c.Web.Hostname)
|
||||
if host == "" {
|
||||
host = strings.TrimSpace(c.Web.PublicIP)
|
||||
}
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
if parsed, err := url.Parse(host); err == nil && parsed.Hostname() != "" {
|
||||
host = parsed.Hostname()
|
||||
}
|
||||
host = strings.Trim(host, "[]")
|
||||
if ip := net.ParseIP(host); ip != nil && strings.Contains(host, ":") {
|
||||
host = "[" + host + "]"
|
||||
}
|
||||
return (&url.URL{Scheme: "https", Host: host, Path: "/reset"}).String()
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -76,3 +77,42 @@ func TestValidateRejectsInvalidPort(t *testing.T) {
|
||||
t.Fatal("无效端口未被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetURLUsesWebHostnameWithoutPort(t *testing.T) {
|
||||
cfg := Default(t.TempDir())
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Server.Port = 8443
|
||||
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
|
||||
t.Fatalf("域名密码重置地址不正确:%s", value)
|
||||
}
|
||||
cfg.Server.Port = 443
|
||||
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
|
||||
t.Fatalf("默认 HTTPS 端口不应显示端口号:%s", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetURLSupportsPublicIPv6(t *testing.T) {
|
||||
cfg := Default(t.TempDir())
|
||||
cfg.Web.PublicIP = "2001:db8::10"
|
||||
cfg.Server.Port = 8443
|
||||
if value := cfg.ResetURL(); value != "https://[2001:db8::10]/reset" {
|
||||
t.Fatalf("IPv6 密码重置地址不正确:%s", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSavedConfigDoesNotContainIndependentResetPort(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := Default(dir)
|
||||
path := filepath.Join(dir, "config", "scert.json")
|
||||
if err := cfg.Save(path); err != nil {
|
||||
t.Fatalf("保存配置失败:%v", err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("读取配置失败:%v", err)
|
||||
}
|
||||
content := string(data)
|
||||
if strings.Contains(content, "reset_service_port") || strings.Contains(content, "reset_service_host") {
|
||||
t.Fatalf("配置文件不应再包含独立密码重置监听配置:%s", content)
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ func TestOpenAndMigrateSQLite(t *testing.T) {
|
||||
if err := db.DB.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&count); err != nil {
|
||||
t.Fatalf("读取迁移版本失败:%v", err)
|
||||
}
|
||||
if count != 2 {
|
||||
if count != 3 {
|
||||
t.Fatalf("迁移版本数量错误:%d", count)
|
||||
}
|
||||
var autoRenew bool
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed migrations/sqlite/0001_initial.sql migrations/sqlite/0002_domain_options.sql migrations/mysql/0001_initial.sql migrations/mysql/0002_domain_options.sql
|
||||
//go:embed migrations/sqlite/0001_initial.sql migrations/sqlite/0002_domain_options.sql migrations/sqlite/0003_deployment.sql migrations/mysql/0001_initial.sql migrations/mysql/0002_domain_options.sql migrations/mysql/0003_deployment.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
func Migrate(ctx context.Context, db *sql.DB, driver string) error {
|
||||
@@ -37,7 +37,7 @@ func Migrate(ctx context.Context, db *sql.DB, driver string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
const latestMigrationVersion = 2
|
||||
const latestMigrationVersion = 3
|
||||
|
||||
func applyMigration(ctx context.Context, db *sql.DB, driver string, version int) error {
|
||||
path := fmt.Sprintf("migrations/%s/%04d_%s.sql", driver, version, migrationName(version))
|
||||
@@ -83,6 +83,8 @@ func migrationName(version int) string {
|
||||
return "initial"
|
||||
case 2:
|
||||
return "domain_options"
|
||||
case 3:
|
||||
return "deployment"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE IF NOT EXISTS servers (
|
||||
id VARCHAR(36) NOT NULL PRIMARY KEY,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
address VARCHAR(253) NOT NULL,
|
||||
port INT NOT NULL,
|
||||
username VARCHAR(128) NOT NULL,
|
||||
private_key_ref VARCHAR(255) NOT NULL,
|
||||
host_key_fingerprint VARCHAR(255) NOT NULL,
|
||||
certificate_path VARCHAR(1024) NOT NULL,
|
||||
private_key_path VARCHAR(1024) NOT NULL,
|
||||
certificate_chain_path VARCHAR(1024) NOT NULL,
|
||||
web_server VARCHAR(32) NOT NULL,
|
||||
reload_command_json TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX idx_servers_name (name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS domain_servers (
|
||||
domain_id VARCHAR(36) NOT NULL,
|
||||
server_id VARCHAR(36) NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (domain_id, server_id),
|
||||
INDEX idx_domain_servers_server_id (server_id)
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE IF NOT EXISTS servers (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
private_key_ref TEXT NOT NULL,
|
||||
host_key_fingerprint TEXT NOT NULL,
|
||||
certificate_path TEXT NOT NULL,
|
||||
private_key_path TEXT NOT NULL,
|
||||
certificate_chain_path TEXT NOT NULL,
|
||||
web_server TEXT NOT NULL,
|
||||
reload_command_json TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS domain_servers (
|
||||
domain_id TEXT NOT NULL,
|
||||
server_id TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (domain_id, server_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_domain_servers_server_id ON domain_servers(server_id);
|
||||
@@ -52,14 +52,14 @@ func TestSQLiteMigrationIsIdempotentAndCreatesBaseTables(t *testing.T) {
|
||||
if err := db.DB.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&versions); err != nil {
|
||||
t.Fatalf("读取迁移版本失败:%v", err)
|
||||
}
|
||||
if versions != 2 {
|
||||
if versions != 3 {
|
||||
t.Fatalf("重复迁移写入了多条版本记录:%d", versions)
|
||||
}
|
||||
var tables int
|
||||
if err := db.DB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('settings', 'domains', 'tasks', 'audit_logs')`).Scan(&tables); err != nil {
|
||||
if err := db.DB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('settings', 'domains', 'tasks', 'audit_logs', 'servers', 'domain_servers')`).Scan(&tables); err != nil {
|
||||
t.Fatalf("检查基础数据表失败:%v", err)
|
||||
}
|
||||
if tables != 4 {
|
||||
if tables != 6 {
|
||||
t.Fatalf("基础数据表数量不正确:%d", tables)
|
||||
}
|
||||
if err := Migrate(context.Background(), db.DB, "postgres"); err == nil {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package deployment
|
||||
|
||||
import "context"
|
||||
|
||||
type CommandResult struct {
|
||||
Output []byte
|
||||
ExitCode int
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
MkdirAll(ctx context.Context, path string) error
|
||||
Exists(ctx context.Context, path string) (bool, error)
|
||||
Upload(ctx context.Context, path string, data []byte, mode uint32) error
|
||||
Rename(ctx context.Context, source, target string) error
|
||||
Remove(ctx context.Context, path string) error
|
||||
Run(ctx context.Context, command []string) (CommandResult, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
type ClientFactory interface {
|
||||
Connect(ctx context.Context, server Server) (Client, error)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type WebServer string
|
||||
|
||||
const (
|
||||
WebServerNginx WebServer = "nginx"
|
||||
WebServerCaddy WebServer = "caddy"
|
||||
WebServerApache WebServer = "apache"
|
||||
WebServerCustom WebServer = "custom"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultCertificatePath = "/ssl/{域名}/{证书类型}/cert.pem"
|
||||
DefaultCertificateChainPath = "/ssl/{域名}/{证书类型}/fullchain.pem"
|
||||
DefaultPrivateKeyPath = "/ssl/{域名}/{证书类型}/key.pem"
|
||||
)
|
||||
|
||||
var serverPathPlaceholderPattern = regexp.MustCompile(`\{[^{}]+\}`)
|
||||
|
||||
type Server struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
PrivateKeyRef string `json:"private_key_ref"`
|
||||
HostKeyFingerprint string `json:"host_key_fingerprint"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
CertificateChainPath string `json:"certificate_chain_path"`
|
||||
WebServer WebServer `json:"web_server"`
|
||||
ReloadCommand []string `json:"reload_command,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s Server) Normalize() Server {
|
||||
s.ID = strings.TrimSpace(s.ID)
|
||||
s.Name = strings.TrimSpace(s.Name)
|
||||
s.Address = strings.TrimSpace(s.Address)
|
||||
s.Username = strings.TrimSpace(s.Username)
|
||||
s.PrivateKeyRef = strings.TrimSpace(s.PrivateKeyRef)
|
||||
s.HostKeyFingerprint = strings.TrimSpace(s.HostKeyFingerprint)
|
||||
s.CertificatePath = strings.TrimSpace(s.CertificatePath)
|
||||
s.PrivateKeyPath = strings.TrimSpace(s.PrivateKeyPath)
|
||||
s.CertificateChainPath = strings.TrimSpace(s.CertificateChainPath)
|
||||
if s.CertificatePath == "" {
|
||||
s.CertificatePath = DefaultCertificatePath
|
||||
}
|
||||
if s.CertificateChainPath == "" {
|
||||
s.CertificateChainPath = DefaultCertificateChainPath
|
||||
}
|
||||
if s.PrivateKeyPath == "" {
|
||||
s.PrivateKeyPath = DefaultPrivateKeyPath
|
||||
}
|
||||
s.WebServer = WebServer(strings.ToLower(strings.TrimSpace(string(s.WebServer))))
|
||||
if s.Port == 0 {
|
||||
s.Port = 22
|
||||
}
|
||||
if len(s.ReloadCommand) == 0 {
|
||||
s.ReloadCommand = DefaultReloadCommand(s.WebServer)
|
||||
}
|
||||
for index := range s.ReloadCommand {
|
||||
s.ReloadCommand[index] = strings.TrimSpace(s.ReloadCommand[index])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func ResolveServerPaths(server Server, domainName, certificateType string) (Server, error) {
|
||||
server = server.Normalize()
|
||||
domainDirectory, err := normalizeDomainDirectory(domainName)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
certificateType = strings.ToLower(strings.TrimSpace(certificateType))
|
||||
switch certificateType {
|
||||
case "single", "wildcard", "san":
|
||||
default:
|
||||
return Server{}, fmt.Errorf("证书类型无法用于远程路径:%s", certificateType)
|
||||
}
|
||||
replacer := strings.NewReplacer(
|
||||
"{域名}", domainDirectory,
|
||||
"{domain}", domainDirectory,
|
||||
"{证书类型}", certificateType,
|
||||
"{certificate_type}", certificateType,
|
||||
)
|
||||
server.CertificatePath, err = resolveServerPathTemplate("远程证书路径", server.CertificatePath, replacer)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
server.CertificateChainPath, err = resolveServerPathTemplate("远程完整证书链路径", server.CertificateChainPath, replacer)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
server.PrivateKeyPath, err = resolveServerPathTemplate("远程私钥路径", server.PrivateKeyPath, replacer)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func normalizeDomainDirectory(value string) (string, error) {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
value = strings.TrimPrefix(value, "*.")
|
||||
if value == "" || value == "." || value == ".." || strings.ContainsAny(value, "/\\\x00\r\n") {
|
||||
return "", fmt.Errorf("域名无法用于远程路径:%s", value)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func resolveServerPathTemplate(label, value string, replacer *strings.Replacer) (string, error) {
|
||||
resolved := replacer.Replace(strings.TrimSpace(value))
|
||||
if placeholder := serverPathPlaceholderPattern.FindString(resolved); placeholder != "" {
|
||||
return "", fmt.Errorf("%s包含不支持的占位符:%s", label, placeholder)
|
||||
}
|
||||
cleaned := RemotePath(resolved)
|
||||
if cleaned == "" || cleaned == "." {
|
||||
return "", fmt.Errorf("%s无效", label)
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
func (s Server) Validate() error {
|
||||
s = s.Normalize()
|
||||
if s.ID == "" {
|
||||
return errors.New("服务器 ID 不能为空")
|
||||
}
|
||||
if s.Name == "" {
|
||||
return errors.New("服务器名称不能为空")
|
||||
}
|
||||
if s.Address == "" || net.ParseIP(s.Address) == nil && strings.ContainsAny(s.Address, " /\\") {
|
||||
return errors.New("服务器地址无效")
|
||||
}
|
||||
if s.Port < 1 || s.Port > 65535 {
|
||||
return errors.New("SSH 端口无效")
|
||||
}
|
||||
if s.Username == "" {
|
||||
return errors.New("SSH 用户不能为空")
|
||||
}
|
||||
if s.PrivateKeyRef == "" {
|
||||
return errors.New("SSH 私钥引用不能为空")
|
||||
}
|
||||
if s.HostKeyFingerprint == "" {
|
||||
return errors.New("SSH 主机指纹不能为空")
|
||||
}
|
||||
if s.CertificatePath == "" || s.PrivateKeyPath == "" || s.CertificateChainPath == "" {
|
||||
return errors.New("远程证书路径不能为空")
|
||||
}
|
||||
if _, err := ResolveServerPaths(s, "example.com", "single"); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.WebServer != WebServerNginx && s.WebServer != WebServerCaddy && s.WebServer != WebServerApache && s.WebServer != WebServerCustom {
|
||||
return fmt.Errorf("网站服务类型无效:%s", s.WebServer)
|
||||
}
|
||||
if len(s.ReloadCommand) == 0 || s.ReloadCommand[0] == "" {
|
||||
return errors.New("reload 命令不能为空")
|
||||
}
|
||||
for _, argument := range s.ReloadCommand {
|
||||
if argument == "" || strings.ContainsAny(argument, "\x00\r\n") {
|
||||
return errors.New("reload 命令参数无效")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DefaultReloadCommand(webServer WebServer) []string {
|
||||
switch WebServer(strings.ToLower(strings.TrimSpace(string(webServer)))) {
|
||||
case WebServerNginx:
|
||||
return []string{"nginx", "-s", "reload"}
|
||||
case WebServerCaddy:
|
||||
return []string{"caddy", "reload"}
|
||||
case WebServerApache:
|
||||
return []string{"apachectl", "-k", "graceful"}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func RemotePath(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
return ""
|
||||
}
|
||||
return path.Clean(strings.ReplaceAll(value, "\\", "/"))
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package deployment
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestServerUsesDefaultReloadCommand(t *testing.T) {
|
||||
server := testServer("one").Normalize()
|
||||
if err := server.Validate(); err != nil {
|
||||
t.Fatalf("服务器配置校验失败:%v", err)
|
||||
}
|
||||
if len(server.ReloadCommand) != 3 || server.ReloadCommand[0] != "nginx" {
|
||||
t.Fatalf("Nginx 默认 reload 命令错误:%v", server.ReloadCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerUsesDefaultCertificatePathTemplates(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.CertificatePath = ""
|
||||
server.CertificateChainPath = ""
|
||||
server.PrivateKeyPath = ""
|
||||
server = server.Normalize()
|
||||
if server.CertificatePath != DefaultCertificatePath || server.CertificateChainPath != DefaultCertificateChainPath || server.PrivateKeyPath != DefaultPrivateKeyPath {
|
||||
t.Fatalf("远程证书默认路径模板错误:%+v", server)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveServerPathsByCertificateType(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
domainName string
|
||||
certificateType string
|
||||
expectedRoot string
|
||||
}{
|
||||
{name: "单域名", domainName: "example.com", certificateType: "single", expectedRoot: "/ssl/example.com/single"},
|
||||
{name: "泛域名", domainName: "*.example.com", certificateType: "wildcard", expectedRoot: "/ssl/example.com/wildcard"},
|
||||
{name: "SAN", domainName: "example.com", certificateType: "san", expectedRoot: "/ssl/example.com/san"},
|
||||
}
|
||||
for _, item := range tests {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.CertificatePath = ""
|
||||
server.CertificateChainPath = ""
|
||||
server.PrivateKeyPath = ""
|
||||
resolved, err := ResolveServerPaths(server, item.domainName, item.certificateType)
|
||||
if err != nil {
|
||||
t.Fatalf("解析远程证书路径失败:%v", err)
|
||||
}
|
||||
if resolved.CertificatePath != item.expectedRoot+"/cert.pem" || resolved.CertificateChainPath != item.expectedRoot+"/fullchain.pem" || resolved.PrivateKeyPath != item.expectedRoot+"/key.pem" {
|
||||
t.Fatalf("远程证书路径解析错误:%+v", resolved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveServerPathsKeepsCustomPathAndRejectsUnknownPlaceholder(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.CertificatePath = "/custom/{domain}/{certificate_type}/certificate.crt"
|
||||
resolved, err := ResolveServerPaths(server, "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("解析自定义远程证书路径失败:%v", err)
|
||||
}
|
||||
if resolved.CertificatePath != "/custom/example.com/single/certificate.crt" {
|
||||
t.Fatalf("自定义远程证书路径被错误处理:%s", resolved.CertificatePath)
|
||||
}
|
||||
server.CertificatePath = "/ssl/{未知占位符}/cert.pem"
|
||||
if _, err := ResolveServerPaths(server, "example.com", "single"); err == nil {
|
||||
t.Fatal("包含未知占位符的远程证书路径应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerRejectsPasswordStyleOrUnsafeConfiguration(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.PrivateKeyRef = ""
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("未配置 SSH 私钥引用时应拒绝服务器配置")
|
||||
}
|
||||
server = testServer("one")
|
||||
server.ReloadCommand = []string{"nginx\nrm", "-s", "reload"}
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("reload 参数包含换行时应拒绝服务器配置")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Target struct {
|
||||
Server Server
|
||||
}
|
||||
|
||||
type Artifact struct {
|
||||
Certificate []byte
|
||||
FullChain []byte
|
||||
PrivateKey []byte
|
||||
}
|
||||
|
||||
type SavedFiles struct {
|
||||
CertificatePath string
|
||||
FullChainPath string
|
||||
PrivateKeyPath string
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
ServerID string `json:"server_id"`
|
||||
Server string `json:"server"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
BackupID string `json:"backup_id,omitempty"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Total int `json:"total"`
|
||||
Success int `json:"success"`
|
||||
Failed int `json:"failed"`
|
||||
Status string `json:"status"`
|
||||
Results []Result `json:"results"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
factory ClientFactory
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewService(factory ClientFactory) *Service {
|
||||
return &Service{factory: factory, now: time.Now}
|
||||
}
|
||||
|
||||
func (s *Service) Deploy(ctx context.Context, targets []Target, artifact Artifact) Report {
|
||||
report := Report{Total: len(targets), Results: make([]Result, 0, len(targets))}
|
||||
if s == nil || s.factory == nil {
|
||||
report.Status = "failed"
|
||||
report.Failed = len(targets)
|
||||
for _, target := range targets {
|
||||
report.Results = append(report.Results, Result{ServerID: target.Server.ID, Server: target.Server.Name, Status: "failed", Message: "部署服务未初始化"})
|
||||
}
|
||||
return report
|
||||
}
|
||||
if err := validateArtifact(artifact); err != nil {
|
||||
report.Status = "failed"
|
||||
report.Failed = len(targets)
|
||||
for _, target := range targets {
|
||||
report.Results = append(report.Results, Result{ServerID: target.Server.ID, Server: target.Server.Name, Status: "failed", Message: err.Error()})
|
||||
}
|
||||
return report
|
||||
}
|
||||
for _, target := range targets {
|
||||
result := s.deployOne(ctx, target.Server, artifact)
|
||||
report.Results = append(report.Results, result)
|
||||
if result.Status == "success" {
|
||||
report.Success++
|
||||
} else {
|
||||
report.Failed++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case report.Failed == 0:
|
||||
report.Status = "success"
|
||||
case report.Success == 0:
|
||||
report.Status = "failed"
|
||||
default:
|
||||
report.Status = "partial"
|
||||
}
|
||||
return report
|
||||
}
|
||||
|
||||
func (s *Service) DeploySaved(ctx context.Context, targets []Target, saved SavedFiles) (Report, error) {
|
||||
certificateData, err := os.ReadFile(saved.CertificatePath)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("读取证书文件失败:%w", err)
|
||||
}
|
||||
fullChainData, err := os.ReadFile(saved.FullChainPath)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("读取完整证书链失败:%w", err)
|
||||
}
|
||||
privateKeyData, err := os.ReadFile(saved.PrivateKeyPath)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("读取私钥文件失败:%w", err)
|
||||
}
|
||||
return s.Deploy(ctx, targets, Artifact{Certificate: certificateData, FullChain: fullChainData, PrivateKey: privateKeyData}), nil
|
||||
}
|
||||
|
||||
func (s *Service) deployOne(ctx context.Context, server Server, artifact Artifact) Result {
|
||||
server = server.Normalize()
|
||||
result := Result{ServerID: server.ID, Server: server.Name, Status: "failed"}
|
||||
if err := server.Validate(); err != nil {
|
||||
result.Message = err.Error()
|
||||
return result
|
||||
}
|
||||
client, err := s.factory.Connect(ctx, server)
|
||||
if err != nil {
|
||||
result.Message = fmt.Sprintf("连接服务器失败:%v", err)
|
||||
return result
|
||||
}
|
||||
defer client.Close()
|
||||
paths := []remoteFile{
|
||||
{path: RemotePath(server.CertificatePath), data: artifact.Certificate, mode: 0o644},
|
||||
{path: RemotePath(server.CertificateChainPath), data: artifact.FullChain, mode: 0o644},
|
||||
{path: RemotePath(server.PrivateKeyPath), data: artifact.PrivateKey, mode: 0o600},
|
||||
}
|
||||
for _, file := range paths {
|
||||
if file.path == "" || file.path == "." {
|
||||
result.Message = "远程证书路径无效"
|
||||
return result
|
||||
}
|
||||
}
|
||||
backupID := s.backupID()
|
||||
type backup struct{ original, saved string }
|
||||
backups := make([]backup, 0, len(paths))
|
||||
temporary := make([]string, 0, len(paths))
|
||||
installed := make([]string, 0, len(paths))
|
||||
rollback := func() {
|
||||
for _, path := range temporary {
|
||||
_ = client.Remove(context.Background(), path)
|
||||
}
|
||||
for _, path := range installed {
|
||||
_ = client.Remove(context.Background(), path)
|
||||
}
|
||||
for index := len(backups) - 1; index >= 0; index-- {
|
||||
item := backups[index]
|
||||
_ = client.Rename(context.Background(), item.saved, item.original)
|
||||
}
|
||||
}
|
||||
for _, file := range paths {
|
||||
if err := client.MkdirAll(ctx, parentPath(file.path)); err != nil {
|
||||
result.Message = fmt.Sprintf("创建远程目录失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
exists, err := client.Exists(ctx, file.path)
|
||||
if err != nil {
|
||||
result.Message = fmt.Sprintf("检查远程文件失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
if exists {
|
||||
backupPath := file.path + ".scert-backup-" + backupID
|
||||
if err := client.Rename(ctx, file.path, backupPath); err != nil {
|
||||
result.Message = fmt.Sprintf("备份远程证书失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
backups = append(backups, backup{original: file.path, saved: backupPath})
|
||||
}
|
||||
temporaryPath := file.path + ".scert-tmp-" + backupID
|
||||
if err := client.Upload(ctx, temporaryPath, file.data, file.mode); err != nil {
|
||||
result.Message = fmt.Sprintf("上传远程证书失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
temporary = append(temporary, temporaryPath)
|
||||
if err := client.Rename(ctx, temporaryPath, file.path); err != nil {
|
||||
result.Message = fmt.Sprintf("替换远程证书失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
temporary = temporary[:len(temporary)-1]
|
||||
installed = append(installed, file.path)
|
||||
}
|
||||
commandResult, err := client.Run(ctx, server.ReloadCommand)
|
||||
if err != nil || commandResult.ExitCode != 0 {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("退出码 %d", commandResult.ExitCode)
|
||||
}
|
||||
result.Message = fmt.Sprintf("reload 失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
result.Status = "success"
|
||||
result.Message = "证书部署并 reload 成功"
|
||||
result.BackupID = backupID
|
||||
return result
|
||||
}
|
||||
|
||||
type remoteFile struct {
|
||||
path string
|
||||
data []byte
|
||||
mode uint32
|
||||
}
|
||||
|
||||
func validateArtifact(artifact Artifact) error {
|
||||
if len(artifact.Certificate) == 0 || len(artifact.FullChain) == 0 || len(artifact.PrivateKey) == 0 {
|
||||
return errors.New("证书部署文件不完整")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) backupID() string {
|
||||
var random [6]byte
|
||||
_, _ = rand.Read(random[:])
|
||||
now := time.Now
|
||||
if s.now != nil {
|
||||
now = s.now
|
||||
}
|
||||
return now().UTC().Format("20060102-150405.000000000") + "-" + hex.EncodeToString(random[:])
|
||||
}
|
||||
|
||||
func parentPath(path string) string {
|
||||
index := strings.LastIndexAny(path, "/\\")
|
||||
if index < 1 {
|
||||
return "."
|
||||
}
|
||||
return path[:index]
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type memoryFile struct {
|
||||
data []byte
|
||||
mode uint32
|
||||
}
|
||||
|
||||
type memoryClient struct {
|
||||
files map[string]memoryFile
|
||||
command []string
|
||||
runResult CommandResult
|
||||
runErr error
|
||||
uploadError string
|
||||
}
|
||||
|
||||
func newMemoryClient() *memoryClient {
|
||||
return &memoryClient{files: map[string]memoryFile{}, runResult: CommandResult{ExitCode: 0}}
|
||||
}
|
||||
|
||||
func (c *memoryClient) MkdirAll(context.Context, string) error { return nil }
|
||||
|
||||
func (c *memoryClient) Exists(_ context.Context, path string) (bool, error) {
|
||||
_, ok := c.files[path]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Upload(_ context.Context, path string, data []byte, mode uint32) error {
|
||||
if c.uploadError != "" && strings.Contains(path, c.uploadError) {
|
||||
return errors.New("模拟上传失败")
|
||||
}
|
||||
c.files[path] = memoryFile{data: append([]byte(nil), data...), mode: mode}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Rename(_ context.Context, source, target string) error {
|
||||
value, ok := c.files[source]
|
||||
if !ok {
|
||||
return errors.New("源文件不存在")
|
||||
}
|
||||
delete(c.files, source)
|
||||
c.files[target] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Remove(_ context.Context, path string) error {
|
||||
delete(c.files, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Run(_ context.Context, command []string) (CommandResult, error) {
|
||||
c.command = append([]string(nil), command...)
|
||||
return c.runResult, c.runErr
|
||||
}
|
||||
|
||||
func (c *memoryClient) Close() error { return nil }
|
||||
|
||||
type memoryFactory struct {
|
||||
clients map[string]*memoryClient
|
||||
errors map[string]error
|
||||
}
|
||||
|
||||
func (f memoryFactory) Connect(_ context.Context, server Server) (Client, error) {
|
||||
if err := f.errors[server.ID]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.clients[server.ID], nil
|
||||
}
|
||||
|
||||
func TestDeployReplacesFilesAndKeepsBackup(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
client.files[server.CertificateChainPath] = memoryFile{data: []byte("old-chain"), mode: 0o644}
|
||||
client.files[server.PrivateKeyPath] = memoryFile{data: []byte("old-key"), mode: 0o600}
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{server.ID: client}})
|
||||
service.now = func() time.Time { return time.Date(2026, 8, 27, 1, 2, 3, 4, time.UTC) }
|
||||
report := service.Deploy(context.Background(), []Target{{Server: server}}, testArtifact())
|
||||
if report.Status != "success" || report.Success != 1 {
|
||||
t.Fatalf("部署结果错误:%+v", report)
|
||||
}
|
||||
if string(client.files[server.CertificatePath].data) != "new-cert" || client.files[server.PrivateKeyPath].mode != 0o600 {
|
||||
t.Fatalf("远程证书内容或权限错误:%+v", client.files)
|
||||
}
|
||||
if len(client.command) != 3 || client.command[0] != "nginx" {
|
||||
t.Fatalf("reload 命令错误:%v", client.command)
|
||||
}
|
||||
backupCount := 0
|
||||
for path := range client.files {
|
||||
if strings.Contains(path, ".scert-backup-") {
|
||||
backupCount++
|
||||
}
|
||||
}
|
||||
if backupCount != 3 {
|
||||
t.Fatalf("成功部署后应保留三份远程备份:%d", backupCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployRollsBackWhenReloadFails(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
client.runResult.ExitCode = 1
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{server.ID: client}})
|
||||
report := service.Deploy(context.Background(), []Target{{Server: server}}, testArtifact())
|
||||
if report.Status != "failed" || report.Failed != 1 {
|
||||
t.Fatalf("reload 失败结果错误:%+v", report)
|
||||
}
|
||||
if string(client.files[server.CertificatePath].data) != "old-cert" {
|
||||
t.Fatalf("reload 失败后旧证书未恢复:%+v", client.files)
|
||||
}
|
||||
if _, ok := client.files[server.PrivateKeyPath]; ok {
|
||||
t.Fatal("原本不存在的私钥文件应在回滚时删除")
|
||||
}
|
||||
for path := range client.files {
|
||||
if strings.Contains(path, ".scert-tmp-") || strings.Contains(path, ".scert-backup-") {
|
||||
t.Fatalf("回滚后不应残留临时文件或备份文件:%s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployReportsPartialSuccess(t *testing.T) {
|
||||
first := newMemoryClient()
|
||||
second := newMemoryClient()
|
||||
second.uploadError = "fullchain.pem"
|
||||
firstServer := testServer("first")
|
||||
secondServer := testServer("second")
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{"first": first, "second": second}})
|
||||
report := service.Deploy(context.Background(), []Target{{Server: firstServer}, {Server: secondServer}}, testArtifact())
|
||||
if report.Status != "partial" || report.Success != 1 || report.Failed != 1 {
|
||||
t.Fatalf("部分成功汇总错误:%+v", report)
|
||||
}
|
||||
}
|
||||
|
||||
func testServer(id string) Server {
|
||||
return Server{
|
||||
ID: id, Name: id, Address: "192.0.2.10", Port: 22, Username: "deploy",
|
||||
PrivateKeyRef: "secret://ssh/" + id, HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/etc/scert/cert.pem", CertificateChainPath: "/etc/scert/fullchain.pem",
|
||||
PrivateKeyPath: "/etc/scert/key.pem", WebServer: WebServerNginx,
|
||||
}
|
||||
}
|
||||
|
||||
func testArtifact() Artifact {
|
||||
return Artifact{Certificate: []byte("new-cert"), FullChain: []byte("new-chain"), PrivateKey: []byte("new-key")}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type SecretReader interface {
|
||||
Get(ctx context.Context, reference string) (map[string]string, error)
|
||||
}
|
||||
|
||||
type SSHFactory struct {
|
||||
Secrets SecretReader
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (f SSHFactory) Connect(ctx context.Context, server Server) (Client, error) {
|
||||
server = server.Normalize()
|
||||
if err := server.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.Secrets == nil {
|
||||
return nil, errors.New("SSH 敏感信息存储未初始化")
|
||||
}
|
||||
secrets, err := f.Secrets.Get(ctx, server.PrivateKeyRef)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 SSH 私钥失败:%w", err)
|
||||
}
|
||||
privateKey := strings.TrimSpace(secrets["private_key"])
|
||||
if privateKey == "" {
|
||||
return nil, errors.New("SSH 私钥内容不能为空")
|
||||
}
|
||||
var signer ssh.Signer
|
||||
passphrase := secrets["passphrase"]
|
||||
if passphrase != "" {
|
||||
signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(privateKey), []byte(passphrase))
|
||||
} else {
|
||||
signer, err = ssh.ParsePrivateKey([]byte(privateKey))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.New("解析 SSH 私钥失败:私钥格式或口令无效")
|
||||
}
|
||||
timeout := f.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 15 * time.Second
|
||||
}
|
||||
address := net.JoinHostPort(server.Address, fmt.Sprintf("%d", server.Port))
|
||||
dialer := net.Dialer{Timeout: timeout}
|
||||
connection, err := dialer.DialContext(ctx, "tcp", address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("连接 SSH 服务器失败:%w", err)
|
||||
}
|
||||
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
fingerprint := ssh.FingerprintSHA256(key)
|
||||
if fingerprint != server.HostKeyFingerprint {
|
||||
return fmt.Errorf("SSH 主机指纹不匹配:服务器 %s 返回 %s", server.Name, fingerprint)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config := &ssh.ClientConfig{
|
||||
User: server.Username, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
|
||||
HostKeyCallback: hostKeyCallback, Timeout: timeout,
|
||||
}
|
||||
clientConn, channels, requests, err := ssh.NewClientConn(connection, address, config)
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("SSH 握手失败:%w", err)
|
||||
}
|
||||
sshClient := ssh.NewClient(clientConn, channels, requests)
|
||||
sftpClient, err := sftp.NewClient(sshClient)
|
||||
if err != nil {
|
||||
_ = sshClient.Close()
|
||||
return nil, fmt.Errorf("创建 SFTP 客户端失败:%w", err)
|
||||
}
|
||||
return &sshClientAdapter{ssh: sshClient, sftp: sftpClient}, nil
|
||||
}
|
||||
|
||||
type sshClientAdapter struct {
|
||||
ssh *ssh.Client
|
||||
sftp *sftp.Client
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) MkdirAll(ctx context.Context, path string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.sftp.MkdirAll(path)
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Exists(ctx context.Context, path string) (bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err := c.sftp.Stat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Upload(ctx context.Context, path string, data []byte, mode uint32) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := c.sftp.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
closeFile := func() error { return file.Close() }
|
||||
if _, err := file.Write(data); err != nil {
|
||||
_ = closeFile()
|
||||
return err
|
||||
}
|
||||
if err := file.Chmod(os.FileMode(mode)); err != nil {
|
||||
_ = closeFile()
|
||||
return err
|
||||
}
|
||||
return closeFile()
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Rename(ctx context.Context, source, target string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.sftp.Rename(source, target)
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Remove(ctx context.Context, path string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
err := c.sftp.Remove(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Run(ctx context.Context, command []string) (CommandResult, error) {
|
||||
if len(command) == 0 {
|
||||
return CommandResult{}, errors.New("远程命令不能为空")
|
||||
}
|
||||
if err := validateCommand(command); err != nil {
|
||||
return CommandResult{}, err
|
||||
}
|
||||
session, err := c.ssh.NewSession()
|
||||
if err != nil {
|
||||
return CommandResult{}, err
|
||||
}
|
||||
defer session.Close()
|
||||
output, err := session.CombinedOutput(joinShellArgs(command))
|
||||
if err != nil {
|
||||
var exitError *ssh.ExitError
|
||||
if errors.As(err, &exitError) {
|
||||
return CommandResult{Output: output, ExitCode: exitError.ExitStatus()}, nil
|
||||
}
|
||||
return CommandResult{Output: output, ExitCode: -1}, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return CommandResult{Output: output, ExitCode: -1}, err
|
||||
}
|
||||
return CommandResult{Output: output}, nil
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Close() error {
|
||||
var first error
|
||||
if c.sftp != nil {
|
||||
if err := c.sftp.Close(); err != nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
if c.ssh != nil {
|
||||
if err := c.ssh.Close(); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
func validateCommand(command []string) error {
|
||||
for _, token := range command {
|
||||
if strings.TrimSpace(token) == "" || strings.ContainsAny(token, "\x00\r\n") {
|
||||
return errors.New("远程命令参数无效")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func joinShellArgs(command []string) string {
|
||||
quoted := make([]string, len(command))
|
||||
for index, token := range command {
|
||||
quoted[index] = "'" + strings.ReplaceAll(token, "'", "'\\''") + "'"
|
||||
}
|
||||
return strings.Join(quoted, " ")
|
||||
}
|
||||
|
||||
var _ io.Closer = (*sshClientAdapter)(nil)
|
||||
@@ -0,0 +1,68 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/pem"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type staticSecretReader map[string]map[string]string
|
||||
|
||||
func (s staticSecretReader) Get(_ context.Context, reference string) (map[string]string, error) {
|
||||
return s[reference], nil
|
||||
}
|
||||
|
||||
func TestSSHFactoryParsesEncryptedPrivateKeyBeforeDialing(t *testing.T) {
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate test private key: %v", err)
|
||||
}
|
||||
block, err := ssh.MarshalPrivateKeyWithPassphrase(key, "scert-deployment-test", []byte("deployment-passphrase"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encrypt test private key: %v", err)
|
||||
}
|
||||
privateKey := string(pem.EncodeToMemory(block))
|
||||
server := Server{
|
||||
ID: "server-test", Name: "test server", Address: "127.0.0.1", Port: 1,
|
||||
Username: "deploy", PrivateKeyRef: "secret://ssh/test", HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/tmp/cert.pem", PrivateKeyPath: "/tmp/key.pem",
|
||||
CertificateChainPath: "/tmp/fullchain.pem", WebServer: WebServerNginx,
|
||||
}
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{server.PrivateKeyRef: {"private_key": privateKey, "passphrase": "deployment-passphrase"}},
|
||||
Timeout: 100 * time.Millisecond,
|
||||
}
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "\u8fde\u63a5 SSH \u670d\u52a1\u5668\u5931\u8d25") {
|
||||
t.Fatalf("encrypted private key should parse before the expected dial failure: %v", err)
|
||||
}
|
||||
factory.Secrets = staticSecretReader{server.PrivateKeyRef: {"private_key": privateKey, "passphrase": "wrong-passphrase"}}
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "\u89e3\u6790 SSH \u79c1\u94a5\u5931\u8d25") {
|
||||
t.Fatalf("wrong passphrase should be rejected before dialing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCommandRejectsShellControlLines(t *testing.T) {
|
||||
for _, command := range [][]string{
|
||||
{"nginx", "-s", "reload\nrm -rf /"},
|
||||
{"nginx", "", "reload"},
|
||||
{"nginx", "-s", "reload\x00"},
|
||||
} {
|
||||
if err := validateCommand(command); err == nil {
|
||||
t.Fatalf("不安全远程命令未被拒绝:%q", command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinShellArgsQuotesArguments(t *testing.T) {
|
||||
command := []string{"nginx", "-c", "/etc/nginx/my config.conf", "reload'check"}
|
||||
joined := joinShellArgs(command)
|
||||
if !strings.Contains(joined, "'/etc/nginx/my config.conf'") || !strings.Contains(joined, "'reload'\\''check'") {
|
||||
t.Fatalf("远程命令参数未正确转义:%s", joined)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/auth"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
authCookieName = "scert_session"
|
||||
authSessionLifetime = 30 * time.Minute
|
||||
rememberSessionLife = 14 * 24 * time.Hour
|
||||
loginWindow = 15 * time.Minute
|
||||
loginBlockDuration = 5 * time.Minute
|
||||
loginFailureLimit = 5
|
||||
authRequestBodyLimit = 16 * 1024
|
||||
)
|
||||
|
||||
type authSession struct {
|
||||
Username string
|
||||
Email string
|
||||
Role string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type loginAttempt struct {
|
||||
Failures int
|
||||
WindowStart time.Time
|
||||
BlockedTill time.Time
|
||||
}
|
||||
|
||||
type authLoginRequest struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Password string `json:"password"`
|
||||
Remember bool `json:"remember"`
|
||||
}
|
||||
|
||||
func (s *Server) authLogin(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, authRequestBodyLimit)
|
||||
var request authLoginRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "\u767b\u5f55\u8bf7\u6c42\u53c2\u6570\u65e0\u6548", err)
|
||||
return
|
||||
}
|
||||
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
if !cfg.SetupReady {
|
||||
s.writeError(c, http.StatusConflict, "\u8bf7\u5148\u5b8c\u6210\u521d\u59cb\u5316\u914d\u7f6e", nil)
|
||||
return
|
||||
}
|
||||
|
||||
key := loginAttemptKey(c.Request, request.Identifier)
|
||||
if !s.allowLogin(key) {
|
||||
s.writeError(c, http.StatusTooManyRequests, "\u767b\u5f55\u5931\u8d25\u6b21\u6570\u8fc7\u591a\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5", nil)
|
||||
return
|
||||
}
|
||||
account, err := auth.AuthenticateAdmin(
|
||||
request.Identifier,
|
||||
request.Password,
|
||||
cfg.Admin.Username,
|
||||
cfg.Admin.Email,
|
||||
cfg.Admin.PasswordHash,
|
||||
)
|
||||
if err != nil {
|
||||
s.recordLoginFailure(key)
|
||||
s.recordAuthAudit(c, "\u767b\u5f55\u5931\u8d25", "failed", "\u767b\u5f55\u51ed\u636e\u6821\u9a8c\u5931\u8d25")
|
||||
s.writeError(c, http.StatusUnauthorized, "\u8d26\u53f7\u6216\u5bc6\u7801\u9519\u8bef", nil)
|
||||
return
|
||||
}
|
||||
s.clearLoginFailures(key)
|
||||
|
||||
token, err := newAuthToken()
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "\u65e0\u6cd5\u521b\u5efa\u767b\u5f55\u4f1a\u8bdd\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5", err)
|
||||
return
|
||||
}
|
||||
lifetime := authSessionLifetime
|
||||
if request.Remember {
|
||||
lifetime = rememberSessionLife
|
||||
}
|
||||
expiresAt := s.now().Add(lifetime)
|
||||
s.authMu.Lock()
|
||||
s.authSessions[token] = authSession{
|
||||
Username: account.Username,
|
||||
Email: account.Email,
|
||||
Role: account.Role,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
s.authMu.Unlock()
|
||||
s.setAuthCookie(c, token, expiresAt)
|
||||
s.recordAuthAudit(c, "\u767b\u5f55\u6210\u529f", "success", "\u8d85\u7ea7\u7ba1\u7406\u5458\u767b\u5f55\u6210\u529f")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authenticated": true,
|
||||
"account": account.Username,
|
||||
"email": account.Email,
|
||||
"role": account.Role,
|
||||
"is_admin": true,
|
||||
"next_step": "complete",
|
||||
"required_steps": []string{},
|
||||
"expires_at": expiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) authSession(c *gin.Context) {
|
||||
session, ok := s.currentAuthSession(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"authenticated": false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authenticated": true,
|
||||
"account": session.Username,
|
||||
"email": session.Email,
|
||||
"role": session.Role,
|
||||
"is_admin": session.Role == "super_admin" || session.Role == "admin",
|
||||
"next_step": "complete",
|
||||
"required_steps": []string{},
|
||||
"expires_at": session.ExpiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) authLogout(c *gin.Context) {
|
||||
if token, err := c.Cookie(authCookieName); err == nil && token != "" {
|
||||
s.authMu.Lock()
|
||||
delete(s.authSessions, token)
|
||||
s.authMu.Unlock()
|
||||
}
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: authCookieName, Value: "", Path: "/", MaxAge: -1,
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: requestIsHTTPS(c.Request),
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{"authenticated": false, "message": "\u5df2\u9000\u51fa\u767b\u5f55"})
|
||||
}
|
||||
|
||||
func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
|
||||
token, err := c.Cookie(authCookieName)
|
||||
if err != nil || strings.TrimSpace(token) == "" {
|
||||
return authSession{}, false
|
||||
}
|
||||
now := s.now()
|
||||
s.authMu.RLock()
|
||||
session, ok := s.authSessions[token]
|
||||
s.authMu.RUnlock()
|
||||
if !ok {
|
||||
return authSession{}, false
|
||||
}
|
||||
if !session.ExpiresAt.After(now) {
|
||||
s.authMu.Lock()
|
||||
delete(s.authSessions, token)
|
||||
s.authMu.Unlock()
|
||||
return authSession{}, false
|
||||
}
|
||||
return session, true
|
||||
}
|
||||
|
||||
func (s *Server) setAuthCookie(c *gin.Context, token string, expiresAt time.Time) {
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: authCookieName, Value: token, Path: "/",
|
||||
Expires: expiresAt, MaxAge: max(1, int(time.Until(expiresAt).Seconds())),
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: requestIsHTTPS(c.Request),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) allowLogin(key string) bool {
|
||||
now := s.now()
|
||||
s.loginMu.Lock()
|
||||
defer s.loginMu.Unlock()
|
||||
attempt, ok := s.loginAttempts[key]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if !attempt.BlockedTill.IsZero() && attempt.BlockedTill.After(now) {
|
||||
return false
|
||||
}
|
||||
if attempt.WindowStart.IsZero() || now.Sub(attempt.WindowStart) >= loginWindow {
|
||||
delete(s.loginAttempts, key)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) recordLoginFailure(key string) {
|
||||
now := s.now()
|
||||
s.loginMu.Lock()
|
||||
defer s.loginMu.Unlock()
|
||||
attempt := s.loginAttempts[key]
|
||||
if attempt.WindowStart.IsZero() || now.Sub(attempt.WindowStart) >= loginWindow {
|
||||
attempt = loginAttempt{WindowStart: now}
|
||||
}
|
||||
attempt.Failures++
|
||||
if attempt.Failures >= loginFailureLimit {
|
||||
attempt.BlockedTill = now.Add(loginBlockDuration)
|
||||
}
|
||||
s.loginAttempts[key] = attempt
|
||||
}
|
||||
|
||||
func (s *Server) clearLoginFailures(key string) {
|
||||
s.loginMu.Lock()
|
||||
delete(s.loginAttempts, key)
|
||||
s.loginMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) recordAuthAudit(c *gin.Context, action, status, message string) {
|
||||
if s.audit == nil {
|
||||
return
|
||||
}
|
||||
if err := s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: action, ResourceType: "auth", ResourceID: "login", Status: status, Message: message,
|
||||
}); err != nil && s.logger != nil {
|
||||
s.logger.Warn("\u4fdd\u5b58\u767b\u5f55\u5ba1\u8ba1\u65e5\u5fd7\u5931\u8d25", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func loginAttemptKey(request *http.Request, identifier string) string {
|
||||
remote := "unknown"
|
||||
if request != nil {
|
||||
remote = request.RemoteAddr
|
||||
if host, _, err := net.SplitHostPort(remote); err == nil {
|
||||
remote = host
|
||||
}
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(remote + "|" + identifier))
|
||||
}
|
||||
|
||||
func newAuthToken() (string, error) {
|
||||
buffer := make([]byte, 32)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func requestIsHTTPS(request *http.Request) bool {
|
||||
if request == nil {
|
||||
return false
|
||||
}
|
||||
return request.TLS != nil || strings.EqualFold(strings.TrimSpace(request.Header.Get("X-Forwarded-Proto")), "https")
|
||||
}
|
||||
|
||||
func max(left, right int) int {
|
||||
if left > right {
|
||||
return left
|
||||
}
|
||||
return right
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"html/template"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/passwordpolicy"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
type resetPageData struct {
|
||||
CSRFToken string
|
||||
Message string
|
||||
Success bool
|
||||
}
|
||||
|
||||
func (s *Server) currentResetSession() (admin.State, bool) {
|
||||
state, err := admin.ReadState(s.resetStatePath)
|
||||
if err != nil || !state.Active || state.CodeHash == "" || !s.now().UTC().Before(state.ExpiresAt) {
|
||||
return admin.State{}, false
|
||||
}
|
||||
if state.CodeHash == s.resetClosedHash {
|
||||
return admin.State{}, false
|
||||
}
|
||||
return state, true
|
||||
}
|
||||
|
||||
func newCSRFToken() (string, error) {
|
||||
buffer := make([]byte, 32)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func (s *Server) setResetCSRFCookie(c *gin.Context, token string, expiresAt time.Time) {
|
||||
maxAge := int(expiresAt.Sub(s.now().UTC()).Seconds())
|
||||
if maxAge < 1 {
|
||||
maxAge = 1
|
||||
}
|
||||
c.SetSameSite(http.SameSiteStrictMode)
|
||||
c.SetCookie(resetCSRFTokenName, token, maxAge, admin.ResetPath, "", resetCookieSecure(c.Request), true)
|
||||
}
|
||||
|
||||
func resetCookieSecure(request *http.Request) bool {
|
||||
if request == nil {
|
||||
return true
|
||||
}
|
||||
if request.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := request.Host
|
||||
if parsedHost, _, err := net.SplitHostPort(request.Host); err == nil {
|
||||
host = parsedHost
|
||||
}
|
||||
host = strings.Trim(host, "[]")
|
||||
return host != "localhost" && host != "127.0.0.1" && host != "::1"
|
||||
}
|
||||
func (s *Server) resetSubmit(c *gin.Context) {
|
||||
s.resetMu.Lock()
|
||||
defer s.resetMu.Unlock()
|
||||
session, ok := s.currentResetSession()
|
||||
if !ok {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
ip := resetClientIP(c.Request)
|
||||
now := s.now().UTC()
|
||||
if !s.resetLimiter.allowed(ip, now) {
|
||||
s.recordResetAudit(c, "blocked", "密码重置请求超过失败频率限制")
|
||||
c.Status(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
if !sameOrigin(c.Request) {
|
||||
s.resetLimiter.failed(ip, now)
|
||||
s.recordResetAudit(c, "rejected", "密码重置请求来源校验失败")
|
||||
s.writeResetFailure(c, http.StatusForbidden, "请求来源校验失败,请从重置页面重新提交")
|
||||
return
|
||||
}
|
||||
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
|
||||
if err != nil || mediaType != "application/x-www-form-urlencoded" {
|
||||
s.resetLimiter.failed(ip, now)
|
||||
s.recordResetAudit(c, "rejected", "密码重置请求类型无效")
|
||||
s.writeResetFailure(c, http.StatusBadRequest, "请求格式无效,请从重置页面重新提交")
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, resetMaxBodyBytes)
|
||||
if err := c.Request.ParseForm(); err != nil {
|
||||
s.resetLimiter.failed(ip, now)
|
||||
s.recordResetAudit(c, "rejected", "密码重置请求内容无效")
|
||||
s.writeResetFailure(c, http.StatusBadRequest, "请求内容无效,请稍后重试")
|
||||
return
|
||||
}
|
||||
token := c.Request.PostForm.Get("csrf_token")
|
||||
cookie, err := c.Request.Cookie(resetCSRFTokenName)
|
||||
if err != nil || subtle.ConstantTimeCompare([]byte(token), []byte(cookie.Value)) != 1 || token == "" {
|
||||
s.resetLimiter.failed(ip, now)
|
||||
s.recordResetAudit(c, "rejected", "密码重置 CSRF 校验失败")
|
||||
s.writeResetFailure(c, http.StatusForbidden, "安全校验失败,请刷新页面后重试")
|
||||
return
|
||||
}
|
||||
code := c.Request.PostForm.Get("reset_code")
|
||||
verified, err := admin.VerifyCode(s.resetStatePath, code, now)
|
||||
if err != nil || verified.CodeHash != session.CodeHash {
|
||||
s.resetLimiter.failed(ip, now)
|
||||
s.recordResetAudit(c, "failed", "密码重置校验码无效或已失效")
|
||||
s.writeResetFailure(c, http.StatusBadRequest, "重置校验失败,请检查一次性校验码")
|
||||
return
|
||||
}
|
||||
password := c.Request.PostForm.Get("new_password")
|
||||
confirmation := c.Request.PostForm.Get("confirm_password")
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
if password != confirmation {
|
||||
s.recordResetAudit(c, "failed", "密码重置两次输入不一致")
|
||||
s.renderResetPage(c, http.StatusBadRequest, token, "两次输入的新密码不一致")
|
||||
return
|
||||
}
|
||||
if err := passwordpolicy.Validate(password, cfg.Admin.Username); err != nil {
|
||||
s.recordResetAudit(c, "failed", "密码重置新密码不符合安全规则")
|
||||
s.renderResetPage(c, http.StatusBadRequest, token, err.Error())
|
||||
return
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
s.recordResetAudit(c, "error", "生成新密码摘要失败")
|
||||
s.writeResetFailure(c, http.StatusInternalServerError, "暂时无法保存新密码,请稍后重试")
|
||||
return
|
||||
}
|
||||
cfg.Admin.PasswordHash = string(hash)
|
||||
if strings.TrimSpace(s.configPath) == "" {
|
||||
s.recordResetAudit(c, "error", "密码重置配置路径未配置")
|
||||
s.writeResetFailure(c, http.StatusInternalServerError, "服务配置路径未就绪,请联系管理员")
|
||||
return
|
||||
}
|
||||
if err := cfg.Save(s.configPath); err != nil {
|
||||
s.recordResetAudit(c, "error", "保存密码重置配置失败")
|
||||
s.writeResetFailure(c, http.StatusInternalServerError, "暂时无法保存新密码,请稍后重试")
|
||||
return
|
||||
}
|
||||
if err := admin.Consume(s.resetStatePath, verified, now); err != nil {
|
||||
s.resetClosedHash = session.CodeHash
|
||||
s.configMu.Lock()
|
||||
s.config = cfg
|
||||
s.configMu.Unlock()
|
||||
s.recordResetAudit(c, "error", "新密码已保存但重置入口关闭失败")
|
||||
s.clearResetCookie(c)
|
||||
s.renderResetSuccess(c, "密码已更新,但重置入口关闭状态需要由 Scert-admin 停止后完成")
|
||||
return
|
||||
}
|
||||
s.configMu.Lock()
|
||||
s.config = cfg
|
||||
s.configMu.Unlock()
|
||||
s.resetClosedHash = session.CodeHash
|
||||
s.resetLimiter.clear(ip)
|
||||
s.recordResetAudit(c, "success", "超级管理员密码重置成功")
|
||||
s.clearResetCookie(c)
|
||||
s.renderResetSuccess(c, "密码重置成功,请停止 Scert-admin 以结束本次维护窗口")
|
||||
}
|
||||
|
||||
func sameOrigin(request *http.Request) bool {
|
||||
if request == nil || strings.TrimSpace(request.Host) == "" {
|
||||
return false
|
||||
}
|
||||
scheme := "http"
|
||||
if request.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
origin := strings.TrimSpace(request.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
origin = strings.TrimSpace(request.Header.Get("Referer"))
|
||||
}
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Scheme, scheme) {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(parsed.Host, request.Host)
|
||||
}
|
||||
|
||||
func (s *Server) clearResetCookie(c *gin.Context) {
|
||||
c.SetSameSite(http.SameSiteStrictMode)
|
||||
c.SetCookie(resetCSRFTokenName, "", -1, admin.ResetPath, "", resetCookieSecure(c.Request), true)
|
||||
}
|
||||
|
||||
func (s *Server) writeResetFailure(c *gin.Context, status int, message string) {
|
||||
token := ""
|
||||
if cookie, err := c.Request.Cookie(resetCSRFTokenName); err == nil {
|
||||
token = cookie.Value
|
||||
}
|
||||
s.renderResetPage(c, status, token, message)
|
||||
}
|
||||
|
||||
func (s *Server) renderResetPage(c *gin.Context, status int, token, message string) {
|
||||
s.setResetHeaders(c)
|
||||
data := resetPageData{CSRFToken: token, Message: message}
|
||||
c.Status(status)
|
||||
if err := resetTemplate.Execute(c.Writer, data); err != nil && s.logger != nil {
|
||||
s.logger.Error("渲染密码重置页面失败", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) renderResetSuccess(c *gin.Context, message string) {
|
||||
s.setResetHeaders(c)
|
||||
if err := resetSuccessTemplate.Execute(c.Writer, resetPageData{Message: message, Success: true}); err != nil && s.logger != nil {
|
||||
s.logger.Error("渲染密码重置成功页面失败", "error", err)
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s *Server) setResetHeaders(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store, no-cache, must-revalidate")
|
||||
c.Header("Pragma", "no-cache")
|
||||
c.Header("X-Robots-Tag", "noindex, nofollow, noarchive")
|
||||
c.Header("Referrer-Policy", "no-referrer")
|
||||
c.Header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'")
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
}
|
||||
|
||||
func (s *Server) recordResetAudit(c *gin.Context, status, message string) {
|
||||
if s.audit == nil {
|
||||
return
|
||||
}
|
||||
err := s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "admin_password_reset", ResourceType: "super_admin", ResourceID: "super-admin",
|
||||
Status: status, Message: message, CreatedAt: s.now().UTC(),
|
||||
})
|
||||
if err != nil && s.logger != nil {
|
||||
s.logger.Warn("写入密码重置审计日志失败", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
var resetTemplate = template.Must(template.New("reset").Parse(`<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>Scert 超级管理员密码重置</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f7fb;color:#172033;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}.card{width:min(520px,calc(100% - 40px));padding:34px;border:1px solid #dce5f1;border-radius:20px;background:#fff;box-shadow:0 18px 60px rgba(31,50,87,.12)}h1{margin:0 0 14px;font-size:26px}p{margin:8px 0;color:#52637b;line-height:1.7}label{display:block;margin-top:16px;font-weight:700}input{box-sizing:border-box;width:100%;margin-top:8px;padding:12px;border:1px solid #c8d4e3;border-radius:10px;font:inherit}.button{width:100%;margin-top:22px;padding:12px;border:0;border-radius:10px;background:#2167d5;color:#fff;font:inherit;font-weight:700;cursor:pointer}.notice{margin-top:18px;padding:14px 16px;border-radius:12px;background:#edf5ff;color:#285a99;font-weight:700}.error{background:#fff1f0;color:#a12b22}</style></head><body><main class="card"><h1>超级管理员密码重置</h1><p>本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。</p>{{if .Message}}<div class="notice {{if not .Success}}error{{end}}">{{.Message}}</div>{{end}}<form method="post" action="/reset" autocomplete="off"><input type="hidden" name="csrf_token" value="{{.CSRFToken}}"><label for="reset-code">一次性校验码</label><input id="reset-code" name="reset_code" required maxlength="32" autocomplete="one-time-code"><label for="new-password">新密码</label><input id="new-password" name="new_password" required minlength="8" maxlength="128" type="password" autocomplete="new-password"><label for="confirm-password">确认新密码</label><input id="confirm-password" name="confirm_password" required minlength="8" maxlength="128" type="password" autocomplete="new-password"><button class="button" type="submit">确认重置密码</button></form></main></body></html>`))
|
||||
|
||||
var resetSuccessTemplate = template.Must(template.New("reset-success").Parse(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Scert 密码重置完成</title></head><body><main><h1>密码重置完成</h1><p>{{.Message}}</p></main></body></html>`))
|
||||
@@ -0,0 +1,84 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
resetCSRFTokenName = "scert_reset_csrf"
|
||||
resetRateWindow = 15 * time.Minute
|
||||
resetRateLimit = 5
|
||||
resetMaxBodyBytes = 16 << 10
|
||||
)
|
||||
|
||||
type resetRateLimiter struct {
|
||||
mu sync.Mutex
|
||||
failure map[string][]time.Time
|
||||
}
|
||||
|
||||
func newResetRateLimiter() *resetRateLimiter {
|
||||
return &resetRateLimiter{failure: make(map[string][]time.Time)}
|
||||
}
|
||||
|
||||
func (l *resetRateLimiter) allowed(ip string, now time.Time) bool {
|
||||
if l == nil {
|
||||
return true
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.pruneLocked(ip, now)
|
||||
return len(l.failure[ip]) < resetRateLimit
|
||||
}
|
||||
|
||||
func (l *resetRateLimiter) failed(ip string, now time.Time) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.pruneLocked(ip, now)
|
||||
l.failure[ip] = append(l.failure[ip], now)
|
||||
}
|
||||
|
||||
func (l *resetRateLimiter) clear(ip string) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
delete(l.failure, ip)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
func (l *resetRateLimiter) pruneLocked(ip string, now time.Time) {
|
||||
cutoff := now.Add(-resetRateWindow)
|
||||
items := l.failure[ip]
|
||||
keep := items[:0]
|
||||
for _, item := range items {
|
||||
if item.After(cutoff) {
|
||||
keep = append(keep, item)
|
||||
}
|
||||
}
|
||||
if len(keep) == 0 {
|
||||
delete(l.failure, ip)
|
||||
return
|
||||
}
|
||||
l.failure[ip] = keep
|
||||
}
|
||||
|
||||
func resetClientIP(request *http.Request) string {
|
||||
if request == nil {
|
||||
return "unknown"
|
||||
}
|
||||
host, _, err := net.SplitHostPort(strings.TrimSpace(request.RemoteAddr))
|
||||
if err == nil && host != "" {
|
||||
return host
|
||||
}
|
||||
if value := strings.TrimSpace(request.RemoteAddr); value != "" {
|
||||
return value
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
@@ -12,7 +12,9 @@ import (
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/buildinfo"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
@@ -166,3 +168,20 @@ func TestUpdateDomainRejectsInvalidEnvironment(t *testing.T) {
|
||||
t.Fatalf("非法 ACME 环境响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueDomainUsesCertificateWorkflow(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
calledID := ""
|
||||
server := New(Dependencies{
|
||||
Config: cfg, Repository: &stubDomainRepository{},
|
||||
IssueCertificate: func(_ context.Context, id string) (certificate.IssueResult, deployment.Report, error) {
|
||||
calledID = id
|
||||
return certificate.IssueResult{DomainID: id}, deployment.Report{Status: "success"}, nil
|
||||
},
|
||||
})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/issue", nil))
|
||||
if response.Code != http.StatusOK || calledID != "domain-1" || !strings.Contains(response.Body.String(), `"status":"success"`) {
|
||||
t.Fatalf("证书申请接口响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -6,38 +6,61 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/buildinfo"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/logging"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
SetupDNS setupDNSVerifier
|
||||
Firewall firewall.Manager
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
Servers repository.ServerRepository
|
||||
SSHKeys *sshkey.Service
|
||||
SetupDNS setupDNSVerifier
|
||||
Firewall firewall.Manager
|
||||
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
ResetStatePath string
|
||||
Audit repository.AuditRepository
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
configMu sync.RWMutex
|
||||
config config.Config
|
||||
configPath string
|
||||
logger *logging.Logger
|
||||
repository repository.DomainRepository
|
||||
setupDNS setupDNSVerifier
|
||||
firewall firewall.Manager
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
configMu sync.RWMutex
|
||||
config config.Config
|
||||
configPath string
|
||||
logger *logging.Logger
|
||||
repository repository.DomainRepository
|
||||
servers repository.ServerRepository
|
||||
sshKeys *sshkey.Service
|
||||
setupDNS setupDNSVerifier
|
||||
firewall firewall.Manager
|
||||
issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
resetStatePath string
|
||||
audit repository.AuditRepository
|
||||
resetMu sync.Mutex
|
||||
resetClosedHash string
|
||||
resetLimiter *resetRateLimiter
|
||||
authSessions map[string]authSession
|
||||
authMu sync.RWMutex
|
||||
loginAttempts map[string]loginAttempt
|
||||
loginMu sync.Mutex
|
||||
now func() time.Time
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
}
|
||||
|
||||
func New(deps Dependencies) *Server {
|
||||
@@ -47,6 +70,15 @@ func New(deps Dependencies) *Server {
|
||||
server := &Server{
|
||||
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger,
|
||||
repository: deps.Repository, setupDNS: deps.SetupDNS, firewall: deps.Firewall, router: router,
|
||||
servers: deps.Servers,
|
||||
sshKeys: deps.SSHKeys,
|
||||
issueCertificate: deps.IssueCertificate,
|
||||
resetStatePath: deps.ResetStatePath,
|
||||
audit: deps.Audit,
|
||||
resetLimiter: newResetRateLimiter(),
|
||||
authSessions: make(map[string]authSession),
|
||||
loginAttempts: make(map[string]loginAttempt),
|
||||
now: time.Now,
|
||||
}
|
||||
server.registerRoutes()
|
||||
server.registerSetupRoutes()
|
||||
@@ -56,11 +88,27 @@ func New(deps Dependencies) *Server {
|
||||
func (s *Server) registerRoutes() {
|
||||
// 主路由保持独立,初始化路由由专用模块注册。
|
||||
s.router.GET("/healthz", s.health)
|
||||
s.router.GET(admin.ResetPath, s.resetPage)
|
||||
s.router.POST(admin.ResetPath, s.resetSubmit)
|
||||
s.router.GET("/api/v1/status", s.status)
|
||||
s.router.GET("/api/v1/auth/session", s.authSession)
|
||||
s.router.POST("/api/v1/auth/login", s.authLogin)
|
||||
s.router.POST("/api/v1/auth/logout", s.authLogout)
|
||||
s.router.GET("/api/v1/domains", s.listDomains)
|
||||
s.router.POST("/api/v1/domains", s.createDomain)
|
||||
s.router.PUT("/api/v1/domains/:id", s.updateDomain)
|
||||
s.router.DELETE("/api/v1/domains/:id", s.deleteDomain)
|
||||
s.router.POST("/api/v1/domains/:id/issue", s.issueDomain)
|
||||
s.router.GET("/api/v1/domains/:id/servers", s.listDomainServers)
|
||||
s.router.PUT("/api/v1/domains/:id/servers", s.replaceDomainServers)
|
||||
s.router.GET("/api/v1/servers", s.listServers)
|
||||
s.router.POST("/api/v1/servers", s.createServer)
|
||||
s.router.GET("/api/v1/servers/:id", s.getServer)
|
||||
s.router.PUT("/api/v1/servers/:id", s.updateServer)
|
||||
s.router.DELETE("/api/v1/servers/:id", s.deleteServer)
|
||||
s.router.GET("/api/v1/ssh-keys", s.listSSHKeys)
|
||||
s.router.POST("/api/v1/ssh-keys", s.createSSHKey)
|
||||
s.router.DELETE("/api/v1/ssh-keys/:id", s.deleteSSHKey)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
@@ -105,10 +153,45 @@ type domainRequest struct {
|
||||
DNSProvider string `json:"dns_provider"`
|
||||
}
|
||||
|
||||
type serverRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Address string `json:"address" binding:"required"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
PrivateKeyRef string `json:"private_key_ref" binding:"required"`
|
||||
HostKeyFingerprint string `json:"host_key_fingerprint" binding:"required"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
CertificateChainPath string `json:"certificate_chain_path"`
|
||||
WebServer string `json:"web_server" binding:"required"`
|
||||
ReloadCommand []string `json:"reload_command"`
|
||||
}
|
||||
|
||||
type domainServersRequest struct {
|
||||
ServerIDs []string `json:"server_ids"`
|
||||
}
|
||||
|
||||
func (s *Server) health(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "service": "scert"})
|
||||
}
|
||||
|
||||
func (s *Server) resetPage(c *gin.Context) {
|
||||
s.resetMu.Lock()
|
||||
defer s.resetMu.Unlock()
|
||||
session, ok := s.currentResetSession()
|
||||
if !ok {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
token, err := newCSRFToken()
|
||||
if err != nil {
|
||||
s.writeResetFailure(c, http.StatusInternalServerError, "暂时无法生成安全校验信息,请稍后重试")
|
||||
return
|
||||
}
|
||||
s.setResetCSRFCookie(c, token, session.ExpiresAt)
|
||||
s.renderResetPage(c, http.StatusOK, token, "")
|
||||
}
|
||||
|
||||
func (s *Server) status(c *gin.Context) {
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
@@ -120,6 +203,7 @@ func (s *Server) status(c *gin.Context) {
|
||||
"setup_ready": cfg.SetupReady,
|
||||
"https_mode": cfg.Server.HTTPSMode,
|
||||
"database_driver": cfg.Database.Driver,
|
||||
"reset_url": cfg.ResetURL(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -217,6 +301,204 @@ func (s *Server) deleteDomain(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) issueDomain(c *gin.Context) {
|
||||
if s.issueCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书申请接口尚未配置", errors.New("证书申请工作流未配置"))
|
||||
return
|
||||
}
|
||||
certificateResult, deploymentReport, err := s.issueCertificate(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadGateway, "证书申请或部署失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"certificate": certificateResult, "deployment": deploymentReport})
|
||||
}
|
||||
|
||||
func (s *Server) listServers(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
items, err := s.servers.ListServers(c.Request.Context())
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (s *Server) getServer(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
item, err := s.servers.GetServerByID(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "服务器不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, item)
|
||||
}
|
||||
|
||||
func (s *Server) createServer(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
var request serverRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "请求参数无效", err)
|
||||
return
|
||||
}
|
||||
item := serverFromRequest(request)
|
||||
item = item.Normalize()
|
||||
if err := s.validateSSHKeyReference(c.Request.Context(), item.PrivateKeyRef); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "SSH 私钥引用无效", err)
|
||||
return
|
||||
}
|
||||
if err := s.servers.CreateServer(c.Request.Context(), item); err != nil {
|
||||
s.writeError(c, serverErrorStatus(err), "保存服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, item)
|
||||
}
|
||||
|
||||
func (s *Server) updateServer(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
var request serverRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "请求参数无效", err)
|
||||
return
|
||||
}
|
||||
item := serverFromRequest(request)
|
||||
item.ID = c.Param("id")
|
||||
item = item.Normalize()
|
||||
existing, err := s.servers.GetServerByID(c.Request.Context(), item.ID)
|
||||
if err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "服务器不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取服务器失败", err)
|
||||
return
|
||||
}
|
||||
item.CreatedAt = existing.CreatedAt
|
||||
if err := s.validateSSHKeyReference(c.Request.Context(), item.PrivateKeyRef); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "SSH 私钥引用无效", err)
|
||||
return
|
||||
}
|
||||
if err := s.servers.UpdateServer(c.Request.Context(), item); err != nil {
|
||||
s.writeError(c, serverErrorStatus(err), "更新服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, item)
|
||||
}
|
||||
|
||||
func (s *Server) validateSSHKeyReference(ctx context.Context, reference string) error {
|
||||
if s.sshKeys == nil {
|
||||
return errors.New("SSH 私钥管理服务未配置")
|
||||
}
|
||||
_, err := s.sshKeys.ValidateReference(ctx, reference)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) deleteServer(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
if err := s.servers.DeleteServer(c.Request.Context(), c.Param("id")); err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "服务器不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "删除服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) listDomainServers(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
if _, err := s.repository.GetByID(c.Request.Context(), c.Param("id")); err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "域名不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取域名失败", err)
|
||||
return
|
||||
}
|
||||
items, err := s.servers.ListServersByDomainID(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询域名部署服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (s *Server) replaceDomainServers(c *gin.Context) {
|
||||
if s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "服务器管理接口尚未配置", errors.New("服务器仓储未配置"))
|
||||
return
|
||||
}
|
||||
if _, err := s.repository.GetByID(c.Request.Context(), c.Param("id")); err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "域名不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取域名失败", err)
|
||||
return
|
||||
}
|
||||
var request domainServersRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "请求参数无效", err)
|
||||
return
|
||||
}
|
||||
if err := s.servers.ReplaceDomainServers(c.Request.Context(), c.Param("id"), request.ServerIDs); err != nil {
|
||||
s.writeError(c, serverErrorStatus(err), "保存域名部署服务器失败", err)
|
||||
return
|
||||
}
|
||||
items, err := s.servers.ListServersByDomainID(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "读取域名部署服务器失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func serverFromRequest(request serverRequest) deployment.Server {
|
||||
return deployment.Server{
|
||||
ID: domain.NewID(), Name: request.Name, Address: request.Address, Port: request.Port,
|
||||
Username: request.Username, PrivateKeyRef: request.PrivateKeyRef, HostKeyFingerprint: request.HostKeyFingerprint,
|
||||
CertificatePath: request.CertificatePath, PrivateKeyPath: request.PrivateKeyPath,
|
||||
CertificateChainPath: request.CertificateChainPath, WebServer: deployment.WebServer(request.WebServer),
|
||||
ReloadCommand: request.ReloadCommand,
|
||||
}
|
||||
}
|
||||
|
||||
func serverErrorStatus(err error) int {
|
||||
if repository.IsConflict(err) {
|
||||
return http.StatusConflict
|
||||
}
|
||||
if repository.IsNotFound(err) {
|
||||
return http.StatusNotFound
|
||||
}
|
||||
if strings.Contains(err.Error(), "不存在") || strings.Contains(err.Error(), "不能为空") || strings.Contains(err.Error(), "无效") {
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
func (s *Server) writeError(c *gin.Context, status int, message string, err error) {
|
||||
if s.logger != nil {
|
||||
s.logger.Error(message, "error", err)
|
||||
|
||||
@@ -2,16 +2,26 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/logging"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
|
||||
)
|
||||
|
||||
func TestHealthAndDomainAPI(t *testing.T) {
|
||||
@@ -53,3 +63,411 @@ func TestHealthAndDomainAPI(t *testing.T) {
|
||||
t.Fatalf("域名列表响应错误:%d %s", list.Code, list.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPathRequiresScertAdminActivation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Server.Port = 8443
|
||||
statePath := admin.StatePath(cfg.Paths.Data)
|
||||
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}, ResetStatePath: statePath})
|
||||
|
||||
inactive := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(inactive, httptest.NewRequest(http.MethodGet, "/reset", nil))
|
||||
if inactive.Code != http.StatusNotFound {
|
||||
t.Fatalf("Scert-admin 未启动时 /reset 应返回 404:%d", inactive.Code)
|
||||
}
|
||||
|
||||
controller := admin.New(cfg)
|
||||
if _, err := controller.Start(); err != nil {
|
||||
t.Fatalf("启用测试密码重置入口失败:%v", err)
|
||||
}
|
||||
active := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(active, httptest.NewRequest(http.MethodGet, "/reset", nil))
|
||||
if active.Code != http.StatusOK || !strings.Contains(active.Body.String(), "超级管理员密码重置") {
|
||||
t.Fatalf("Scert-admin 启用后 /reset 页面错误:%d %s", active.Code, active.Body.String())
|
||||
}
|
||||
if active.Header().Get("Cache-Control") != "no-store, no-cache, must-revalidate" || !strings.Contains(active.Header().Get("X-Robots-Tag"), "noindex") {
|
||||
t.Fatalf("密码重置页面缺少安全响应头:%v", active.Header())
|
||||
}
|
||||
if err := controller.Stop(); err != nil {
|
||||
t.Fatalf("关闭测试密码重置入口失败:%v", err)
|
||||
}
|
||||
stopped := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(stopped, httptest.NewRequest(http.MethodGet, "/reset", nil))
|
||||
if stopped.Code != http.StatusNotFound {
|
||||
t.Fatalf("Scert-admin 停止后 /reset 应恢复 404:%d", stopped.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
oldHash, err := bcrypt.GenerateFromPassword([]byte("OldPassword123"), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成旧密码摘要失败:%v", err)
|
||||
}
|
||||
cfg.Admin.PasswordHash = string(oldHash)
|
||||
configPath := filepath.Join(dir, "config", "scert.json")
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
controller := admin.New(cfg)
|
||||
session, err := controller.Start()
|
||||
if err != nil {
|
||||
t.Fatalf("启动测试重置会话失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{}, ResetStatePath: admin.StatePath(cfg.Paths.Data)})
|
||||
get := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "http://scert.example.test/reset", nil))
|
||||
if get.Code != http.StatusOK {
|
||||
t.Fatalf("获取密码重置页面失败:%d", get.Code)
|
||||
}
|
||||
cookie := get.Result().Cookies()[0]
|
||||
form := url.Values{
|
||||
"csrf_token": {cookie.Value},
|
||||
"reset_code": {session.Code},
|
||||
"new_password": {"NewPassword123"},
|
||||
"confirm_password": {"NewPassword123"},
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "http://scert.example.test")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "密码重置成功") {
|
||||
t.Fatalf("密码重置响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
state, err := admin.ReadState(admin.StatePath(cfg.Paths.Data))
|
||||
if err != nil {
|
||||
t.Fatalf("读取重置状态失败:%v", err)
|
||||
}
|
||||
if state.Active || state.CodeHash != "" {
|
||||
t.Fatalf("密码重置成功后会话必须失效:%+v", state)
|
||||
}
|
||||
loaded, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取重置后的配置失败:%v", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil {
|
||||
t.Fatal("新密码摘要无法验证新密码")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("OldPassword123")) == nil {
|
||||
t.Fatal("旧密码不应继续有效")
|
||||
}
|
||||
second := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(second, httptest.NewRequest(http.MethodGet, "http://scert.example.test/reset", nil))
|
||||
if second.Code != http.StatusNotFound {
|
||||
t.Fatalf("密码重置成功后入口必须关闭:%d", second.Code)
|
||||
}
|
||||
if err := controller.Refresh(); err != admin.ErrResetSessionClosed {
|
||||
t.Fatalf("Scert-admin 不得刷新已消费会话:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetRejectsCrossSiteAndLimitsFailures(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = "not-used-in-this-test"
|
||||
controller := admin.New(cfg)
|
||||
session, err := controller.Start()
|
||||
if err != nil {
|
||||
t.Fatalf("启动测试重置会话失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: filepath.Join(dir, "config", "scert.json"), Repository: &stubDomainRepository{}, ResetStatePath: admin.StatePath(cfg.Paths.Data)})
|
||||
get := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "http://scert.example.test/reset", nil))
|
||||
cookie := get.Result().Cookies()[0]
|
||||
base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPassword123"}, "confirm_password": {"NewPassword123"}}
|
||||
for i := 0; i < 5; i++ {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(base.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "http://evil.example.test")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("跨站请求应被拒绝:第 %d 次状态码为 %d", i+1, response.Code)
|
||||
}
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(base.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "http://scert.example.test")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("超过失败次数后应限流:%d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerAndDomainAssociationAPI(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.Database.DSN = filepath.Join(dir, "data", "servers.db")
|
||||
db, err := database.Open(context.Background(), cfg.Database)
|
||||
if err != nil {
|
||||
t.Fatalf("打开数据库失败:%v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatalf("数据库迁移失败:%v", err)
|
||||
}
|
||||
secretStore, err := secretstore.Open(filepath.Join(dir, "config"))
|
||||
if err != nil {
|
||||
t.Fatalf("打开敏感信息存储失败:%v", err)
|
||||
}
|
||||
sshKeys := sshkey.NewService(secretStore)
|
||||
key, err := sshKeys.Create(t.Context(), "测试部署私钥", testSSHPrivateKey(t), "")
|
||||
if err != nil {
|
||||
t.Fatalf("创建测试 SSH 私钥失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{
|
||||
Config: cfg, Repository: repository.NewSQLDomainRepository(db.DB),
|
||||
Servers: repository.NewSQLServerRepository(db.DB), SSHKeys: sshKeys,
|
||||
})
|
||||
|
||||
domainRequest := httptest.NewRequest(http.MethodPost, "/api/v1/domains", strings.NewReader(`{"name":"example.com","certificate_type":"single"}`))
|
||||
domainRequest.Header.Set("Content-Type", "application/json")
|
||||
domainResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(domainResponse, domainRequest)
|
||||
if domainResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("创建测试域名失败:%d %s", domainResponse.Code, domainResponse.Body.String())
|
||||
}
|
||||
var item struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(domainResponse.Body.Bytes(), &item); err != nil || item.ID == "" {
|
||||
t.Fatalf("测试域名响应无效:%v %s", err, domainResponse.Body.String())
|
||||
}
|
||||
|
||||
serverRequest := httptest.NewRequest(http.MethodPost, "/api/v1/servers", strings.NewReader(`{"name":"测试服务器","address":"192.0.2.50","port":22,"username":"deploy","private_key_ref":"`+key.Reference+`","host_key_fingerprint":"SHA256:test","web_server":"nginx"}`))
|
||||
serverRequest.Header.Set("Content-Type", "application/json")
|
||||
serverResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(serverResponse, serverRequest)
|
||||
if serverResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("创建测试服务器失败:%d %s", serverResponse.Code, serverResponse.Body.String())
|
||||
}
|
||||
var created deployment.Server
|
||||
if err := json.Unmarshal(serverResponse.Body.Bytes(), &created); err != nil || created.ID == "" || len(created.ReloadCommand) != 3 {
|
||||
t.Fatalf("测试服务器响应无效:%v %+v", err, created)
|
||||
}
|
||||
if created.CertificatePath != deployment.DefaultCertificatePath || created.CertificateChainPath != deployment.DefaultCertificateChainPath || created.PrivateKeyPath != deployment.DefaultPrivateKeyPath {
|
||||
t.Fatalf("服务器 API 未使用默认远程证书路径模板:%+v", created)
|
||||
}
|
||||
|
||||
associationRequest := httptest.NewRequest(http.MethodPut, "/api/v1/domains/"+item.ID+"/servers", strings.NewReader(`{"server_ids":["`+created.ID+`"]}`))
|
||||
associationRequest.Header.Set("Content-Type", "application/json")
|
||||
associationResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(associationResponse, associationRequest)
|
||||
if associationResponse.Code != http.StatusOK || !strings.Contains(associationResponse.Body.String(), created.ID) {
|
||||
t.Fatalf("保存域名服务器关联失败:%d %s", associationResponse.Code, associationResponse.Body.String())
|
||||
}
|
||||
|
||||
deleteResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(deleteResponse, httptest.NewRequest(http.MethodDelete, "/api/v1/servers/"+created.ID, nil))
|
||||
if deleteResponse.Code != http.StatusNoContent {
|
||||
t.Fatalf("删除测试服务器失败:%d %s", deleteResponse.Code, deleteResponse.Body.String())
|
||||
}
|
||||
listResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(listResponse, httptest.NewRequest(http.MethodGet, "/api/v1/domains/"+item.ID+"/servers", nil))
|
||||
if listResponse.Code != http.StatusOK || strings.Contains(listResponse.Body.String(), created.ID) {
|
||||
t.Fatalf("服务器删除后域名关联未清理:%d %s", listResponse.Code, listResponse.Body.String())
|
||||
}
|
||||
}
|
||||
func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
blockedPath := filepath.Join(t.TempDir(), "config-target")
|
||||
if err := os.MkdirAll(blockedPath, 0o700); err != nil {
|
||||
t.Fatalf("创建无效配置目标失败:%v", err)
|
||||
}
|
||||
fixture.server.configPath = blockedPath
|
||||
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "https://scert.example.test")
|
||||
request.AddCookie(fixture.cookie)
|
||||
response := httptest.NewRecorder()
|
||||
fixture.server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("配置保存失败时应返回 500:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
state, err := admin.ReadState(admin.StatePath(fixture.cfg.Paths.Data))
|
||||
if err != nil {
|
||||
t.Fatalf("读取配置保存失败后的重置状态失败:%v", err)
|
||||
}
|
||||
if !state.Active || state.CodeHash != fixture.session.State.CodeHash {
|
||||
t.Fatalf("配置保存失败时不得消费重置会话:%+v", state)
|
||||
}
|
||||
fixture.server.configMu.RLock()
|
||||
passwordHash := fixture.server.config.Admin.PasswordHash
|
||||
fixture.server.configMu.RUnlock()
|
||||
if passwordHash != fixture.oldPasswordHash {
|
||||
t.Fatal("配置保存失败时不得更新内存中的密码摘要")
|
||||
}
|
||||
active := httptest.NewRecorder()
|
||||
fixture.server.Handler().ServeHTTP(active, httptest.NewRequest(http.MethodGet, "https://scert.example.test/reset", nil))
|
||||
if active.Code != http.StatusOK {
|
||||
t.Fatalf("配置保存失败后 /reset 应继续可访问:%d", active.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetRejectsOversizedRequestBody(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form.Set("padding", strings.Repeat("x", resetMaxBodyBytes))
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "https://scert.example.test")
|
||||
request.AddCookie(fixture.cookie)
|
||||
response := httptest.NewRecorder()
|
||||
fixture.server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("超过请求体限制时应返回 400:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
state, err := admin.ReadState(admin.StatePath(fixture.cfg.Paths.Data))
|
||||
if err != nil {
|
||||
t.Fatalf("读取超限请求后的重置状态失败:%v", err)
|
||||
}
|
||||
if !state.Active {
|
||||
t.Fatal("请求体超限时不得消费重置会话")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetCSRFCookieHasRestrictedAttributes(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
cookie := fixture.cookie
|
||||
if !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode {
|
||||
t.Fatalf("CSRF Cookie 安全属性不完整:%+v", cookie)
|
||||
}
|
||||
if cookie.Path != admin.ResetPath {
|
||||
t.Fatalf("CSRF Cookie 路径错误:%q", cookie.Path)
|
||||
}
|
||||
if cookie.MaxAge <= 0 || cookie.MaxAge > 90 {
|
||||
t.Fatalf("CSRF Cookie 有效期必须限制在重置租约内:%d", cookie.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
start := make(chan struct{})
|
||||
responses := make(chan int, 2)
|
||||
var waitGroup sync.WaitGroup
|
||||
for i := 0; i < 2; i++ {
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
<-start
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "https://scert.example.test")
|
||||
request.AddCookie(fixture.cookie)
|
||||
response := httptest.NewRecorder()
|
||||
fixture.server.Handler().ServeHTTP(response, request)
|
||||
responses <- response.Code
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
close(responses)
|
||||
|
||||
successes := 0
|
||||
failures := 0
|
||||
for status := range responses {
|
||||
if status == http.StatusOK {
|
||||
successes++
|
||||
} else {
|
||||
failures++
|
||||
}
|
||||
}
|
||||
if successes != 1 || failures != 1 {
|
||||
t.Fatalf("并发提交必须恰好一个成功、一个失败:successes=%d failures=%d", successes, failures)
|
||||
}
|
||||
state, err := admin.ReadState(admin.StatePath(fixture.cfg.Paths.Data))
|
||||
if err != nil {
|
||||
t.Fatalf("读取并发提交后的重置状态失败:%v", err)
|
||||
}
|
||||
if state.Active || state.CodeHash != "" {
|
||||
t.Fatalf("并发提交成功后重置会话必须关闭:%+v", state)
|
||||
}
|
||||
loaded, err := config.Load(fixture.configPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取并发提交后的配置失败:%v", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil {
|
||||
t.Fatal("并发提交后的密码摘要无法验证新密码")
|
||||
}
|
||||
}
|
||||
|
||||
type resetTestFixture struct {
|
||||
server *Server
|
||||
cfg config.Config
|
||||
controller *admin.Controller
|
||||
session admin.Session
|
||||
cookie *http.Cookie
|
||||
configPath string
|
||||
oldPasswordHash string
|
||||
}
|
||||
|
||||
func newResetTestFixture(t *testing.T) resetTestFixture {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
oldPasswordHash, err := bcrypt.GenerateFromPassword([]byte("OldPassword123"), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
cfg.Admin.PasswordHash = string(oldPasswordHash)
|
||||
configPath := filepath.Join(dir, "config", "scert.json")
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
controller := admin.New(cfg)
|
||||
session, err := controller.Start()
|
||||
if err != nil {
|
||||
t.Fatalf("启动测试重置会话失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{}, ResetStatePath: admin.StatePath(cfg.Paths.Data)})
|
||||
get := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "https://scert.example.test/reset", nil))
|
||||
if get.Code != http.StatusOK {
|
||||
t.Fatalf("获取测试重置页面失败:%d", get.Code)
|
||||
}
|
||||
cookies := get.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("测试重置页面应返回一个 CSRF Cookie:%d", len(cookies))
|
||||
}
|
||||
return resetTestFixture{
|
||||
server: server, cfg: cfg, controller: controller, session: session,
|
||||
cookie: cookies[0], configPath: configPath, oldPasswordHash: cfg.Admin.PasswordHash,
|
||||
}
|
||||
}
|
||||
|
||||
func resetForm(code, csrfToken, password string) url.Values {
|
||||
return url.Values{
|
||||
"csrf_token": {csrfToken},
|
||||
"reset_code": {code},
|
||||
"new_password": {password},
|
||||
"confirm_password": {password},
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,9 @@ type setupDNSVerifier interface {
|
||||
|
||||
type setupRequest struct {
|
||||
AdminUsername string `json:"admin_username"`
|
||||
AdminEmail string `json:"admin_email"`
|
||||
AdminPassword string `json:"admin_password"`
|
||||
ServerPort int `json:"server_port"`
|
||||
ResetServicePort int `json:"reset_service_port"`
|
||||
EmailProvider string `json:"email_provider"`
|
||||
EmailEndpoint string `json:"email_endpoint"`
|
||||
Recipients []string `json:"recipients"`
|
||||
@@ -78,7 +78,7 @@ func (s *Server) setupStatus(c *gin.Context) {
|
||||
"phase": phase,
|
||||
"blockers": blockers,
|
||||
"server_port": cfg.Server.Port,
|
||||
"reset_service_port": cfg.Admin.ResetServicePort,
|
||||
"reset_url": cfg.ResetURL(),
|
||||
"https_mode": cfg.Server.HTTPSMode,
|
||||
"web_enabled": cfg.Web.Enabled,
|
||||
"web_hostname": cfg.Web.Hostname,
|
||||
@@ -172,9 +172,9 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
updated := s.config
|
||||
err := setup.Apply(&updated, setup.Input{
|
||||
AdminUsername: request.AdminUsername,
|
||||
AdminEmail: request.AdminEmail,
|
||||
AdminPassword: request.AdminPassword,
|
||||
ServerPort: request.ServerPort,
|
||||
ResetServicePort: request.ResetServicePort,
|
||||
EmailProvider: request.EmailProvider,
|
||||
EmailEndpoint: request.EmailEndpoint,
|
||||
EmailRecipients: request.Recipients,
|
||||
@@ -231,15 +231,15 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"initialized": true,
|
||||
"message": fmt.Sprintf(
|
||||
"初始化配置已保存,DNS API 已完成在线验证且凭据已加密保存。%s。请确认云安全组已放行主服务端口 %d;Scert-admin 仅允许本机访问。证书申请和 HTTPS 切换将在后续任务中完成。",
|
||||
firewallResult.Message, updated.Server.Port,
|
||||
"初始化配置已保存,DNS API 已完成在线验证且凭据已加密保存。%s。请确认云安全组已放行主服务端口 %d;Scert-admin 默认关闭,启动后通过 %s 使用临时重置入口。证书申请和 HTTPS 切换将在后续任务中完成。",
|
||||
firewallResult.Message, updated.Server.Port, updated.ResetURL(),
|
||||
),
|
||||
"status": gin.H{
|
||||
"server_port": updated.Server.Port,
|
||||
"reset_service_port": updated.Admin.ResetServicePort,
|
||||
"web_enabled": updated.Web.Enabled,
|
||||
"https_mode": updated.Server.HTTPSMode,
|
||||
"firewall": firewallResult,
|
||||
"server_port": updated.Server.Port,
|
||||
"reset_url": updated.ResetURL(),
|
||||
"web_enabled": updated.Web.Enabled,
|
||||
"https_mode": updated.Server.HTTPSMode,
|
||||
"firewall": firewallResult,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -149,9 +149,9 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
})
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"server_port":8443,
|
||||
"reset_service_port":8091,
|
||||
"email_provider":"mail-api",
|
||||
"email_endpoint":"https://mail.example.test/send",
|
||||
"recipients":["ops@example.test","ops@example.test"],
|
||||
@@ -181,6 +181,9 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
if !strings.Contains(response.Body.String(), `"firewall"`) || !strings.Contains(response.Body.String(), `"created":true`) {
|
||||
t.Fatalf("初始化响应应返回本机防火墙结果:%s", response.Body.String())
|
||||
}
|
||||
if !strings.Contains(response.Body.String(), `"reset_url":"https://scert.example.test/reset"`) {
|
||||
t.Fatalf("初始化响应应返回根据 Web 地址生成的密码重置路径:%s", response.Body.String())
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
@@ -193,7 +196,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
t.Fatalf("解析保存后的配置失败:%v", err)
|
||||
}
|
||||
if !saved.SetupReady || saved.Admin.Username != "root-admin" || saved.Server.Port != 8443 {
|
||||
if !saved.SetupReady || saved.Admin.Username != "root-admin" || saved.Admin.Email != "admin@example.test" || saved.Server.Port != 8443 {
|
||||
t.Fatalf("保存后的初始化配置不正确:%+v", saved)
|
||||
}
|
||||
if len(saved.Notification.Recipients) != 1 {
|
||||
@@ -385,9 +388,9 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) {
|
||||
func setupPayload(baseDir, password string) string {
|
||||
return `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"` + password + `",
|
||||
"server_port":8443,
|
||||
"reset_service_port":8091,
|
||||
"dns_provider":"cloudflare",
|
||||
"dns_credential_ref":"secret://dns/cloudflare/test",
|
||||
"dns_verification_token":"verified-token",
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const maxSSHKeyRequestBytes = 2 * 1024 * 1024
|
||||
|
||||
type sshKeyRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
PrivateKey string `json:"private_key" binding:"required"`
|
||||
Passphrase string `json:"passphrase"`
|
||||
}
|
||||
|
||||
func (s *Server) listSSHKeys(c *gin.Context) {
|
||||
if s.sshKeys == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "SSH 私钥管理接口尚未配置", errors.New("SSH 私钥管理服务未配置"))
|
||||
return
|
||||
}
|
||||
items, err := s.sshKeys.List(c.Request.Context())
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询 SSH 私钥失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (s *Server) createSSHKey(c *gin.Context) {
|
||||
if s.sshKeys == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "SSH 私钥管理接口尚未配置", errors.New("SSH 私钥管理服务未配置"))
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxSSHKeyRequestBytes)
|
||||
var request sshKeyRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
s.writeError(c, http.StatusRequestEntityTooLarge, "SSH 私钥请求内容过大", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusBadRequest, "请求参数无效", err)
|
||||
return
|
||||
}
|
||||
item, err := s.sshKeys.Create(c.Request.Context(), request.Name, request.PrivateKey, request.Passphrase)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "SSH 私钥无效", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, item)
|
||||
}
|
||||
|
||||
func (s *Server) deleteSSHKey(c *gin.Context) {
|
||||
if s.sshKeys == nil || s.servers == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "SSH 私钥管理接口尚未配置", errors.New("SSH 私钥或服务器管理服务未配置"))
|
||||
return
|
||||
}
|
||||
reference, err := s.sshKeys.Reference(c.Param("id"))
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "SSH 私钥 ID 无效", err)
|
||||
return
|
||||
}
|
||||
used, err := s.servers.IsPrivateKeyRefUsed(c.Request.Context(), reference)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "检查 SSH 私钥占用状态失败", err)
|
||||
return
|
||||
}
|
||||
if used {
|
||||
s.writeError(c, http.StatusConflict, "SSH 私钥仍被部署服务器使用", errors.New("SSH 私钥引用正在使用"))
|
||||
return
|
||||
}
|
||||
if err := s.sshKeys.Delete(c.Request.Context(), c.Param("id")); err != nil {
|
||||
s.writeError(c, http.StatusNotFound, "SSH 私钥不存在", err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
|
||||
)
|
||||
|
||||
func TestSSHKeyAPIHidesPrivateKeyAndBlocksDeletingUsedReference(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
cfg := config.Default(directory)
|
||||
cfg.Database.DSN = filepath.Join(directory, "data", "ssh-keys.db")
|
||||
db, err := database.Open(context.Background(), cfg.Database)
|
||||
if err != nil {
|
||||
t.Fatalf("打开数据库失败:%v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatalf("数据库迁移失败:%v", err)
|
||||
}
|
||||
store, err := secretstore.Open(filepath.Join(directory, "config"))
|
||||
if err != nil {
|
||||
t.Fatalf("打开敏感信息存储失败:%v", err)
|
||||
}
|
||||
serverRepo := repository.NewSQLServerRepository(db.DB)
|
||||
server := New(Dependencies{
|
||||
Config: cfg, Repository: repository.NewSQLDomainRepository(db.DB), Servers: serverRepo,
|
||||
SSHKeys: sshkey.NewService(store),
|
||||
})
|
||||
|
||||
privateKey := testSSHPrivateKey(t)
|
||||
createBody, err := json.Marshal(sshKeyRequest{Name: "生产私钥", PrivateKey: privateKey})
|
||||
if err != nil {
|
||||
t.Fatalf("编码 SSH 私钥请求失败:%v", err)
|
||||
}
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ssh-keys", strings.NewReader(string(createBody)))
|
||||
createRequest.Header.Set("Content-Type", "application/json")
|
||||
createResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(createResponse, createRequest)
|
||||
if createResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("创建 SSH 私钥失败:%d %s", createResponse.Code, createResponse.Body.String())
|
||||
}
|
||||
if strings.Contains(createResponse.Body.String(), "PRIVATE KEY") || strings.Contains(createResponse.Body.String(), "private_key") {
|
||||
t.Fatalf("SSH 私钥创建响应泄露了敏感内容:%s", createResponse.Body.String())
|
||||
}
|
||||
var key sshkey.Metadata
|
||||
if err := json.Unmarshal(createResponse.Body.Bytes(), &key); err != nil || key.ID == "" || key.Reference == "" {
|
||||
t.Fatalf("SSH 私钥创建响应无效:%v %+v", err, key)
|
||||
}
|
||||
|
||||
listResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(listResponse, httptest.NewRequest(http.MethodGet, "/api/v1/ssh-keys", nil))
|
||||
if listResponse.Code != http.StatusOK || !strings.Contains(listResponse.Body.String(), key.Reference) || strings.Contains(listResponse.Body.String(), "PRIVATE KEY") {
|
||||
t.Fatalf("SSH 私钥列表响应无效或泄露敏感内容:%d %s", listResponse.Code, listResponse.Body.String())
|
||||
}
|
||||
|
||||
serverBody := `{"name":"生产服务器","address":"192.0.2.60","port":22,"username":"deploy","private_key_ref":"` + key.Reference + `","host_key_fingerprint":"SHA256:test","certificate_path":"/etc/scert/cert.pem","private_key_path":"/etc/scert/key.pem","certificate_chain_path":"/etc/scert/fullchain.pem","web_server":"nginx"}`
|
||||
serverRequest := httptest.NewRequest(http.MethodPost, "/api/v1/servers", strings.NewReader(serverBody))
|
||||
serverRequest.Header.Set("Content-Type", "application/json")
|
||||
serverResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(serverResponse, serverRequest)
|
||||
if serverResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("创建使用 SSH 私钥的服务器失败:%d %s", serverResponse.Code, serverResponse.Body.String())
|
||||
}
|
||||
var createdServer struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(serverResponse.Body.Bytes(), &createdServer); err != nil || createdServer.ID == "" {
|
||||
t.Fatalf("服务器创建响应无效:%v %s", err, serverResponse.Body.String())
|
||||
}
|
||||
|
||||
deleteUsedResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(deleteUsedResponse, httptest.NewRequest(http.MethodDelete, "/api/v1/ssh-keys/"+key.ID, nil))
|
||||
if deleteUsedResponse.Code != http.StatusConflict {
|
||||
t.Fatalf("仍被使用的 SSH 私钥应禁止删除:%d %s", deleteUsedResponse.Code, deleteUsedResponse.Body.String())
|
||||
}
|
||||
deleteServerResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(deleteServerResponse, httptest.NewRequest(http.MethodDelete, "/api/v1/servers/"+createdServer.ID, nil))
|
||||
if deleteServerResponse.Code != http.StatusNoContent {
|
||||
t.Fatalf("删除测试服务器失败:%d %s", deleteServerResponse.Code, deleteServerResponse.Body.String())
|
||||
}
|
||||
deleteKeyResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(deleteKeyResponse, httptest.NewRequest(http.MethodDelete, "/api/v1/ssh-keys/"+key.ID, nil))
|
||||
if deleteKeyResponse.Code != http.StatusNoContent {
|
||||
t.Fatalf("删除未使用的 SSH 私钥失败:%d %s", deleteKeyResponse.Code, deleteKeyResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHKeyAPIRejectsInvalidKeyWithoutEchoingIt(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("打开敏感信息存储失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: config.Default(t.TempDir()), Repository: &stubDomainRepository{}, SSHKeys: sshkey.NewService(store)})
|
||||
secret := "invalid-private-key-sensitive-content"
|
||||
body, _ := json.Marshal(sshKeyRequest{Name: "错误私钥", PrivateKey: secret})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/ssh-keys", strings.NewReader(string(body)))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest || strings.Contains(response.Body.String(), secret) {
|
||||
t.Fatalf("无效 SSH 私钥响应不安全:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHKeyAPIRejectsOversizedRequestBody(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open secret store: %v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: config.Default(t.TempDir()), Repository: &stubDomainRepository{}, SSHKeys: sshkey.NewService(store)})
|
||||
body := `{"name":"oversized request","private_key":"` + strings.Repeat("a", maxSSHKeyRequestBytes) + `"}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/ssh-keys", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("oversized SSH key request should return 413: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHKeyAPIRejectsOversizedPrivateKeyAndPassphrase(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open secret store: %v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: config.Default(t.TempDir()), Repository: &stubDomainRepository{}, SSHKeys: sshkey.NewService(store)})
|
||||
requests := []sshKeyRequest{
|
||||
{Name: "oversized key", PrivateKey: strings.Repeat("a", sshkey.MaxPrivateKeyBytes+1)},
|
||||
{Name: "oversized passphrase", PrivateKey: testSSHPrivateKey(t), Passphrase: strings.Repeat("p", 4097)},
|
||||
}
|
||||
for _, input := range requests {
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encode limit test request: %v", err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/ssh-keys", strings.NewReader(string(body)))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
leaksPassphrase := input.Passphrase != "" && strings.Contains(response.Body.String(), input.Passphrase)
|
||||
if response.Code != http.StatusBadRequest || strings.Contains(response.Body.String(), input.PrivateKey) || leaksPassphrase {
|
||||
t.Fatalf("oversized input should be rejected safely: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testSSHPrivateKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试 SSH 私钥失败:%v", err)
|
||||
}
|
||||
encoded, err := x509.MarshalPKCS8PrivateKey(key)
|
||||
if err != nil {
|
||||
t.Fatalf("编码测试 SSH 私钥失败:%v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: encoded}))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package passwordpolicy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
MinLength = 8
|
||||
MaxLength = 128
|
||||
)
|
||||
|
||||
func Validate(password, username string) error {
|
||||
length := utf8.RuneCountInString(password)
|
||||
if length < MinLength {
|
||||
return fmt.Errorf("超级管理员密码至少需要 %d 个字符", MinLength)
|
||||
}
|
||||
if length > MaxLength {
|
||||
return fmt.Errorf("超级管理员密码最多允许 %d 个字符", MaxLength)
|
||||
}
|
||||
if strings.EqualFold(password, strings.TrimSpace(username)) {
|
||||
return fmt.Errorf("超级管理员密码不能与用户名相同")
|
||||
}
|
||||
hasLetter := false
|
||||
hasDigit := false
|
||||
for _, value := range password {
|
||||
if unicode.IsControl(value) {
|
||||
return fmt.Errorf("超级管理员密码不能包含控制字符")
|
||||
}
|
||||
hasLetter = hasLetter || unicode.IsLetter(value)
|
||||
hasDigit = hasDigit || unicode.IsDigit(value)
|
||||
}
|
||||
if !hasLetter || !hasDigit {
|
||||
return fmt.Errorf("超级管理员密码必须同时包含字母和数字")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package passwordpolicy
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
password string
|
||||
username string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "合法密码", password: "Password123", username: "admin"},
|
||||
{name: "支持中文字符", password: "安全密码2026", username: "admin"},
|
||||
{name: "长度不足", password: "Pass123", username: "admin", wantErr: true},
|
||||
{name: "缺少数字", password: "PasswordOnly", username: "admin", wantErr: true},
|
||||
{name: "缺少字母", password: "123456789", username: "admin", wantErr: true},
|
||||
{name: "等于用户名", password: "Admin123", username: "Admin123", wantErr: true},
|
||||
{name: "包含控制字符", password: "Password1\n", username: "admin", wantErr: true},
|
||||
{name: "长度超限", password: "Password1" + strings.Repeat("a", MaxLength), username: "admin", wantErr: true},
|
||||
}
|
||||
for _, test := range cases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := Validate(test.password, test.username)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("密码校验结果不正确:err=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AuditLog struct {
|
||||
Action string
|
||||
ResourceType string
|
||||
ResourceID string
|
||||
Status string
|
||||
Message string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AuditRepository interface {
|
||||
CreateAuditLog(ctx context.Context, item AuditLog) error
|
||||
}
|
||||
|
||||
type SQLAuditRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewSQLAuditRepository(db *sql.DB) *SQLAuditRepository {
|
||||
return &SQLAuditRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *SQLAuditRepository) CreateAuditLog(ctx context.Context, item AuditLog) error {
|
||||
if r == nil || r.db == nil {
|
||||
return errors.New("数据库连接不能为空")
|
||||
}
|
||||
item.Action = strings.TrimSpace(item.Action)
|
||||
item.ResourceType = strings.TrimSpace(item.ResourceType)
|
||||
item.ResourceID = strings.TrimSpace(item.ResourceID)
|
||||
item.Status = strings.TrimSpace(item.Status)
|
||||
if item.Action == "" || item.ResourceType == "" || item.Status == "" {
|
||||
return errors.New("审计日志必要字段不能为空")
|
||||
}
|
||||
if item.CreatedAt.IsZero() {
|
||||
item.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO audit_logs
|
||||
(action, resource_type, resource_id, status, message, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, item.Action, item.ResourceType, item.ResourceID, item.Status, item.Message, item.CreatedAt.UTC())
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存审计日志失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
)
|
||||
|
||||
func TestSQLAuditRepositoryCreatesLog(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
dbConfig := config.Default(dir).Database
|
||||
dbConfig.DSN = filepath.Join(dir, "data", "audit.db")
|
||||
db, err := database.Open(context.Background(), dbConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("打开数据库失败:%v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatalf("迁移数据库失败:%v", err)
|
||||
}
|
||||
repo := NewSQLAuditRepository(db.DB)
|
||||
if err := repo.CreateAuditLog(context.Background(), AuditLog{Action: "admin_password_reset", ResourceType: "super_admin", ResourceID: "super-admin", Status: "success", Message: "密码重置成功"}); err != nil {
|
||||
t.Fatalf("写入审计日志失败:%v", err)
|
||||
}
|
||||
var count int
|
||||
if err := db.DB.QueryRow("SELECT COUNT(*) FROM audit_logs WHERE action = ? AND status = ?", "admin_password_reset", "success").Scan(&count); err != nil {
|
||||
t.Fatalf("查询审计日志失败:%v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("审计日志数量不正确:%d", count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
)
|
||||
|
||||
type ServerRepository interface {
|
||||
CreateServer(ctx context.Context, server deployment.Server) error
|
||||
UpdateServer(ctx context.Context, server deployment.Server) error
|
||||
GetServerByID(ctx context.Context, id string) (deployment.Server, error)
|
||||
ListServers(ctx context.Context) ([]deployment.Server, error)
|
||||
DeleteServer(ctx context.Context, id string) error
|
||||
IsPrivateKeyRefUsed(ctx context.Context, reference string) (bool, error)
|
||||
ListServersByDomainID(ctx context.Context, domainID string) ([]deployment.Server, error)
|
||||
ReplaceDomainServers(ctx context.Context, domainID string, serverIDs []string) error
|
||||
}
|
||||
|
||||
type SQLServerRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewSQLServerRepository(db *sql.DB) *SQLServerRepository {
|
||||
return &SQLServerRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) CreateServer(ctx context.Context, server deployment.Server) error {
|
||||
server = server.Normalize()
|
||||
if err := validateServer(server); err != nil {
|
||||
return err
|
||||
}
|
||||
command, err := json.Marshal(server.ReloadCommand)
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码 reload 命令失败:%w", err)
|
||||
}
|
||||
createdAt := server.CreatedAt
|
||||
if createdAt.IsZero() {
|
||||
createdAt = time.Now().UTC()
|
||||
}
|
||||
updatedAt := server.UpdatedAt
|
||||
if updatedAt.IsZero() {
|
||||
updatedAt = createdAt
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, `INSERT INTO servers
|
||||
(id, name, address, port, username, private_key_ref, host_key_fingerprint, certificate_path, private_key_path, certificate_chain_path, web_server, reload_command_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, server.ID, server.Name, server.Address, server.Port, server.Username, server.PrivateKeyRef,
|
||||
server.HostKeyFingerprint, server.CertificatePath, server.PrivateKeyPath, server.CertificateChainPath, server.WebServer, string(command), createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存服务器失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) UpdateServer(ctx context.Context, server deployment.Server) error {
|
||||
server = server.Normalize()
|
||||
if err := validateServer(server); err != nil {
|
||||
return err
|
||||
}
|
||||
command, err := json.Marshal(server.ReloadCommand)
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码 reload 命令失败:%w", err)
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE servers SET name = ?, address = ?, port = ?, username = ?, private_key_ref = ?, host_key_fingerprint = ?, certificate_path = ?, private_key_path = ?, certificate_chain_path = ?, web_server = ?, reload_command_json = ?, updated_at = ? WHERE id = ?`,
|
||||
server.Name, server.Address, server.Port, server.Username, server.PrivateKeyRef, server.HostKeyFingerprint, server.CertificatePath, server.PrivateKeyPath, server.CertificateChainPath, server.WebServer, string(command), time.Now().UTC(), server.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新服务器失败:%w", err)
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取服务器更新结果失败:%w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) GetServerByID(ctx context.Context, id string) (deployment.Server, error) {
|
||||
row := r.db.QueryRowContext(ctx, serverSelect+` WHERE id = ?`, strings.TrimSpace(id))
|
||||
return scanServer(row)
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) ListServers(ctx context.Context) ([]deployment.Server, error) {
|
||||
rows, err := r.db.QueryContext(ctx, serverSelect+` ORDER BY name, id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询服务器失败:%w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]deployment.Server, 0)
|
||||
for rows.Next() {
|
||||
server, err := scanServer(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, server)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("读取服务器失败:%w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) DeleteServer(ctx context.Context, id string) error {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
return errors.New("服务器 ID 不能为空")
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始删除服务器失败:%w", err)
|
||||
}
|
||||
rollback := func(cause error) error {
|
||||
_ = tx.Rollback()
|
||||
return cause
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM domain_servers WHERE server_id = ?", id); err != nil {
|
||||
return rollback(fmt.Errorf("删除服务器关联失败:%w", err))
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, "DELETE FROM servers WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return rollback(fmt.Errorf("删除服务器失败:%w", err))
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return rollback(fmt.Errorf("读取服务器删除结果失败:%w", err))
|
||||
}
|
||||
if count == 0 {
|
||||
return rollback(sql.ErrNoRows)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("提交服务器删除失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) IsPrivateKeyRefUsed(ctx context.Context, reference string) (bool, error) {
|
||||
reference = strings.TrimSpace(reference)
|
||||
if reference == "" {
|
||||
return false, errors.New("SSH 私钥引用不能为空")
|
||||
}
|
||||
var count int
|
||||
if err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM servers WHERE private_key_ref = ?", reference).Scan(&count); err != nil {
|
||||
return false, fmt.Errorf("检查 SSH 私钥引用占用状态失败:%w", err)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) ListServersByDomainID(ctx context.Context, domainID string) ([]deployment.Server, error) {
|
||||
rows, err := r.db.QueryContext(ctx, serverSelectQualified+` INNER JOIN domain_servers ds ON ds.server_id = servers.id WHERE ds.domain_id = ? ORDER BY servers.name, servers.id`, strings.TrimSpace(domainID))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询域名部署服务器失败:%w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]deployment.Server, 0)
|
||||
for rows.Next() {
|
||||
server, err := scanServer(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, server)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("读取域名部署服务器失败:%w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) ReplaceDomainServers(ctx context.Context, domainID string, serverIDs []string) error {
|
||||
if strings.TrimSpace(domainID) == "" {
|
||||
return errors.New("域名 ID 不能为空")
|
||||
}
|
||||
cleaned := make([]string, 0, len(serverIDs))
|
||||
seen := make(map[string]struct{}, len(serverIDs))
|
||||
for _, id := range serverIDs {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
return errors.New("服务器 ID 不能为空")
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
cleaned = append(cleaned, id)
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始更新域名服务器关联失败:%w", err)
|
||||
}
|
||||
rollback := func(cause error) error {
|
||||
_ = tx.Rollback()
|
||||
return cause
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM domain_servers WHERE domain_id = ?", domainID); err != nil {
|
||||
return rollback(fmt.Errorf("清理域名服务器关联失败:%w", err))
|
||||
}
|
||||
for _, serverID := range cleaned {
|
||||
var exists int
|
||||
if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM servers WHERE id = ?", serverID).Scan(&exists); err != nil {
|
||||
return rollback(fmt.Errorf("校验部署服务器失败:%w", err))
|
||||
}
|
||||
if exists == 0 {
|
||||
return rollback(fmt.Errorf("部署服务器不存在:%s", serverID))
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "INSERT INTO domain_servers (domain_id, server_id) VALUES (?, ?)", domainID, serverID); err != nil {
|
||||
return rollback(fmt.Errorf("保存域名服务器关联失败:%w", err))
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("提交域名服务器关联失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const serverSelect = `SELECT id, name, address, port, username, private_key_ref, host_key_fingerprint, certificate_path, private_key_path, certificate_chain_path, web_server, reload_command_json, created_at, updated_at FROM servers`
|
||||
const serverSelectQualified = `SELECT servers.id, servers.name, servers.address, servers.port, servers.username, servers.private_key_ref, servers.host_key_fingerprint, servers.certificate_path, servers.private_key_path, servers.certificate_chain_path, servers.web_server, servers.reload_command_json, servers.created_at, servers.updated_at FROM servers`
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanServer(row rowScanner) (deployment.Server, error) {
|
||||
var server deployment.Server
|
||||
var webServer string
|
||||
var commandJSON string
|
||||
if err := row.Scan(&server.ID, &server.Name, &server.Address, &server.Port, &server.Username, &server.PrivateKeyRef, &server.HostKeyFingerprint, &server.CertificatePath, &server.PrivateKeyPath, &server.CertificateChainPath, &webServer, &commandJSON, &server.CreatedAt, &server.UpdatedAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return deployment.Server{}, sql.ErrNoRows
|
||||
}
|
||||
return deployment.Server{}, fmt.Errorf("读取服务器失败:%w", err)
|
||||
}
|
||||
server.WebServer = deployment.WebServer(webServer)
|
||||
if err := json.Unmarshal([]byte(commandJSON), &server.ReloadCommand); err != nil {
|
||||
return deployment.Server{}, fmt.Errorf("解析 reload 命令失败:%w", err)
|
||||
}
|
||||
return server.Normalize(), nil
|
||||
}
|
||||
|
||||
func validateServer(server deployment.Server) error {
|
||||
if err := server.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
)
|
||||
|
||||
func TestServerRepositoryCRUDAndDomainAssociations(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir).Database
|
||||
cfg.DSN = filepath.Join(dir, "data", "servers.db")
|
||||
db, err := database.Open(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewSQLServerRepository(db.DB)
|
||||
server := deployment.Server{
|
||||
ID: "server-1", Name: "生产服务器", Address: "192.0.2.10", Port: 22, Username: "deploy",
|
||||
PrivateKeyRef: "secret://ssh/server-1", HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/etc/scert/cert.pem", PrivateKeyPath: "/etc/scert/key.pem",
|
||||
CertificateChainPath: "/etc/scert/fullchain.pem", WebServer: deployment.WebServerNginx,
|
||||
}
|
||||
if err := repo.CreateServer(context.Background(), server); err != nil {
|
||||
t.Fatalf("创建服务器失败:%v", err)
|
||||
}
|
||||
loaded, err := repo.GetServerByID(context.Background(), server.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("读取服务器失败:%v", err)
|
||||
}
|
||||
if loaded.Name != server.Name || loaded.ReloadCommand[0] != "nginx" || loaded.CreatedAt.IsZero() {
|
||||
t.Fatalf("服务器内容错误:%+v", loaded)
|
||||
}
|
||||
server.Name = "生产服务器-更新"
|
||||
server.WebServer = deployment.WebServerCaddy
|
||||
server.ReloadCommand = nil
|
||||
if err := repo.UpdateServer(context.Background(), server); err != nil {
|
||||
t.Fatalf("更新服务器失败:%v", err)
|
||||
}
|
||||
if err := repo.ReplaceDomainServers(context.Background(), "domain-1", []string{server.ID, server.ID}); err != nil {
|
||||
t.Fatalf("保存域名服务器关联失败:%v", err)
|
||||
}
|
||||
associated, err := repo.ListServersByDomainID(context.Background(), "domain-1")
|
||||
if err != nil || len(associated) != 1 || associated[0].WebServer != deployment.WebServerCaddy {
|
||||
t.Fatalf("域名服务器关联错误:%v %+v", err, associated)
|
||||
}
|
||||
servers, err := repo.ListServers(context.Background())
|
||||
if err != nil || len(servers) != 1 {
|
||||
t.Fatalf("服务器列表错误:%v %+v", err, servers)
|
||||
}
|
||||
if err := repo.DeleteServer(context.Background(), server.ID); err != nil {
|
||||
t.Fatalf("删除服务器失败:%v", err)
|
||||
}
|
||||
associated, err = repo.ListServersByDomainID(context.Background(), "domain-1")
|
||||
if err != nil {
|
||||
t.Fatalf("读取删除后的域名服务器关联失败:%v", err)
|
||||
}
|
||||
if len(associated) != 0 {
|
||||
t.Fatalf("删除服务器后不应保留悬空关联:%+v", associated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerRepositoryRejectsInvalidServer(t *testing.T) {
|
||||
db, err := database.Open(context.Background(), config.DatabaseConfig{
|
||||
Driver: "sqlite", DSN: ":memory:", MaxOpenConns: 1, MaxIdleConns: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := NewSQLServerRepository(db.DB).CreateServer(context.Background(), deployment.Server{}); err == nil {
|
||||
t.Fatal("无效服务器配置应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerRepositoryReportsPrivateKeyReferenceUsage(t *testing.T) {
|
||||
db := openServerTestDatabase(t)
|
||||
defer db.Close()
|
||||
repo := NewSQLServerRepository(db.DB)
|
||||
server := validTestServer()
|
||||
server.ID = "server-private-key-usage"
|
||||
server.PrivateKeyRef = "secret://ssh/used-key"
|
||||
if err := repo.CreateServer(t.Context(), server); err != nil {
|
||||
t.Fatalf("创建测试服务器失败:%v", err)
|
||||
}
|
||||
used, err := repo.IsPrivateKeyRefUsed(t.Context(), server.PrivateKeyRef)
|
||||
if err != nil || !used {
|
||||
t.Fatalf("未识别已占用的 SSH 私钥引用:used=%t err=%v", used, err)
|
||||
}
|
||||
used, err = repo.IsPrivateKeyRefUsed(t.Context(), "secret://ssh/not-used")
|
||||
if err != nil || used {
|
||||
t.Fatalf("错误识别未占用的 SSH 私钥引用:used=%t err=%v", used, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceDomainServersRejectsUnknownServerWithoutChangingAssociations(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir).Database
|
||||
cfg.DSN = filepath.Join(dir, "data", "association.db")
|
||||
db, err := database.Open(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewSQLServerRepository(db.DB)
|
||||
server := deployment.Server{ID: "server-1", Name: "服务器", Address: "192.0.2.20", Username: "deploy", PrivateKeyRef: "secret://ssh/1", HostKeyFingerprint: "SHA256:test", CertificatePath: "/etc/scert/cert.pem", PrivateKeyPath: "/etc/scert/key.pem", CertificateChainPath: "/etc/scert/fullchain.pem", WebServer: deployment.WebServerNginx}
|
||||
if err := repo.CreateServer(context.Background(), server); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.ReplaceDomainServers(context.Background(), "domain-1", []string{server.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.ReplaceDomainServers(context.Background(), "domain-1", []string{"missing"}); err == nil {
|
||||
t.Fatal("未知服务器应被拒绝")
|
||||
}
|
||||
items, err := repo.ListServersByDomainID(context.Background(), "domain-1")
|
||||
if err != nil || len(items) != 1 || items[0].ID != server.ID {
|
||||
t.Fatalf("失败后原关联应保持不变:%v %+v", err, items)
|
||||
}
|
||||
}
|
||||
|
||||
func openServerTestDatabase(t *testing.T) *database.Database {
|
||||
t.Helper()
|
||||
directory := t.TempDir()
|
||||
cfg := config.Default(directory).Database
|
||||
cfg.DSN = filepath.Join(directory, "data", "server-test.db")
|
||||
db, err := database.Open(t.Context(), cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("打开服务器测试数据库失败:%v", err)
|
||||
}
|
||||
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||
_ = db.Close()
|
||||
t.Fatalf("迁移服务器测试数据库失败:%v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func validTestServer() deployment.Server {
|
||||
return deployment.Server{
|
||||
Name: "测试服务器", Address: "192.0.2.70", Port: 22, Username: "deploy",
|
||||
PrivateKeyRef: "secret://ssh/test", HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/etc/scert/cert.pem", PrivateKeyPath: "/etc/scert/key.pem",
|
||||
CertificateChainPath: "/etc/scert/fullchain.pem", WebServer: deployment.WebServerNginx,
|
||||
}
|
||||
}
|
||||
@@ -100,16 +100,30 @@ func (r *SQLDomainRepository) Delete(ctx context.Context, id string) error {
|
||||
if r == nil || r.db == nil {
|
||||
return errors.New("数据库连接不能为空")
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, "DELETE FROM domains WHERE id = ?", id)
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除域名失败:%w", err)
|
||||
return fmt.Errorf("开始删除域名失败:%w", err)
|
||||
}
|
||||
rollback := func(cause error) error {
|
||||
_ = tx.Rollback()
|
||||
return cause
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM domain_servers WHERE domain_id = ?", id); err != nil {
|
||||
return rollback(fmt.Errorf("删除域名服务器关联失败:%w", err))
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, "DELETE FROM domains WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return rollback(fmt.Errorf("删除域名失败:%w", err))
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取删除结果失败:%w", err)
|
||||
return rollback(fmt.Errorf("读取删除结果失败:%w", err))
|
||||
}
|
||||
if count == 0 {
|
||||
return sql.ErrNoRows
|
||||
return rollback(sql.ErrNoRows)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("提交域名删除失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
@@ -84,9 +85,21 @@ func TestRepositoryCRUD(t *testing.T) {
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("域名列表不正确:%v,%+v", err, items)
|
||||
}
|
||||
serverRepo := NewSQLServerRepository(db.DB)
|
||||
server := deployment.Server{ID: "server-1", Name: "服务器", Address: "192.0.2.30", Username: "deploy", PrivateKeyRef: "secret://ssh/1", HostKeyFingerprint: "SHA256:test", CertificatePath: "/etc/scert/cert.pem", PrivateKeyPath: "/etc/scert/key.pem", CertificateChainPath: "/etc/scert/fullchain.pem", WebServer: deployment.WebServerNginx}
|
||||
if err := serverRepo.CreateServer(context.Background(), server); err != nil {
|
||||
t.Fatalf("创建关联服务器失败:%v", err)
|
||||
}
|
||||
if err := serverRepo.ReplaceDomainServers(context.Background(), item.ID, []string{server.ID}); err != nil {
|
||||
t.Fatalf("创建域名服务器关联失败:%v", err)
|
||||
}
|
||||
if err := repo.Delete(context.Background(), item.ID); err != nil {
|
||||
t.Fatalf("删除域名失败:%v", err)
|
||||
}
|
||||
associated, err := serverRepo.ListServersByDomainID(context.Background(), item.ID)
|
||||
if err != nil || len(associated) != 0 {
|
||||
t.Fatalf("删除域名后不应保留服务器关联:%v %+v", err, associated)
|
||||
}
|
||||
if err := repo.Delete(context.Background(), item.ID); !IsNotFound(err) {
|
||||
t.Fatalf("重复删除未返回未找到:%v", err)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -37,6 +39,12 @@ type Store struct {
|
||||
filePath string
|
||||
}
|
||||
|
||||
// Metadata 仅包含敏感信息引用及更新时间,不包含密文或明文内容。
|
||||
type Metadata struct {
|
||||
Reference string `json:"reference"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func Open(configDir string) (*Store, error) {
|
||||
if configDir == "" {
|
||||
return nil, errors.New("敏感信息目录不能为空")
|
||||
@@ -158,6 +166,55 @@ func (s *Store) Has(ctx context.Context, reference string) (bool, error) {
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
// List 按引用前缀返回敏感信息元数据,不解密或返回敏感内容。
|
||||
func (s *Store) List(ctx context.Context, prefix string) ([]Metadata, error) {
|
||||
if s == nil {
|
||||
return nil, errors.New("敏感信息存储未初始化")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
data, err := s.readLocked()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]Metadata, 0)
|
||||
for reference, item := range data.Items {
|
||||
if prefix == "" || strings.HasPrefix(reference, prefix) {
|
||||
result = append(result, Metadata{Reference: reference, UpdatedAt: item.UpdatedAt})
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return result[i].Reference < result[j].Reference })
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Delete 原子删除指定引用;引用不存在时返回明确错误。
|
||||
func (s *Store) Delete(ctx context.Context, reference string) error {
|
||||
if s == nil {
|
||||
return errors.New("敏感信息存储未初始化")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
reference = strings.TrimSpace(reference)
|
||||
if reference == "" {
|
||||
return errors.New("敏感信息引用不能为空")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
data, err := s.readLocked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := data.Items[reference]; !ok {
|
||||
return fmt.Errorf("敏感信息引用不存在:%s", reference)
|
||||
}
|
||||
delete(data.Items, reference)
|
||||
return s.writeLocked(data)
|
||||
}
|
||||
|
||||
func (s *Store) readLocked() (fileData, error) {
|
||||
data := fileData{Version: storeVersion, Items: map[string]encryptedItem{}}
|
||||
content, err := os.ReadFile(s.filePath)
|
||||
|
||||
@@ -52,6 +52,40 @@ func TestStoreSupportsMultipleUpdates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreListsMetadataAndDeletesReferenceWithoutLeakingValues(t *testing.T) {
|
||||
store, err := Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("打开敏感信息存储失败:%v", err)
|
||||
}
|
||||
if err := store.Put(t.Context(), "secret://ssh/key-b", map[string]string{"private_key": "secret-b"}); err != nil {
|
||||
t.Fatalf("保存第二个 SSH 私钥失败:%v", err)
|
||||
}
|
||||
if err := store.Put(t.Context(), "secret://dns/provider", map[string]string{"token": "dns-secret"}); err != nil {
|
||||
t.Fatalf("保存 DNS 凭据失败:%v", err)
|
||||
}
|
||||
if err := store.Put(t.Context(), "secret://ssh/key-a", map[string]string{"private_key": "secret-a"}); err != nil {
|
||||
t.Fatalf("保存第一个 SSH 私钥失败:%v", err)
|
||||
}
|
||||
|
||||
items, err := store.List(t.Context(), "secret://ssh/")
|
||||
if err != nil {
|
||||
t.Fatalf("列出 SSH 私钥引用失败:%v", err)
|
||||
}
|
||||
if len(items) != 2 || items[0].Reference != "secret://ssh/key-a" || items[1].Reference != "secret://ssh/key-b" {
|
||||
t.Fatalf("SSH 私钥引用列表不正确:%+v", items)
|
||||
}
|
||||
if err := store.Delete(t.Context(), items[0].Reference); err != nil {
|
||||
t.Fatalf("删除 SSH 私钥引用失败:%v", err)
|
||||
}
|
||||
exists, err := store.Has(t.Context(), items[0].Reference)
|
||||
if err != nil || exists {
|
||||
t.Fatalf("SSH 私钥引用删除后仍然存在:exists=%t err=%v", exists, err)
|
||||
}
|
||||
if err := store.Delete(t.Context(), items[0].Reference); err == nil {
|
||||
t.Fatal("重复删除不存在的敏感信息引用应返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAtomicFileReplacesExistingFile(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
path := filepath.Join(directory, "secrets.json")
|
||||
|
||||
@@ -3,18 +3,20 @@ package setup
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/mail"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/passwordpolicy"
|
||||
)
|
||||
|
||||
type Input struct {
|
||||
AdminUsername string
|
||||
AdminEmail string
|
||||
AdminPassword string
|
||||
ServerPort int
|
||||
ResetServicePort int
|
||||
EmailProvider string
|
||||
EmailEndpoint string
|
||||
EmailRecipients []string
|
||||
@@ -35,18 +37,16 @@ func Apply(cfg *config.Config, input Input) error {
|
||||
if strings.TrimSpace(input.AdminUsername) == "" {
|
||||
return fmt.Errorf("超级管理员用户名不能为空")
|
||||
}
|
||||
if len(input.AdminPassword) < 8 {
|
||||
return fmt.Errorf("超级管理员密码至少需要 8 个字符")
|
||||
adminEmail, err := normalizeAdminEmail(input.AdminEmail)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := passwordpolicy.Validate(input.AdminPassword, input.AdminUsername); err != nil {
|
||||
return err
|
||||
}
|
||||
if input.ServerPort < 1 || input.ServerPort > 65535 {
|
||||
return fmt.Errorf("主服务端口无效:%d", input.ServerPort)
|
||||
}
|
||||
if input.ResetServicePort < 1 || input.ResetServicePort > 65535 {
|
||||
return fmt.Errorf("密码重置服务端口无效:%d", input.ResetServicePort)
|
||||
}
|
||||
if input.ServerPort == input.ResetServicePort {
|
||||
return fmt.Errorf("主服务和密码重置服务不能使用相同端口")
|
||||
}
|
||||
if strings.TrimSpace(input.DNSProvider) == "" {
|
||||
return fmt.Errorf("DNS 服务商不能为空")
|
||||
}
|
||||
@@ -57,13 +57,13 @@ func Apply(cfg *config.Config, input Input) error {
|
||||
return fmt.Errorf("DNS API 尚未通过验证测试")
|
||||
}
|
||||
if strings.TrimSpace(input.WebHostname) == "" && strings.TrimSpace(input.WebPublicIP) == "" {
|
||||
return fmt.Errorf("Web 页面必须配置域名或公网 IP")
|
||||
return fmt.Errorf("管理页面必须配置域名或公网 IP")
|
||||
}
|
||||
if input.WebHostname != "" && input.WebPublicIP != "" {
|
||||
return fmt.Errorf("Web 页面不能同时配置域名和公网 IP")
|
||||
return fmt.Errorf("管理页面不能同时配置域名和公网 IP")
|
||||
}
|
||||
if input.WebPublicIP != "" && net.ParseIP(input.WebPublicIP) == nil {
|
||||
return fmt.Errorf("Web 公网 IP 格式无效")
|
||||
return fmt.Errorf("管理页面公网 IP 格式无效")
|
||||
}
|
||||
if input.HTTPSMode == "" {
|
||||
input.HTTPSMode = "direct"
|
||||
@@ -79,8 +79,8 @@ func Apply(cfg *config.Config, input Input) error {
|
||||
return fmt.Errorf("生成管理员密码摘要失败:%w", err)
|
||||
}
|
||||
cfg.Admin.Username = strings.TrimSpace(input.AdminUsername)
|
||||
cfg.Admin.Email = adminEmail
|
||||
cfg.Admin.PasswordHash = string(hash)
|
||||
cfg.Admin.ResetServicePort = input.ResetServicePort
|
||||
cfg.Server.Port = input.ServerPort
|
||||
cfg.Server.HTTPSMode = input.HTTPSMode
|
||||
cfg.Web.Enabled = input.WebEnabled
|
||||
@@ -116,3 +116,15 @@ func cleanRecipients(values []string) []string {
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func normalizeAdminEmail(value string) (string, error) {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("超级管理员绑定邮箱不能为空")
|
||||
}
|
||||
parsed, err := mail.ParseAddress(value)
|
||||
if err != nil || parsed.Address != value || parsed.Name != "" {
|
||||
return "", fmt.Errorf("超级管理员绑定邮箱格式无效")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
func TestApplyRequiresVerifiedDNS(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
err := Apply(&cfg, Input{
|
||||
AdminUsername: "admin", AdminPassword: "password123", ServerPort: 8080, ResetServicePort: 8091,
|
||||
AdminUsername: "admin", AdminEmail: "admin@example.com", AdminPassword: "password123", ServerPort: 8080,
|
||||
DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", CertificateRoot: cfg.Paths.Certificate,
|
||||
WebHostname: "panel.example.com", WebEnabled: true,
|
||||
})
|
||||
@@ -21,7 +21,7 @@ func TestApplyRequiresVerifiedDNS(t *testing.T) {
|
||||
func TestApplyBuildsReadyConfig(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
err := Apply(&cfg, Input{
|
||||
AdminUsername: "admin", AdminPassword: "password123", ServerPort: 8080, ResetServicePort: 8091,
|
||||
AdminUsername: "admin", AdminEmail: "admin@example.com", AdminPassword: "password123", ServerPort: 8080,
|
||||
EmailProvider: "mail-api", EmailEndpoint: "https://mail.example.test/send", EmailRecipients: []string{"a@example.test,b@example.test", "a@example.test"},
|
||||
DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", DNSVerified: true, CertificateRoot: cfg.Paths.Certificate,
|
||||
WebHostname: "panel.example.com", WebEnabled: true,
|
||||
@@ -38,12 +38,15 @@ func TestApplyBuildsReadyConfig(t *testing.T) {
|
||||
if cfg.Admin.PasswordHash == "password123" || cfg.Admin.PasswordHash == "" {
|
||||
t.Fatal("管理员密码不应明文保存")
|
||||
}
|
||||
if cfg.ResetURL() != "https://panel.example.com/reset" {
|
||||
t.Fatalf("密码重置地址生成错误:%s", cfg.ResetURL())
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRejectsWebIPAsHostnamePair(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
err := Apply(&cfg, Input{
|
||||
AdminUsername: "admin", AdminPassword: "password123", ServerPort: 8080, ResetServicePort: 8091,
|
||||
AdminUsername: "admin", AdminEmail: "admin@example.com", AdminPassword: "password123", ServerPort: 8080,
|
||||
DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", DNSVerified: true,
|
||||
WebHostname: "panel.example.com", WebPublicIP: "203.0.113.10", WebEnabled: true,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
package sshkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
)
|
||||
|
||||
const (
|
||||
ReferencePrefix = "secret://ssh/"
|
||||
secretKind = "ssh_private_key"
|
||||
MaxPrivateKeyBytes = 1024 * 1024
|
||||
maxNameLength = 128
|
||||
maxPassphraseBytes = 4096
|
||||
)
|
||||
|
||||
type Store interface {
|
||||
Put(ctx context.Context, reference string, value map[string]string) error
|
||||
Get(ctx context.Context, reference string) (map[string]string, error)
|
||||
List(ctx context.Context, prefix string) ([]secretstore.Metadata, error)
|
||||
Delete(ctx context.Context, reference string) error
|
||||
}
|
||||
|
||||
// Metadata 是可安全返回给 API、CLI 和前端的 SSH 私钥元数据。
|
||||
type Metadata struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Reference string `json:"reference"`
|
||||
Algorithm string `json:"algorithm"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store Store
|
||||
}
|
||||
|
||||
func NewService(store Store) *Service {
|
||||
return &Service{store: store}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, name, privateKey, passphrase string) (Metadata, error) {
|
||||
if s == nil || s.store == nil {
|
||||
return Metadata{}, errors.New("SSH 私钥存储未初始化")
|
||||
}
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return Metadata{}, errors.New("SSH 私钥名称不能为空")
|
||||
}
|
||||
if len([]rune(name)) > maxNameLength {
|
||||
return Metadata{}, fmt.Errorf("SSH 私钥名称不能超过 %d 个字符", maxNameLength)
|
||||
}
|
||||
privateKey = strings.TrimSpace(privateKey)
|
||||
if privateKey == "" {
|
||||
return Metadata{}, errors.New("SSH 私钥内容不能为空")
|
||||
}
|
||||
if len(privateKey) > MaxPrivateKeyBytes {
|
||||
return Metadata{}, fmt.Errorf("SSH 私钥内容不能超过 %d 字节", MaxPrivateKeyBytes)
|
||||
}
|
||||
if len(passphrase) > maxPassphraseBytes {
|
||||
return Metadata{}, fmt.Errorf("SSH 私钥口令不能超过 %d 字节", maxPassphraseBytes)
|
||||
}
|
||||
signer, err := parsePrivateKey(privateKey, passphrase)
|
||||
if err != nil {
|
||||
return Metadata{}, err
|
||||
}
|
||||
id := domain.NewID()
|
||||
reference := ReferencePrefix + id
|
||||
payload := map[string]string{
|
||||
"kind": secretKind,
|
||||
"name": name,
|
||||
"private_key": privateKey + "\n",
|
||||
"passphrase": passphrase,
|
||||
"algorithm": signer.PublicKey().Type(),
|
||||
"fingerprint": ssh.FingerprintSHA256(signer.PublicKey()),
|
||||
}
|
||||
if err := s.store.Put(ctx, reference, payload); err != nil {
|
||||
return Metadata{}, fmt.Errorf("保存 SSH 私钥失败:%w", err)
|
||||
}
|
||||
return Metadata{
|
||||
ID: id, Name: name, Reference: reference, Algorithm: payload["algorithm"],
|
||||
Fingerprint: payload["fingerprint"], UpdatedAt: time.Now().UTC(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context) ([]Metadata, error) {
|
||||
if s == nil || s.store == nil {
|
||||
return nil, errors.New("SSH 私钥存储未初始化")
|
||||
}
|
||||
items, err := s.store.List(ctx, ReferencePrefix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("列出 SSH 私钥失败:%w", err)
|
||||
}
|
||||
result := make([]Metadata, 0, len(items))
|
||||
for _, item := range items {
|
||||
metadata, err := s.metadata(ctx, item.Reference, item.UpdatedAt, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, metadata)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) ValidateReference(ctx context.Context, reference string) (Metadata, error) {
|
||||
if s == nil || s.store == nil {
|
||||
return Metadata{}, errors.New("SSH 私钥存储未初始化")
|
||||
}
|
||||
return s.metadata(ctx, strings.TrimSpace(reference), time.Time{}, true)
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, id string) error {
|
||||
if s == nil || s.store == nil {
|
||||
return errors.New("SSH 私钥存储未初始化")
|
||||
}
|
||||
reference, err := referenceFromID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.metadata(ctx, reference, time.Time{}, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.store.Delete(ctx, reference); err != nil {
|
||||
return fmt.Errorf("删除 SSH 私钥失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) Reference(id string) (string, error) {
|
||||
return referenceFromID(id)
|
||||
}
|
||||
|
||||
func (s *Service) metadata(ctx context.Context, reference string, updatedAt time.Time, validateKey bool) (Metadata, error) {
|
||||
if !strings.HasPrefix(reference, ReferencePrefix) {
|
||||
return Metadata{}, errors.New("SSH 私钥引用格式无效")
|
||||
}
|
||||
id := strings.TrimPrefix(reference, ReferencePrefix)
|
||||
if _, err := referenceFromID(id); err != nil {
|
||||
return Metadata{}, err
|
||||
}
|
||||
payload, err := s.store.Get(ctx, reference)
|
||||
if err != nil {
|
||||
return Metadata{}, fmt.Errorf("读取 SSH 私钥失败:%w", err)
|
||||
}
|
||||
if payload["kind"] != secretKind || strings.TrimSpace(payload["private_key"]) == "" {
|
||||
return Metadata{}, errors.New("敏感信息引用不是有效的 SSH 私钥")
|
||||
}
|
||||
algorithm := payload["algorithm"]
|
||||
fingerprint := payload["fingerprint"]
|
||||
if validateKey || algorithm == "" || fingerprint == "" {
|
||||
signer, parseErr := parsePrivateKey(payload["private_key"], payload["passphrase"])
|
||||
if parseErr != nil {
|
||||
return Metadata{}, parseErr
|
||||
}
|
||||
algorithm = signer.PublicKey().Type()
|
||||
fingerprint = ssh.FingerprintSHA256(signer.PublicKey())
|
||||
}
|
||||
return Metadata{
|
||||
ID: id, Name: payload["name"], Reference: reference,
|
||||
Algorithm: algorithm, Fingerprint: fingerprint, UpdatedAt: updatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parsePrivateKey(privateKey, passphrase string) (ssh.Signer, error) {
|
||||
var (
|
||||
signer ssh.Signer
|
||||
err error
|
||||
)
|
||||
if passphrase != "" {
|
||||
signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(privateKey), []byte(passphrase))
|
||||
} else {
|
||||
signer, err = ssh.ParsePrivateKey([]byte(privateKey))
|
||||
}
|
||||
if err != nil {
|
||||
var missing *ssh.PassphraseMissingError
|
||||
if errors.As(err, &missing) {
|
||||
return nil, errors.New("SSH 私钥已加密,请提供私钥口令")
|
||||
}
|
||||
return nil, errors.New("SSH 私钥格式或口令无效")
|
||||
}
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
func referenceFromID(id string) (string, error) {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || strings.ContainsAny(id, "/\\\x00\r\n") {
|
||||
return "", errors.New("SSH 私钥 ID 无效")
|
||||
}
|
||||
return ReferencePrefix + id, nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package sshkey
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
)
|
||||
|
||||
func TestServiceCreatesListsValidatesAndDeletesSSHKey(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("打开敏感信息存储失败:%v", err)
|
||||
}
|
||||
service := NewService(store)
|
||||
privateKey := testPrivateKey(t)
|
||||
created, err := service.Create(t.Context(), "生产部署私钥", privateKey, "")
|
||||
if err != nil {
|
||||
t.Fatalf("创建 SSH 私钥失败:%v", err)
|
||||
}
|
||||
if created.ID == "" || !strings.HasPrefix(created.Reference, ReferencePrefix) || created.Algorithm != "ssh-ed25519" || !strings.HasPrefix(created.Fingerprint, "SHA256:") {
|
||||
t.Fatalf("SSH 私钥元数据无效:%+v", created)
|
||||
}
|
||||
items, err := service.List(t.Context())
|
||||
if err != nil || len(items) != 1 || items[0].Name != "生产部署私钥" {
|
||||
t.Fatalf("SSH 私钥列表无效:items=%+v err=%v", items, err)
|
||||
}
|
||||
validated, err := service.ValidateReference(t.Context(), created.Reference)
|
||||
if err != nil || validated.Fingerprint != created.Fingerprint {
|
||||
t.Fatalf("SSH 私钥引用校验失败:metadata=%+v err=%v", validated, err)
|
||||
}
|
||||
if err := service.Delete(t.Context(), created.ID); err != nil {
|
||||
t.Fatalf("删除 SSH 私钥失败:%v", err)
|
||||
}
|
||||
if _, err := service.ValidateReference(t.Context(), created.Reference); err == nil {
|
||||
t.Fatal("已删除的 SSH 私钥引用不应继续通过校验")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceRejectsInvalidSSHKeyWithoutLeakingContent(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("打开敏感信息存储失败:%v", err)
|
||||
}
|
||||
privateKey := "very-sensitive-invalid-private-key"
|
||||
_, err = NewService(store).Create(t.Context(), "错误私钥", privateKey, "")
|
||||
if err == nil {
|
||||
t.Fatal("无效 SSH 私钥应被拒绝")
|
||||
}
|
||||
if strings.Contains(err.Error(), privateKey) {
|
||||
t.Fatalf("错误信息不应泄露私钥内容:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceSupportsEncryptedSSHKeyAndRejectsWrongPassphrase(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open secret store: %v", err)
|
||||
}
|
||||
privateKey := testEncryptedPrivateKey(t, "correct-passphrase")
|
||||
service := NewService(store)
|
||||
created, err := service.Create(t.Context(), "encrypted deployment key", privateKey, "correct-passphrase")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create encrypted SSH key: %v", err)
|
||||
}
|
||||
if created.Algorithm != "ssh-ed25519" || !strings.HasPrefix(created.Fingerprint, "SHA256:") {
|
||||
t.Fatalf("invalid encrypted SSH key metadata: %+v", created)
|
||||
}
|
||||
_, err = service.Create(t.Context(), "wrong passphrase key", privateKey, "wrong-passphrase")
|
||||
if err == nil || strings.Contains(err.Error(), "wrong-passphrase") || strings.Contains(err.Error(), "correct-passphrase") {
|
||||
t.Fatalf("wrong passphrase was not rejected safely: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceRejectsOversizedPrivateKeyAndPassphrase(t *testing.T) {
|
||||
store, err := secretstore.Open(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open secret store: %v", err)
|
||||
}
|
||||
service := NewService(store)
|
||||
if _, err := service.Create(t.Context(), "oversized key", strings.Repeat("a", MaxPrivateKeyBytes+1), ""); err == nil {
|
||||
t.Fatal("oversized SSH private key should be rejected")
|
||||
}
|
||||
if _, err := service.Create(t.Context(), "oversized passphrase", testPrivateKey(t), strings.Repeat("p", maxPassphraseBytes+1)); err == nil {
|
||||
t.Fatal("oversized SSH private key passphrase should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func testPrivateKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试私钥失败:%v", err)
|
||||
}
|
||||
encoded, err := x509.MarshalPKCS8PrivateKey(key)
|
||||
if err != nil {
|
||||
t.Fatalf("编码测试私钥失败:%v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: encoded}))
|
||||
}
|
||||
|
||||
func testEncryptedPrivateKey(t *testing.T, passphrase string) string {
|
||||
t.Helper()
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate test private key: %v", err)
|
||||
}
|
||||
block, err := ssh.MarshalPrivateKeyWithPassphrase(key, "scert-test", []byte(passphrase))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encrypt test private key: %v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(block))
|
||||
}
|
||||
Reference in new issue
Block a user