完善 Scert 前后端与部署支持
This commit is contained in:
1 parent
afdb947bea
commit
7f0af703ed
85 files changed
+7530
-800
No files matched your search
+12
-6
@@ -1,6 +1,6 @@
|
||||
# Scert
|
||||
|
||||
Scert 是面向 Windows 和 Linux 的 SSL 证书管理服务。当前代码处于首轮基础骨架阶段,已建立配置、数据库、日志、CLI、HTTP API 和前端占位结构。
|
||||
Scert 是面向 Windows 和 Linux 的 SSL 证书管理服务。当前代码已覆盖核心证书生命周期、DNS-01、自动续期、SSH 部署、通知、认证和 Web 管理流程。
|
||||
|
||||
## 当前已实现
|
||||
|
||||
@@ -12,7 +12,7 @@ Scert 是面向 Windows 和 Linux 的 SSL 证书管理服务。当前代码处
|
||||
- 域名基础模型与 Repository。
|
||||
- 健康检查、状态和域名基础 API。
|
||||
- 中文 CLI:`version`、`help`、`init`、`status`、`serve`、`domain list`、`domain add`。
|
||||
- Vue 前端状态占位页面。
|
||||
- Vue 前端管理页面。
|
||||
|
||||
## 首轮运行
|
||||
|
||||
@@ -34,7 +34,13 @@ go run ./cmd/scert serve --base-dir C:\ScertData
|
||||
- `POST /api/v1/domains`
|
||||
- `DELETE /api/v1/domains/:id`
|
||||
|
||||
当前 `serve` 是 HTTP 基础骨架。HTTPS 双模式、ACME 证书申请、DNS-01、远程部署等功能按开发任务清单在后续阶段实现。
|
||||
当前 `serve` 已接入配置加载、数据库迁移、认证、DNS 在线测试、ACME 证书申请、自动续期、证书导入、SSH 部署和通知流程。HTTPS 生产切换、真实 DNS/ACME 申请、远程服务器及平台安装仍需授权环境验收。
|
||||
|
||||
### 开发阶段使用 9003 端口
|
||||
|
||||
反向代理开发测试时,将配置中的服务地址设为 `127.0.0.1`、端口设为 `9003`,并将 `https_mode` 设为 `proxy`。Scert 只提供本机内部 HTTPS,公网 HTTPS 由 Nginx 监听 `443` 并转发到 `https://127.0.0.1:9003`。端口可通过配置文件 `server.port` 或初始化参数 `--server-port` 修改;修改后需要重启服务。
|
||||
|
||||
SMTP 通知是 Scert 的出站连接,不需要为 Scert 开放 SMTP 入站端口。公网防火墙通常只需放行 Nginx 使用的 `443`,若配置 HTTP 跳转再放行 `80`;内部端口 `9003` 不应对公网开放。
|
||||
|
||||
## 测试和构建
|
||||
|
||||
@@ -62,10 +68,10 @@ Remove-Item Env:GOARCH
|
||||
- 数据库密码不得写入 Git、脚本参数或日志。
|
||||
- MySQL 客户端和服务实例必须使用明确路径、端口和 DSN,不能通过 PATH 中的单个 `mysql` 命令判断版本。
|
||||
|
||||
## 当前未实现
|
||||
## 当前生产验收边界
|
||||
|
||||
ACME/lego 实际申请、DNS 服务商 API、自动续期、SSH/SFTP 部署、Nginx/Caddy/Apache reload、完整 Web 管理界面、Wails 桌面版、Windows Service 和 Linux systemd 均未在首轮基础骨架中宣称完成。
|
||||
代码层已实现 ACME/lego 申请、第一批 DNS Provider、CNAME 委派、自动续期、证书导入、SSH/SFTP 部署、Nginx/Caddy/Apache reload、通知和 Web 管理接口。以下项目不能仅凭本地自动化测试宣称生产完成:真实 DNS 权限与公网传播、Let’s Encrypt Production 签发、真实远程服务器部署、Windows Service、Linux systemd 实机安装、Wails 桌面封装、Windows ACL、MySQL 真实实例和最终 HTTPS 到达性验收。
|
||||
|
||||
## 首轮复审状态
|
||||
|
||||
2026 年 8 月 26 日已完成首轮代码复审。`gofmt`、`go vet`、`go test`、竞态检测、Windows amd64 构建、Linux amd64 交叉构建、CLI 和 HTTP 实际流程均通过。MySQL 5.7/8.0 仅完成代码层实现和客户端版本确认,真实实例连接与迁移仍需明确 DSN、端口和凭据后验证。
|
||||
2026 年 8 月 26 日已完成首轮代码复审。`gofmt`、`go vet`、`go test`、竞态检测、Windows amd64 构建、Linux amd64 交叉构建、CLI 和 HTTP 实际流程均通过。MySQL 5.7/8.0 仅完成代码层实现和客户端版本确认,真实实例连接与迁移仍需明确 DSN、端口和凭据后验证。
|
||||
@@ -116,6 +116,12 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
|
||||
result, err := workflow.DeployCurrent(ctx, domainID)
|
||||
return result.Certificate, result.Deployment, err
|
||||
},
|
||||
RestoreCertificateVersion: func(ctx context.Context, domainID, version string) (certificate.IssueResult, error) {
|
||||
return certificates.RestoreVersion(ctx, domainID, version)
|
||||
},
|
||||
RunRenewal: func(ctx context.Context) (certificate.RenewalReport, error) {
|
||||
return renewal.RunOnce(ctx)
|
||||
},
|
||||
CurrentCertificate: certificates,
|
||||
ResetStatePath: admin.StatePath(cfg.Paths.Data),
|
||||
Audit: auditRepo,
|
||||
@@ -123,7 +129,9 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
|
||||
})
|
||||
return &App{
|
||||
Config: cfg, Logger: logger, Database: db, Repository: repo,
|
||||
Servers: serverRepo,
|
||||
Tasks: taskRepo,
|
||||
Deployment: deploymentService,
|
||||
SecretStore: secretStore, SSHKeys: sshKeys, DNSVerification: dnsVerification, HTTP: server,
|
||||
Certificates: certificates,
|
||||
Workflow: workflow,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestNewWiresApplicationServices(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
cfg := config.Default(baseDir)
|
||||
application, err := NewWithConfigPath(context.Background(), cfg, filepath.Join(cfg.Paths.Config, "scert.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("初始化应用失败:%v", err)
|
||||
}
|
||||
defer application.Close()
|
||||
|
||||
if application.Repository == nil || application.Servers == nil || application.Tasks == nil {
|
||||
t.Fatal("数据库仓储未完整注入应用实例")
|
||||
}
|
||||
if application.Deployment == nil || application.Certificates == nil || application.Workflow == nil || application.Renewal == nil {
|
||||
t.Fatal("证书申请、部署或续期服务未完整注入应用实例")
|
||||
}
|
||||
if application.SecretStore == nil || application.SSHKeys == nil || application.DNSVerification == nil || application.HTTP == nil {
|
||||
t.Fatal("敏感信息、SSH、DNS 或 HTTP 服务未完整注入应用实例")
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -39,20 +40,21 @@ type Resource struct {
|
||||
}
|
||||
|
||||
type SavedResource struct {
|
||||
Domain string `json:"domain"`
|
||||
CertificateType string `json:"certificate_type,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
SANs []string `json:"sans,omitempty"`
|
||||
SerialNumber string `json:"serial_number,omitempty"`
|
||||
FingerprintSHA256 string `json:"fingerprint_sha256,omitempty"`
|
||||
ChainLength int `json:"chain_length,omitempty"`
|
||||
Directory string `json:"directory"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
FullChainPath string `json:"fullchain_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
BackupDirectory string `json:"backup_directory,omitempty"`
|
||||
Domain string `json:"domain"`
|
||||
CertificateType string `json:"certificate_type,omitempty"`
|
||||
CertificateIdentifier string `json:"certificate_identifier,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
SANs []string `json:"sans,omitempty"`
|
||||
SerialNumber string `json:"serial_number,omitempty"`
|
||||
FingerprintSHA256 string `json:"fingerprint_sha256,omitempty"`
|
||||
ChainLength int `json:"chain_length,omitempty"`
|
||||
Directory string `json:"directory"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
FullChainPath string `json:"fullchain_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
BackupDirectory string `json:"backup_directory,omitempty"`
|
||||
}
|
||||
|
||||
type FileStore struct {
|
||||
@@ -158,7 +160,7 @@ func (s FileStore) Save(ctx context.Context, domain string, resource Resource) (
|
||||
return s.save(ctx, domain, "", resource)
|
||||
}
|
||||
|
||||
// SaveForType 按证书类型保存当前证书和历史版本。
|
||||
// SaveForType 按证书类型保存唯一的当前证书版本。
|
||||
func (s FileStore) SaveForType(ctx context.Context, domain, certificateType string, resource Resource) (SavedResource, error) {
|
||||
return s.save(ctx, domain, certificateType, resource)
|
||||
}
|
||||
@@ -183,59 +185,66 @@ func (s FileStore) save(ctx context.Context, domain, certificateType string, res
|
||||
return SavedResource{}, errors.New("证书存储根目录不能为空")
|
||||
}
|
||||
baseDirectory := filepath.Join(root, directoryName(primary))
|
||||
typeDirectory := baseDirectory
|
||||
directory := baseDirectory
|
||||
certificateIdentifier := ""
|
||||
if certificateType != "" {
|
||||
certificateType = strings.ToLower(strings.TrimSpace(certificateType))
|
||||
if certificateType != "single" && certificateType != "wildcard" && certificateType != "san" {
|
||||
return SavedResource{}, fmt.Errorf("证书类型无效:%s", certificateType)
|
||||
}
|
||||
directory = filepath.Join(baseDirectory, certificateType)
|
||||
typeDirectory = filepath.Join(baseDirectory, certificateType)
|
||||
directory = typeDirectory
|
||||
if certificateType == "san" {
|
||||
certificateIdentifier = sanCertificateIdentifier(resource.Domains)
|
||||
directory = filepath.Join(typeDirectory, certificateIdentifier)
|
||||
}
|
||||
}
|
||||
activeDirectory := directory
|
||||
currentDirectory := directory
|
||||
version := ""
|
||||
if certificateType != "" {
|
||||
currentDirectory = filepath.Join(directory, "current")
|
||||
activeDirectory, err = s.activeCertificateDirectoryForType(typeDirectory, certificateType)
|
||||
if err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
if !directoryContainsCertificateFiles(activeDirectory) {
|
||||
activeDirectory = ""
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if s.Now != nil {
|
||||
now = s.Now().UTC()
|
||||
}
|
||||
version, err = nextCertificateVersion(directory, now)
|
||||
if err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
currentDirectory = filepath.Join(directory, version)
|
||||
}
|
||||
backupDirectory := ""
|
||||
if activeDirectory != "" {
|
||||
backupDirectory, err = s.backupExisting(activeDirectory, primary)
|
||||
if err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(currentDirectory, 0o700); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("创建证书目录失败:%w", err)
|
||||
}
|
||||
backupDirectory, err := s.backupExisting(currentDirectory, primary)
|
||||
if err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
fullChain := resource.Certificate
|
||||
if len(resource.IssuerCertificate) > 0 && !bytes.Contains(resource.Certificate, resource.IssuerCertificate) {
|
||||
fullChain = append(append([]byte(nil), resource.Certificate...), resource.IssuerCertificate...)
|
||||
}
|
||||
version := ""
|
||||
if certificateType != "" {
|
||||
now := time.Now
|
||||
if s.Now != nil {
|
||||
now = s.Now
|
||||
}
|
||||
version = now().UTC().Format("20060102-150405.000000000")
|
||||
versionDirectory := filepath.Join(directory, "versions", version)
|
||||
for suffix := 1; ; suffix++ {
|
||||
if _, statErr := os.Stat(versionDirectory); errors.Is(statErr, os.ErrNotExist) {
|
||||
break
|
||||
} else if statErr != nil {
|
||||
return SavedResource{}, fmt.Errorf("读取证书版本目录失败:%w", statErr)
|
||||
}
|
||||
version = fmt.Sprintf("%s-%02d", now().UTC().Format("20060102-150405.000000000"), suffix)
|
||||
versionDirectory = filepath.Join(directory, "versions", version)
|
||||
}
|
||||
if err := os.MkdirAll(versionDirectory, 0o700); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("创建证书版本目录失败:%w", err)
|
||||
}
|
||||
if err := writeCertificateFiles(versionDirectory, resource.Certificate, fullChain, resource.PrivateKey); err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
}
|
||||
if err := writeCertificateFiles(currentDirectory, resource.Certificate, fullChain, resource.PrivateKey); err != nil {
|
||||
if certificateType != "" {
|
||||
_ = os.RemoveAll(currentDirectory)
|
||||
}
|
||||
return SavedResource{}, err
|
||||
}
|
||||
leaf, _ := parseLeafCertificate(resource.Certificate)
|
||||
result := SavedResource{
|
||||
Domain: primary, CertificateType: certificateType, Version: version, SANs: append([]string(nil), resource.Domains...),
|
||||
Domain: primary, CertificateType: certificateType, CertificateIdentifier: certificateIdentifier,
|
||||
Version: version, SANs: append([]string(nil), resource.Domains...),
|
||||
Directory: currentDirectory, CertificatePath: filepath.Join(currentDirectory, "cert.pem"),
|
||||
FullChainPath: filepath.Join(currentDirectory, "fullchain.pem"), PrivateKeyPath: filepath.Join(currentDirectory, "key.pem"),
|
||||
NotBefore: resource.NotBefore, NotAfter: resource.NotAfter, BackupDirectory: backupDirectory,
|
||||
@@ -247,15 +256,20 @@ func (s FileStore) save(ctx context.Context, domain, certificateType string, res
|
||||
}
|
||||
metadata, err := json.MarshalIndent(result, "", " ")
|
||||
if err != nil {
|
||||
if certificateType != "" {
|
||||
_ = os.RemoveAll(currentDirectory)
|
||||
}
|
||||
return SavedResource{}, fmt.Errorf("生成证书元数据失败:%w", err)
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(currentDirectory, "metadata.json"), metadata, 0o600); err != nil {
|
||||
if certificateType != "" {
|
||||
_ = os.RemoveAll(currentDirectory)
|
||||
}
|
||||
return SavedResource{}, fmt.Errorf("写入证书元数据失败:%w", err)
|
||||
}
|
||||
if certificateType != "" {
|
||||
versionMetadata := filepath.Join(directory, "versions", version, "metadata.json")
|
||||
if err := atomicWrite(versionMetadata, metadata, 0o600); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("写入历史证书元数据失败:%w", err)
|
||||
if certificateType != "" && activeDirectory != "" && activeDirectory != currentDirectory {
|
||||
if err := removeCertificateDirectory(activeDirectory, typeDirectory); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("清理旧当前证书目录失败:%w", err)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
@@ -309,7 +323,16 @@ func (s FileStore) backupExisting(directory, domain string) (string, error) {
|
||||
if s.Now != nil {
|
||||
now = s.Now
|
||||
}
|
||||
backupDirectory := filepath.Join(backupRoot, directoryName(domain), now().UTC().Format("20060102-150405.000000000"))
|
||||
backupBase := filepath.Join(backupRoot, directoryName(domain), now().UTC().Format("20060102-150405.000000000"))
|
||||
backupDirectory := backupBase
|
||||
for suffix := 1; ; suffix++ {
|
||||
if _, statErr := os.Stat(backupDirectory); errors.Is(statErr, os.ErrNotExist) {
|
||||
break
|
||||
} else if statErr != nil {
|
||||
return "", fmt.Errorf("读取证书备份目录失败:%w", statErr)
|
||||
}
|
||||
backupDirectory = fmt.Sprintf("%s-%02d", backupBase, suffix)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(backupDirectory), 0o700); err != nil {
|
||||
return "", fmt.Errorf("创建证书备份目录失败:%w", err)
|
||||
}
|
||||
@@ -395,6 +418,200 @@ func directoryName(domain string) string {
|
||||
return name
|
||||
}
|
||||
|
||||
func nextCertificateVersion(directory string, now time.Time) (string, error) {
|
||||
date := now.UTC().Format("20060102")
|
||||
major := 1
|
||||
minor := -1
|
||||
entries, err := os.ReadDir(directory)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("读取证书类型目录失败:%w", err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
entryDate, entryMajor, entryMinor, valid := parseCertificateVersion(entry.Name())
|
||||
if !valid || entryDate != date {
|
||||
continue
|
||||
}
|
||||
if entryMajor > major || entryMajor == major && entryMinor > minor {
|
||||
major = entryMajor
|
||||
minor = entryMinor
|
||||
}
|
||||
}
|
||||
if minor < 0 {
|
||||
minor = 0
|
||||
} else {
|
||||
minor++
|
||||
}
|
||||
return fmt.Sprintf("%s-V%d.%d", date, major, minor), nil
|
||||
}
|
||||
|
||||
func parseCertificateVersion(version string) (string, int, int, bool) {
|
||||
if len(version) < len("20060102-V1.0") || filepath.Base(version) != version || strings.ContainsAny(version, `/\\`) {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
if version[8:10] != "-V" {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
date := version[:8]
|
||||
for _, r := range date {
|
||||
if r < '0' || r > '9' {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
}
|
||||
parts := strings.Split(version[10:], ".")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
major, err := strconv.Atoi(parts[0])
|
||||
if err != nil || major < 1 {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
minor, err := strconv.Atoi(parts[1])
|
||||
if err != nil || minor < 0 {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
return date, major, minor, true
|
||||
}
|
||||
|
||||
func (s FileStore) activeCertificateDirectory(directory string) (string, error) {
|
||||
entries, err := os.ReadDir(directory)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return directory, nil
|
||||
}
|
||||
return "", fmt.Errorf("读取证书类型目录失败:%w", err)
|
||||
}
|
||||
active := ""
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
candidate := filepath.Join(directory, entry.Name())
|
||||
if _, _, _, valid := parseCertificateVersion(entry.Name()); valid && newerCertificateDirectory(candidate, active) {
|
||||
active = candidate
|
||||
}
|
||||
}
|
||||
if active != "" {
|
||||
return active, nil
|
||||
}
|
||||
legacyCurrent := filepath.Join(directory, "current")
|
||||
if info, statErr := os.Stat(legacyCurrent); statErr == nil && info.IsDir() {
|
||||
return legacyCurrent, nil
|
||||
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("读取旧版当前证书目录失败:%w", statErr)
|
||||
}
|
||||
return directory, nil
|
||||
}
|
||||
|
||||
func sanCertificateIdentifier(domains []string) string {
|
||||
sum := sha256.Sum256([]byte(strings.Join(domains, "\n")))
|
||||
return fmt.Sprintf("san-%x", sum[:8])
|
||||
}
|
||||
|
||||
func directoryContainsCertificateFiles(directory string) bool {
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
return false
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
if info, err := os.Stat(filepath.Join(directory, name)); err == nil && !info.IsDir() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func newerCertificateDirectory(candidate, current string) bool {
|
||||
if current == "" {
|
||||
return true
|
||||
}
|
||||
candidateDate, candidateMajor, candidateMinor, candidateValid := parseCertificateVersion(filepath.Base(candidate))
|
||||
currentDate, currentMajor, currentMinor, currentValid := parseCertificateVersion(filepath.Base(current))
|
||||
if !candidateValid {
|
||||
return false
|
||||
}
|
||||
if !currentValid {
|
||||
return true
|
||||
}
|
||||
if candidateDate != currentDate {
|
||||
return candidateDate > currentDate
|
||||
}
|
||||
if candidateMajor != currentMajor {
|
||||
return candidateMajor > currentMajor
|
||||
}
|
||||
if candidateMinor != currentMinor {
|
||||
return candidateMinor > currentMinor
|
||||
}
|
||||
return candidate > current
|
||||
}
|
||||
|
||||
func (s FileStore) activeCertificateDirectoryForType(typeDirectory, certificateType string) (string, error) {
|
||||
active, err := s.activeCertificateDirectory(typeDirectory)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if certificateType != "san" || directoryContainsCertificateFiles(active) {
|
||||
return active, nil
|
||||
}
|
||||
entries, err := os.ReadDir(typeDirectory)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return typeDirectory, nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() || entry.Name() == "current" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(entry.Name(), "san-") {
|
||||
continue
|
||||
}
|
||||
if _, _, _, valid := parseCertificateVersion(entry.Name()); valid {
|
||||
continue
|
||||
}
|
||||
candidate, candidateErr := s.activeCertificateDirectory(filepath.Join(typeDirectory, entry.Name()))
|
||||
if candidateErr != nil {
|
||||
return "", candidateErr
|
||||
}
|
||||
if directoryContainsCertificateFiles(candidate) && newerCertificateDirectory(candidate, active) {
|
||||
active = candidate
|
||||
}
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
func removeCertificateDirectory(directory, certificateTypeDirectory string) error {
|
||||
directory = filepath.Clean(directory)
|
||||
certificateTypeDirectory = filepath.Clean(certificateTypeDirectory)
|
||||
parentDirectory := filepath.Dir(directory)
|
||||
if parentDirectory != certificateTypeDirectory && filepath.Dir(parentDirectory) != certificateTypeDirectory {
|
||||
return errors.New("旧证书目录超出证书类型目录")
|
||||
}
|
||||
name := filepath.Base(directory)
|
||||
if name != "current" {
|
||||
if err := validateCertificateVersion(name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := os.RemoveAll(directory); err != nil {
|
||||
return err
|
||||
}
|
||||
if parentDirectory != certificateTypeDirectory {
|
||||
entries, err := os.ReadDir(parentDirectory)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
return os.Remove(parentDirectory)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validDomain(value string) bool {
|
||||
value = strings.TrimPrefix(value, "*.")
|
||||
if len(value) < 3 || len(value) > 253 || !strings.Contains(value, ".") {
|
||||
@@ -413,7 +630,7 @@ func validDomain(value string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// CurrentDirectory returns the active certificate directory for a domain and certificate type.
|
||||
// CurrentDirectory 返回当前唯一使用的证书版本目录。
|
||||
func (s FileStore) CurrentDirectory(domain, certificateType string) (string, error) {
|
||||
primary := strings.TrimSpace(domain)
|
||||
if _, err := NormalizeDomains([]string{primary}); err != nil {
|
||||
@@ -427,7 +644,8 @@ func (s FileStore) CurrentDirectory(domain, certificateType string) (string, err
|
||||
if root == "." || root == "" {
|
||||
return "", errors.New("证书存储根目录不能为空")
|
||||
}
|
||||
return filepath.Join(root, directoryName(primary), certificateType, "current"), nil
|
||||
directory := filepath.Join(root, directoryName(primary), certificateType)
|
||||
return s.activeCertificateDirectoryForType(directory, certificateType)
|
||||
}
|
||||
|
||||
// LoadCurrent reads the active certificate files and metadata.
|
||||
@@ -485,41 +703,113 @@ func (s FileStore) LoadCurrent(ctx context.Context, domain, certificateType stri
|
||||
return saved, resource, nil
|
||||
}
|
||||
|
||||
// ListVersions returns all stored certificate versions in descending order.
|
||||
// LoadVersion 仅允许读取当前使用的版本,保留该方法用于兼容已有接口。
|
||||
func (s FileStore) LoadVersion(ctx context.Context, domain, certificateType, version string) (SavedResource, Resource, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return SavedResource{}, Resource{}, err
|
||||
}
|
||||
if err := validateCertificateVersion(version); err != nil {
|
||||
return SavedResource{}, Resource{}, err
|
||||
}
|
||||
directory, err := s.CurrentDirectory(domain, certificateType)
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, err
|
||||
}
|
||||
if filepath.Base(directory) != version {
|
||||
return SavedResource{}, Resource{}, errors.New("指定版本不是当前使用的证书版本")
|
||||
}
|
||||
certificateData, err := os.ReadFile(filepath.Join(directory, "cert.pem"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取当前证书失败:%w", err)
|
||||
}
|
||||
fullChainData, err := os.ReadFile(filepath.Join(directory, "fullchain.pem"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取当前完整证书链失败:%w", err)
|
||||
}
|
||||
privateKeyData, err := os.ReadFile(filepath.Join(directory, "key.pem"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取当前私钥失败:%w", err)
|
||||
}
|
||||
var saved SavedResource
|
||||
metadata, err := os.ReadFile(filepath.Join(directory, "metadata.json"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取当前证书元数据失败:%w", err)
|
||||
}
|
||||
if err := json.Unmarshal(metadata, &saved); err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("解析当前证书元数据失败:%w", err)
|
||||
}
|
||||
if saved.Version != version {
|
||||
return SavedResource{}, Resource{}, errors.New("当前证书版本标识不一致")
|
||||
}
|
||||
domains := saved.SANs
|
||||
if len(domains) == 0 {
|
||||
domains = []string{domain}
|
||||
}
|
||||
resource, err := ValidateResourceForDomains(Resource{
|
||||
Domains: domains,
|
||||
Certificate: certificateData,
|
||||
IssuerCertificate: fullChainData,
|
||||
PrivateKey: privateKeyData,
|
||||
}, domains)
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("当前证书校验失败:%w", err)
|
||||
}
|
||||
saved.Directory = directory
|
||||
saved.CertificatePath = filepath.Join(directory, "cert.pem")
|
||||
saved.FullChainPath = filepath.Join(directory, "fullchain.pem")
|
||||
saved.PrivateKeyPath = filepath.Join(directory, "key.pem")
|
||||
saved.BackupDirectory = ""
|
||||
resource.IssuerCertificate = nil
|
||||
return saved, resource, nil
|
||||
}
|
||||
|
||||
// RestoreVersion 已停用,正式证书目录只保留当前使用的版本。
|
||||
func (s FileStore) RestoreVersion(ctx context.Context, domain, certificateType, version string) (SavedResource, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
if err := validateCertificateVersion(version); err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
return SavedResource{}, errors.New("当前仅保留当前使用的证书版本,不支持历史版本恢复")
|
||||
}
|
||||
|
||||
// ListVersions 返回当前唯一使用的证书版本,保留该方法用于兼容已有接口。
|
||||
func (s FileStore) ListVersions(ctx context.Context, domain, certificateType string) ([]SavedResource, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := s.CurrentDirectory(domain, certificateType)
|
||||
directory, err := s.CurrentDirectory(domain, certificateType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
certificateDirectory := filepath.Dir(current)
|
||||
versionsDirectory := filepath.Join(certificateDirectory, "versions")
|
||||
entries, err := os.ReadDir(versionsDirectory)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if _, statErr := os.Stat(filepath.Join(directory, "metadata.json")); statErr != nil {
|
||||
if errors.Is(statErr, os.ErrNotExist) {
|
||||
return []SavedResource{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("读取证书版本失败:%w", err)
|
||||
return nil, fmt.Errorf("读取当前证书版本失败:%w", statErr)
|
||||
}
|
||||
versions := make([]SavedResource, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
metadata, readErr := os.ReadFile(filepath.Join(versionsDirectory, entry.Name(), "metadata.json"))
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("读取证书版本元数据失败:%w", readErr)
|
||||
}
|
||||
var item SavedResource
|
||||
if err := json.Unmarshal(metadata, &item); err != nil {
|
||||
return nil, fmt.Errorf("解析证书版本元数据失败:%w", err)
|
||||
}
|
||||
versions = append(versions, item)
|
||||
saved, _, err := s.LoadCurrent(ctx, domain, certificateType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(versions, func(i, j int) bool { return versions[i].Version > versions[j].Version })
|
||||
return versions, nil
|
||||
return []SavedResource{saved}, nil
|
||||
}
|
||||
|
||||
func validateCertificateVersion(version string) error {
|
||||
if _, _, _, valid := parseCertificateVersion(version); !valid {
|
||||
return errors.New("证书版本标识无效,应使用 YYYYMMDD-Vx.x 格式")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeCertificateFiles(directory string) error {
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
if err := os.Remove(filepath.Join(directory, name)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RollbackSavedResource 在初始化后续阶段失败时恢复证书目录。
|
||||
@@ -543,6 +833,9 @@ func RollbackSavedResource(ctx context.Context, saved SavedResource) error {
|
||||
if err := restoreCertificateFiles(directory, backupDirectory); err != nil {
|
||||
return fmt.Errorf("恢复原证书失败:%w", err)
|
||||
}
|
||||
if err := rewriteRestoredMetadata(directory); err != nil {
|
||||
return fmt.Errorf("更新回滚证书元数据失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
@@ -551,6 +844,11 @@ func RollbackSavedResource(ctx context.Context, saved SavedResource) error {
|
||||
return fmt.Errorf("清理失败证书文件 %s 失败:%w", name, err)
|
||||
}
|
||||
}
|
||||
if _, _, _, valid := parseCertificateVersion(filepath.Base(directory)); valid {
|
||||
if err := os.Remove(directory); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("清理失败证书目录失败:%w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -577,3 +875,25 @@ func restoreCertificateFiles(directory, backupDirectory string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rewriteRestoredMetadata(directory string) error {
|
||||
path := filepath.Join(directory, "metadata.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var saved SavedResource
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
return err
|
||||
}
|
||||
saved.Directory = directory
|
||||
saved.CertificatePath = filepath.Join(directory, "cert.pem")
|
||||
saved.FullChainPath = filepath.Join(directory, "fullchain.pem")
|
||||
saved.PrivateKeyPath = filepath.Join(directory, "key.pem")
|
||||
saved.BackupDirectory = ""
|
||||
data, err = json.MarshalIndent(saved, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return atomicWrite(path, data, 0o600)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFileStoreVersionedLayoutAndHistory(t *testing.T) {
|
||||
func TestFileStoreUsesSingleDatedCurrentVersion(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := FileStore{
|
||||
Root: filepath.Join(root, "ssl"),
|
||||
@@ -26,25 +26,28 @@ func TestFileStoreVersionedLayoutAndHistory(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("保存第二版证书失败:%v", err)
|
||||
}
|
||||
if first.Version == second.Version {
|
||||
t.Fatalf("重复保存不应覆盖历史版本:%q", first.Version)
|
||||
if first.Version != "20260827-V1.0" || second.Version != "20260827-V1.1" {
|
||||
t.Fatalf("证书版本命名错误:first=%q second=%q", first.Version, second.Version)
|
||||
}
|
||||
wantCurrent := filepath.Join(root, "ssl", "example.com", "single", "current")
|
||||
wantCurrent := filepath.Join(root, "ssl", "example.com", "single", second.Version)
|
||||
if second.Directory != wantCurrent {
|
||||
t.Fatalf("当前目录错误:got=%q want=%q", second.Directory, wantCurrent)
|
||||
}
|
||||
for _, path := range []string{
|
||||
filepath.Join(wantCurrent, "cert.pem"),
|
||||
filepath.Join(wantCurrent, "fullchain.pem"),
|
||||
filepath.Join(wantCurrent, "key.pem"),
|
||||
filepath.Join(wantCurrent, "metadata.json"),
|
||||
filepath.Join(root, "ssl", "example.com", "single", "versions", first.Version, "metadata.json"),
|
||||
filepath.Join(root, "ssl", "example.com", "single", "versions", second.Version, "metadata.json"),
|
||||
} {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("证书文件不存在:%s:%v", path, err)
|
||||
if _, err := os.Stat(first.Directory); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("旧当前版本目录仍存在:%v", err)
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
if _, err := os.Stat(filepath.Join(wantCurrent, name)); err != nil {
|
||||
t.Fatalf("当前证书文件不存在:%s:%v", name, err)
|
||||
}
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Dir(wantCurrent))
|
||||
if err != nil {
|
||||
t.Fatalf("读取证书类型目录失败:%v", err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].Name() != second.Version {
|
||||
t.Fatalf("正式证书目录应只保留一个版本:%v", entries)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
info, err := os.Stat(second.PrivateKeyPath)
|
||||
if err != nil {
|
||||
@@ -56,44 +59,47 @@ func TestFileStoreVersionedLayoutAndHistory(t *testing.T) {
|
||||
}
|
||||
versions, err := store.ListVersions(context.Background(), "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("读取证书版本失败:%v", err)
|
||||
t.Fatalf("读取当前证书版本失败:%v", err)
|
||||
}
|
||||
if len(versions) != 2 || versions[0].Version != second.Version || versions[1].Version != first.Version {
|
||||
t.Fatalf("证书版本历史错误:%+v", versions)
|
||||
if len(versions) != 1 || versions[0].Version != second.Version {
|
||||
t.Fatalf("当前证书版本列表错误:%+v", versions)
|
||||
}
|
||||
metadata, loaded, err := store.LoadCurrent(context.Background(), "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("读取当前证书失败:%v", err)
|
||||
}
|
||||
if metadata.Version != second.Version || len(loaded.Certificate) == 0 || len(loaded.PrivateKey) == 0 {
|
||||
if metadata.Version != second.Version || metadata.Directory != second.Directory || len(loaded.Certificate) == 0 || len(loaded.PrivateKey) == 0 {
|
||||
t.Fatalf("当前证书内容错误:metadata=%+v", metadata)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileStoreListVersionsReturnsEmptyWhenNoHistory(t *testing.T) {
|
||||
func TestFileStoreListVersionsReturnsEmptyWhenNoCurrentCertificate(t *testing.T) {
|
||||
store := FileStore{Root: t.TempDir()}
|
||||
versions, err := store.ListVersions(context.Background(), "example.com", "san")
|
||||
if err != nil {
|
||||
t.Fatalf("无版本记录时查询失败:%v", err)
|
||||
t.Fatalf("无当前证书时查询失败:%v", err)
|
||||
}
|
||||
if versions == nil || len(versions) != 0 {
|
||||
t.Fatalf("无版本记录时应返回空列表:%+v", versions)
|
||||
t.Fatalf("无当前证书时应返回空列表:%+v", versions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRollbackSavedResourceRestoresPreviousCertificate(t *testing.T) {
|
||||
func TestRollbackSavedResourceRestoresPreviousCertificateInCurrentDirectory(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := FileStore{
|
||||
Root: filepath.Join(root, "ssl"),
|
||||
BackupRoot: filepath.Join(root, "backups"),
|
||||
Now: func() time.Time { return time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC) },
|
||||
}
|
||||
resource := testResource(t, "example.com")
|
||||
first, err := store.SaveForType(context.Background(), "example.com", "single", resource)
|
||||
first, err := store.SaveForType(context.Background(), "example.com", "single", testResource(t, "example.com"))
|
||||
if err != nil {
|
||||
t.Fatalf("保存初始证书失败:%v", err)
|
||||
}
|
||||
second, err := store.SaveForType(context.Background(), "example.com", "single", resource)
|
||||
firstCertificate, err := os.ReadFile(first.CertificatePath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取初始证书失败:%v", err)
|
||||
}
|
||||
second, err := store.SaveForType(context.Background(), "example.com", "single", testResource(t, "example.com"))
|
||||
if err != nil {
|
||||
t.Fatalf("保存新证书失败:%v", err)
|
||||
}
|
||||
@@ -103,11 +109,19 @@ func TestRollbackSavedResourceRestoresPreviousCertificate(t *testing.T) {
|
||||
if err := RollbackSavedResource(context.Background(), second); err != nil {
|
||||
t.Fatalf("回滚证书失败:%v", err)
|
||||
}
|
||||
if _, err := os.Stat(first.FullChainPath); err != nil {
|
||||
currentCertificate, err := os.ReadFile(second.CertificatePath)
|
||||
if err != nil {
|
||||
t.Fatalf("回滚后当前证书不存在:%v", err)
|
||||
}
|
||||
if _, err := os.Stat(second.PrivateKeyPath); err != nil {
|
||||
t.Fatalf("回滚后当前私钥不存在:%v", err)
|
||||
if string(currentCertificate) != string(firstCertificate) {
|
||||
t.Fatal("回滚后当前证书内容不匹配")
|
||||
}
|
||||
current, _, err := store.LoadCurrent(context.Background(), "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("读取回滚后的当前证书失败:%v", err)
|
||||
}
|
||||
if current.Version != first.Version || current.Directory != second.Directory {
|
||||
t.Fatalf("回滚后的当前元数据错误:%+v", current)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,9 +138,62 @@ func TestRollbackSavedResourceClearsNewCertificateFiles(t *testing.T) {
|
||||
if err := RollbackSavedResource(context.Background(), saved); err != nil {
|
||||
t.Fatalf("清理失败证书失败:%v", err)
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
if _, err := os.Stat(filepath.Join(saved.Directory, name)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("回滚后文件仍存在:%s,错误:%v", name, err)
|
||||
}
|
||||
if _, err := os.Stat(saved.Directory); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("回滚后当前版本目录仍存在:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileStoreDoesNotRestoreHistoricalVersion(t *testing.T) {
|
||||
store := FileStore{Root: t.TempDir()}
|
||||
if _, err := store.RestoreVersion(context.Background(), "example.com", "single", "20260830-V1.0"); err == nil {
|
||||
t.Fatal("仅保留当前版本时不应支持历史版本恢复")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileStoreUsesStableSANIdentifierAndRemovesPreviousIdentifier(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := FileStore{
|
||||
Root: filepath.Join(root, "ssl"),
|
||||
BackupRoot: filepath.Join(root, "backups"),
|
||||
Now: func() time.Time { return time.Date(2026, 8, 30, 12, 0, 0, 0, time.UTC) },
|
||||
}
|
||||
firstResource := testResource(t, "example.com")
|
||||
firstResource.Domains = []string{"example.com", "www.example.com"}
|
||||
first, err := store.SaveForType(context.Background(), "example.com", "san", firstResource)
|
||||
if err != nil {
|
||||
t.Fatalf("save first SAN certificate: %v", err)
|
||||
}
|
||||
if first.CertificateIdentifier == "" {
|
||||
t.Fatal("SAN certificate identifier should be stored")
|
||||
}
|
||||
if first.Version != "20260830-V1.0" {
|
||||
t.Fatalf("unexpected first SAN version: %s", first.Version)
|
||||
}
|
||||
wantFirst := filepath.Join(root, "ssl", "example.com", "san", first.CertificateIdentifier, first.Version)
|
||||
if first.Directory != wantFirst {
|
||||
t.Fatalf("unexpected first SAN directory: got=%q want=%q", first.Directory, wantFirst)
|
||||
}
|
||||
|
||||
secondResource := firstResource
|
||||
secondResource.Domains = []string{"api.example.com", "example.com"}
|
||||
second, err := store.SaveForType(context.Background(), "example.com", "san", secondResource)
|
||||
if err != nil {
|
||||
t.Fatalf("save second SAN certificate: %v", err)
|
||||
}
|
||||
if second.CertificateIdentifier == first.CertificateIdentifier {
|
||||
t.Fatal("different SAN sets should use different identifiers")
|
||||
}
|
||||
if second.Version != "20260830-V1.0" {
|
||||
t.Fatalf("unexpected second SAN version: %s", second.Version)
|
||||
}
|
||||
if _, err := os.Stat(first.Directory); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("previous SAN certificate directory still exists: %v", err)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(root, "ssl", "example.com", "san"))
|
||||
if err != nil {
|
||||
t.Fatalf("read SAN directory: %v", err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].Name() != second.CertificateIdentifier {
|
||||
t.Fatalf("SAN directory should keep only the active identifier: %v", entries)
|
||||
}
|
||||
}
|
||||
@@ -386,3 +386,41 @@ func (s *Service) ListVersions(ctx context.Context, domainID string) ([]SavedRes
|
||||
}
|
||||
return s.store.ListVersions(ctx, item.Name, string(item.CertificateType))
|
||||
}
|
||||
|
||||
// RestoreVersion 将指定历史版本恢复为当前证书,并更新域名证书状态。
|
||||
func (s *Service) RestoreVersion(ctx context.Context, domainID, version string) (IssueResult, error) {
|
||||
if s == nil || s.repository == nil {
|
||||
return IssueResult{}, errors.New("证书服务未初始化")
|
||||
}
|
||||
item, err := s.repository.GetByID(ctx, strings.TrimSpace(domainID))
|
||||
if err != nil {
|
||||
return IssueResult{}, fmt.Errorf("读取域名配置失败:%w", err)
|
||||
}
|
||||
domains, err := requestedDomains(item)
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
_, resource, err := s.store.LoadVersion(ctx, item.Name, string(item.CertificateType), strings.TrimSpace(version))
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
if _, err := ValidateResourceForDomains(resource, domains); err != nil {
|
||||
return IssueResult{}, fmt.Errorf("历史证书不匹配当前域名配置:%w", err)
|
||||
}
|
||||
saved, err := s.store.RestoreVersion(ctx, item.Name, string(item.CertificateType), strings.TrimSpace(version))
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
if _, err := ValidateResourceForDomains(resource, domains); err != nil {
|
||||
return IssueResult{}, fmt.Errorf("恢复后证书校验失败:%w", err)
|
||||
}
|
||||
if err := s.repository.UpdateCertificateState(ctx, item.ID, "valid", &saved.NotAfter); err != nil {
|
||||
rollbackErr := RollbackSavedResource(context.Background(), saved)
|
||||
if rollbackErr != nil {
|
||||
return IssueResult{}, errors.Join(err, rollbackErr)
|
||||
}
|
||||
return IssueResult{}, fmt.Errorf("certificate state update failed after restore: %w", err)
|
||||
}
|
||||
saved.SANs = append([]string(nil), domains...)
|
||||
return IssueResult{DomainID: item.ID, Domains: domains, Saved: saved}, nil
|
||||
}
|
||||
@@ -22,8 +22,9 @@ import (
|
||||
)
|
||||
|
||||
type serviceRepository struct {
|
||||
item domain.Domain
|
||||
states []string
|
||||
item domain.Domain
|
||||
states []string
|
||||
updateErr error
|
||||
}
|
||||
|
||||
func (r *serviceRepository) GetByID(_ context.Context, _ string) (domain.Domain, error) {
|
||||
@@ -31,6 +32,9 @@ func (r *serviceRepository) GetByID(_ context.Context, _ string) (domain.Domain,
|
||||
}
|
||||
|
||||
func (r *serviceRepository) UpdateCertificateState(_ context.Context, _ string, status string, expiresAt *time.Time) error {
|
||||
if status == "valid" && r.updateErr != nil {
|
||||
return r.updateErr
|
||||
}
|
||||
r.states = append(r.states, status)
|
||||
r.item.Status = status
|
||||
r.item.ExpiresAt = expiresAt
|
||||
@@ -212,6 +216,55 @@ func TestServiceRejectsOwnedCertificateForWrongDomain(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceRestoreVersionRollsBackFilesWhenStateUpdateFails(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
cfg := certificateTestConfig(root)
|
||||
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup}
|
||||
first, err := store.SaveForType(context.Background(), item.Name, "single", testResource(t, "example.com"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := store.SaveForType(context.Background(), item.Name, "single", testResource(t, "example.com"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeCertificate, err := os.ReadFile(second.CertificatePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeKey, err := os.ReadFile(second.PrivateKeyPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := &serviceRepository{item: item, updateErr: errors.New("simulated state update failure")}
|
||||
service := NewService(cfg, repository, nil, nil, nil)
|
||||
if _, err := service.RestoreVersion(context.Background(), item.ID, first.Version); err == nil {
|
||||
t.Fatal("state update failure should be returned")
|
||||
}
|
||||
afterCertificate, err := os.ReadFile(second.CertificatePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
afterKey, err := os.ReadFile(second.PrivateKeyPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(afterCertificate) != string(beforeCertificate) || string(afterKey) != string(beforeKey) {
|
||||
t.Fatal("certificate files were not rolled back after state update failure")
|
||||
}
|
||||
current, _, err := store.LoadCurrent(context.Background(), item.Name, string(item.CertificateType))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if current.Version != second.Version {
|
||||
t.Fatalf("current metadata was not rolled back: got=%s want=%s", current.Version, second.Version)
|
||||
}
|
||||
}
|
||||
|
||||
func certificateTestConfig(root string) config.Config {
|
||||
cfg := config.Default(root)
|
||||
cfg.Paths.Certificate = filepath.Join(root, "ssl")
|
||||
@@ -261,7 +314,7 @@ func TestServiceIssuesSetupCertificateWithTypedLayout(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("申请初始化证书失败:%v", err)
|
||||
}
|
||||
wantDirectory := filepath.Join(cfg.Paths.Certificate, "scert.example.com", "single", "current")
|
||||
wantDirectory := filepath.Join(cfg.Paths.Certificate, "scert.example.com", "single", saved.Version)
|
||||
if saved.Directory != wantDirectory {
|
||||
t.Fatalf("初始化证书目录错误:got=%q want=%q", saved.Directory, wantDirectory)
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/app"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
)
|
||||
|
||||
func newCertificateCommand() *cobra.Command {
|
||||
@@ -203,7 +203,7 @@ func newLogsCommand() *cobra.Command {
|
||||
|
||||
func newConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{Use: "config", Short: "查看和修改服务配置"}
|
||||
command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigValidateCommand())
|
||||
command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigSetSecretCommand(), newConfigValidateCommand())
|
||||
return command
|
||||
}
|
||||
|
||||
@@ -221,6 +221,60 @@ func newConfigShowCommand() *cobra.Command {
|
||||
}
|
||||
}
|
||||
|
||||
func newConfigSetSecretCommand() *cobra.Command {
|
||||
var key, value string
|
||||
command := &cobra.Command{
|
||||
Use: "set-secret",
|
||||
Short: "安全更新 SMTP 敏感凭据",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if key != "notification.smtp_password" {
|
||||
return fmt.Errorf("不支持更新的敏感配置项:%s", key)
|
||||
}
|
||||
if value == "" {
|
||||
var err error
|
||||
value, err = ask(bufio.NewReader(cmd.InOrStdin()), cmd.OutOrStdout(), "请输入新的 SMTP 密码或授权码", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if value == "" {
|
||||
return errors.New("SMTP 密码不能为空")
|
||||
}
|
||||
cfg, err := loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
username := strings.TrimSpace(cfg.Notification.SMTPUsername)
|
||||
if username == "" {
|
||||
return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名")
|
||||
}
|
||||
store, err := secretstore.Open(cfg.Paths.Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("初始化 SMTP 凭据存储失败:%w", err)
|
||||
}
|
||||
ref, err := newSMTPCredentialReference()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store.Put(cmd.Context(), ref, map[string]string{"username": username, "password": value}); err != nil {
|
||||
return fmt.Errorf("保存 SMTP 凭据失败:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPCredentialRef = ref
|
||||
if err := cfg.Save(resolveConfigPath()); err != nil {
|
||||
cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cleanupCancel()
|
||||
_ = store.Delete(cleanupContext, ref)
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(cmd.OutOrStdout(), "SMTP 凭据已加密更新。")
|
||||
return err
|
||||
},
|
||||
}
|
||||
command.Flags().StringVar(&key, "key", "", "敏感配置项名称")
|
||||
command.Flags().StringVar(&value, "value", "", "SMTP 密码;留空时交互输入")
|
||||
_ = command.MarkFlagRequired("key")
|
||||
return command
|
||||
}
|
||||
func newConfigValidateCommand() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "validate",
|
||||
@@ -551,6 +605,27 @@ func setConfigValue(cfg *config.Config, key, value string) error {
|
||||
return fmt.Errorf("SMTP 通知开关格式无效:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPEnabled = parsed
|
||||
|
||||
case "notification.smtp_host":
|
||||
cfg.Notification.SMTPHost = value
|
||||
case "notification.smtp_port":
|
||||
parsed, err := parseInt()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 端口格式无效:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPPort = parsed
|
||||
case "notification.smtp_username":
|
||||
cfg.Notification.SMTPUsername = value
|
||||
case "notification.smtp_mode":
|
||||
cfg.Notification.SMTPMode = value
|
||||
case "notification.smtp_allow_plaintext_auth":
|
||||
parsed, err := parseBool()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 明文认证开关格式无效:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPAllowPlaintextAuth = parsed
|
||||
case "notification.smtp_password":
|
||||
return errors.New("SMTP 密码属于敏感信息,请使用 scert config set-secret --key notification.smtp_password")
|
||||
case "notification.provider":
|
||||
cfg.Notification.Provider = value
|
||||
case "notification.endpoint":
|
||||
|
||||
@@ -3,6 +3,8 @@ package cli
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -72,7 +74,7 @@ func newRootCommand() *cobra.Command {
|
||||
&cobra.Command{Use: "version", Short: "显示版本信息", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("Scert %s\n", version) }},
|
||||
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newCertificateCommand(),
|
||||
newRenewCommand(), newDeployCommand(), newLogsCommand(), newConfigCommand(), newBackupCommand(), newRestoreCommand(),
|
||||
newServerCommand(), newSSHKeyCommand(),
|
||||
newServerCommand(), newSSHKeyCommand(), newServiceCommand(),
|
||||
)
|
||||
localizeHelpFlags(root)
|
||||
return root
|
||||
@@ -117,11 +119,12 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
var (
|
||||
adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string
|
||||
emailHTTPPath, emailHTTPLoginPath, emailHTTPAuthMode, emailHTTPCredentialRef, emailHTTPHeaders string
|
||||
emailSMTPHost, emailSMTPUsername, emailSMTPPassword, emailSMTPMode string
|
||||
emailEventMode, emailSenderName, emailSenderEmail, emailRetryIntervals string
|
||||
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
|
||||
webHostname, webPublicIP, httpsMode string
|
||||
serverPort, emailTimeoutSecs, emailRetryCount int
|
||||
emailHTTPEnabled, emailIncludeDeploymentDetails bool
|
||||
serverPort, emailTimeoutSecs, emailRetryCount, emailSMTPPort int
|
||||
emailHTTPEnabled, emailSMTPEnabled, emailSMTPAllowPlaintextAuth, emailIncludeDeploymentDetails bool
|
||||
emailIncludeCertificateSerial, emailIncludeManagementURL bool
|
||||
dnsVerified, webEnabled bool
|
||||
)
|
||||
@@ -143,8 +146,11 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
}
|
||||
input := setup.Input{
|
||||
AdminUsername: adminUsername, AdminEmail: adminEmail, AdminPassword: adminPassword, ServerPort: serverPort,
|
||||
EmailHTTPEnabled: emailHTTPEnabled,
|
||||
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
|
||||
EmailHTTPEnabled: emailHTTPEnabled, EmailSMTPEnabled: emailSMTPEnabled,
|
||||
EmailSMTPHost: emailSMTPHost, EmailSMTPPort: emailSMTPPort, EmailSMTPUsername: emailSMTPUsername,
|
||||
EmailSMTPPassword: emailSMTPPassword,
|
||||
EmailSMTPMode: emailSMTPMode, EmailSMTPAllowPlaintextAuth: emailSMTPAllowPlaintextAuth,
|
||||
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
|
||||
EmailHTTPPath: emailHTTPPath, EmailHTTPLoginPath: emailHTTPLoginPath, EmailHTTPAuthMode: emailHTTPAuthMode,
|
||||
EmailHTTPCredentialRef: emailHTTPCredentialRef, EmailHTTPHeaders: emailHeaders,
|
||||
EmailEventMode: emailEventMode, EmailIncludeDeploymentDetails: emailIncludeDeploymentDetails,
|
||||
@@ -161,10 +167,19 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
return err
|
||||
}
|
||||
}
|
||||
cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
|
||||
cleanupDNS, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cleanupSMTP, err := prepareSMTPCredentials(cmd.Context(), cfg, &input)
|
||||
if err != nil {
|
||||
cleanupDNS()
|
||||
return err
|
||||
}
|
||||
cleanupSecret := func() {
|
||||
cleanupSMTP()
|
||||
cleanupDNS()
|
||||
}
|
||||
if err := setup.Apply(&cfg, input); err != nil {
|
||||
cleanupSecret()
|
||||
return err
|
||||
@@ -185,6 +200,13 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
command.Flags().StringVar(&adminPassword, "admin-password", "", "超级管理员密码(仅建议临时使用参数,优先交互输入)")
|
||||
command.Flags().IntVar(&serverPort, "server-port", 8080, "Scert 主服务端口")
|
||||
command.Flags().BoolVar(&emailHTTPEnabled, "email-http-enabled", false, "是否启用 HTTP 邮件通知")
|
||||
command.Flags().BoolVar(&emailSMTPEnabled, "email-smtp-enabled", false, "是否启用 SMTP 邮件通知")
|
||||
command.Flags().StringVar(&emailSMTPHost, "email-smtp-host", "", "SMTP 服务器主机")
|
||||
command.Flags().IntVar(&emailSMTPPort, "email-smtp-port", 587, "SMTP 服务器端口")
|
||||
command.Flags().StringVar(&emailSMTPUsername, "email-smtp-username", "", "SMTP 用户名")
|
||||
command.Flags().StringVar(&emailSMTPPassword, "email-smtp-password", "", "SMTP 密码(仅建议临时使用参数,优先交互输入)")
|
||||
command.Flags().StringVar(&emailSMTPMode, "email-smtp-mode", "starttls", "SMTP 连接模式:plain、starttls、implicit_tls")
|
||||
command.Flags().BoolVar(&emailSMTPAllowPlaintextAuth, "email-smtp-allow-plaintext-auth", false, "是否允许 SMTP 明文连接认证")
|
||||
command.Flags().StringVar(&emailHTTPPath, "email-http-path", "/api/email/send", "HTTP 邮件通知请求路径")
|
||||
command.Flags().StringVar(&emailHTTPLoginPath, "email-http-login-path", "/api/login", "HTTP 会话认证登录请求路径")
|
||||
command.Flags().StringVar(&emailHTTPAuthMode, "email-http-auth-mode", "none", "HTTP 邮件通知认证方式:none、bearer、hmac_sha256、session")
|
||||
@@ -262,14 +284,52 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
|
||||
return err
|
||||
}
|
||||
value.ServerPort = port
|
||||
value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "")
|
||||
value.EmailHTTPEnabled, err = askYesNo(reader, output, "是否启用 HTTP 邮件通知?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailEndpoint, err = ask(reader, output, "第三方邮箱 API 地址", "")
|
||||
if value.EmailHTTPEnabled {
|
||||
value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailEndpoint, err = ask(reader, output, "第三方邮箱 API 地址", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
value.EmailSMTPEnabled, err = askYesNo(reader, output, "是否启用 SMTP 邮件通知?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value.EmailSMTPEnabled {
|
||||
value.EmailSMTPHost, err = ask(reader, output, "SMTP 服务器主机 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPPort, err = askInt(reader, output, "SMTP 服务器端口 *", 587)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPUsername, err = ask(reader, output, "SMTP 用户名 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPPassword, err = ask(reader, output, "SMTP 密码或授权码 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPMode, err = ask(reader, output, "SMTP 连接模式(plain/starttls/implicit_tls)", "starttls")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value.EmailSMTPMode == "plain" {
|
||||
value.EmailSMTPAllowPlaintextAuth, err = askYesNo(reader, output, "是否允许 SMTP 明文认证?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
receiver, err := ask(reader, output, "通知收件人(逗号分隔)", "")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -328,6 +388,55 @@ func askDNSCredentials(reader *bufio.Reader, output io.Writer, providerID string
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func prepareSMTPCredentials(ctx context.Context, cfg config.Config, input *setup.Input) (func(), error) {
|
||||
if input == nil {
|
||||
return func() {}, errors.New("初始化输入不能为空")
|
||||
}
|
||||
if !input.EmailSMTPEnabled {
|
||||
return func() {}, nil
|
||||
}
|
||||
if strings.TrimSpace(input.EmailSMTPCredentialRef) != "" {
|
||||
return func() {}, nil
|
||||
}
|
||||
if strings.TrimSpace(input.EmailSMTPUsername) == "" {
|
||||
return func() {}, errors.New("启用 SMTP 通知后必须填写 SMTP 用户名")
|
||||
}
|
||||
if input.EmailSMTPPassword == "" {
|
||||
return func() {}, errors.New("启用 SMTP 通知后必须填写 SMTP 密码")
|
||||
}
|
||||
if cfg.Paths.Config == "" {
|
||||
return func() {}, errors.New("SMTP 敏感凭据存储目录不能为空")
|
||||
}
|
||||
store, err := secretstore.Open(cfg.Paths.Config)
|
||||
if err != nil {
|
||||
return func() {}, fmt.Errorf("初始化 SMTP 凭据存储失败:%w", err)
|
||||
}
|
||||
reference, err := newSMTPCredentialReference()
|
||||
if err != nil {
|
||||
return func() {}, err
|
||||
}
|
||||
if err := store.Put(ctx, reference, map[string]string{
|
||||
"username": strings.TrimSpace(input.EmailSMTPUsername),
|
||||
"password": input.EmailSMTPPassword,
|
||||
}); err != nil {
|
||||
return func() {}, fmt.Errorf("保存 SMTP 凭据失败:%w", err)
|
||||
}
|
||||
input.EmailSMTPCredentialRef = reference
|
||||
return func() {
|
||||
cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cleanupCancel()
|
||||
_ = store.Delete(cleanupContext, reference)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newSMTPCredentialReference() (string, error) {
|
||||
buffer := make([]byte, 18)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", fmt.Errorf("生成 SMTP 凭据引用失败:%w", err)
|
||||
}
|
||||
return "secret://notification/smtp/" + hex.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func prepareDNSCredentials(ctx context.Context, cfg config.Config, input *setup.Input, output io.Writer) (func(), error) {
|
||||
if input == nil {
|
||||
return func() {}, errors.New("初始化输入不能为空")
|
||||
|
||||
@@ -187,7 +187,7 @@ func TestAskDNSProviderUsesNumberedSelection(t *testing.T) {
|
||||
|
||||
func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("4\n1\n")), &output)
|
||||
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("9\n1\n")), &output)
|
||||
if err != nil {
|
||||
t.Fatalf("DNS 服务商选择失败:%v", err)
|
||||
}
|
||||
@@ -198,6 +198,7 @@ func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) {
|
||||
t.Fatalf("选择未开放服务商时未给出提示:%s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
blockedParent := filepath.Join(baseDir, "blocked")
|
||||
@@ -236,9 +237,9 @@ type cliFakeDNSCredentialTester struct {
|
||||
credentials map[string]string
|
||||
}
|
||||
|
||||
func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) error {
|
||||
func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) (setup.DNSVerificationReport, error) {
|
||||
f.credentials = credentials
|
||||
return nil
|
||||
return setup.DNSVerificationReport{}, nil
|
||||
}
|
||||
|
||||
func TestPrepareDNSCredentialsEncryptsAndClearsInput(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/servicehost"
|
||||
)
|
||||
|
||||
func newServiceCommand() *cobra.Command {
|
||||
var name string
|
||||
var displayName string
|
||||
var description string
|
||||
var executable string
|
||||
var serviceConfig string
|
||||
var workDir string
|
||||
|
||||
command := &cobra.Command{
|
||||
Use: "service",
|
||||
Short: "管理系统服务",
|
||||
}
|
||||
install := &cobra.Command{
|
||||
Use: "install",
|
||||
Short: "注册 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
executablePath, directory, configPath, err := servicePaths(executable, workDir, serviceConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return servicehost.Install(cmd.Context(), servicehost.Options{
|
||||
Name: name, DisplayName: displayName, Description: description,
|
||||
Executable: executablePath, ConfigPath: configPath, WorkDir: directory,
|
||||
})
|
||||
},
|
||||
}
|
||||
uninstall := &cobra.Command{
|
||||
Use: "uninstall",
|
||||
Short: "取消注册 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return servicehost.Uninstall(cmd.Context(), name)
|
||||
},
|
||||
}
|
||||
start := &cobra.Command{
|
||||
Use: "start",
|
||||
Short: "启动 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return servicehost.Start(cmd.Context(), name)
|
||||
},
|
||||
}
|
||||
stop := &cobra.Command{
|
||||
Use: "stop",
|
||||
Short: "停止 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return servicehost.Stop(cmd.Context(), name)
|
||||
},
|
||||
}
|
||||
for _, child := range []*cobra.Command{install, uninstall, start, stop} {
|
||||
command.AddCommand(child)
|
||||
}
|
||||
command.PersistentFlags().StringVar(&name, "name", "Scert", "系统服务名称")
|
||||
install.Flags().StringVar(&displayName, "display-name", "Scert SSL 证书管理服务", "系统服务显示名称")
|
||||
install.Flags().StringVar(&description, "description", "Scert SSL 证书管理服务", "系统服务描述")
|
||||
install.Flags().StringVar(&executable, "executable", "", "服务程序路径,默认使用当前 scert 程序")
|
||||
install.Flags().StringVar(&serviceConfig, "service-config", "", "服务配置文件路径,默认使用当前配置")
|
||||
install.Flags().StringVar(&workDir, "work-dir", "", "服务工作目录,默认使用程序目录")
|
||||
return command
|
||||
}
|
||||
|
||||
func servicePaths(executable, workDir, serviceConfig string) (string, string, string, error) {
|
||||
if executable == "" {
|
||||
current, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("读取当前程序路径失败:%w", err)
|
||||
}
|
||||
executable = current
|
||||
}
|
||||
executable, err := filepath.Abs(executable)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("解析服务程序路径失败:%w", err)
|
||||
}
|
||||
if workDir == "" {
|
||||
workDir = filepath.Dir(executable)
|
||||
}
|
||||
workDir, err = filepath.Abs(workDir)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("解析服务工作目录失败:%w", err)
|
||||
}
|
||||
if serviceConfig == "" {
|
||||
serviceConfig = resolveConfigPath()
|
||||
}
|
||||
serviceConfig, err = filepath.Abs(serviceConfig)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("解析服务配置路径失败:%w", err)
|
||||
}
|
||||
return executable, workDir, serviceConfig, nil
|
||||
}
|
||||
|
||||
var _ = context.Background
|
||||
@@ -108,6 +108,12 @@ type NotificationConfig struct {
|
||||
TimeoutSecs int `json:"timeout_secs"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
RetryIntervalsSecs []int `json:"retry_intervals_secs"`
|
||||
SMTPHost string `json:"smtp_host"`
|
||||
SMTPPort int `json:"smtp_port"`
|
||||
SMTPUsername string `json:"smtp_username"`
|
||||
SMTPCredentialRef string `json:"smtp_credential_ref"`
|
||||
SMTPMode string `json:"smtp_mode"`
|
||||
SMTPAllowPlaintextAuth bool `json:"smtp_allow_plaintext_auth"`
|
||||
}
|
||||
|
||||
func Default(baseDir string) Config {
|
||||
@@ -141,6 +147,8 @@ func Default(baseDir string) Config {
|
||||
TimeoutSecs: 10,
|
||||
RetryCount: 3,
|
||||
RetryIntervalsSecs: []int{30, 120, 600},
|
||||
SMTPPort: 587,
|
||||
SMTPMode: "starttls",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -250,6 +258,12 @@ func (c *Config) Normalize() {
|
||||
if c.Notification.HTTPHeaders == nil {
|
||||
c.Notification.HTTPHeaders = map[string]string{}
|
||||
}
|
||||
if c.Notification.SMTPPort == 0 {
|
||||
c.Notification.SMTPPort = 587
|
||||
}
|
||||
if c.Notification.SMTPMode == "" {
|
||||
c.Notification.SMTPMode = "starttls"
|
||||
}
|
||||
}
|
||||
func (c Config) Save(path string) error {
|
||||
if err := c.Validate(); err != nil {
|
||||
@@ -391,6 +405,20 @@ func (c Config) Validate() error {
|
||||
if c.Notification.EventMode != "detailed" && c.Notification.EventMode != "unified" {
|
||||
return fmt.Errorf("通知事件模式无效:%s", c.Notification.EventMode)
|
||||
}
|
||||
if c.Notification.SMTPMode != "plain" && c.Notification.SMTPMode != "starttls" && c.Notification.SMTPMode != "implicit_tls" {
|
||||
return fmt.Errorf("\u0053\u004d\u0054\u0050 \u8fde\u63a5\u6a21\u5f0f\u65e0\u6548\uff1a%s", c.Notification.SMTPMode)
|
||||
}
|
||||
if c.Notification.SMTPEnabled {
|
||||
if strings.TrimSpace(c.Notification.SMTPHost) == "" {
|
||||
return fmt.Errorf("\u542f\u7528 SMTP \u901a\u77e5\u65f6\u5fc5\u987b\u914d\u7f6e SMTP \u4e3b\u673a")
|
||||
}
|
||||
if c.Notification.SMTPPort < 1 || c.Notification.SMTPPort > 65535 {
|
||||
return fmt.Errorf("SMTP \u7aef\u53e3\u65e0\u6548\uff1a%d", c.Notification.SMTPPort)
|
||||
}
|
||||
if strings.TrimSpace(c.Notification.SMTPUsername) != "" && strings.TrimSpace(c.Notification.SMTPCredentialRef) == "" {
|
||||
return fmt.Errorf("SMTP \u914d\u7f6e\u7528\u6237\u540d\u540e\u5fc5\u987b\u914d\u7f6e\u52a0\u5bc6\u51ed\u636e\u5f15\u7528")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(c.Notification.HTTPPath) == "" || !strings.HasPrefix(strings.TrimSpace(c.Notification.HTTPPath), "/") {
|
||||
return fmt.Errorf("HTTP 通知请求路径必须以 / 开头")
|
||||
}
|
||||
|
||||
@@ -65,10 +65,12 @@ var descriptors = map[string]Descriptor{
|
||||
},
|
||||
},
|
||||
CNAME: {
|
||||
ID: CNAME, Name: "CNAME 委派", Description: "需要先配置委派目标和目标 DNS 服务商,后续任务接入自动验证。",
|
||||
ID: CNAME, Name: "CNAME 委派", Description: "使用已配置的 CNAME 将 DNS-01 挑战转发到专用验证域,并由目标 DNS 服务商创建和清理 TXT 记录。",
|
||||
Available: true,
|
||||
CredentialFields: []CredentialField{
|
||||
{Name: "delegated_domain", Label: "专用验证域", Required: true, Placeholder: "例如 acme.example.com"},
|
||||
{Name: "delegated_provider", Label: "委派目标 DNS 服务商", Required: true},
|
||||
{Name: "delegated_credentials_json", Label: "委派凭据 JSON", Secret: true, Required: true, Placeholder: "例如 {\"api_token\":\"...\"}"},
|
||||
},
|
||||
},
|
||||
HuaweiCloud: {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
)
|
||||
|
||||
// cnameDelegationProvider 将原始域名的 DNS-01 挑战转发到专用验证域。
|
||||
// 委派域上的 TXT 记录由目标 Provider 管理,原始域名上的 CNAME 记录由用户提前配置。
|
||||
type cnameDelegationProvider struct {
|
||||
delegatedDomain string
|
||||
target challenge.Provider
|
||||
}
|
||||
|
||||
func newCNAMEDelegationProvider(delegatedDomain string, target challenge.Provider) (challenge.Provider, error) {
|
||||
delegatedDomain = normalizeProviderDomain(delegatedDomain)
|
||||
if delegatedDomain == "" {
|
||||
return nil, ErrInvalidDelegatedDomain
|
||||
}
|
||||
if target == nil {
|
||||
return nil, ErrDelegatedProviderUnavailable
|
||||
}
|
||||
return &cnameDelegationProvider{delegatedDomain: delegatedDomain, target: target}, nil
|
||||
}
|
||||
|
||||
func (p *cnameDelegationProvider) Present(ctx context.Context, _ string, token, keyAuth string) error {
|
||||
return p.target.Present(ctx, p.delegatedDomain, token, keyAuth)
|
||||
}
|
||||
|
||||
func (p *cnameDelegationProvider) CleanUp(ctx context.Context, _ string, token, keyAuth string) error {
|
||||
return p.target.CleanUp(ctx, p.delegatedDomain, token, keyAuth)
|
||||
}
|
||||
|
||||
func normalizeProviderDomain(value string) string {
|
||||
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
)
|
||||
|
||||
type delegationRecordingProvider struct {
|
||||
presentDomain string
|
||||
cleanupDomain string
|
||||
presentToken string
|
||||
cleanupToken string
|
||||
presentErr error
|
||||
cleanupErr error
|
||||
}
|
||||
|
||||
func (p *delegationRecordingProvider) Present(_ context.Context, domain, token, _ string) error {
|
||||
p.presentDomain = domain
|
||||
p.presentToken = token
|
||||
return p.presentErr
|
||||
}
|
||||
|
||||
func (p *delegationRecordingProvider) CleanUp(_ context.Context, domain, token, _ string) error {
|
||||
p.cleanupDomain = domain
|
||||
p.cleanupToken = token
|
||||
return p.cleanupErr
|
||||
}
|
||||
|
||||
var _ challenge.Provider = (*delegationRecordingProvider)(nil)
|
||||
|
||||
func TestCNAMEDelegationProviderForwardsChallengeDomain(t *testing.T) {
|
||||
target := &delegationRecordingProvider{}
|
||||
provider, err := newCNAMEDelegationProvider(" ACME.Example.com. ", target)
|
||||
if err != nil {
|
||||
t.Fatalf("创建 CNAME 委派 Provider 失败:%v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := provider.Present(ctx, "www.example.net", "token", "key-auth"); err != nil {
|
||||
t.Fatalf("转发创建 TXT 记录失败:%v", err)
|
||||
}
|
||||
if target.presentDomain != "acme.example.com" || target.presentToken != "token" {
|
||||
t.Fatalf("创建记录未转发到规范化委派域:domain=%q token=%q", target.presentDomain, target.presentToken)
|
||||
}
|
||||
if err := provider.CleanUp(ctx, "www.example.net", "token", "key-auth"); err != nil {
|
||||
t.Fatalf("转发清理 TXT 记录失败:%v", err)
|
||||
}
|
||||
if target.cleanupDomain != "acme.example.com" || target.cleanupToken != "token" {
|
||||
t.Fatalf("清理记录未转发到规范化委派域:domain=%q token=%q", target.cleanupDomain, target.cleanupToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNAMEDelegationProviderPropagatesTargetErrors(t *testing.T) {
|
||||
presentErr := errors.New("创建失败")
|
||||
cleanupErr := errors.New("清理失败")
|
||||
target := &delegationRecordingProvider{presentErr: presentErr, cleanupErr: cleanupErr}
|
||||
provider, err := newCNAMEDelegationProvider("acme.example.com", target)
|
||||
if err != nil {
|
||||
t.Fatalf("创建 CNAME 委派 Provider 失败:%v", err)
|
||||
}
|
||||
if err := provider.Present(context.Background(), "example.com", "token", "key-auth"); !errors.Is(err, presentErr) {
|
||||
t.Fatalf("创建错误未透传:%v", err)
|
||||
}
|
||||
if err := provider.CleanUp(context.Background(), "example.com", "token", "key-auth"); !errors.Is(err, cleanupErr) {
|
||||
t.Fatalf("清理错误未透传:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegoFactoryCreatesCNAMEDelegationProvider(t *testing.T) {
|
||||
provider, err := NewLegoFactory().Create(CNAME, map[string]string{
|
||||
"delegated_domain": "acme.example.com",
|
||||
"delegated_provider": Cloudflare,
|
||||
"delegated_credentials_json": `{"api_token":"test-token"}`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("创建 CNAME 委派 Provider 失败:%v", err)
|
||||
}
|
||||
if provider == nil {
|
||||
t.Fatal("CNAME 委派 Provider 不应为空")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegoFactoryRejectsRecursiveCNAMEDelegation(t *testing.T) {
|
||||
_, err := NewLegoFactory().Create(CNAME, map[string]string{
|
||||
"delegated_domain": "acme.example.com",
|
||||
"delegated_provider": CNAME,
|
||||
"delegated_credentials_json": `{}`,
|
||||
})
|
||||
if !errors.Is(err, ErrDelegatedProviderUnavailable) {
|
||||
t.Fatalf("递归 CNAME 委派应被拒绝:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegoFactoryRejectsInvalidCNAMEDelegationCredentials(t *testing.T) {
|
||||
_, err := NewLegoFactory().Create(CNAME, map[string]string{
|
||||
"delegated_domain": "acme.example.com",
|
||||
"delegated_provider": Cloudflare,
|
||||
"delegated_credentials_json": `[]`,
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidDelegatedCredentials) {
|
||||
t.Fatalf("非对象 CNAME 凭据应被拒绝:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dnsprovider
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidDelegatedDomain = errors.New("CNAME 委派域名无效")
|
||||
ErrInvalidDelegatedCredentials = errors.New("CNAME 委派凭据无效")
|
||||
ErrDelegatedProviderUnavailable = errors.New("CNAME 委派目标 Provider 不可用")
|
||||
)
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
"github.com/go-acme/lego/v5/providers/dns/tencentcloud"
|
||||
"golang.org/x/oauth2/google"
|
||||
gdns "google.golang.org/api/dns/v1"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
type LegoFactory struct{}
|
||||
@@ -37,6 +39,27 @@ func (LegoFactory) Create(providerID string, credentials map[string]string) (cha
|
||||
return nil, err
|
||||
}
|
||||
switch providerID {
|
||||
case CNAME:
|
||||
delegatedDomain := normalizeProviderDomain(cleaned["delegated_domain"])
|
||||
if delegatedDomain == "" || strings.HasPrefix(delegatedDomain, "*.") || !domain.IsValidName(delegatedDomain) {
|
||||
return nil, ErrInvalidDelegatedDomain
|
||||
}
|
||||
delegatedProvider := strings.ToLower(strings.TrimSpace(cleaned["delegated_provider"]))
|
||||
if delegatedProvider == CNAME || delegatedProvider == Other || delegatedProvider == "" {
|
||||
return nil, fmt.Errorf("%w: %s", ErrDelegatedProviderUnavailable, delegatedProvider)
|
||||
}
|
||||
var delegatedCredentials map[string]string
|
||||
if err := json.Unmarshal([]byte(cleaned["delegated_credentials_json"]), &delegatedCredentials); err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrInvalidDelegatedCredentials, err)
|
||||
}
|
||||
if delegatedCredentials == nil {
|
||||
return nil, ErrInvalidDelegatedCredentials
|
||||
}
|
||||
target, err := (LegoFactory{}).Create(delegatedProvider, delegatedCredentials)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrDelegatedProviderUnavailable, err)
|
||||
}
|
||||
return newCNAMEDelegationProvider(delegatedDomain, target)
|
||||
case Cloudflare:
|
||||
cfg := cloudflare.NewDefaultConfig()
|
||||
cfg.AuthToken = cleaned["api_token"]
|
||||
|
||||
@@ -7,55 +7,190 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
"github.com/go-acme/lego/v5/challenge/dns01"
|
||||
"github.com/go-acme/lego/v5/challenge/dnspersist01"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/setup"
|
||||
)
|
||||
|
||||
type Factory interface {
|
||||
Create(providerID string, credentials map[string]string) (challenge.Provider, error)
|
||||
}
|
||||
|
||||
type Tester struct {
|
||||
factory Factory
|
||||
type TXTResolver interface {
|
||||
LookupTXT(ctx context.Context, fqdn string) ([]string, error)
|
||||
}
|
||||
|
||||
type Tester struct {
|
||||
factory Factory
|
||||
resolver TXTResolver
|
||||
}
|
||||
|
||||
const dnsCleanupTimeout = 30 * time.Second
|
||||
|
||||
func NewTester(factory Factory) *Tester {
|
||||
return &Tester{factory: factory}
|
||||
return NewTesterWithResolver(factory, legoTXTResolver{})
|
||||
}
|
||||
|
||||
func (t *Tester) Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) error {
|
||||
if t == nil || t.factory == nil {
|
||||
return errors.New("DNS 验证服务未初始化")
|
||||
func NewTesterWithResolver(factory Factory, resolver TXTResolver) *Tester {
|
||||
return &Tester{factory: factory, resolver: resolver}
|
||||
}
|
||||
|
||||
type VerificationError struct {
|
||||
Report setup.DNSVerificationReport
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *VerificationError) Error() string {
|
||||
if e == nil || e.Err == nil {
|
||||
return "DNS API 在线验证失败"
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e *VerificationError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Err
|
||||
}
|
||||
|
||||
func (t *Tester) Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) (setup.DNSVerificationReport, error) {
|
||||
return t.VerifyWithReport(ctx, providerID, testDomain, credentials)
|
||||
}
|
||||
|
||||
func (t *Tester) VerifyWithReport(ctx context.Context, providerID, testDomain string, credentials map[string]string) (setup.DNSVerificationReport, error) {
|
||||
report := setup.DNSVerificationReport{}
|
||||
if t == nil || t.factory == nil || t.resolver == nil {
|
||||
return report, errors.New("DNS 验证服务未初始化")
|
||||
}
|
||||
testDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(testDomain), "."))
|
||||
if !domain.IsValidName(testDomain) {
|
||||
return fmt.Errorf("DNS 测试域名格式无效:%s", testDomain)
|
||||
return report, fmt.Errorf("DNS 测试域名格式无效:%s", testDomain)
|
||||
}
|
||||
cleaned, err := ValidateCredentials(providerID, credentials)
|
||||
if err != nil {
|
||||
return err
|
||||
return report, err
|
||||
}
|
||||
provider, err := t.factory.Create(providerID, cleaned)
|
||||
if err != nil {
|
||||
return err
|
||||
return report, err
|
||||
}
|
||||
token, err := randomValue(24)
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成 DNS 测试标识失败:%w", err)
|
||||
return report, fmt.Errorf("生成 DNS 测试标识失败:%w", err)
|
||||
}
|
||||
keyAuth, err := randomValue(48)
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成 DNS 测试授权值失败:%w", err)
|
||||
return report, fmt.Errorf("生成 DNS 测试授权值失败:%w", err)
|
||||
}
|
||||
challengeInfo := dns01.GetChallengeInfo(ctx, testDomain, keyAuth)
|
||||
report.RecordName = challengeInfo.EffectiveFQDN
|
||||
if err := provider.Present(ctx, testDomain, token, keyAuth); err != nil {
|
||||
return fmt.Errorf("创建 DNS 测试记录失败:%w", err)
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "创建记录", Status: "failed", Message: "调用 DNS API 创建临时 TXT 记录失败。",
|
||||
})
|
||||
return report, &VerificationError{Report: report, Err: fmt.Errorf("创建 DNS 测试记录失败:%w", err)}
|
||||
}
|
||||
if err := provider.CleanUp(ctx, testDomain, token, keyAuth); err != nil {
|
||||
return fmt.Errorf("DNS 测试记录已创建,但自动清理失败:%w", err)
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "创建记录", Status: "completed", Message: "已调用 DNS API 创建临时 TXT 记录。",
|
||||
})
|
||||
|
||||
if err := waitForTXT(ctx, t.resolver, report.RecordName, challengeInfo.Value); err != nil {
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "查询记录", Status: "failed", Message: "公网 DNS 查询未确认 TXT 记录已生效。",
|
||||
})
|
||||
cleanupErr := cleanupChallenge(ctx, provider, testDomain, token, keyAuth)
|
||||
if cleanupErr != nil {
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "清理记录", Status: "failed", Message: "测试记录清理失败,请检查 DNS API 权限。",
|
||||
})
|
||||
return report, &VerificationError{Report: report, Err: fmt.Errorf("DNS 测试记录未通过公网查询,且自动清理失败:%w", cleanupErr)}
|
||||
}
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "清理记录", Status: "completed", Message: "已清理未通过查询确认的临时 TXT 记录。",
|
||||
})
|
||||
return report, &VerificationError{Report: report, Err: fmt.Errorf("DNS 测试记录未通过公网查询:%w", err)}
|
||||
}
|
||||
return nil
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "查询记录", Status: "completed", Message: "公网 DNS 查询已确认 TXT 记录生效。",
|
||||
})
|
||||
|
||||
if err := cleanupChallenge(ctx, provider, testDomain, token, keyAuth); err != nil {
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "清理记录", Status: "failed", Message: "测试记录已创建并确认生效,但自动清理失败。",
|
||||
})
|
||||
return report, &VerificationError{Report: report, Err: fmt.Errorf("DNS 测试记录已创建并确认生效,但自动清理失败:%w", err)}
|
||||
}
|
||||
report.Stages = append(report.Stages, setup.DNSVerificationStage{
|
||||
Name: "清理记录", Status: "completed", Message: "已调用 DNS API 清理临时 TXT 记录。",
|
||||
})
|
||||
if values, err := t.resolver.LookupTXT(ctx, report.RecordName); err == nil && containsTXT(values, challengeInfo.Value) {
|
||||
report.Stages[len(report.Stages)-1] = setup.DNSVerificationStage{
|
||||
Name: "清理记录", Status: "warning", Message: "清理请求已成功,但公网 DNS 仍能查询到旧记录,可能正在等待缓存刷新。",
|
||||
}
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func cleanupChallenge(ctx context.Context, provider challenge.Provider, testDomain, token, keyAuth string) error {
|
||||
cleanupBase := context.WithoutCancel(ctx)
|
||||
cleanupCtx, cancel := context.WithTimeout(cleanupBase, dnsCleanupTimeout)
|
||||
defer cancel()
|
||||
return provider.CleanUp(cleanupCtx, testDomain, token, keyAuth)
|
||||
}
|
||||
|
||||
type legoTXTResolver struct{}
|
||||
|
||||
func (legoTXTResolver) LookupTXT(ctx context.Context, fqdn string) ([]string, error) {
|
||||
result, err := dnspersist01.DefaultClient().LookupTXT(ctx, fqdn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values := make([]string, 0, len(result.Records))
|
||||
for _, record := range result.Records {
|
||||
values = append(values, record.Value)
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func waitForTXT(ctx context.Context, resolver TXTResolver, fqdn, expected string) error {
|
||||
if resolver == nil {
|
||||
return errors.New("TXT 查询服务未初始化")
|
||||
}
|
||||
deadline := time.NewTimer(30 * time.Second)
|
||||
defer deadline.Stop()
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
values, err := resolver.LookupTXT(ctx, fqdn)
|
||||
if err == nil && containsTXT(values, expected) {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-deadline.C:
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 TXT 记录失败:%w", err)
|
||||
}
|
||||
return errors.New("查询结果中未找到测试 TXT 值")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func containsTXT(values []string, expected string) bool {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) == expected {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func randomValue(size int) (string, error) {
|
||||
|
||||
@@ -3,9 +3,11 @@ package dnsprovider
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
"github.com/go-acme/lego/v5/challenge/dns01"
|
||||
)
|
||||
|
||||
type fakeFactory struct {
|
||||
@@ -18,38 +20,69 @@ func (f fakeFactory) Create(string, map[string]string) (challenge.Provider, erro
|
||||
}
|
||||
|
||||
type fakeProvider struct {
|
||||
presented bool
|
||||
cleaned bool
|
||||
presentErr error
|
||||
cleanupErr error
|
||||
presented bool
|
||||
cleaned bool
|
||||
cleanupSawCanceled bool
|
||||
presentErr error
|
||||
cleanupErr error
|
||||
domain string
|
||||
keyAuth string
|
||||
}
|
||||
|
||||
func (p *fakeProvider) Present(context.Context, string, string, string) error {
|
||||
type fakeTXTResolver struct {
|
||||
provider *fakeProvider
|
||||
}
|
||||
|
||||
func (r fakeTXTResolver) LookupTXT(ctx context.Context, _ string) ([]string, error) {
|
||||
if r.provider == nil || r.provider.domain == "" || r.provider.keyAuth == "" {
|
||||
return nil, errors.New("测试 DNS 记录尚未创建")
|
||||
}
|
||||
return []string{dns01.GetChallengeInfo(ctx, r.provider.domain, r.provider.keyAuth).Value}, nil
|
||||
}
|
||||
|
||||
func (p *fakeProvider) Present(_ context.Context, domain, _, keyAuth string) error {
|
||||
p.presented = true
|
||||
p.domain = domain
|
||||
p.keyAuth = keyAuth
|
||||
return p.presentErr
|
||||
}
|
||||
|
||||
func (p *fakeProvider) CleanUp(context.Context, string, string, string) error {
|
||||
func (p *fakeProvider) CleanUp(ctx context.Context, _ string, _ string, _ string) error {
|
||||
p.cleaned = true
|
||||
p.cleanupSawCanceled = ctx.Err() != nil
|
||||
return p.cleanupErr
|
||||
}
|
||||
|
||||
type missingTXTResolver struct{}
|
||||
|
||||
func (missingTXTResolver) LookupTXT(context.Context, string) ([]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestTesterCreatesAndCleansChallengeRecord(t *testing.T) {
|
||||
provider := &fakeProvider{}
|
||||
tester := NewTester(fakeFactory{provider: provider})
|
||||
err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"})
|
||||
tester := NewTesterWithResolver(fakeFactory{provider: provider}, fakeTXTResolver{provider: provider})
|
||||
report, err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"})
|
||||
if err != nil {
|
||||
t.Fatalf("DNS 测试失败:%v", err)
|
||||
}
|
||||
if !provider.presented || !provider.cleaned {
|
||||
t.Fatalf("DNS 测试未完整执行:presented=%v cleaned=%v", provider.presented, provider.cleaned)
|
||||
}
|
||||
if report.RecordName == "" || len(report.Stages) != 3 {
|
||||
t.Fatalf("DNS 测试阶段报告不完整:%+v", report)
|
||||
}
|
||||
for index, stage := range report.Stages {
|
||||
if stage.Status != "completed" && !(index == 2 && stage.Status == "warning") {
|
||||
t.Fatalf("DNS 测试阶段状态异常:%+v", report.Stages)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTesterDoesNotCleanupWhenPresentFails(t *testing.T) {
|
||||
provider := &fakeProvider{presentErr: errors.New("拒绝访问")}
|
||||
tester := NewTester(fakeFactory{provider: provider})
|
||||
err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"})
|
||||
_, err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"})
|
||||
if err == nil {
|
||||
t.Fatal("创建测试记录失败时应返回错误")
|
||||
}
|
||||
@@ -58,6 +91,39 @@ func TestTesterDoesNotCleanupWhenPresentFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTesterCleansUpWithIndependentContextAfterQueryCancellation(t *testing.T) {
|
||||
provider := &fakeProvider{}
|
||||
tester := NewTesterWithResolver(fakeFactory{provider: provider}, missingTXTResolver{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
_, err := tester.Verify(ctx, Cloudflare, "example.com", map[string]string{"api_token": "secret-token"})
|
||||
if err == nil {
|
||||
t.Fatal("公网查询被取消时应返回错误")
|
||||
}
|
||||
if !provider.cleaned {
|
||||
t.Fatal("公网查询被取消时仍应尝试清理测试记录")
|
||||
}
|
||||
if provider.cleanupSawCanceled {
|
||||
t.Fatal("清理测试记录不应继承已取消的请求上下文")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTesterReportsCleanupFailureAfterQueryFailure(t *testing.T) {
|
||||
provider := &fakeProvider{cleanupErr: errors.New("权限不足")}
|
||||
tester := NewTesterWithResolver(fakeFactory{provider: provider}, missingTXTResolver{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
report, err := tester.Verify(ctx, Cloudflare, "example.com", map[string]string{"api_token": "secret-token"})
|
||||
if err == nil || !strings.Contains(err.Error(), "自动清理失败") {
|
||||
t.Fatalf("查询失败且清理失败时应返回组合诊断:%v", err)
|
||||
}
|
||||
if len(report.Stages) != 3 || report.Stages[1].Status != "failed" || report.Stages[2].Status != "failed" {
|
||||
t.Fatalf("查询和清理失败阶段报告不完整:%+v", report.Stages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCredentialsRejectsUnknownField(t *testing.T) {
|
||||
_, err := ValidateCredentials(Cloudflare, map[string]string{"api_token": "token", "unexpected": "value"})
|
||||
if err == nil {
|
||||
@@ -65,10 +131,13 @@ func TestValidateCredentialsRejectsUnknownField(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnavailableProviderReturnsTypedError(t *testing.T) {
|
||||
_, err := NewLegoFactory().Create(CNAME, map[string]string{"delegated_domain": "acme.example.com", "delegated_provider": "cloudflare"})
|
||||
if !errors.Is(err, ErrProviderUnavailable) {
|
||||
t.Fatalf("未开放适配器应返回指定错误:%v", err)
|
||||
func TestCNAMEProviderIsAvailable(t *testing.T) {
|
||||
descriptor, err := GetDescriptor(CNAME)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read CNAME descriptor: %v", err)
|
||||
}
|
||||
if !descriptor.Available {
|
||||
t.Fatal("CNAME delegation adapter should be available")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +164,7 @@ func TestLegoFactoryCreatesConfiguredProviders(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "华为云无效区域校验",
|
||||
name: "DNSPod",
|
||||
providerID: HuaweiCloud,
|
||||
credentials: map[string]string{
|
||||
"access_key_id": "id",
|
||||
@@ -104,7 +173,7 @@ func TestLegoFactoryCreatesConfiguredProviders(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "腾讯云",
|
||||
name: "华为云无效区域校验",
|
||||
providerID: TencentCloud,
|
||||
credentials: map[string]string{
|
||||
"secret_id": "id",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
func (s *Server) restoreCertificateVersion(c *gin.Context) {
|
||||
if s.restoreVersion == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书恢复接口尚未配置", errors.New("证书恢复流程未配置"))
|
||||
return
|
||||
}
|
||||
version := strings.TrimSpace(c.Param("version"))
|
||||
result, err := s.restoreVersion(c.Request.Context(), strings.TrimSpace(c.Param("id")), version)
|
||||
if err != nil {
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "failed",
|
||||
Message: "恢复证书历史版本失败:" + err.Error(),
|
||||
})
|
||||
}
|
||||
s.writeError(c, certificateErrorStatus(err), "恢复证书历史版本失败", err)
|
||||
return
|
||||
}
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "success",
|
||||
Message: "已恢复证书历史版本:" + version,
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
type restoreCertificateReader struct {
|
||||
versions []certificate.SavedResource
|
||||
}
|
||||
|
||||
func (r restoreCertificateReader) Current(context.Context, string) (certificate.IssueResult, error) {
|
||||
return certificate.IssueResult{}, nil
|
||||
}
|
||||
|
||||
func (r restoreCertificateReader) ListVersions(context.Context, string) ([]certificate.SavedResource, error) {
|
||||
return r.versions, nil
|
||||
}
|
||||
|
||||
type restoreAuditRepository struct {
|
||||
items []repository.AuditLog
|
||||
}
|
||||
|
||||
func (r *restoreAuditRepository) CreateAuditLog(_ context.Context, item repository.AuditLog) error {
|
||||
r.items = append(r.items, item)
|
||||
return nil
|
||||
}
|
||||
|
||||
func newRestoreAPITestServer(t *testing.T, restore func(context.Context, string, string) (certificate.IssueResult, error)) (*Server, *restoreAuditRepository) {
|
||||
t.Helper()
|
||||
audit := &restoreAuditRepository{}
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
Repository: &stubDomainRepository{},
|
||||
CurrentCertificate: restoreCertificateReader{},
|
||||
RestoreCertificateVersion: restore,
|
||||
Audit: audit,
|
||||
})
|
||||
server.authSessions["test-session"] = authSession{
|
||||
Username: "admin",
|
||||
Role: "super_admin",
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
}
|
||||
return server, audit
|
||||
}
|
||||
|
||||
func TestRestoreCertificateVersionAPIRecordsSuccessAudit(t *testing.T) {
|
||||
called := false
|
||||
server, audit := newRestoreAPITestServer(t, func(_ context.Context, domainID, version string) (certificate.IssueResult, error) {
|
||||
called = true
|
||||
if domainID != "domain-1" || version != "20260830-120000" {
|
||||
t.Fatalf("unexpected restore request: %s %s", domainID, version)
|
||||
}
|
||||
return certificate.IssueResult{DomainID: domainID, Saved: certificate.SavedResource{Version: version}}, nil
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/versions/20260830-120000/restore", nil)
|
||||
request.AddCookie(&http.Cookie{Name: authCookieName, Value: "test-session"})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "20260830-120000") {
|
||||
t.Fatalf("unexpected success response: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if !called {
|
||||
t.Fatal("restore callback was not called")
|
||||
}
|
||||
if len(audit.items) != 1 || audit.items[0].Status != "success" || audit.items[0].Action != "certificate_version_restore" {
|
||||
t.Fatalf("success audit was not recorded: %+v", audit.items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreCertificateVersionAPIRecordsFailureAudit(t *testing.T) {
|
||||
server, audit := newRestoreAPITestServer(t, func(context.Context, string, string) (certificate.IssueResult, error) {
|
||||
return certificate.IssueResult{}, errors.New("simulated restore failure")
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/versions/bad/restore", nil)
|
||||
request.AddCookie(&http.Cookie{Name: authCookieName, Value: "test-session"})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("unexpected failure response: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if len(audit.items) != 1 || audit.items[0].Status != "failed" || audit.items[0].Action != "certificate_version_restore" {
|
||||
t.Fatalf("failure audit was not recorded: %+v", audit.items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListCertificateVersionsAPIRequiresAuthentication(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
Repository: &stubDomainRepository{},
|
||||
CurrentCertificate: restoreCertificateReader{versions: []certificate.SavedResource{{Domain: "example.com", Version: "v1"}}},
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/domains/domain-1/certificate/versions", nil)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated version request should be rejected: %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
var _ repository.DomainRepository = (*stubDomainRepository)(nil)
|
||||
var _ = domain.Domain{}
|
||||
@@ -0,0 +1,89 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
pathpkg "path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// frontend 为浏览器提供前端静态文件,并为 Vue 的 history 路由回退到 index.html。
|
||||
func (s *Server) frontend(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
s.configMu.RLock()
|
||||
enabled := s.config.Web.Enabled
|
||||
s.configMu.RUnlock()
|
||||
if !enabled || strings.TrimSpace(s.frontendDir) == "" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
requestPath := pathpkg.Clean("/" + strings.TrimPrefix(c.Request.URL.Path, "/"))
|
||||
if requestPath == "." || requestPath == "/" {
|
||||
requestPath = "/"
|
||||
}
|
||||
if isCoreRequestPath(requestPath) {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
staticDir, err := filepath.Abs(s.frontendDir)
|
||||
if err != nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
relativePath := strings.TrimPrefix(requestPath, "/")
|
||||
candidate := filepath.Join(staticDir, filepath.FromSlash(relativePath))
|
||||
if !isWithinDirectory(staticDir, candidate) {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if info, statErr := os.Stat(candidate); statErr == nil && info.Mode().IsRegular() {
|
||||
serveFrontendFile(c, candidate)
|
||||
return
|
||||
}
|
||||
|
||||
if requestPath != "/" && filepath.Ext(requestPath) != "" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
indexPath := filepath.Join(staticDir, "index.html")
|
||||
if info, statErr := os.Stat(indexPath); statErr != nil || !info.Mode().IsRegular() {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
serveFrontendFile(c, indexPath)
|
||||
}
|
||||
|
||||
func serveFrontendFile(c *gin.Context, path string) {
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
if filepath.Base(path) != "index.html" {
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
http.ServeFile(c.Writer, c.Request, path)
|
||||
}
|
||||
|
||||
func isCoreRequestPath(path string) bool {
|
||||
return path == "/api" ||
|
||||
strings.HasPrefix(path, "/api/") ||
|
||||
path == "/healthz" ||
|
||||
path == "/reset" ||
|
||||
strings.HasPrefix(path, "/reset/")
|
||||
}
|
||||
|
||||
func isWithinDirectory(directory, candidate string) bool {
|
||||
relative, err := filepath.Rel(directory, candidate)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestFrontendServesAssetsAndHistoryRoutes(t *testing.T) {
|
||||
staticDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(staticDir, "index.html"), []byte("<html>Scert</html>"), 0o644); err != nil {
|
||||
t.Fatalf("写入前端入口失败:%v", err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(staticDir, "assets"), 0o755); err != nil {
|
||||
t.Fatalf("创建静态资源目录失败:%v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(staticDir, "assets", "app.js"), []byte("console.log('ok')"), 0o644); err != nil {
|
||||
t.Fatalf("写入静态资源失败:%v", err)
|
||||
}
|
||||
|
||||
cfg := config.Default(t.TempDir())
|
||||
server := New(Dependencies{Config: cfg, FrontendDir: staticDir})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
wantStatus int
|
||||
wantBody string
|
||||
}{
|
||||
{name: "root", method: http.MethodGet, path: "/", wantStatus: http.StatusOK, wantBody: "Scert"},
|
||||
{name: "history route", method: http.MethodGet, path: "/login", wantStatus: http.StatusOK, wantBody: "Scert"},
|
||||
{name: "asset", method: http.MethodGet, path: "/assets/app.js", wantStatus: http.StatusOK, wantBody: "console.log"},
|
||||
{name: "missing asset", method: http.MethodGet, path: "/assets/missing.js", wantStatus: http.StatusNotFound},
|
||||
{name: "unknown api", method: http.MethodGet, path: "/api/unknown", wantStatus: http.StatusNotFound},
|
||||
{name: "post fallback", method: http.MethodPost, path: "/login", wantStatus: http.StatusNotFound},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(test.method, test.path, nil)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != test.wantStatus {
|
||||
t.Fatalf("状态码 = %d,期望 %d,响应:%s", response.Code, test.wantStatus, response.Body.String())
|
||||
}
|
||||
if test.wantBody != "" && !strings.Contains(response.Body.String(), test.wantBody) {
|
||||
t.Fatalf("响应未包含 %q:%s", test.wantBody, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrontendRespectsWebEnabled(t *testing.T) {
|
||||
staticDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(staticDir, "index.html"), []byte("Scert"), 0o644); err != nil {
|
||||
t.Fatalf("写入前端入口失败:%v", err)
|
||||
}
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Web.Enabled = false
|
||||
server := New(Dependencies{Config: cfg, FrontendDir: staticDir})
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("关闭 Web 后根路径应返回 404:%d", response.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (s *Server) runRenewalNow(c *gin.Context) {
|
||||
if s.runRenewal == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "续期服务未配置", errors.New("续期工作流未配置"))
|
||||
return
|
||||
}
|
||||
report, err := s.runRenewal(c.Request.Context())
|
||||
response := gin.H{"report": report}
|
||||
if err != nil {
|
||||
response["error"] = err.Error()
|
||||
c.JSON(http.StatusConflict, response)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
@@ -246,6 +246,6 @@ func (s *Server) recordResetAudit(c *gin.Context, status, message string) {
|
||||
}
|
||||
|
||||
var resetTemplate = template.Must(template.New("reset").Parse(`<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>Scert 超级管理员密码重置</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f7fb;color:#172033;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}.card{width:min(520px,calc(100% - 40px));padding:34px;border:1px solid #dce5f1;border-radius:20px;background:#fff;box-shadow:0 18px 60px rgba(31,50,87,.12)}h1{margin:0 0 14px;font-size:26px}p{margin:8px 0;color:#52637b;line-height:1.7}label{display:block;margin-top:16px;font-weight:700}input{box-sizing:border-box;width:100%;margin-top:8px;padding:12px;border:1px solid #c8d4e3;border-radius:10px;font:inherit}.button{width:100%;margin-top:22px;padding:12px;border:0;border-radius:10px;background:#2167d5;color:#fff;font:inherit;font-weight:700;cursor:pointer}.notice{margin-top:18px;padding:14px 16px;border-radius:12px;background:#edf5ff;color:#285a99;font-weight:700}.error{background:#fff1f0;color:#a12b22}</style></head><body><main class="card"><h1>超级管理员密码重置</h1><p>本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。</p>{{if .Message}}<div class="notice {{if not .Success}}error{{end}}">{{.Message}}</div>{{end}}<form method="post" action="/reset" autocomplete="off"><input type="hidden" name="csrf_token" value="{{.CSRFToken}}"><label for="reset-code">一次性校验码</label><input id="reset-code" name="reset_code" required maxlength="32" autocomplete="one-time-code"><label for="new-password">新密码</label><input id="new-password" name="new_password" required minlength="8" maxlength="128" type="password" autocomplete="new-password"><label for="confirm-password">确认新密码</label><input id="confirm-password" name="confirm_password" required minlength="8" maxlength="128" type="password" autocomplete="new-password"><button class="button" type="submit">确认重置密码</button></form></main></body></html>`))
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>Scert 超级管理员密码重置</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f7fb;color:#172033;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}.card{width:min(520px,calc(100% - 40px));padding:34px;border:1px solid #dce5f1;border-radius:20px;background:#fff;box-shadow:0 18px 60px rgba(31,50,87,.12)}h1{margin:0 0 14px;font-size:26px}p{margin:8px 0;color:#52637b;line-height:1.7}label{display:block;margin-top:16px;font-weight:700}input{box-sizing:border-box;width:100%;margin-top:8px;padding:12px;border:1px solid #c8d4e3;border-radius:10px;font:inherit}.button{width:100%;margin-top:22px;padding:12px;border:0;border-radius:10px;background:#2167d5;color:#fff;font:inherit;font-weight:700;cursor:pointer}.notice{margin-top:18px;padding:14px 16px;border-radius:12px;background:#edf5ff;color:#285a99;font-weight:700}.error{background:#fff1f0;color:#a12b22}</style></head><body><main class="card"><h1>超级管理员密码重置</h1><p>本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。</p>{{if .Message}}<div class="notice {{if not .Success}}error{{end}}">{{.Message}}</div>{{end}}<form method="post" action="/reset" autocomplete="off"><input type="hidden" name="csrf_token" value="{{.CSRFToken}}"><label for="reset-code">一次性校验码</label><input id="reset-code" name="reset_code" required maxlength="32" autocomplete="one-time-code"><label for="new-password">新密码</label><input id="new-password" name="new_password" required minlength="8" maxlength="12" type="password" autocomplete="new-password"><label for="confirm-password">确认新密码</label><input id="confirm-password" name="confirm_password" required minlength="8" maxlength="12" type="password" autocomplete="new-password"><button class="button" type="submit">确认重置密码</button></form></main></body></html>`))
|
||||
|
||||
var resetSuccessTemplate = template.Must(template.New("reset-success").Parse(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Scert 密码重置完成</title></head><body><main><h1>密码重置完成</h1><p>{{.Message}}</p></main></body></html>`))
|
||||
@@ -29,33 +29,39 @@ import (
|
||||
|
||||
type setupSecretWriter interface {
|
||||
Put(context.Context, string, map[string]string) error
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type Dependencies struct {
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
Servers repository.ServerRepository
|
||||
SSHKeys *sshkey.Service
|
||||
SetupDNS setupDNSVerifier
|
||||
Secrets setupSecretWriter
|
||||
Firewall firewall.Manager
|
||||
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
|
||||
RollbackSetupCertificate func(context.Context, certificate.SavedResource) error
|
||||
ImportCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error)
|
||||
DeployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
CurrentCertificate certificateReader
|
||||
ResetStatePath string
|
||||
Audit repository.AuditRepository
|
||||
Tasks repository.TaskRepository
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
FrontendDir string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
Servers repository.ServerRepository
|
||||
SSHKeys *sshkey.Service
|
||||
SetupDNS setupDNSVerifier
|
||||
Secrets setupSecretWriter
|
||||
Firewall firewall.Manager
|
||||
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
|
||||
RollbackSetupCertificate func(context.Context, certificate.SavedResource) error
|
||||
ImportCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error)
|
||||
DeployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
RestoreCertificateVersion func(context.Context, string, string) (certificate.IssueResult, error)
|
||||
|
||||
RunRenewal func(context.Context) (certificate.RenewalReport, error)
|
||||
CurrentCertificate certificateReader
|
||||
ResetStatePath string
|
||||
Audit repository.AuditRepository
|
||||
Tasks repository.TaskRepository
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
configMu sync.RWMutex
|
||||
config config.Config
|
||||
configPath string
|
||||
frontendDir string
|
||||
logger *logging.Logger
|
||||
repository repository.DomainRepository
|
||||
servers repository.ServerRepository
|
||||
@@ -68,28 +74,35 @@ type Server struct {
|
||||
rollbackSetupCertificate func(context.Context, certificate.SavedResource) error
|
||||
importCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error)
|
||||
deployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
currentCertificate certificateReader
|
||||
resetStatePath string
|
||||
audit repository.AuditRepository
|
||||
tasks repository.TaskRepository
|
||||
resetMu sync.Mutex
|
||||
resetClosedHash string
|
||||
resetLimiter *resetRateLimiter
|
||||
authSessions map[string]authSession
|
||||
authMu sync.RWMutex
|
||||
loginAttempts map[string]loginAttempt
|
||||
loginMu sync.Mutex
|
||||
now func() time.Time
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
restoreVersion func(context.Context, string, string) (certificate.IssueResult, error)
|
||||
|
||||
runRenewal func(context.Context) (certificate.RenewalReport, error)
|
||||
currentCertificate certificateReader
|
||||
resetStatePath string
|
||||
audit repository.AuditRepository
|
||||
tasks repository.TaskRepository
|
||||
resetMu sync.Mutex
|
||||
resetClosedHash string
|
||||
resetLimiter *resetRateLimiter
|
||||
authSessions map[string]authSession
|
||||
authMu sync.RWMutex
|
||||
loginAttempts map[string]loginAttempt
|
||||
loginMu sync.Mutex
|
||||
now func() time.Time
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
}
|
||||
|
||||
func New(deps Dependencies) *Server {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
router := gin.New()
|
||||
router.Use(gin.Recovery())
|
||||
frontendDir := strings.TrimSpace(deps.FrontendDir)
|
||||
if frontendDir == "" {
|
||||
frontendDir = filepath.Join(deps.Config.Paths.Install, "web")
|
||||
}
|
||||
server := &Server{
|
||||
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger,
|
||||
config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger,
|
||||
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
|
||||
servers: deps.Servers,
|
||||
sshKeys: deps.SSHKeys,
|
||||
@@ -98,6 +111,8 @@ func New(deps Dependencies) *Server {
|
||||
rollbackSetupCertificate: deps.RollbackSetupCertificate,
|
||||
importCertificate: deps.ImportCertificate,
|
||||
deployCertificate: deps.DeployCertificate,
|
||||
restoreVersion: deps.RestoreCertificateVersion,
|
||||
runRenewal: deps.RunRenewal,
|
||||
currentCertificate: deps.CurrentCertificate,
|
||||
resetStatePath: deps.ResetStatePath,
|
||||
audit: deps.Audit,
|
||||
@@ -133,12 +148,16 @@ func (s *Server) registerRoutes() {
|
||||
adminAPI.GET("/tasks/:id", s.getTask)
|
||||
adminAPI.GET("/tasks/:id/attempts", s.listTaskAttempts)
|
||||
adminAPI.GET("/audit-logs", s.listAuditLogs)
|
||||
adminAPI.GET("/settings", s.getSettings)
|
||||
adminAPI.PUT("/settings", s.updateSettings)
|
||||
adminAPI.POST("/renewal/run", s.runRenewalNow)
|
||||
adminAPI.GET("/certificates", s.listCertificates)
|
||||
adminAPI.GET("/certificates/:id", s.getCertificate)
|
||||
adminAPI.POST("/domains/:id/certificate/import", s.importCertificateFiles)
|
||||
adminAPI.POST("/domains/:id/certificate/validate", s.validateCertificate)
|
||||
adminAPI.POST("/domains/:id/deploy", s.deployCertificateCurrent)
|
||||
adminAPI.GET("/domains/:id/certificate/versions", s.listCertificateVersions)
|
||||
adminAPI.POST("/domains/:id/certificate/versions/:version/restore", s.restoreCertificateVersion)
|
||||
adminAPI.GET("/domains/:id/servers", s.listDomainServers)
|
||||
adminAPI.PUT("/domains/:id/servers", s.replaceDomainServers)
|
||||
adminAPI.GET("/servers", s.listServers)
|
||||
@@ -149,6 +168,7 @@ func (s *Server) registerRoutes() {
|
||||
adminAPI.GET("/ssh-keys", s.listSSHKeys)
|
||||
adminAPI.POST("/ssh-keys", s.createSSHKey)
|
||||
adminAPI.DELETE("/ssh-keys/:id", s.deleteSSHKey)
|
||||
s.router.NoRoute(s.frontend)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
|
||||
@@ -134,8 +134,8 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) {
|
||||
form := url.Values{
|
||||
"csrf_token": {cookie.Value},
|
||||
"reset_code": {session.Code},
|
||||
"new_password": {"NewPassword123"},
|
||||
"confirm_password": {"NewPassword123"},
|
||||
"new_password": {"NewPass1234"},
|
||||
"confirm_password": {"NewPass1234"},
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
@@ -157,7 +157,7 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("读取重置后的配置失败:%v", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil {
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPass1234")) != nil {
|
||||
t.Fatal("新密码摘要无法验证新密码")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("OldPassword123")) == nil {
|
||||
@@ -191,7 +191,7 @@ func TestResetRejectsCrossSiteAndLimitsFailures(t *testing.T) {
|
||||
get := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "http://scert.example.test/reset", nil))
|
||||
cookie := get.Result().Cookies()[0]
|
||||
base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPassword123"}, "confirm_password": {"NewPassword123"}}
|
||||
base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPass1234"}, "confirm_password": {"NewPass1234"}}
|
||||
for i := 0; i < 5; i++ {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(base.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
@@ -296,7 +296,7 @@ func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) {
|
||||
}
|
||||
fixture.server.configPath = blockedPath
|
||||
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234")
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "https://scert.example.test")
|
||||
@@ -329,7 +329,7 @@ func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) {
|
||||
|
||||
func TestResetRejectsOversizedRequestBody(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234")
|
||||
form.Set("padding", strings.Repeat("x", resetMaxBodyBytes))
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
@@ -365,7 +365,7 @@ func TestResetCSRFCookieHasRestrictedAttributes(t *testing.T) {
|
||||
|
||||
func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234")
|
||||
start := make(chan struct{})
|
||||
responses := make(chan int, 2)
|
||||
var waitGroup sync.WaitGroup
|
||||
@@ -410,7 +410,7 @@ func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("读取并发提交后的配置失败:%v", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil {
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPass1234")) != nil {
|
||||
t.Fatal("并发提交后的密码摘要无法验证新密码")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
type settingsView struct {
|
||||
Server settingsServerView `json:"server"`
|
||||
Web settingsWebView `json:"web"`
|
||||
Paths settingsPathsView `json:"paths"`
|
||||
ACME settingsACMEView `json:"acme"`
|
||||
DNS settingsDNSView `json:"dns"`
|
||||
Notification settingsNotificationView `json:"notification"`
|
||||
}
|
||||
|
||||
type settingsServerView struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
HTTPSMode string `json:"https_mode"`
|
||||
}
|
||||
|
||||
type settingsWebView struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Hostname string `json:"hostname"`
|
||||
PublicIP string `json:"public_ip"`
|
||||
}
|
||||
|
||||
type settingsPathsView struct {
|
||||
Certificate string `json:"certificate"`
|
||||
}
|
||||
|
||||
type settingsACMEView struct {
|
||||
CA string `json:"ca"`
|
||||
Environment string `json:"environment"`
|
||||
AccountEmail string `json:"account_email"`
|
||||
RenewalThresholdDays int `json:"renewal_threshold_days"`
|
||||
PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
|
||||
PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
|
||||
}
|
||||
|
||||
type settingsDNSView struct {
|
||||
Provider string `json:"provider"`
|
||||
VerificationState string `json:"verification_state"`
|
||||
}
|
||||
|
||||
type settingsNotificationView struct {
|
||||
HTTPEnabled bool `json:"http_enabled"`
|
||||
SMTPEnabled bool `json:"smtp_enabled"`
|
||||
SMTPHost string `json:"smtp_host"`
|
||||
SMTPPort int `json:"smtp_port"`
|
||||
SMTPUsername string `json:"smtp_username"`
|
||||
SMTPMode string `json:"smtp_mode"`
|
||||
SMTPAllowPlaintextAuth bool `json:"smtp_allow_plaintext_auth"`
|
||||
SMTPCredentialConfigured bool `json:"smtp_credential_configured"`
|
||||
Provider string `json:"provider"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
HTTPPath string `json:"http_path"`
|
||||
HTTPLoginPath string `json:"http_login_path"`
|
||||
HTTPAuthMode string `json:"http_auth_mode"`
|
||||
HTTPCredentialConfigured bool `json:"http_credential_configured"`
|
||||
EventMode string `json:"event_mode"`
|
||||
IncludeDeploymentDetails bool `json:"include_deployment_details"`
|
||||
IncludeCertificateSerial bool `json:"include_certificate_serial"`
|
||||
IncludeManagementURL bool `json:"include_management_url"`
|
||||
SenderName string `json:"sender_name"`
|
||||
SenderEmail string `json:"sender_email"`
|
||||
Recipients []string `json:"recipients"`
|
||||
TimeoutSecs int `json:"timeout_secs"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
RetryIntervalsSecs []int `json:"retry_intervals_secs"`
|
||||
}
|
||||
|
||||
type settingsRequest struct {
|
||||
Server *settingsServerRequest `json:"server"`
|
||||
Web *settingsWebRequest `json:"web"`
|
||||
Paths *settingsPathsRequest `json:"paths"`
|
||||
ACME *settingsACMERequest `json:"acme"`
|
||||
DNS *settingsDNSRequest `json:"dns"`
|
||||
Notification *settingsNotificationRequest `json:"notification"`
|
||||
}
|
||||
|
||||
type settingsServerRequest struct {
|
||||
Host *string `json:"host"`
|
||||
Port *int `json:"port"`
|
||||
HTTPSMode *string `json:"https_mode"`
|
||||
}
|
||||
|
||||
type settingsWebRequest struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Hostname *string `json:"hostname"`
|
||||
PublicIP *string `json:"public_ip"`
|
||||
}
|
||||
|
||||
type settingsPathsRequest struct {
|
||||
Certificate *string `json:"certificate"`
|
||||
}
|
||||
|
||||
type settingsACMERequest struct {
|
||||
CA *string `json:"ca"`
|
||||
Environment *string `json:"environment"`
|
||||
AccountEmail *string `json:"account_email"`
|
||||
RenewalThresholdDays *int `json:"renewal_threshold_days"`
|
||||
PropagationTimeoutSecs *int `json:"propagation_timeout_secs"`
|
||||
PropagationPollingIntervalSecs *int `json:"propagation_polling_interval_secs"`
|
||||
}
|
||||
|
||||
type settingsDNSRequest struct {
|
||||
Provider *string `json:"provider"`
|
||||
}
|
||||
|
||||
type settingsNotificationRequest struct {
|
||||
HTTPEnabled *bool `json:"http_enabled"`
|
||||
SMTPEnabled *bool `json:"smtp_enabled"`
|
||||
SMTPHost *string `json:"smtp_host"`
|
||||
SMTPPort *int `json:"smtp_port"`
|
||||
SMTPUsername *string `json:"smtp_username"`
|
||||
SMTPPassword *string `json:"smtp_password"`
|
||||
SMTPMode *string `json:"smtp_mode"`
|
||||
SMTPAllowPlaintextAuth *bool `json:"smtp_allow_plaintext_auth"`
|
||||
HTTPCredentials map[string]string `json:"http_credentials"`
|
||||
Provider *string `json:"provider"`
|
||||
Endpoint *string `json:"endpoint"`
|
||||
HTTPPath *string `json:"http_path"`
|
||||
HTTPLoginPath *string `json:"http_login_path"`
|
||||
HTTPAuthMode *string `json:"http_auth_mode"`
|
||||
EventMode *string `json:"event_mode"`
|
||||
IncludeDeploymentDetails *bool `json:"include_deployment_details"`
|
||||
IncludeCertificateSerial *bool `json:"include_certificate_serial"`
|
||||
IncludeManagementURL *bool `json:"include_management_url"`
|
||||
SenderName *string `json:"sender_name"`
|
||||
SenderEmail *string `json:"sender_email"`
|
||||
Recipients *[]string `json:"recipients"`
|
||||
TimeoutSecs *int `json:"timeout_secs"`
|
||||
RetryCount *int `json:"retry_count"`
|
||||
RetryIntervalsSecs *[]int `json:"retry_intervals_secs"`
|
||||
}
|
||||
|
||||
func (s *Server) getSettings(c *gin.Context) {
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
c.JSON(http.StatusOK, settingsViewFromConfig(cfg))
|
||||
}
|
||||
|
||||
func (s *Server) updateSettings(c *gin.Context) {
|
||||
if strings.TrimSpace(s.configPath) == "" {
|
||||
s.writeError(c, http.StatusInternalServerError, "配置文件路径未配置", errors.New("配置文件路径为空"))
|
||||
return
|
||||
}
|
||||
var request settingsRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "设置请求格式不正确", err)
|
||||
return
|
||||
}
|
||||
|
||||
s.configMu.Lock()
|
||||
previous := s.config
|
||||
updated := s.config
|
||||
applySettingsRequest(&updated, request)
|
||||
updated.Normalize()
|
||||
if err := s.saveSettingsNotificationCredentials(c.Request.Context(), &updated, request); err != nil {
|
||||
s.configMu.Unlock()
|
||||
s.writeError(c, http.StatusBadRequest, "保存通知凭据失败", err)
|
||||
return
|
||||
}
|
||||
if err := updated.Validate(); err != nil {
|
||||
s.configMu.Unlock()
|
||||
s.writeError(c, http.StatusBadRequest, "设置内容校验失败", err)
|
||||
return
|
||||
}
|
||||
if err := updated.Save(s.configPath); err != nil {
|
||||
s.configMu.Unlock()
|
||||
s.writeError(c, http.StatusInternalServerError, "保存设置失败", err)
|
||||
return
|
||||
}
|
||||
restartRequired := previous.Server.Host != updated.Server.Host ||
|
||||
previous.Server.Port != updated.Server.Port ||
|
||||
previous.Server.HTTPSMode != updated.Server.HTTPSMode ||
|
||||
previous.Paths.Certificate != updated.Paths.Certificate ||
|
||||
!reflect.DeepEqual(previous.ACME, updated.ACME) ||
|
||||
!reflect.DeepEqual(previous.DNS, updated.DNS) ||
|
||||
!reflect.DeepEqual(previous.Notification, updated.Notification)
|
||||
message := "设置已保存"
|
||||
if restartRequired {
|
||||
message = "设置已保存;服务监听地址、端口或 HTTPS 模式已变更,请重启 Scert 服务"
|
||||
}
|
||||
s.config = updated
|
||||
s.configMu.Unlock()
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"settings": settingsViewFromConfig(updated),
|
||||
"restart_required": restartRequired,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
func settingsViewFromConfig(cfg config.Config) settingsView {
|
||||
return settingsView{
|
||||
Server: settingsServerView{Host: cfg.Server.Host, Port: cfg.Server.Port, HTTPSMode: cfg.Server.HTTPSMode},
|
||||
Web: settingsWebView{Enabled: cfg.Web.Enabled, Hostname: cfg.Web.Hostname, PublicIP: cfg.Web.PublicIP},
|
||||
Paths: settingsPathsView{Certificate: cfg.Paths.Certificate},
|
||||
ACME: settingsACMEView{CA: cfg.ACME.CA, Environment: cfg.ACME.Environment, AccountEmail: cfg.ACME.AccountEmail, RenewalThresholdDays: cfg.ACME.RenewalThresholdDays, PropagationTimeoutSecs: cfg.ACME.PropagationTimeoutSecs, PropagationPollingIntervalSecs: cfg.ACME.PropagationPollingIntervalSecs},
|
||||
DNS: settingsDNSView{Provider: cfg.DNS.Provider, VerificationState: cfg.DNS.VerificationState},
|
||||
Notification: settingsNotificationView{
|
||||
HTTPEnabled: cfg.Notification.HTTPEnabled, SMTPEnabled: cfg.Notification.SMTPEnabled, Provider: cfg.Notification.Provider,
|
||||
SMTPHost: cfg.Notification.SMTPHost, SMTPPort: cfg.Notification.SMTPPort, SMTPUsername: cfg.Notification.SMTPUsername,
|
||||
SMTPMode: cfg.Notification.SMTPMode, SMTPAllowPlaintextAuth: cfg.Notification.SMTPAllowPlaintextAuth,
|
||||
SMTPCredentialConfigured: strings.TrimSpace(cfg.Notification.SMTPCredentialRef) != "",
|
||||
Endpoint: cfg.Notification.Endpoint, HTTPPath: cfg.Notification.HTTPPath, HTTPLoginPath: cfg.Notification.HTTPLoginPath,
|
||||
HTTPAuthMode: cfg.Notification.HTTPAuthMode, HTTPCredentialConfigured: strings.TrimSpace(cfg.Notification.HTTPCredentialRef) != "",
|
||||
EventMode: cfg.Notification.EventMode, IncludeDeploymentDetails: cfg.Notification.IncludeDeploymentDetails,
|
||||
IncludeCertificateSerial: cfg.Notification.IncludeCertificateSerial, IncludeManagementURL: cfg.Notification.IncludeManagementURL,
|
||||
SenderName: cfg.Notification.SenderName, SenderEmail: cfg.Notification.SenderEmail,
|
||||
Recipients: append([]string(nil), cfg.Notification.Recipients...), TimeoutSecs: cfg.Notification.TimeoutSecs,
|
||||
RetryCount: cfg.Notification.RetryCount, RetryIntervalsSecs: append([]int(nil), cfg.Notification.RetryIntervalsSecs...),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func applySettingsRequest(cfg *config.Config, request settingsRequest) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if request.Server != nil {
|
||||
if request.Server.Host != nil {
|
||||
cfg.Server.Host = strings.TrimSpace(*request.Server.Host)
|
||||
}
|
||||
if request.Server.Port != nil {
|
||||
cfg.Server.Port = *request.Server.Port
|
||||
}
|
||||
if request.Server.HTTPSMode != nil {
|
||||
cfg.Server.HTTPSMode = strings.TrimSpace(*request.Server.HTTPSMode)
|
||||
}
|
||||
}
|
||||
if request.Web != nil {
|
||||
if request.Web.Enabled != nil {
|
||||
cfg.Web.Enabled = *request.Web.Enabled
|
||||
}
|
||||
if request.Web.Hostname != nil {
|
||||
cfg.Web.Hostname = strings.TrimSpace(*request.Web.Hostname)
|
||||
}
|
||||
if request.Web.PublicIP != nil {
|
||||
cfg.Web.PublicIP = strings.TrimSpace(*request.Web.PublicIP)
|
||||
}
|
||||
}
|
||||
if request.Paths != nil && request.Paths.Certificate != nil {
|
||||
cfg.Paths.Certificate = strings.TrimSpace(*request.Paths.Certificate)
|
||||
}
|
||||
if request.ACME != nil {
|
||||
if request.ACME.CA != nil {
|
||||
cfg.ACME.CA = strings.TrimSpace(*request.ACME.CA)
|
||||
}
|
||||
if request.ACME.Environment != nil {
|
||||
cfg.ACME.Environment = strings.TrimSpace(*request.ACME.Environment)
|
||||
}
|
||||
if request.ACME.AccountEmail != nil {
|
||||
cfg.ACME.AccountEmail = strings.TrimSpace(*request.ACME.AccountEmail)
|
||||
}
|
||||
if request.ACME.RenewalThresholdDays != nil {
|
||||
cfg.ACME.RenewalThresholdDays = *request.ACME.RenewalThresholdDays
|
||||
}
|
||||
if request.ACME.PropagationTimeoutSecs != nil {
|
||||
cfg.ACME.PropagationTimeoutSecs = *request.ACME.PropagationTimeoutSecs
|
||||
}
|
||||
if request.ACME.PropagationPollingIntervalSecs != nil {
|
||||
cfg.ACME.PropagationPollingIntervalSecs = *request.ACME.PropagationPollingIntervalSecs
|
||||
}
|
||||
}
|
||||
if request.DNS != nil && request.DNS.Provider != nil {
|
||||
cfg.DNS.Provider = strings.TrimSpace(*request.DNS.Provider)
|
||||
}
|
||||
if request.Notification != nil {
|
||||
item := request.Notification
|
||||
if item.HTTPEnabled != nil {
|
||||
cfg.Notification.HTTPEnabled = *item.HTTPEnabled
|
||||
}
|
||||
if item.SMTPEnabled != nil {
|
||||
cfg.Notification.SMTPEnabled = *item.SMTPEnabled
|
||||
}
|
||||
if item.SMTPHost != nil {
|
||||
cfg.Notification.SMTPHost = strings.TrimSpace(*item.SMTPHost)
|
||||
}
|
||||
if item.SMTPPort != nil {
|
||||
cfg.Notification.SMTPPort = *item.SMTPPort
|
||||
}
|
||||
if item.SMTPUsername != nil {
|
||||
cfg.Notification.SMTPUsername = strings.TrimSpace(*item.SMTPUsername)
|
||||
}
|
||||
if item.SMTPMode != nil {
|
||||
cfg.Notification.SMTPMode = strings.TrimSpace(*item.SMTPMode)
|
||||
}
|
||||
if item.SMTPAllowPlaintextAuth != nil {
|
||||
cfg.Notification.SMTPAllowPlaintextAuth = *item.SMTPAllowPlaintextAuth
|
||||
}
|
||||
if item.Provider != nil {
|
||||
cfg.Notification.Provider = strings.TrimSpace(*item.Provider)
|
||||
}
|
||||
if item.Endpoint != nil {
|
||||
cfg.Notification.Endpoint = strings.TrimSpace(*item.Endpoint)
|
||||
}
|
||||
if item.HTTPPath != nil {
|
||||
cfg.Notification.HTTPPath = strings.TrimSpace(*item.HTTPPath)
|
||||
}
|
||||
if item.HTTPLoginPath != nil {
|
||||
cfg.Notification.HTTPLoginPath = strings.TrimSpace(*item.HTTPLoginPath)
|
||||
}
|
||||
if item.HTTPAuthMode != nil {
|
||||
cfg.Notification.HTTPAuthMode = strings.TrimSpace(*item.HTTPAuthMode)
|
||||
}
|
||||
if item.EventMode != nil {
|
||||
cfg.Notification.EventMode = strings.TrimSpace(*item.EventMode)
|
||||
}
|
||||
if item.IncludeDeploymentDetails != nil {
|
||||
cfg.Notification.IncludeDeploymentDetails = *item.IncludeDeploymentDetails
|
||||
}
|
||||
if item.IncludeCertificateSerial != nil {
|
||||
cfg.Notification.IncludeCertificateSerial = *item.IncludeCertificateSerial
|
||||
}
|
||||
if item.IncludeManagementURL != nil {
|
||||
cfg.Notification.IncludeManagementURL = *item.IncludeManagementURL
|
||||
}
|
||||
if item.SenderName != nil {
|
||||
cfg.Notification.SenderName = strings.TrimSpace(*item.SenderName)
|
||||
}
|
||||
if item.SenderEmail != nil {
|
||||
cfg.Notification.SenderEmail = strings.TrimSpace(*item.SenderEmail)
|
||||
}
|
||||
if item.Recipients != nil {
|
||||
cfg.Notification.Recipients = append([]string(nil), (*item.Recipients)...)
|
||||
}
|
||||
if item.TimeoutSecs != nil {
|
||||
cfg.Notification.TimeoutSecs = *item.TimeoutSecs
|
||||
}
|
||||
if item.RetryCount != nil {
|
||||
cfg.Notification.RetryCount = *item.RetryCount
|
||||
}
|
||||
if item.RetryIntervalsSecs != nil {
|
||||
cfg.Notification.RetryIntervalsSecs = append([]int(nil), (*item.RetryIntervalsSecs)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestSettingsAPIRequiresAuthentication(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
server := New(Dependencies{Config: cfg})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/settings", nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("未登录访问设置接口应返回 401,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsAPIUpdatesSafeFieldsWithoutReturningSecrets(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
cfg.Database.DSN = "mysql://secret-user:secret-password@localhost/scert"
|
||||
configPath := dir + "\\config\\scert.json"
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||
"server": {"port": 5443},
|
||||
"web": {"hostname": "admin.example.test"},
|
||||
"acme": {"renewal_threshold_days": 10}
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("更新设置应成功,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, secret := range []string{"password_hash", "secret-password", "credential_ref", "tls_key", "mysql://"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("响应不应包含敏感字段 %q:%s", secret, body)
|
||||
}
|
||||
}
|
||||
var payload struct {
|
||||
Settings settingsView `json:"settings"`
|
||||
RestartRequired bool `json:"restart_required"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("解析设置响应失败:%v", err)
|
||||
}
|
||||
if !payload.RestartRequired || payload.Settings.Server.Port != 5443 || payload.Settings.Web.Hostname != "admin.example.test" || payload.Settings.ACME.RenewalThresholdDays != 10 {
|
||||
t.Fatalf("设置响应内容不正确:%+v", payload.Settings)
|
||||
}
|
||||
if !strings.Contains(payload.Message, "请重启 Scert 服务") {
|
||||
t.Fatalf("监听参数变更后应明确提示重启服务:%s", payload.Message)
|
||||
}
|
||||
saved, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取保存后的配置失败:%v", err)
|
||||
}
|
||||
if saved.Admin.PasswordHash != cfg.Admin.PasswordHash || saved.Database.DSN != cfg.Database.DSN {
|
||||
t.Fatal("更新设置不应覆盖管理员密码或数据库 DSN")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsAPIWebAddressChangeDoesNotRequireRestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
configPath := dir + "\\config\\scert.json"
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||
"web": {"hostname": "admin.example.test", "public_ip": "203.0.113.10"}
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("更新 Web 访问地址应成功,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
RestartRequired bool `json:"restart_required"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("解析设置响应失败:%v", err)
|
||||
}
|
||||
if payload.RestartRequired {
|
||||
t.Fatal("仅修改 Web 域名或公网 IP 不应要求重启服务")
|
||||
}
|
||||
if payload.Message != "设置已保存" {
|
||||
t.Fatalf("无需重启时应返回简洁保存提示:%s", payload.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsAPIReturnsChineseNotificationCredentialError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
configPath := dir + "\\config\\scert.json"
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||
"notification": {"smtp_password": "secret-password"}
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("敏感凭据存储未配置时应返回 400,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
if !strings.Contains(response.Body.String(), "保存通知凭据失败") {
|
||||
t.Fatalf("响应应包含中文通知凭据错误说明:%s", response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "???") {
|
||||
t.Fatalf("响应不应包含问号乱码:%s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewalAPIUsesConfiguredRunner(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
called := false
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
RunRenewal: func(context.Context) (certificate.RenewalReport, error) {
|
||||
called = true
|
||||
return certificate.RenewalReport{Checked: 2, Selected: 1, Succeeded: 1}, nil
|
||||
},
|
||||
})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/renewal/run", nil)
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !called || !strings.Contains(response.Body.String(), `"selected":1`) {
|
||||
t.Fatalf("续期接口调用结果不正确:%d %s;called=%v", response.Code, response.Body.String(), called)
|
||||
}
|
||||
}
|
||||
|
||||
func loginForSettingsTest(t *testing.T, server *Server) *http.Cookie {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"admin","password":"Password123"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("管理员登录失败:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
cookies := response.Result().Cookies()
|
||||
if len(cookies) == 0 {
|
||||
t.Fatal("登录响应未返回会话 Cookie")
|
||||
}
|
||||
return cookies[0]
|
||||
}
|
||||
|
||||
func mustTestPasswordHash(t *testing.T, password string) string {
|
||||
t.Helper()
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
return string(hash)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
// saveSettingsNotificationCredentials 将页面提交的通知密码写入加密存储,配置文件只保存引用。
|
||||
func (s *Server) saveSettingsNotificationCredentials(ctx context.Context, cfg *config.Config, request settingsRequest) error {
|
||||
if cfg == nil || request.Notification == nil {
|
||||
return nil
|
||||
}
|
||||
item := request.Notification
|
||||
if len(item.HTTPCredentials) > 0 {
|
||||
if s.secrets == nil {
|
||||
return errors.New("HTTP 通知敏感凭据存储尚未初始化")
|
||||
}
|
||||
values, err := normalizeNotificationCredentials(cfg.Notification.HTTPAuthMode, item.HTTPCredentials)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref, err := newNotificationCredentialReference()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Notification.HTTPCredentialRef = ref
|
||||
}
|
||||
if item.SMTPPassword == nil || *item.SMTPPassword == "" {
|
||||
return nil
|
||||
}
|
||||
if s.secrets == nil {
|
||||
return errors.New("SMTP 通知敏感凭据存储尚未初始化")
|
||||
}
|
||||
username := strings.TrimSpace(cfg.Notification.SMTPUsername)
|
||||
if username == "" {
|
||||
return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名")
|
||||
}
|
||||
ref, err := newNotificationCredentialReference()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
values := map[string]string{"username": username, "password": *item.SMTPPassword}
|
||||
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Notification.SMTPCredentialRef = ref
|
||||
return nil
|
||||
}
|
||||
@@ -34,6 +34,13 @@ type setupRequest struct {
|
||||
AdminPassword string `json:"admin_password"`
|
||||
ServerPort int `json:"server_port"`
|
||||
EmailHTTPEnabled *bool `json:"email_http_enabled"`
|
||||
EmailSMTPEnabled *bool `json:"email_smtp_enabled"`
|
||||
EmailSMTPHost string `json:"email_smtp_host"`
|
||||
EmailSMTPPort int `json:"email_smtp_port"`
|
||||
EmailSMTPUsername string `json:"email_smtp_username"`
|
||||
EmailSMTPPassword string `json:"email_smtp_password"`
|
||||
EmailSMTPMode string `json:"email_smtp_mode"`
|
||||
EmailSMTPAllowPlaintextAuth bool `json:"email_smtp_allow_plaintext_auth"`
|
||||
EmailProvider string `json:"email_provider"`
|
||||
EmailEndpoint string `json:"email_endpoint"`
|
||||
EmailHTTPPath string `json:"email_http_path"`
|
||||
@@ -145,10 +152,15 @@ func (s *Server) testSetupDNS(c *gin.Context) {
|
||||
s.writeError(c, http.StatusNotImplemented, "该 DNS 服务商在线验证适配器尚未开放", nil)
|
||||
return
|
||||
}
|
||||
report := result.TestReport
|
||||
var verificationErr *setup.DNSVerificationError
|
||||
if errors.As(err, &verificationErr) {
|
||||
report = verificationErr.Report
|
||||
}
|
||||
if s.logger != nil {
|
||||
s.logger.Error("DNS API 在线验证失败", "provider", request.ProviderID, "test_domain", request.TestDomain)
|
||||
}
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "DNS API 在线验证失败,请检查凭据、测试域名和 DNS 权限"})
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "DNS API 在线验证失败,请检查凭据、测试域名和 DNS 权限", "test_report": report})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -156,6 +168,7 @@ func (s *Server) testSetupDNS(c *gin.Context) {
|
||||
"credential_ref": result.CredentialRef,
|
||||
"verification_token": result.VerificationToken,
|
||||
"expires_at": result.ExpiresAt,
|
||||
"test_report": result.TestReport,
|
||||
"message": "DNS API 在线验证通过,凭据已加密保存。",
|
||||
})
|
||||
}
|
||||
@@ -197,7 +210,37 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
if request.EmailHTTPEnabled != nil {
|
||||
emailHTTPEnabled = *request.EmailHTTPEnabled
|
||||
}
|
||||
emailSMTPEnabled := false
|
||||
if request.EmailSMTPEnabled != nil {
|
||||
emailSMTPEnabled = *request.EmailSMTPEnabled
|
||||
}
|
||||
createdCredentialRefs := make([]string, 0, 2)
|
||||
emailCredentialRef := strings.TrimSpace(request.EmailHTTPCredentialRef)
|
||||
smtpCredentialRef := ""
|
||||
if emailSMTPEnabled {
|
||||
smtpCredentialRef = strings.TrimSpace(s.config.Notification.SMTPCredentialRef)
|
||||
if strings.TrimSpace(request.EmailSMTPPassword) != "" {
|
||||
if strings.TrimSpace(request.EmailSMTPUsername) == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "填写 SMTP 密码前必须配置 SMTP 用户名", nil)
|
||||
return
|
||||
}
|
||||
if s.secrets == nil {
|
||||
s.writeError(c, http.StatusServiceUnavailable, "SMTP 通知敏感凭据存储尚未初始化", nil)
|
||||
return
|
||||
}
|
||||
var smtpErr error
|
||||
smtpCredentialRef, smtpErr = newNotificationCredentialReference()
|
||||
if smtpErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "生成 SMTP 通知凭据引用失败", smtpErr)
|
||||
return
|
||||
}
|
||||
createdCredentialRefs = append(createdCredentialRefs, smtpCredentialRef)
|
||||
}
|
||||
if smtpCredentialRef == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "启用 SMTP 通知后必须填写 SMTP 密码或使用已有凭据", nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
var notificationCredentials map[string]string
|
||||
var credentialErr error
|
||||
if emailHTTPEnabled && strings.ToLower(strings.TrimSpace(request.EmailHTTPAuthMode)) != "none" {
|
||||
@@ -216,6 +259,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
s.writeError(c, http.StatusInternalServerError, "生成 HTTP 通知凭据引用失败", credentialErr)
|
||||
return
|
||||
}
|
||||
createdCredentialRefs = append(createdCredentialRefs, emailCredentialRef)
|
||||
} else if emailCredentialRef == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用", nil)
|
||||
return
|
||||
@@ -228,6 +272,13 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
AdminPassword: request.AdminPassword,
|
||||
ServerPort: request.ServerPort,
|
||||
EmailHTTPEnabled: emailHTTPEnabled,
|
||||
EmailSMTPEnabled: emailSMTPEnabled,
|
||||
EmailSMTPHost: request.EmailSMTPHost,
|
||||
EmailSMTPPort: request.EmailSMTPPort,
|
||||
EmailSMTPUsername: request.EmailSMTPUsername,
|
||||
EmailSMTPCredentialRef: smtpCredentialRef,
|
||||
EmailSMTPMode: request.EmailSMTPMode,
|
||||
EmailSMTPAllowPlaintextAuth: request.EmailSMTPAllowPlaintextAuth,
|
||||
EmailProvider: request.EmailProvider,
|
||||
EmailEndpoint: request.EmailEndpoint,
|
||||
EmailHTTPPath: request.EmailHTTPPath,
|
||||
@@ -257,18 +308,22 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
HTTPSMode: request.HTTPSMode,
|
||||
})
|
||||
if err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(s.configPath) == "" {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusInternalServerError, "服务未配置配置文件路径,无法保存初始化结果", nil)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(updated.Web.PublicIP) != "" {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusBadRequest, "公网 IP 暂不支持通过 DNS-01 自动申请管理后台证书,请先配置域名或上传自有证书", nil)
|
||||
return
|
||||
}
|
||||
if s.issueSetupCertificate == nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusServiceUnavailable, "初始化证书申请服务尚未配置", nil)
|
||||
return
|
||||
}
|
||||
@@ -286,10 +341,12 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
})
|
||||
certificateCancel()
|
||||
if certificateErr != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusBadGateway, "申请管理后台证书失败,初始化尚未完成", certificateErr)
|
||||
return
|
||||
}
|
||||
if err := validateSetupCertificateFiles(savedCertificate); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("管理后台证书文件校验失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -300,6 +357,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
updated.Server.TLSKey = savedCertificate.PrivateKeyPath
|
||||
if len(notificationCredentials) > 0 {
|
||||
if err := s.secrets.Put(c.Request.Context(), emailCredentialRef, notificationCredentials); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存 HTTP 通知凭据失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -307,8 +365,22 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if emailSMTPEnabled && strings.TrimSpace(request.EmailSMTPPassword) != "" {
|
||||
if err := s.secrets.Put(c.Request.Context(), smtpCredentialRef, map[string]string{
|
||||
"username": strings.TrimSpace(request.EmailSMTPUsername),
|
||||
"password": request.EmailSMTPPassword,
|
||||
}); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存 SMTP 通知凭据失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "保存 SMTP 通知凭据失败,初始化尚未完成", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
updated.SetupReady = true
|
||||
if err := updated.Validate(); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("初始化证书配置无效,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -324,6 +396,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
firewallResult, err = s.firewall.OpenTCP(firewallContext, updated.Server.Port)
|
||||
cancel()
|
||||
if err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("自动配置本机防火墙失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -345,6 +418,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
if certificateRollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存初始化配置失败,且初始化证书回滚失败", "error", certificateRollbackErr)
|
||||
}
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if firewallRollbackErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败,且自动创建的防火墙规则回滚失败,请手动检查本机防火墙", err)
|
||||
return
|
||||
@@ -376,6 +450,36 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) rollbackSetupCredentialsWithLog(references []string) {
|
||||
if err := s.rollbackSetupCredentials(references); err != nil && s.logger != nil {
|
||||
s.logger.Error("\u521d\u59cb\u5316\u654f\u611f\u51ed\u636e\u56de\u6eda\u5931\u8d25", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) rollbackSetupCredentials(references []string) error {
|
||||
if s == nil || s.secrets == nil || len(references) == 0 {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
seen := make(map[string]struct{}, len(references))
|
||||
var rollbackErrors []error
|
||||
for _, reference := range references {
|
||||
reference = strings.TrimSpace(reference)
|
||||
if reference == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[reference]; ok {
|
||||
continue
|
||||
}
|
||||
seen[reference] = struct{}{}
|
||||
if err := s.secrets.Delete(ctx, reference); err != nil {
|
||||
rollbackErrors = append(rollbackErrors, fmt.Errorf("\u56de\u6eda\u654f\u611f\u51ed\u636e %s \u5931\u8d25\uFF1A%w", reference, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(rollbackErrors...)
|
||||
}
|
||||
|
||||
func (s *Server) rollbackIssuedSetupCertificate(saved certificate.SavedResource) error {
|
||||
if s.rollbackSetupCertificate == nil {
|
||||
return nil
|
||||
|
||||
@@ -29,7 +29,8 @@ type fakeSetupDNSVerifier struct {
|
||||
}
|
||||
|
||||
type fakeSetupSecretWriter struct {
|
||||
values map[string]map[string]string
|
||||
values map[string]map[string]string
|
||||
deleted []string
|
||||
}
|
||||
|
||||
func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value map[string]string) error {
|
||||
@@ -44,6 +45,18 @@ func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSetupSecretWriter) Delete(_ context.Context, reference string) error {
|
||||
if f.values == nil {
|
||||
return errors.New("secret not found")
|
||||
}
|
||||
if _, ok := f.values[reference]; !ok {
|
||||
return errors.New("secret not found")
|
||||
}
|
||||
delete(f.values, reference)
|
||||
f.deleted = append(f.deleted, reference)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeFirewallManager struct {
|
||||
result firewall.Result
|
||||
openErr error
|
||||
@@ -99,6 +112,14 @@ func (f *fakeSetupDNSVerifier) Verify(context.Context, setup.DNSVerificationInpu
|
||||
CredentialRef: "secret://dns/cloudflare/test",
|
||||
VerificationToken: "verified-token",
|
||||
ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
|
||||
TestReport: setup.DNSVerificationReport{
|
||||
RecordName: "_acme-challenge.example.com.",
|
||||
Stages: []setup.DNSVerificationStage{
|
||||
{Name: "创建记录", Status: "completed", Message: "已创建测试记录"},
|
||||
{Name: "查询记录", Status: "completed", Message: "已确认测试记录"},
|
||||
{Name: "清理记录", Status: "completed", Message: "已清理测试记录"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return f.verifyResult, f.verifyErr
|
||||
@@ -175,6 +196,11 @@ func TestSetupDNSProviderCatalogAndOnlineTest(t *testing.T) {
|
||||
if strings.Contains(testResponse.Body.String(), "secret-token") {
|
||||
t.Fatal("DNS 在线测试响应不应返回明文凭据")
|
||||
}
|
||||
if !strings.Contains(testResponse.Body.String(), "test_report") ||
|
||||
!strings.Contains(testResponse.Body.String(), "创建记录") ||
|
||||
!strings.Contains(testResponse.Body.String(), "清理记录") {
|
||||
t.Fatalf("DNS 在线测试响应应包含阶段报告:%s", testResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
@@ -193,7 +219,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"admin_password":"secure1234",
|
||||
"server_port":8443,
|
||||
"email_provider":"mail-api",
|
||||
"email_endpoint":"https://mail.example.test/send",
|
||||
@@ -234,7 +260,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("读取保存后的配置失败:%v", err)
|
||||
}
|
||||
if strings.Contains(string(data), "secure-pass-123") {
|
||||
if strings.Contains(string(data), "secure1234") {
|
||||
t.Fatal("配置文件不应保存管理员明文密码")
|
||||
}
|
||||
var saved config.Config
|
||||
@@ -275,7 +301,7 @@ func TestSetupApplyEncryptsNotificationCredentialsAndPersistsReference(t *testin
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"admin_password":"secure1234",
|
||||
"server_port":8443,
|
||||
"email_http_enabled":true,
|
||||
"email_provider":"mail-api",
|
||||
@@ -368,7 +394,7 @@ func TestSetupApplyRejectsMissingNotificationCredentials(t *testing.T) {
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"admin_password":"secure1234",
|
||||
"server_port":8443,
|
||||
"email_http_enabled":true,
|
||||
"email_endpoint":"https://mail.example.test",
|
||||
@@ -483,7 +509,7 @@ func TestSetupSaveFailureDoesNotConsumeDNSToken(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -513,7 +539,7 @@ func TestSetupSaveFailureKeepsExistingFirewallRule(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: &fakeSetupDNSVerifier{}, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -536,7 +562,7 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -552,6 +578,48 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupLateFailureDeletesNewNotificationCredentials(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
blockedParent := filepath.Join(baseDir, "blocked")
|
||||
if err := os.WriteFile(blockedParent, []byte("blocked"), 0o600); err != nil {
|
||||
t.Fatalf("create blocked path: %v", err)
|
||||
}
|
||||
secrets := &fakeSetupSecretWriter{}
|
||||
firewallManager := &fakeFirewallManager{result: firewall.Result{
|
||||
Backend: "ufw", RuleName: "Scert Web TCP 8443", Port: 8443, Created: true,
|
||||
}}
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: filepath.Join(blockedParent, "scert.json"),
|
||||
Repository: &stubDomainRepository{}, SetupDNS: &fakeSetupDNSVerifier{}, Secrets: secrets,
|
||||
Firewall: firewallManager, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure1234"),
|
||||
`"server_port":8443,`,
|
||||
`"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":"http-secret"},
|
||||
"email_smtp_enabled":true,
|
||||
"email_smtp_host":"smtp.example.test",
|
||||
"email_smtp_port":587,
|
||||
"email_smtp_username":"smtp-user",
|
||||
"email_smtp_password":"smtp-secret",
|
||||
"email_smtp_mode":"starttls",`, 1)
|
||||
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.StatusInternalServerError {
|
||||
t.Fatalf("late setup failure should return 500: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if len(secrets.deleted) != 2 || len(secrets.values) != 0 {
|
||||
t.Fatalf("new notification credentials should be deleted: deleted=%v values=%v", secrets.deleted, secrets.values)
|
||||
}
|
||||
}
|
||||
|
||||
func setupPayload(baseDir, password string) string {
|
||||
return `{
|
||||
"admin_username":"root-admin",
|
||||
@@ -578,7 +646,7 @@ func TestSetupCertificateFailureDoesNotSaveOrConsumeDNSToken(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, errors.New("模拟证书申请失败")),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -609,7 +677,7 @@ func TestSetupCertificateFileValidationDoesNotSaveOrConsumeDNSToken(t *testing.T
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: issuer,
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -634,7 +702,7 @@ func TestSetupWithPublicIPRejectsDNSAutomaticCertificate(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure-pass-123"),
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure1234"),
|
||||
`"web_hostname":"scert.example.test",`,
|
||||
`"web_hostname":"","web_public_ip":"192.0.2.10",`, 1)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
|
||||
@@ -667,7 +735,7 @@ func TestSetupFirewallFailureRollsBackIssuedCertificate(t *testing.T) {
|
||||
return certificate.RollbackSavedResource(context.Background(), saved)
|
||||
},
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -88,17 +89,18 @@ func (e *sessionExpiredError) Error() string {
|
||||
|
||||
// Service 通过 HTTP 邮件 API 发送通知。
|
||||
type Service struct {
|
||||
config config.NotificationConfig
|
||||
credentials CredentialReader
|
||||
client HTTPDoer
|
||||
now func() time.Time
|
||||
requestID func() string
|
||||
sleep func(context.Context, time.Duration) error
|
||||
config config.NotificationConfig
|
||||
credentials CredentialReader
|
||||
client HTTPDoer
|
||||
now func() time.Time
|
||||
requestID func() string
|
||||
sleep func(context.Context, time.Duration) error
|
||||
smtpTLSConfig func(string) *tls.Config
|
||||
}
|
||||
|
||||
// New 创建 HTTP 通知服务。SMTP 配置暂保留为兼容字段,当前发送器只执行 HTTP 通知。
|
||||
func New(cfg config.NotificationConfig, credentials CredentialReader) *Service {
|
||||
return &Service{
|
||||
service := &Service{
|
||||
config: cfg,
|
||||
credentials: credentials,
|
||||
client: &http.Client{},
|
||||
@@ -106,18 +108,19 @@ func New(cfg config.NotificationConfig, credentials CredentialReader) *Service {
|
||||
requestID: newRequestID,
|
||||
sleep: sleepContext,
|
||||
}
|
||||
service.smtpTLSConfig = func(host string) *tls.Config {
|
||||
return &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
// Send 按配置发送通知;未启用任何通知通道时直接返回成功。
|
||||
func (s *Service) Send(ctx context.Context, event Event) error {
|
||||
func (s *Service) sendHTTP(ctx context.Context, event Event) error {
|
||||
if s == nil {
|
||||
return errors.New("通知服务未初始化")
|
||||
}
|
||||
if !s.config.HTTPEnabled && !s.config.SMTPEnabled {
|
||||
return nil
|
||||
}
|
||||
if !s.config.HTTPEnabled {
|
||||
return errors.New("当前仅支持 HTTP 邮件通知,SMTP 通知发送器尚未接入")
|
||||
return nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
@@ -272,7 +275,7 @@ func (s *Service) sendOnce(ctx context.Context, endpoint string, body []byte, cr
|
||||
func (s *Service) loginSession(ctx context.Context, credentials map[string]string) (sessionAuth, error) {
|
||||
account := credentialValue(credentials, "account", "username", "identifier")
|
||||
password := credentials["password"]
|
||||
if account == "" || strings.TrimSpace(password) == "" {
|
||||
if account == "" || password == "" {
|
||||
return sessionAuth{}, errors.New("HTTP 通知会话凭据必须包含账号和密码")
|
||||
}
|
||||
loginURL, err := notificationURL(s.config.Endpoint, s.config.HTTPLoginPath)
|
||||
@@ -321,7 +324,7 @@ func (s *Service) loginSession(ctx context.Context, credentials map[string]strin
|
||||
if strings.TrimSpace(envelope.ErrorMsg) == "" {
|
||||
return sessionAuth{}, fmt.Errorf("HTTP 通知登录失败,错误码 %d", *envelope.ErrorNo)
|
||||
}
|
||||
return sessionAuth{}, fmt.Errorf("HTTP 通知登录失败,错误码 %d", *envelope.ErrorNo)
|
||||
return sessionAuth{}, fmt.Errorf("HTTP 通知登录失败,错误码 %d:%s", *envelope.ErrorNo, strings.TrimSpace(envelope.ErrorMsg))
|
||||
}
|
||||
cookies := make([]string, 0, len(response.Cookies()))
|
||||
csrf := ""
|
||||
|
||||
@@ -271,3 +271,80 @@ func TestSendRefreshesExpiredSession(t *testing.T) {
|
||||
t.Fatalf("未使用刷新后的会话:%v", cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRejectsEmptySessionPasswordWithoutTrimmingValidPassword(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := newTestConfig(server.URL)
|
||||
cfg.HTTPAuthMode = "session"
|
||||
cfg.HTTPCredentialRef = "secret://mail-session"
|
||||
service := New(cfg, credentialReaderStub{values: map[string]string{
|
||||
"account": "xuans",
|
||||
"password": "",
|
||||
}})
|
||||
err := service.Send(context.Background(), Event{Status: "success", Domain: "example.com"})
|
||||
if err == nil || !strings.Contains(err.Error(), "必须包含账号和密码") {
|
||||
t.Fatalf("空密码应在发起登录请求前被拒绝:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLoginPreservesWhitespacePassword(t *testing.T) {
|
||||
var loginPayload map[string]string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != "/api/login" {
|
||||
writer.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal(body, &loginPayload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer.Header().Add("Set-Cookie", "session=whitespace-session; Path=/; HttpOnly")
|
||||
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_, _ = writer.Write([]byte(`{"errorNo":0,"errorMsg":""}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := newTestConfig(server.URL)
|
||||
cfg.HTTPAuthMode = "session"
|
||||
cfg.HTTPCredentialRef = "secret://mail-session"
|
||||
service := New(cfg, credentialReaderStub{values: map[string]string{
|
||||
"account": "xuans",
|
||||
"password": " test-password ",
|
||||
}})
|
||||
if err := service.Send(context.Background(), Event{Status: "success", Domain: "example.com"}); err != nil {
|
||||
t.Fatalf("保留空白密码的会话登录失败:%v", err)
|
||||
}
|
||||
if loginPayload["password"] != " test-password " {
|
||||
t.Fatalf("密码不应被 TrimSpace:%q", loginPayload["password"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLoginReturnsBusinessMessageWithoutCredentials(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_, _ = writer.Write([]byte(`{"errorNo":403,"errorMsg":"账号或密码错误"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := newTestConfig(server.URL)
|
||||
cfg.HTTPAuthMode = "session"
|
||||
cfg.HTTPCredentialRef = "secret://mail-session"
|
||||
service := New(cfg, credentialReaderStub{values: map[string]string{
|
||||
"account": "xuans",
|
||||
"password": "test-password",
|
||||
}})
|
||||
err := service.Send(context.Background(), Event{Status: "success", Domain: "example.com"})
|
||||
if err == nil || !strings.Contains(err.Error(), "错误码 403") || !strings.Contains(err.Error(), "账号或密码错误") {
|
||||
t.Fatalf("登录业务错误应包含安全诊断:%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "test-password") {
|
||||
t.Fatalf("登录错误不得包含密码:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Send 通过所有已启用的出站通道发送通知。
|
||||
func (s *Service) Send(ctx context.Context, event Event) error {
|
||||
if s == nil {
|
||||
return errors.New("通知服务未初始化")
|
||||
}
|
||||
if !s.config.HTTPEnabled && !s.config.SMTPEnabled {
|
||||
return nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
var errs []error
|
||||
if s.config.HTTPEnabled {
|
||||
if err := s.sendHTTP(ctx, event); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if s.config.SMTPEnabled {
|
||||
payload, err := s.buildPayload(event)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
} else if err := s.sendSMTPWithRetry(ctx, payload); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (s *Service) sendSMTPWithRetry(ctx context.Context, payload mailPayload) error {
|
||||
if strings.TrimSpace(s.config.SMTPHost) == "" {
|
||||
return errors.New("SMTP 主机不能为空")
|
||||
}
|
||||
credentials, err := s.loadSMTPCredentials(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= s.config.RetryCount; attempt++ {
|
||||
if attempt > 0 {
|
||||
interval := time.Duration(0)
|
||||
if attempt-1 < len(s.config.RetryIntervalsSecs) {
|
||||
interval = time.Duration(s.config.RetryIntervalsSecs[attempt-1]) * time.Second
|
||||
}
|
||||
if err := s.sleep(ctx, interval); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := s.sendSMTPOnce(ctx, payload, credentials); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("发送 SMTP 通知失败,已重试 %d 次:%w", s.config.RetryCount, lastErr)
|
||||
}
|
||||
|
||||
func (s *Service) loadSMTPCredentials(ctx context.Context) (map[string]string, error) {
|
||||
ref := strings.TrimSpace(s.config.SMTPCredentialRef)
|
||||
if ref == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if s.credentials == nil {
|
||||
return nil, errors.New("SMTP 通知凭据存储未配置")
|
||||
}
|
||||
values, err := s.credentials.Get(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 SMTP 通知凭据失败:%w", err)
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func (s *Service) sendSMTPOnce(ctx context.Context, payload mailPayload, credentials map[string]string) error {
|
||||
host := strings.TrimSpace(s.config.SMTPHost)
|
||||
if host == "" {
|
||||
return errors.New("SMTP 主机不能为空")
|
||||
}
|
||||
timeout := time.Duration(s.config.TimeoutSecs) * time.Second
|
||||
if timeout < time.Second {
|
||||
timeout = time.Second
|
||||
}
|
||||
address := net.JoinHostPort(strings.Trim(host, "[]"), strconv.Itoa(s.config.SMTPPort))
|
||||
conn, err := s.dialSMTP(ctx, address, host, s.config.SMTPMode, timeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接 SMTP 服务器失败:%w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(timeout))
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("初始化 SMTP 客户端失败:%w", err)
|
||||
}
|
||||
defer client.Close()
|
||||
if s.config.SMTPMode == "starttls" {
|
||||
tlsConfig := s.smtpTLSConfig(host)
|
||||
if ok, _ := client.Extension("STARTTLS"); !ok {
|
||||
return errors.New("SMTP 服务器不支持 STARTTLS")
|
||||
}
|
||||
if err := client.StartTLS(tlsConfig); err != nil {
|
||||
return fmt.Errorf("建立 SMTP STARTTLS 连接失败:%w", err)
|
||||
}
|
||||
}
|
||||
username := strings.TrimSpace(s.config.SMTPUsername)
|
||||
if username == "" {
|
||||
username = credentialValue(credentials, "username", "account", "email")
|
||||
}
|
||||
password := credentialValue(credentials, "password", "pass")
|
||||
if username != "" {
|
||||
if password == "" {
|
||||
return errors.New("SMTP 凭据中缺少密码")
|
||||
}
|
||||
if s.config.SMTPMode == "plain" && !s.config.SMTPAllowPlaintextAuth {
|
||||
return errors.New("SMTP 明文连接禁止认证,请启用 TLS 或明确允许明文认证")
|
||||
}
|
||||
if err := client.Auth(smtp.PlainAuth("", username, password, host)); err != nil {
|
||||
return fmt.Errorf("SMTP 认证失败:%w", err)
|
||||
}
|
||||
}
|
||||
recipients := make([]string, 0, len(payload.To))
|
||||
for _, item := range payload.To {
|
||||
recipients = append(recipients, item.Email)
|
||||
}
|
||||
if err := client.Mail(payload.From.Email); err != nil {
|
||||
return fmt.Errorf("设置 SMTP 发件人失败:%w", err)
|
||||
}
|
||||
for _, recipient := range recipients {
|
||||
if err := client.Rcpt(recipient); err != nil {
|
||||
return fmt.Errorf("设置 SMTP 收件人失败:%w", err)
|
||||
}
|
||||
}
|
||||
writer, err := client.Data()
|
||||
if err != nil {
|
||||
return fmt.Errorf("打开 SMTP 邮件数据通道失败:%w", err)
|
||||
}
|
||||
if _, err := writer.Write(buildSMTPMessage(payload)); err != nil {
|
||||
_ = writer.Close()
|
||||
return fmt.Errorf("写入 SMTP 邮件内容失败:%w", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return fmt.Errorf("提交 SMTP 邮件失败:%w", err)
|
||||
}
|
||||
if err := client.Quit(); err != nil {
|
||||
return fmt.Errorf("关闭 SMTP 会话失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) dialSMTP(ctx context.Context, address, host, mode string, timeout time.Duration) (net.Conn, error) {
|
||||
dialer := &net.Dialer{Timeout: timeout}
|
||||
conn, err := dialer.DialContext(ctx, "tcp", address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mode != "implicit_tls" {
|
||||
return conn, nil
|
||||
}
|
||||
tlsConfig := s.smtpTLSConfig
|
||||
if tlsConfig == nil {
|
||||
tlsConfig = func(serverName string) *tls.Config {
|
||||
return &tls.Config{ServerName: serverName, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
}
|
||||
tlsConn := tls.Client(conn, tlsConfig(host))
|
||||
if err := tlsConn.SetDeadline(time.Now().Add(timeout)); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
_ = tlsConn.SetDeadline(time.Time{})
|
||||
return tlsConn, nil
|
||||
}
|
||||
|
||||
func buildSMTPMessage(payload mailPayload) []byte {
|
||||
from := formatSMTPAddress(payload.From)
|
||||
to := make([]string, 0, len(payload.To))
|
||||
for _, item := range payload.To {
|
||||
to = append(to, formatSMTPAddress(item))
|
||||
}
|
||||
subject := mime.QEncoding.Encode("UTF-8", payload.Subject)
|
||||
content := payload.Text
|
||||
content = strings.ReplaceAll(content, "\r\n", "\n")
|
||||
content = strings.ReplaceAll(content, "\r", "\n")
|
||||
content = strings.ReplaceAll(content, "\n", "\r\n")
|
||||
if !strings.HasSuffix(content, "\r\n") {
|
||||
content += "\r\n"
|
||||
}
|
||||
message := "From: " + from + "\r\n" +
|
||||
"To: " + strings.Join(to, ", ") + "\r\n" +
|
||||
"Subject: " + subject + "\r\n" +
|
||||
"Date: " + time.Now().Format(time.RFC1123Z) + "\r\n" +
|
||||
"MIME-Version: 1.0\r\n" +
|
||||
"Content-Type: text/plain; charset=UTF-8\r\n" +
|
||||
"Content-Transfer-Encoding: 8bit\r\n\r\n" + content
|
||||
return []byte(message)
|
||||
}
|
||||
|
||||
func formatSMTPAddress(value address) string {
|
||||
parsed, err := mail.ParseAddress(value.Email)
|
||||
if err != nil || parsed.Address == "" {
|
||||
return value.Email
|
||||
}
|
||||
name := strings.TrimSpace(value.Name)
|
||||
if name == "" {
|
||||
name = parsed.Name
|
||||
}
|
||||
if name == "" {
|
||||
return parsed.Address
|
||||
}
|
||||
return mime.QEncoding.Encode("UTF-8", name) + " <" + parsed.Address + ">"
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
type smtpTestServer struct {
|
||||
listener net.Listener
|
||||
tlsConfig *tls.Config
|
||||
implicitTLS bool
|
||||
failMailOnce bool
|
||||
rejectAuth bool
|
||||
mu sync.Mutex
|
||||
messages [][]byte
|
||||
connections int
|
||||
}
|
||||
|
||||
func newSMTPTestServer(t *testing.T, implicitTLS, startTLS bool) *smtpTestServer {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("create SMTP test listener: %v", err)
|
||||
}
|
||||
server := &smtpTestServer{listener: listener, implicitTLS: implicitTLS}
|
||||
if implicitTLS || startTLS {
|
||||
server.tlsConfig = newSMTPTestTLSConfig(t)
|
||||
}
|
||||
go server.serve(startTLS)
|
||||
t.Cleanup(func() { _ = listener.Close() })
|
||||
return server
|
||||
}
|
||||
|
||||
func (s *smtpTestServer) address() (string, int) {
|
||||
address := s.listener.Addr().(*net.TCPAddr)
|
||||
return address.IP.String(), address.Port
|
||||
}
|
||||
|
||||
func (s *smtpTestServer) serve(startTLS bool) {
|
||||
for {
|
||||
connection, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.connections++
|
||||
s.mu.Unlock()
|
||||
go s.handle(connection, startTLS)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *smtpTestServer) handle(connection net.Conn, startTLS bool) {
|
||||
defer connection.Close()
|
||||
if s.implicitTLS {
|
||||
tlsConnection := tls.Server(connection, s.tlsConfig)
|
||||
if err := tlsConnection.Handshake(); err != nil {
|
||||
return
|
||||
}
|
||||
connection = tlsConnection
|
||||
}
|
||||
reader := bufio.NewReader(connection)
|
||||
writeLine := func(value string) error {
|
||||
_, err := io.WriteString(connection, value+"\r\n")
|
||||
return err
|
||||
}
|
||||
if writeLine("220 smtp.test.local ESMTP") != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
command := strings.TrimSpace(line)
|
||||
upper := strings.ToUpper(command)
|
||||
switch {
|
||||
case strings.HasPrefix(upper, "EHLO"), strings.HasPrefix(upper, "HELO"):
|
||||
if writeLine("250-smtp.test.local") != nil {
|
||||
return
|
||||
}
|
||||
if startTLS && writeLine("250-STARTTLS") != nil {
|
||||
return
|
||||
}
|
||||
if writeLine("250 AUTH PLAIN") != nil {
|
||||
return
|
||||
}
|
||||
case strings.HasPrefix(upper, "STARTTLS"):
|
||||
if !startTLS || writeLine("220 ready for TLS") != nil {
|
||||
return
|
||||
}
|
||||
tlsConnection := tls.Server(connection, s.tlsConfig)
|
||||
if err := tlsConnection.Handshake(); err != nil {
|
||||
return
|
||||
}
|
||||
connection = tlsConnection
|
||||
reader = bufio.NewReader(connection)
|
||||
case strings.HasPrefix(upper, "AUTH PLAIN"):
|
||||
if s.rejectAuth {
|
||||
if writeLine("535 authentication failed") != nil {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if writeLine("235 authentication successful") != nil {
|
||||
return
|
||||
}
|
||||
case strings.HasPrefix(upper, "MAIL FROM:"):
|
||||
s.mu.Lock()
|
||||
fail := s.failMailOnce
|
||||
s.failMailOnce = false
|
||||
s.mu.Unlock()
|
||||
if fail {
|
||||
if writeLine("451 temporary failure") != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
if writeLine("250 sender accepted") != nil {
|
||||
return
|
||||
}
|
||||
case strings.HasPrefix(upper, "RCPT TO:"):
|
||||
if writeLine("250 recipient accepted") != nil {
|
||||
return
|
||||
}
|
||||
case upper == "DATA":
|
||||
if writeLine("354 end with <CRLF>.<CRLF>") != nil {
|
||||
return
|
||||
}
|
||||
var message strings.Builder
|
||||
for {
|
||||
dataLine, readErr := reader.ReadString('\n')
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
if dataLine == ".\r\n" {
|
||||
break
|
||||
}
|
||||
message.WriteString(dataLine)
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.messages = append(s.messages, []byte(message.String()))
|
||||
s.mu.Unlock()
|
||||
if writeLine("250 queued") != nil {
|
||||
return
|
||||
}
|
||||
case upper == "QUIT":
|
||||
_ = writeLine("221 closing connection")
|
||||
return
|
||||
default:
|
||||
if writeLine("250 ok") != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *smtpTestServer) clientTLSConfig(host string) *tls.Config {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
pool := x509.NewCertPool()
|
||||
if len(s.tlsConfig.Certificates) == 0 || len(s.tlsConfig.Certificates[0].Certificate) == 0 {
|
||||
return &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
pool.AppendCertsFromPEM(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: s.tlsConfig.Certificates[0].Certificate[0]}))
|
||||
return &tls.Config{ServerName: host, RootCAs: pool, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
|
||||
func (s *smtpTestServer) message() []byte {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.messages) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append([]byte(nil), s.messages[len(s.messages)-1]...)
|
||||
}
|
||||
|
||||
func newSMTPTestTLSConfig(t *testing.T) *tls.Config {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("generate SMTP test key: %v", err)
|
||||
}
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120))
|
||||
if err != nil {
|
||||
t.Fatalf("generate SMTP test serial: %v", err)
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: "127.0.0.1"},
|
||||
DNSNames: []string{"smtp.test.local"},
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
NotBefore: time.Now().Add(-time.Minute),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("generate SMTP test certificate: %v", err)
|
||||
}
|
||||
certificate, err := tls.X509KeyPair(
|
||||
pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
|
||||
pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("load SMTP test certificate: %v", err)
|
||||
}
|
||||
return &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
|
||||
func smtpTestConfig(host string, port int, mode string) config.NotificationConfig {
|
||||
return config.NotificationConfig{
|
||||
SMTPEnabled: true,
|
||||
SMTPHost: host,
|
||||
SMTPPort: port,
|
||||
SMTPUsername: "user",
|
||||
SMTPCredentialRef: "secret://notification/smtp/test",
|
||||
SMTPMode: mode,
|
||||
TimeoutSecs: 2,
|
||||
RetryCount: 0,
|
||||
SenderName: "Scert",
|
||||
SenderEmail: "sender@example.com",
|
||||
Recipients: []string{"receiver@example.com"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPRejectsPlainAuthenticationByDefault(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, false)
|
||||
host, port := server.address()
|
||||
service := New(smtpTestConfig(host, port, "plain"), credentialReaderStub{values: map[string]string{
|
||||
"username": "user",
|
||||
"password": "test-password",
|
||||
}})
|
||||
|
||||
err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"})
|
||||
if err == nil || !strings.Contains(err.Error(), "\u660e\u6587\u8fde\u63a5\u7981\u6b62\u8ba4\u8bc1") {
|
||||
t.Fatalf("plain SMTP authentication should be rejected: %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "test-password") {
|
||||
t.Fatalf("SMTP errors must not expose password: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPSendsUTF8WithAllowedPlainAuthentication(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, false)
|
||||
host, port := server.address()
|
||||
cfg := smtpTestConfig(host, port, "plain")
|
||||
cfg.SMTPAllowPlaintextAuth = true
|
||||
service := New(cfg, credentialReaderStub{values: map[string]string{
|
||||
"username": "user",
|
||||
"password": "test-password",
|
||||
}})
|
||||
|
||||
if err := service.Send(context.Background(), Event{Type: "certificate_renewal", Status: "success", Domain: "example.test"}); err != nil {
|
||||
t.Fatalf("send UTF-8 SMTP notification: %v", err)
|
||||
}
|
||||
message := string(server.message())
|
||||
if !strings.Contains(message, "Subject: =?UTF-8?") || !strings.Contains(message, "example.test") {
|
||||
t.Fatalf("SMTP message was not generated correctly: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPStartTLS(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, true)
|
||||
host, port := server.address()
|
||||
service := New(smtpTestConfig(host, port, "starttls"), credentialReaderStub{values: map[string]string{
|
||||
"username": "user",
|
||||
"password": "test-password",
|
||||
}})
|
||||
service.smtpTLSConfig = server.clientTLSConfig
|
||||
|
||||
if err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}); err != nil {
|
||||
t.Fatalf("send SMTP STARTTLS notification: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPImplicitTLS(t *testing.T) {
|
||||
server := newSMTPTestServer(t, true, false)
|
||||
host, port := server.address()
|
||||
service := New(smtpTestConfig(host, port, "implicit_tls"), credentialReaderStub{values: map[string]string{
|
||||
"username": "user",
|
||||
"password": "test-password",
|
||||
}})
|
||||
service.smtpTLSConfig = server.clientTLSConfig
|
||||
|
||||
if err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}); err != nil {
|
||||
t.Fatalf("send SMTP implicit TLS notification: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPRetriesTemporaryFailure(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, false)
|
||||
server.failMailOnce = true
|
||||
host, port := server.address()
|
||||
cfg := smtpTestConfig(host, port, "plain")
|
||||
cfg.SMTPAllowPlaintextAuth = true
|
||||
cfg.RetryCount = 1
|
||||
cfg.RetryIntervalsSecs = []int{0}
|
||||
service := New(cfg, credentialReaderStub{values: map[string]string{
|
||||
"username": "user",
|
||||
"password": "test-password",
|
||||
}})
|
||||
service.sleep = func(context.Context, time.Duration) error { return nil }
|
||||
|
||||
if err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}); err != nil {
|
||||
t.Fatalf("SMTP retry should recover from temporary failure: %v", err)
|
||||
}
|
||||
server.mu.Lock()
|
||||
connections := server.connections
|
||||
messages := len(server.messages)
|
||||
server.mu.Unlock()
|
||||
if connections < 2 || messages != 1 {
|
||||
t.Fatalf("SMTP retry result is incorrect: connections=%d messages=%d", connections, messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPAuthFailureDoesNotLeakPassword(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, true)
|
||||
server.rejectAuth = true
|
||||
host, port := server.address()
|
||||
service := New(smtpTestConfig(host, port, "starttls"), credentialReaderStub{values: map[string]string{
|
||||
"username": "user",
|
||||
"password": "wrong-password",
|
||||
}})
|
||||
service.smtpTLSConfig = server.clientTLSConfig
|
||||
|
||||
err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"})
|
||||
if err == nil || !strings.Contains(err.Error(), "\u8ba4\u8bc1\u5931\u8d25") {
|
||||
t.Fatalf("SMTP authentication failure should be reported: %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "wrong-password") {
|
||||
t.Fatalf("SMTP authentication errors must not expose password: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPRejectsMissingHost(t *testing.T) {
|
||||
cfg := smtpTestConfig("", 587, "starttls")
|
||||
service := New(cfg, nil)
|
||||
err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"})
|
||||
if err == nil || !strings.Contains(err.Error(), "SMTP \u4e3b\u673a\u4e0d\u80fd\u4e3a\u7a7a") {
|
||||
t.Fatalf("missing SMTP host should return a clear error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPAddressFormatting(t *testing.T) {
|
||||
value := formatSMTPAddress(address{Name: "\u7ba1\u7406\u670d\u52a1", Email: "admin@example.com"})
|
||||
if !strings.Contains(value, "admin@example.com") || !strings.Contains(value, "=?UTF-8?") {
|
||||
t.Fatalf("SMTP address encoding is incorrect: %s", value)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
const (
|
||||
MinLength = 8
|
||||
MaxLength = 128
|
||||
MaxLength = 12
|
||||
)
|
||||
|
||||
func Validate(password, username string) error {
|
||||
|
||||
@@ -13,6 +13,8 @@ func TestValidate(t *testing.T) {
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "合法密码", password: "Password123", username: "admin"},
|
||||
{name: "length at max", password: "Pass12345678", username: "admin"},
|
||||
{name: "length above max", password: "Pass123456789", username: "admin", wantErr: true},
|
||||
{name: "支持中文字符", password: "安全密码2026", username: "admin"},
|
||||
{name: "长度不足", password: "Pass123", username: "admin", wantErr: true},
|
||||
{name: "缺少数字", password: "PasswordOnly", username: "admin", wantErr: true},
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//go:build linux
|
||||
|
||||
package servicehost
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func Install(ctx context.Context, options Options) error {
|
||||
o, err := options.normalized()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runSystemctl(ctx, "enable", o.Name); err != nil {
|
||||
return commandError("注册", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Uninstall(ctx context.Context, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runSystemctl(ctx, "disable", name); err != nil {
|
||||
return commandError("取消注册", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Start(ctx context.Context, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runSystemctl(ctx, "start", name); err != nil {
|
||||
return commandError("启动", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Stop(ctx context.Context, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runSystemctl(ctx, "stop", name); err != nil {
|
||||
return commandError("停止", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runSystemctl(ctx context.Context, args ...string) error {
|
||||
command := exec.CommandContext(ctx, "systemctl", args...)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
return &commandFailure{output: string(output), err: err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type commandFailure struct {
|
||||
output string
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *commandFailure) Error() string {
|
||||
if e.err != nil {
|
||||
return e.output + ": " + e.err.Error()
|
||||
}
|
||||
return e.output
|
||||
}
|
||||
|
||||
func (e *commandFailure) Unwrap() error { return e.err }
|
||||
|
||||
func validateName(name string) error {
|
||||
if name == "" || name == "." || name == ".." {
|
||||
return ErrInvalidName
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var ErrInvalidName = &commandFailure{output: "服务名称无效"}
|
||||
@@ -0,0 +1,65 @@
|
||||
package servicehost
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Name string
|
||||
DisplayName string
|
||||
Description string
|
||||
Executable string
|
||||
ConfigPath string
|
||||
WorkDir string
|
||||
}
|
||||
|
||||
func (o Options) Validate() error {
|
||||
if strings.TrimSpace(o.Name) == "" {
|
||||
return errors.New("服务名称不能为空")
|
||||
}
|
||||
if strings.ContainsAny(o.Name, `/\\`) {
|
||||
return errors.New("服务名称不能包含路径分隔符")
|
||||
}
|
||||
if strings.TrimSpace(o.Executable) == "" {
|
||||
return errors.New("服务程序路径不能为空")
|
||||
}
|
||||
if filepath.Clean(o.Executable) == "." {
|
||||
return errors.New("服务程序路径无效")
|
||||
}
|
||||
if strings.TrimSpace(o.ConfigPath) == "" {
|
||||
return errors.New("配置文件路径不能为空")
|
||||
}
|
||||
if filepath.Clean(o.ConfigPath) == "." {
|
||||
return errors.New("配置文件路径无效")
|
||||
}
|
||||
if strings.TrimSpace(o.WorkDir) == "" {
|
||||
return errors.New("服务工作目录不能为空")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o Options) normalized() (Options, error) {
|
||||
if err := o.Validate(); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
o.Name = strings.TrimSpace(o.Name)
|
||||
o.DisplayName = strings.TrimSpace(o.DisplayName)
|
||||
if o.DisplayName == "" {
|
||||
o.DisplayName = o.Name
|
||||
}
|
||||
o.Description = strings.TrimSpace(o.Description)
|
||||
if o.Description == "" {
|
||||
o.Description = o.DisplayName
|
||||
}
|
||||
o.Executable = filepath.Clean(strings.TrimSpace(o.Executable))
|
||||
o.ConfigPath = filepath.Clean(strings.TrimSpace(o.ConfigPath))
|
||||
o.WorkDir = filepath.Clean(strings.TrimSpace(o.WorkDir))
|
||||
return o, nil
|
||||
}
|
||||
|
||||
func commandError(action string, err error) error {
|
||||
return fmt.Errorf("%s服务失败:%w", action, err)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package servicehost
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOptionsValidate(t *testing.T) {
|
||||
base := Options{
|
||||
Name: "Scert",
|
||||
Executable: filepath.Join("C:", "scert.exe"),
|
||||
ConfigPath: filepath.Join("C:", "scert", "scert.json"),
|
||||
WorkDir: filepath.Join("C:", "scert"),
|
||||
}
|
||||
if err := base.Validate(); err != nil {
|
||||
t.Fatalf("有效服务配置不应失败:%v", err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*Options){
|
||||
"名称为空": func(o *Options) { o.Name = "" },
|
||||
"名称含路径": func(o *Options) { o.Name = "a/b" },
|
||||
"程序路径为空": func(o *Options) { o.Executable = "" },
|
||||
"配置路径为空": func(o *Options) { o.ConfigPath = "" },
|
||||
"工作目录为空": func(o *Options) { o.WorkDir = "" },
|
||||
} {
|
||||
item := base
|
||||
mutate(&item)
|
||||
if err := item.Validate(); err == nil {
|
||||
t.Errorf("%s时应校验失败", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionsNormalizedDefaultsDisplayText(t *testing.T) {
|
||||
item, err := (Options{
|
||||
Name: " Scert ", Executable: "scert.exe", ConfigPath: "scert.json", WorkDir: filepath.Join("C:", "scert"),
|
||||
}).normalized()
|
||||
if err != nil {
|
||||
t.Fatalf("规范化服务配置失败:%v", err)
|
||||
}
|
||||
if item.DisplayName != "Scert" || item.Description != "Scert" {
|
||||
t.Fatalf("服务显示信息默认值错误:%+v", item)
|
||||
}
|
||||
if strings.TrimSpace(item.Executable) == "" {
|
||||
t.Fatal("规范化后程序路径不能为空")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build !windows && !linux
|
||||
|
||||
package servicehost
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var ErrUnsupported = errors.New("当前操作系统不支持系统服务管理")
|
||||
|
||||
func Install(_ context.Context, _ Options) error { return ErrUnsupported }
|
||||
func Uninstall(_ context.Context, _ string) error { return ErrUnsupported }
|
||||
func Start(_ context.Context, _ string) error { return ErrUnsupported }
|
||||
func Stop(_ context.Context, _ string) error { return ErrUnsupported }
|
||||
@@ -0,0 +1,90 @@
|
||||
//go:build windows
|
||||
|
||||
package servicehost
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func Install(ctx context.Context, options Options) error {
|
||||
o, err := options.normalized()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
binPath := strconv.Quote(o.Executable) + " --config " + strconv.Quote(o.ConfigPath) + " serve"
|
||||
if err := runSC(ctx, "create", o.Name, "binPath=", binPath, "start=", "auto", "DisplayName=", o.DisplayName); err != nil {
|
||||
return commandError("安装", err)
|
||||
}
|
||||
if err := runSC(ctx, "description", o.Name, o.Description); err != nil {
|
||||
return commandError("写入描述", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Uninstall(ctx context.Context, name string) error {
|
||||
if name == "" {
|
||||
return commandError("卸载", ErrInvalidName)
|
||||
}
|
||||
if err := runSC(ctx, "stop", name); err != nil {
|
||||
// 服务未运行时允许继续删除。
|
||||
_ = err
|
||||
}
|
||||
if err := runSC(ctx, "delete", name); err != nil {
|
||||
return commandError("卸载", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Start(ctx context.Context, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runSC(ctx, "start", name); err != nil {
|
||||
return commandError("启动", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Stop(ctx context.Context, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runSC(ctx, "stop", name); err != nil {
|
||||
return commandError("停止", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runSC(ctx context.Context, args ...string) error {
|
||||
command := exec.CommandContext(ctx, "sc.exe", args...)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
return &commandFailure{output: string(output), err: err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var ErrInvalidName = &commandFailure{output: "服务名称无效"}
|
||||
|
||||
type commandFailure struct {
|
||||
output string
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *commandFailure) Error() string {
|
||||
if e.err != nil {
|
||||
return e.output + ": " + e.err.Error()
|
||||
}
|
||||
return e.output
|
||||
}
|
||||
|
||||
func (e *commandFailure) Unwrap() error { return e.err }
|
||||
|
||||
func validateName(name string) error {
|
||||
if name == "" || name == "." || name == ".." {
|
||||
return ErrInvalidName
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -16,7 +16,37 @@ import (
|
||||
const dnsVerificationLifetime = 15 * time.Minute
|
||||
|
||||
type DNSCredentialTester interface {
|
||||
Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) error
|
||||
Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) (DNSVerificationReport, error)
|
||||
}
|
||||
|
||||
type DNSVerificationStage struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type DNSVerificationReport struct {
|
||||
RecordName string `json:"record_name"`
|
||||
Stages []DNSVerificationStage `json:"stages"`
|
||||
}
|
||||
|
||||
type DNSVerificationError struct {
|
||||
Report DNSVerificationReport
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *DNSVerificationError) Error() string {
|
||||
if e == nil || e.Err == nil {
|
||||
return "DNS API 在线验证失败"
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e *DNSVerificationError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Err
|
||||
}
|
||||
|
||||
type SecretWriter interface {
|
||||
@@ -33,6 +63,7 @@ type DNSVerificationResult struct {
|
||||
CredentialRef string
|
||||
VerificationToken string
|
||||
ExpiresAt time.Time
|
||||
TestReport DNSVerificationReport
|
||||
}
|
||||
|
||||
type dnsVerificationSession struct {
|
||||
@@ -69,15 +100,20 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
||||
if !domain.IsValidName(testDomain) {
|
||||
return DNSVerificationResult{}, fmt.Errorf("DNS 测试域名格式无效:%s", testDomain)
|
||||
}
|
||||
if err := m.tester.Verify(ctx, providerID, testDomain, input.Credentials); err != nil {
|
||||
return DNSVerificationResult{}, err
|
||||
normalizedCredentials := normalizeCredentials(input.Credentials)
|
||||
testReport, err := m.tester.Verify(ctx, providerID, testDomain, normalizedCredentials)
|
||||
if err != nil {
|
||||
return DNSVerificationResult{TestReport: testReport}, &DNSVerificationError{
|
||||
Report: testReport,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
credentialID, err := secureToken(18)
|
||||
if err != nil {
|
||||
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 凭据引用失败:%w", err)
|
||||
}
|
||||
credentialRef := fmt.Sprintf("secret://dns/%s/%s", providerID, credentialID)
|
||||
if err := m.store.Put(ctx, credentialRef, input.Credentials); err != nil {
|
||||
if err := m.store.Put(ctx, credentialRef, normalizedCredentials); err != nil {
|
||||
return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败:%w", err)
|
||||
}
|
||||
verificationToken, err := secureToken(32)
|
||||
@@ -94,6 +130,7 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
||||
m.mu.Unlock()
|
||||
return DNSVerificationResult{
|
||||
CredentialRef: credentialRef, VerificationToken: verificationToken, ExpiresAt: expiresAt,
|
||||
TestReport: testReport,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -140,6 +177,17 @@ func (m *DNSVerificationManager) clearExpiredLocked(now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeCredentials(credentials map[string]string) map[string]string {
|
||||
if credentials == nil {
|
||||
return nil
|
||||
}
|
||||
normalized := make(map[string]string, len(credentials))
|
||||
for key, value := range credentials {
|
||||
normalized[strings.TrimSpace(key)] = strings.TrimSpace(value)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
func normalizeTestDomain(value string) string {
|
||||
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@ type fakeDNSTester struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeDNSTester) Verify(context.Context, string, string, map[string]string) error {
|
||||
return f.err
|
||||
func (f fakeDNSTester) Verify(context.Context, string, string, map[string]string) (DNSVerificationReport, error) {
|
||||
return DNSVerificationReport{}, f.err
|
||||
}
|
||||
|
||||
type memorySecretWriter struct {
|
||||
@@ -105,3 +105,38 @@ func TestDNSVerificationManagerDoesNotStoreFailedCredential(t *testing.T) {
|
||||
t.Fatal("DNS 测试失败时不应保存凭据")
|
||||
}
|
||||
}
|
||||
|
||||
type recordingDNSTester struct {
|
||||
credentials map[string]string
|
||||
}
|
||||
|
||||
func (f *recordingDNSTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) (DNSVerificationReport, error) {
|
||||
f.credentials = credentials
|
||||
return DNSVerificationReport{}, nil
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerNormalizesCredentialCopyBeforeTestingAndStoring(t *testing.T) {
|
||||
store := &memorySecretWriter{}
|
||||
tester := &recordingDNSTester{}
|
||||
manager := NewDNSVerificationManager(tester, store)
|
||||
inputCredentials := map[string]string{" api_token ": " secret-token "}
|
||||
result, err := manager.Verify(t.Context(), DNSVerificationInput{
|
||||
ProviderID: "cloudflare", TestDomain: "example.com", Credentials: inputCredentials,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DNS 在线验证失败:%v", err)
|
||||
}
|
||||
if tester.credentials["api_token"] != "secret-token" {
|
||||
t.Fatalf("传给测试器的凭据未规范化:%v", tester.credentials)
|
||||
}
|
||||
if _, ok := tester.credentials[" api_token "]; ok {
|
||||
t.Fatal("测试器不应收到带首尾空格的凭据键")
|
||||
}
|
||||
stored := store.values[result.CredentialRef]
|
||||
if stored["api_token"] != "secret-token" {
|
||||
t.Fatalf("保存的凭据未规范化:%v", stored)
|
||||
}
|
||||
if inputCredentials[" api_token "] != " secret-token " {
|
||||
t.Fatal("规范化过程不应修改调用方的原始凭据 Map")
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,14 @@ type Input struct {
|
||||
AdminPassword string
|
||||
ServerPort int
|
||||
EmailHTTPEnabled bool
|
||||
EmailSMTPEnabled bool
|
||||
EmailSMTPHost string
|
||||
EmailSMTPPort int
|
||||
EmailSMTPUsername string
|
||||
EmailSMTPPassword string
|
||||
EmailSMTPCredentialRef string
|
||||
EmailSMTPMode string
|
||||
EmailSMTPAllowPlaintextAuth bool
|
||||
EmailProvider string
|
||||
EmailEndpoint string
|
||||
EmailHTTPPath string
|
||||
@@ -118,7 +126,17 @@ func Apply(cfg *config.Config, input Input) error {
|
||||
cfg.DNS.CredentialRef = strings.TrimSpace(input.DNSCredentialRef)
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Notification.HTTPEnabled = input.EmailHTTPEnabled
|
||||
cfg.Notification.SMTPEnabled = false
|
||||
cfg.Notification.SMTPEnabled = input.EmailSMTPEnabled
|
||||
cfg.Notification.SMTPHost = strings.TrimSpace(input.EmailSMTPHost)
|
||||
if input.EmailSMTPPort != 0 {
|
||||
cfg.Notification.SMTPPort = input.EmailSMTPPort
|
||||
}
|
||||
cfg.Notification.SMTPUsername = strings.TrimSpace(input.EmailSMTPUsername)
|
||||
cfg.Notification.SMTPCredentialRef = strings.TrimSpace(input.EmailSMTPCredentialRef)
|
||||
if strings.TrimSpace(input.EmailSMTPMode) != "" {
|
||||
cfg.Notification.SMTPMode = strings.TrimSpace(input.EmailSMTPMode)
|
||||
}
|
||||
cfg.Notification.SMTPAllowPlaintextAuth = input.EmailSMTPAllowPlaintextAuth
|
||||
cfg.Notification.Provider = strings.TrimSpace(input.EmailProvider)
|
||||
cfg.Notification.Endpoint = strings.TrimSpace(input.EmailEndpoint)
|
||||
if strings.TrimSpace(input.EmailHTTPPath) != "" {
|
||||
@@ -162,6 +180,9 @@ func Apply(cfg *config.Config, input Input) error {
|
||||
cfg.Notification.Recipients = []string{adminEmail}
|
||||
}
|
||||
cfg.SetupReady = true
|
||||
if cfg.Notification.SMTPEnabled && strings.TrimSpace(cfg.Notification.SMTPCredentialRef) == "" {
|
||||
return fmt.Errorf("启用 SMTP 通知后必须配置加密凭据引用")
|
||||
}
|
||||
return cfg.Validate()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHandlerReturnsServiceUnavailableWhenRuntimeIsNil(t *testing.T) {
|
||||
var runtime *Runtime
|
||||
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
response := httptest.NewRecorder()
|
||||
runtime.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("空运行时状态码错误:%d", response.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/app"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
type Runtime struct {
|
||||
core *app.App
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func Open(configPath, baseDir string) (*Runtime, error) {
|
||||
configPath = strings.TrimSpace(configPath)
|
||||
baseDir = strings.TrimSpace(baseDir)
|
||||
if configPath == "" {
|
||||
configPath = filepath.Join(defaultPaths(baseDir).Config, "scert.json")
|
||||
}
|
||||
if baseDir == "" {
|
||||
baseDir = filepath.Dir(filepath.Dir(configPath))
|
||||
}
|
||||
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
cfg = defaultConfig(baseDir)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
core, err := app.NewWithConfigPath(ctx, cfg, configPath)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if core.Renewal != nil && cfg.SetupReady {
|
||||
core.Renewal.Start(ctx)
|
||||
}
|
||||
return &Runtime{core: core, cancel: cancel}, nil
|
||||
}
|
||||
|
||||
func (r *Runtime) Handler() http.Handler {
|
||||
if r == nil || r.core == nil || r.core.HTTP == nil {
|
||||
return http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(writer, "Scert 核心服务未初始化", http.StatusServiceUnavailable)
|
||||
})
|
||||
}
|
||||
return r.core.HTTP.Handler()
|
||||
}
|
||||
|
||||
func (r *Runtime) Close() error {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
if r.cancel != nil {
|
||||
r.cancel()
|
||||
}
|
||||
if r.core != nil {
|
||||
return r.core.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultConfig(baseDir string) config.Config {
|
||||
cfg := config.Default(baseDir)
|
||||
if runtime.GOOS == "linux" && strings.TrimSpace(baseDir) != "" {
|
||||
install := filepath.Join(baseDir, "Scert")
|
||||
cfg.Paths.Install = install
|
||||
cfg.Paths.Certificate = filepath.Join(install, "ssl")
|
||||
cfg.Paths.Config = filepath.Join(install, "config")
|
||||
cfg.Paths.Data = filepath.Join(install, "data")
|
||||
cfg.Paths.Log = filepath.Join(install, "logs")
|
||||
cfg.Paths.Backup = filepath.Join(install, "backups")
|
||||
cfg.Database.DSN = filepath.Join(cfg.Paths.Data, "scert.db")
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func defaultPaths(baseDir string) config.PathsConfig {
|
||||
return defaultConfig(baseDir).Paths
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOpenCreatesUninitializedRuntime(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
runtime, err := Open(filepath.Join(baseDir, "config", "scert.json"), baseDir)
|
||||
if err != nil {
|
||||
t.Fatalf("打开桌面核心服务失败:%v", err)
|
||||
}
|
||||
defer runtime.Close()
|
||||
|
||||
request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1/api/v1/setup/status", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.RemoteAddr = "127.0.0.1:1234"
|
||||
response := newRecordingResponse()
|
||||
runtime.Handler().ServeHTTP(response, request)
|
||||
if response.status != http.StatusOK {
|
||||
t.Fatalf("初始化状态接口状态码错误:%d,响应:%s", response.status, response.body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsInvalidConfiguration(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
configPath := filepath.Join(baseDir, "config", "scert.json")
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(configPath, []byte("{invalid"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Open(configPath, baseDir); err == nil {
|
||||
t.Fatal("无效配置不应打开成功")
|
||||
}
|
||||
}
|
||||
|
||||
type recordingResponse struct {
|
||||
header http.Header
|
||||
status int
|
||||
body string
|
||||
}
|
||||
|
||||
func newRecordingResponse() *recordingResponse {
|
||||
return &recordingResponse{header: make(http.Header)}
|
||||
}
|
||||
|
||||
func (r *recordingResponse) Header() http.Header {
|
||||
return r.header
|
||||
}
|
||||
|
||||
func (r *recordingResponse) WriteHeader(status int) {
|
||||
r.status = status
|
||||
}
|
||||
|
||||
func (r *recordingResponse) Write(body []byte) (int, error) {
|
||||
if r.status == 0 {
|
||||
r.status = http.StatusOK
|
||||
}
|
||||
r.body += string(body)
|
||||
return len(body), nil
|
||||
}
|
||||
Reference in new issue
Block a user