保存执行租约与原子绑定复核前检查点
This commit is contained in:
1 parent
73dba287d9
commit
7a3b78daa3
28 files changed
+1236
-48
No files matched your search
@@ -0,0 +1,82 @@
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
)
|
||||
|
||||
type DNSExecutionLeaseStore interface {
|
||||
AcquireDNSExecutionLease(context.Context, domain.Domain, domain.DNSExecutionIdentity) (domain.DNSExecutionLease, error)
|
||||
ValidateDNSExecutionLease(context.Context, domain.DNSExecutionLease) error
|
||||
ReleaseDNSExecutionLease(context.Context, string) error
|
||||
}
|
||||
|
||||
type dnsExecutionContextKey struct{}
|
||||
|
||||
func WithDNSExecutionIdentity(ctx context.Context, identity domain.DNSExecutionIdentity) context.Context {
|
||||
return context.WithValue(ctx, dnsExecutionContextKey{}, identity)
|
||||
}
|
||||
|
||||
func (s *Service) SetDNSExecutionLeaseStore(store DNSExecutionLeaseStore) {
|
||||
if s != nil {
|
||||
s.dnsLeases = store
|
||||
}
|
||||
}
|
||||
|
||||
// 每次写挑战前再次检查任务和权限;清理只能使用原 Provider 和固定凭据。
|
||||
// 失败的 Present 也可能已写入远端,因此必须等待匹配的 CleanUp 成功才释放引用。
|
||||
type leasedDNSProvider struct {
|
||||
challenge.Provider
|
||||
store DNSExecutionLeaseStore
|
||||
lease domain.DNSExecutionLease
|
||||
mu sync.Mutex
|
||||
pending map[[3]string]bool
|
||||
}
|
||||
|
||||
func (p *leasedDNSProvider) Present(ctx context.Context, name, token, keyAuth string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.store.ValidateDNSExecutionLease(ctx, p.lease); err != nil {
|
||||
return errors.New("DNS 执行授权已失效,未写入挑战记录")
|
||||
}
|
||||
key := [3]string{name, token, keyAuth}
|
||||
p.mu.Lock()
|
||||
p.pending[key] = true
|
||||
p.mu.Unlock()
|
||||
return p.Provider.Present(ctx, name, token, keyAuth)
|
||||
}
|
||||
|
||||
func (p *leasedDNSProvider) CleanUp(ctx context.Context, name, token, keyAuth string) error {
|
||||
// 任务取消不取消必要的挑战清理;清理自身仍有明确的时间上限。
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute)
|
||||
defer cancel()
|
||||
if err := p.Provider.CleanUp(cleanupCtx, name, token, keyAuth); err != nil {
|
||||
return err
|
||||
}
|
||||
p.mu.Lock()
|
||||
delete(p.pending, [3]string{name, token, keyAuth})
|
||||
p.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *leasedDNSProvider) clean() bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return len(p.pending) == 0
|
||||
}
|
||||
|
||||
// 不覆盖服务商自己的传播等待参数。
|
||||
func (p *leasedDNSProvider) Timeout() (time.Duration, time.Duration) {
|
||||
if timed, ok := p.Provider.(interface {
|
||||
Timeout() (time.Duration, time.Duration)
|
||||
}); ok {
|
||||
return timed.Timeout()
|
||||
}
|
||||
return time.Minute, 2 * time.Second
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
)
|
||||
|
||||
type executionLeaseStub struct {
|
||||
lease domain.DNSExecutionLease
|
||||
acquireErr, validateErr, releaseErr error
|
||||
acquired, validated, released int
|
||||
}
|
||||
|
||||
func (s *executionLeaseStub) AcquireDNSExecutionLease(_ context.Context, _ domain.Domain, identity domain.DNSExecutionIdentity) (domain.DNSExecutionLease, error) {
|
||||
s.acquired++
|
||||
s.lease.Identity = identity
|
||||
return s.lease, s.acquireErr
|
||||
}
|
||||
func (s *executionLeaseStub) ValidateDNSExecutionLease(_ context.Context, lease domain.DNSExecutionLease) error {
|
||||
s.validated++
|
||||
if lease.CredentialRef != s.lease.CredentialRef {
|
||||
return errors.New("秘密引用被替换")
|
||||
}
|
||||
return s.validateErr
|
||||
}
|
||||
func (s *executionLeaseStub) ReleaseDNSExecutionLease(ctx context.Context, _ string) error {
|
||||
s.released++
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.releaseErr
|
||||
}
|
||||
|
||||
type executionCredentials struct {
|
||||
reference string
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *executionCredentials) Get(_ context.Context, reference string) (map[string]string, error) {
|
||||
r.reference = reference
|
||||
return map[string]string{"api_token": "independent-test-only"}, r.err
|
||||
}
|
||||
|
||||
type executionProvider struct {
|
||||
presented, cleaned int
|
||||
presentErr, cleanErr error
|
||||
}
|
||||
|
||||
func (p *executionProvider) Present(context.Context, string, string, string) error {
|
||||
p.presented++
|
||||
return p.presentErr
|
||||
}
|
||||
func (p *executionProvider) CleanUp(ctx context.Context, _, _, _ string) error {
|
||||
p.cleaned++
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.cleanErr
|
||||
}
|
||||
func (p *executionProvider) Timeout() (time.Duration, time.Duration) {
|
||||
return 3 * time.Minute, 4 * time.Second
|
||||
}
|
||||
|
||||
type executionFactory struct {
|
||||
provider challenge.Provider
|
||||
id string
|
||||
}
|
||||
|
||||
func (f *executionFactory) Create(id string, _ map[string]string) (challenge.Provider, error) {
|
||||
f.id = id
|
||||
return f.provider, nil
|
||||
}
|
||||
|
||||
type executionIssuer struct {
|
||||
run func(context.Context) (Resource, error)
|
||||
}
|
||||
|
||||
func (i executionIssuer) Obtain(ctx context.Context, _ ObtainRequest) (Resource, error) {
|
||||
return i.run(ctx)
|
||||
}
|
||||
|
||||
func TestIndependentDNSExecutionLifecycle(t *testing.T) {
|
||||
for _, scenario := range []string{"success", "acquire-failed", "validate-failed", "credential-failed", "present-failed", "cleanup-failed", "missing-cleanup", "release-failed", "cancelled", "revoked-before-present", "revoked-before-cleanup"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
cfg := certificateTestConfig(t.TempDir())
|
||||
cfg.DNS.Provider, cfg.DNS.CredentialRef, cfg.DNS.VerificationState = "aliyun", "secret://dns/system-must-not-read", "unverified"
|
||||
item, err := domain.NewDomain("lease.example.test", domain.CertificateSingle, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item.DNSAccountID, item.DNSBindingID, item.DNSProvider = "account", "binding", "cloudflare"
|
||||
repo := &serviceRepository{item: item}
|
||||
store := &executionLeaseStub{lease: domain.DNSExecutionLease{ID: "lease", DomainID: item.ID, AccountID: "account", BindingID: "binding", Provider: "cloudflare", CredentialRef: "secret://dns/independent", Revision: 2}}
|
||||
reader := &executionCredentials{}
|
||||
provider := &executionProvider{}
|
||||
factory := &executionFactory{provider: provider}
|
||||
service := NewService(cfg, repo, reader, factory, serviceAccounts{})
|
||||
service.SetDNSExecutionLeaseStore(store)
|
||||
resource := testResourceForDomains(t, []string{item.Name})
|
||||
service.acmeRoots = testResourceRoots(t, resource)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
ctx = WithDNSExecutionIdentity(ctx, domain.DNSExecutionIdentity{TaskID: "task", AttemptID: "attempt", AttemptNumber: 2})
|
||||
failure := errors.New("测试失败")
|
||||
switch scenario {
|
||||
case "acquire-failed":
|
||||
store.acquireErr = failure
|
||||
case "validate-failed":
|
||||
store.validateErr = failure
|
||||
case "credential-failed":
|
||||
reader.err = failure
|
||||
case "present-failed":
|
||||
provider.presentErr = failure
|
||||
case "cleanup-failed":
|
||||
provider.cleanErr = failure
|
||||
case "release-failed":
|
||||
store.releaseErr = failure
|
||||
}
|
||||
service.newIssuer = func(_ *AccountUser, challengeProvider challenge.Provider, _ string) Issuer {
|
||||
return executionIssuer{run: func(ctx context.Context) (Resource, error) {
|
||||
if scenario == "revoked-before-present" {
|
||||
store.validateErr = failure
|
||||
}
|
||||
if timeout, interval := challengeProvider.(challenge.ProviderTimeout).Timeout(); timeout != 3*time.Minute || interval != 4*time.Second {
|
||||
t.Fatal("服务商传播参数丢失")
|
||||
}
|
||||
if err := challengeProvider.Present(ctx, item.Name, "token", "auth"); err != nil {
|
||||
return Resource{}, err
|
||||
}
|
||||
if scenario == "missing-cleanup" {
|
||||
return resource, nil
|
||||
}
|
||||
if scenario == "revoked-before-cleanup" {
|
||||
store.validateErr = failure
|
||||
}
|
||||
if scenario == "cancelled" {
|
||||
cancel()
|
||||
}
|
||||
if err := challengeProvider.CleanUp(ctx, item.Name, "token", "auth"); err != nil {
|
||||
return Resource{}, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Resource{}, err
|
||||
}
|
||||
return resource, nil
|
||||
}}
|
||||
}
|
||||
_, err = service.Issue(ctx, item.ID)
|
||||
wantSuccess := scenario == "success" || scenario == "revoked-before-cleanup"
|
||||
if (err == nil) != wantSuccess {
|
||||
t.Fatalf("场景结果不符:%v", err)
|
||||
}
|
||||
if store.acquired != 1 {
|
||||
t.Fatal("未获取真实执行租约")
|
||||
}
|
||||
if reader.reference == cfg.DNS.CredentialRef || (factory.id != "" && factory.id != "cloudflare") {
|
||||
t.Fatal("独立账户回退到系统配置")
|
||||
}
|
||||
if scenario != "acquire-failed" && scenario != "validate-failed" && reader.reference != "secret://dns/independent" {
|
||||
t.Fatal("未读取固定凭据")
|
||||
}
|
||||
retained := scenario == "present-failed" || scenario == "cleanup-failed" || scenario == "missing-cleanup" || scenario == "acquire-failed"
|
||||
if (store.released == 0) != retained {
|
||||
t.Fatalf("不确定挑战清理时释放引用,或正常收尾未释放:%d", store.released)
|
||||
}
|
||||
if scenario == "revoked-before-present" && provider.presented != 0 {
|
||||
t.Fatal("撤权后仍调用 DNS 服务商")
|
||||
}
|
||||
if scenario == "cancelled" && provider.cleaned != 1 {
|
||||
t.Fatal("取消不应跳过清理")
|
||||
}
|
||||
if scenario == "release-failed" && (err == nil || !strings.Contains(err.Error(), "租约释放失败")) {
|
||||
t.Fatal("释放失败未上报")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndependentDNSExecutionRequiresTaskContext(t *testing.T) {
|
||||
item, _ := domain.NewDomain("lease.example.test", domain.CertificateSingle, nil)
|
||||
item.DNSAccountID, item.DNSBindingID = "account", "binding"
|
||||
repo := &serviceRepository{item: item}
|
||||
service := NewService(certificateTestConfig(t.TempDir()), repo, serviceCredentials{}, serviceProviderFactory{}, serviceAccounts{})
|
||||
store := &executionLeaseStub{}
|
||||
service.SetDNSExecutionLeaseStore(store)
|
||||
if _, err := service.Issue(t.Context(), item.ID); err == nil {
|
||||
t.Fatal("不能在任务之外使用独立凭据")
|
||||
}
|
||||
if store.acquired != 0 || repo.updateCalls != 0 {
|
||||
t.Fatal("拒绝前不应产生副作用")
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,7 @@ type Service struct {
|
||||
preferredChain string
|
||||
acmeRoots *x509.CertPool
|
||||
httpChallenges *httpchallenge.Store
|
||||
dnsLeases DNSExecutionLeaseStore
|
||||
}
|
||||
|
||||
func (s *Service) SetHTTPChallenges(store *httpchallenge.Store) {
|
||||
@@ -138,7 +139,7 @@ func NewService(cfg config.Config, repository DomainStateRepository, credentials
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, error) {
|
||||
func (s *Service) Issue(ctx context.Context, domainID string) (result IssueResult, returnErr error) {
|
||||
if s == nil || s.repository == nil || s.accounts == nil || s.newIssuer == nil {
|
||||
return IssueResult{}, errors.New("证书申请服务未初始化")
|
||||
}
|
||||
@@ -150,8 +151,8 @@ func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, erro
|
||||
if err != nil {
|
||||
return IssueResult{}, fmt.Errorf("读取域名配置失败:%w", err)
|
||||
}
|
||||
// 独立账户执行租约接入前禁止退回系统账户,避免配置与实际用证账户不一致。
|
||||
if item.DNSAccountID != "" || item.DNSBindingID != "" {
|
||||
independent := item.DNSAccountID != "" || item.DNSBindingID != ""
|
||||
if independent && s.dnsLeases == nil {
|
||||
return IssueResult{}, errors.New("独立 DNS 账户执行租约尚未就绪,拒绝使用系统凭据替代")
|
||||
}
|
||||
domains, err := requestedDomains(item)
|
||||
@@ -166,8 +167,38 @@ func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, erro
|
||||
return IssueResult{}, fmt.Errorf("签发配置权限校验失败:%w", err)
|
||||
}
|
||||
providerID := ""
|
||||
credentialRef := s.config.DNS.CredentialRef
|
||||
var dnsLease domain.DNSExecutionLease
|
||||
var guardedProvider *leasedDNSProvider
|
||||
var lease *httpchallenge.Lease
|
||||
if challengeType == domain.ChallengeHTTP01 {
|
||||
if independent {
|
||||
if challengeType != domain.ChallengeDNS01 || s.credentials == nil || s.providers == nil {
|
||||
return IssueResult{}, errors.New("独立 DNS 账户配置无效")
|
||||
}
|
||||
identity, ok := ctx.Value(dnsExecutionContextKey{}).(domain.DNSExecutionIdentity)
|
||||
if !ok {
|
||||
return IssueResult{}, errors.New("独立 DNS 账户缺少真实任务执行身份")
|
||||
}
|
||||
dnsLease, err = s.dnsLeases.AcquireDNSExecutionLease(ctx, item, identity)
|
||||
if err != nil {
|
||||
return IssueResult{}, errors.New("获取独立 DNS 账户执行租约失败,未使用系统凭据")
|
||||
}
|
||||
defer func() {
|
||||
if guardedProvider != nil && !guardedProvider.clean() {
|
||||
returnErr = errors.Join(returnErr, errors.New("DNS 挑战清理尚未确认,执行租约及原凭据引用已保留"))
|
||||
return
|
||||
}
|
||||
finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.dnsLeases.ReleaseDNSExecutionLease(finishCtx, dnsLease.ID); err != nil {
|
||||
returnErr = errors.Join(returnErr, errors.New("DNS 执行租约释放失败,原凭据引用已保留"))
|
||||
}
|
||||
}()
|
||||
providerID, credentialRef = dnsLease.Provider, dnsLease.CredentialRef
|
||||
if err := dnsprovider.ValidateAliyunTargetDomains(providerID, domains); err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
} else if challengeType == domain.ChallengeHTTP01 {
|
||||
lease, err = s.httpChallenges.NewLease(ctx, domains)
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
@@ -197,7 +228,12 @@ func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, erro
|
||||
return fail(err)
|
||||
}
|
||||
} else {
|
||||
credentials, err = s.credentials.Get(ctx, s.config.DNS.CredentialRef)
|
||||
if independent {
|
||||
if err := s.dnsLeases.ValidateDNSExecutionLease(ctx, dnsLease); err != nil {
|
||||
return fail(errors.New("DNS 执行授权已失效,未读取凭据"))
|
||||
}
|
||||
}
|
||||
credentials, err = s.credentials.Get(ctx, credentialRef)
|
||||
if err != nil {
|
||||
return fail(fmt.Errorf("读取 DNS 凭据失败:%w", err))
|
||||
}
|
||||
@@ -214,6 +250,10 @@ func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, erro
|
||||
if err != nil {
|
||||
return fail(fmt.Errorf("创建 DNS Provider 失败:%w", err))
|
||||
}
|
||||
if independent {
|
||||
guardedProvider = &leasedDNSProvider{Provider: provider, store: s.dnsLeases, lease: dnsLease, pending: make(map[[3]string]bool)}
|
||||
provider = guardedProvider
|
||||
}
|
||||
}
|
||||
email := strings.TrimSpace(s.config.ACME.AccountEmail)
|
||||
if email == "" && len(s.config.Notification.Recipients) > 0 {
|
||||
|
||||
Reference in new issue
Block a user