完善证书申请续期与安装初始化流程

This commit is contained in:
xuans committed 2026-08-27 00:31:40 +08:00
1 parent fd8d8608f5
commit 07636abe44
66 files changed
+9470 -165

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
package setup
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"strings"
"sync"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
const dnsVerificationLifetime = 15 * time.Minute
type DNSCredentialTester interface {
Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) error
}
type SecretWriter interface {
Put(ctx context.Context, reference string, value map[string]string) error
}
type DNSVerificationInput struct {
ProviderID string
TestDomain string
Credentials map[string]string
}
type DNSVerificationResult struct {
CredentialRef string
VerificationToken string
ExpiresAt time.Time
}
type dnsVerificationSession struct {
ProviderID string
TestDomain string
CredentialRef string
ExpiresAt time.Time
}
type DNSVerificationManager struct {
mu sync.Mutex
tester DNSCredentialTester
store SecretWriter
now func() time.Time
sessions map[string]dnsVerificationSession
}
func NewDNSVerificationManager(tester DNSCredentialTester, store SecretWriter) *DNSVerificationManager {
return &DNSVerificationManager{
tester: tester, store: store, now: time.Now,
sessions: make(map[string]dnsVerificationSession),
}
}
func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificationInput) (DNSVerificationResult, error) {
if m == nil || m.tester == nil || m.store == nil {
return DNSVerificationResult{}, errors.New("DNS 在线验证服务未初始化")
}
providerID := strings.ToLower(strings.TrimSpace(input.ProviderID))
testDomain := normalizeTestDomain(input.TestDomain)
if providerID == "" {
return DNSVerificationResult{}, errors.New("DNS 服务商不能为空")
}
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
}
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 {
return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败:%w", err)
}
verificationToken, err := secureToken(32)
if err != nil {
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 验证令牌失败:%w", err)
}
expiresAt := m.now().UTC().Add(dnsVerificationLifetime)
m.mu.Lock()
m.clearExpiredLocked(m.now().UTC())
m.sessions[verificationToken] = dnsVerificationSession{
ProviderID: providerID, TestDomain: testDomain,
CredentialRef: credentialRef, ExpiresAt: expiresAt,
}
m.mu.Unlock()
return DNSVerificationResult{
CredentialRef: credentialRef, VerificationToken: verificationToken, ExpiresAt: expiresAt,
}, nil
}
func (m *DNSVerificationManager) Check(token, providerID, credentialRef, testDomain string) error {
return m.validateSession(token, providerID, credentialRef, testDomain, false)
}
func (m *DNSVerificationManager) Consume(token, providerID, credentialRef, testDomain string) error {
return m.validateSession(token, providerID, credentialRef, testDomain, true)
}
func (m *DNSVerificationManager) validateSession(token, providerID, credentialRef, testDomain string, consume bool) error {
if m == nil {
return errors.New("DNS 在线验证服务未初始化")
}
token = strings.TrimSpace(token)
if token == "" {
return errors.New("必须先完成 DNS API 在线验证")
}
now := m.now().UTC()
m.mu.Lock()
defer m.mu.Unlock()
m.clearExpiredLocked(now)
session, ok := m.sessions[token]
if !ok {
return errors.New("DNS 验证令牌无效或已经过期,请重新测试")
}
if session.ProviderID != strings.ToLower(strings.TrimSpace(providerID)) ||
session.CredentialRef != strings.TrimSpace(credentialRef) ||
session.TestDomain != normalizeTestDomain(testDomain) {
return errors.New("DNS 验证结果与当前配置不匹配,请重新测试")
}
if consume {
delete(m.sessions, token)
}
return nil
}
func (m *DNSVerificationManager) clearExpiredLocked(now time.Time) {
for token, session := range m.sessions {
if !session.ExpiresAt.After(now) {
delete(m.sessions, token)
}
}
}
func normalizeTestDomain(value string) string {
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
}
func secureToken(size int) (string, error) {
value := make([]byte, size)
if _, err := rand.Read(value); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(value), nil
}
@@ -0,0 +1,107 @@
package setup
import (
"context"
"errors"
"testing"
"time"
)
type fakeDNSTester struct {
err error
}
func (f fakeDNSTester) Verify(context.Context, string, string, map[string]string) error {
return f.err
}
type memorySecretWriter struct {
values map[string]map[string]string
}
func (m *memorySecretWriter) Put(_ context.Context, reference string, value map[string]string) error {
if m.values == nil {
m.values = map[string]map[string]string{}
}
m.values[reference] = value
return nil
}
func TestDNSVerificationManagerIssuesOneTimeToken(t *testing.T) {
store := &memorySecretWriter{}
manager := NewDNSVerificationManager(fakeDNSTester{}, store)
result, err := manager.Verify(t.Context(), DNSVerificationInput{
ProviderID: "cloudflare", TestDomain: "example.com",
Credentials: map[string]string{"api_token": "secret"},
})
if err != nil {
t.Fatalf("DNS 在线验证失败:%v", err)
}
if result.CredentialRef == "" || result.VerificationToken == "" {
t.Fatalf("DNS 验证结果不完整:%+v", result)
}
if len(store.values) != 1 {
t.Fatalf("DNS 凭据没有写入敏感信息存储:%v", store.values)
}
if err := manager.Check(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err != nil {
t.Fatalf("检查 DNS 验证令牌失败:%v", err)
}
if err := manager.Check(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err != nil {
t.Fatalf("检查 DNS 验证令牌不应消费令牌:%v", err)
}
if err := manager.Consume(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err != nil {
t.Fatalf("消费 DNS 验证令牌失败:%v", err)
}
if err := manager.Check(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err == nil {
t.Fatal("已消费的 DNS 验证令牌不应继续通过检查")
}
if err := manager.Consume(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err == nil {
t.Fatal("DNS 验证令牌只能使用一次")
}
}
func TestDNSVerificationManagerRejectsMismatchedConfiguration(t *testing.T) {
manager := NewDNSVerificationManager(fakeDNSTester{}, &memorySecretWriter{})
result, err := manager.Verify(t.Context(), DNSVerificationInput{
ProviderID: "cloudflare", TestDomain: "example.com",
Credentials: map[string]string{"api_token": "secret"},
})
if err != nil {
t.Fatalf("DNS 在线验证失败:%v", err)
}
if err := manager.Consume(result.VerificationToken, "cloudflare", result.CredentialRef, "other.example.com"); err == nil {
t.Fatal("DNS 验证结果不应允许绑定到其他域名")
}
}
func TestDNSVerificationManagerRejectsExpiredToken(t *testing.T) {
manager := NewDNSVerificationManager(fakeDNSTester{}, &memorySecretWriter{})
now := time.Date(2026, 8, 26, 8, 0, 0, 0, time.UTC)
manager.now = func() time.Time { return now }
result, err := manager.Verify(t.Context(), DNSVerificationInput{
ProviderID: "cloudflare", TestDomain: "example.com",
Credentials: map[string]string{"api_token": "secret"},
})
if err != nil {
t.Fatalf("DNS 在线验证失败:%v", err)
}
now = now.Add(dnsVerificationLifetime + time.Second)
if err := manager.Consume(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err == nil {
t.Fatal("过期 DNS 验证令牌应被拒绝")
}
}
func TestDNSVerificationManagerDoesNotStoreFailedCredential(t *testing.T) {
store := &memorySecretWriter{}
manager := NewDNSVerificationManager(fakeDNSTester{err: errors.New("权限不足")}, store)
_, err := manager.Verify(t.Context(), DNSVerificationInput{
ProviderID: "cloudflare", TestDomain: "example.com",
Credentials: map[string]string{"api_token": "secret"},
})
if err == nil {
t.Fatal("DNS 测试失败时应返回错误")
}
if len(store.values) != 0 {
t.Fatal("DNS 测试失败时不应保存凭据")
}
}
+118
View File
@@ -0,0 +1,118 @@
package setup
import (
"fmt"
"net"
"strings"
"golang.org/x/crypto/bcrypt"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
type Input struct {
AdminUsername string
AdminPassword string
ServerPort int
ResetServicePort int
EmailProvider string
EmailEndpoint string
EmailRecipients []string
DNSProvider string
DNSCredentialRef string
DNSVerified bool
CertificateRoot string
WebHostname string
WebPublicIP string
WebEnabled bool
HTTPSMode string
}
func Apply(cfg *config.Config, input Input) error {
if cfg == nil {
return fmt.Errorf("配置不能为空")
}
if strings.TrimSpace(input.AdminUsername) == "" {
return fmt.Errorf("超级管理员用户名不能为空")
}
if len(input.AdminPassword) < 8 {
return fmt.Errorf("超级管理员密码至少需要 8 个字符")
}
if input.ServerPort < 1 || input.ServerPort > 65535 {
return fmt.Errorf("主服务端口无效:%d", input.ServerPort)
}
if input.ResetServicePort < 1 || input.ResetServicePort > 65535 {
return fmt.Errorf("密码重置服务端口无效:%d", input.ResetServicePort)
}
if input.ServerPort == input.ResetServicePort {
return fmt.Errorf("主服务和密码重置服务不能使用相同端口")
}
if strings.TrimSpace(input.DNSProvider) == "" {
return fmt.Errorf("DNS 服务商不能为空")
}
if strings.TrimSpace(input.DNSCredentialRef) == "" {
return fmt.Errorf("DNS 凭据引用不能为空;明文密钥不会直接写入配置文件")
}
if !input.DNSVerified {
return fmt.Errorf("DNS API 尚未通过验证测试")
}
if strings.TrimSpace(input.WebHostname) == "" && strings.TrimSpace(input.WebPublicIP) == "" {
return fmt.Errorf("Web 页面必须配置域名或公网 IP")
}
if input.WebHostname != "" && input.WebPublicIP != "" {
return fmt.Errorf("Web 页面不能同时配置域名和公网 IP")
}
if input.WebPublicIP != "" && net.ParseIP(input.WebPublicIP) == nil {
return fmt.Errorf("Web 公网 IP 格式无效")
}
if input.HTTPSMode == "" {
input.HTTPSMode = "direct"
}
if input.HTTPSMode != "direct" && input.HTTPSMode != "proxy" {
return fmt.Errorf("HTTPS 模式无效:%s", input.HTTPSMode)
}
if strings.TrimSpace(input.CertificateRoot) == "" {
input.CertificateRoot = cfg.Paths.Certificate
}
hash, err := bcrypt.GenerateFromPassword([]byte(input.AdminPassword), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("生成管理员密码摘要失败:%w", err)
}
cfg.Admin.Username = strings.TrimSpace(input.AdminUsername)
cfg.Admin.PasswordHash = string(hash)
cfg.Admin.ResetServicePort = input.ResetServicePort
cfg.Server.Port = input.ServerPort
cfg.Server.HTTPSMode = input.HTTPSMode
cfg.Web.Enabled = input.WebEnabled
cfg.Web.Hostname = strings.TrimSpace(input.WebHostname)
cfg.Web.PublicIP = strings.TrimSpace(input.WebPublicIP)
cfg.Web.InitReady = true
cfg.Paths.Certificate = strings.TrimSpace(input.CertificateRoot)
cfg.DNS.Provider = strings.TrimSpace(input.DNSProvider)
cfg.DNS.CredentialRef = strings.TrimSpace(input.DNSCredentialRef)
cfg.DNS.VerificationState = "verified"
cfg.Notification.Provider = strings.TrimSpace(input.EmailProvider)
cfg.Notification.Endpoint = strings.TrimSpace(input.EmailEndpoint)
cfg.Notification.Recipients = cleanRecipients(input.EmailRecipients)
cfg.SetupReady = true
return cfg.Validate()
}
func cleanRecipients(values []string) []string {
items := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
for _, part := range strings.Split(value, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if _, ok := seen[part]; ok {
continue
}
seen[part] = struct{}{}
items = append(items, part)
}
}
return items
}
+53
View File
@@ -0,0 +1,53 @@
package setup
import (
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
func TestApplyRequiresVerifiedDNS(t *testing.T) {
cfg := config.Default(t.TempDir())
err := Apply(&cfg, Input{
AdminUsername: "admin", AdminPassword: "password123", ServerPort: 8080, ResetServicePort: 8091,
DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", CertificateRoot: cfg.Paths.Certificate,
WebHostname: "panel.example.com", WebEnabled: true,
})
if err == nil {
t.Fatal("未通过 DNS 验证时不应完成初始化")
}
}
func TestApplyBuildsReadyConfig(t *testing.T) {
cfg := config.Default(t.TempDir())
err := Apply(&cfg, Input{
AdminUsername: "admin", AdminPassword: "password123", ServerPort: 8080, ResetServicePort: 8091,
EmailProvider: "mail-api", EmailEndpoint: "https://mail.example.test/send", EmailRecipients: []string{"a@example.test,b@example.test", "a@example.test"},
DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", DNSVerified: true, CertificateRoot: cfg.Paths.Certificate,
WebHostname: "panel.example.com", WebEnabled: true,
})
if err != nil {
t.Fatalf("初始化配置失败:%v", err)
}
if !cfg.SetupReady || cfg.DNS.VerificationState != "verified" || cfg.Admin.Username != "admin" {
t.Fatalf("初始化状态不正确:%+v", cfg)
}
if len(cfg.Notification.Recipients) != 2 {
t.Fatalf("收件人去重失败:%v", cfg.Notification.Recipients)
}
if cfg.Admin.PasswordHash == "password123" || cfg.Admin.PasswordHash == "" {
t.Fatal("管理员密码不应明文保存")
}
}
func TestApplyRejectsWebIPAsHostnamePair(t *testing.T) {
cfg := config.Default(t.TempDir())
err := Apply(&cfg, Input{
AdminUsername: "admin", AdminPassword: "password123", ServerPort: 8080, ResetServicePort: 8091,
DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", DNSVerified: true,
WebHostname: "panel.example.com", WebPublicIP: "203.0.113.10", WebEnabled: true,
})
if err == nil {
t.Fatal("域名和公网 IP 同时配置时应被拒绝")
}
}