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

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" "context"
"flag" "flag"
"fmt" "fmt"
"io"
"os" "os"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
@@ -14,9 +15,17 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/config" "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() { func main() {
baseDir := flag.String("base-dir", "", "Windows 默认安装根目录") baseDir := flag.String("base-dir", "", "Windows 默认安装根目录")
configPath := flag.String("config", "", "配置文件路径") configPath := flag.String("config", "", "配置文件路径")
codeOutput := flag.String("code-output", "", "一次性校验码文件路径")
flag.Parse() flag.Parse()
path := *configPath path := *configPath
if path == "" { if path == "" {
@@ -27,16 +36,13 @@ func main() {
fmt.Fprintln(os.Stderr, "读取配置失败:", err) fmt.Fprintln(os.Stderr, "读取配置失败:", err)
os.Exit(1) os.Exit(1)
} }
controller := admin.New(cfg) controller := admin.NewWithCodePath(cfg, *codeOutput)
session, err := controller.Start() session, err := controller.Start()
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, "启用密码重置入口失败:", err) fmt.Fprintln(os.Stderr, "启用密码重置入口失败:", err)
os.Exit(1) os.Exit(1)
} }
fmt.Println("Scert-admin 已启用临时密码重置入口,不监听独立网络端口。") writeSessionInfo(os.Stdout, session)
fmt.Println("重置地址:", session.State.ResetURL)
fmt.Println("一次性校验码:", session.Code)
fmt.Println("停止 Scert-admin 后入口将立即关闭;异常退出时入口会在租约过期后自动关闭。")
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop() defer stop()
ticker := time.NewTicker(admin.RefreshInterval) 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 ( const (
ResetPath = "/reset" ResetPath = "/reset"
stateFileName = "scert-admin-reset.json" stateFileName = "scert-admin-reset.json"
codeFileName = "scert-admin-reset-code"
defaultLease = 90 * time.Second defaultLease = 90 * time.Second
RefreshInterval = 30 * time.Second RefreshInterval = 30 * time.Second
) )
@@ -30,6 +31,7 @@ type State struct {
Active bool `json:"active"` Active bool `json:"active"`
ResetURL string `json:"reset_url"` ResetURL string `json:"reset_url"`
CodeHash string `json:"code_hash"` CodeHash string `json:"code_hash"`
CodePath string `json:"code_path,omitempty"`
ProcessID int `json:"process_id"` ProcessID int `json:"process_id"`
StartedAt time.Time `json:"started_at"` StartedAt time.Time `json:"started_at"`
ExpiresAt time.Time `json:"expires_at"` ExpiresAt time.Time `json:"expires_at"`
@@ -43,15 +45,24 @@ type Session struct {
type Controller struct { type Controller struct {
config config.Config config config.Config
statePath string statePath string
codePath string
leaseDuration time.Duration leaseDuration time.Duration
now func() time.Time now func() time.Time
state State state State
} }
func New(cfg config.Config) *Controller { 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{ return &Controller{
config: cfg, config: cfg,
statePath: StatePath(cfg.Paths.Data), statePath: StatePath(cfg.Paths.Data),
codePath: codePath,
leaseDuration: defaultLease, leaseDuration: defaultLease,
now: time.Now, now: time.Now,
} }
@@ -61,6 +72,10 @@ func StatePath(dataDir string) string {
return filepath.Join(dataDir, stateFileName) return filepath.Join(dataDir, stateFileName)
} }
func CodePath(dataDir string) string {
return filepath.Join(dataDir, codeFileName)
}
func (c *Controller) Start() (Session, error) { func (c *Controller) Start() (Session, error) {
if c == nil { if c == nil {
return Session{}, fmt.Errorf("Scert-admin 控制器不能为空") return Session{}, fmt.Errorf("Scert-admin 控制器不能为空")
@@ -72,9 +87,11 @@ func (c *Controller) Start() (Session, error) {
if resetURL == "" { if resetURL == "" {
return Session{}, fmt.Errorf("未配置管理页面域名或公网 IP,无法生成密码重置地址") 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 return Session{}, err
} else if active { }
if active {
return Session{}, fmt.Errorf("密码重置入口已经启用") return Session{}, fmt.Errorf("密码重置入口已经启用")
} }
code, err := generateCode() code, err := generateCode()
@@ -83,10 +100,14 @@ func (c *Controller) Start() (Session, error) {
} }
now := c.now().UTC() now := c.now().UTC()
c.state = State{ 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), 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 { if err := writeState(c.statePath, c.state); err != nil {
_ = removeCodeFile(c.codePath)
return Session{}, err return Session{}, err
} }
return Session{State: c.state, Code: code}, nil 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) { if !latest.Active || latest.CodeHash != c.state.CodeHash || !c.now().UTC().Before(latest.ExpiresAt) {
c.state.Active = false c.state.Active = false
_ = removeCodeFile(codePathForState(c.statePath, latest))
return ErrResetSessionClosed return ErrResetSessionClosed
} }
c.state = latest c.state = latest
@@ -113,9 +135,14 @@ func (c *Controller) Stop() error {
if c == nil || !c.state.Active { if c == nil || !c.state.Active {
return nil return nil
} }
c.state.Active = false state := c.state
c.state.ExpiresAt = c.now().UTC() state.Active = false
return writeState(c.statePath, c.state) 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) { 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 { if err != nil {
return false, err 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) { 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 return State{}, err
} }
if !state.Active || state.CodeHash == "" || !now.UTC().Before(state.ExpiresAt) { if !state.Active || state.CodeHash == "" || !now.UTC().Before(state.ExpiresAt) {
_ = removeCodeFile(codePathForState(path, state))
return State{}, ErrResetSessionClosed return State{}, ErrResetSessionClosed
} }
expected := hashCode(code) expected := hashCode(code)
@@ -150,6 +184,7 @@ func Consume(path string, session State, now time.Time) error {
return err return err
} }
if !latest.Active || latest.CodeHash == "" || !now.UTC().Before(latest.ExpiresAt) { if !latest.Active || latest.CodeHash == "" || !now.UTC().Before(latest.ExpiresAt) {
_ = removeCodeFile(codePathForState(path, latest))
return ErrResetSessionClosed return ErrResetSessionClosed
} }
if subtle.ConstantTimeCompare([]byte(latest.CodeHash), []byte(session.CodeHash)) != 1 { 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.Active = false
latest.CodeHash = "" latest.CodeHash = ""
latest.ExpiresAt = now.UTC() 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) { func ReadState(path string) (State, error) {
@@ -200,6 +238,56 @@ func writeState(path string, state State) error {
return nil 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) { func generateCode() (string, error) {
buffer := make([]byte, 10) buffer := make([]byte, 10)
if _, err := rand.Read(buffer); err != nil { if _, err := rand.Read(buffer); err != nil {
+132 -2
View File
@@ -24,10 +24,12 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
unit := activeUnitText(string(data)) unit := activeUnitText(string(data))
for _, required := range []string{ for _, required := range []string{
"Documentation=file:///scert/docs/Scert-admin服务管理说明.md", "Documentation=file:///scert/docs/Scert-admin-service-management.md",
"User=Scert", "User=Scert",
"Group=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", "Restart=no",
"RuntimeMaxSec=30min", "RuntimeMaxSec=30min",
"UMask=0077", "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 { func activeUnitText(unit string) string {
lines := strings.Split(unit, "\n") lines := strings.Split(unit, "\n")
active := make([]string, 0, len(lines)) active := make([]string, 0, len(lines))
@@ -143,3 +248,28 @@ func activeUnitText(unit string) string {
} }
return strings.Join(active, "\n") 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)) unit := activeUnitText(string(data))
for _, required := range []string{ for _, required := range []string{
"Documentation=file:///scert/docs/Scert服务管理说明.md", "Documentation=file:///scert/docs/Scert-service-management.md",
"User=Scert", "User=Scert",
"Group=Scert", "Group=Scert",
"ExecStart=/scert/scert --config /scert/conf/scert.json serve", "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) renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays)
server := httpapi.New(httpapi.Dependencies{ server := httpapi.New(httpapi.Dependencies{
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, SSHKeys: sshKeys, 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, IssueCertificate: workflow.IssueForHTTP,
IssueSetupCertificate: func(ctx context.Context, request certificate.SetupCertificateRequest) (certificate.SavedResource, error) { IssueSetupCertificate: func(ctx context.Context, request certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
return certificates.IssueForSetup(ctx, request) 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 } func (u *AccountUser) GetPrivateKey() crypto.Signer { return u.PrivateKey }
type LegoIssuer struct { type LegoIssuer struct {
User *AccountUser User *AccountUser
Provider challenge.Provider Provider challenge.Provider
Environment string Environment string
HTTPClient *http.Client PropagationTimeout time.Duration
Now func() time.Time 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) { 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 { if err != nil {
return Resource{}, fmt.Errorf("创建 ACME 客户端失败:%w", err) 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) return Resource{}, fmt.Errorf("配置 DNS-01 验证失败:%w", err)
} }
if i.User.Registration == nil { if i.User.Registration == nil {
@@ -77,11 +97,14 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
i.User.Registration = account i.User.Registration = account
} }
issued, err := client.Certificate.Obtain(ctx, legoCertificate.ObtainRequest{ issued, err := client.Certificate.Obtain(ctx, legoCertificate.ObtainRequest{
Domains: domains, EmailAddresses: nonEmptyEmail(request.AccountEmail, i.User.Email), Domains: domains,
KeyType: certcrypto.RSA2048, Bundle: true, KeyType: certcrypto.RSA2048, Bundle: true,
PreferredChain: request.PreferredChain, PreferredChain: request.PreferredChain,
}) })
if err != nil { 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) return Resource{}, fmt.Errorf("申请证书失败:%w", err)
} }
resource := Resource{ resource := Resource{
@@ -93,12 +116,3 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
} }
return ValidateResource(resource) 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, config: cfg, repository: repository, credentials: credentials, providers: providers, accounts: accounts,
store: FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup}, store: FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup},
newIssuer: func(user *AccountUser, provider challenge.Provider, environment string) Issuer { 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/config"
"git.pcux.cn/xuans/Scert/backend/internal/domain" "git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
) )
type serviceRepository struct { type serviceRepository struct {
@@ -53,6 +54,17 @@ func (serviceProviderFactory) Create(string, map[string]string) (challenge.Provi
return serviceProvider{}, nil 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{} type serviceAccounts struct{}
func (serviceAccounts) LoadOrCreate(context.Context, string, string) (*AccountUser, error) { 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 var output string
command := &cobra.Command{ command := &cobra.Command{
Use: "backup", Use: "backup",
Short: "备份配置和 SQLite 数据库", Short: "备份配置和数据库",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig() cfg, err := loadConfig()
if err != nil { if err != nil {
@@ -294,6 +294,11 @@ func newBackupCommand() *cobra.Command {
return err 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) _, err = fmt.Fprintf(cmd.OutOrStdout(), "备份已创建:%s\n", output)
return err return err
}, },
@@ -306,7 +311,7 @@ func newRestoreCommand() *cobra.Command {
var input string var input string
command := &cobra.Command{ command := &cobra.Command{
Use: "restore", Use: "restore",
Short: "恢复 SQLite 数据库备份", Short: "恢复配置和数据库备份",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
input, err := validateRestoreInput(input) input, err := validateRestoreInput(input)
if err != nil { if err != nil {
@@ -319,16 +324,24 @@ func newRestoreCommand() *cobra.Command {
} }
currentPath := filepath.Clean(resolveConfigPath()) currentPath := filepath.Clean(resolveConfigPath())
_, currentConfigErr := config.Load(currentPath) currentConfig, currentConfigErr := config.Load(currentPath)
if currentConfigErr != nil && !errors.Is(currentConfigErr, os.ErrNotExist) { if currentConfigErr != nil && !errors.Is(currentConfigErr, os.ErrNotExist) {
return fmt.Errorf("读取当前配置失败:%w", currentConfigErr) 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() { if info, statErr := os.Stat(currentPath); statErr == nil && !info.Mode().IsRegular() {
return errors.New("当前配置路径不是普通文件") return errors.New("当前配置路径不是普通文件")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) { } else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return fmt.Errorf("检查当前配置失败:%w", statErr) 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") databaseSource := filepath.Join(input, "scert.db")
databaseSourceInfo, databaseSourceErr := os.Stat(databaseSource) databaseSourceInfo, databaseSourceErr := os.Stat(databaseSource)
databaseSourceExists := databaseSourceErr == nil databaseSourceExists := databaseSourceErr == nil
@@ -338,6 +351,9 @@ func newRestoreCommand() *cobra.Command {
if databaseSourceExists && !databaseSourceInfo.Mode().IsRegular() { if databaseSourceExists && !databaseSourceInfo.Mode().IsRegular() {
return errors.New("备份数据库不是普通文件") 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 cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists {
if samePath(databaseSource, cfg.Database.DSN) { if samePath(databaseSource, cfg.Database.DSN) {
return errors.New("备份数据库与当前数据库路径相同") 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 { if err := cfg.Save(currentPath); err != nil {
return err return err
} }
@@ -382,6 +406,20 @@ func newRestoreCommand() *cobra.Command {
return fmt.Errorf("恢复 SQLite 数据库失败:%w", err) 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) _, err = fmt.Fprintf(cmd.OutOrStdout(), "恢复已完成:%s\n", input)
return err return err
}, },
@@ -483,6 +521,18 @@ func setConfigValue(cfg *config.Config, key, value string) error {
return fmt.Errorf("续期阈值格式无效:%w", err) return fmt.Errorf("续期阈值格式无效:%w", err)
} }
cfg.ACME.RenewalThresholdDays = parsed 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": case "dns.provider":
cfg.DNS.Provider = value cfg.DNS.Provider = value
case "dns.credential_ref": case "dns.credential_ref":
+9
View File
@@ -50,6 +50,15 @@ func TestSetConfigValueUpdatesAndValidatesAllowedFields(t *testing.T) {
if cfg.Notification.HTTPLoginPath != "/api/login" { if cfg.Notification.HTTPLoginPath != "/api/login" {
t.Fatalf("HTTP 登录路径未更新:%s", cfg.Notification.HTTPLoginPath) 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 { if err := setConfigValue(&cfg, "admin.password_hash", "plain"); err == nil {
t.Fatal("不应允许直接修改密码摘要") 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/buildinfo"
"git.pcux.cn/xuans/Scert/backend/internal/certificate" "git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/config" "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/domain"
"git.pcux.cn/xuans/Scert/backend/internal/firewall" "git.pcux.cn/xuans/Scert/backend/internal/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup" "git.pcux.cn/xuans/Scert/backend/internal/setup"
) )
@@ -159,15 +161,21 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
return err return err
} }
} }
cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
if err != nil {
return err
}
if err := setup.Apply(&cfg, input); err != nil { if err := setup.Apply(&cfg, input); err != nil {
cleanupSecret()
return err return err
} }
firewallResult, err := saveSetupWithFirewall(cmd.Context(), cfg, path, firewallManager) firewallResult, err := saveSetupWithFirewall(cmd.Context(), cfg, path, firewallManager)
if err != nil { if err != nil {
cleanupSecret()
return err return err
} }
fmt.Fprintf(cmd.OutOrStdout(), "初始化配置已保存:%s\n", path) 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(), "本机防火墙:%s\n", firewallResult.Message)
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL()) fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL())
return nil return nil
@@ -195,8 +203,8 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
command.Flags().IntVar(&emailRetryCount, "email-retry-count", 3, "通知失败重试次数") command.Flags().IntVar(&emailRetryCount, "email-retry-count", 3, "通知失败重试次数")
command.Flags().StringVar(&emailRetryIntervals, "email-retry-intervals", "30,120,600", "通知重试间隔(秒,逗号分隔)") command.Flags().StringVar(&emailRetryIntervals, "email-retry-intervals", "30,120,600", "通知重试间隔(秒,逗号分隔)")
command.Flags().StringVar(&dnsProvider, "dns-provider", "", "DNS API 服务商标识") command.Flags().StringVar(&dnsProvider, "dns-provider", "", "DNS API 服务商标识")
command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用,不保存明文密钥") command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用")
command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过外部验证测试") command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过验证测试")
command.Flags().StringVar(&certificateRoot, "certificate-root", "", "证书部署根目录,默认使用系统目录") command.Flags().StringVar(&certificateRoot, "certificate-root", "", "证书部署根目录,默认使用系统目录")
command.Flags().StringVar(&webHostname, "web-hostname", "", "管理页面域名") command.Flags().StringVar(&webHostname, "web-hostname", "", "管理页面域名")
command.Flags().StringVar(&webPublicIP, "web-public-ip", "", "没有域名时使用的公网 IP") 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 return err
} }
value.EmailRecipients = splitValues(receiver) value.EmailRecipients = splitValues(receiver)
value.DNSProvider, err = ask(reader, output, "DNS API 服务商 *", "") value.DNSProvider, err = askDNSProvider(reader, output)
if err != nil { if err != nil {
return err return err
} }
value.DNSCredentialRef, err = ask(reader, output, "DNS 凭据引用 *(不要输入明文密钥)", "") value.DNSCredentials, err = askDNSCredentials(reader, output, value.DNSProvider)
if err != nil { if err != nil {
return err return err
} }
value.DNSVerified, err = askYesNo(reader, output, "DNS API 是否已经完成验证测试?", false) value.DNSTestDomain, err = ask(reader, output, "DNS 权限测试域名 *", "")
if err != nil { if err != nil {
return err return err
} }
@@ -297,6 +305,120 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
return err 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) { func ask(reader *bufio.Reader, output io.Writer, label, defaultValue string) (string, error) {
if defaultValue != "" { if defaultValue != "" {
fmt.Fprintf(output, "%s [%s]:", label, defaultValue) fmt.Fprintf(output, "%s [%s]:", label, defaultValue)
+85
View File
@@ -1,6 +1,7 @@
package cli package cli
import ( import (
"bufio"
"bytes" "bytes"
"context" "context"
"errors" "errors"
@@ -12,7 +13,10 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/buildinfo" "git.pcux.cn/xuans/Scert/backend/internal/buildinfo"
"git.pcux.cn/xuans/Scert/backend/internal/config" "git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/deployment" "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/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup"
) )
type cliFakeFirewallManager struct { 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) { func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
baseDir := t.TempDir() baseDir := t.TempDir()
blockedParent := filepath.Join(baseDir, "blocked") blockedParent := filepath.Join(baseDir, "blocked")
@@ -197,3 +231,54 @@ func TestSaveSetupWithFirewallReportsRollbackFailure(t *testing.T) {
t.Fatalf("防火墙回滚失败应返回明确错误:%v", err) 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/mail"
"net/url" "net/url"
"os" "os"
"os/user"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strconv"
"strings" "strings"
) )
@@ -72,10 +74,12 @@ type PathsConfig struct {
} }
type ACMEConfig struct { type ACMEConfig struct {
CA string `json:"ca"` CA string `json:"ca"`
Environment string `json:"environment"` Environment string `json:"environment"`
AccountEmail string `json:"account_email"` AccountEmail string `json:"account_email"`
RenewalThresholdDays int `json:"renewal_threshold_days"` RenewalThresholdDays int `json:"renewal_threshold_days"`
PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
} }
type DNSConfig struct { type DNSConfig struct {
@@ -119,8 +123,14 @@ func Default(baseDir string) Config {
MaxOpenConns: 4, MaxIdleConns: 2, ConnMaxLifetimeMins: 30, MaxOpenConns: 4, MaxIdleConns: 2, ConnMaxLifetimeMins: 30,
}, },
Paths: paths, Paths: paths,
ACME: ACMEConfig{CA: "letsencrypt", Environment: "staging", RenewalThresholdDays: 6}, ACME: ACMEConfig{
DNS: DNSConfig{VerificationState: "not_configured"}, CA: "letsencrypt",
Environment: "staging",
RenewalThresholdDays: 6,
PropagationTimeoutSecs: 900,
PropagationPollingIntervalSecs: 10,
},
DNS: DNSConfig{VerificationState: "not_configured"},
Notification: NotificationConfig{ Notification: NotificationConfig{
HTTPHeaders: map[string]string{}, HTTPHeaders: map[string]string{},
HTTPPath: "/api/email/send", HTTPPath: "/api/email/send",
@@ -207,6 +217,12 @@ func (c *Config) Normalize() {
if c.DNS.VerificationState == "" { if c.DNS.VerificationState == "" {
c.DNS.VerificationState = "not_configured" 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 == "" { if c.Notification.HTTPPath == "" {
c.Notification.HTTPPath = "/api/email/send" 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 { if err := os.Chmod(path, 0o600); err != nil {
return fmt.Errorf("设置配置文件权限失败:%w", err) return fmt.Errorf("设置配置文件权限失败:%w", err)
} }
if err := applyLinuxServiceOwnership(filepath.Dir(path), path); err != nil {
return fmt.Errorf("设置配置文件归属失败:%w", err)
}
return nil 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 { func (c Config) Validate() error {
if c.Version != CurrentVersion { if c.Version != CurrentVersion {
return fmt.Errorf("配置版本不兼容:%d", c.Version) return fmt.Errorf("配置版本不兼容:%d", c.Version)
@@ -303,6 +354,15 @@ func (c Config) Validate() error {
if c.ACME.RenewalThresholdDays < 1 { if c.ACME.RenewalThresholdDays < 1 {
return fmt.Errorf("续期阈值必须大于 0") 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" { 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) return fmt.Errorf("DNS 验证状态无效:%s", c.DNS.VerificationState)
} }
@@ -369,19 +429,37 @@ func (c Config) Validate() error {
// ResetURL 返回通过主 Web 服务访问密码重置入口的公开地址。 // ResetURL 返回通过主 Web 服务访问密码重置入口的公开地址。
func (c Config) ResetURL() string { func (c Config) ResetURL() string {
host := strings.TrimSpace(c.Web.Hostname) rawHost := strings.TrimSpace(c.Web.Hostname)
if host == "" { if rawHost == "" {
host = strings.TrimSpace(c.Web.PublicIP) rawHost = strings.TrimSpace(c.Web.PublicIP)
} }
if host == "" { if rawHost == "" {
return "" return ""
} }
if parsed, err := url.Parse(host); err == nil && parsed.Hostname() != "" { host, _ := splitResetHost(rawHost)
host = parsed.Hostname()
}
host = strings.Trim(host, "[]") 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 + "]" host = "[" + host + "]"
} }
return (&url.URL{Scheme: "https", Host: host, Path: "/reset"}).String() 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 := Default(t.TempDir())
cfg.Web.Hostname = "scert.example.test" cfg.Web.Hostname = "scert.example.test"
cfg.Server.Port = 8443 cfg.Server.Port = 8443
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { if value := cfg.ResetURL(); value != "https://scert.example.test/reset" {
t.Fatalf("域名密码重置地址不正确:%s", value) t.Fatalf("密码重置地址不得暴露主服务端口:%s", value)
} }
cfg.Server.Port = 443 cfg.Server.Port = 443
if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { 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 := Default(t.TempDir())
cfg.Web.PublicIP = "2001:db8::10" cfg.Web.PublicIP = "2001:db8::10"
cfg.Server.Port = 8443 cfg.Server.Port = 8443
@@ -116,3 +116,95 @@ func TestSavedConfigDoesNotContainIndependentResetPort(t *testing.T) {
t.Fatalf("配置文件不应再包含独立密码重置监听配置:%s", content) 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 { func ufwIsActive(output []byte) bool {
for _, line := range strings.Split(strings.ToLower(string(output)), "\n") { 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 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) { func TestFirewalldCreatesPermanentRuleAndReloads(t *testing.T) {
runner := &fakeRunner{ runner := &fakeRunner{
paths: map[string]string{"firewall-cmd": "/usr/bin/firewall-cmd"}, 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" "git.pcux.cn/xuans/Scert/backend/internal/sshkey"
) )
type setupSecretWriter interface {
Put(context.Context, string, map[string]string) error
}
type Dependencies struct { type Dependencies struct {
Config config.Config Config config.Config
ConfigPath string ConfigPath string
@@ -35,6 +39,7 @@ type Dependencies struct {
Servers repository.ServerRepository Servers repository.ServerRepository
SSHKeys *sshkey.Service SSHKeys *sshkey.Service
SetupDNS setupDNSVerifier SetupDNS setupDNSVerifier
Secrets setupSecretWriter
Firewall firewall.Manager Firewall firewall.Manager
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
@@ -56,6 +61,7 @@ type Server struct {
servers repository.ServerRepository servers repository.ServerRepository
sshKeys *sshkey.Service sshKeys *sshkey.Service
setupDNS setupDNSVerifier setupDNS setupDNSVerifier
secrets setupSecretWriter
firewall firewall.Manager firewall firewall.Manager
issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
issueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) issueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
@@ -84,7 +90,7 @@ func New(deps Dependencies) *Server {
router.Use(gin.Recovery()) router.Use(gin.Recovery())
server := &Server{ server := &Server{
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger, 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, servers: deps.Servers,
sshKeys: deps.SSHKeys, sshKeys: deps.SSHKeys,
issueCertificate: deps.IssueCertificate, issueCertificate: deps.IssueCertificate,
+162 -74
View File
@@ -2,6 +2,8 @@ package httpapi
import ( import (
"context" "context"
"crypto/rand"
"encoding/base64"
"errors" "errors"
"fmt" "fmt"
"net" "net"
@@ -27,37 +29,40 @@ type setupDNSVerifier interface {
} }
type setupRequest struct { type setupRequest struct {
AdminUsername string `json:"admin_username"` AdminUsername string `json:"admin_username"`
AdminEmail string `json:"admin_email"` AdminEmail string `json:"admin_email"`
AdminPassword string `json:"admin_password"` AdminPassword string `json:"admin_password"`
ServerPort int `json:"server_port"` ServerPort int `json:"server_port"`
EmailHTTPEnabled *bool `json:"email_http_enabled"` EmailHTTPEnabled *bool `json:"email_http_enabled"`
EmailProvider string `json:"email_provider"` EmailProvider string `json:"email_provider"`
EmailEndpoint string `json:"email_endpoint"` EmailEndpoint string `json:"email_endpoint"`
EmailHTTPPath string `json:"email_http_path"` EmailHTTPPath string `json:"email_http_path"`
EmailHTTPLoginPath string `json:"email_http_login_path"` EmailHTTPLoginPath string `json:"email_http_login_path"`
EmailHTTPAuthMode string `json:"email_http_auth_mode"` EmailHTTPAuthMode string `json:"email_http_auth_mode"`
EmailHTTPCredentialRef string `json:"email_http_credential_ref"` EmailHTTPCredentialRef string `json:"email_http_credential_ref"`
EmailHTTPHeaders map[string]string `json:"email_http_headers"` EmailHTTPCredentials map[string]string `json:"email_http_credentials"`
EmailEventMode string `json:"email_event_mode"` EmailHTTPHeaders map[string]string `json:"email_http_headers"`
EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"` EmailEventMode string `json:"email_event_mode"`
EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"` EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"`
EmailIncludeManagementURL bool `json:"email_include_management_url"` EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"`
EmailSenderName string `json:"email_sender_name"` EmailIncludeManagementURL bool `json:"email_include_management_url"`
EmailSenderEmail string `json:"email_sender_email"` EmailSenderName string `json:"email_sender_name"`
Recipients []string `json:"recipients"` EmailSenderEmail string `json:"email_sender_email"`
EmailTimeoutSecs int `json:"email_timeout_secs"` Recipients []string `json:"recipients"`
EmailRetryCount int `json:"email_retry_count"` EmailTimeoutSecs int `json:"email_timeout_secs"`
EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"` EmailRetryCount int `json:"email_retry_count"`
DNSProvider string `json:"dns_provider"` EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"`
DNSCredentialRef string `json:"dns_credential_ref"` DNSProvider string `json:"dns_provider"`
DNSVerificationToken string `json:"dns_verification_token"` DNSCredentialRef string `json:"dns_credential_ref"`
DNSTestDomain string `json:"dns_test_domain"` DNSVerificationToken string `json:"dns_verification_token"`
CertificateRoot string `json:"certificate_root"` DNSTestDomain string `json:"dns_test_domain"`
WebHostname string `json:"web_hostname"` PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
WebPublicIP string `json:"web_public_ip"` PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
WebEnabled *bool `json:"web_enabled"` CertificateRoot string `json:"certificate_root"`
HTTPSMode string `json:"https_mode"` WebHostname string `json:"web_hostname"`
WebPublicIP string `json:"web_public_ip"`
WebEnabled *bool `json:"web_enabled"`
HTTPSMode string `json:"https_mode"`
} }
type dnsTestRequest struct { type dnsTestRequest struct {
@@ -91,19 +96,21 @@ func (s *Server) setupStatus(c *gin.Context) {
} }
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"initialized": cfg.SetupReady, "initialized": cfg.SetupReady,
"phase": phase, "phase": phase,
"blockers": blockers, "blockers": blockers,
"server_port": cfg.Server.Port, "server_port": cfg.Server.Port,
"reset_url": cfg.ResetURL(), "reset_url": cfg.ResetURL(),
"https_mode": cfg.Server.HTTPSMode, "https_mode": cfg.Server.HTTPSMode,
"web_enabled": cfg.Web.Enabled, "web_enabled": cfg.Web.Enabled,
"web_hostname": cfg.Web.Hostname, "web_hostname": cfg.Web.Hostname,
"web_public_ip": cfg.Web.PublicIP, "web_public_ip": cfg.Web.PublicIP,
"certificate_root": cfg.Paths.Certificate, "certificate_root": cfg.Paths.Certificate,
"dns_provider": cfg.DNS.Provider, "dns_provider": cfg.DNS.Provider,
"dns_verification_state": cfg.DNS.VerificationState, "dns_verification_state": cfg.DNS.VerificationState,
"dns_test_available": s.setupDNS != nil, "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 { if request.EmailHTTPEnabled != nil {
emailHTTPEnabled = *request.EmailHTTPEnabled 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 updated := s.config
err := setup.Apply(&updated, setup.Input{ err := setup.Apply(&updated, setup.Input{
AdminUsername: request.AdminUsername, AdminUsername: request.AdminUsername,
AdminEmail: request.AdminEmail, AdminEmail: request.AdminEmail,
AdminPassword: request.AdminPassword, AdminPassword: request.AdminPassword,
ServerPort: request.ServerPort, ServerPort: request.ServerPort,
EmailHTTPEnabled: emailHTTPEnabled, EmailHTTPEnabled: emailHTTPEnabled,
EmailProvider: request.EmailProvider, EmailProvider: request.EmailProvider,
EmailEndpoint: request.EmailEndpoint, EmailEndpoint: request.EmailEndpoint,
EmailHTTPPath: request.EmailHTTPPath, EmailHTTPPath: request.EmailHTTPPath,
EmailHTTPLoginPath: request.EmailHTTPLoginPath, EmailHTTPLoginPath: request.EmailHTTPLoginPath,
EmailHTTPAuthMode: request.EmailHTTPAuthMode, EmailHTTPAuthMode: request.EmailHTTPAuthMode,
EmailHTTPCredentialRef: request.EmailHTTPCredentialRef, EmailHTTPCredentialRef: emailCredentialRef,
EmailHTTPHeaders: request.EmailHTTPHeaders, EmailHTTPHeaders: request.EmailHTTPHeaders,
EmailEventMode: request.EmailEventMode, EmailEventMode: request.EmailEventMode,
EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails, EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails,
EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial, EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial,
EmailIncludeManagementURL: request.EmailIncludeManagementURL, EmailIncludeManagementURL: request.EmailIncludeManagementURL,
EmailSenderName: request.EmailSenderName, EmailSenderName: request.EmailSenderName,
EmailSenderEmail: request.EmailSenderEmail, EmailSenderEmail: request.EmailSenderEmail,
EmailRecipients: request.Recipients, EmailRecipients: request.Recipients,
EmailTimeoutSecs: request.EmailTimeoutSecs, EmailTimeoutSecs: request.EmailTimeoutSecs,
EmailRetryCount: request.EmailRetryCount, EmailRetryCount: request.EmailRetryCount,
EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs, EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs,
DNSProvider: request.DNSProvider, DNSProvider: request.DNSProvider,
DNSCredentialRef: request.DNSCredentialRef, DNSCredentialRef: request.DNSCredentialRef,
DNSVerified: true, DNSVerified: true,
CertificateRoot: request.CertificateRoot, PropagationTimeoutSecs: request.PropagationTimeoutSecs,
WebHostname: request.WebHostname, PropagationPollingIntervalSecs: request.PropagationPollingIntervalSecs,
WebPublicIP: request.WebPublicIP, CertificateRoot: request.CertificateRoot,
WebEnabled: webEnabled, WebHostname: request.WebHostname,
HTTPSMode: request.HTTPSMode, WebPublicIP: request.WebPublicIP,
WebEnabled: webEnabled,
HTTPSMode: request.HTTPSMode,
}) })
if err != nil { if err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err) 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.TLSCert = savedCertificate.FullChainPath
updated.Server.TLSKey = savedCertificate.PrivateKeyPath 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 updated.SetupReady = true
if err := updated.Validate(); err != nil { if err := updated.Validate(); err != nil {
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != 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)) ip := net.ParseIP(strings.TrimSpace(host))
return ip != nil && ip.IsLoopback() 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 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 { type fakeFirewallManager struct {
result firewall.Result result firewall.Result
openErr error openErr error
@@ -186,6 +202,8 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
"dns_credential_ref":"secret://dns/cloudflare/default", "dns_credential_ref":"secret://dns/cloudflare/default",
"dns_verification_token":"verified-token", "dns_verification_token":"verified-token",
"dns_test_domain":"scert.example.test", "dns_test_domain":"scert.example.test",
"propagation_timeout_secs":1200,
"propagation_polling_interval_secs":15,
"certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `", "certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `",
"web_hostname":"scert.example.test", "web_hostname":"scert.example.test",
"web_enabled":true, "web_enabled":true,
@@ -229,6 +247,9 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
if len(saved.Notification.Recipients) != 1 { if len(saved.Notification.Recipients) != 1 {
t.Fatalf("通知收件人未去重:%v", saved.Notification.Recipients) 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 := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
repeat.RemoteAddr = "127.0.0.1:53001" 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) { func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) {
cfg := config.Default(t.TempDir()) cfg := config.Default(t.TempDir())
verifier := &fakeSetupDNSVerifier{checkErr: errors.New("DNS 验证令牌无效或已经过期,请重新测试")} 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) { func TestSetupApplyRejectsOversizedRequest(t *testing.T) {
cfg := config.Default(t.TempDir()) cfg := config.Default(t.TempDir())
server := New(Dependencies{ 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.UpdateTask(context.Background(), task.ID, status, "certificate_issue", message, &now, &finished)
_ = s.tasks.FinishAttempt(context.Background(), attempt.ID, status, message, &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 { if s.audit != nil {
auditStatus := status auditStatus := status
if issueErr != nil { if issueErr != nil {
@@ -105,12 +111,6 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
c.JSON(http.StatusBadGateway, response) c.JSON(http.StatusBadGateway, response)
return return
} }
task.Status = status
task.Stage = "certificate_issue"
task.Message = message
task.StartedAt = &now
task.FinishedAt = &finished
task.UpdatedAt = finished
response["task"] = task response["task"] = task
c.JSON(http.StatusOK, response) c.JSON(http.StatusOK, response)
} }
+21
View File
@@ -2,6 +2,7 @@ package httpapi
import ( import (
"context" "context"
"encoding/json"
"errors" "errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -110,6 +111,26 @@ func TestTaskAPIReturnsFailureAndKeepsTaskTrace(t *testing.T) {
if response.Code != http.StatusBadGateway || !strings.Contains(response.Body.String(), "模拟证书申请失败") { if response.Code != http.StatusBadGateway || !strings.Contains(response.Body.String(), "模拟证书申请失败") {
t.Fatalf("失败任务响应错误:%d %s", response.Code, 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) items, err := taskRepo.ListTasks(context.Background(), "", 10)
if err != nil || len(items) != 1 || items[0].Status != "failed" { if err != nil || len(items) != 1 || items[0].Status != "failed" {
t.Fatalf("失败任务状态错误:%+v %v", items, err) t.Fatalf("失败任务状态错误:%+v %v", items, err)
+40 -30
View File
@@ -13,36 +13,40 @@ import (
) )
type Input struct { type Input struct {
AdminUsername string AdminUsername string
AdminEmail string AdminEmail string
AdminPassword string AdminPassword string
ServerPort int ServerPort int
EmailHTTPEnabled bool EmailHTTPEnabled bool
EmailProvider string EmailProvider string
EmailEndpoint string EmailEndpoint string
EmailHTTPPath string EmailHTTPPath string
EmailHTTPLoginPath string EmailHTTPLoginPath string
EmailHTTPAuthMode string EmailHTTPAuthMode string
EmailHTTPCredentialRef string EmailHTTPCredentialRef string
EmailHTTPHeaders map[string]string EmailHTTPHeaders map[string]string
EmailEventMode string EmailEventMode string
EmailIncludeDeploymentDetails bool EmailIncludeDeploymentDetails bool
EmailIncludeCertificateSerial bool EmailIncludeCertificateSerial bool
EmailIncludeManagementURL bool EmailIncludeManagementURL bool
EmailSenderName string EmailSenderName string
EmailSenderEmail string EmailSenderEmail string
EmailRecipients []string EmailRecipients []string
EmailTimeoutSecs int EmailTimeoutSecs int
EmailRetryCount int EmailRetryCount int
EmailRetryIntervalsSecs []int EmailRetryIntervalsSecs []int
DNSProvider string DNSProvider string
DNSCredentialRef string DNSCredentialRef string
DNSVerified bool DNSCredentials map[string]string
CertificateRoot string DNSTestDomain string
WebHostname string DNSVerified bool
WebPublicIP string PropagationTimeoutSecs int
WebEnabled bool PropagationPollingIntervalSecs int
HTTPSMode string CertificateRoot string
WebHostname string
WebPublicIP string
WebEnabled bool
HTTPSMode string
} }
func Apply(cfg *config.Config, input Input) error { 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.Email = adminEmail
cfg.Admin.PasswordHash = string(hash) cfg.Admin.PasswordHash = string(hash)
cfg.ACME.AccountEmail = adminEmail 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.Port = input.ServerPort
cfg.Server.HTTPSMode = input.HTTPSMode cfg.Server.HTTPSMode = input.HTTPSMode
cfg.Web.Enabled = input.WebEnabled cfg.Web.Enabled = input.WebEnabled
+85
View File
@@ -1,6 +1,9 @@
package setup package setup
import ( import (
"os"
"path/filepath"
"strings"
"testing" "testing"
"git.pcux.cn/xuans/Scert/backend/internal/config" "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, 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"}, 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, DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", DNSVerified: true, CertificateRoot: cfg.Paths.Certificate,
PropagationTimeoutSecs: 1200, PropagationPollingIntervalSecs: 15,
WebHostname: "panel.example.com", WebEnabled: true, WebHostname: "panel.example.com", WebEnabled: true,
}) })
if err != nil { if err != nil {
@@ -41,8 +45,44 @@ func TestApplyBuildsReadyConfig(t *testing.T) {
if cfg.ResetURL() != "https://panel.example.com/reset" { if cfg.ResetURL() != "https://panel.example.com/reset" {
t.Fatalf("密码重置地址生成错误:%s", cfg.ResetURL()) 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) { func TestApplyRejectsWebIPAsHostnamePair(t *testing.T) {
cfg := config.Default(t.TempDir()) cfg := config.Default(t.TempDir())
err := Apply(&cfg, Input{ err := Apply(&cfg, Input{
@@ -77,3 +117,48 @@ func TestApplyUsesAdminEmailAndStoresNotificationOptions(t *testing.T) {
t.Fatalf("HTTP 通知配置未正确保存:%+v", cfg.Notification) 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)
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ systemctl start Scert-admin
systemctl stop Scert-admin systemctl stop Scert-admin
``` ```
`Scert-admin` 不监听任何 TCP/UDP 端口。启动后,它只维护 Scert 主服务 `/reset` 路径的短时激活租约并输出一次性校验码;停止后入口立即失效,异常退出后入口会在租约过期时失效。云安全组只需由管理员根据初始化提示放行主服务端口。 `Scert-admin` 不监听任何 TCP/UDP 端口。启动后,它只维护 Scert 主服务 `/reset` 路径的短时激活租约,并将一次性校验码写入 `/run/scert-admin/reset-code` 受保护临时文件,不写入标准输出或 systemd 日志;停止后入口立即失效,异常退出后入口会在租约过期时失效。管理员可使用 `sudo cat /run/scert-admin/reset-code` 读取校验码,校验码在成功消费、服务停止或租约失效后自动销毁。云安全组只需由管理员根据初始化提示放行主服务端口。
## 参数说明 ## 参数说明
+4 -4
View File
@@ -116,8 +116,8 @@ validate_managed_paths() {
"$INSTALL_DIR/scert" \ "$INSTALL_DIR/scert" \
"$INSTALL_DIR/scert-admin" \ "$INSTALL_DIR/scert-admin" \
"$INSTALL_METADATA_FILE" \ "$INSTALL_METADATA_FILE" \
"$INSTALL_DIR/docs/Scert服务管理说明.md" \ "$INSTALL_DIR/docs/Scert-service-management.md" \
"$INSTALL_DIR/docs/Scert-admin服务管理说明.md" \ "$INSTALL_DIR/docs/Scert-admin-service-management.md" \
"$SERVICE_DIR/Scert.service" \ "$SERVICE_DIR/Scert.service" \
"$SERVICE_DIR/Scert-admin.service" \ "$SERVICE_DIR/Scert-admin.service" \
"$SERVICE_DROP_IN_DIR" \ "$SERVICE_DROP_IN_DIR" \
@@ -227,10 +227,10 @@ install_service_files() {
install -o root -g root -m 0644 \ install -o root -g root -m 0644 \
"$SCRIPT_DIR/systemd/Scert服务管理说明.md" \ "$SCRIPT_DIR/systemd/Scert服务管理说明.md" \
"$INSTALL_DIR/docs/Scert服务管理说明.md" "$INSTALL_DIR/docs/Scert-service-management.md"
install -o root -g root -m 0644 \ install -o root -g root -m 0644 \
"$SCRIPT_DIR/systemd/Scert-admin服务管理说明.md" \ "$SCRIPT_DIR/systemd/Scert-admin服务管理说明.md" \
"$INSTALL_DIR/docs/Scert-admin服务管理说明.md" "$INSTALL_DIR/docs/Scert-admin-service-management.md"
} }
reload_systemd() { reload_systemd() {
+5 -3
View File
@@ -1,6 +1,6 @@
[Unit] [Unit]
Description=Scert-admin 临时密码重置入口激活器 Description=Scert-admin 临时密码重置入口激活器
Documentation=file:///scert/docs/Scert-admin服务管理说明.md Documentation=file:///scert/docs/Scert-admin-service-management.md
After=network-online.target After=network-online.target
Wants=network-online.target Wants=network-online.target
ConditionPathExists=/scert/conf/scert.json ConditionPathExists=/scert/conf/scert.json
@@ -10,7 +10,9 @@ Type=simple
User=Scert User=Scert
Group=Scert Group=Scert
WorkingDirectory=/scert WorkingDirectory=/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
KillSignal=SIGTERM KillSignal=SIGTERM
TimeoutStopSec=15 TimeoutStopSec=15
Restart=no Restart=no
@@ -20,7 +22,7 @@ NoNewPrivileges=yes
PrivateTmp=yes PrivateTmp=yes
ProtectHome=yes ProtectHome=yes
ProtectSystem=full ProtectSystem=full
ReadWritePaths=/scert/data /scert/log ReadWritePaths=/scert/data /scert/log /run/scert-admin
RestrictAddressFamilies=AF_UNIX RestrictAddressFamilies=AF_UNIX
# Scert-admin 不监听任何 TCP/UDP 端口,只维护主服务 /reset 路径的短时激活租约。 # Scert-admin 不监听任何 TCP/UDP 端口,只维护主服务 /reset 路径的短时激活租约。
@@ -6,6 +6,12 @@
Linux 安装程序必须同时安装 `Scert` 和 `Scert-admin` 的 systemd 单元,但不得执行 `systemctl enable Scert-admin`,不得为 `Scert-admin` 创建开机启动软链接,也不得配置 `Restart=always` 或其他自动拉起策略。 Linux 安装程序必须同时安装 `Scert` 和 `Scert-admin` 的 systemd 单元,但不得执行 `systemctl enable Scert-admin`,不得为 `Scert-admin` 创建开机启动软链接,也不得配置 `Restart=always` 或其他自动拉起策略。
## 一次性校验码文件
Linux systemd 安装默认将校验码写入 `/run/scert-admin/reset-code`,该目录由 systemd 创建并设置为 `0700`,文件由 Scert-admin 创建并设置为 `0600`。直接运行程序时可以通过 `--code-output` 指定受保护的临时文件路径;不要将该路径放入公开目录、日志目录或备份目录。
校验码文件只用于人工读取,不属于配置数据。读取后不得复制到工单、聊天记录或日志中;密码重置成功后文件会立即销毁。
## 支持的生命周期控制 ## 支持的生命周期控制
日常运行时,`Scert-admin` 只支持以下两个控制命令: 日常运行时,`Scert-admin` 只支持以下两个控制命令:
@@ -32,7 +38,7 @@ systemd 无法阻止 root 或具备等效系统权限的操作者调用 `status`
5. 安装器、桌面端和运维文档只提供 `start`、`stop` 两个日常控制入口。 5. 安装器、桌面端和运维文档只提供 `start`、`stop` 两个日常控制入口。
6. 任何需要重新加载 unit 的行为仅限安装或升级阶段,不能通过 Web 管理界面触发。 6. 任何需要重新加载 unit 的行为仅限安装或升级阶段,不能通过 Web 管理界面触发。
7. 激活租约有效期为 90 秒,每 30 秒刷新;systemd 使用 `RuntimeMaxSec=30min` 将单次激活最长时间限制为 30 分钟。 7. 激活租约有效期为 90 秒,每 30 秒刷新;systemd 使用 `RuntimeMaxSec=30min` 将单次激活最长时间限制为 30 分钟。
8. 启动时生成的一次性校验码只在当前终端显示,状态文件仅保存 SHA-256 摘要,不保存明文校验码。 8. 启动时生成的一次性校验码不会写入标准输出或 systemd 日志。校验码只写入受保护的临时文件;systemd 单元使用 `RuntimeDirectory=scert-admin` 和 `RuntimeDirectoryMode=0700`,文件权限为 `0600`,仅允许 `Scert` 用户和 root 读取。
这组限制可以避免服务因安装配置被纳入开机启动、避免服务自动反复拉起,并彻底取消独立密码重置监听端口。需要注意:`/reset` 与 Scert 主服务共享 HTTPS 端口,激活期间仍可能被外部访问,因此完整密码重置实现还必须校验一次性校验码、限制请求频率、单次消费校验码并记录审计日志。不能把拥有 root 权限的恶意操作者从 systemd 管理能力中排除。 这组限制可以避免服务因安装配置被纳入开机启动、避免服务自动反复拉起,并彻底取消独立密码重置监听端口。需要注意:`/reset` 与 Scert 主服务共享 HTTPS 端口,激活期间仍可能被外部访问,因此完整密码重置实现还必须校验一次性校验码、限制请求频率、单次消费校验码并记录审计日志。不能把拥有 root 权限的恶意操作者从 systemd 管理能力中排除。
@@ -54,4 +60,4 @@ systemctl restart Scert-admin
安装完成后只提示管理员在确有需要时手动执行 `systemctl start Scert-admin`;不需要密码重置时保持服务停止,完成重置后立即执行 `systemctl stop Scert-admin`。 安装完成后只提示管理员在确有需要时手动执行 `systemctl start Scert-admin`;不需要密码重置时保持服务停止,完成重置后立即执行 `systemctl stop Scert-admin`。
当前实现已经接入一次性校验码、单次消费、密码复杂度校验、CSRF、同源校验、失败限流、配置原子保存和审计日志。密码重置成功后 `/reset` 立即关闭,Scert-admin 后续刷新旧租约也会自动终止。一次性校验码仍会在直接运行或 systemd 标准输出中呈现;正式上线前必须替换为不把明文校验码长期保留在持久日志中的受保护本地呈现机制。 当前实现已经接入一次性校验码、单次消费、密码复杂度校验、CSRF、同源校验、失败限流、配置原子保存和审计日志。密码重置成功后 `/reset` 立即关闭,Scert-admin 后续刷新旧租约也会自动终止。启动后请按终端提示,使用 root 或 `Scert` 用户读取受保护的临时校验码文件:`sudo cat /run/scert-admin/reset-code`。校验码在密码重置成功、服务停止或租约失效后自动销毁。
+1 -1
View File
@@ -1,6 +1,6 @@
[Unit] [Unit]
Description=Scert SSL 证书管理核心服务 Description=Scert SSL 证书管理核心服务
Documentation=file:///scert/docs/Scert服务管理说明.md Documentation=file:///scert/docs/Scert-service-management.md
After=network-online.target After=network-online.target
Wants=network-online.target Wants=network-online.target
ConditionPathExists=/scert/conf/scert.json ConditionPathExists=/scert/conf/scert.json
@@ -157,6 +157,8 @@ CLI 在初始化完成后不直接操作数据库。`init` 负责交互式填写
- `lego`、DNS provider、证书解析、任务调度和部署逻辑均作为 Go 模块或内部适配器实现,减少 Linux 与 Windows 的行为差异。 - `lego`、DNS provider、证书解析、任务调度和部署逻辑均作为 Go 模块或内部适配器实现,减少 Linux 与 Windows 的行为差异。
- 初始化阶段仍需要预检公网连通性、DNS API 权限、证书存储目录、系统时间和文件权限;这些预检必须使用 Go 实现,不依赖平台特定 Shell 命令。 - 初始化阶段仍需要预检公网连通性、DNS API 权限、证书存储目录、系统时间和文件权限;这些预检必须使用 Go 实现,不依赖平台特定 Shell 命令。
- DNS 凭据只以受控配置对象传递到 provider,禁止出现在命令行参数、日志、任务错误详情和 API 响应中。 - DNS 凭据只以受控配置对象传递到 provider,禁止出现在命令行参数、日志、任务错误详情和 API 响应中。
- DNS-01 传播最大等待时间:默认900秒,可通过配置修改。
- DNS-01 传播检测间隔:默认10秒,不得大于最大等待时间。
- 证书链和私钥校验优先使用 Go 标准库 `crypto/x509`;只有确实需要调用外部 Web 服务器检查命令时,才通过平台命令执行适配器运行白名单命令。 - 证书链和私钥校验优先使用 Go 标准库 `crypto/x509`;只有确实需要调用外部 Web 服务器检查命令时,才通过平台命令执行适配器运行白名单命令。
- Windows 和 Linux 的服务注册、文件权限、路径规范化和系统托盘仍由平台适配层分别实现。 - Windows 和 Linux 的服务注册、文件权限、路径规范化和系统托盘仍由平台适配层分别实现。
- 安装、升级和卸载不得删除用户证书、数据库或备份;所有删除操作必须经过 Web/CLI 明确确认并写入审计日志。 - 安装、升级和卸载不得删除用户证书、数据库或备份;所有删除操作必须经过 Web/CLI 明确确认并写入审计日志。
@@ -543,6 +545,8 @@ POST /api/v1/domains/{id}/renew
- 允许域名级覆盖:需要时覆盖全局 DNS 配置 - 允许域名级覆盖:需要时覆盖全局 DNS 配置
- CNAME 委派:自动创建、失败手动提示 - CNAME 委派:自动创建、失败手动提示
- DNS 传播检测超时 - DNS 传播检测超时
- DNS-01 传播最大等待时间:默认900秒,可通过配置修改。
- DNS-01 传播检测间隔:默认10秒,不得大于最大等待时间。
- 测试 DNS 权限和 Zone - 测试 DNS 权限和 Zone
**三、部署服务器配置** **三、部署服务器配置**
@@ -652,7 +656,6 @@ POST /api/v1/domains/{id}/test-servers
| check_interval_days | 常规检查间隔,默认 3 天 | | check_interval_days | 常规检查间隔,默认 3 天 |
| near_expiry_check_days | 临近到期检查阈值,默认 10 天 | | near_expiry_check_days | 临近到期检查阈值,默认 10 天 |
| renewal_threshold_days | 自动续期阈值,默认 6 天 | | renewal_threshold_days | 自动续期阈值,默认 6 天 |
| emergency_threshold_days | 紧急重试阈值,默认 3 天 |
| next_check_at | 下一次计划检查时间 | | next_check_at | 下一次计划检查时间 |
| next_renewal_at | 下一次计划续期时间,可为空 | | next_renewal_at | 下一次计划续期时间,可为空 |
| notification_rule_id | 域名级通知规则引用 | | notification_rule_id | 域名级通知规则引用 |
+8
View File
@@ -104,6 +104,12 @@
- [x] 支持 DNSPod API Token - [x] 支持 DNSPod API Token
- [x] 预留其他 DNS 服务商适配接口 - [x] 预留其他 DNS 服务商适配接口
- [x] 支持 CNAME 委派方式 - [x] 支持 CNAME 委派方式
- [x] 已确认需求:配置 DNS API 凭据时允许在 CLI 和 Web 初始化界面中明文查看,便于用户核对输入内容;提交保存后不得将明文凭据写入普通配置文件、数据库字段、日志或命令行输出。
- 【用户补充 U-074】(请填写):
- 补充内容:配置时允许明文显示,存入数据库和调用时加密
- 确认结果:已填写
- [x] 已确认需求:DNS API 凭据在线验证期间仅在内存中使用;验证成功后写入加密敏感信息存储并返回凭据引用,证书申请和续期时根据凭据引用解密后调用 Provider。
- 【实现约束】:Web 和 CLI 不得把完整凭据写入响应、日志、错误信息、测试输出或备份;配置文件只保存 `secret://` 凭据引用。
- [x] 第一阶段 DNS 验证方式支持 Cloudflare、阿里云 DNS、DNSPod、CNAME 委派、华为云、腾讯云、AWS Route 53、Google Cloud DNS,并预留其他服务商适配接口。 - [x] 第一阶段 DNS 验证方式支持 Cloudflare、阿里云 DNS、DNSPod、CNAME 委派、华为云、腾讯云、AWS Route 53、Google Cloud DNS,并预留其他服务商适配接口。
- [x] 已确认需求:第一阶段使用 Let's Encrypt 作为 ACME CA,并使用 `go-acme/lego` 负责证书申请、DNS-01 验证和自动续期。 - [x] 已确认需求:第一阶段使用 Let's Encrypt 作为 ACME CA,并使用 `go-acme/lego` 负责证书申请、DNS-01 验证和自动续期。
- 【用户补充 U-007】(请填写): - 【用户补充 U-007】(请填写):
@@ -539,6 +545,8 @@ web页面:站内信提示全部的通知状态
- [x] DNS API 密钥加密存储 - [x] DNS API 密钥加密存储
- [x] SMTP 密码加密存储 - [x] SMTP 密码加密存储
- [x] 日志中禁止记录明文密钥 - [x] 日志中禁止记录明文密钥
- [x] 已确认需求:敏感凭据在配置录入阶段允许明文显示,但仅限当前配置页面或当前交互输入过程;保存时使用 AES-GCM 等认证加密方式持久化,业务调用时按凭据引用解密,普通配置和数据库业务字段不保存明文。
- 【安全边界】:明文只允许短时存在于进程内存;验证失败、取消配置或保存失败时不得留下可复用的普通配置记录;敏感信息文件和主密钥继续使用受限权限保护。
- [x] 所有重要操作记录审计日志 - [x] 所有重要操作记录审计日志
- [x] 已确认需求:使用主密码保护的加密配置。 - [x] 已确认需求:使用主密码保护的加密配置。
- 【用户补充 U-063】(请填写): - 【用户补充 U-063】(请填写):
+488 -2
View File
@@ -1397,13 +1397,50 @@ Linux amd64 可以交叉编译
- [ ] 接入阿里云 DNS、DNSPod/腾讯云、华为云、AWS Route 53 和 Google Cloud DNS 在线适配器。 - [ ] 接入阿里云 DNS、DNSPod/腾讯云、华为云、AWS Route 53 和 Google Cloud DNS 在线适配器。
- [ ] 完成 CNAME 委派的目标 Provider 组合验证流程。 - [ ] 完成 CNAME 委派的目标 Provider 组合验证流程。
- [ ] 将 CLI `scert init` 从“凭据引用加手动确认”升级为真实 DNS 在线验证流程。 - [x] 将 CLI `scert init` 从“凭据引用加手动确认”升级为真实 DNS 在线验证流程;交互输入允许明文查看,验证通过后只保存加密凭据引用。
- [ ] 集成 `go-acme/lego` 真实证书签发、续期和初始化管理后台证书部署。 - [ ] 集成 `go-acme/lego` 真实证书签发、续期和初始化管理后台证书部署。
- [ ] 实现 HTTPS 双模式实际启动和初始化完成后的安全切换。 - [ ] 实现 HTTPS 双模式实际启动和初始化完成后的安全切换。
- [ ] 将敏感信息密文文件保存升级为安全原子替换,并补充异常中断恢复测试。 - [x] 将敏感信息密文文件保存升级为安全原子替换,并补充异常替换失败时保留旧文件的测试。
- [ ] 清理过期、重复测试或放弃初始化所产生的未引用 DNS 凭据。 - [ ] 清理过期、重复测试或放弃初始化所产生的未引用 DNS 凭据。
- [ ] 完成 Scert-admin 受保护的本地密码重置通道、安装器和系统服务。 - [ ] 完成 Scert-admin 受保护的本地密码重置通道、安装器和系统服务。
- [!] MySQL 5.7/8.0 真实实例测试仍等待明确的 DSN、端口、账号和密码;不得通过 PATH 自动判断 MySQL 实例。 - [!] MySQL 5.7/8.0 真实实例测试仍等待明确的 DSN、端口、账号和密码;不得通过 PATH 自动判断 MySQL 实例。
## 五十七、配置凭据明文查看与加密存储复审记录(2026-08-28)
### 57.1 需求清单
- [x] 配置阶段允许用户在 CLI 中明文查看 DNS API 凭据,便于核对输入内容。
- [x] 配置阶段允许用户在 Web 初始化页面中切换 DNS 凭据的明文显示和隐藏显示。
- [x] DNS 凭据在线验证时只在进程内存中传递给 Provider 测试器。
- [x] 验证成功后使用 AES-GCM 加密写入敏感信息存储,普通配置文件只保存 `secret://` 凭据引用。
- [x] 证书申请和续期通过凭据引用从敏感信息存储解密后创建 DNS Provider,不要求业务配置保存明文凭据。
- [x] 验证失败、初始化提交失败或配置保存失败时,不消费验证令牌,不把明文凭据写入普通配置或日志。
### 57.2 实现和测试状态
- [x] CLI 动态读取 DNS Provider 凭据字段,并在明文输入提示中明确说明提交后的加密保存边界。
- [x] Web 初始化向导新增“显示凭据明文”控制项;隐藏状态使用掩码显示,JSON 凭据不在隐藏状态下暴露内容。
- [x] 增加 CLI 凭据输入、验证、加密保存、输入清空和临时凭据清理测试。
- [x] 增加最终 `scert.json` 只保存 DNS 凭据引用、不保存 Token 或字段名的测试。
- [x] 增加证书服务根据加密凭据引用解密后创建 DNS Provider 的测试。
- [x] 增加敏感信息密文文件不包含明文凭据、权限受限和原子替换失败保留旧文件的测试。
### 57.3 验证结果
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] 前端 `npm.cmd run build` 通过。
- [✓] 代码和文档中未新增明文测试凭据输出;测试使用的凭据仅用于断言,未写入仓库文件。
### 57.4 复审边界
- [!] 浏览器真实操作时,初始化页面仍应限制为本机访问;明文凭据只应在用户明确操作期间短时显示。
- [!] 生产环境仍需继续执行真实 DNS Provider、Let’s Encrypt、MySQL 5.7/8.0 和远程部署验收;本轮自动化测试不替代实机验收。
- [!] 未引用敏感信息的定期清理策略仍需后续实现,不能在本轮擅自删除可能仍被业务引用的密文记录。
### 57.5 复审结论
本轮“配置时可明文查看、保存时加密、调用时按引用解密”的代码链路和自动化测试已完成并通过复审。明文凭据不进入普通配置文件、业务数据库字段、日志、错误响应或 Git 文件;生产级部署和真实外部服务验收仍按既有边界执行。
--- ---
## 三十一、敏感信息文件原子写入复审记录(2026-08-26) ## 三十一、敏感信息文件原子写入复审记录(2026-08-26)
@@ -2097,3 +2134,452 @@ Linux amd64 可以交叉编译
### 48.3 复审结论 ### 48.3 复审结论
本轮已完成 HTTP 邮件通知的 UTF-8 编码、业务响应判断、会话失效刷新和配置入口开发,并通过自动化验证;同时已通过临时邮件服务的接口详情确认修复后的中文内容正常。Scert 代码链路已经避免因客户端默认字符集导致的中文乱码,但最终收件邮箱客户端的到达和渲染仍需在发布环境继续复核。 本轮已完成 HTTP 邮件通知的 UTF-8 编码、业务响应判断、会话失效刷新和配置入口开发,并通过自动化验证;同时已通过临时邮件服务的接口详情确认修复后的中文内容正常。Scert 代码链路已经避免因客户端默认字符集导致的中文乱码,但最终收件邮箱客户端的到达和渲染仍需在发布环境继续复核。
## 四十九、持续开发复审记录(2026-08-28)
### 49.1 本轮需求清单
- [x] 继续复审上一轮 Ubuntu 模拟测试后的配置、任务、重置地址、安装服务和数据库备份恢复改动。
- [x] 增强 MySQL 5.7/8.0 备份 SQL 的数据字面量和恢复语句拆分兼容性。
- [x] 补充失败证书任务 HTTP 响应的嵌套状态、顶层状态和完成时间断言。
- [x] 补充管理页面域名带路径时的 `/reset` 地址边界测试。
- [x] 复核 systemd 技术文档路径与 Linux 安装脚本复制路径的一致性。
- [x] 执行本地全量自动化验证和 Windows/Linux amd64 交叉构建。
### 49.2 本轮开发任务状态
- [x] MySQL 备份导出支持 `sql.RawBytes`,并对字符串中的反斜杠、空字节、换行、回车、控制字符和单引号进行 SQL 字面量转义。
- [x] MySQL 恢复语句拆分器保留 `/*!...*/` 和 `/*+...*/` 可执行注释,避免丢失 MySQL 版本条件语句或优化提示。
- [x] 失败证书任务返回 JSON 中的 `task.status`、`task.stage`、`task.message`、完成时间、更新时间与 `task_status` 已增加一致性测试。
- [x] `/reset` 地址生成支持不带协议的域名、完整 URL、IPv4、IPv6、显式端口和附带路径的域名输入。
- [x] systemd unit 使用 ASCII 技术文档文件名,安装脚本保留中文源文档并复制为技术文件名。
### 49.3 自动化验证状态
- [✓] `go test ./...` 通过。
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] `go mod verify` 通过。
- [✓] `npm.cmd run build` 通过。
- [✓] Windows amd64 核心服务和 `Scert-admin` 交叉构建通过。
- [✓] Linux amd64 核心服务和 `Scert-admin` 交叉构建通过。
- [✓] `git diff --check` 通过;Git 输出的 LF/CRLF 提示不属于代码差异错误。
- [✓] 源码范围未发现 `acme.sh`、旧的 `super-admin-reset` 或旧独立重置端口配置引用;测试中保留的旧字段字符串仅用于确认配置不会再次写入该字段。
- [✓] 本轮未删除文件,未清理 `.runtime`,未执行 Git 提交、推送、重置或强制操作。
### 49.4 当前边界和后续验收
- [!] 尚未使用真实 MySQL 5.7 和 MySQL 8.0 实例执行备份、恢复、迁移和回滚;当前结论为代码级和 SQLite 自动化验证通过。
- [!] 尚未在真实 Let’s Encrypt、DNS Provider、远程 SSH/SFTP、Windows 服务器和各类反向代理环境中完成端到端验收。
- [!] 尚未完成生产级 HTTPS 终止、高级代理内部 HTTPS、Wails 桌面安装器、Windows Service 和跨平台防火墙的完整实机验收。
- [!] `Scert-admin` 一次性重置入口仍需受保护的本地校验码呈现机制,不能把标准输出校验码作为生产方案。
### 49.5 复审结论
本轮可以在本机独立验证的代码修复、测试和构建任务已完成并通过复审。项目仍处于“本地开发复审通过、真实环境和产品级验收未完成”状态,不能据此宣称完整需求已全部交付。
## 五十、Ubuntu 22.04 服务生命周期复测与重置地址修复记录(2026-08-28)
### 50.1 本轮需求清单
- [✓] 使用 Ubuntu 22.04 测试环境复测 `Scert` 和 `Scert-admin` 的手动启停流程。
- [✓] 确认 `Scert-admin` 不开机自启动、不监听独立 TCP/UDP 端口,只通过 `systemctl start Scert-admin` 和 `systemctl stop Scert-admin` 控制。
- [✓] 确认 `Scert-admin` 启动后 `/reset` 可用,停止后 `/reset` 返回 404。
- [✓] 按已确认规则修复重置地址,不在 `https://域名或IP/reset` 中暴露主服务端口。
- [✓] 同步当前 Linux amd64 构建产物到 Ubuntu 测试机,并保留远程旧二进制备份。
- [✓] 复核本机全量测试、竞态测试、静态检查、模块校验和前端构建。
### 50.2 Ubuntu 22.04 实测结果
- [✓] 测试环境为 Ubuntu 22.04.5 LTS,systemd 版本为 249.11。
- [✓] `Scert.service` 使用当前构建产物后正常启动并保持 `active` 状态。
- [✓] `Scert-admin.service` 使用当前构建产物后可以手动启动并保持 `active` 状态。
- [✓] `systemctl is-enabled Scert-admin` 返回 `static`,服务未配置 `[Install]` 和 `WantedBy=`,不能纳入开机启动。
- [✓] `ss -lntup` 仅观察到核心 `Scert` 监听 `*:5200`,没有发现 `Scert-admin` 独立监听端口。
- [✓] `Scert-admin` 启动后访问 `/reset` 返回 HTTP 200,页面中文正常显示。
- [✓] `systemctl stop Scert-admin` 后访问 `/reset` 返回 HTTP 404,临时入口已关闭。
- [✓] systemd unit 的 `Documentation` 已同步为 ASCII 技术文档路径,`systemctl show` 不再出现中文路径 URL 警告。
### 50.3 本轮修复内容
- [✓] `Config.ResetURL()` 现在始终根据管理域名或公网 IP 生成不带端口的 `https://域名或IP/reset` 地址。
- [✓] 保留 IPv4、IPv6、完整 URL、附带路径和显式端口输入的解析能力,但不把输入端口写入公开重置地址。
- [✓] 更新配置、初始化、管理接口和重置控制器相关测试,覆盖不带端口的域名、IPv4、IPv6、完整 URL和附带路径场景。
- [✓] 测试机直接模式使用临时自签名测试证书启动,仅用于本次 HTTPS 服务生命周期验证,不代表生产证书验收。
### 50.4 自动化验证状态
- [✓] `go test ./...` 通过。
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] `go mod verify` 通过。
- [✓] `npm.cmd run build` 通过。
- [✓] `git diff --check` 通过;Git 输出的换行格式提示不属于差异错误。
- [✓] Linux amd64 核心服务和 `Scert-admin` 重新构建并在 Ubuntu 22.04 测试机启动验证通过。
### 50.5 当前边界
- [!] 测试机使用的是临时自签名证书,尚未完成 Let’s Encrypt Production 真实申请、证书链校验和公网域名访问验收。
- [!] 尚未使用真实 DNS API 权限执行 DNS-01 记录创建、传播检测、清理和证书续期。
- [!] 尚未完成真实远程 SSH/SFTP 部署、Nginx reload、部署失败回滚以及 Windows 服务器实测。
- [!] `Scert-admin` 一次性校验码当前仍通过标准输出和 systemd 日志呈现,正式生产前需要替换为受保护的本地呈现机制。
- [!] 当前测试机原有 SQLite 配置未切换为 MySQL,MySQL 5.7 和 8.0 的真实迁移、备份、恢复和回滚仍需单独验收。
### 50.6 复审结论
Ubuntu 22.04 上的核心服务启动、`Scert-admin` 手动控制、无独立重置端口、`/reset` 入口启停生命周期和当前构建产物验证通过。本轮同时修复了重置地址仍暴露主服务端口的问题。项目仍为“本地代码和受控测试环境复审通过”,真实 ACME、DNS、远程部署、生产 HTTPS、Windows 和 MySQL 双版本验收仍未完成。
## 五十一、真实环境集成测试记录(2026-08-28)
### 51.1 本轮测试范围
- [x] 使用临时邮件服务执行真实登录和邮件发送接口调用。
- [✓] 在 Ubuntu 22.04 测试机上使用独立 MySQL 数据库执行 Scert 迁移。
- [✓] 在独立 MySQL 数据库中写入中文配置和域名测试数据。
- [✓] 执行 Scert MySQL 备份,检查备份文件权限和内容可恢复性。
- [✓] 将备份恢复到第二个独立 MySQL 数据库,并核对迁移、配置和域名数据。
- [✓] 停止临时 MySQL 测试服务,确认原有 `Scert.service` 和 `5200` 监听不受影响。
### 51.2 临时邮件服务真实调用结果
- [x] 登录接口返回 HTTP 200,业务错误码为 `0`。
- [x] 邮件发送接口返回 HTTP 200,业务错误码为 `0`。
- [x] 请求使用 UTF-8 中文主题、纯文本正文、HTML 正文和外部收件人。
- [x] 邮件服务实际登录响应只返回会话 Cookie,当前响应未返回 `smail_csrf` Cookie;在本次部署中,携带会话和同源请求头即可完成发送。
- [!] 尚未从外部收件箱客户端确认最终投递、中文显示和邮件状态异步处理结果;API 返回成功只代表邮件已通过接口校验并创建发送任务。
- [!] 需要在正式接入前确认临时服务部署版本是否与 `doc/后端接口说明文档.md` 中的 CSRF 约定一致,并保留无 CSRF Cookie 的兼容行为或补充服务端配置。
测试过程中未将密码、会话 Cookie 或令牌写入 Scert 配置、日志、Git 文件或本任务清单。
### 51.3 Ubuntu 22.04 MySQL 8.0 真实测试结果
测试机信息:
```text
系统:Ubuntu 22.04.5 LTS
MySQL:8.0.46-0ubuntu0.22.04.3
监听端口:3306
连接方式:本机 Unix Socket,使用独立测试数据库
```
- [✓] 创建独立数据库 `scert_real_test_20260828`,字符集为 `utf8mb4`;未修改原有数据库。
- [✓] 使用当前 Scert 二进制和 MySQL DSN 启动临时服务,应用启动自动完成 1—4 号迁移。
- [✓] 迁移后确认存在 `settings`、`domains`、`tasks`、`audit_logs`、`servers`、`domain_servers`、`task_attempts` 和 `schema_migrations` 表。
- [✓] 写入中文设置项和域名记录,读取结果与写入内容一致。
- [✓] 执行 `scert backup`,生成 `scert.json` 和 `scert.sql` 备份。
- [✓] SQL 备份文件权限为 `600`。
- [✓] 创建第二个独立数据库 `scert_real_restore_20260828`,执行 `scert restore` 后,迁移版本 1—4、中文设置项和域名记录均恢复正确。
- [✓] 临时服务停止后,原有 `Scert.service` 仍为运行状态,原有 `5200` 端口保持监听,临时 `5290` 端口已关闭。
### 51.4 MySQL 5.7 兼容性状态
- [!] 本轮未找到可安全使用的 MySQL 5.7 实际服务授权账号,未对本机或测试机的 MySQL 5.7 实例进行登录、迁移、备份或恢复操作。
- [✓] 已通过代码级迁移语句兼容性检查;当前实现避免使用 MySQL 5.7 不支持的 `ADD COLUMN IF NOT EXISTS`,并在迁移前查询字段和索引是否存在。
- [!] MySQL 5.7 仍需使用独立测试库完成真实迁移、中文数据、备份、恢复和重复迁移幂等性验证后,才能标记为复审通过。
### 51.5 DNS、ACME 和远程部署边界
- [!] 当前没有获得可确认的真实测试域名和可执行的 DNS API 凭据,本轮未创建或清理 `_acme-challenge` 记录,未执行 Let’s Encrypt Staging 或 Production 申请。
- [!] 当前未执行真实 SSH/SFTP 证书推送、Nginx/Caddy/Apache reload、失败回滚和部署后公网 HTTPS 校验。
- [!] Ubuntu 测试机本轮使用的临时自签名证书只用于 HTTPS 服务生命周期验证,不能作为 Let’s Encrypt 证书链验收结果。
### 51.6 本轮复审结论
- [✓] 临时邮件服务的真实登录和发送接口调用通过,Scert 当前 HTTP 通知请求格式与该部署的接口行为兼容。
- [✓] Ubuntu 22.04 + MySQL 8.0 的 Scert 迁移、中文数据读写、备份和恢复通过。
- [x] 外部邮箱最终收件、MySQL 5.7 真实实例、DNS API、Let’s Encrypt、远程服务器部署和多类反向代理仍处于等待真实环境或凭据验证状态。
当前准确结论:
```text
Scert 本地代码、Ubuntu 22.04 服务生命周期、HTTP 邮件接口调用和 MySQL 8.0 独立数据库流程已完成验证;
外部邮箱最终投递、MySQL 5.7 实例、DNS/ACME 证书申请、远程部署和生产级跨平台验收仍未完成。
```
## 五十二、持续开发:MySQL 恢复失败保护(2026-08-28)
### 52.1 本轮需求清单
- [✓] 复审当前未提交代码,确认不覆盖两个已有补丁文件,不执行文件删除和 Git 操作。
- [✓] 检查 MySQL 备份和恢复流程的失败安全边界。
- [✓] 补充 MySQL 恢复前快照和失败回滚保护。
- [✓] 防止不同数据库类型的备份被错误恢复。
- [✓] 完成 Go、前端和差异检查。
### 52.2 本轮代码调整
- [✓] MySQL 恢复前在配置的备份目录创建 `scert-before-restore-*` 快照目录。
- [✓] 快照目录权限设置为 `700`,SQL 快照文件权限设置为 `600`。
- [✓] MySQL 恢复失败时自动尝试恢复目标数据库快照。
- [✓] MySQL 数据库回滚失败时,将原始恢复错误和回滚错误同时返回。
- [✓] 配置文件恢复仍保留原有的失败回滚逻辑。
- [✓] SQLite 非内存数据库恢复时强制要求备份目录包含 `scert.db`。
- [✓] 备份配置与当前配置的数据库驱动不一致时拒绝恢复。
### 52.3 自动化验证
- [✓] `go test ./...` 通过。
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] `go mod verify` 通过。
- [✓] `npm.cmd run build` 通过。
- [✓] `git diff --check` 通过;仅报告现有 Windows 工作区换行格式提示,没有发现空白错误。
### 52.4 复审边界
- [!] 本轮未对真实 MySQL 5.7 服务执行故障注入回滚测试,仍需独立测试库和明确授权账号。
- [!] MySQL 恢复快照在恢复成功后保留,后续需要增加备份保留策略和管理员可控清理功能;本轮不自动删除快照。
- [!] DNS/ACME、远程服务器部署、生产 HTTPS、Windows 实机和外部邮箱最终投递仍不属于本轮已完成验收范围。
### 52.5 本轮复审结论
本轮代码修改已完成并通过现有自动化验证。MySQL 恢复流程现在具备恢复前快照、失败回滚和数据库类型隔离保护;但真实 MySQL 5.7 故障注入以及完整生产环境验收仍保持阻塞状态,不能标记为整体项目完成。
## 五十三、持续开发:Scert-admin 校验码安全呈现(2026-08-28)
### 53.1 本轮需求清单
- [✓] Scert-admin 不监听独立 TCP/UDP 端口,继续保持手动启动和停止策略。
- [✓] 一次性校验码不得写入标准输出、systemd 日志、配置文件或审计日志。
- [✓] Linux systemd 使用受保护的运行时目录保存一次性校验码。
- [✓] 校验码文件仅允许服务运行用户和 root 读取,并在使用后销毁。
- [✓] 补充服务停止、租约失效、成功消费和文件覆盖保护测试。
- [!] Windows 受 ACL 保护的本地校验码呈现适配仍需单独实现和实机验收。
### 53.2 本轮代码调整
- [✓] `Scert-admin` 增加 `--code-output` 参数,支持指定一次性校验码文件路径。
- [✓] Linux systemd 默认使用 `/run/scert-admin/reset-code`,并配置 `RuntimeDirectoryMode=0700`。
- [✓] 一次性校验码文件采用排他创建和 `0600` 权限,禁止覆盖已有文件。
- [✓] 状态文件只保存校验码 SHA-256 摘要和校验码文件路径,不保存明文校验码。
- [✓] 服务停止、租约失效、校验码消费成功后自动销毁校验码文件。
- [✓] 命令行只显示重置地址和受保护文件路径,不显示校验码明文。
- [✓] 更新 Linux systemd unit、部署说明和 Scert-admin 运维说明。
### 53.3 自动化验证
- [✓] Scert-admin 控制器测试通过。
- [✓] 校验码文件权限、内容、消费销毁、租约失效销毁和禁止覆盖测试通过。
- [✓] 命令行输出测试确认不会泄露一次性校验码。
- [✓] systemd unit 测试确认包含受保护运行时目录和 `--code-output` 参数。
### 53.4 复审边界
- [!] 本轮未在 Ubuntu 22.04 实机上验证 systemd `RuntimeDirectory` 实际权限、root/Scert 读取边界和 journal 输出;需要后续在测试机执行交互式验证。
- [!] Windows 暂使用通用文件实现,尚未切换为 ACL 或命名管道保护方案,不能标记为跨平台安全验收通过。
### 53.5 本轮复审结论
Scert-admin 的 Linux 代码路径已经不再通过标准输出泄露一次性校验码,默认 systemd 部署改为受保护的 `/run/scert-admin/reset-code` 临时文件,并覆盖了生命周期销毁和命令行输出回归测试。Linux 实机权限边界与 Windows 受保护呈现仍保持待验证状态。
## 五十四、持续开发:校验码跨平台保护接入复审(2026-08-28)
### 54.1 本轮需求清单
- [✓] 继续保留超级管理员、管理员、普通用户、多角色和权限控制逻辑,不改为单账户模式。
- [✓] 一次性校验码不得写入标准输出、systemd journal、普通配置、审计日志或备份。
- [✓] Linux 使用 `0600` 文件权限和受保护运行时目录保存一次性校验码。
- [✓] Windows 使用当前服务账户、Local System 和本地管理员组构造受保护 ACL。
- [✓] 校验码成功消费、服务停止、租约失效和过期消费时销毁临时文件。
- [✓] 已有校验码文件不得被新的重置会话覆盖。
### 54.2 代码复审与调整
- [✓] 复审发现 Windows ACL 函数已实现但未接入实际写入流程。
- [✓] `writeCodeFile` 在写入并同步校验码后调用 `protectCodeFile`,保护失败时沿用失败清理逻辑删除临时文件。
- [✓] Windows ACL 使用受保护 DACL,服务账户仅获得读取和删除权限,Local System 与本地管理员组保留管理权限。
- [✓] Linux 路径继续使用 `0600` 权限,不引入不必要的平台特定依赖。
- [✓] 保留排他创建逻辑,避免覆盖已有校验码文件。
### 54.3 自动化验证
- [✓] `go test ./...` 通过。
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] `go mod verify` 通过。
- [✓] `GOOS=windows GOARCH=amd64 go build ./internal/admin ./cmd/scert-admin` 通过。
- [✓] `npm.cmd run build` 通过。
- [✓] `git diff --check` 未发现空白错误;换行格式提示属于 Windows 工作区提示。
### 54.4 复审边界
- [!] 尚未在真实 Windows 服务账户环境中验证 ACL 的实际读取、删除和拒绝其他账户读取效果。
- [!] 尚未在 Ubuntu 22.04 实机中再次验证 systemd 运行时目录权限、journal 内容和停止服务后的文件销毁。
- [!] 真实 ACME/DNS API、远程 SSH 部署、Nginx/Caddy/Apache、生产 HTTPS 和外部邮箱最终投递仍不属于本轮已完成验收范围。
### 54.5 本轮复审结论
Windows ACL 保护现在已经接入一次性校验码实际写入流程,失败会自动清理临时文件;Linux 文件权限和生命周期销毁逻辑保持通过。自动化构建与测试通过,但 Windows 权限实测和 Ubuntu 22.04 systemd 实机复审仍需单独完成,不能将跨平台生产安全验收标记为已完成。
## 五十五、Ubuntu 22.04 实机复审:Scert-admin 受保护校验码(2026-08-28)
### 55.1 测试范围
- [✓] 在 Ubuntu 22.04.5 LTS 测试机 `192.168.2.3` 上部署本轮 Linux amd64 `Scert-admin` 构建产物。
- [✓] 部署本轮 `Scert-admin.service`,执行 `systemctl daemon-reload` 和 `systemd-analyze verify`。
- [✓] 测试机原有 `Scert-admin` 二进制和 unit 已创建带时间戳的 `/tmp` 备份,未删除原文件。
- [✓] 验证手动启停、运行时目录权限、校验码文件权限、日志泄露、网络监听和停止后销毁行为。
### 55.2 实机验证结果
- [✓] `systemctl is-enabled Scert-admin` 返回 `static`,没有开机自启动注册。
- [✓] `systemctl start Scert-admin` 后服务状态为 `active`。
- [✓] `/run/scert-admin` 实际权限为 `700`,所有者为 `Scert:Scert`。
- [✓] `/run/scert-admin/reset-code` 实际权限为 `600`,所有者为 `Scert:Scert`。
- [✓] 本次新版服务启动后的最近日志未发现校验码明文。
- [✓] 未发现 `Scert-admin` 独立 TCP/UDP 网络监听;核心服务继续使用既有 `5200` 监听。
- [✓] `systemctl stop Scert-admin` 后服务变为 `inactive`,校验码文件和运行时目录均被清理。
### 55.3 测试机历史遗留说明
- [!] 测试机旧版服务在本次升级前的历史 journal 中曾保存过明文校验码;这属于旧版本遗留日志,不能通过本轮代码自动消除。
- [!] 生产升级前应根据组织日志保留策略处理旧 journal,并确保升级后的服务不再写入明文校验码。
- [!] `systemd-analyze verify` 同时报告了测试机其他 `snapd.service` 的未知配置项警告,与 Scert unit 无关;Scert unit 本身未产生语法错误。
### 55.4 当前复审结论
Linux Ubuntu 22.04 上的 `Scert-admin` 手动启停、无开机自启动、无独立网络监听、受保护运行时目录、校验码权限、日志不泄露和停止后销毁均已完成实机验证。Windows ACL 仍只完成代码接入、自动化交叉编译和静态复审,尚未完成 Windows 服务账户权限实测,因此整体跨平台安全验收仍不能标记为完成。
## 五十六、真实 ACME/DNS 测试:阿里云 DNS 与 Let’s Encrypt(2026-08-28)
### 56.1 测试范围
- [✓] 使用项目现有 `go-acme/lego` 实现进行 DNS-01 验证。
- [✓] 使用阿里云 DNS Provider 验证 RAM 凭据和 DNS 记录操作权限。
- [✓] 测试域名 `salg.cn` 的 DNS TXT 记录创建、传播检查和清理。
- [!] 测试域名 `zhuguang.asia` 暂未申请证书,不修改其现有 DNS 配置。
- [✓] 证书申请使用独立临时进程和内存密钥,不写入 Scert 证书目录、配置、数据库或备份。
### 56.2 代码修正
- [✓] 修正 `backend/internal/certificate/lego.go`:ACME 账户邮箱仅用于账户注册,不再写入证书 CSR 的 `EmailAddresses` 字段。
- [✓] 修正后通过 Let’s Encrypt Staging 的证书申请验证,确认不再触发 `CSR contains one or more email address fields` 错误。
### 56.3 实测结果
- [✓] `salg.cn` 阿里云 DNS API 测试成功,临时 `_acme-challenge` TXT 记录能够创建和清理。
- [✓] `salg.cn` Let’s Encrypt Staging DNS-01 验证成功。
- [✓] `salg.cn` Let’s Encrypt Staging 证书签发成功。
- [✓] Staging 证书域名匹配成功,证书与私钥匹配成功。
- [✓] Staging 证书链解析成功,共解析到 5 张证书。
- [✓] Staging 证书有效期为 2026-08-28T15:49:14Z 至 2026-11-26T15:49:13Z。
- [✓] 通过阿里云 DNS API 查询确认测试结束后 `_acme-challenge.salg.cn` TXT 记录数为 0。
- [✓] `go test ./...`、`go vet ./...`、`go mod verify` 和 `npm.cmd run build` 全部通过。
### 56.4 `zhuguang.asia` 阻塞原因
- [!] `_acme-challenge.zhuguang.asia` 当前存在 CNAME 委派,目标为 `expired.hichina.com`。
- [!] 阿里云 Provider 按 CNAME 委派查找目标 DNS 区域时,无法在当前阿里云账号中找到 `expired.hichina.com` 托管区域。
- [!] 在用户修正或确认该 CNAME 委派前,不执行自动删除、替换或新增 DNS 记录。
### 56.5 Production 实测边界
- [!] `salg.cn` Production 申请已发起,但因递归 DNS 服务器在传播窗口内仍返回此前测试的旧 TXT 值,未能完成本次验证。
- [✓] Production 失败后 lego 已执行 DNS-01 清理和授权停用,没有留下运行中的申请任务。
- [!] 该失败暴露出 DNS 删除/新增后的缓存传播窗口约为 600 秒;后续应在生产流程中支持可配置传播等待时间、重试策略和失败后的明确诊断。
- [!] 本轮未将生产证书保存到 Scert 默认目录,也未执行远程服务器部署或修改 Nginx、Caddy、Apache 配置。
### 56.6 本轮复审结论
阿里云 DNS Provider 的 RAM 权限、`salg.cn` 的 DNS-01 验证、lego Staging 证书申请、证书解析、域名匹配、私钥匹配和清理流程已完成真实验证。当前需要后续处理的事项为:修正 `zhuguang.asia` 的 CNAME 委派,以及在 DNS 传播延迟场景下完善 Production 申请的等待和重试策略。Production 证书签发、证书落盘、自动续期、远程部署和线上 HTTPS 校验仍不能标记为整体完成。
## 五十七、DNS-01 传播等待与诊断配置(2026-08-29)
### 57.1 需求清单
- [✓] 为 DNS-01 增加可配置的最大传播等待时间。
- [✓] 为 DNS-01 增加可配置的传播检测间隔。
- [✓] 保留旧配置兼容性,读取缺少新字段的配置时自动补齐默认值。
- [✓] 对等待时间和检测间隔增加范围校验,避免无效参数进入证书申请流程。
- [✓] 证书申请失败时输出本次使用的传播等待参数,便于诊断 DNS 缓存传播延迟。
### 57.2 实现清单
- [✓] 在 `ACMEConfig` 中增加 `propagation_timeout_secs`,默认值为 900 秒。
- [✓] 在 `ACMEConfig` 中增加 `propagation_polling_interval_secs`,默认值为 10 秒。
- [✓] 通过 `challenge.ProviderTimeout` 包装实际 DNS Provider,并注入 `go-acme/lego`。
- [✓] 在 `scert config set` 支持修改上述两个配置项。
- [✓] 增加默认值、旧配置归一化、范围校验和保存加载测试。
- [✓] 增加 Provider 操作转发、参数读取、无效参数保护和空 Provider 测试。
- [✓] 保持敏感 DNS 凭据仅在调用时解密,未改变明文配置阶段和加密持久化策略。
### 57.3 参数规则
| 配置项 | 默认值 | 允许范围 | 说明 |
|---|---:|---:|---|
| `acme.propagation_timeout_secs` | 900 秒 | 1 至 86400 秒 | DNS 记录发布后,lego 等待验证传播的最长时间 |
| `acme.propagation_polling_interval_secs` | 10 秒 | 大于 0 且不大于等待时间 | lego 检查 DNS 记录传播状态的间隔 |
### 57.4 验证结果
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] `go mod verify` 通过。
- [✓] 前端生产构建通过。
- [✓] `git diff --check` 通过。
### 57.5 当前边界
- [!] 配置已接入真实 lego DNS-01 流程,但仍需使用真实 DNS Provider 和 Let's Encrypt Production 在公网传播延迟场景完成最终验收。
- [!] 本轮未修改远程服务器部署、Nginx、Caddy、Apache 或证书文件替换逻辑。
## 五十八、Web 初始化接入 DNS-01 传播等待配置(2026-08-29)
### 58.1 本轮需求清单
- [✓] Web 初始化向导可以配置 DNS-01 最大传播等待时间。
- [✓] Web 初始化向导可以配置 DNS-01 传播检测间隔。
- [✓] Web 表单显示默认值:最大等待 900 秒、检测间隔 10 秒。
- [✓] 前端阻止小于 1 秒、超过 86400 秒或检测间隔大于最大等待时间的输入。
- [✓] 配置完成前参数只保留在向导内存,提交时由后端统一校验并保存。
- [✓] 兼容未提交这两个字段的旧调用,后端沿用配置默认值。
### 58.2 代码调整
- [✓] `backend/internal/httpapi/setup.go` 接收并返回两个 DNS 传播配置字段。
- [✓] `backend/internal/setup/setup.go` 将 Web 初始化请求写入 `ACMEConfig`,保留零值缺省兼容行为。
- [✓] `frontend/src/views/SetupWizard/SetupWizard.js` 增加表单状态、前端校验和提交字段。
- [✓] `frontend/src/views/SetupWizard/SetupWizard.vue` 在 DNS 验证步骤增加两个中文配置项及说明。
- [✓] 保持页面相关文件按 `src/views/SetupWizard/` 目录集中管理。
### 58.3 自动化验证
- [✓] 增加初始化层的非法传播参数回归测试。
- [✓] 增加 Web 初始化接口保存传播参数回归测试。
- [✓] `go test -race ./...` 通过。
- [✓] `go vet ./...` 通过。
- [✓] `go mod verify` 通过。
- [✓] `npm.cmd run build` 通过。
- [✓] `git diff --check` 通过。
- [✓] 目标代码范围未发现连续问号、替换字符或错误换行标记。
### 58.4 复审边界
- [!] 本轮未使用浏览器 MCP 进行页面截图验收;本轮目标是配置链路接入,不包含布局和视觉改版。
- [!] 真实 DNS Provider、Let's Encrypt Production 公网传播延迟和生产续期仍需在授权环境完成最终验收。
- [!] 本轮未执行 Git 提交、推送、文件清理或删除。
## 五十九、初始化向导通知布局与敏感凭据交互优化(2026-08-29)
### 59.1 需求清单
- [x] 初始化向导第二步按服务配置、认证配置、敏感凭据、收发件人和投递策略分组显示。
- [x] HTTP 通知的 Token、HMAC 密钥和会话凭据支持配置时明文查看与隐藏切换。
- [x] 配置提交后由后端加密保存敏感凭据,普通配置文件不保存明文密钥。
- [x] DNS 凭据字段使用不同的动态 ID,避免模板静态检查发现重复 ID。
- [x] 页面显示文字保持中文,源码范围未发现 HTML 编码中文和替换字符。
### 59.2 实现与验证清单
- [x] 完成 `SetupWizard.vue` 中 DNS 普通凭据输入框动态 ID 修正。
- [x] 完成前端生产构建验证:`npm.cmd run build`。
- [x] 完成后端竞态测试:`go test -race ./...`。
- [x] 完成后端静态检查:`go vet ./...`。
- [x] 完成 Go 模块完整性检查:`go mod verify`。
- [x] 完成 Git 差异格式检查:`git diff --check`。
- [!] 浏览器 MCP 因共享 Chrome Profile 已被其他浏览器进程占用,本轮未完成真实截图验收;未强制关闭用户浏览器。
- [!] 低高度桌面窗口下的初始化向导最终视觉效果仍需在 MCP 可用后复测。
### 59.3 当前状态
本轮代码调整和自动化检查已完成,相关任务标记为“已完成,等待复审”。浏览器 MCP 视觉验收属于外部运行环境阻塞,不影响前端构建和后端自动化检查结果;待独立浏览器窗口可用后,再对桌面宽屏、中等窗口和低高度窗口进行实际显示复审。
File diff suppressed because it is too large. Load diff
+114 -5
View File
@@ -27,6 +27,9 @@ export function useSetupWizard(props, emit) {
const dnsTestError = ref(""); const dnsTestError = ref("");
const dnsProviders = ref([]); const dnsProviders = ref([]);
const dnsCredentials = ref({}); const dnsCredentials = ref({});
const dnsCredentialsVisible = ref(true);
const emailCredentials = ref("");
const emailCredentialsVisible = ref(true);
const dnsTestDomain = ref(props.status.web_hostname || ""); const dnsTestDomain = ref(props.status.web_hostname || "");
const dnsVerification = ref(null); const dnsVerification = ref(null);
const verificationClock = ref(Date.now()); const verificationClock = ref(Date.now());
@@ -60,6 +63,9 @@ export function useSetupWizard(props, emit) {
email_retry_intervals_secs: "30,120,600", email_retry_intervals_secs: "30,120,600",
recipients: "", recipients: "",
dns_provider: props.status.dns_provider || "cloudflare", dns_provider: props.status.dns_provider || "cloudflare",
propagation_timeout_secs: props.status.propagation_timeout_secs || 900,
propagation_polling_interval_secs:
props.status.propagation_polling_interval_secs || 10,
certificate_root: props.status.certificate_root || "", certificate_root: props.status.certificate_root || "",
web_hostname: props.status.web_hostname || "", web_hostname: props.status.web_hostname || "",
web_public_ip: props.status.web_public_ip || "", web_public_ip: props.status.web_public_ip || "",
@@ -70,6 +76,30 @@ export function useSetupWizard(props, emit) {
const targetLabel = computed(() => const targetLabel = computed(() =>
targetType.value === "hostname" ? "管理页面域名" : "公网 IP 地址", targetType.value === "hostname" ? "管理页面域名" : "公网 IP 地址",
); );
const emailCredentialLabel = computed(() => {
switch (form.value.email_http_auth_mode) {
case "bearer":
return "Bearer Token 凭据(JSON)";
case "hmac_sha256":
return "HMAC-SHA256 凭据(JSON)";
case "session":
return "登录会话凭据(JSON)";
default:
return "HTTP 通知凭据";
}
});
const emailCredentialPlaceholder = computed(() => {
switch (form.value.email_http_auth_mode) {
case "bearer":
return '{"token":"请输入 Bearer Token"}';
case "hmac_sha256":
return '{"secret":"请输入签名密钥"}';
case "session":
return '{"account":"请输入账号","password":"请输入密码"}';
default:
return "无需填写凭据";
}
});
const resetURLPreview = computed(() => { const resetURLPreview = computed(() => {
const rawHost = const rawHost =
targetType.value === "hostname" targetType.value === "hostname"
@@ -191,6 +221,33 @@ export function useSetupWizard(props, emit) {
return payload; return payload;
} }
function maskCredential(value) {
const text = String(value || "");
if (!text) return "";
return "•".repeat(Math.min(Math.max(text.length, 8), 64));
}
function emailCredentialPayload() {
if (
!form.value.email_http_enabled ||
form.value.email_http_auth_mode === "none"
) {
return {};
}
const text = emailCredentials.value.trim();
if (!text) return {};
const parsed = JSON.parse(text);
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
throw new Error("HTTP 通知凭据必须是 JSON 对象。");
}
for (const [key, value] of Object.entries(parsed)) {
if (!key.trim() || typeof value !== "string" || !value.trim()) {
throw new Error("HTTP 通知凭据的字段和值必须是非空文本。");
}
}
return parsed;
}
async function testDNS() { async function testDNS() {
dnsTestError.value = ""; dnsTestError.value = "";
resultMessage.value = ""; resultMessage.value = "";
@@ -280,11 +337,24 @@ export function useSetupWizard(props, emit) {
if ( if (
form.value.email_http_enabled && form.value.email_http_enabled &&
form.value.email_http_auth_mode !== "none" && form.value.email_http_auth_mode !== "none" &&
!form.value.email_http_credential_ref.trim() !form.value.email_http_credential_ref.trim() &&
!emailCredentials.value.trim()
) { ) {
error.value = "启用 HTTP 通知认证后必须填写凭据引用。"; error.value = "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用。";
return false; return false;
} }
if (
form.value.email_http_enabled &&
form.value.email_http_auth_mode !== "none" &&
emailCredentials.value.trim()
) {
try {
emailCredentialPayload();
} catch (err) {
error.value = err.message || "HTTP 通知凭据格式无效。";
return false;
}
}
if (form.value.email_http_headers.trim()) { if (form.value.email_http_headers.trim()) {
try { try {
const headers = JSON.parse(form.value.email_http_headers); const headers = JSON.parse(form.value.email_http_headers);
@@ -299,6 +369,26 @@ export function useSetupWizard(props, emit) {
} }
if (currentStep.value === 3) { if (currentStep.value === 3) {
const propagationTimeout = Number(form.value.propagation_timeout_secs);
const propagationInterval = Number(
form.value.propagation_polling_interval_secs,
);
if (
!Number.isInteger(propagationTimeout) ||
propagationTimeout < 1 ||
propagationTimeout > 86400
) {
error.value = "DNS 传播最大等待时间必须在 1 至 86400 秒之间。";
return false;
}
if (
!Number.isInteger(propagationInterval) ||
propagationInterval < 1 ||
propagationInterval > propagationTimeout
) {
error.value = "DNS 传播检测间隔必须大于 0 且不超过最大等待时间。";
return false;
}
const provider = selectedDNSProvider.value; const provider = selectedDNSProvider.value;
if (!provider) { if (!provider) {
error.value = "请选择 DNS 服务商。"; error.value = "请选择 DNS 服务商。";
@@ -398,6 +488,12 @@ export function useSetupWizard(props, emit) {
error.value = "必须先完成 DNS API 在线验证;验证结果已过期时请重新测试。"; error.value = "必须先完成 DNS API 在线验证;验证结果已过期时请重新测试。";
return; return;
} }
try {
emailCredentialPayload();
} catch (err) {
error.value = err.message || "HTTP 通知凭据格式无效。";
return;
}
const hostname = const hostname =
targetType.value === "hostname" ? form.value.web_hostname.trim() : ""; targetType.value === "hostname" ? form.value.web_hostname.trim() : "";
const publicIP = const publicIP =
@@ -422,9 +518,10 @@ export function useSetupWizard(props, emit) {
email_endpoint: form.value.email_endpoint, email_endpoint: form.value.email_endpoint,
email_http_path: form.value.email_http_path, email_http_path: form.value.email_http_path,
email_http_login_path: form.value.email_http_login_path, email_http_login_path: form.value.email_http_login_path,
email_http_auth_mode: form.value.email_http_auth_mode, email_http_auth_mode: form.value.email_http_auth_mode,
email_http_credential_ref: form.value.email_http_credential_ref, email_http_credential_ref: form.value.email_http_credential_ref,
email_http_headers: emailHeaders(), email_http_credentials: emailCredentialPayload(),
email_http_headers: emailHeaders(),
email_event_mode: form.value.email_event_mode, email_event_mode: form.value.email_event_mode,
email_include_deployment_details: email_include_deployment_details:
form.value.email_include_deployment_details, form.value.email_include_deployment_details,
@@ -441,6 +538,12 @@ export function useSetupWizard(props, emit) {
dns_credential_ref: dnsVerification.value.credential_ref, dns_credential_ref: dnsVerification.value.credential_ref,
dns_verification_token: dnsVerification.value.verification_token, dns_verification_token: dnsVerification.value.verification_token,
dns_test_domain: dnsTestDomain.value.trim(), dns_test_domain: dnsTestDomain.value.trim(),
propagation_timeout_secs: Number(
form.value.propagation_timeout_secs,
),
propagation_polling_interval_secs: Number(
form.value.propagation_polling_interval_secs,
),
certificate_root: form.value.certificate_root, certificate_root: form.value.certificate_root,
web_hostname: hostname, web_hostname: hostname,
web_public_ip: publicIP, web_public_ip: publicIP,
@@ -492,6 +595,10 @@ export function useSetupWizard(props, emit) {
dnsTestError, dnsTestError,
dnsProviders, dnsProviders,
dnsCredentials, dnsCredentials,
dnsCredentialsVisible,
maskCredential,
emailCredentials,
emailCredentialsVisible,
dnsTestDomain, dnsTestDomain,
dnsVerification, dnsVerification,
currentStep, currentStep,
@@ -501,6 +608,8 @@ export function useSetupWizard(props, emit) {
selectedEmailDomain, selectedEmailDomain,
emailLocalPart, emailLocalPart,
targetLabel, targetLabel,
emailCredentialLabel,
emailCredentialPlaceholder,
resetURLPreview, resetURLPreview,
selectedDNSProvider, selectedDNSProvider,
dnsVerificationValid, dnsVerificationValid,
+302 -147
View File
@@ -22,6 +22,8 @@ const {
dnsTestError, dnsTestError,
dnsProviders, dnsProviders,
dnsCredentials, dnsCredentials,
dnsCredentialsVisible,
maskCredential,
dnsTestDomain, dnsTestDomain,
dnsVerification, dnsVerification,
currentStep, currentStep,
@@ -172,162 +174,268 @@ const {
</div> </div>
</fieldset> </fieldset>
<fieldset v-if="currentStep === 2" class="setup-step-card setup-notification-step"> <fieldset
v-if="currentStep === 2"
class="setup-step-card setup-notification-step"
>
<legend><span>02</span>服务与通知</legend> <legend><span>02</span>服务与通知</legend>
<div class="setup-grid two-columns email-primary-grid">
<label <div class="notification-layout">
><span>Scert 主服务端口</span <div class="notification-row notification-service-row">
><input <label>
id="server-port" <span>Scert 主服务端口</span>
name="server_port" <input
v-model.number="form.server_port" id="server-port"
required name="server_port"
min="1" v-model.number="form.server_port"
max="65535" required
type="number" min="1"
/></label> max="65535"
<label class="confirm-row compact-row" type="number"
><input />
id="email-http-enabled" </label>
v-model="form.email_http_enabled" <label class="confirm-row compact-row">
type="checkbox" <input
/><span><strong>启用 HTTP 邮件通知</strong><small>兼容 Smail 等 HTTP 邮件服务。</small></span></label id="email-http-enabled"
v-model="form.email_http_enabled"
type="checkbox"
/>
<span>
<strong>启用 HTTP 邮件通知</strong>
<small>兼容 Smail 等 HTTP 邮件服务。</small>
</span>
</label>
<label v-if="form.email_http_enabled">
<span>第三方邮箱服务标识</span>
<input
id="email-provider"
name="email_provider"
v-model.trim="form.email_provider"
placeholder="例如 company-mail-api"
/>
</label>
</div>
<div
v-if="form.email_http_enabled"
class="notification-row notification-api-row"
> >
<label v-if="form.email_http_enabled" <label>
><span>第三方邮箱服务标识</span <span>邮件 API 地址</span>
><input <input
id="email-provider" id="email-endpoint"
name="email_provider" name="email_endpoint"
v-model.trim="form.email_provider" v-model.trim="form.email_endpoint"
placeholder="例如 company-mail-api" type="url"
/></label> placeholder="https://mail.example.com/send"
<label v-if="form.email_http_enabled" />
><span>邮件 API 地址</span </label>
><input <label>
id="email-endpoint" <span>HTTP 请求路径</span>
name="email_endpoint" <input
v-model.trim="form.email_endpoint" id="email-http-path"
type="url" v-model.trim="form.email_http_path"
placeholder="https://mail.example.com/send" placeholder="/api/email/send"
/></label> />
<label v-if="form.email_http_enabled" </label>
><span>HTTP 请求路径</span <label>
><input <span>HTTP 认证方式</span>
id="email-http-path" <select
v-model.trim="form.email_http_path" id="email-http-auth-mode"
placeholder="/api/email/send" v-model="form.email_http_auth_mode"
/></label> >
<label v-if="form.email_http_enabled" <option value="none">无认证</option>
><span>HTTP 认证方式</span <option value="bearer">Bearer Token</option>
><select <option value="hmac_sha256">HMAC-SHA256</option>
id="email-http-auth-mode" <option value="session">账号登录会话</option>
v-model="form.email_http_auth_mode" </select>
</label>
</div>
<div
v-if="form.email_http_enabled"
class="notification-row notification-auth-row"
>
<label v-if="form.email_http_auth_mode === 'session'">
<span>登录请求路径</span>
<input
id="email-http-login-path"
v-model.trim="form.email_http_login_path"
placeholder="/api/login"
/>
</label>
<label>
<span>已有凭据引用(可选)</span>
<input
id="email-http-credential-ref"
v-model.trim="form.email_http_credential_ref"
placeholder="已有 secret://notification/... 引用"
/>
</label>
<div
v-if="form.email_http_auth_mode === 'none'"
class="notification-auth-note"
> >
<option value="none">无认证</option> 当前接口不启用认证,不需要填写凭据。
<option value="bearer">Bearer Token</option> </div>
<option value="hmac_sha256">HMAC-SHA256</option> </div>
<option value="session">账号登录会话</option>
</select></label <div
>
<label
v-if=" v-if="
form.email_http_enabled && form.email_http_enabled &&
form.email_http_auth_mode === 'session' form.email_http_auth_mode !== 'none'
" "
><span>登录请求路径</span class="notification-credential-field"
><input
id="email-http-login-path"
v-model.trim="form.email_http_login_path"
placeholder="/api/login"
/></label>
<label v-if="form.email_http_enabled"
><span>凭据引用</span
><input
id="email-http-credential-ref"
v-model.trim="form.email_http_credential_ref"
placeholder="secret://notification/mail"
/></label>
<label v-if="form.email_http_enabled"
><span>发件人名称</span
><input
id="email-sender-name"
v-model.trim="form.email_sender_name"
placeholder="Scert"
/></label>
<label v-if="form.email_http_enabled"
><span>发件人地址</span
><input
id="email-sender-email"
v-model.trim="form.email_sender_email"
type="email"
placeholder="留空使用管理员邮箱"
/></label>
</div>
<div class="provider-description reset-preview">
<strong>密码重置地址</strong><span>{{ resetURLPreview }}</span
><span
>无需配置独立端口;只有手动启动 Scert-admin
后,此地址才会临时可用。</span
> >
</div> <div class="credential-visibility-row">
<label v-if="form.email_http_enabled" <span>{{ emailCredentialLabel }}</span>
><span>通知收件人</span <label class="credential-visibility-control">
><input <input
id="recipients" v-model="emailCredentialsVisible"
name="recipients" type="checkbox"
v-model="form.recipients" />
placeholder="多个地址使用逗号分隔" <span>显示凭据明文</span>
/></label> </label>
<div v-if="form.email_http_enabled" class="setup-grid two-columns email-delivery-grid"> </div>
<label <textarea
><span>通知事件模式</span v-if="emailCredentialsVisible"
><select v-model="form.email_event_mode"> id="email-http-credentials-visible"
<option value="detailed">详细事件</option> v-model="emailCredentials"
<option value="unified">统一事件</option> rows="3"
</select></label autocomplete="off"
:placeholder="emailCredentialPlaceholder"
></textarea>
<textarea
v-else
id="email-http-credentials-masked"
:value="maskCredential(emailCredentials)"
rows="3"
readonly
autocomplete="off"
></textarea>
<small>
配置时允许明文显示;提交后仅保存加密凭据引用,普通配置文件不会保存密码或令牌。
</small>
</div>
<div
v-if="form.email_http_enabled"
class="provider-description reset-preview"
> >
<label <strong>密码重置地址</strong>
><span>请求超时(秒)</span <span>{{ resetURLPreview }}</span>
><input <span>
v-model.number="form.email_timeout_secs" 无需配置独立端口;只有手动启动 Scert-admin
type="number" 后,此地址才会临时可用。
min="1" </span>
/></label> </div>
<label
><span>重试次数</span <div
><input v-if="form.email_http_enabled"
v-model.number="form.email_retry_count" class="notification-row notification-sender-row"
type="number"
min="1"
/></label>
<label
><span>重试间隔(秒)</span
><input
v-model.trim="form.email_retry_intervals_secs"
placeholder="30,120,600"
/></label>
</div>
<label v-if="form.email_http_enabled" class="email-headers-field"
><span>HTTP 自定义请求头(JSON)</span
><textarea
v-model.trim="form.email_http_headers"
rows="2"
placeholder='例如:{"X-Tenant":"scert"}'
></textarea
></label>
<div v-if="form.email_http_enabled" class="setup-grid three-columns compact-options email-option-grid">
<label class="confirm-row compact-row"
><input v-model="form.email_include_deployment_details" type="checkbox" /><span>部署明细</span></label
> >
<label class="confirm-row compact-row" <label>
><input v-model="form.email_include_certificate_serial" type="checkbox" /><span>证书序列号</span></label <span>发件人名称</span>
<input
id="email-sender-name"
v-model.trim="form.email_sender_name"
placeholder="Scert"
/>
</label>
<label>
<span>发件人地址</span>
<input
id="email-sender-email"
v-model.trim="form.email_sender_email"
type="email"
placeholder="留空使用管理员邮箱"
/>
</label>
<label>
<span>通知收件人</span>
<input
id="recipients"
name="recipients"
v-model="form.recipients"
placeholder="多个地址使用逗号分隔"
/>
</label>
</div>
<div
v-if="form.email_http_enabled"
class="notification-row notification-delivery-row"
> >
<label class="confirm-row compact-row" <label>
><input v-model="form.email_include_management_url" type="checkbox" /><span>管理后台链接</span></label <span>通知事件模式</span>
<select v-model="form.email_event_mode">
<option value="detailed">详细事件</option>
<option value="unified">统一事件</option>
</select>
</label>
<label>
<span>请求超时(秒)</span>
<input
v-model.number="form.email_timeout_secs"
type="number"
min="1"
/>
</label>
<label>
<span>重试次数</span>
<input
v-model.number="form.email_retry_count"
type="number"
min="1"
/>
</label>
<label>
<span>重试间隔(秒)</span>
<input
v-model.trim="form.email_retry_intervals_secs"
placeholder="30,120,600"
/>
</label>
</div>
<div
v-if="form.email_http_enabled"
class="notification-bottom-row"
> >
<label class="email-headers-field">
<span>HTTP 自定义请求头(JSON)</span>
<textarea
v-model.trim="form.email_http_headers"
rows="2"
placeholder='例如:{"X-Tenant":"scert"}'
></textarea>
</label>
<div class="setup-grid three-columns compact-options email-option-grid">
<label class="confirm-row compact-row">
<input
v-model="form.email_include_deployment_details"
type="checkbox"
/>
<span>部署明细</span>
</label>
<label class="confirm-row compact-row">
<input
v-model="form.email_include_certificate_serial"
type="checkbox"
/>
<span>证书序列号</span>
</label>
<label class="confirm-row compact-row">
<input
v-model="form.email_include_management_url"
type="checkbox"
/>
<span>管理后台链接</span>
</label>
</div>
</div>
</div> </div>
</fieldset> </fieldset>
<fieldset v-if="currentStep === 3" class="setup-step-card"> <fieldset v-if="currentStep === 3" class="setup-step-card">
<legend><span>03</span>DNS 验证</legend> <legend><span>03</span>DNS 验证</legend>
<div class="setup-grid two-columns"> <div class="setup-grid two-columns">
@@ -367,6 +475,34 @@ const {
></label ></label
> >
</div> </div>
<div class="setup-grid two-columns propagation-grid">
<label>
<span>DNS 传播最大等待时间(秒)</span>
<input
id="propagation-timeout-secs"
name="propagation_timeout_secs"
v-model.number="form.propagation_timeout_secs"
type="number"
min="1"
max="86400"
required
/>
<small>默认 900 秒,最长允许等待 86400 秒。</small>
</label>
<label>
<span>DNS 传播检测间隔(秒)</span>
<input
id="propagation-polling-interval-secs"
name="propagation_polling_interval_secs"
v-model.number="form.propagation_polling_interval_secs"
type="number"
min="1"
:max="form.propagation_timeout_secs"
required
/>
<small>默认 10 秒,不能大于最大等待时间。</small>
</label>
</div>
<p v-if="dnsCatalogError" class="inline-error"> <p v-if="dnsCatalogError" class="inline-error">
{{ dnsCatalogError }} {{ dnsCatalogError }}
</p> </p>
@@ -386,6 +522,16 @@ const {
v-if="selectedDNSProvider" v-if="selectedDNSProvider"
class="setup-grid two-columns credential-grid" class="setup-grid two-columns credential-grid"
> >
<div class="credential-visibility-row">
<span>DNS 凭据</span>
<label class="credential-visibility-control">
<input
v-model="dnsCredentialsVisible"
type="checkbox"
/>
<span>显示凭据明文</span>
</label>
</div>
<label <label
v-for="field in selectedDNSProvider.credential_fields" v-for="field in selectedDNSProvider.credential_fields"
:key="field.name" :key="field.name"
@@ -395,8 +541,8 @@ const {
}}{{ field.required ? "(必填)" : "(可选)" }}</span }}{{ field.required ? "(必填)" : "(可选)" }}</span
> >
<textarea <textarea
v-if="field.name.includes('json')" v-if="field.name.includes('json') && dnsCredentialsVisible"
:id="`dns-credential-${field.name}`" :id="`dns-credential-json-${field.name}`"
:name="`dns_credential_${field.name}`" :name="`dns_credential_${field.name}`"
v-model="dnsCredentials[field.name]" v-model="dnsCredentials[field.name]"
:required="field.required" :required="field.required"
@@ -404,13 +550,22 @@ const {
rows="4" rows="4"
autocomplete="off" autocomplete="off"
></textarea> ></textarea>
<textarea
v-else-if="field.name.includes('json')"
:id="`dns-credential-masked-${field.name}`"
:name="`dns_credential_${field.name}`"
:value="maskCredential(dnsCredentials[field.name])"
rows="4"
readonly
autocomplete="off"
></textarea>
<input <input
v-else v-else
:id="`dns-credential-${field.name}`" :id="`dns-credential-value-${field.name}`"
:name="`dns_credential_${field.name}`" :name="`dns_credential_${field.name}`"
v-model="dnsCredentials[field.name]" v-model="dnsCredentials[field.name]"
:required="field.required" :required="field.required"
:type="field.secret ? 'password' : 'text'" :type="field.secret && !dnsCredentialsVisible ? 'password' : 'text'"
:placeholder="field.placeholder" :placeholder="field.placeholder"
autocomplete="off" autocomplete="off"
/> />
@@ -19,11 +19,12 @@
} }
.access-shell--setup { .access-shell--setup {
width: min(1360px, calc(100vw - 32px)); width: min(1380px, calc(100vw - 40px));
max-width: calc(100vw - 32px); max-width: calc(100vw - 40px);
height: min(760px, calc(100vh - 32px)); height: min(790px, calc(100dvh - 40px));
max-height: calc(100vh - 32px); max-height: calc(100dvh - 40px);
min-height: 0; min-height: 0;
grid-template-columns: minmax(245px, 0.32fr) minmax(0, 0.68fr);
} }
.access-shell--compact { .access-shell--compact {
@@ -140,7 +141,27 @@
.access-shell--setup .access-panel-inner { .access-shell--setup .access-panel-inner {
align-items: stretch; align-items: stretch;
padding: clamp(22px, 2.7vw, 42px); padding: clamp(18px, 2.2vw, 32px);
}
.access-shell--setup .access-brand-content {
padding: clamp(28px, 2.8vw, 42px) clamp(22px, 2.2vw, 34px);
}
.access-shell--setup .access-logo {
width: clamp(64px, 6vw, 84px);
height: clamp(64px, 6vw, 84px);
margin-bottom: clamp(16px, 2vw, 24px);
}
.access-shell--setup .access-brand-title {
font-size: clamp(20px, 1.7vw, 29px);
}
.access-shell--setup .access-brand-description {
max-width: 290px;
font-size: 12px;
line-height: 1.7;
} }
@media (max-width: 900px) { @media (max-width: 900px) {
@@ -155,6 +176,14 @@
border-radius: 22px; border-radius: 22px;
} }
.access-shell--setup {
width: min(calc(100% - 24px), 900px);
max-width: calc(100% - 24px);
height: calc(100dvh - 24px);
max-height: calc(100dvh - 24px);
grid-template-rows: 112px minmax(0, 1fr);
}
.access-brand-content { .access-brand-content {
display: grid; display: grid;
grid-template-columns: auto minmax(0, 1fr); grid-template-columns: auto minmax(0, 1fr);
@@ -204,6 +233,14 @@
border-radius: 17px; border-radius: 17px;
} }
.access-shell--setup {
width: calc(100% - 12px);
max-width: calc(100% - 12px);
height: calc(100dvh - 12px);
max-height: calc(100dvh - 12px);
grid-template-rows: 88px minmax(0, 1fr);
}
.access-brand-content { .access-brand-content {
column-gap: 11px; column-gap: 11px;
padding: 9px 12px; padding: 9px 12px;