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

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

No files matched your search

+30 -16
View File
@@ -28,11 +28,30 @@ func (u *AccountUser) GetRegistration() *acme.ExtendedAccount { return u.Registr
func (u *AccountUser) GetPrivateKey() crypto.Signer { return u.PrivateKey }
type LegoIssuer struct {
User *AccountUser
Provider challenge.Provider
Environment string
HTTPClient *http.Client
Now func() time.Time
User *AccountUser
Provider challenge.Provider
Environment string
PropagationTimeout time.Duration
PropagationInterval time.Duration
HTTPClient *http.Client
Now func() time.Time
}
type propagationProvider struct {
challenge.Provider
timeout time.Duration
interval time.Duration
}
func (p propagationProvider) Timeout() (time.Duration, time.Duration) {
return p.timeout, p.interval
}
func withPropagationSettings(provider challenge.Provider, timeout, interval time.Duration) challenge.Provider {
if provider == nil || timeout <= 0 || interval <= 0 || interval > timeout {
return provider
}
return propagationProvider{Provider: provider, timeout: timeout, interval: interval}
}
func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resource, error) {
@@ -66,7 +85,8 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
if err != nil {
return Resource{}, fmt.Errorf("创建 ACME 客户端失败:%w", err)
}
if err := client.Challenge.SetDNS01Provider(i.Provider); err != nil {
provider := withPropagationSettings(i.Provider, i.PropagationTimeout, i.PropagationInterval)
if err := client.Challenge.SetDNS01Provider(provider); err != nil {
return Resource{}, fmt.Errorf("配置 DNS-01 验证失败:%w", err)
}
if i.User.Registration == nil {
@@ -77,11 +97,14 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
i.User.Registration = account
}
issued, err := client.Certificate.Obtain(ctx, legoCertificate.ObtainRequest{
Domains: domains, EmailAddresses: nonEmptyEmail(request.AccountEmail, i.User.Email),
Domains: domains,
KeyType: certcrypto.RSA2048, Bundle: true,
PreferredChain: request.PreferredChain,
})
if err != nil {
if i.PropagationTimeout > 0 && i.PropagationInterval > 0 && i.PropagationInterval <= i.PropagationTimeout {
return Resource{}, fmt.Errorf("申请证书失败(DNS 传播等待时间 %s,检测间隔 %s):%w", i.PropagationTimeout, i.PropagationInterval, err)
}
return Resource{}, fmt.Errorf("申请证书失败:%w", err)
}
resource := Resource{
@@ -93,12 +116,3 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc
}
return ValidateResource(resource)
}
func nonEmptyEmail(values ...string) []string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return []string{strings.TrimSpace(value)}
}
}
return nil
}
+74
View File
@@ -0,0 +1,74 @@
package certificate
import (
"context"
"testing"
"time"
"github.com/go-acme/lego/v5/challenge"
)
type propagationTestProvider struct {
present bool
cleanup bool
}
func (p *propagationTestProvider) Present(context.Context, string, string, string) error {
p.present = true
return nil
}
func (p *propagationTestProvider) CleanUp(context.Context, string, string, string) error {
p.cleanup = true
return nil
}
func TestWithPropagationSettingsProvidesConfiguredTimeout(t *testing.T) {
base := &propagationTestProvider{}
timeout := 15 * time.Minute
interval := 10 * time.Second
wrapped := withPropagationSettings(base, timeout, interval)
provider, ok := wrapped.(challenge.ProviderTimeout)
if !ok {
t.Fatal("DNS Provider 未实现传播等待配置接口")
}
actualTimeout, actualInterval := provider.Timeout()
if actualTimeout != timeout || actualInterval != interval {
t.Fatalf("DNS 传播参数不正确:timeout=%s interval=%s", actualTimeout, actualInterval)
}
if err := wrapped.Present(context.Background(), "example.com", "token", "key-auth"); err != nil {
t.Fatalf("Provider Present 转发失败:%v", err)
}
if err := wrapped.CleanUp(context.Background(), "example.com", "token", "key-auth"); err != nil {
t.Fatalf("Provider CleanUp 转发失败:%v", err)
}
if !base.present || !base.cleanup {
t.Fatal("包装器未正确转发 Provider 操作")
}
}
func TestWithPropagationSettingsPreservesProviderForInvalidValues(t *testing.T) {
base := &propagationTestProvider{}
cases := []struct {
name string
timeout time.Duration
interval time.Duration
}{
{name: "zero timeout", timeout: 0, interval: time.Second},
{name: "zero interval", timeout: time.Minute, interval: 0},
{name: "interval exceeds timeout", timeout: time.Second, interval: time.Minute},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
if got := withPropagationSettings(base, item.timeout, item.interval); got != base {
t.Fatal("无效 DNS 传播参数不应替换原 Provider")
}
})
}
}
func TestWithPropagationSettingsPreservesNilProvider(t *testing.T) {
if got := withPropagationSettings(nil, time.Minute, time.Second); got != nil {
t.Fatal("空 Provider 应保持为空")
}
}
+7 -1
View File
@@ -75,7 +75,13 @@ func NewService(cfg config.Config, repository DomainStateRepository, credentials
config: cfg, repository: repository, credentials: credentials, providers: providers, accounts: accounts,
store: FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup},
newIssuer: func(user *AccountUser, provider challenge.Provider, environment string) Issuer {
return &LegoIssuer{User: user, Provider: provider, Environment: environment}
return &LegoIssuer{
User: user,
Provider: provider,
Environment: environment,
PropagationTimeout: time.Duration(cfg.ACME.PropagationTimeoutSecs) * time.Second,
PropagationInterval: time.Duration(cfg.ACME.PropagationPollingIntervalSecs) * time.Second,
}
},
}
}
@@ -18,6 +18,7 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
)
type serviceRepository struct {
@@ -53,6 +54,17 @@ func (serviceProviderFactory) Create(string, map[string]string) (challenge.Provi
return serviceProvider{}, nil
}
type recordingProviderFactory struct {
providerID string
credentials map[string]string
}
func (f *recordingProviderFactory) Create(providerID string, credentials map[string]string) (challenge.Provider, error) {
f.providerID = providerID
f.credentials = credentials
return serviceProvider{}, nil
}
type serviceAccounts struct{}
func (serviceAccounts) LoadOrCreate(context.Context, string, string) (*AccountUser, error) {
@@ -262,3 +274,49 @@ func TestServiceIssuesSetupCertificateWithTypedLayout(t *testing.T) {
}
}
}
func TestServiceDecryptsCredentialReferenceBeforeCreatingProvider(t *testing.T) {
root := t.TempDir()
cfg := certificateTestConfig(root)
store, err := secretstore.Open(cfg.Paths.Config)
if err != nil {
t.Fatalf("打开敏感信息存储失败:%v", err)
}
credentialRef := "secret://dns/cloudflare/service-test"
if err := store.Put(context.Background(), credentialRef, map[string]string{
"api_token": "test-dns-token",
}); err != nil {
t.Fatalf("保存测试 DNS 凭据失败:%v", err)
}
cfg.DNS.CredentialRef = credentialRef
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare")
if err != nil {
t.Fatal(err)
}
repository := &serviceRepository{item: item}
factory := &recordingProviderFactory{}
issuer := &serviceIssuer{resource: testResource(t, "example.com")}
service := NewService(cfg, repository, store, factory, serviceAccounts{})
service.newIssuer = func(*AccountUser, challenge.Provider, string) Issuer { return issuer }
if _, err := service.Issue(context.Background(), item.ID); err != nil {
t.Fatalf("使用加密凭据引用申请证书失败:%v", err)
}
if factory.providerID != "cloudflare" || factory.credentials["api_token"] != "test-dns-token" {
t.Fatalf("创建 DNS Provider 时未正确解密凭据:provider=%q credentials=%v", factory.providerID, factory.credentials)
}
}
func TestNewServiceInjectsPropagationSettings(t *testing.T) {
cfg := certificateTestConfig(t.TempDir())
cfg.ACME.PropagationTimeoutSecs = 1200
cfg.ACME.PropagationPollingIntervalSecs = 15
service := NewService(cfg, nil, nil, nil, nil)
issuer, ok := service.newIssuer(&AccountUser{}, serviceProvider{}, "staging").(*LegoIssuer)
if !ok {
t.Fatal("创建的 Issuer 类型不正确")
}
if issuer.PropagationTimeout != 1200*time.Second || issuer.PropagationInterval != 15*time.Second {
t.Fatalf("DNS 传播参数注入不正确:timeout=%s interval=%s", issuer.PropagationTimeout, issuer.PropagationInterval)
}
}