修复阿里云精确查询并补偿授权探测响应丢失
This commit is contained in:
1 parent
7d059e0196
commit
0bb427d5f8
8 files changed
+266
-3
No files matched your search
@@ -298,6 +298,10 @@ func dereferenceString(value *string) string {
|
||||
|
||||
// DiagnoseAliyunError 对阿里云 API 返回的错误进行分类并提供明确的修复指导。
|
||||
func DiagnoseAliyunError(err error, domainName string) string {
|
||||
var reconciliation *aliyunReconciliationError
|
||||
if errors.As(err, &reconciliation) {
|
||||
return fmt.Sprintf("阿里云授权探测创建响应异常,临时 TXT 记录 %s 的清理尚未确认,请核对该记录;本次权限验证未通过", reconciliation.recordName)
|
||||
}
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ func (a aliyunRecords) Add(ctx context.Context, zone, rr, value string) (string,
|
||||
SetType("TXT").SetValue(value).SetTTL(aliyunAuthorizationTTL)
|
||||
response, err := client.AddDomainRecordWithContext(ctx, a.client, request, &dara.RuntimeOptions{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", a.reconcileAuthorizationAdd(ctx, zone, rr, value, err)
|
||||
}
|
||||
if response == nil || response.Body == nil || response.Body.RecordId == nil || strings.TrimSpace(*response.Body.RecordId) == "" {
|
||||
return "", errors.New("阿里云未返回新增记录 ID,状态未确认,请人工核对本次记录")
|
||||
@@ -56,7 +56,7 @@ func (a aliyunRecords) Describe(ctx context.Context, zone, rr, recordID string)
|
||||
ctx,
|
||||
a.client,
|
||||
new(client.DescribeDomainRecordsRequest).SetDomainName(zone).SetRRKeyWord(rr).
|
||||
SetTypeKeyWord("TXT").SetSearchMode("EXACT").SetPageNumber(1).SetPageSize(100),
|
||||
SetTypeKeyWord("TXT").SetSearchMode("COMBINATION").SetPageNumber(1).SetPageSize(100),
|
||||
&dara.RuntimeOptions{},
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/alibabacloud-go/tea/dara"
|
||||
"github.com/go-acme/alidns-20150109/v5/client"
|
||||
)
|
||||
|
||||
const aliyunReconciliationTimeout = 10 * time.Second
|
||||
|
||||
type aliyunReconciliationError struct {
|
||||
error
|
||||
recordName string
|
||||
}
|
||||
|
||||
// 创建响应丢失不等于云端未写入;仅核对本次随机授权探测记录,不重试创建。
|
||||
// ACME 固定主机记录可能被其他挑战共享,不能使用此补偿入口删除。
|
||||
func (a aliyunRecords) reconcileAuthorizationAdd(ctx context.Context, zone, rr, value string, cause error) error {
|
||||
var networkError net.Error
|
||||
uncertain := errors.Is(cause, context.DeadlineExceeded) || errors.Is(cause, context.Canceled) ||
|
||||
errors.Is(cause, io.EOF) || errors.Is(cause, io.ErrUnexpectedEOF) || errors.As(cause, &networkError)
|
||||
if !uncertain || !strings.HasPrefix(rr, "_scert-authorization-") {
|
||||
return cause
|
||||
}
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), aliyunReconciliationTimeout)
|
||||
defer cancel()
|
||||
err := a.cleanupUncertainAuthorizationRecord(cleanupCtx, zone, rr, value)
|
||||
if err != nil {
|
||||
err = &aliyunReconciliationError{error: err, recordName: rr + "." + zone}
|
||||
return errors.Join(cause, fmt.Errorf("授权探测创建结果不确定,记录 %s.%s 需要核对:%w", rr, zone, err))
|
||||
}
|
||||
// 即使补偿成功,本次权限验证仍然失败,不能将网络异常转成已授权。
|
||||
return cause
|
||||
}
|
||||
|
||||
func (a aliyunRecords) cleanupUncertainAuthorizationRecord(ctx context.Context, zone, rr, value string) error {
|
||||
response, err := client.DescribeDomainRecordsWithContext(ctx, a.client,
|
||||
new(client.DescribeDomainRecordsRequest).SetDomainName(zone).SetRRKeyWord(rr).
|
||||
SetTypeKeyWord("TXT").SetValueKeyWord(value).SetSearchMode("COMBINATION").
|
||||
SetPageNumber(1).SetPageSize(100), &dara.RuntimeOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if response == nil || response.Body == nil || response.Body.DomainRecords == nil || response.Body.TotalCount == nil {
|
||||
return errors.New("云端未返回完整的记录核对结果")
|
||||
}
|
||||
records := response.Body.DomainRecords.Record
|
||||
if *response.Body.TotalCount != int64(len(records)) || len(records) > 1 {
|
||||
return errors.New("核对结果不唯一或分页不完整,已拒绝删除")
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return errors.New("暂未发现记录,不能排除云端延迟写入,请稍后核对")
|
||||
}
|
||||
record := records[0]
|
||||
if record == nil {
|
||||
return errors.New("核对返回空记录,已拒绝删除")
|
||||
}
|
||||
info := aliyunRecordInfo{
|
||||
RecordID: dereferenceString(record.RecordId), DomainName: dereferenceString(record.DomainName),
|
||||
RR: dereferenceString(record.RR), Type: dereferenceString(record.Type), Value: dereferenceString(record.Value),
|
||||
}
|
||||
if strings.TrimSpace(info.RecordID) == "" || !matchesAliyunAuthorizationRecord(info, info.RecordID, zone, rr, value) {
|
||||
return errors.New("核对记录与本次随机授权探测不一致,已拒绝删除")
|
||||
}
|
||||
return a.Delete(ctx, info.RecordID)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
||||
"github.com/alibabacloud-go/tea/dara"
|
||||
"github.com/go-acme/alidns-20150109/v5/client"
|
||||
)
|
||||
|
||||
func TestAliyunAuthorizationLostAddResponse(t *testing.T) {
|
||||
for _, scenario := range []string{"cleanup", "wrong_value", "wrong_zone", "wrong_rr", "wrong_type", "empty_id", "multiple", "missing", "incomplete", "query_error", "delete_error"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var actions []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
action := r.Header.Get("x-acs-action")
|
||||
mu.Lock()
|
||||
actions = append(actions, action)
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch action {
|
||||
case "AddDomainRecord":
|
||||
// 模拟云端已经接受写入,但创建响应在传输中丢失。
|
||||
connection, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
_ = connection.Close()
|
||||
case "DescribeDomainRecords":
|
||||
for key, expected := range map[string]string{
|
||||
"DomainName": "example.com", "RRKeyWord": "_scert-authorization-unique.web",
|
||||
"TypeKeyWord": "TXT", "ValueKeyWord": "unique-proof", "SearchMode": "COMBINATION",
|
||||
} {
|
||||
if r.Form.Get(key) != expected {
|
||||
t.Errorf("补偿查询未限定本次记录:%s", key)
|
||||
}
|
||||
}
|
||||
if scenario == "query_error" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"Code":"Forbidden.RAM","Message":"denied"}`))
|
||||
return
|
||||
}
|
||||
record := map[string]string{"RecordId": "owned-id", "DomainName": "example.com", "RR": "_scert-authorization-unique.web", "Type": "TXT", "Value": "unique-proof"}
|
||||
switch scenario {
|
||||
case "wrong_value":
|
||||
record["Value"] = "other-proof"
|
||||
case "wrong_zone":
|
||||
record["DomainName"] = "other.com"
|
||||
case "wrong_rr":
|
||||
record["RR"] = "other"
|
||||
case "wrong_type":
|
||||
record["Type"] = "A"
|
||||
case "empty_id":
|
||||
record["RecordId"] = ""
|
||||
}
|
||||
records := []map[string]string{record}
|
||||
if scenario == "multiple" {
|
||||
records = append(records, record)
|
||||
} else if scenario == "missing" {
|
||||
records = nil
|
||||
}
|
||||
total := len(records)
|
||||
if scenario == "incomplete" {
|
||||
total++
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"TotalCount": total, "DomainRecords": map[string]any{"Record": records}})
|
||||
case "DeleteDomainRecord":
|
||||
if r.Form.Get("RecordId") != "owned-id" {
|
||||
t.Error("不得删除其他记录")
|
||||
}
|
||||
if scenario == "delete_error" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"Code":"Forbidden.RAM","Message":"denied"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"RecordId":"owned-id"}`))
|
||||
default:
|
||||
t.Errorf("不允许的云端操作:%s", action)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
sdk, err := client.NewClient(new(openapi.Config).SetAccessKeyId("test-id").SetAccessKeySecret("test-secret").
|
||||
SetEndpoint(strings.TrimPrefix(server.URL, "http://")).SetProtocol("http").
|
||||
SetRetryOptions(&dara.RetryOptions{Retryable: false, MaxAttempts: 1}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := (aliyunRecords{client: sdk}).Add(t.Context(), "example.com", "_scert-authorization-unique.web", "unique-proof")
|
||||
if err == nil || id != "" {
|
||||
t.Fatal("创建结果不确定不能变成验证成功")
|
||||
}
|
||||
if scenario != "cleanup" && !strings.Contains(err.Error(), "需要核对") {
|
||||
t.Fatalf("补偿未完成必须保留人工核对信息:%v", err)
|
||||
}
|
||||
if scenario != "cleanup" && !strings.Contains(DiagnoseAliyunError(err, "example.com"), "_scert-authorization-unique.web.example.com") {
|
||||
t.Fatal("页面诊断必须保留待核对记录,不能只显示通用超时")
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
want := "AddDomainRecord,DescribeDomainRecords"
|
||||
if scenario == "cleanup" || scenario == "delete_error" {
|
||||
want += ",DeleteDomainRecord"
|
||||
}
|
||||
if strings.Join(actions, ",") != want {
|
||||
t.Fatalf("云端操作越界或自动重试创建:%v", actions)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliyunReconcilePreservesCancellationAndExclusions(t *testing.T) {
|
||||
api := aliyunRecords{}
|
||||
denied := errors.New("Forbidden.RAM")
|
||||
if got := api.reconcileAuthorizationAdd(t.Context(), "example.com", "_scert-authorization-unique", "proof", denied); got != denied {
|
||||
t.Fatal("明确拒绝不应触发补偿查询")
|
||||
}
|
||||
if got := api.reconcileAuthorizationAdd(t.Context(), "example.com", "_acme-challenge", "proof", context.DeadlineExceeded); got != context.DeadlineExceeded {
|
||||
t.Fatal("不得通过授权探测补偿删除共享 ACME 记录")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"TotalCount":0,"DomainRecords":{"Record":[]}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
sdk, err := client.NewClient(new(openapi.Config).SetAccessKeyId("test-id").SetAccessKeySecret("test-secret").SetEndpoint(strings.TrimPrefix(server.URL, "http://")).SetProtocol("http"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
api.client = sdk
|
||||
started := time.Now()
|
||||
err = api.reconcileAuthorizationAdd(ctx, "example.com", "_scert-authorization-unique", "proof", context.Canceled)
|
||||
if !errors.Is(err, context.Canceled) || calls != 1 || time.Since(started) > aliyunReconciliationTimeout {
|
||||
t.Fatalf("补偿应独立于取消且保持时限和原始错误:calls=%d err=%v", calls, err)
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ func TestAliyunRecordsDescribeUsesScopedExactQuery(t *testing.T) {
|
||||
for key, expected := range map[string]string{
|
||||
"DomainName": "example.com",
|
||||
"RRKeyWord": "_scert-authorization-mixed.web", "TypeKeyWord": "TXT",
|
||||
"SearchMode": "EXACT", "PageNumber": "1", "PageSize": "100",
|
||||
"SearchMode": "COMBINATION", "PageNumber": "1", "PageSize": "100",
|
||||
} {
|
||||
if got := r.Form.Get(key); got != expected {
|
||||
t.Errorf("查询范围错误:%s=%q,预期 %q", key, got, expected)
|
||||
|
||||
Reference in new issue
Block a user