完善初始化向导、通知配置与证书流程

This commit is contained in:
xuans committed 2026-08-29 11:52:31 +08:00
1 parent b2833b761d
commit f85ef10527
41 files changed
+3645 -1697

No files matched your search

+11 -5
View File
@@ -4,6 +4,7 @@ import (
"context"
"flag"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
@@ -14,9 +15,17 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
func writeSessionInfo(writer io.Writer, session admin.Session) {
fmt.Fprintln(writer, "Scert-admin 已启用临时密码重置入口,不监听独立网络端口。")
fmt.Fprintln(writer, "重置地址:", session.State.ResetURL)
fmt.Fprintln(writer, "一次性校验码已写入受保护的临时文件:", session.State.CodePath)
fmt.Fprintln(writer, "请使用 root 或 Scert 用户读取该文件;密码重置完成后文件会自动销毁。")
fmt.Fprintln(writer, "停止 Scert-admin 后入口将立即关闭;异常退出时入口会在租约过期后自动关闭。")
}
func main() {
baseDir := flag.String("base-dir", "", "Windows 默认安装根目录")
configPath := flag.String("config", "", "配置文件路径")
codeOutput := flag.String("code-output", "", "一次性校验码文件路径")
flag.Parse()
path := *configPath
if path == "" {
@@ -27,16 +36,13 @@ func main() {
fmt.Fprintln(os.Stderr, "读取配置失败:", err)
os.Exit(1)
}
controller := admin.New(cfg)
controller := admin.NewWithCodePath(cfg, *codeOutput)
session, err := controller.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "启用密码重置入口失败:", err)
os.Exit(1)
}
fmt.Println("Scert-admin 已启用临时密码重置入口,不监听独立网络端口。")
fmt.Println("重置地址:", session.State.ResetURL)
fmt.Println("一次性校验码:", session.Code)
fmt.Println("停止 Scert-admin 后入口将立即关闭;异常退出时入口会在租约过期后自动关闭。")
writeSessionInfo(os.Stdout, session)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
ticker := time.NewTicker(admin.RefreshInterval)
+27
View File
@@ -0,0 +1,27 @@
package main
import (
"bytes"
"strings"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/admin"
)
func TestSessionInfoDoesNotExposeResetCode(t *testing.T) {
const secretCode = "ABCDE-12345-FGHIJ"
var output bytes.Buffer
writeSessionInfo(&output, admin.Session{
State: admin.State{
ResetURL: "https://scert.example.test/reset",
CodePath: "/run/scert-admin/reset-code",
},
Code: secretCode,
})
if strings.Contains(output.String(), secretCode) {
t.Fatal("命令行输出不得包含一次性校验码")
}
if !strings.Contains(output.String(), "/run/scert-admin/reset-code") {
t.Fatal("命令行输出必须提示受保护校验码文件路径")
}
}
@@ -0,0 +1,7 @@
//go:build !windows
package admin
func protectCodeFile(string) error {
return nil
}
@@ -0,0 +1,100 @@
//go:build windows
package admin
import (
"fmt"
"runtime"
"golang.org/x/sys/windows"
)
func protectCodeFile(path string) error {
currentSID, err := currentProcessUserSID()
if err != nil {
return err
}
systemSID, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
if err != nil {
return fmt.Errorf("创建系统账户安全标识失败:%w", err)
}
adminSID, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
if err != nil {
return fmt.Errorf("创建本地管理员组安全标识失败:%w", err)
}
var pinner runtime.Pinner
pinner.Pin(currentSID)
pinner.Pin(systemSID)
pinner.Pin(adminSID)
defer pinner.Unpin()
readDelete := windows.ACCESS_MASK(windows.FILE_GENERIC_READ | windows.DELETE | windows.READ_CONTROL | windows.SYNCHRONIZE)
fullControl := windows.ACCESS_MASK(windows.FILE_GENERIC_READ |
windows.FILE_GENERIC_WRITE |
windows.FILE_GENERIC_EXECUTE |
windows.DELETE |
windows.READ_CONTROL |
windows.WRITE_DAC |
windows.WRITE_OWNER |
windows.SYNCHRONIZE)
entries := []windows.EXPLICIT_ACCESS{
{
AccessPermissions: readDelete,
AccessMode: windows.SET_ACCESS,
Inheritance: windows.NO_INHERITANCE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_USER,
TrusteeValue: windows.TrusteeValueFromSID(currentSID),
},
},
{
AccessPermissions: fullControl,
AccessMode: windows.SET_ACCESS,
Inheritance: windows.NO_INHERITANCE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_WELL_KNOWN_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(systemSID),
},
},
{
AccessPermissions: fullControl,
AccessMode: windows.SET_ACCESS,
Inheritance: windows.NO_INHERITANCE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_ALIAS,
TrusteeValue: windows.TrusteeValueFromSID(adminSID),
},
},
}
acl, err := windows.ACLFromEntries(entries, nil)
if err != nil {
return fmt.Errorf("创建校验码文件访问控制列表失败:%w", err)
}
if err := windows.SetNamedSecurityInfo(
path,
windows.SE_FILE_OBJECT,
windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION,
nil,
nil,
acl,
nil,
); err != nil {
return fmt.Errorf("应用校验码文件访问控制列表失败:%w", err)
}
return nil
}
func currentProcessUserSID() (*windows.SID, error) {
user, err := windows.GetCurrentProcessToken().GetTokenUser()
if err != nil {
return nil, fmt.Errorf("读取当前服务账户安全标识失败:%w", err)
}
if user == nil || user.User.Sid == nil {
return nil, fmt.Errorf("当前服务账户没有有效的安全标识")
}
return user.User.Sid, nil
}
+96 -8
View File
@@ -20,6 +20,7 @@ import (
const (
ResetPath = "/reset"
stateFileName = "scert-admin-reset.json"
codeFileName = "scert-admin-reset-code"
defaultLease = 90 * time.Second
RefreshInterval = 30 * time.Second
)
@@ -30,6 +31,7 @@ type State struct {
Active bool `json:"active"`
ResetURL string `json:"reset_url"`
CodeHash string `json:"code_hash"`
CodePath string `json:"code_path,omitempty"`
ProcessID int `json:"process_id"`
StartedAt time.Time `json:"started_at"`
ExpiresAt time.Time `json:"expires_at"`
@@ -43,15 +45,24 @@ type Session struct {
type Controller struct {
config config.Config
statePath string
codePath string
leaseDuration time.Duration
now func() time.Time
state State
}
func New(cfg config.Config) *Controller {
return NewWithCodePath(cfg, "")
}
func NewWithCodePath(cfg config.Config, codePath string) *Controller {
if strings.TrimSpace(codePath) == "" {
codePath = CodePath(cfg.Paths.Data)
}
return &Controller{
config: cfg,
statePath: StatePath(cfg.Paths.Data),
codePath: codePath,
leaseDuration: defaultLease,
now: time.Now,
}
@@ -61,6 +72,10 @@ func StatePath(dataDir string) string {
return filepath.Join(dataDir, stateFileName)
}
func CodePath(dataDir string) string {
return filepath.Join(dataDir, codeFileName)
}
func (c *Controller) Start() (Session, error) {
if c == nil {
return Session{}, fmt.Errorf("Scert-admin 控制器不能为空")
@@ -72,9 +87,11 @@ func (c *Controller) Start() (Session, error) {
if resetURL == "" {
return Session{}, fmt.Errorf("未配置管理页面域名或公网 IP,无法生成密码重置地址")
}
if active, err := IsActive(c.statePath, c.now()); err != nil {
active, err := IsActive(c.statePath, c.now())
if err != nil {
return Session{}, err
} else if active {
}
if active {
return Session{}, fmt.Errorf("密码重置入口已经启用")
}
code, err := generateCode()
@@ -83,10 +100,14 @@ func (c *Controller) Start() (Session, error) {
}
now := c.now().UTC()
c.state = State{
Active: true, ResetURL: resetURL, CodeHash: hashCode(code), ProcessID: os.Getpid(),
Active: true, ResetURL: resetURL, CodeHash: hashCode(code), CodePath: c.codePath, ProcessID: os.Getpid(),
StartedAt: now, ExpiresAt: now.Add(c.leaseDuration),
}
if err := writeCodeFile(c.codePath, code); err != nil {
return Session{}, err
}
if err := writeState(c.statePath, c.state); err != nil {
_ = removeCodeFile(c.codePath)
return Session{}, err
}
return Session{State: c.state, Code: code}, nil
@@ -102,6 +123,7 @@ func (c *Controller) Refresh() error {
}
if !latest.Active || latest.CodeHash != c.state.CodeHash || !c.now().UTC().Before(latest.ExpiresAt) {
c.state.Active = false
_ = removeCodeFile(codePathForState(c.statePath, latest))
return ErrResetSessionClosed
}
c.state = latest
@@ -113,9 +135,14 @@ func (c *Controller) Stop() error {
if c == nil || !c.state.Active {
return nil
}
c.state.Active = false
c.state.ExpiresAt = c.now().UTC()
return writeState(c.statePath, c.state)
state := c.state
state.Active = false
state.ExpiresAt = c.now().UTC()
if err := writeState(c.statePath, state); err != nil {
return err
}
c.state = state
return removeCodeFile(codePathForState(c.statePath, state))
}
func IsActive(path string, now time.Time) (bool, error) {
@@ -126,7 +153,13 @@ func IsActive(path string, now time.Time) (bool, error) {
if err != nil {
return false, err
}
return state.Active && now.UTC().Before(state.ExpiresAt), nil
active := state.Active && now.UTC().Before(state.ExpiresAt)
if !active {
if err := removeCodeFile(codePathForState(path, state)); err != nil {
return false, err
}
}
return active, nil
}
func VerifyCode(path, code string, now time.Time) (State, error) {
@@ -135,6 +168,7 @@ func VerifyCode(path, code string, now time.Time) (State, error) {
return State{}, err
}
if !state.Active || state.CodeHash == "" || !now.UTC().Before(state.ExpiresAt) {
_ = removeCodeFile(codePathForState(path, state))
return State{}, ErrResetSessionClosed
}
expected := hashCode(code)
@@ -150,6 +184,7 @@ func Consume(path string, session State, now time.Time) error {
return err
}
if !latest.Active || latest.CodeHash == "" || !now.UTC().Before(latest.ExpiresAt) {
_ = removeCodeFile(codePathForState(path, latest))
return ErrResetSessionClosed
}
if subtle.ConstantTimeCompare([]byte(latest.CodeHash), []byte(session.CodeHash)) != 1 {
@@ -158,7 +193,10 @@ func Consume(path string, session State, now time.Time) error {
latest.Active = false
latest.CodeHash = ""
latest.ExpiresAt = now.UTC()
return writeState(path, latest)
if err := writeState(path, latest); err != nil {
return err
}
return removeCodeFile(codePathForState(path, latest))
}
func ReadState(path string) (State, error) {
@@ -200,6 +238,56 @@ func writeState(path string, state State) error {
return nil
}
func writeCodeFile(path, code string) error {
if strings.TrimSpace(path) == "" {
return fmt.Errorf("未配置一次性校验码文件路径")
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return fmt.Errorf("创建一次性校验码目录失败:%w", err)
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return fmt.Errorf("创建一次性校验码文件失败:%w", err)
}
success := false
defer func() {
_ = file.Close()
if !success {
_ = os.Remove(path)
}
}()
if err := file.Chmod(0o600); err != nil {
return fmt.Errorf("设置一次性校验码文件权限失败:%w", err)
}
if _, err := file.WriteString(code + "\n"); err != nil {
return fmt.Errorf("写入一次性校验码文件失败:%w", err)
}
if err := file.Sync(); err != nil {
return fmt.Errorf("刷新一次性校验码文件失败:%w", err)
}
if err := protectCodeFile(path); err != nil {
return fmt.Errorf("保护一次性校验码文件失败:%w", err)
}
success = true
return nil
}
func removeCodeFile(path string) error {
if strings.TrimSpace(path) == "" {
return nil
}
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("销毁一次性校验码文件失败:%w", err)
}
return nil
}
func codePathForState(statePath string, state State) string {
if strings.TrimSpace(state.CodePath) != "" {
return state.CodePath
}
return CodePath(filepath.Dir(statePath))
}
func generateCode() (string, error) {
buffer := make([]byte, 10)
if _, err := rand.Read(buffer); err != nil {
+132 -2
View File
@@ -24,10 +24,12 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
unit := activeUnitText(string(data))
for _, required := range []string{
"Documentation=file:///scert/docs/Scert-admin服务管理说明.md",
"Documentation=file:///scert/docs/Scert-admin-service-management.md",
"User=Scert",
"Group=Scert",
"ExecStart=/scert/scert-admin --config /scert/conf/scert.json",
"RuntimeDirectory=scert-admin",
"RuntimeDirectoryMode=0700",
"ExecStart=/scert/scert-admin --config /scert/conf/scert.json --code-output /run/scert-admin/reset-code",
"Restart=no",
"RuntimeMaxSec=30min",
"UMask=0077",
@@ -131,6 +133,109 @@ func TestResetCodeCanOnlyBeConsumedOnce(t *testing.T) {
}
}
func TestControllerWritesAndDestroysProtectedCodeFile(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Web.Hostname = "scert.example.test"
codePath := filepath.Join(t.TempDir(), "runtime", "reset-code")
controller := NewWithCodePath(cfg, codePath)
session, err := controller.Start()
if err != nil {
t.Fatalf("启动密码重置入口失败:%v", err)
}
content, err := os.ReadFile(codePath)
if err != nil {
t.Fatalf("读取受保护校验码文件失败:%v", err)
}
if string(content) != session.Code+"\n" {
t.Fatalf("校验码文件内容错误:%q", string(content))
}
if runtime.GOOS != "windows" {
info, err := os.Stat(codePath)
if err != nil {
t.Fatalf("读取校验码文件属性失败:%v", err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("校验码文件权限错误:%o", info.Mode().Perm())
}
}
if err := controller.Stop(); err != nil {
t.Fatalf("停止密码重置入口失败:%v", err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("停止服务后校验码文件必须销毁,当前错误:%v", err)
}
}
func TestConsumeDestroysCodeFile(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Web.Hostname = "scert.example.test"
codePath := filepath.Join(t.TempDir(), "runtime", "reset-code")
controller := NewWithCodePath(cfg, codePath)
now := time.Date(2026, 8, 28, 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 {
t.Fatalf("校验一次性校验码失败:%v", err)
}
if err := Consume(StatePath(cfg.Paths.Data), verified, now); err != nil {
t.Fatalf("消费一次性校验码失败:%v", err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("校验码消费后文件必须销毁,当前错误:%v", err)
}
}
func TestExpiredLeaseDestroysCodeFile(t *testing.T) {
dataDir := t.TempDir()
statePath := StatePath(dataDir)
codePath := CodePath(dataDir)
if err := writeCodeFile(codePath, "expired-code"); err != nil {
t.Fatalf("创建过期校验码文件失败:%v", err)
}
now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
if err := writeState(statePath, State{Active: true, CodePath: codePath, ExpiresAt: now.Add(-time.Second)}); err != nil {
t.Fatalf("写入过期租约失败:%v", err)
}
active, err := IsActive(statePath, now)
if err != nil || active {
t.Fatalf("过期租约必须失效:active=%t err=%v", active, err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("租约失效后校验码文件必须销毁,当前错误:%v", err)
}
}
func TestControllerDoesNotOverwriteExistingCodeFile(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Web.Hostname = "scert.example.test"
codePath := filepath.Join(t.TempDir(), "runtime", "reset-code")
if err := os.MkdirAll(filepath.Dir(codePath), 0o700); err != nil {
t.Fatalf("创建测试目录失败:%v", err)
}
const existing = "existing-code\n"
if err := os.WriteFile(codePath, []byte(existing), 0o600); err != nil {
t.Fatalf("创建已有校验码文件失败:%v", err)
}
if _, err := NewWithCodePath(cfg, codePath).Start(); err == nil {
t.Fatal("已有校验码文件时不允许覆盖")
}
content, err := os.ReadFile(codePath)
if err != nil {
t.Fatalf("读取已有校验码文件失败:%v", err)
}
if string(content) != existing {
t.Fatalf("已有校验码文件被修改:%q", string(content))
}
}
func activeUnitText(unit string) string {
lines := strings.Split(unit, "\n")
active := make([]string, 0, len(lines))
@@ -143,3 +248,28 @@ func activeUnitText(unit string) string {
}
return strings.Join(active, "\n")
}
func TestConsumeExpiredSessionRemovesCodeFile(t *testing.T) {
baseDir := t.TempDir()
statePath := filepath.Join(baseDir, "state.json")
codePath := filepath.Join(baseDir, "reset-code")
now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
if err := os.WriteFile(codePath, []byte("expired-code\n"), 0o600); err != nil {
t.Fatalf("创建过期校验码文件失败:%v", err)
}
state := State{
Active: true,
CodeHash: hashCode("expired-code"),
CodePath: codePath,
ExpiresAt: now.Add(-time.Second),
}
if err := writeState(statePath, state); err != nil {
t.Fatalf("写入过期会话失败:%v", err)
}
if err := Consume(statePath, state, now); err != ErrResetSessionClosed {
t.Fatalf("消费过期会话应返回关闭错误:%v", err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("消费过期会话后必须销毁校验码文件:%v", err)
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ func TestScertSystemdUnitPolicy(t *testing.T) {
}
unit := activeUnitText(string(data))
for _, required := range []string{
"Documentation=file:///scert/docs/Scert服务管理说明.md",
"Documentation=file:///scert/docs/Scert-service-management.md",
"User=Scert",
"Group=Scert",
"ExecStart=/scert/scert --config /scert/conf/scert.json serve",
+1 -1
View File
@@ -100,7 +100,7 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays)
server := httpapi.New(httpapi.Dependencies{
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, SSHKeys: sshKeys,
SetupDNS: dnsVerification, Firewall: firewall.NewManager(),
SetupDNS: dnsVerification, Secrets: secretStore, Firewall: firewall.NewManager(),
IssueCertificate: workflow.IssueForHTTP,
IssueSetupCertificate: func(ctx context.Context, request certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
return certificates.IssueForSetup(ctx, request)
+30 -16
View File
@@ -28,11 +28,30 @@ func (u *AccountUser) GetRegistration() *acme.ExtendedAccount { return u.Registr
func (u *AccountUser) GetPrivateKey() crypto.Signer { return u.PrivateKey }
type LegoIssuer struct {
User *AccountUser
Provider challenge.Provider
Environment string
HTTPClient *http.Client
Now func() time.Time
User *AccountUser
Provider challenge.Provider
Environment string
PropagationTimeout time.Duration
PropagationInterval time.Duration
HTTPClient *http.Client
Now func() time.Time
}
type propagationProvider struct {
challenge.Provider
timeout time.Duration
interval time.Duration
}
func (p propagationProvider) Timeout() (time.Duration, time.Duration) {
return p.timeout, p.interval
}
func withPropagationSettings(provider challenge.Provider, timeout, interval time.Duration) challenge.Provider {
if provider == nil || timeout <= 0 || interval <= 0 || interval > timeout {
return provider
}
return propagationProvider{Provider: provider, timeout: timeout, interval: interval}
}
func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resource, error) {
@@ -66,7 +85,8 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
if err != nil {
return Resource{}, fmt.Errorf("创建 ACME 客户端失败:%w", err)
}
if err := client.Challenge.SetDNS01Provider(i.Provider); err != nil {
provider := withPropagationSettings(i.Provider, i.PropagationTimeout, i.PropagationInterval)
if err := client.Challenge.SetDNS01Provider(provider); err != nil {
return Resource{}, fmt.Errorf("配置 DNS-01 验证失败:%w", err)
}
if i.User.Registration == nil {
@@ -77,11 +97,14 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
i.User.Registration = account
}
issued, err := client.Certificate.Obtain(ctx, legoCertificate.ObtainRequest{
Domains: domains, EmailAddresses: nonEmptyEmail(request.AccountEmail, i.User.Email),
Domains: domains,
KeyType: certcrypto.RSA2048, Bundle: true,
PreferredChain: request.PreferredChain,
})
if err != nil {
if i.PropagationTimeout > 0 && i.PropagationInterval > 0 && i.PropagationInterval <= i.PropagationTimeout {
return Resource{}, fmt.Errorf("申请证书失败(DNS 传播等待时间 %s,检测间隔 %s):%w", i.PropagationTimeout, i.PropagationInterval, err)
}
return Resource{}, fmt.Errorf("申请证书失败:%w", err)
}
resource := Resource{
@@ -93,12 +116,3 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
}
return ValidateResource(resource)
}
func nonEmptyEmail(values ...string) []string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return []string{strings.TrimSpace(value)}
}
}
return nil
}
+74
View File
@@ -0,0 +1,74 @@
package certificate
import (
"context"
"testing"
"time"
"github.com/go-acme/lego/v5/challenge"
)
type propagationTestProvider struct {
present bool
cleanup bool
}
func (p *propagationTestProvider) Present(context.Context, string, string, string) error {
p.present = true
return nil
}
func (p *propagationTestProvider) CleanUp(context.Context, string, string, string) error {
p.cleanup = true
return nil
}
func TestWithPropagationSettingsProvidesConfiguredTimeout(t *testing.T) {
base := &propagationTestProvider{}
timeout := 15 * time.Minute
interval := 10 * time.Second
wrapped := withPropagationSettings(base, timeout, interval)
provider, ok := wrapped.(challenge.ProviderTimeout)
if !ok {
t.Fatal("DNS Provider 未实现传播等待配置接口")
}
actualTimeout, actualInterval := provider.Timeout()
if actualTimeout != timeout || actualInterval != interval {
t.Fatalf("DNS 传播参数不正确:timeout=%s interval=%s", actualTimeout, actualInterval)
}
if err := wrapped.Present(context.Background(), "example.com", "token", "key-auth"); err != nil {
t.Fatalf("Provider Present 转发失败:%v", err)
}
if err := wrapped.CleanUp(context.Background(), "example.com", "token", "key-auth"); err != nil {
t.Fatalf("Provider CleanUp 转发失败:%v", err)
}
if !base.present || !base.cleanup {
t.Fatal("包装器未正确转发 Provider 操作")
}
}
func TestWithPropagationSettingsPreservesProviderForInvalidValues(t *testing.T) {
base := &propagationTestProvider{}
cases := []struct {
name string
timeout time.Duration
interval time.Duration
}{
{name: "zero timeout", timeout: 0, interval: time.Second},
{name: "zero interval", timeout: time.Minute, interval: 0},
{name: "interval exceeds timeout", timeout: time.Second, interval: time.Minute},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
if got := withPropagationSettings(base, item.timeout, item.interval); got != base {
t.Fatal("无效 DNS 传播参数不应替换原 Provider")
}
})
}
}
func TestWithPropagationSettingsPreservesNilProvider(t *testing.T) {
if got := withPropagationSettings(nil, time.Minute, time.Second); got != nil {
t.Fatal("空 Provider 应保持为空")
}
}
+7 -1
View File
@@ -75,7 +75,13 @@ func NewService(cfg config.Config, repository DomainStateRepository, credentials
config: cfg, repository: repository, credentials: credentials, providers: providers, accounts: accounts,
store: FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup},
newIssuer: func(user *AccountUser, provider challenge.Provider, environment string) Issuer {
return &LegoIssuer{User: user, Provider: provider, Environment: environment}
return &LegoIssuer{
User: user,
Provider: provider,
Environment: environment,
PropagationTimeout: time.Duration(cfg.ACME.PropagationTimeoutSecs) * time.Second,
PropagationInterval: time.Duration(cfg.ACME.PropagationPollingIntervalSecs) * time.Second,
}
},
}
}
@@ -18,6 +18,7 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
)
type serviceRepository struct {
@@ -53,6 +54,17 @@ func (serviceProviderFactory) Create(string, map[string]string) (challenge.Provi
return serviceProvider{}, nil
}
type recordingProviderFactory struct {
providerID string
credentials map[string]string
}
func (f *recordingProviderFactory) Create(providerID string, credentials map[string]string) (challenge.Provider, error) {
f.providerID = providerID
f.credentials = credentials
return serviceProvider{}, nil
}
type serviceAccounts struct{}
func (serviceAccounts) LoadOrCreate(context.Context, string, string) (*AccountUser, error) {
@@ -262,3 +274,49 @@ func TestServiceIssuesSetupCertificateWithTypedLayout(t *testing.T) {
}
}
}
func TestServiceDecryptsCredentialReferenceBeforeCreatingProvider(t *testing.T) {
root := t.TempDir()
cfg := certificateTestConfig(root)
store, err := secretstore.Open(cfg.Paths.Config)
if err != nil {
t.Fatalf("打开敏感信息存储失败:%v", err)
}
credentialRef := "secret://dns/cloudflare/service-test"
if err := store.Put(context.Background(), credentialRef, map[string]string{
"api_token": "test-dns-token",
}); err != nil {
t.Fatalf("保存测试 DNS 凭据失败:%v", err)
}
cfg.DNS.CredentialRef = credentialRef
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare")
if err != nil {
t.Fatal(err)
}
repository := &serviceRepository{item: item}
factory := &recordingProviderFactory{}
issuer := &serviceIssuer{resource: testResource(t, "example.com")}
service := NewService(cfg, repository, store, factory, serviceAccounts{})
service.newIssuer = func(*AccountUser, challenge.Provider, string) Issuer { return issuer }
if _, err := service.Issue(context.Background(), item.ID); err != nil {
t.Fatalf("使用加密凭据引用申请证书失败:%v", err)
}
if factory.providerID != "cloudflare" || factory.credentials["api_token"] != "test-dns-token" {
t.Fatalf("创建 DNS Provider 时未正确解密凭据:provider=%q credentials=%v", factory.providerID, factory.credentials)
}
}
func TestNewServiceInjectsPropagationSettings(t *testing.T) {
cfg := certificateTestConfig(t.TempDir())
cfg.ACME.PropagationTimeoutSecs = 1200
cfg.ACME.PropagationPollingIntervalSecs = 15
service := NewService(cfg, nil, nil, nil, nil)
issuer, ok := service.newIssuer(&AccountUser{}, serviceProvider{}, "staging").(*LegoIssuer)
if !ok {
t.Fatal("创建的 Issuer 类型不正确")
}
if issuer.PropagationTimeout != 1200*time.Second || issuer.PropagationInterval != 15*time.Second {
t.Fatalf("DNS 传播参数注入不正确:timeout=%s interval=%s", issuer.PropagationTimeout, issuer.PropagationInterval)
}
}
+341
View File
@@ -0,0 +1,341 @@
package cli
import (
"context"
"database/sql"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/database"
)
// backupMySQL 将 MySQL 的表结构和数据导出为可在 MySQL 5.7/8.0 导入的 SQL 文件。
func backupMySQL(ctx context.Context, cfg config.Config, output string) error {
db, err := database.Open(ctx, cfg.Database)
if err != nil {
return fmt.Errorf("打开 MySQL 备份连接失败:%w", err)
}
defer db.Close()
temporaryPath := output + ".tmp"
file, err := os.OpenFile(temporaryPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return fmt.Errorf("创建 MySQL 备份文件失败:%w", err)
}
removeTemporary := true
defer func() {
_ = file.Close()
if removeTemporary {
_ = os.Remove(temporaryPath)
}
}()
if _, err := fmt.Fprintf(file, "-- Scert MySQL 数据备份\n-- 生成时间:%s\n\nSET FOREIGN_KEY_CHECKS=0;\n\n", time.Now().UTC().Format(time.RFC3339)); err != nil {
return fmt.Errorf("写入 MySQL 备份头失败:%w", err)
}
rows, err := db.DB.QueryContext(ctx, "SHOW TABLES")
if err != nil {
return fmt.Errorf("读取 MySQL 表列表失败:%w", err)
}
var tableNames []string
for rows.Next() {
var tableName string
if err := rows.Scan(&tableName); err != nil {
_ = rows.Close()
return fmt.Errorf("读取 MySQL 表名失败:%w", err)
}
tableNames = append(tableNames, tableName)
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return fmt.Errorf("遍历 MySQL 表列表失败:%w", err)
}
if err := rows.Close(); err != nil {
return fmt.Errorf("关闭 MySQL 表列表失败:%w", err)
}
for _, tableName := range tableNames {
if err := dumpMySQLTable(ctx, db.DB, file, tableName); err != nil {
return err
}
}
if _, err := fmt.Fprint(file, "SET FOREIGN_KEY_CHECKS=1;\n"); err != nil {
return fmt.Errorf("写入 MySQL 备份尾失败:%w", err)
}
if err := file.Close(); err != nil {
return fmt.Errorf("关闭 MySQL 备份文件失败:%w", err)
}
if err := os.Chmod(temporaryPath, 0o600); err != nil {
return fmt.Errorf("设置 MySQL 备份文件权限失败:%w", err)
}
if err := os.Rename(temporaryPath, output); err != nil {
return fmt.Errorf("保存 MySQL 备份文件失败:%w", err)
}
removeTemporary = false
return nil
}
// createMySQLRestoreBackup 在恢复前保留目标数据库快照,供失败时回滚使用。
// 快照目录不会在恢复成功后自动删除,便于管理员在需要时继续排查或手动恢复。
func createMySQLRestoreBackup(ctx context.Context, cfg config.Config) (string, error) {
backupRoot := filepath.Clean(strings.TrimSpace(cfg.Paths.Backup))
if backupRoot == "." || backupRoot == "" {
return "", fmt.Errorf("MySQL 恢复前备份目录不能为空")
}
if err := os.MkdirAll(backupRoot, 0o700); err != nil {
return "", fmt.Errorf("创建 MySQL 恢复前备份目录失败:%w", err)
}
info, err := os.Lstat(backupRoot)
if err != nil {
return "", fmt.Errorf("检查 MySQL 恢复前备份目录失败:%w", err)
}
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return "", fmt.Errorf("MySQL 恢复前备份目录必须是普通目录")
}
if err := os.Chmod(backupRoot, 0o700); err != nil {
return "", fmt.Errorf("设置 MySQL 恢复前备份目录权限失败:%w", err)
}
rollbackDirectory, err := os.MkdirTemp(backupRoot, "scert-before-restore-")
if err != nil {
return "", fmt.Errorf("创建 MySQL 恢复快照目录失败:%w", err)
}
rollbackPath := filepath.Join(rollbackDirectory, "scert.sql")
if err := backupMySQL(ctx, cfg, rollbackPath); err != nil {
return "", fmt.Errorf("创建 MySQL 恢复前快照失败:%w", err)
}
return rollbackPath, nil
}
func dumpMySQLTable(ctx context.Context, db *sql.DB, output *os.File, tableName string) error {
quotedTable := quoteMySQLIdentifier(tableName)
var name, createSQL string
if err := db.QueryRowContext(ctx, "SHOW CREATE TABLE "+quotedTable).Scan(&name, &createSQL); err != nil {
return fmt.Errorf("读取 MySQL 表结构失败(%s):%w", tableName, err)
}
if _, err := fmt.Fprintf(output, "DROP TABLE IF EXISTS %s;\n%s;\n\n", quotedTable, createSQL); err != nil {
return fmt.Errorf("写入 MySQL 表结构失败(%s):%w", tableName, err)
}
rows, err := db.QueryContext(ctx, "SELECT * FROM "+quotedTable)
if err != nil {
return fmt.Errorf("读取 MySQL 表数据失败(%s):%w", tableName, err)
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return fmt.Errorf("读取 MySQL 表字段失败(%s):%w", tableName, err)
}
for rows.Next() {
values := make([]any, len(columns))
pointers := make([]any, len(columns))
for index := range values {
pointers[index] = &values[index]
}
if err := rows.Scan(pointers...); err != nil {
return fmt.Errorf("读取 MySQL 表行失败(%s):%w", tableName, err)
}
literals := make([]string, len(values))
for index, value := range values {
literals[index] = mysqlSQLLiteral(value)
}
if _, err := fmt.Fprintf(output, "INSERT INTO %s (%s) VALUES (%s);\n", quotedTable, quoteMySQLColumns(columns), strings.Join(literals, ", ")); err != nil {
return fmt.Errorf("写入 MySQL 表数据失败(%s):%w", tableName, err)
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("遍历 MySQL 表数据失败(%s):%w", tableName, err)
}
_, err = fmt.Fprintln(output)
return err
}
func quoteMySQLIdentifier(value string) string {
return "`" + strings.ReplaceAll(value, "`", "``") + "`"
}
func quoteMySQLColumns(columns []string) string {
quoted := make([]string, len(columns))
for index, column := range columns {
quoted[index] = quoteMySQLIdentifier(column)
}
return strings.Join(quoted, ", ")
}
func mysqlSQLLiteral(value any) string {
switch typed := value.(type) {
case nil:
return "NULL"
case sql.RawBytes:
return "X'" + hex.EncodeToString(typed) + "'"
case []byte:
return "X'" + hex.EncodeToString(typed) + "'"
case string:
return mysqlStringLiteral(typed)
case time.Time:
return "'" + typed.UTC().Format("2006-01-02 15:04:05.999999") + "'"
case bool:
if typed {
return "1"
}
return "0"
case int64:
return strconv.FormatInt(typed, 10)
case uint64:
return strconv.FormatUint(typed, 10)
case float64:
return strconv.FormatFloat(typed, 'g', -1, 64)
case float32:
return strconv.FormatFloat(float64(typed), 'g', -1, 32)
default:
return mysqlStringLiteral(fmt.Sprint(typed))
}
}
func mysqlStringLiteral(value string) string {
var builder strings.Builder
builder.Grow(len(value) + 2)
builder.WriteByte('\'')
for index := 0; index < len(value); index++ {
switch value[index] {
case '\\':
builder.WriteString(`\\`)
case '\x00':
builder.WriteString(`\0`)
case '\n':
builder.WriteString(`\n`)
case '\r':
builder.WriteString(`\r`)
case '\x1a':
builder.WriteString(`\Z`)
case '\'':
builder.WriteString(`''`)
default:
builder.WriteByte(value[index])
}
}
builder.WriteByte('\'')
return builder.String()
}
// restoreMySQL 执行 Scert 生成的 MySQL SQL 备份。
func restoreMySQL(ctx context.Context, cfg config.Config, input string) error {
script, err := os.ReadFile(input)
if err != nil {
return fmt.Errorf("读取 MySQL 备份文件失败:%w", err)
}
db, err := database.Open(ctx, cfg.Database)
if err != nil {
return fmt.Errorf("打开 MySQL 恢复连接失败:%w", err)
}
defer db.Close()
for _, statement := range splitMySQLStatements(string(script)) {
if _, err := db.DB.ExecContext(ctx, statement); err != nil {
return fmt.Errorf("执行 MySQL 恢复语句失败:%w", err)
}
}
return nil
}
func splitMySQLStatements(script string) []string {
var statements []string
var statement strings.Builder
var quote byte
lineComment := false
blockComment := false
executableComment := false
escaped := false
flush := func() {
value := strings.TrimSpace(statement.String())
if value != "" {
statements = append(statements, value)
}
statement.Reset()
}
for index := 0; index < len(script); index++ {
current := script[index]
if lineComment {
if current == '\n' {
lineComment = false
statement.WriteByte('\n')
}
continue
}
if blockComment {
if current == '*' && index+1 < len(script) && script[index+1] == '/' {
blockComment = false
index++
statement.WriteByte(' ')
}
continue
}
if executableComment {
statement.WriteByte(current)
if current == '*' && index+1 < len(script) && script[index+1] == '/' {
statement.WriteByte(script[index+1])
index++
executableComment = false
}
continue
}
if quote != 0 {
statement.WriteByte(current)
if escaped {
escaped = false
continue
}
if current == '\\' {
escaped = true
continue
}
if current == quote {
if index+1 < len(script) && script[index+1] == quote {
statement.WriteByte(script[index+1])
index++
continue
}
quote = 0
}
continue
}
if current == '\'' || current == '"' || current == '`' {
quote = current
statement.WriteByte(current)
continue
}
if current == '#' {
lineComment = true
continue
}
if current == '-' && index+2 < len(script) && script[index+1] == '-' && (script[index+2] == ' ' || script[index+2] == '\t' || script[index+2] == '\n') {
lineComment = true
index++
continue
}
if current == '/' && index+1 < len(script) && script[index+1] == '*' {
if index+2 < len(script) && (script[index+2] == '!' || script[index+2] == '+') {
statement.WriteByte(current)
statement.WriteByte(script[index+1])
index++
executableComment = true
continue
}
blockComment = true
index++
continue
}
if current == ';' {
flush()
continue
}
statement.WriteByte(current)
}
flush()
return statements
}
+63
View File
@@ -0,0 +1,63 @@
package cli
import (
"database/sql"
"strings"
"testing"
)
func TestQuoteMySQLIdentifierEscapesBackticks(t *testing.T) {
if value := quoteMySQLIdentifier("a`b"); value != "`a``b`" {
t.Fatalf("MySQL 标识符转义不正确:%s", value)
}
}
func TestMySQLSQLLiteral(t *testing.T) {
cases := []struct {
name string
value any
want string
}{
{name: "null", value: nil, want: "NULL"},
{name: "string", value: "a'b\\c\n\x00\x1a", want: "'a''b\\\\c\\n\\0\\Z'"},
{name: "binary", value: []byte{0x01, 0xaf}, want: "X'01af'"},
{name: "raw bytes", value: sql.RawBytes{0x00, 0xff}, want: "X'00ff'"},
{name: "integer", value: int64(42), want: "42"},
{name: "boolean", value: true, want: "1"},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
if value := mysqlSQLLiteral(item.value); value != item.want {
t.Fatalf("SQL 字面量不正确:%s", value)
}
})
}
}
func TestQuoteMySQLColumns(t *testing.T) {
value := quoteMySQLColumns([]string{"id", "display_name"})
if value != "`id`, `display_name`" || strings.Contains(value, "'") {
t.Fatalf("MySQL 字段列表不正确:%s", value)
}
}
func TestSplitMySQLStatementsKeepsQuotedSemicolons(t *testing.T) {
script := "-- 注释\nSET FOREIGN_KEY_CHECKS=0;\nINSERT INTO `items` (`value`) VALUES ('a; b'), ('it''s');\n"
statements := splitMySQLStatements(script)
if len(statements) != 2 {
t.Fatalf("SQL 语句拆分数量不正确:%d %#v", len(statements), statements)
}
if strings.Contains(statements[0], "注释") || !strings.Contains(statements[1], "'a; b'") || !strings.Contains(statements[1], "'it''s'") {
t.Fatalf("SQL 语句拆分内容不正确:%#v", statements)
}
}
func TestSplitMySQLStatementsKeepsExecutableComments(t *testing.T) {
script := "CREATE TABLE `items` (`id` bigint) /*!50100 SET @value = 'a;b' */;\n"
statements := splitMySQLStatements(script)
if len(statements) != 1 {
t.Fatalf("带可执行注释的 SQL 语句拆分数量不正确:%d %#v", len(statements), statements)
}
if !strings.Contains(statements[0], "/*!50100 SET @value = 'a;b' */") {
t.Fatalf("MySQL 可执行注释不应被删除:%s", statements[0])
}
}
+53 -3
View File
@@ -270,7 +270,7 @@ func newBackupCommand() *cobra.Command {
var output string
command := &cobra.Command{
Use: "backup",
Short: "备份配置和 SQLite 数据库",
Short: "备份配置和数据库",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
@@ -294,6 +294,11 @@ func newBackupCommand() *cobra.Command {
return err
}
}
if cfg.Database.Driver == "mysql" {
if err := backupMySQL(cmd.Context(), cfg, filepath.Join(output, "scert.sql")); err != nil {
return err
}
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "备份已创建:%s\n", output)
return err
},
@@ -306,7 +311,7 @@ func newRestoreCommand() *cobra.Command {
var input string
command := &cobra.Command{
Use: "restore",
Short: "恢复 SQLite 数据库备份",
Short: "恢复配置和数据库备份",
RunE: func(cmd *cobra.Command, args []string) error {
input, err := validateRestoreInput(input)
if err != nil {
@@ -319,16 +324,24 @@ func newRestoreCommand() *cobra.Command {
}
currentPath := filepath.Clean(resolveConfigPath())
_, currentConfigErr := config.Load(currentPath)
currentConfig, currentConfigErr := config.Load(currentPath)
if currentConfigErr != nil && !errors.Is(currentConfigErr, os.ErrNotExist) {
return fmt.Errorf("读取当前配置失败:%w", currentConfigErr)
}
if currentConfigErr == nil && currentConfig.Database.Driver != cfg.Database.Driver {
return fmt.Errorf("备份数据库类型(%s)与当前配置数据库类型(%s)不一致,拒绝恢复", cfg.Database.Driver, currentConfig.Database.Driver)
}
if info, statErr := os.Stat(currentPath); statErr == nil && !info.Mode().IsRegular() {
return errors.New("当前配置路径不是普通文件")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return fmt.Errorf("检查当前配置失败:%w", statErr)
}
mysqlSource := filepath.Join(input, "scert.sql")
if cfg.Database.Driver == "mysql" && !isRegularFile(mysqlSource) {
return errors.New("MySQL 备份目录缺少有效的 scert.sql 文件")
}
databaseSource := filepath.Join(input, "scert.db")
databaseSourceInfo, databaseSourceErr := os.Stat(databaseSource)
databaseSourceExists := databaseSourceErr == nil
@@ -338,6 +351,9 @@ func newRestoreCommand() *cobra.Command {
if databaseSourceExists && !databaseSourceInfo.Mode().IsRegular() {
return errors.New("备份数据库不是普通文件")
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && !databaseSourceExists {
return errors.New("SQLite 备份目录缺少有效的 scert.db 文件")
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists {
if samePath(databaseSource, cfg.Database.DSN) {
return errors.New("备份数据库与当前数据库路径相同")
@@ -368,6 +384,14 @@ func newRestoreCommand() *cobra.Command {
}
}
mysqlBackupPath := ""
if cfg.Database.Driver == "mysql" {
mysqlBackupPath, err = createMySQLRestoreBackup(cmd.Context(), cfg)
if err != nil {
return err
}
}
if err := cfg.Save(currentPath); err != nil {
return err
}
@@ -382,6 +406,20 @@ func newRestoreCommand() *cobra.Command {
return fmt.Errorf("恢复 SQLite 数据库失败:%w", err)
}
}
if cfg.Database.Driver == "mysql" {
if err := restoreMySQL(cmd.Context(), cfg, mysqlSource); err != nil {
restoreFailure := fmt.Errorf("恢复 MySQL 数据库失败:%w", err)
if mysqlBackupPath != "" {
if rollbackErr := restoreMySQL(cmd.Context(), cfg, mysqlBackupPath); rollbackErr != nil {
restoreFailure = fmt.Errorf("%w;MySQL 数据库回滚失败:%v", restoreFailure, rollbackErr)
}
}
if configBackupPath != "" {
_ = copyFile(configBackupPath, currentPath, 0o600)
}
return restoreFailure
}
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "恢复已完成:%s\n", input)
return err
},
@@ -483,6 +521,18 @@ func setConfigValue(cfg *config.Config, key, value string) error {
return fmt.Errorf("续期阈值格式无效:%w", err)
}
cfg.ACME.RenewalThresholdDays = parsed
case "acme.propagation_timeout_secs":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("DNS 传播等待时间格式无效:%w", err)
}
cfg.ACME.PropagationTimeoutSecs = parsed
case "acme.propagation_polling_interval_secs":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("DNS 传播检测间隔格式无效:%w", err)
}
cfg.ACME.PropagationPollingIntervalSecs = parsed
case "dns.provider":
cfg.DNS.Provider = value
case "dns.credential_ref":
+9
View File
@@ -50,6 +50,15 @@ func TestSetConfigValueUpdatesAndValidatesAllowedFields(t *testing.T) {
if cfg.Notification.HTTPLoginPath != "/api/login" {
t.Fatalf("HTTP 登录路径未更新:%s", cfg.Notification.HTTPLoginPath)
}
if err := setConfigValue(&cfg, "acme.propagation_timeout_secs", "1200"); err != nil {
t.Fatal(err)
}
if err := setConfigValue(&cfg, "acme.propagation_polling_interval_secs", "15"); err != nil {
t.Fatal(err)
}
if cfg.ACME.PropagationTimeoutSecs != 1200 || cfg.ACME.PropagationPollingIntervalSecs != 15 {
t.Fatalf("DNS 传播参数未更新:%+v", cfg.ACME)
}
if err := setConfigValue(&cfg, "admin.password_hash", "plain"); err == nil {
t.Fatal("不应允许直接修改密码摘要")
}
+128 -6
View File
@@ -22,8 +22,10 @@ import (
"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/dnsprovider"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup"
)
@@ -159,15 +161,21 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
return err
}
}
cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
if err != nil {
return err
}
if err := setup.Apply(&cfg, input); err != nil {
cleanupSecret()
return err
}
firewallResult, err := saveSetupWithFirewall(cmd.Context(), cfg, path, firewallManager)
if err != nil {
cleanupSecret()
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "初始化配置已保存:%s\n", path)
fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已标记为验证通过;真实 provider 连通性测试和 Web 证书申请将在后续任务接入。\n")
fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已完成在线验证,凭据已加密保存;真实 Web 证书申请将在后续任务接入。\n")
fmt.Fprintf(cmd.OutOrStdout(), "本机防火墙:%s\n", firewallResult.Message)
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL())
return nil
@@ -195,8 +203,8 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
command.Flags().IntVar(&emailRetryCount, "email-retry-count", 3, "通知失败重试次数")
command.Flags().StringVar(&emailRetryIntervals, "email-retry-intervals", "30,120,600", "通知重试间隔(秒,逗号分隔)")
command.Flags().StringVar(&dnsProvider, "dns-provider", "", "DNS API 服务商标识")
command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用,不保存明文密钥")
command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过外部验证测试")
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", "", "管理页面域名")
command.Flags().StringVar(&webPublicIP, "web-public-ip", "", "没有域名时使用的公网 IP")
@@ -267,15 +275,15 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
return err
}
value.EmailRecipients = splitValues(receiver)
value.DNSProvider, err = ask(reader, output, "DNS API 服务商 *", "")
value.DNSProvider, err = askDNSProvider(reader, output)
if err != nil {
return err
}
value.DNSCredentialRef, err = ask(reader, output, "DNS 凭据引用 *(不要输入明文密钥)", "")
value.DNSCredentials, err = askDNSCredentials(reader, output, value.DNSProvider)
if err != nil {
return err
}
value.DNSVerified, err = askYesNo(reader, output, "DNS API 是否已经完成验证测试?", false)
value.DNSTestDomain, err = ask(reader, output, "DNS 权限测试域名 *", "")
if err != nil {
return err
}
@@ -297,6 +305,120 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
return err
}
func askDNSCredentials(reader *bufio.Reader, output io.Writer, providerID string) (map[string]string, error) {
descriptor, err := dnsprovider.GetDescriptor(providerID)
if err != nil {
return nil, err
}
credentials := make(map[string]string, len(descriptor.CredentialFields))
fmt.Fprintln(output, "请输入 DNS API 凭据。输入内容会在当前配置过程中明文显示,提交后只保存加密内容。")
for _, field := range descriptor.CredentialFields {
label := field.Label
if field.Required {
label += " *"
}
value, err := ask(reader, output, label, "")
if err != nil {
return nil, err
}
if strings.TrimSpace(value) != "" {
credentials[field.Name] = value
}
}
return credentials, nil
}
func prepareDNSCredentials(ctx context.Context, cfg config.Config, input *setup.Input, output io.Writer) (func(), error) {
if input == nil {
return func() {}, errors.New("初始化输入不能为空")
}
if strings.TrimSpace(input.DNSCredentialRef) != "" {
return func() {}, nil
}
if len(input.DNSCredentials) == 0 {
return func() {}, errors.New("DNS 凭据不能为空")
}
if strings.TrimSpace(input.DNSTestDomain) == "" {
return func() {}, errors.New("DNS 权限测试域名不能为空")
}
store, err := secretstore.Open(cfg.Paths.Config)
if err != nil {
return func() {}, fmt.Errorf("初始化 DNS 凭据存储失败:%w", err)
}
manager := setup.NewDNSVerificationManager(
dnsprovider.NewTester(dnsprovider.NewLegoFactory()),
store,
)
return prepareDNSCredentialsWithManager(ctx, input, output, manager, store)
}
func prepareDNSCredentialsWithManager(ctx context.Context, input *setup.Input, output io.Writer, manager *setup.DNSVerificationManager, store *secretstore.Store) (func(), error) {
if input == nil {
return func() {}, errors.New("初始化输入不能为空")
}
if manager == nil || store == nil {
return func() {}, errors.New("DNS 凭据验证服务未初始化")
}
if strings.TrimSpace(input.DNSCredentialRef) != "" {
return func() {}, nil
}
if len(input.DNSCredentials) == 0 {
return func() {}, errors.New("DNS 凭据不能为空")
}
if strings.TrimSpace(input.DNSTestDomain) == "" {
return func() {}, errors.New("DNS 权限测试域名不能为空")
}
testContext, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
result, err := manager.Verify(testContext, setup.DNSVerificationInput{
ProviderID: input.DNSProvider,
TestDomain: input.DNSTestDomain,
Credentials: input.DNSCredentials,
})
if err != nil {
return func() {}, fmt.Errorf("DNS API 在线验证失败:%w", err)
}
input.DNSCredentialRef = result.CredentialRef
input.DNSVerified = true
input.DNSCredentials = nil
fmt.Fprintf(output, "DNS API 在线验证通过,凭据已加密保存,有效期至 %s。\n", result.ExpiresAt.Local().Format("2006-01-02 15:04:05"))
return func() {
cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cleanupCancel()
_ = store.Delete(cleanupContext, result.CredentialRef)
}, nil
}
func askDNSProvider(reader *bufio.Reader, output io.Writer) (string, error) {
providers := dnsprovider.Descriptors()
fmt.Fprintln(output, "请选择 DNS API 服务商:")
for index, provider := range providers {
status := ""
if !provider.Available {
status = "(暂未开放)"
}
fmt.Fprintf(output, "%d. %s%s\n", index+1, provider.Name, status)
}
for {
value, err := ask(reader, output, "请输入编号", "")
if err != nil {
return "", err
}
index, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || index < 1 || index > len(providers) {
fmt.Fprintln(output, "编号无效,请重新输入。")
continue
}
provider := providers[index-1]
if !provider.Available {
fmt.Fprintf(output, "%s 当前暂未开放,请选择其他服务商。\n", provider.Name)
continue
}
return provider.ID, nil
}
}
func ask(reader *bufio.Reader, output io.Writer, label, defaultValue string) (string, error) {
if defaultValue != "" {
fmt.Fprintf(output, "%s [%s]:", label, defaultValue)
+85
View File
@@ -1,6 +1,7 @@
package cli
import (
"bufio"
"bytes"
"context"
"errors"
@@ -12,7 +13,10 @@ 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/dnsprovider"
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup"
)
type cliFakeFirewallManager struct {
@@ -164,6 +168,36 @@ func TestInitCommandDoesNotExposeResetServicePort(t *testing.T) {
}
}
func TestAskDNSProviderUsesNumberedSelection(t *testing.T) {
var output bytes.Buffer
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("99\n2\n")), &output)
if err != nil {
t.Fatalf("DNS 服务商选择失败:%v", err)
}
if provider != "aliyun" {
t.Fatalf("编号 2 应选择阿里云 DNS,实际为:%s", provider)
}
if !strings.Contains(output.String(), "1. Cloudflare") || !strings.Contains(output.String(), "2. 阿里云 DNS") {
t.Fatalf("DNS 服务商列表未按编号显示:%s", output.String())
}
if !strings.Contains(output.String(), "编号无效,请重新输入。") {
t.Fatalf("无效编号未提示重新输入:%s", output.String())
}
}
func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) {
var output bytes.Buffer
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("4\n1\n")), &output)
if err != nil {
t.Fatalf("DNS 服务商选择失败:%v", err)
}
if provider != "cloudflare" {
t.Fatalf("重新选择后应返回 Cloudflare,实际为:%s", provider)
}
if !strings.Contains(output.String(), "当前暂未开放") {
t.Fatalf("选择未开放服务商时未给出提示:%s", output.String())
}
}
func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
baseDir := t.TempDir()
blockedParent := filepath.Join(baseDir, "blocked")
@@ -197,3 +231,54 @@ func TestSaveSetupWithFirewallReportsRollbackFailure(t *testing.T) {
t.Fatalf("防火墙回滚失败应返回明确错误:%v", err)
}
}
type cliFakeDNSCredentialTester struct {
credentials map[string]string
}
func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) error {
f.credentials = credentials
return nil
}
func TestPrepareDNSCredentialsEncryptsAndClearsInput(t *testing.T) {
configDir := t.TempDir()
store, err := secretstore.Open(configDir)
if err != nil {
t.Fatalf("打开敏感信息存储失败:%v", err)
}
tester := &cliFakeDNSCredentialTester{}
manager := setup.NewDNSVerificationManager(tester, store)
input := &setup.Input{
DNSProvider: dnsprovider.Cloudflare,
DNSCredentials: map[string]string{"api_token": "test-dns-token"},
DNSTestDomain: "example.com",
}
var output bytes.Buffer
cleanup, err := prepareDNSCredentialsWithManager(context.Background(), input, &output, manager, store)
if err != nil {
t.Fatalf("准备 DNS 凭据失败:%v", err)
}
if input.DNSCredentialRef == "" || !input.DNSVerified || input.DNSCredentials != nil {
t.Fatalf("DNS 凭据输入状态不正确:%+v", input)
}
if tester.credentials["api_token"] != "test-dns-token" {
t.Fatalf("在线验证未收到凭据:%v", tester.credentials)
}
content, err := os.ReadFile(filepath.Join(configDir, "secrets.json"))
if err != nil {
t.Fatalf("读取敏感信息文件失败:%v", err)
}
if strings.Contains(string(content), "test-dns-token") || strings.Contains(output.String(), "test-dns-token") {
t.Fatal("DNS 凭据不应以明文写入文件或输出")
}
value, err := store.Get(context.Background(), input.DNSCredentialRef)
if err != nil || value["api_token"] != "test-dns-token" {
t.Fatalf("加密凭据解密结果不正确:value=%v err=%v", value, err)
}
cleanup()
exists, err := store.Has(context.Background(), input.DNSCredentialRef)
if err != nil || exists {
t.Fatalf("保存失败清理后凭据引用仍存在:exists=%t err=%v", exists, err)
}
}
+92 -14
View File
@@ -7,8 +7,10 @@ import (
"net/mail"
"net/url"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
)
@@ -72,10 +74,12 @@ type PathsConfig struct {
}
type ACMEConfig struct {
CA string `json:"ca"`
Environment string `json:"environment"`
AccountEmail string `json:"account_email"`
RenewalThresholdDays int `json:"renewal_threshold_days"`
CA string `json:"ca"`
Environment string `json:"environment"`
AccountEmail string `json:"account_email"`
RenewalThresholdDays int `json:"renewal_threshold_days"`
PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
}
type DNSConfig struct {
@@ -119,8 +123,14 @@ func Default(baseDir string) Config {
MaxOpenConns: 4, MaxIdleConns: 2, ConnMaxLifetimeMins: 30,
},
Paths: paths,
ACME: ACMEConfig{CA: "letsencrypt", Environment: "staging", RenewalThresholdDays: 6},
DNS: DNSConfig{VerificationState: "not_configured"},
ACME: ACMEConfig{
CA: "letsencrypt",
Environment: "staging",
RenewalThresholdDays: 6,
PropagationTimeoutSecs: 900,
PropagationPollingIntervalSecs: 10,
},
DNS: DNSConfig{VerificationState: "not_configured"},
Notification: NotificationConfig{
HTTPHeaders: map[string]string{},
HTTPPath: "/api/email/send",
@@ -207,6 +217,12 @@ func (c *Config) Normalize() {
if c.DNS.VerificationState == "" {
c.DNS.VerificationState = "not_configured"
}
if c.ACME.PropagationTimeoutSecs == 0 {
c.ACME.PropagationTimeoutSecs = 900
}
if c.ACME.PropagationPollingIntervalSecs == 0 {
c.ACME.PropagationPollingIntervalSecs = 10
}
if c.Notification.HTTPPath == "" {
c.Notification.HTTPPath = "/api/email/send"
}
@@ -258,9 +274,44 @@ func (c Config) Save(path string) error {
if err := os.Chmod(path, 0o600); err != nil {
return fmt.Errorf("设置配置文件权限失败:%w", err)
}
if err := applyLinuxServiceOwnership(filepath.Dir(path), path); err != nil {
return fmt.Errorf("设置配置文件归属失败:%w", err)
}
return nil
}
// applyLinuxServiceOwnership 在 root 初始化配置时,将配置目录和文件交给 Scert 服务用户管理。
// 非 Linux、非 root 进程或系统尚未创建 Scert 用户时保持原有行为,便于开发环境使用。
func applyLinuxServiceOwnership(directory, path string) error {
if runtime.GOOS != "linux" || os.Geteuid() != 0 {
return nil
}
serviceUser, err := user.Lookup("Scert")
if err != nil {
return nil
}
serviceGroup, err := user.LookupGroup("Scert")
if err != nil {
return nil
}
uid, err := strconv.Atoi(serviceUser.Uid)
if err != nil {
return fmt.Errorf("解析 Scert 用户编号失败:%w", err)
}
gid, err := strconv.Atoi(serviceGroup.Gid)
if err != nil {
return fmt.Errorf("解析 Scert 用户组编号失败:%w", err)
}
if err := os.Chown(directory, uid, gid); err != nil {
return err
}
if err := os.Chmod(directory, 0o700); err != nil {
return err
}
return os.Chown(path, uid, gid)
}
func (c Config) Validate() error {
if c.Version != CurrentVersion {
return fmt.Errorf("配置版本不兼容:%d", c.Version)
@@ -303,6 +354,15 @@ func (c Config) Validate() error {
if c.ACME.RenewalThresholdDays < 1 {
return fmt.Errorf("续期阈值必须大于 0")
}
if c.ACME.PropagationTimeoutSecs < 1 || c.ACME.PropagationTimeoutSecs > 86400 {
return fmt.Errorf("DNS 传播等待时间必须在 1 到 86400 秒之间")
}
if c.ACME.PropagationPollingIntervalSecs < 1 {
return fmt.Errorf("DNS 传播检测间隔必须大于 0")
}
if c.ACME.PropagationPollingIntervalSecs > c.ACME.PropagationTimeoutSecs {
return fmt.Errorf("DNS 传播检测间隔不能大于传播等待时间")
}
if c.DNS.VerificationState != "not_configured" && c.DNS.VerificationState != "pending" && c.DNS.VerificationState != "verified" && c.DNS.VerificationState != "failed" {
return fmt.Errorf("DNS 验证状态无效:%s", c.DNS.VerificationState)
}
@@ -369,19 +429,37 @@ func (c Config) Validate() error {
// ResetURL 返回通过主 Web 服务访问密码重置入口的公开地址。
func (c Config) ResetURL() string {
host := strings.TrimSpace(c.Web.Hostname)
if host == "" {
host = strings.TrimSpace(c.Web.PublicIP)
rawHost := strings.TrimSpace(c.Web.Hostname)
if rawHost == "" {
rawHost = strings.TrimSpace(c.Web.PublicIP)
}
if host == "" {
if rawHost == "" {
return ""
}
if parsed, err := url.Parse(host); err == nil && parsed.Hostname() != "" {
host = parsed.Hostname()
}
host, _ := splitResetHost(rawHost)
host = strings.Trim(host, "[]")
if ip := net.ParseIP(host); ip != nil && strings.Contains(host, ":") {
if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
host = "[" + host + "]"
}
return (&url.URL{Scheme: "https", Host: host, Path: "/reset"}).String()
}
func splitResetHost(rawHost string) (string, string) {
trimmed := strings.TrimSpace(rawHost)
withoutBrackets := strings.Trim(trimmed, "[]")
if net.ParseIP(withoutBrackets) != nil {
return withoutBrackets, ""
}
parseTarget := trimmed
if !strings.Contains(parseTarget, "://") {
parseTarget = "//" + parseTarget
}
if parsed, err := url.Parse(parseTarget); err == nil && parsed.Hostname() != "" {
return parsed.Hostname(), parsed.Port()
}
if parsedHost, parsedPort, err := net.SplitHostPort(trimmed); err == nil {
return parsedHost, parsedPort
}
return withoutBrackets, ""
}
+95 -3
View File
@@ -78,12 +78,12 @@ func TestValidateRejectsInvalidPort(t *testing.T) {
}
}
func TestResetURLUsesWebHostnameWithoutPort(t *testing.T) {
func TestResetURLAlwaysUsesWebHostnameWithoutPort(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)
t.Fatalf("密码重置地址不得暴露主服务端口:%s", value)
}
cfg.Server.Port = 443
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
@@ -91,7 +91,7 @@ func TestResetURLUsesWebHostnameWithoutPort(t *testing.T) {
}
}
func TestResetURLSupportsPublicIPv6(t *testing.T) {
func TestResetURLSupportsPublicIPv6WithoutPort(t *testing.T) {
cfg := Default(t.TempDir())
cfg.Web.PublicIP = "2001:db8::10"
cfg.Server.Port = 8443
@@ -116,3 +116,95 @@ func TestSavedConfigDoesNotContainIndependentResetPort(t *testing.T) {
t.Fatalf("配置文件不应再包含独立密码重置监听配置:%s", content)
}
}
func TestResetURLIgnoresExplicitPortAndURLInput(t *testing.T) {
cfg := Default(t.TempDir())
cfg.Web.Hostname = "https://scert.example.test:9443"
cfg.Server.Port = 5200
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
t.Fatalf("外部地址中的显式端口不得出现在重置地址中:%s", value)
}
}
func TestResetURLIgnoresPathFromWebHostname(t *testing.T) {
cfg := Default(t.TempDir())
cfg.Web.Hostname = "scert.example.test/manage"
cfg.Server.Port = 8443
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
t.Fatalf("管理页面域名附带路径时重置地址不正确:%s", value)
}
}
func TestResetURLUsesExternalProxyAddress(t *testing.T) {
cfg := Default(t.TempDir())
cfg.Web.Hostname = "scert.example.test"
cfg.Server.HTTPSMode = "proxy"
cfg.Server.Port = 5200
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
t.Fatalf("代理模式不应暴露核心服务端口:%s", value)
}
}
func TestResetURLSupportsIPv6WithoutPort(t *testing.T) {
cfg := Default(t.TempDir())
cfg.Web.PublicIP = "2001:db8::10"
cfg.Server.Port = 443
if value := cfg.ResetURL(); value != "https://[2001:db8::10]/reset" {
t.Fatalf("IPv6 默认 HTTPS 地址不正确:%s", value)
}
}
func TestDefaultACMEPropagationSettings(t *testing.T) {
cfg := Default(t.TempDir())
if cfg.ACME.PropagationTimeoutSecs != 900 || cfg.ACME.PropagationPollingIntervalSecs != 10 {
t.Fatalf("默认 DNS 传播参数不正确:%+v", cfg.ACME)
}
}
func TestNormalizeRestoresMissingACMEPropagationSettings(t *testing.T) {
cfg := Default(t.TempDir())
cfg.ACME.PropagationTimeoutSecs = 0
cfg.ACME.PropagationPollingIntervalSecs = 0
cfg.Normalize()
if cfg.ACME.PropagationTimeoutSecs != 900 || cfg.ACME.PropagationPollingIntervalSecs != 10 {
t.Fatalf("旧配置的 DNS 传播参数未补齐:%+v", cfg.ACME)
}
}
func TestValidateRejectsInvalidACMEPropagationTimeout(t *testing.T) {
for _, value := range []int{0, 86401} {
cfg := Default(t.TempDir())
cfg.ACME.PropagationTimeoutSecs = value
if err := cfg.Validate(); err == nil {
t.Fatalf("无效 DNS 传播等待时间未被拒绝:%d", value)
}
}
}
func TestValidateRejectsInvalidACMEPropagationInterval(t *testing.T) {
for _, value := range []int{0, 901} {
cfg := Default(t.TempDir())
cfg.ACME.PropagationPollingIntervalSecs = value
if err := cfg.Validate(); err == nil {
t.Fatalf("无效 DNS 传播检测间隔未被拒绝:%d", value)
}
}
}
func TestSaveAndLoadACMEPropagationSettings(t *testing.T) {
dir := t.TempDir()
cfg := Default(dir)
cfg.ACME.PropagationTimeoutSecs = 1200
cfg.ACME.PropagationPollingIntervalSecs = 15
path := filepath.Join(dir, "config", "scert.json")
if err := cfg.Save(path); err != nil {
t.Fatalf("保存配置失败:%v", err)
}
loaded, err := Load(path)
if err != nil {
t.Fatalf("读取配置失败:%v", err)
}
if loaded.ACME.PropagationTimeoutSecs != 1200 || loaded.ACME.PropagationPollingIntervalSecs != 15 {
t.Fatalf("DNS 传播参数持久化不一致:%+v", loaded.ACME)
}
}
+3 -1
View File
@@ -124,7 +124,9 @@ func (m *manager) rollbackFirewalld(ctx context.Context, result Result) error {
func ufwIsActive(output []byte) bool {
for _, line := range strings.Split(strings.ToLower(string(output)), "\n") {
if strings.TrimSpace(line) == "status: active" {
line = strings.TrimSpace(strings.ReplaceAll(line, ":", ":"))
line = strings.Join(strings.Fields(line), " ")
if line == "status: active" || line == "状态: 激活" {
return true
}
}
+13
View File
@@ -139,6 +139,19 @@ func TestUFWKeepsExistingRule(t *testing.T) {
}
}
func TestUFWRecognizesChineseActiveStatus(t *testing.T) {
runner := &fakeRunner{
paths: map[string]string{"ufw": "/usr/sbin/ufw"},
responses: []runnerResponse{{result: CommandResult{Output: []byte("状态: 激活\n8443/tcp ALLOW Anywhere\n")}}},
}
result, err := NewManagerForOS("linux", runner).OpenTCP(context.Background(), 8443)
if err != nil {
t.Fatalf("中文 UFW 状态检查失败:%v", err)
}
if result.Created || result.Backend != backendUFW {
t.Fatalf("中文 UFW 已有规则不应重复创建:%+v", result)
}
}
func TestFirewalldCreatesPermanentRuleAndReloads(t *testing.T) {
runner := &fakeRunner{
paths: map[string]string{"firewall-cmd": "/usr/bin/firewall-cmd"},
+7 -1
View File
@@ -27,6 +27,10 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
)
type setupSecretWriter interface {
Put(context.Context, string, map[string]string) error
}
type Dependencies struct {
Config config.Config
ConfigPath string
@@ -35,6 +39,7 @@ type Dependencies struct {
Servers repository.ServerRepository
SSHKeys *sshkey.Service
SetupDNS setupDNSVerifier
Secrets setupSecretWriter
Firewall firewall.Manager
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
@@ -56,6 +61,7 @@ type Server struct {
servers repository.ServerRepository
sshKeys *sshkey.Service
setupDNS setupDNSVerifier
secrets setupSecretWriter
firewall firewall.Manager
issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
issueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
@@ -84,7 +90,7 @@ func New(deps Dependencies) *Server {
router.Use(gin.Recovery())
server := &Server{
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger,
repository: deps.Repository, setupDNS: deps.SetupDNS, firewall: deps.Firewall, router: router,
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
servers: deps.Servers,
sshKeys: deps.SSHKeys,
issueCertificate: deps.IssueCertificate,
+162 -74
View File
@@ -2,6 +2,8 @@ package httpapi
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net"
@@ -27,37 +29,40 @@ 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"`
EmailHTTPEnabled *bool `json:"email_http_enabled"`
EmailProvider string `json:"email_provider"`
EmailEndpoint string `json:"email_endpoint"`
EmailHTTPPath string `json:"email_http_path"`
EmailHTTPLoginPath string `json:"email_http_login_path"`
EmailHTTPAuthMode string `json:"email_http_auth_mode"`
EmailHTTPCredentialRef string `json:"email_http_credential_ref"`
EmailHTTPHeaders map[string]string `json:"email_http_headers"`
EmailEventMode string `json:"email_event_mode"`
EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"`
EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"`
EmailIncludeManagementURL bool `json:"email_include_management_url"`
EmailSenderName string `json:"email_sender_name"`
EmailSenderEmail string `json:"email_sender_email"`
Recipients []string `json:"recipients"`
EmailTimeoutSecs int `json:"email_timeout_secs"`
EmailRetryCount int `json:"email_retry_count"`
EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"`
DNSProvider string `json:"dns_provider"`
DNSCredentialRef string `json:"dns_credential_ref"`
DNSVerificationToken string `json:"dns_verification_token"`
DNSTestDomain string `json:"dns_test_domain"`
CertificateRoot string `json:"certificate_root"`
WebHostname string `json:"web_hostname"`
WebPublicIP string `json:"web_public_ip"`
WebEnabled *bool `json:"web_enabled"`
HTTPSMode string `json:"https_mode"`
AdminUsername string `json:"admin_username"`
AdminEmail string `json:"admin_email"`
AdminPassword string `json:"admin_password"`
ServerPort int `json:"server_port"`
EmailHTTPEnabled *bool `json:"email_http_enabled"`
EmailProvider string `json:"email_provider"`
EmailEndpoint string `json:"email_endpoint"`
EmailHTTPPath string `json:"email_http_path"`
EmailHTTPLoginPath string `json:"email_http_login_path"`
EmailHTTPAuthMode string `json:"email_http_auth_mode"`
EmailHTTPCredentialRef string `json:"email_http_credential_ref"`
EmailHTTPCredentials map[string]string `json:"email_http_credentials"`
EmailHTTPHeaders map[string]string `json:"email_http_headers"`
EmailEventMode string `json:"email_event_mode"`
EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"`
EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"`
EmailIncludeManagementURL bool `json:"email_include_management_url"`
EmailSenderName string `json:"email_sender_name"`
EmailSenderEmail string `json:"email_sender_email"`
Recipients []string `json:"recipients"`
EmailTimeoutSecs int `json:"email_timeout_secs"`
EmailRetryCount int `json:"email_retry_count"`
EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"`
DNSProvider string `json:"dns_provider"`
DNSCredentialRef string `json:"dns_credential_ref"`
DNSVerificationToken string `json:"dns_verification_token"`
DNSTestDomain string `json:"dns_test_domain"`
PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
CertificateRoot string `json:"certificate_root"`
WebHostname string `json:"web_hostname"`
WebPublicIP string `json:"web_public_ip"`
WebEnabled *bool `json:"web_enabled"`
HTTPSMode string `json:"https_mode"`
}
type dnsTestRequest struct {
@@ -91,19 +96,21 @@ func (s *Server) setupStatus(c *gin.Context) {
}
}
c.JSON(http.StatusOK, gin.H{
"initialized": cfg.SetupReady,
"phase": phase,
"blockers": blockers,
"server_port": cfg.Server.Port,
"reset_url": cfg.ResetURL(),
"https_mode": cfg.Server.HTTPSMode,
"web_enabled": cfg.Web.Enabled,
"web_hostname": cfg.Web.Hostname,
"web_public_ip": cfg.Web.PublicIP,
"certificate_root": cfg.Paths.Certificate,
"dns_provider": cfg.DNS.Provider,
"dns_verification_state": cfg.DNS.VerificationState,
"dns_test_available": s.setupDNS != nil,
"initialized": cfg.SetupReady,
"phase": phase,
"blockers": blockers,
"server_port": cfg.Server.Port,
"reset_url": cfg.ResetURL(),
"https_mode": cfg.Server.HTTPSMode,
"web_enabled": cfg.Web.Enabled,
"web_hostname": cfg.Web.Hostname,
"web_public_ip": cfg.Web.PublicIP,
"certificate_root": cfg.Paths.Certificate,
"dns_provider": cfg.DNS.Provider,
"dns_verification_state": cfg.DNS.VerificationState,
"dns_test_available": s.setupDNS != nil,
"propagation_timeout_secs": cfg.ACME.PropagationTimeoutSecs,
"propagation_polling_interval_secs": cfg.ACME.PropagationPollingIntervalSecs,
})
}
@@ -190,38 +197,64 @@ func (s *Server) applySetup(c *gin.Context) {
if request.EmailHTTPEnabled != nil {
emailHTTPEnabled = *request.EmailHTTPEnabled
}
emailCredentialRef := strings.TrimSpace(request.EmailHTTPCredentialRef)
var notificationCredentials map[string]string
var credentialErr error
if emailHTTPEnabled && strings.ToLower(strings.TrimSpace(request.EmailHTTPAuthMode)) != "none" {
if len(request.EmailHTTPCredentials) > 0 {
notificationCredentials, credentialErr = normalizeNotificationCredentials(request.EmailHTTPAuthMode, request.EmailHTTPCredentials)
if credentialErr != nil {
s.writeError(c, http.StatusBadRequest, credentialErr.Error(), nil)
return
}
if s.secrets == nil {
s.writeError(c, http.StatusServiceUnavailable, "HTTP 通知敏感凭据存储尚未初始化", nil)
return
}
emailCredentialRef, credentialErr = newNotificationCredentialReference()
if credentialErr != nil {
s.writeError(c, http.StatusInternalServerError, "生成 HTTP 通知凭据引用失败", credentialErr)
return
}
} else if emailCredentialRef == "" {
s.writeError(c, http.StatusBadRequest, "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用", nil)
return
}
}
updated := s.config
err := setup.Apply(&updated, setup.Input{
AdminUsername: request.AdminUsername,
AdminEmail: request.AdminEmail,
AdminPassword: request.AdminPassword,
ServerPort: request.ServerPort,
EmailHTTPEnabled: emailHTTPEnabled,
EmailProvider: request.EmailProvider,
EmailEndpoint: request.EmailEndpoint,
EmailHTTPPath: request.EmailHTTPPath,
EmailHTTPLoginPath: request.EmailHTTPLoginPath,
EmailHTTPAuthMode: request.EmailHTTPAuthMode,
EmailHTTPCredentialRef: request.EmailHTTPCredentialRef,
EmailHTTPHeaders: request.EmailHTTPHeaders,
EmailEventMode: request.EmailEventMode,
EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails,
EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial,
EmailIncludeManagementURL: request.EmailIncludeManagementURL,
EmailSenderName: request.EmailSenderName,
EmailSenderEmail: request.EmailSenderEmail,
EmailRecipients: request.Recipients,
EmailTimeoutSecs: request.EmailTimeoutSecs,
EmailRetryCount: request.EmailRetryCount,
EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs,
DNSProvider: request.DNSProvider,
DNSCredentialRef: request.DNSCredentialRef,
DNSVerified: true,
CertificateRoot: request.CertificateRoot,
WebHostname: request.WebHostname,
WebPublicIP: request.WebPublicIP,
WebEnabled: webEnabled,
HTTPSMode: request.HTTPSMode,
AdminUsername: request.AdminUsername,
AdminEmail: request.AdminEmail,
AdminPassword: request.AdminPassword,
ServerPort: request.ServerPort,
EmailHTTPEnabled: emailHTTPEnabled,
EmailProvider: request.EmailProvider,
EmailEndpoint: request.EmailEndpoint,
EmailHTTPPath: request.EmailHTTPPath,
EmailHTTPLoginPath: request.EmailHTTPLoginPath,
EmailHTTPAuthMode: request.EmailHTTPAuthMode,
EmailHTTPCredentialRef: emailCredentialRef,
EmailHTTPHeaders: request.EmailHTTPHeaders,
EmailEventMode: request.EmailEventMode,
EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails,
EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial,
EmailIncludeManagementURL: request.EmailIncludeManagementURL,
EmailSenderName: request.EmailSenderName,
EmailSenderEmail: request.EmailSenderEmail,
EmailRecipients: request.Recipients,
EmailTimeoutSecs: request.EmailTimeoutSecs,
EmailRetryCount: request.EmailRetryCount,
EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs,
DNSProvider: request.DNSProvider,
DNSCredentialRef: request.DNSCredentialRef,
DNSVerified: true,
PropagationTimeoutSecs: request.PropagationTimeoutSecs,
PropagationPollingIntervalSecs: request.PropagationPollingIntervalSecs,
CertificateRoot: request.CertificateRoot,
WebHostname: request.WebHostname,
WebPublicIP: request.WebPublicIP,
WebEnabled: webEnabled,
HTTPSMode: request.HTTPSMode,
})
if err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
@@ -265,6 +298,15 @@ func (s *Server) applySetup(c *gin.Context) {
}
updated.Server.TLSCert = savedCertificate.FullChainPath
updated.Server.TLSKey = savedCertificate.PrivateKeyPath
if len(notificationCredentials) > 0 {
if err := s.secrets.Put(c.Request.Context(), emailCredentialRef, notificationCredentials); err != nil {
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
s.logger.Error("保存 HTTP 通知凭据失败,且证书回滚失败", "error", rollbackErr)
}
s.writeError(c, http.StatusInternalServerError, "保存 HTTP 通知凭据失败,初始化尚未完成", err)
return
}
}
updated.SetupReady = true
if err := updated.Validate(); err != nil {
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
@@ -387,3 +429,49 @@ func isLoopbackRequest(request *http.Request) bool {
ip := net.ParseIP(strings.TrimSpace(host))
return ip != nil && ip.IsLoopback()
}
func newNotificationCredentialReference() (string, error) {
buffer := make([]byte, 18)
if _, err := rand.Read(buffer); err != nil {
return "", err
}
return "secret://notification/" + base64.RawURLEncoding.EncodeToString(buffer), nil
}
func normalizeNotificationCredentials(authMode string, values map[string]string) (map[string]string, error) {
result := make(map[string]string, len(values))
for key, value := range values {
key = strings.TrimSpace(key)
if key == "" {
continue
}
result[key] = value
}
if len(result) == 0 {
return nil, fmt.Errorf("HTTP 通知凭据不能为空")
}
switch strings.ToLower(strings.TrimSpace(authMode)) {
case "bearer":
if strings.TrimSpace(result["token"]) == "" && strings.TrimSpace(result["access_token"]) == "" {
return nil, fmt.Errorf("Bearer Token 凭据必须包含 token 或 access_token")
}
case "hmac_sha256":
if strings.TrimSpace(result["secret"]) == "" && strings.TrimSpace(result["hmac_secret"]) == "" && strings.TrimSpace(result["key"]) == "" && strings.TrimSpace(result["token"]) == "" {
return nil, fmt.Errorf("HMAC-SHA256 凭据必须包含签名密钥")
}
case "session":
account := result["account"]
if account == "" {
account = result["username"]
}
if account == "" {
account = result["identifier"]
}
if strings.TrimSpace(account) == "" || result["password"] == "" {
return nil, fmt.Errorf("会话认证凭据必须包含账号和密码")
}
default:
return nil, fmt.Errorf("HTTP 通知认证方式无效")
}
return result, nil
}
+137
View File
@@ -28,6 +28,22 @@ type fakeSetupDNSVerifier struct {
consumed bool
}
type fakeSetupSecretWriter struct {
values map[string]map[string]string
}
func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value map[string]string) error {
if f.values == nil {
f.values = make(map[string]map[string]string)
}
copyValue := make(map[string]string, len(value))
for key, item := range value {
copyValue[key] = item
}
f.values[reference] = copyValue
return nil
}
type fakeFirewallManager struct {
result firewall.Result
openErr error
@@ -186,6 +202,8 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
"dns_credential_ref":"secret://dns/cloudflare/default",
"dns_verification_token":"verified-token",
"dns_test_domain":"scert.example.test",
"propagation_timeout_secs":1200,
"propagation_polling_interval_secs":15,
"certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `",
"web_hostname":"scert.example.test",
"web_enabled":true,
@@ -229,6 +247,9 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
if len(saved.Notification.Recipients) != 1 {
t.Fatalf("通知收件人未去重:%v", saved.Notification.Recipients)
}
if saved.ACME.PropagationTimeoutSecs != 1200 || saved.ACME.PropagationPollingIntervalSecs != 15 {
t.Fatalf("Web 初始化未保存 DNS 传播等待配置:timeout=%d interval=%d", saved.ACME.PropagationTimeoutSecs, saved.ACME.PropagationPollingIntervalSecs)
}
repeat := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
repeat.RemoteAddr = "127.0.0.1:53001"
@@ -240,6 +261,65 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
}
}
func TestSetupApplyEncryptsNotificationCredentialsAndPersistsReference(t *testing.T) {
baseDir := t.TempDir()
cfg := config.Default(baseDir)
configPath := filepath.Join(baseDir, "config", "scert.json")
verifier := &fakeSetupDNSVerifier{}
secrets := &fakeSetupSecretWriter{}
server := New(Dependencies{
Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{},
SetupDNS: verifier, Secrets: secrets,
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
})
payload := `{
"admin_username":"root-admin",
"admin_email":"admin@example.test",
"admin_password":"secure-pass-123",
"server_port":8443,
"email_http_enabled":true,
"email_provider":"mail-api",
"email_endpoint":"https://mail.example.test/send",
"email_http_auth_mode":"bearer",
"email_http_credentials":{"token":"plain-token-value"},
"recipients":["ops@example.test"],
"dns_provider":"cloudflare",
"dns_credential_ref":"secret://dns/cloudflare/default",
"dns_verification_token":"verified-token",
"dns_test_domain":"scert.example.test",
"certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `",
"web_hostname":"scert.example.test",
"web_enabled":true,
"https_mode":"direct"
}`
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
request.RemoteAddr = "127.0.0.1:53000"
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("提交带 HTTP 通知凭据的初始化配置失败:%d %s", response.Code, response.Body.String())
}
data, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("读取初始化配置失败:%v", err)
}
if strings.Contains(string(data), "plain-token-value") || strings.Contains(string(data), "email_http_credentials") {
t.Fatal("普通配置文件不应保存 HTTP 通知明文凭据")
}
var saved config.Config
if err := json.Unmarshal(data, &saved); err != nil {
t.Fatalf("解析初始化配置失败:%v", err)
}
if !strings.HasPrefix(saved.Notification.HTTPCredentialRef, "secret://notification/") {
t.Fatalf("初始化配置应保存通知凭据引用:%q", saved.Notification.HTTPCredentialRef)
}
stored, ok := secrets.values[saved.Notification.HTTPCredentialRef]
if !ok || stored["token"] != "plain-token-value" {
t.Fatalf("通知凭据未写入敏感信息存储:%v", secrets.values)
}
}
func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) {
cfg := config.Default(t.TempDir())
verifier := &fakeSetupDNSVerifier{checkErr: errors.New("DNS 验证令牌无效或已经过期,请重新测试")}
@@ -254,6 +334,63 @@ func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) {
}
}
func TestNormalizeNotificationCredentials(t *testing.T) {
tests := []struct {
name string
mode string
values map[string]string
wantErr bool
}{
{name: "bearer", mode: "bearer", values: map[string]string{"token": "token-value"}},
{name: "hmac", mode: "hmac_sha256", values: map[string]string{"secret": "secret-value"}},
{name: "session", mode: "session", values: map[string]string{"account": "test", "password": "password-value"}},
{name: "missing bearer token", mode: "bearer", values: map[string]string{"name": "test"}, wantErr: true},
{name: "missing session password", mode: "session", values: map[string]string{"account": "test"}, wantErr: true},
{name: "unknown mode", mode: "unknown", values: map[string]string{"token": "test"}, wantErr: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := normalizeNotificationCredentials(test.mode, test.values)
if (err != nil) != test.wantErr {
t.Fatalf("凭据校验结果不正确:error=%v", err)
}
})
}
}
func TestSetupApplyRejectsMissingNotificationCredentials(t *testing.T) {
cfg := config.Default(t.TempDir())
verifier := &fakeSetupDNSVerifier{}
server := New(Dependencies{
Config: cfg, ConfigPath: filepath.Join(t.TempDir(), "scert.json"),
Repository: &stubDomainRepository{}, SetupDNS: verifier,
})
payload := `{
"admin_username":"root-admin",
"admin_email":"admin@example.test",
"admin_password":"secure-pass-123",
"server_port":8443,
"email_http_enabled":true,
"email_endpoint":"https://mail.example.test",
"email_http_auth_mode":"bearer",
"dns_provider":"cloudflare",
"dns_credential_ref":"secret://dns/cloudflare/test",
"dns_verification_token":"verified-token",
"dns_test_domain":"example.test",
"certificate_root":"/ssl",
"web_hostname":"scert.example.test",
"https_mode":"direct"
}`
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
request.RemoteAddr = "127.0.0.1:53000"
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(), "明文凭据或已有凭据引用") {
t.Fatalf("缺少 HTTP 通知凭据时应被拒绝:%d %s", response.Code, response.Body.String())
}
}
func TestSetupApplyRejectsOversizedRequest(t *testing.T) {
cfg := config.Default(t.TempDir())
server := New(Dependencies{
+6 -6
View File
@@ -80,6 +80,12 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
}
_ = s.tasks.UpdateTask(context.Background(), task.ID, status, "certificate_issue", message, &now, &finished)
_ = s.tasks.FinishAttempt(context.Background(), attempt.ID, status, message, &finished)
task.Status = status
task.Stage = "certificate_issue"
task.Message = message
task.StartedAt = &now
task.FinishedAt = &finished
task.UpdatedAt = finished
if s.audit != nil {
auditStatus := status
if issueErr != nil {
@@ -105,12 +111,6 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
c.JSON(http.StatusBadGateway, response)
return
}
task.Status = status
task.Stage = "certificate_issue"
task.Message = message
task.StartedAt = &now
task.FinishedAt = &finished
task.UpdatedAt = finished
response["task"] = task
c.JSON(http.StatusOK, response)
}
+21
View File
@@ -2,6 +2,7 @@ package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
@@ -110,6 +111,26 @@ func TestTaskAPIReturnsFailureAndKeepsTaskTrace(t *testing.T) {
if response.Code != http.StatusBadGateway || !strings.Contains(response.Body.String(), "模拟证书申请失败") {
t.Fatalf("失败任务响应错误:%d %s", response.Code, response.Body.String())
}
var payload struct {
Task struct {
Status string `json:"status"`
Stage string `json:"stage"`
Message string `json:"message"`
FinishedAt string `json:"finished_at"`
UpdatedAt string `json:"updated_at"`
} `json:"task"`
TaskStatus string `json:"task_status"`
FinishedAt string `json:"finished_at"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatalf("失败任务响应不是有效 JSON:%v;响应:%s", err, response.Body.String())
}
if payload.Task.Status != "failed" || payload.Task.Stage != "certificate_issue" || payload.Task.Message != "模拟证书申请失败" {
t.Fatalf("失败任务嵌套状态不一致:%+v", payload.Task)
}
if payload.TaskStatus != "failed" || payload.FinishedAt == "" || payload.Task.FinishedAt == "" || payload.Task.UpdatedAt == "" {
t.Fatalf("失败任务顶层状态或时间字段不完整:%+v", payload)
}
items, err := taskRepo.ListTasks(context.Background(), "", 10)
if err != nil || len(items) != 1 || items[0].Status != "failed" {
t.Fatalf("失败任务状态错误:%+v %v", items, err)
+40 -30
View File
@@ -13,36 +13,40 @@ import (
)
type Input struct {
AdminUsername string
AdminEmail string
AdminPassword string
ServerPort int
EmailHTTPEnabled bool
EmailProvider string
EmailEndpoint string
EmailHTTPPath string
EmailHTTPLoginPath string
EmailHTTPAuthMode string
EmailHTTPCredentialRef string
EmailHTTPHeaders map[string]string
EmailEventMode string
EmailIncludeDeploymentDetails bool
EmailIncludeCertificateSerial bool
EmailIncludeManagementURL bool
EmailSenderName string
EmailSenderEmail string
EmailRecipients []string
EmailTimeoutSecs int
EmailRetryCount int
EmailRetryIntervalsSecs []int
DNSProvider string
DNSCredentialRef string
DNSVerified bool
CertificateRoot string
WebHostname string
WebPublicIP string
WebEnabled bool
HTTPSMode string
AdminUsername string
AdminEmail string
AdminPassword string
ServerPort int
EmailHTTPEnabled bool
EmailProvider string
EmailEndpoint string
EmailHTTPPath string
EmailHTTPLoginPath string
EmailHTTPAuthMode string
EmailHTTPCredentialRef string
EmailHTTPHeaders map[string]string
EmailEventMode string
EmailIncludeDeploymentDetails bool
EmailIncludeCertificateSerial bool
EmailIncludeManagementURL bool
EmailSenderName string
EmailSenderEmail string
EmailRecipients []string
EmailTimeoutSecs int
EmailRetryCount int
EmailRetryIntervalsSecs []int
DNSProvider string
DNSCredentialRef string
DNSCredentials map[string]string
DNSTestDomain string
DNSVerified bool
PropagationTimeoutSecs int
PropagationPollingIntervalSecs int
CertificateRoot string
WebHostname string
WebPublicIP string
WebEnabled bool
HTTPSMode string
}
func Apply(cfg *config.Config, input Input) error {
@@ -97,6 +101,12 @@ func Apply(cfg *config.Config, input Input) error {
cfg.Admin.Email = adminEmail
cfg.Admin.PasswordHash = string(hash)
cfg.ACME.AccountEmail = adminEmail
if input.PropagationTimeoutSecs != 0 {
cfg.ACME.PropagationTimeoutSecs = input.PropagationTimeoutSecs
}
if input.PropagationPollingIntervalSecs != 0 {
cfg.ACME.PropagationPollingIntervalSecs = input.PropagationPollingIntervalSecs
}
cfg.Server.Port = input.ServerPort
cfg.Server.HTTPSMode = input.HTTPSMode
cfg.Web.Enabled = input.WebEnabled
+85
View File
@@ -1,6 +1,9 @@
package setup
import (
"os"
"path/filepath"
"strings"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/config"
@@ -24,6 +27,7 @@ func TestApplyBuildsReadyConfig(t *testing.T) {
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,
PropagationTimeoutSecs: 1200, PropagationPollingIntervalSecs: 15,
WebHostname: "panel.example.com", WebEnabled: true,
})
if err != nil {
@@ -41,8 +45,44 @@ func TestApplyBuildsReadyConfig(t *testing.T) {
if cfg.ResetURL() != "https://panel.example.com/reset" {
t.Fatalf("密码重置地址生成错误:%s", cfg.ResetURL())
}
if cfg.ACME.PropagationTimeoutSecs != 1200 || cfg.ACME.PropagationPollingIntervalSecs != 15 {
t.Fatalf("DNS 传播等待配置保存错误:timeout=%d interval=%d", cfg.ACME.PropagationTimeoutSecs, cfg.ACME.PropagationPollingIntervalSecs)
}
}
func TestApplyRejectsInvalidPropagationSettings(t *testing.T) {
cases := []struct {
name string
timeout int
interval int
}{
{name: "等待时间小于最小值", timeout: 0 - 1, interval: 10},
{name: "等待时间超过最大值", timeout: 86401, interval: 10},
{name: "检测间隔超过等待时间", timeout: 900, interval: 901},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
cfg := config.Default(t.TempDir())
err := Apply(&cfg, Input{
AdminUsername: "admin",
AdminEmail: "admin@example.com",
AdminPassword: "password123",
ServerPort: 8080,
DNSProvider: "cloudflare",
DNSCredentialRef: "credential-1",
DNSVerified: true,
PropagationTimeoutSecs: item.timeout,
PropagationPollingIntervalSecs: item.interval,
WebHostname: "panel.example.com",
WebEnabled: true,
})
if err == nil {
t.Fatal("非法 DNS 传播等待配置不应完成初始化")
}
})
}
}
func TestApplyRejectsWebIPAsHostnamePair(t *testing.T) {
cfg := config.Default(t.TempDir())
err := Apply(&cfg, Input{
@@ -77,3 +117,48 @@ func TestApplyUsesAdminEmailAndStoresNotificationOptions(t *testing.T) {
t.Fatalf("HTTP 通知配置未正确保存:%+v", cfg.Notification)
}
}
func TestApplyAndSaveStoresOnlyCredentialReference(t *testing.T) {
root := t.TempDir()
cfg := config.Default(root)
credentialRef := "secret://dns/cloudflare/test"
secretValue := "test-dns-token"
if err := Apply(&cfg, Input{
AdminUsername: "admin",
AdminEmail: "admin@example.com",
AdminPassword: "password123",
ServerPort: 8080,
DNSProvider: "cloudflare",
DNSCredentialRef: credentialRef,
DNSVerified: true,
CertificateRoot: cfg.Paths.Certificate,
WebHostname: "panel.example.com",
WebEnabled: true,
}); err != nil {
t.Fatalf("构造初始化配置失败:%v", err)
}
path := filepath.Join(root, "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, credentialRef) {
t.Fatalf("初始化配置应保存凭据引用:%s", content)
}
if strings.Contains(content, secretValue) || strings.Contains(content, "api_token") {
t.Fatalf("初始化配置不应保存 DNS 明文凭据:%s", content)
}
loaded, err := config.Load(path)
if err != nil {
t.Fatalf("重新读取初始化配置失败:%v", err)
}
if loaded.DNS.CredentialRef != credentialRef {
t.Fatalf("重新读取后凭据引用不正确:%q", loaded.DNS.CredentialRef)
}
}