完善阿里云权限与会话回归测试
This commit is contained in:
1 parent
50ece6093b
commit
bbabc35cbf
25 files changed
+502
-250
No files matched your search
@@ -6,10 +6,13 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/dnsverification"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
@@ -24,16 +27,9 @@ type DNSCredentialTester interface {
|
||||
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 DNSVerificationStage = dnsverification.Stage
|
||||
|
||||
type DNSVerificationReport struct {
|
||||
RecordName string `json:"record_name"`
|
||||
Stages []DNSVerificationStage `json:"stages"`
|
||||
}
|
||||
type DNSVerificationReport = dnsverification.Report
|
||||
|
||||
type DNSVerificationError struct {
|
||||
Report DNSVerificationReport
|
||||
@@ -114,6 +110,10 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
||||
return DNSVerificationResult{}, fmt.Errorf("DNS 测试域名格式无效:%s", testDomain)
|
||||
}
|
||||
normalizedCredentials := normalizeCredentials(input.Credentials)
|
||||
cleanedCredentials, err := dnsprovider.ValidateCredentials(providerID, normalizedCredentials)
|
||||
if err != nil {
|
||||
return DNSVerificationResult{}, err
|
||||
}
|
||||
if err := m.reserveVerificationSlot(); err != nil {
|
||||
return DNSVerificationResult{}, err
|
||||
}
|
||||
@@ -123,7 +123,7 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
||||
m.releaseVerificationSlot()
|
||||
}
|
||||
}()
|
||||
testReport, err := m.tester.Verify(ctx, providerID, testDomain, normalizedCredentials)
|
||||
testReport, err := m.tester.Verify(ctx, providerID, testDomain, cleanedCredentials)
|
||||
if err != nil {
|
||||
return DNSVerificationResult{TestReport: testReport}, &DNSVerificationError{
|
||||
Report: testReport,
|
||||
@@ -139,10 +139,11 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
||||
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 凭据引用失败:%w", err)
|
||||
}
|
||||
credentialRef := fmt.Sprintf("secret://dns/%s/%s", providerID, credentialID)
|
||||
if err := m.store.Put(ctx, credentialRef, normalizedCredentials); err != nil {
|
||||
if err := m.store.Put(ctx, credentialRef, cleanedCredentials); err != nil {
|
||||
cleanupErr := m.deleteCredential(credentialRef)
|
||||
if cleanupErr != nil {
|
||||
return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败,且无法确认临时凭据已回收:%w", errors.Join(err, cleanupErr))
|
||||
m.logCleanupFailure()
|
||||
return DNSVerificationResult{}, errors.New("加密保存 DNS 凭据失败,临时凭据回收未确认")
|
||||
}
|
||||
return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败:%w", err)
|
||||
}
|
||||
@@ -250,10 +251,16 @@ func (m *DNSVerificationManager) clearExpiredLocked(now time.Time) []string {
|
||||
|
||||
func (m *DNSVerificationManager) deleteCredentials(references []string) {
|
||||
for _, reference := range references {
|
||||
_ = m.deleteCredential(reference)
|
||||
if err := m.deleteCredential(reference); err != nil {
|
||||
m.logCleanupFailure()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DNSVerificationManager) logCleanupFailure() {
|
||||
log.Print("DNS 临时凭据回收失败")
|
||||
}
|
||||
|
||||
func (m *DNSVerificationManager) deleteCredential(reference string) error {
|
||||
if m == nil || m.deleter == nil || strings.TrimSpace(reference) == "" {
|
||||
return nil
|
||||
|
||||
@@ -3,6 +3,7 @@ package setup
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -11,24 +12,33 @@ type fakeDNSTester struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func TestDNSVerificationBindsScopeToNewCredentialReference(t *testing.T) {
|
||||
func TestDNSVerificationStoresOnlyCurrentAliyunCredentials(t *testing.T) {
|
||||
store := &memorySecretWriter{}
|
||||
manager := NewDNSVerificationManager(fakeDNSTester{}, store)
|
||||
input := DNSVerificationInput{ProviderID: "aliyun", TestDomain: "www.example.com", Credentials: map[string]string{"managed_zones": "example.com", "allowed_domains": "www.example.com"}}
|
||||
input := DNSVerificationInput{ProviderID: "aliyun", TestDomain: "www.example.com", Credentials: map[string]string{
|
||||
"access_key_id": "test-id", "access_key_secret": "test-secret",
|
||||
"managed_zones": "example.com", "allowed_domains": "www.example.com",
|
||||
}}
|
||||
first, err := manager.Verify(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input.Credentials["allowed_domains"] = "*.example.com"
|
||||
if _, ok := store.values[first.CredentialRef]["managed_zones"]; ok {
|
||||
t.Fatal("legacy managed zone must not be persisted as a credential")
|
||||
}
|
||||
if _, ok := store.values[first.CredentialRef]["allowed_domains"]; ok {
|
||||
t.Fatal("legacy allowed domain must not be persisted as a credential")
|
||||
}
|
||||
input.Credentials["access_key_secret"] = "new-secret"
|
||||
second, err := manager.Verify(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.CredentialRef == second.CredentialRef || store.values[first.CredentialRef]["allowed_domains"] != "www.example.com" {
|
||||
t.Fatal("范围变更不能覆盖已验证引用")
|
||||
if first.CredentialRef == second.CredentialRef || store.values[first.CredentialRef]["access_key_secret"] != "test-secret" {
|
||||
t.Fatal("credential changes must not overwrite an already verified reference")
|
||||
}
|
||||
if err := manager.Check(first.VerificationToken, "aliyun", second.CredentialRef, input.TestDomain); err == nil {
|
||||
t.Fatal("旧令牌不能授权新范围")
|
||||
t.Fatal("old token must not authorize a new credential reference")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,15 +47,33 @@ func (f fakeDNSTester) Verify(context.Context, string, string, map[string]string
|
||||
}
|
||||
|
||||
type memorySecretWriter struct {
|
||||
values map[string]map[string]string
|
||||
mu sync.Mutex
|
||||
values map[string]map[string]string
|
||||
deleted []string
|
||||
putErr error
|
||||
deleteErr error
|
||||
}
|
||||
|
||||
func (m *memorySecretWriter) Put(_ context.Context, reference string, value map[string]string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.values == nil {
|
||||
m.values = map[string]map[string]string{}
|
||||
}
|
||||
m.values[reference] = value
|
||||
return nil
|
||||
copy := make(map[string]string, len(value))
|
||||
for key, item := range value {
|
||||
copy[key] = item
|
||||
}
|
||||
m.values[reference] = copy
|
||||
return m.putErr
|
||||
}
|
||||
|
||||
func (m *memorySecretWriter) Delete(_ context.Context, reference string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.deleted = append(m.deleted, reference)
|
||||
delete(m.values, reference)
|
||||
return m.deleteErr
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerIssuesOneTimeToken(t *testing.T) {
|
||||
@@ -96,7 +124,8 @@ func TestDNSVerificationManagerRejectsMismatchedConfiguration(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerRejectsExpiredToken(t *testing.T) {
|
||||
manager := NewDNSVerificationManager(fakeDNSTester{}, &memorySecretWriter{})
|
||||
store := &memorySecretWriter{}
|
||||
manager := NewDNSVerificationManager(fakeDNSTester{}, store)
|
||||
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{
|
||||
@@ -110,6 +139,107 @@ func TestDNSVerificationManagerRejectsExpiredToken(t *testing.T) {
|
||||
if err := manager.Consume(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com"); err == nil {
|
||||
t.Fatal("过期 DNS 验证令牌应被拒绝")
|
||||
}
|
||||
if len(store.deleted) != 1 || store.deleted[0] != result.CredentialRef {
|
||||
t.Fatalf("expired session did not delete temporary credential: %v", store.deleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerDeletesCredentialWhenPutReportsFailure(t *testing.T) {
|
||||
store := &memorySecretWriter{putErr: errors.New("write failed")}
|
||||
manager := NewDNSVerificationManager(fakeDNSTester{}, store)
|
||||
_, err := manager.Verify(t.Context(), DNSVerificationInput{
|
||||
ProviderID: "cloudflare", TestDomain: "example.com",
|
||||
Credentials: map[string]string{"api_token": "secret"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Put failure unexpectedly succeeded")
|
||||
}
|
||||
if len(store.deleted) != 1 {
|
||||
t.Fatalf("Put failure did not trigger credential cleanup: %v", store.deleted)
|
||||
}
|
||||
if len(store.values) != 0 {
|
||||
t.Fatalf("Put failure left temporary credentials stored: %v", store.values)
|
||||
}
|
||||
}
|
||||
|
||||
type countingDNSTester struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
block <-chan struct{}
|
||||
}
|
||||
|
||||
func (f *countingDNSTester) Verify(_ context.Context, _ string, _ string, _ map[string]string) (DNSVerificationReport, error) {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
f.mu.Unlock()
|
||||
if f.block != nil {
|
||||
<-f.block
|
||||
}
|
||||
return DNSVerificationReport{}, nil
|
||||
}
|
||||
|
||||
func (f *countingDNSTester) CallCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.calls
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerRejectsCapacityBeforeTestingOrStoring(t *testing.T) {
|
||||
tester := &countingDNSTester{}
|
||||
store := &memorySecretWriter{}
|
||||
manager := NewDNSVerificationManager(tester, store)
|
||||
manager.sessions = make(map[string]dnsVerificationSession, dnsVerificationSessionCapacity)
|
||||
expiresAt := time.Now().UTC().Add(time.Hour)
|
||||
for index := 0; index < dnsVerificationSessionCapacity; index++ {
|
||||
manager.sessions[string(rune(index))] = dnsVerificationSession{CredentialRef: "secret://existing", ExpiresAt: expiresAt}
|
||||
}
|
||||
_, err := manager.Verify(t.Context(), DNSVerificationInput{
|
||||
ProviderID: "cloudflare", TestDomain: "example.com", Credentials: map[string]string{"api_token": "secret"},
|
||||
})
|
||||
if err == nil || tester.CallCount() != 0 || len(store.values) != 0 {
|
||||
t.Fatalf("capacity rejection must precede testing and storage: err=%v calls=%d values=%v", err, tester.CallCount(), store.values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerRejectsInFlightCapacityBeforeTestingOrStoring(t *testing.T) {
|
||||
tester := &countingDNSTester{}
|
||||
store := &memorySecretWriter{}
|
||||
manager := NewDNSVerificationManager(tester, store)
|
||||
manager.inFlight = dnsVerificationInFlightCapacity
|
||||
_, err := manager.Verify(t.Context(), DNSVerificationInput{
|
||||
ProviderID: "cloudflare", TestDomain: "example.com", Credentials: map[string]string{"api_token": "secret"},
|
||||
})
|
||||
if err == nil || tester.CallCount() != 0 || len(store.values) != 0 {
|
||||
t.Fatalf("in-flight rejection must precede testing and storage: err=%v calls=%d values=%v", err, tester.CallCount(), store.values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerConsumesTokenOnlyOnceUnderConcurrency(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.Fatal(err)
|
||||
}
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
<-start
|
||||
results <- manager.Consume(result.VerificationToken, "cloudflare", result.CredentialRef, "example.com")
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
successes := 0
|
||||
for range 2 {
|
||||
if <-results == nil {
|
||||
successes++
|
||||
}
|
||||
}
|
||||
if successes != 1 {
|
||||
t.Fatalf("concurrent Consume successes = %d; want 1", successes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSVerificationManagerDoesNotStoreFailedCredential(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user