保存显式授权范围与认证加固中间检查点
This commit is contained in:
1 parent
7f567ea23a
commit
49ede22861
28 files changed
+961
-148
No files matched your search
@@ -47,10 +47,11 @@ type AuthorizationReport struct {
|
||||
type AliyunAuthorizationChecker struct {
|
||||
now func() time.Time
|
||||
verifyDomainFunc func(context.Context, string, map[string]string) error
|
||||
recordAPI func(map[string]string) (aliyunRecordAPI, error)
|
||||
}
|
||||
|
||||
func NewAliyunAuthorizationChecker() *AliyunAuthorizationChecker {
|
||||
return &AliyunAuthorizationChecker{now: time.Now}
|
||||
return &AliyunAuthorizationChecker{now: time.Now, recordAPI: newAliyunRecordAPI}
|
||||
}
|
||||
|
||||
func (c *AliyunAuthorizationChecker) Supports(providerID string) bool {
|
||||
@@ -83,6 +84,19 @@ func (c *AliyunAuthorizationChecker) Inspect(ctx context.Context, requestedDomai
|
||||
if !domain.IsValidName(requestedDomain) {
|
||||
return report, fmt.Errorf("待检查托管区格式无效:%s", requestedDomain)
|
||||
}
|
||||
scope, err := ParseAliyunScope(credentials)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
explicit := false
|
||||
for _, zone := range scope.ManagedZones {
|
||||
if zone == requestedDomain {
|
||||
explicit = true
|
||||
}
|
||||
}
|
||||
if !explicit {
|
||||
return report, errors.New("只允许读取显式配置的托管区,未调用阿里云 API")
|
||||
}
|
||||
report.Domains = []AuthorizationDomain{{Domain: requestedDomain, Status: "等待读取权限检查"}}
|
||||
dnsClient, err := newAliyunClient(credentials)
|
||||
if err != nil {
|
||||
@@ -105,52 +119,63 @@ func (c *AliyunAuthorizationChecker) Inspect(ctx context.Context, requestedDomai
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// Verify 从目标域名到父级托管区逐级执行最小写入和精确清理。
|
||||
// Verify 只在用户显式允许的域名及托管区中执行一次写入和精确清理。
|
||||
func (c *AliyunAuthorizationChecker) Verify(ctx context.Context, requestedDomain string, credentials map[string]string) (AuthorizationReport, error) {
|
||||
requestedDomain = normalizeAuthorizationDomain(requestedDomain)
|
||||
report := AuthorizationReport{Provider: Aliyun, RequestedDomain: requestedDomain, CheckedAt: c.currentTime().UTC()}
|
||||
if !domain.IsValidName(requestedDomain) {
|
||||
return report, fmt.Errorf("待验证域名格式无效:%s", requestedDomain)
|
||||
}
|
||||
for _, candidate := range authorizationZoneCandidates(requestedDomain) {
|
||||
report.Domains = append(report.Domains, AuthorizationDomain{
|
||||
Domain: candidate, Status: "待验证",
|
||||
})
|
||||
}
|
||||
client, err := newAliyunClient(credentials)
|
||||
scope, err := ParseAliyunScope(credentials)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for index, candidate := range authorizationZoneCandidates(requestedDomain) {
|
||||
report.Domains[index].Status = "正在证明写入权限"
|
||||
recordID, probeErr := addAuthorizationRecord(ctx, client, candidate)
|
||||
if probeErr != nil {
|
||||
lastErr = probeErr
|
||||
report.Domains[index].Status = "不可操作"
|
||||
report.Domains[index].Error = probeErr.Error()
|
||||
continue
|
||||
}
|
||||
report.Domains[index].Writable = true
|
||||
report.MatchedDomain = candidate
|
||||
cleanupContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), aliyunAuthorizationTimeout)
|
||||
cleanupErr := deleteAuthorizationRecord(cleanupContext, client, recordID)
|
||||
cancel()
|
||||
if cleanupErr != nil {
|
||||
markAuthorizationFailure(&report, candidate, fmt.Errorf("清理授权探测 TXT 记录失败:%w", cleanupErr))
|
||||
return report, cleanupErr
|
||||
}
|
||||
report.Domains[index].Cleanup = true
|
||||
report.Domains[index].Status = "可操作"
|
||||
report.Verified = true
|
||||
return report, nil
|
||||
zone, err := scope.Resolve(requestedDomain)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = errors.New("未找到可验证的阿里云 DNS 托管根域名")
|
||||
if err := ctx.Err(); err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Diagnosis = DiagnoseAliyunError(lastErr, requestedDomain)
|
||||
return report, fmt.Errorf("阿里云 RAM 账号无法写入域名 %s:%w(建议:%s)", requestedDomain, lastErr, report.Diagnosis)
|
||||
report.Domains = []AuthorizationDomain{{Domain: zone, Status: "待验证"}}
|
||||
if c == nil || c.recordAPI == nil {
|
||||
return report, errors.New("阿里云权限探测器未初始化")
|
||||
}
|
||||
api, err := c.recordAPI(credentials)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
suffix, err := randomAuthorizationValue(18)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
value, err := randomAuthorizationValue(32)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
rr := "_scert-authorization-" + suffix
|
||||
base := strings.TrimPrefix(requestedDomain, "*.")
|
||||
if base != zone {
|
||||
rr += "." + strings.TrimSuffix(base, "."+zone)
|
||||
}
|
||||
recordID, err := api.Add(ctx, zone, rr, value)
|
||||
if err != nil {
|
||||
markAuthorizationFailure(&report, zone, err)
|
||||
report.Diagnosis = DiagnoseAliyunError(err, zone)
|
||||
return report, err
|
||||
}
|
||||
report.Domains[0].Writable = true
|
||||
report.MatchedDomain = zone
|
||||
cleanupContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), aliyunAuthorizationTimeout)
|
||||
defer cancel()
|
||||
if err := api.Delete(cleanupContext, recordID); err != nil {
|
||||
markAuthorizationFailure(&report, zone, fmt.Errorf("清理授权探测 TXT 记录失败:%w", err))
|
||||
return report, err
|
||||
}
|
||||
report.Domains[0].Cleanup = true
|
||||
report.Domains[0].Status = "可操作"
|
||||
report.Verified = true
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// VerifyDomain 每次重新证明写入和清理能力,不使用跨请求缓存掩盖撤权。
|
||||
@@ -171,6 +196,9 @@ func (c *AliyunAuthorizationChecker) VerifyDomain(ctx context.Context, providerI
|
||||
if _, err := ValidateCredentials(Aliyun, credentials); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ValidateAliyunDomainScope(Aliyun, []string{requestedDomain}, credentials); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.verifyDomainFunc != nil {
|
||||
return c.verifyDomainFunc(ctx, requestedDomain, credentials)
|
||||
}
|
||||
@@ -248,31 +276,6 @@ func listAliyunDomains(ctx context.Context, dnsClient *client.Client) ([]string,
|
||||
return uniqueStrings(result), nil
|
||||
}
|
||||
|
||||
func addAuthorizationRecord(ctx context.Context, dnsClient *client.Client, zone string) (string, error) {
|
||||
suffix, err := randomAuthorizationValue(18)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("生成授权探测标识失败:%w", err)
|
||||
}
|
||||
value, err := randomAuthorizationValue(32)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("生成授权探测值失败:%w", err)
|
||||
}
|
||||
request := new(client.AddDomainRecordRequest).
|
||||
SetDomainName(zone).
|
||||
SetRR("_scert-authorization-" + suffix).
|
||||
SetType("TXT").
|
||||
SetValue(value).
|
||||
SetTTL(aliyunAuthorizationTTL)
|
||||
response, err := client.AddDomainRecordWithContext(ctx, dnsClient, request, &dara.RuntimeOptions{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response == nil || response.Body == nil || response.Body.RecordId == nil || strings.TrimSpace(*response.Body.RecordId) == "" {
|
||||
return "", errors.New("阿里云未返回授权探测记录 ID")
|
||||
}
|
||||
return strings.TrimSpace(*response.Body.RecordId), nil
|
||||
}
|
||||
|
||||
func deleteAuthorizationRecord(ctx context.Context, dnsClient *client.Client, recordID string) error {
|
||||
if strings.TrimSpace(recordID) == "" {
|
||||
return errors.New("授权探测记录 ID 为空")
|
||||
@@ -296,19 +299,6 @@ func matchManagedDomain(requested string, domains []AuthorizationDomain) string
|
||||
return best
|
||||
}
|
||||
|
||||
func authorizationZoneCandidates(requested string) []string {
|
||||
requested = strings.TrimPrefix(normalizeAuthorizationDomain(requested), "*.")
|
||||
labels := strings.Split(requested, ".")
|
||||
result := make([]string, 0, len(labels)-1)
|
||||
for index := 0; index < len(labels)-1; index++ {
|
||||
candidate := strings.Join(labels[index:], ".")
|
||||
if domain.IsValidName(candidate) {
|
||||
result = append(result, candidate)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func markAuthorizationFailure(report *AuthorizationReport, domainName string, err error) {
|
||||
for index := range report.Domains {
|
||||
if report.Domains[index].Domain == domainName {
|
||||
|
||||
@@ -7,19 +7,6 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAuthorizationZoneCandidatesPreferSpecificZones(t *testing.T) {
|
||||
got := authorizationZoneCandidates("*.www.example.com.")
|
||||
want := []string{"www.example.com", "example.com"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("候选托管区数量错误:got=%v want=%v", got, want)
|
||||
}
|
||||
for index := range want {
|
||||
if got[index] != want[index] {
|
||||
t.Fatalf("候选托管区顺序错误:got=%v want=%v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliyunAuthorizationCheckerRechecksEveryRequestAndDetectsRevocation(t *testing.T) {
|
||||
now := time.Date(2026, 9, 14, 12, 0, 0, 0, time.UTC)
|
||||
calls := 0
|
||||
@@ -36,6 +23,8 @@ func TestAliyunAuthorizationCheckerRechecksEveryRequestAndDetectsRevocation(t *t
|
||||
credentials := map[string]string{
|
||||
"access_key_id": "test-id",
|
||||
"access_key_secret": "test-secret",
|
||||
"managed_zones": "example.com",
|
||||
"allowed_domains": "example.com,www.example.com",
|
||||
}
|
||||
|
||||
if err := checker.VerifyDomain(context.Background(), Aliyun, "www.example.com", credentials); err != nil {
|
||||
@@ -67,6 +56,8 @@ func TestAliyunAuthorizationCheckerInvalidatesAfterPermissionFailure(t *testing.
|
||||
credentials := map[string]string{
|
||||
"access_key_id": "test-id",
|
||||
"access_key_secret": "test-secret",
|
||||
"managed_zones": "example.com",
|
||||
"allowed_domains": "example.com",
|
||||
}
|
||||
|
||||
if err := checker.VerifyDomain(context.Background(), Aliyun, "example.com", credentials); err != nil {
|
||||
@@ -91,6 +82,8 @@ func TestAliyunAuthorizationCheckerDoesNotCacheFailedAuthorization(t *testing.T)
|
||||
credentials := map[string]string{
|
||||
"access_key_id": "test-id",
|
||||
"access_key_secret": "test-secret",
|
||||
"managed_zones": "example.com",
|
||||
"allowed_domains": "example.com",
|
||||
}
|
||||
|
||||
if err := checker.VerifyDomain(context.Background(), Aliyun, "example.com", credentials); err == nil {
|
||||
@@ -112,6 +105,8 @@ func TestAliyunAuthorizationCheckerCacheIsSafeForConcurrentUse(t *testing.T) {
|
||||
credentials := map[string]string{
|
||||
"access_key_id": "test-id",
|
||||
"access_key_secret": "test-secret",
|
||||
"managed_zones": "example.com",
|
||||
"allowed_domains": "example.com",
|
||||
}
|
||||
done := make(chan struct{})
|
||||
for index := 0; index < 20; index++ {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/alibabacloud-go/tea/dara"
|
||||
"github.com/go-acme/alidns-20150109/v5/client"
|
||||
"github.com/go-acme/lego/v5/challenge/dns01"
|
||||
)
|
||||
|
||||
type aliyunRecordAPI interface {
|
||||
Add(context.Context, string, string, string) (string, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type aliyunRecords struct{ client *client.Client }
|
||||
|
||||
func (a aliyunRecords) Add(ctx context.Context, zone, rr, value string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, aliyunAuthorizationTimeout)
|
||||
defer cancel()
|
||||
request := new(client.AddDomainRecordRequest).SetDomainName(zone).SetRR(rr).
|
||||
SetType("TXT").SetValue(value).SetTTL(aliyunAuthorizationTTL)
|
||||
response, err := client.AddDomainRecordWithContext(ctx, a.client, request, &dara.RuntimeOptions{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response == nil || response.Body == nil || response.Body.RecordId == nil || strings.TrimSpace(*response.Body.RecordId) == "" {
|
||||
return "", errors.New("阿里云未返回新增记录 ID,状态未确认,请人工核对本次记录")
|
||||
}
|
||||
return strings.TrimSpace(*response.Body.RecordId), nil
|
||||
}
|
||||
|
||||
func (a aliyunRecords) Delete(ctx context.Context, id string) error {
|
||||
return deleteAuthorizationRecord(ctx, a.client, id)
|
||||
}
|
||||
|
||||
func newAliyunRecordAPI(credentials map[string]string) (aliyunRecordAPI, error) {
|
||||
dnsClient, err := newAliyunClient(credentials)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return aliyunRecords{client: dnsClient}, nil
|
||||
}
|
||||
|
||||
// 不使用自动发现托管区的上游适配器,也不沿 CNAME 自动扩大写入范围。
|
||||
type scopedAliyunProvider struct {
|
||||
scope AliyunScope
|
||||
api aliyunRecordAPI
|
||||
mu sync.Mutex
|
||||
records map[[32]byte]string
|
||||
challengeInfo func(context.Context, string, string) (string, string, string)
|
||||
}
|
||||
|
||||
func newScopedAliyunProvider(credentials map[string]string) (*scopedAliyunProvider, error) {
|
||||
scope, err := ParseAliyunScope(credentials)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api, err := newAliyunRecordAPI(credentials)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &scopedAliyunProvider{scope: scope, api: api, records: make(map[[32]byte]string), challengeInfo: aliyunChallengeInfo}, nil
|
||||
}
|
||||
|
||||
func aliyunChallengeInfo(ctx context.Context, domainName, keyAuth string) (string, string, string) {
|
||||
info := dns01.GetChallengeInfo(ctx, domainName, keyAuth)
|
||||
return info.FQDN, info.EffectiveFQDN, info.Value
|
||||
}
|
||||
|
||||
func (p *scopedAliyunProvider) Present(ctx context.Context, name, token, keyAuth string) error {
|
||||
name = normalizeAuthorizationDomain(name)
|
||||
zone, err := p.scope.Resolve(name)
|
||||
// ACME 的通配符授权以去掉通配符的标识符进入 Provider;业务层已逐项验证 SAN。
|
||||
if err != nil && !strings.HasPrefix(name, "*.") {
|
||||
zone, err = p.scope.Resolve("*." + name)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
base := strings.TrimPrefix(name, "*.")
|
||||
fqdn, effective, value := p.challengeInfo(ctx, base, keyAuth)
|
||||
expected := "_acme-challenge." + base
|
||||
if normalizeAuthorizationDomain(fqdn) != expected || normalizeAuthorizationDomain(effective) != expected {
|
||||
return errors.New("DNS 挑战存在 CNAME 重定向,已拒绝自动跟随;请显式配置受限的 CNAME 委派服务商")
|
||||
}
|
||||
rr := strings.TrimSuffix(expected, "."+zone)
|
||||
if rr == expected {
|
||||
return errors.New("DNS 挑战记录不属于显式托管区")
|
||||
}
|
||||
key := sha256.Sum256([]byte(name + "\x00" + token + "\x00" + keyAuth))
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if _, ok := p.records[key]; ok {
|
||||
return errors.New("同一 DNS 挑战已有待清理记录,拒绝重复新增")
|
||||
}
|
||||
id, err := p.api.Add(ctx, zone, rr, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.records[key] = id
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *scopedAliyunProvider) CleanUp(ctx context.Context, name, token, keyAuth string) error {
|
||||
key := sha256.Sum256([]byte(normalizeAuthorizationDomain(name) + "\x00" + token + "\x00" + keyAuth))
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
id, ok := p.records[key]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), aliyunAuthorizationTimeout)
|
||||
defer cancel()
|
||||
if err := p.api.Delete(cleanupCtx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(p.records, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *scopedAliyunProvider) Timeout() (time.Duration, time.Duration) {
|
||||
return 120 * time.Second, 2 * time.Second
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// AliyunScope 是用户授权的上限,不是从 RAM 读取结果自动推导的权限。
|
||||
// 范围随凭据引用不可变地保存;修改范围必须重新在线验证并获得新的引用。
|
||||
type AliyunScope struct {
|
||||
ManagedZones []string `json:"managed_zones"`
|
||||
AllowedDomains []string `json:"allowed_domains"`
|
||||
}
|
||||
|
||||
func ParseAliyunScope(credentials map[string]string) (AliyunScope, error) {
|
||||
var scope AliyunScope
|
||||
var err error
|
||||
scope.ManagedZones, err = parseScopeNames(credentials["managed_zones"], false)
|
||||
if err != nil {
|
||||
return scope, fmt.Errorf("请显式配置阿里云托管区:%w", err)
|
||||
}
|
||||
scope.AllowedDomains, err = parseScopeNames(credentials["allowed_domains"], true)
|
||||
if err != nil {
|
||||
return scope, fmt.Errorf("请显式配置允许操作的域名:%w", err)
|
||||
}
|
||||
for _, name := range scope.AllowedDomains {
|
||||
if scope.zoneFor(strings.TrimPrefix(name, "*.")) == "" {
|
||||
return AliyunScope{}, fmt.Errorf("允许域名 %s 不属于任何显式托管区", name)
|
||||
}
|
||||
}
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
func parseScopeNames(value string, wildcard bool) ([]string, error) {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return nil, errors.New("旧配置或空范围不允许 DNS 操作,请补充范围并重新验证")
|
||||
}
|
||||
parts := strings.Split(value, ",")
|
||||
if len(parts) > 128 {
|
||||
return nil, errors.New("每个范围最多允许 128 项")
|
||||
}
|
||||
result := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
name := normalizeAuthorizationDomain(part)
|
||||
base := strings.TrimPrefix(name, "*.")
|
||||
if !domain.IsValidName(name) || (!wildcard && name != base) {
|
||||
return nil, errors.New("范围应为逗号分隔的有效域名,托管区不能含通配符")
|
||||
}
|
||||
if _, err := publicsuffix.EffectiveTLDPlusOne(base); err != nil {
|
||||
return nil, fmt.Errorf("公共后缀不能作为操作范围:%s", name)
|
||||
}
|
||||
result = append(result, name)
|
||||
}
|
||||
return uniqueStrings(result), nil
|
||||
}
|
||||
|
||||
func (s AliyunScope) zoneFor(name string) string {
|
||||
best := ""
|
||||
for _, zone := range s.ManagedZones {
|
||||
if (name == zone || strings.HasSuffix(name, "."+zone)) && len(zone) > len(best) {
|
||||
best = zone
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// Resolve 只选择最具体的显式托管区;失败后绝不回退到父区。
|
||||
// 通配授权只包含一层子域和对应通配证书,不隐含根域或多层子域。
|
||||
func (s AliyunScope) Resolve(requested string) (string, error) {
|
||||
requested = normalizeAuthorizationDomain(requested)
|
||||
if !domain.IsValidName(requested) {
|
||||
return "", errors.New("待操作域名格式无效")
|
||||
}
|
||||
allowed := false
|
||||
for _, name := range s.AllowedDomains {
|
||||
if requested == name {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(name, "*.") && !strings.HasPrefix(requested, "*.") {
|
||||
suffix := name[1:]
|
||||
if strings.HasSuffix(requested, suffix) {
|
||||
label := strings.TrimSuffix(requested, suffix)
|
||||
allowed = label != "" && !strings.Contains(label, ".")
|
||||
if allowed {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
zone := s.zoneFor(strings.TrimPrefix(requested, "*."))
|
||||
if !allowed || zone == "" {
|
||||
return "", fmt.Errorf("域名 %s 不在用户显式允许范围内,未调用阿里云 API", requested)
|
||||
}
|
||||
return zone, nil
|
||||
}
|
||||
|
||||
func ValidateAliyunDomainScope(providerID string, domains []string, credentials map[string]string) error {
|
||||
if !strings.EqualFold(strings.TrimSpace(providerID), Aliyun) {
|
||||
return nil
|
||||
}
|
||||
scope, err := ParseAliyunScope(credentials)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range domains {
|
||||
if _, err := scope.Resolve(name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func scopeCredentials() map[string]string {
|
||||
return map[string]string{"access_key_id": "test-id", "access_key_secret": "test-secret", "managed_zones": "example.com,sub.example.com", "allowed_domains": "www.sub.example.com,*.example.com"}
|
||||
}
|
||||
|
||||
func TestAliyunScopeBoundaries(t *testing.T) {
|
||||
scope, err := ParseAliyunScope(scopeCredentials())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct{ name, zone string }{
|
||||
{"www.sub.example.com", "sub.example.com"},
|
||||
{"WWW.EXAMPLE.COM.", "example.com"},
|
||||
{"*.example.com", "example.com"},
|
||||
{"example.com", ""},
|
||||
{"evil-example.com", ""},
|
||||
{"example.com.evil.net", ""},
|
||||
{"deep.www.example.com", ""},
|
||||
{"*.sub.example.com", ""},
|
||||
{"pcux.cn", ""},
|
||||
{"com", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
zone, err := scope.Resolve(tc.name)
|
||||
if zone != tc.zone || (err != nil) != (tc.zone == "") {
|
||||
t.Fatalf("范围校验错误:zone=%s err=%v", zone, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, value := range []string{"", "com", "co.uk", "*.example.com", "example.com,", "example.com,co.uk"} {
|
||||
credentials := scopeCredentials()
|
||||
credentials["managed_zones"] = value
|
||||
if _, err := ParseAliyunScope(credentials); err == nil {
|
||||
t.Fatalf("不安全托管区未拒绝:%s", value)
|
||||
}
|
||||
}
|
||||
credentials := scopeCredentials()
|
||||
credentials["allowed_domains"] = "outside.net"
|
||||
if _, err := ParseAliyunScope(credentials); err == nil {
|
||||
t.Fatal("越界的允许范围必须整体拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
type fakeAliyunRecords struct {
|
||||
zones, rrs, deleted []string
|
||||
addErr, deleteErr error
|
||||
canceledCleanup bool
|
||||
}
|
||||
|
||||
func (f *fakeAliyunRecords) Add(_ context.Context, zone, rr, _ string) (string, error) {
|
||||
f.zones = append(f.zones, zone)
|
||||
f.rrs = append(f.rrs, rr)
|
||||
return "created-record-id", f.addErr
|
||||
}
|
||||
|
||||
func (f *fakeAliyunRecords) Delete(ctx context.Context, id string) error {
|
||||
f.deleted = append(f.deleted, id)
|
||||
f.canceledCleanup = ctx.Err() != nil
|
||||
return f.deleteErr
|
||||
}
|
||||
|
||||
func TestAliyunProbeNeverFallsBackOrCallsCloudOutsideScope(t *testing.T) {
|
||||
api := &fakeAliyunRecords{addErr: errors.New("Forbidden.RAM")}
|
||||
checker := NewAliyunAuthorizationChecker()
|
||||
constructed := 0
|
||||
checker.recordAPI = func(map[string]string) (aliyunRecordAPI, error) { constructed++; return api, nil }
|
||||
credentials := scopeCredentials()
|
||||
for _, name := range []string{"example.com", "outside.net", "pcux.cn", "*.sub.example.com"} {
|
||||
if _, err := checker.Verify(t.Context(), name, credentials); err == nil {
|
||||
t.Fatal("越界请求未拒绝")
|
||||
}
|
||||
}
|
||||
if constructed != 0 {
|
||||
t.Fatal("越界请求不能创建云客户端")
|
||||
}
|
||||
if _, err := checker.Verify(t.Context(), "www.sub.example.com", credentials); err == nil {
|
||||
t.Fatal("RAM 拒绝必须返回失败")
|
||||
}
|
||||
if len(api.zones) != 1 || api.zones[0] != "sub.example.com" || !strings.HasSuffix(api.rrs[0], ".www") {
|
||||
t.Fatalf("必须仅写授权子域:%v %v", api.zones, api.rrs)
|
||||
}
|
||||
if len(api.deleted) != 0 {
|
||||
t.Fatal("新增失败不能猜测记录 ID 删除")
|
||||
}
|
||||
api.addErr = nil
|
||||
api.deleteErr = errors.New("Forbidden.RAM")
|
||||
report, err := checker.Verify(t.Context(), "www.sub.example.com", credentials)
|
||||
if err == nil || report.Verified || !report.Domains[0].Writable || report.Domains[0].Cleanup {
|
||||
t.Fatal("清理失败不能证明权限通过")
|
||||
}
|
||||
api.deleteErr = nil
|
||||
report, err = checker.Verify(t.Context(), "www.sub.example.com", credentials)
|
||||
if err != nil || !report.Verified || api.deleted[len(api.deleted)-1] != "created-record-id" {
|
||||
t.Fatal("必须删除本次新增记录")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliyunProviderPinsZoneAndCleanupIdentity(t *testing.T) {
|
||||
scope, _ := ParseAliyunScope(scopeCredentials())
|
||||
api := &fakeAliyunRecords{}
|
||||
p := &scopedAliyunProvider{scope: scope, api: api, records: make(map[[32]byte]string), challengeInfo: func(_ context.Context, name, _ string) (string, string, string) {
|
||||
fqdn := "_acme-challenge." + name + "."
|
||||
return fqdn, fqdn, "txt-value"
|
||||
}}
|
||||
if err := p.Present(t.Context(), "outside.net", "token", "key"); err == nil || len(api.zones) != 0 {
|
||||
t.Fatal("实际 Provider 必须零调用拒绝越界")
|
||||
}
|
||||
if err := p.Present(t.Context(), "www.sub.example.com", "token", "key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(api.zones) != 1 || api.zones[0] != "sub.example.com" || api.rrs[0] != "_acme-challenge.www" {
|
||||
t.Fatal("实际写入没有锁定指定托管区")
|
||||
}
|
||||
if err := p.Present(t.Context(), "www.sub.example.com", "token", "key"); err == nil {
|
||||
t.Fatal("重复挑战不能覆盖待清理 ID")
|
||||
}
|
||||
_ = p.CleanUp(t.Context(), "www.sub.example.com", "other", "key")
|
||||
if len(api.deleted) != 0 {
|
||||
t.Fatal("不能清理其他挑战")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if err := p.CleanUp(ctx, "www.sub.example.com", "token", "key"); err != nil || api.canceledCleanup || len(api.deleted) != 1 {
|
||||
t.Fatal("请求取消后仍需有界清理本次 ID")
|
||||
}
|
||||
p.challengeInfo = func(context.Context, string, string) (string, string, string) {
|
||||
return "_acme-challenge.www.sub.example.com.", "_acme-challenge.outside.net.", "value"
|
||||
}
|
||||
if err := p.Present(t.Context(), "www.sub.example.com", "new", "key"); err == nil || len(api.zones) != 1 {
|
||||
t.Fatal("CNAME 越界不能调用云 API")
|
||||
}
|
||||
}
|
||||
@@ -48,11 +48,13 @@ var descriptors = map[string]Descriptor{
|
||||
},
|
||||
Aliyun: {
|
||||
ID: Aliyun, Name: "阿里云 DNS", Available: true,
|
||||
Description: "使用 RAM AccessKey 创建和清理 DNS-01 测试记录。",
|
||||
Description: "仅操作显式托管区内的允许域名。范围用英文逗号分隔;通配符只允许一层子域,不包含根域。旧配置需补充范围后重新验证。",
|
||||
CredentialFields: []CredentialField{
|
||||
{Name: "access_key_id", Label: "AccessKey ID", Required: true},
|
||||
{Name: "access_key_secret", Label: "AccessKey Secret", Secret: true, Required: true},
|
||||
{Name: "security_token", Label: "Security Token", Secret: true},
|
||||
{Name: "managed_zones", Label: "明确托管区", Required: true, Placeholder: "例如 example.com,example.net;不自动尝试父域"},
|
||||
{Name: "allowed_domains", Label: "允许操作的域名", Required: true, Placeholder: "例如 www.example.com,*.example.net;根域须单独填写"},
|
||||
},
|
||||
},
|
||||
DNSPod: {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v5/challenge"
|
||||
"github.com/go-acme/lego/v5/providers/dns/alidns"
|
||||
"github.com/go-acme/lego/v5/providers/dns/cloudflare"
|
||||
"github.com/go-acme/lego/v5/providers/dns/gcloud"
|
||||
"github.com/go-acme/lego/v5/providers/dns/huaweicloud"
|
||||
@@ -73,15 +72,7 @@ func (LegoFactory) Create(providerID string, credentials map[string]string) (cha
|
||||
}
|
||||
return provider, nil
|
||||
case Aliyun:
|
||||
cfg := alidns.NewDefaultConfig()
|
||||
cfg.APIKey = cleaned["access_key_id"]
|
||||
cfg.SecretKey = cleaned["access_key_secret"]
|
||||
cfg.SecurityToken = cleaned["security_token"]
|
||||
provider, err := alidns.NewDNSProviderConfig(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建阿里云 DNS Provider 失败:%w", err)
|
||||
}
|
||||
return provider, nil
|
||||
return newScopedAliyunProvider(cleaned)
|
||||
case DNSPod, TencentCloud:
|
||||
cfg := tencentcloud.NewDefaultConfig()
|
||||
cfg.SecretID = cleaned["secret_id"]
|
||||
|
||||
@@ -102,6 +102,9 @@ func (t *Tester) VerifyWithReport(ctx context.Context, providerID, testDomain st
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if err := ValidateAliyunDomainScope(providerID, []string{testDomain}, cleaned); err != nil {
|
||||
return report, err
|
||||
}
|
||||
provider, err := t.factory.Create(providerID, cleaned)
|
||||
if err != nil {
|
||||
return report, err
|
||||
|
||||
@@ -175,6 +175,8 @@ func TestLegoFactoryCreatesConfiguredProviders(t *testing.T) {
|
||||
credentials: map[string]string{
|
||||
"access_key_id": "id",
|
||||
"access_key_secret": "secret",
|
||||
"managed_zones": "example.com",
|
||||
"allowed_domains": "example.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user