feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,184 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dnsmgr struct {
|
||||
client *http.Client
|
||||
zone string
|
||||
credential Credential
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func positiveID(s string) bool {
|
||||
id, e := strconv.ParseUint(s, 10, 64)
|
||||
return e == nil && id > 0 && strconv.FormatUint(id, 10) == s
|
||||
}
|
||||
func md5Hex(v string) string { sum := md5.Sum([]byte(v)); return hex.EncodeToString(sum[:]) }
|
||||
func (p *dnsmgr) call(ctx context.Context, path string, values url.Values, output any) error {
|
||||
stamp := strconv.FormatInt(p.now().Unix(), 10)
|
||||
values.Set("uid", p.credential.UserID)
|
||||
values.Set("timestamp", stamp)
|
||||
values.Set("sign", md5Hex(p.credential.UserID+stamp+p.credential.APIKey))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(p.credential.Endpoint, "/")+"/api/"+path, strings.NewReader(values.Encode()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
// List APIs use {total,rows}; mutation/info APIs require an explicit successful code.
|
||||
var raw json.RawMessage
|
||||
if err = doJSON(p.client, req, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
var status struct {
|
||||
Code *int `json:"code"`
|
||||
}
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
return errors.New("彩虹 DNS 响应无效")
|
||||
}
|
||||
if status.Code != nil && *status.Code != 0 {
|
||||
return errors.New("彩虹 DNS 拒绝请求,请检查 API 权限与票据")
|
||||
}
|
||||
if !strings.HasSuffix(path, "domain") && !strings.HasPrefix(path, "record/data/") && status.Code == nil {
|
||||
return errors.New("彩虹 DNS 未确认操作结果")
|
||||
}
|
||||
return json.Unmarshal(raw, output)
|
||||
}
|
||||
func (p *dnsmgr) Present(ctx context.Context, fqdn, value string) (string, error) {
|
||||
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
||||
}
|
||||
|
||||
type mgrRecord struct {
|
||||
ID json.RawMessage `json:"RecordId"`
|
||||
Name string `json:"Name"`
|
||||
Type string `json:"Type"`
|
||||
Value json.RawMessage `json:"Value"`
|
||||
}
|
||||
|
||||
func rawID(raw json.RawMessage) string {
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
return s
|
||||
}
|
||||
var n json.Number
|
||||
if json.Unmarshal(raw, &n) == nil {
|
||||
return n.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func rawValueContains(raw json.RawMessage, value string) bool {
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
return s == value
|
||||
}
|
||||
var all []string
|
||||
if json.Unmarshal(raw, &all) == nil {
|
||||
for _, s := range all {
|
||||
if s == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (p *dnsmgr) records(ctx context.Context, rr, kind, value string) ([]mgrRecord, error) {
|
||||
var out struct {
|
||||
Total *int `json:"total"`
|
||||
Rows []mgrRecord `json:"rows"`
|
||||
}
|
||||
if err := p.call(ctx, "record/data/"+p.credential.ZoneID, url.Values{"subdomain": {rr}, "type": {kind}, "value": {value}, "offset": {"0"}, "limit": {"100"}}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if out.Total == nil || *out.Total > 100 {
|
||||
return nil, errors.New("彩虹 DNS 记录响应不完整")
|
||||
}
|
||||
return out.Rows, nil
|
||||
}
|
||||
func (p *dnsmgr) CreateRecord(ctx context.Context, fqdn, kind, value string) (string, error) {
|
||||
if err := validateRecord(kind, value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
rr, err := relativeRecordName(fqdn, p.zone)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !positiveID(p.credential.ZoneID) {
|
||||
return "", errors.New("彩虹 DNS 域名编号无效")
|
||||
}
|
||||
before, err := p.records(ctx, rr, kind, value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
old := map[string]bool{}
|
||||
for _, r := range before {
|
||||
old[rawID(r.ID)] = true
|
||||
}
|
||||
var info struct {
|
||||
Code int `json:"code"`
|
||||
Data struct {
|
||||
RecordLine []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"recordLine"`
|
||||
MinTTL json.Number `json:"minTTL"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err = p.call(ctx, "domain/"+p.credential.ZoneID, url.Values{}, &info); err != nil {
|
||||
return "", err
|
||||
}
|
||||
minTTL := int64(0)
|
||||
if info.Data.MinTTL != "" {
|
||||
minTTL, err = info.Data.MinTTL.Int64()
|
||||
if err != nil || minTTL < 0 || minTTL > 2147483647 {
|
||||
return "", errors.New("彩虹 DNS 返回了无效的最小 TTL")
|
||||
}
|
||||
}
|
||||
line := ""
|
||||
found := false
|
||||
for _, l := range info.Data.RecordLine {
|
||||
if l.Name == "默认" || strings.EqualFold(l.Name, "default") {
|
||||
line = l.ID
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return "", errors.New("彩虹 DNS 未提供默认解析线路")
|
||||
}
|
||||
var response struct {
|
||||
Code int `json:"code"`
|
||||
}
|
||||
if err = p.call(ctx, "record/add/"+p.credential.ZoneID, url.Values{"name": {rr}, "type": {kind}, "value": {value}, "line": {line}, "ttl": {strconv.FormatInt(max(int64(600), minTTL), 10)}}, &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
after, err := p.records(ctx, rr, kind, value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, r := range after {
|
||||
id := rawID(r.ID)
|
||||
if validIdentifier(id, 1, 128) && !old[id] && (r.Name == rr || r.Name == fqdn) && r.Type == kind && rawValueContains(r.Value, value) {
|
||||
return id, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("彩虹 DNS 已接受创建,但未能核对新增记录编号,请管理员核验")
|
||||
}
|
||||
func (p *dnsmgr) Cleanup(ctx context.Context, id string) error {
|
||||
if !positiveID(p.credential.ZoneID) || !validIdentifier(id, 1, 128) {
|
||||
return errors.New("彩虹 DNS 记录编号无效")
|
||||
}
|
||||
var out struct {
|
||||
Code int `json:"code"`
|
||||
}
|
||||
return p.call(ctx, "record/delete/"+p.credential.ZoneID, url.Values{"recordid": {id}}, &out)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDNSManagerRejectsInvalidTTLBeforeCreatingRecord(t *testing.T) {
|
||||
for _, ttl := range []any{"-1", "1.5", "invalid", "2147483648", false} {
|
||||
t.Run(stringJSON(ttl), func(t *testing.T) {
|
||||
writes := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/record/data/7":
|
||||
_, _ = w.Write([]byte(`{"total":0,"rows":[]}`))
|
||||
case "/api/domain/7":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"minTTL": ttl, "recordLine": []map[string]any{{"id": "default", "name": "默认"}}}})
|
||||
default:
|
||||
writes++
|
||||
_, _ = w.Write([]byte(`{"code":0}`))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := &dnsmgr{client: server.Client(), zone: "example.com", credential: Credential{Endpoint: server.URL, UserID: "12", APIKey: "fixture-api-key", ZoneID: "7"}, now: time.Now}
|
||||
if _, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof"); err == nil || writes != 0 {
|
||||
t.Fatal("invalid TTL reached mutation", err, writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func stringJSON(v any) string { raw, _ := json.Marshal(v); return string(raw) }
|
||||
@@ -0,0 +1,128 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDNSManagerPreservesExistingRecordsAndSignsRequests(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ttl any
|
||||
want string
|
||||
}{{"numeric", 600, "600"}, {"string-low", "60", "600"}, {"string-high", "1800", "1800"}} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
created := false
|
||||
deleted := ""
|
||||
stamp := time.Unix(1780000000, 0)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
t.Error("wrong method")
|
||||
}
|
||||
_ = r.ParseForm()
|
||||
if r.Form.Get("uid") != "12" || r.Form.Get("timestamp") != strconv.FormatInt(stamp.Unix(), 10) || r.Form.Get("sign") != md5Hex("12"+strconv.FormatInt(stamp.Unix(), 10)+"fixture-api-key") {
|
||||
t.Error("invalid API signature")
|
||||
}
|
||||
if r.Form.Get("key") != "" {
|
||||
t.Error("plaintext key transmitted")
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/domain/7":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"recordLine": []map[string]any{{"id": "default", "name": "默认"}}, "minTTL": tc.ttl}})
|
||||
case "/api/record/data/7":
|
||||
rows := []map[string]any{{"RecordId": "9", "Name": "_acme-challenge", "Type": "TXT", "Value": "proof"}}
|
||||
if created {
|
||||
rows = append(rows, map[string]any{"RecordId": "10", "Name": "_acme-challenge", "Type": "TXT", "Value": "proof"})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"total": len(rows), "rows": rows})
|
||||
case "/api/record/add/7":
|
||||
if r.Form.Get("line") != "default" || r.Form.Get("name") != "_acme-challenge" || r.Form.Get("ttl") != tc.want {
|
||||
t.Error("wrong record target")
|
||||
}
|
||||
created = true
|
||||
_, _ = w.Write([]byte(`{"code":0}`))
|
||||
case "/api/record/delete/7":
|
||||
deleted = r.Form.Get("recordid")
|
||||
_, _ = w.Write([]byte(`{"code":0}`))
|
||||
default:
|
||||
t.Error("unexpected endpoint", r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := &dnsmgr{client: srv.Client(), zone: "example.com", credential: Credential{Endpoint: srv.URL, UserID: "12", APIKey: "fixture-api-key", ZoneID: "7"}, now: func() time.Time { return stamp }}
|
||||
id, e := p.Present(context.Background(), "_acme-challenge.example.com", "proof")
|
||||
if e != nil || id != "10" {
|
||||
t.Fatal(id, e)
|
||||
}
|
||||
if e = p.Cleanup(context.Background(), id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if deleted != "10" {
|
||||
t.Fatal("deleted pre-existing record", deleted)
|
||||
}
|
||||
if _, e = p.Present(context.Background(), "outside.example.net", "proof"); e == nil {
|
||||
t.Fatal("zone escape accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestWestAccountUsesReadOnlyDiscoveryAndExactRecordDeletion(t *testing.T) {
|
||||
deleted := ""
|
||||
stamp := time.Unix(1780000000, 0)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
if r.Form.Get("token") != md5Hex("fixture-user"+"fixture-api-key"+strconv.FormatInt(stamp.UnixMilli(), 10)) {
|
||||
t.Error("bad account signature")
|
||||
}
|
||||
switch r.Form.Get("act") {
|
||||
case "adddnsrecord":
|
||||
if r.Form.Get("domain") != "example.com" || r.Form.Get("host") != "_acme-challenge" {
|
||||
t.Error("wrong zone")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"result":200,"data":{"id":55}}`))
|
||||
case "deldnsrecord":
|
||||
deleted = r.Form.Get("id")
|
||||
_, _ = w.Write([]byte(`{"result":200,"data":{}}`))
|
||||
default:
|
||||
t.Error("unexpected operation")
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := &west{client: srv.Client(), baseURL: srv.URL, zone: "example.com", credential: Credential{Username: "fixture-user", APIKey: "fixture-api-key"}, now: func() time.Time { return stamp }}
|
||||
id, e := p.Present(context.Background(), "_acme-challenge.example.com", "proof")
|
||||
if e != nil || id != "55" {
|
||||
t.Fatal(id, e)
|
||||
}
|
||||
if e = p.Cleanup(context.Background(), id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if deleted != "55" {
|
||||
t.Fatal(deleted)
|
||||
}
|
||||
}
|
||||
func TestDNSCustomEndpointCannotReachPrivateNetworks(t *testing.T) {
|
||||
for _, s := range []string{"http://dns.example.com", "https://127.0.0.1", "https://[::1]", "https://10.0.0.1", "https://dns.example.com:9443", "https://user:key@dns.example.com", "https://dns.example.com?a=b", "https://100.64.0.1", "https://[64:ff9b::7f00:1]"} {
|
||||
if _, e := publicEndpoint(s); e == nil {
|
||||
t.Error("unsafe endpoint", s)
|
||||
}
|
||||
}
|
||||
if _, e := publicEndpoint("https://dns.example.com/subdir"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, s := range []string{"127.0.0.1", "::1", "::ffff:127.0.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "64:ff9b::7f00:1", "2002:7f00:1::"} {
|
||||
if publicIP(netip.MustParseAddr(s)) {
|
||||
t.Error("restricted IP accepted", s)
|
||||
}
|
||||
}
|
||||
if !publicIP(netip.MustParseAddr("1.1.1.1")) {
|
||||
t.Fatal("public DNS address rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxResponseBytes = 64 << 10
|
||||
|
||||
type Provider interface {
|
||||
Present(context.Context, string, string) (string, error)
|
||||
CreateRecord(context.Context, string, string, string) (string, error)
|
||||
Cleanup(context.Context, string) error
|
||||
}
|
||||
|
||||
type Credential struct {
|
||||
Endpoint string `json:"endpoint,omitempty"`
|
||||
UserID string `json:"userId,omitempty"`
|
||||
APIKey string `json:"apiKey,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
DomainKey string `json:"domainKey,omitempty"`
|
||||
|
||||
APIToken string `json:"apiToken,omitempty"`
|
||||
ZoneID string `json:"zoneId,omitempty"`
|
||||
AccessKeyID string `json:"accessKeyId,omitempty"`
|
||||
AccessKeySecret string `json:"accessKeySecret,omitempty"`
|
||||
SecretID string `json:"secretId,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
}
|
||||
|
||||
func Validate(provider string, credential Credential) error {
|
||||
provider = strings.ToLower(strings.TrimSpace(provider))
|
||||
switch provider {
|
||||
case "cloudflare":
|
||||
if !validSecret(credential.APIToken, 20, 512) || !validIdentifier(credential.ZoneID, 8, 128) {
|
||||
return errors.New("Cloudflare API Token 或 Zone ID 格式无效")
|
||||
}
|
||||
case "aliyun":
|
||||
if !validIdentifier(credential.AccessKeyID, 8, 128) || !validSecret(credential.AccessKeySecret, 16, 512) {
|
||||
return errors.New("阿里云 AccessKey ID 或 Secret 格式无效")
|
||||
}
|
||||
case "tencent":
|
||||
if !validIdentifier(credential.SecretID, 8, 128) || !validSecret(credential.SecretKey, 16, 512) {
|
||||
return errors.New("腾讯云 SecretId 或 SecretKey 格式无效")
|
||||
}
|
||||
case "west":
|
||||
if credential.DomainKey != "" {
|
||||
if !validSecret(credential.DomainKey, 8, 512) {
|
||||
return errors.New("西部数码单域名密钥格式无效")
|
||||
}
|
||||
} else if !validSecret(credential.Username, 1, 128) || !validSecret(credential.APIKey, 8, 512) {
|
||||
return errors.New("西部数码 API 用户名或 API 密码无效")
|
||||
}
|
||||
case "dnsmgr":
|
||||
if !positiveID(credential.UserID) || !validSecret(credential.APIKey, 8, 512) {
|
||||
return errors.New("彩虹 DNS 用户 ID 或密钥无效")
|
||||
}
|
||||
if _, err := publicEndpoint(credential.Endpoint); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return errors.New("不支持的 DNS 服务商")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func New(provider, zone string, credential Credential) (Provider, error) {
|
||||
if err := Validate(provider, credential); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 20 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(provider)) {
|
||||
case "cloudflare":
|
||||
return &cloudflare{client: client, token: credential.APIToken, zoneID: credential.ZoneID}, nil
|
||||
case "aliyun":
|
||||
return &aliyun{client: client, accessKeyID: credential.AccessKeyID, accessKeySecret: credential.AccessKeySecret, zone: zone, now: time.Now}, nil
|
||||
case "tencent":
|
||||
return &tencent{client: client, secretID: credential.SecretID, secretKey: credential.SecretKey, zone: zone, now: time.Now}, nil
|
||||
case "west":
|
||||
return &west{client: client, zone: zone, credential: credential, now: time.Now}, nil
|
||||
case "dnsmgr":
|
||||
return &dnsmgr{client: publicClient(), zone: zone, credential: credential, now: time.Now}, nil
|
||||
default:
|
||||
return nil, errors.New("不支持的 DNS 服务商")
|
||||
}
|
||||
}
|
||||
|
||||
func validSecret(value string, min, max int) bool {
|
||||
if value != strings.TrimSpace(value) || strings.ContainsAny(value, "\r\n\x00") {
|
||||
return false
|
||||
}
|
||||
return len(value) >= min && len(value) <= max && !strings.ContainsAny(value, "\r\n\x00")
|
||||
}
|
||||
|
||||
func validIdentifier(value string, min, max int) bool {
|
||||
if value != strings.TrimSpace(value) {
|
||||
return false
|
||||
}
|
||||
if len(value) < min || len(value) > max {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if !(char >= 'a' && char <= 'z') && !(char >= 'A' && char <= 'Z') && !(char >= '0' && char <= '9') && char != '-' && char != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func relativeRecordName(fqdn, zone string) (string, error) {
|
||||
fqdn = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(fqdn), "."))
|
||||
zone = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(zone), "."))
|
||||
if fqdn == zone {
|
||||
return "@", nil
|
||||
}
|
||||
suffix := "." + zone
|
||||
if !strings.HasSuffix(fqdn, suffix) {
|
||||
return "", errors.New("DNS 记录不属于凭据区域")
|
||||
}
|
||||
return strings.TrimSuffix(fqdn, suffix), nil
|
||||
}
|
||||
|
||||
type cloudflare struct {
|
||||
client *http.Client
|
||||
token string
|
||||
zoneID string
|
||||
baseURL string
|
||||
}
|
||||
|
||||
func (p *cloudflare) endpoint(path string) string {
|
||||
base := p.baseURL
|
||||
if base == "" {
|
||||
base = "https://api.cloudflare.com/client/v4"
|
||||
}
|
||||
return strings.TrimSuffix(base, "/") + "/zones/" + url.PathEscape(p.zoneID) + "/dns_records" + path
|
||||
}
|
||||
|
||||
func (p *cloudflare) Present(ctx context.Context, fqdn, value string) (string, error) {
|
||||
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
||||
}
|
||||
|
||||
func (p *cloudflare) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
|
||||
if err := validateRecord(recordType, value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]any{"type": recordType, "name": fqdn, "content": value, "ttl": 120, "proxied": false})
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint(""), bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+p.token)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
Result struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err = doJSON(p.client, request, &response); err != nil || !response.Success || response.Result.ID == "" {
|
||||
if err == nil {
|
||||
err = errors.New("Cloudflare 未返回记录编号")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return response.Result.ID, nil
|
||||
}
|
||||
|
||||
func (p *cloudflare) Cleanup(ctx context.Context, recordID string) error {
|
||||
if !validIdentifier(recordID, 1, 128) {
|
||||
return errors.New("Cloudflare 记录编号无效")
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, p.endpoint("/"+url.PathEscape(recordID)), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+p.token)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
if err = doJSON(p.client, request, &response); err != nil {
|
||||
return err
|
||||
}
|
||||
if !response.Success {
|
||||
return errors.New("Cloudflare 删除 DNS 记录失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type aliyun struct {
|
||||
client *http.Client
|
||||
accessKeyID, accessKeySecret string
|
||||
zone, baseURL string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func (p *aliyun) Present(ctx context.Context, fqdn, value string) (string, error) {
|
||||
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
||||
}
|
||||
|
||||
func (p *aliyun) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
|
||||
if err := validateRecord(recordType, value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
rr, err := relativeRecordName(fqdn, p.zone)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var response struct {
|
||||
RecordID string `json:"RecordId"`
|
||||
}
|
||||
err = p.call(ctx, "AddDomainRecord", url.Values{"DomainName": {p.zone}, "RR": {rr}, "Type": {recordType}, "Value": {value}, "TTL": {"600"}}, &response)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response.RecordID == "" {
|
||||
return "", errors.New("阿里云未返回记录编号")
|
||||
}
|
||||
return response.RecordID, nil
|
||||
}
|
||||
|
||||
func (p *aliyun) Cleanup(ctx context.Context, recordID string) error {
|
||||
if !validIdentifier(recordID, 1, 128) {
|
||||
return errors.New("阿里云记录编号无效")
|
||||
}
|
||||
var response struct {
|
||||
Code string `json:"Code"`
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
if err := p.call(ctx, "DeleteDomainRecord", url.Values{"RecordId": {recordID}}, &response); err != nil {
|
||||
return err
|
||||
}
|
||||
if response.Code != "" {
|
||||
return &providerError{Code: response.Code, Message: response.Message}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *aliyun) call(ctx context.Context, action string, query url.Values, output any) error {
|
||||
host := "dns.aliyuncs.com"
|
||||
base := p.baseURL
|
||||
if base == "" {
|
||||
base = "https://" + host
|
||||
}
|
||||
parsed, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if parsed.Host != "" {
|
||||
host = parsed.Host
|
||||
}
|
||||
now := p.now().UTC()
|
||||
nonceBytes := make([]byte, 16)
|
||||
if _, err = rand.Read(nonceBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
payloadHash := sha256Hex(nil)
|
||||
headers := map[string]string{
|
||||
"host": host,
|
||||
"x-acs-action": action,
|
||||
"x-acs-content-sha256": payloadHash,
|
||||
"x-acs-date": now.Format("2006-01-02T15:04:05Z"),
|
||||
"x-acs-signature-nonce": hex.EncodeToString(nonceBytes),
|
||||
"x-acs-version": "2015-01-09",
|
||||
}
|
||||
signed := "host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version"
|
||||
canonicalHeaders := "host:" + headers["host"] + "\n" + "x-acs-action:" + headers["x-acs-action"] + "\n" + "x-acs-content-sha256:" + headers["x-acs-content-sha256"] + "\n" + "x-acs-date:" + headers["x-acs-date"] + "\n" + "x-acs-signature-nonce:" + headers["x-acs-signature-nonce"] + "\n" + "x-acs-version:" + headers["x-acs-version"] + "\n"
|
||||
canonical := "POST\n/\n" + query.Encode() + "\n" + canonicalHeaders + "\n" + signed + "\n" + payloadHash
|
||||
stringToSign := "ACS3-HMAC-SHA256\n" + sha256Hex([]byte(canonical))
|
||||
signature := hmacHex([]byte(p.accessKeySecret), stringToSign)
|
||||
parsed.RawQuery = query.Encode()
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), http.NoBody)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for name, value := range headers {
|
||||
request.Header.Set(name, value)
|
||||
}
|
||||
request.Header.Set("Authorization", "ACS3-HMAC-SHA256 Credential="+p.accessKeyID+",SignedHeaders="+signed+",Signature="+signature)
|
||||
return doJSON(p.client, request, output)
|
||||
}
|
||||
|
||||
type tencent struct {
|
||||
client *http.Client
|
||||
secretID, secretKey string
|
||||
zone, baseURL string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func (p *tencent) Present(ctx context.Context, fqdn, value string) (string, error) {
|
||||
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
||||
}
|
||||
|
||||
func (p *tencent) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
|
||||
if err := validateRecord(recordType, value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
rr, err := relativeRecordName(fqdn, p.zone)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var response struct {
|
||||
Response struct {
|
||||
RecordID uint64 `json:"RecordId"`
|
||||
Error *providerError `json:"Error"`
|
||||
} `json:"Response"`
|
||||
}
|
||||
err = p.call(ctx, "CreateRecord", map[string]any{"Domain": p.zone, "SubDomain": rr, "RecordType": recordType, "RecordLine": "默认", "Value": value, "TTL": 600}, &response)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response.Response.Error != nil {
|
||||
return "", response.Response.Error
|
||||
}
|
||||
if response.Response.RecordID == 0 {
|
||||
return "", errors.New("腾讯云未返回记录编号")
|
||||
}
|
||||
return strconv.FormatUint(response.Response.RecordID, 10), nil
|
||||
}
|
||||
|
||||
func (p *tencent) Cleanup(ctx context.Context, recordID string) error {
|
||||
id, err := strconv.ParseUint(recordID, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return errors.New("腾讯云记录编号无效")
|
||||
}
|
||||
var response struct {
|
||||
Response struct {
|
||||
Error *providerError `json:"Error"`
|
||||
} `json:"Response"`
|
||||
}
|
||||
if err = p.call(ctx, "DeleteRecord", map[string]any{"Domain": p.zone, "RecordId": id}, &response); err != nil {
|
||||
return err
|
||||
}
|
||||
if response.Response.Error != nil {
|
||||
return response.Response.Error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *tencent) call(ctx context.Context, action string, input any, output any) error {
|
||||
payload, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
host := "dnspod.tencentcloudapi.com"
|
||||
endpoint := p.baseURL
|
||||
if endpoint == "" {
|
||||
endpoint = "https://" + host
|
||||
}
|
||||
parsed, err := url.Parse(endpoint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if parsed.Host != "" {
|
||||
host = parsed.Host
|
||||
}
|
||||
now := p.now().UTC()
|
||||
timestamp := strconv.FormatInt(now.Unix(), 10)
|
||||
contentType := "application/json; charset=utf-8"
|
||||
canonicalHeaders := "content-type:" + contentType + "\n" + "host:" + host + "\n" + "x-tc-action:" + strings.ToLower(action) + "\n"
|
||||
signedHeaders := "content-type;host;x-tc-action"
|
||||
canonical := "POST\n/\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + sha256Hex(payload)
|
||||
date := now.Format("2006-01-02")
|
||||
scope := date + "/dnspod/tc3_request"
|
||||
stringToSign := "TC3-HMAC-SHA256\n" + timestamp + "\n" + scope + "\n" + sha256Hex([]byte(canonical))
|
||||
secretDate := hmacBytes([]byte("TC3"+p.secretKey), date)
|
||||
secretService := hmacBytes(secretDate, "dnspod")
|
||||
secretSigning := hmacBytes(secretService, "tc3_request")
|
||||
signature := hmacHex(secretSigning, stringToSign)
|
||||
authorization := "TC3-HMAC-SHA256 Credential=" + p.secretID + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Authorization", authorization)
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
request.Header.Set("X-TC-Action", action)
|
||||
request.Header.Set("X-TC-Timestamp", timestamp)
|
||||
request.Header.Set("X-TC-Version", "2021-03-23")
|
||||
return doJSON(p.client, request, output)
|
||||
}
|
||||
|
||||
type providerError struct{ Code, Message string }
|
||||
|
||||
func (e *providerError) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.Code == "" {
|
||||
return "DNS 服务商拒绝请求"
|
||||
}
|
||||
return "DNS 服务商返回错误 " + e.Code
|
||||
}
|
||||
|
||||
func doJSON(client *http.Client, request *http.Request, output any) error {
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return errors.New("无法连接 DNS 服务商")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return errors.New("读取 DNS 服务商响应失败")
|
||||
}
|
||||
if len(body) > maxResponseBytes {
|
||||
return errors.New("DNS 服务商响应过大")
|
||||
}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return fmt.Errorf("DNS 服务商返回 HTTP %d", response.StatusCode)
|
||||
}
|
||||
if err = json.Unmarshal(body, output); err != nil {
|
||||
return errors.New("DNS 服务商响应格式无效")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sha256Hex(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
|
||||
func hmacBytes(key []byte, value string) []byte {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
_, _ = mac.Write([]byte(value))
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
func hmacHex(key []byte, value string) string { return hex.EncodeToString(hmacBytes(key, value)) }
|
||||
|
||||
func validateRecord(recordType, value string) error {
|
||||
recordType = strings.ToUpper(strings.TrimSpace(recordType))
|
||||
value = strings.TrimSpace(value)
|
||||
if recordType != "TXT" && recordType != "A" && recordType != "AAAA" && recordType != "CNAME" {
|
||||
return errors.New("DNS record type is not supported")
|
||||
}
|
||||
if value == "" || len(value) > 1024 || strings.ContainsAny(value, "\r\n\x00") {
|
||||
return errors.New("DNS record value is invalid")
|
||||
}
|
||||
if recordType == "A" && net.ParseIP(value).To4() == nil {
|
||||
return errors.New("DNS A record requires IPv4")
|
||||
}
|
||||
if recordType == "AAAA" {
|
||||
ip := net.ParseIP(value)
|
||||
if ip == nil || ip.To4() != nil {
|
||||
return errors.New("DNS AAAA record requires IPv6")
|
||||
}
|
||||
}
|
||||
if recordType == "CNAME" && !brokerCompatibleDomainValue(value) {
|
||||
return errors.New("DNS CNAME value is invalid")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func brokerCompatibleDomainValue(value string) bool {
|
||||
value = strings.ToLower(strings.TrimSuffix(value, "."))
|
||||
if len(value) < 3 || len(value) > 253 || strings.ContainsAny(value, " /\\:\t") {
|
||||
return false
|
||||
}
|
||||
return strings.Contains(value, ".")
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRelativeRecordName(t *testing.T) {
|
||||
name, err := relativeRecordName("_acme-challenge.app.example.com", "example.com")
|
||||
if err != nil || name != "_acme-challenge.app" {
|
||||
t.Fatalf("name=%q err=%v", name, err)
|
||||
}
|
||||
if _, err = relativeRecordName("_acme-challenge.evil.example", "example.com"); err == nil {
|
||||
t.Fatal("expected zone boundary error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliyunCleanupDoesNotTreatProviderRejectionAsSuccess(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"Code":"Forbidden","Message":"denied"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := &aliyun{client: server.Client(), accessKeyID: "test", accessKeySecret: "test", zone: "example.com", baseURL: server.URL, now: time.Now}
|
||||
if err := provider.Cleanup(context.Background(), "record_123"); err == nil {
|
||||
t.Fatal("provider rejection treated as successful deletion")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloudflarePresentAndCleanup(t *testing.T) {
|
||||
var created bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 24) {
|
||||
t.Error("missing bearer token")
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
created = true
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["name"] != "_acme-challenge.example.com" || body["type"] != "TXT" {
|
||||
t.Errorf("unexpected body: %#v", body)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"result":{"id":"record_123"}}`))
|
||||
case http.MethodDelete:
|
||||
if !created || !strings.HasSuffix(r.URL.Path, "/record_123") {
|
||||
t.Errorf("unexpected cleanup path: %s", r.URL.Path)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := &cloudflare{client: server.Client(), token: strings.Repeat("t", 24), zoneID: "zone_123456", baseURL: server.URL}
|
||||
recordID, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof")
|
||||
if err != nil || recordID != "record_123" {
|
||||
t.Fatalf("record=%q err=%v", recordID, err)
|
||||
}
|
||||
if err = provider.Cleanup(context.Background(), recordID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloudflareCreatesCNAMEWithoutProxying(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["name"] != "app.example.com" || body["type"] != "CNAME" || body["content"] != "target.vhost.example" || body["proxied"] != false {
|
||||
t.Errorf("unexpected body: %#v", body)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"result":{"id":"cname_123"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := &cloudflare{client: server.Client(), token: strings.Repeat("t", 24), zoneID: "zone_123456", baseURL: server.URL}
|
||||
recordID, err := provider.CreateRecord(context.Background(), "app.example.com", "CNAME", "target.vhost.example")
|
||||
if err != nil || recordID != "cname_123" {
|
||||
t.Fatalf("record=%q err=%v", recordID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRecordRejectsInvalidAddressAndCNAME(t *testing.T) {
|
||||
for _, input := range []struct{ recordType, value string }{{"A", "2001:db8::1"}, {"AAAA", "192.0.2.1"}, {"CNAME", "not-a-domain"}, {"MX", "mail.example.com"}} {
|
||||
if err := validateRecord(input.recordType, input.value); err == nil {
|
||||
t.Fatalf("accepted invalid %s value %q", input.recordType, input.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliyunSignedRequests(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasPrefix(r.Header.Get("Authorization"), "ACS3-HMAC-SHA256 Credential=accessKey123") {
|
||||
t.Error("missing Aliyun V3 signature")
|
||||
}
|
||||
switch r.Header.Get("x-acs-action") {
|
||||
case "AddDomainRecord":
|
||||
if r.URL.Query().Get("RR") != "_acme-challenge.app" || r.URL.Query().Get("DomainName") != "example.com" {
|
||||
t.Errorf("unexpected query: %s", r.URL.RawQuery)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"RecordId":"9988"}`))
|
||||
case "DeleteDomainRecord":
|
||||
if r.URL.Query().Get("RecordId") != "9988" {
|
||||
t.Errorf("unexpected record id")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"RequestId":"ok"}`))
|
||||
default:
|
||||
t.Errorf("unexpected action")
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := &aliyun{client: server.Client(), accessKeyID: "accessKey123", accessKeySecret: strings.Repeat("s", 20), zone: "example.com", baseURL: server.URL, now: func() time.Time { return time.Unix(1700000000, 0) }}
|
||||
recordID, err := provider.Present(context.Background(), "_acme-challenge.app.example.com", "proof")
|
||||
if err != nil || recordID != "9988" {
|
||||
t.Fatalf("record=%q err=%v", recordID, err)
|
||||
}
|
||||
if err = provider.Cleanup(context.Background(), recordID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTencentSignedRequests(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasPrefix(r.Header.Get("Authorization"), "TC3-HMAC-SHA256 Credential=secretId123/") {
|
||||
t.Error("missing Tencent V3 signature")
|
||||
}
|
||||
switch r.Header.Get("X-Tc-Action") {
|
||||
case "CreateRecord":
|
||||
_, _ = w.Write([]byte(`{"Response":{"RecordId":7788,"RequestId":"ok"}}`))
|
||||
case "DeleteRecord":
|
||||
_, _ = w.Write([]byte(`{"Response":{"RequestId":"ok"}}`))
|
||||
default:
|
||||
t.Errorf("unexpected action %q", r.Header.Get("X-Tc-Action"))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := &tencent{client: server.Client(), secretID: "secretId123", secretKey: strings.Repeat("k", 20), zone: "example.com", baseURL: server.URL, now: func() time.Time { return time.Unix(1700000000, 0) }}
|
||||
recordID, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof")
|
||||
if err != nil || recordID != "7788" {
|
||||
t.Fatalf("record=%q err=%v", recordID, err)
|
||||
}
|
||||
if err = provider.Cleanup(context.Background(), recordID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsUnknownProviderAndHeaderInjection(t *testing.T) {
|
||||
if err := Validate("unknown", Credential{}); err == nil {
|
||||
t.Fatal("expected provider error")
|
||||
}
|
||||
if err := Validate("cloudflare", Credential{ZoneID: "zone_123456", APIToken: strings.Repeat("x", 20) + "\n"}); err == nil {
|
||||
t.Fatal("expected secret validation error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func publicEndpoint(raw string) (*url.URL, error) {
|
||||
u, e := url.Parse(raw)
|
||||
if e != nil || len(raw) > 512 || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") || strings.ContainsAny(raw, "\r\n\x00") || strings.ContainsAny(u.Path, "?#\\") || strings.EqualFold(u.Hostname(), "localhost") {
|
||||
return nil, errors.New("DNS API 地址必须为 HTTPS 公网地址,端口为 443,不能包含查询参数或身份信息")
|
||||
}
|
||||
if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicIP(ip) {
|
||||
return nil, errors.New("DNS API 禁止访问内网或保留地址")
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
func publicIP(ip netip.Addr) bool {
|
||||
ip = ip.Unmap()
|
||||
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
for _, v := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "::/96", "64:ff9b::/96", "64:ff9b:1::/48", "2001:db8::/32", "2001::/32", "2002::/16"} {
|
||||
if netip.MustParsePrefix(v).Contains(ip) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func publicClient() *http.Client {
|
||||
transport := &http.Transport{Proxy: nil, TLSHandshakeTimeout: 8 * time.Second, ResponseHeaderTimeout: 15 * time.Second, MaxIdleConnsPerHost: 2, IdleConnTimeout: 20 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, e := net.SplitHostPort(address)
|
||||
if e != nil || port != "443" {
|
||||
return nil, errors.New("restricted DNS endpoint")
|
||||
}
|
||||
ips, e := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
|
||||
if e != nil || len(ips) == 0 {
|
||||
return nil, errors.New("DNS API 域名无法解析")
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if !publicIP(ip) {
|
||||
return nil, errors.New("DNS API 域名解析到受限地址")
|
||||
}
|
||||
}
|
||||
var last error
|
||||
for _, ip := range ips {
|
||||
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), port))
|
||||
if e == nil {
|
||||
return conn, nil
|
||||
}
|
||||
last = e
|
||||
}
|
||||
return nil, last
|
||||
}}
|
||||
return &http.Client{Transport: transport, Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type west struct {
|
||||
client *http.Client
|
||||
zone, baseURL string
|
||||
credential Credential
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func (p *west) call(ctx context.Context, action string, v url.Values, out any) error {
|
||||
base := p.baseURL
|
||||
if base == "" {
|
||||
base = "https://api.west.cn/API/v2"
|
||||
}
|
||||
endpoint := base + "/domain/"
|
||||
v.Set("act", action)
|
||||
if p.credential.DomainKey != "" {
|
||||
endpoint += "dns/"
|
||||
v.Set("apidomainkey", p.credential.DomainKey)
|
||||
} else {
|
||||
stamp := strconv.FormatInt(p.now().UnixMilli(), 10)
|
||||
v.Set("username", p.credential.Username)
|
||||
v.Set("time", stamp)
|
||||
v.Set("token", md5Hex(p.credential.Username+p.credential.APIKey+stamp))
|
||||
}
|
||||
req, e := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(v.Encode()))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
var response struct {
|
||||
Result int `json:"result"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if e = doJSON(p.client, req, &response); e != nil {
|
||||
return e
|
||||
}
|
||||
if response.Result != 200 {
|
||||
return errors.New("西部数码拒绝请求,请检查 API 密码、单域名密钥或白名单")
|
||||
}
|
||||
if out == nil {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(response.Data, out)
|
||||
}
|
||||
func (p *west) Present(ctx context.Context, fqdn, value string) (string, error) {
|
||||
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
||||
}
|
||||
|
||||
type westRecord struct {
|
||||
ID json.RawMessage `json:"record_id"`
|
||||
Hostname string `json:"hostname"`
|
||||
Type string `json:"record_type"`
|
||||
Value string `json:"record_value"`
|
||||
}
|
||||
|
||||
func (p *west) modernRecords(ctx context.Context, fqdn, kind string) ([]westRecord, error) {
|
||||
var data json.RawMessage
|
||||
if e := p.call(ctx, "dnsrec.list", url.Values{"domain": {p.zone}, "hostname": {fqdn}, "record_type": {kind}}, &data); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var list []westRecord
|
||||
if json.Unmarshal(data, &list) == nil {
|
||||
return list, nil
|
||||
}
|
||||
var wrapped struct {
|
||||
Items []westRecord `json:"items"`
|
||||
List []westRecord `json:"list"`
|
||||
Records []westRecord `json:"records"`
|
||||
}
|
||||
if json.Unmarshal(data, &wrapped) != nil {
|
||||
return nil, errors.New("西部数码记录响应无效")
|
||||
}
|
||||
if wrapped.Items != nil {
|
||||
return wrapped.Items, nil
|
||||
}
|
||||
if wrapped.List != nil {
|
||||
return wrapped.List, nil
|
||||
}
|
||||
if wrapped.Records != nil {
|
||||
return wrapped.Records, nil
|
||||
}
|
||||
return nil, errors.New("西部数码未返回解析记录列表")
|
||||
}
|
||||
func (p *west) CreateRecord(ctx context.Context, fqdn, kind, value string) (string, error) {
|
||||
if e := validateRecord(kind, value); e != nil {
|
||||
return "", e
|
||||
}
|
||||
rr, e := relativeRecordName(fqdn, p.zone)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
if p.credential.DomainKey == "" {
|
||||
var out struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
}
|
||||
if e = p.call(ctx, "adddnsrecord", url.Values{"domain": {p.zone}, "host": {rr}, "type": {kind}, "value": {value}, "ttl": {"600"}, "line": {""}}, &out); e != nil {
|
||||
return "", e
|
||||
}
|
||||
id := rawID(out.ID)
|
||||
if !validIdentifier(id, 1, 128) {
|
||||
return "", errors.New("西部数码未返回新增记录编号")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
before, e := p.modernRecords(ctx, fqdn, kind)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
old := map[string]bool{}
|
||||
for _, r := range before {
|
||||
old[rawID(r.ID)] = true
|
||||
}
|
||||
if e = p.call(ctx, "dnsrec.add", url.Values{"domain": {p.zone}, "hostname": {fqdn}, "record_type": {kind}, "record_value": {value}, "ttl": {"600"}}, nil); e != nil {
|
||||
return "", e
|
||||
}
|
||||
after, e := p.modernRecords(ctx, fqdn, kind)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
for _, r := range after {
|
||||
id := rawID(r.ID)
|
||||
if !old[id] && validIdentifier(id, 1, 128) && r.Hostname == fqdn && r.Type == kind && r.Value == value {
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(fqdn + "|" + id)), nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("西部数码已接受创建,但未能核对新增记录编号,请管理员核验")
|
||||
}
|
||||
func (p *west) Cleanup(ctx context.Context, id string) error {
|
||||
v := url.Values{"domain": {p.zone}}
|
||||
action := "deldnsrecord"
|
||||
if p.credential.DomainKey != "" {
|
||||
raw, e := base64.RawURLEncoding.DecodeString(id)
|
||||
if e != nil {
|
||||
return errors.New("西部数码记录标识无效")
|
||||
}
|
||||
parts := strings.Split(string(raw), "|")
|
||||
if len(parts) != 2 {
|
||||
return errors.New("西部数码记录标识无效")
|
||||
}
|
||||
if _, e = relativeRecordName(parts[0], p.zone); e != nil {
|
||||
return e
|
||||
}
|
||||
id = parts[1]
|
||||
action = "dnsrec.remove"
|
||||
v.Set("hostname", parts[0])
|
||||
v.Set("record_id", id)
|
||||
} else {
|
||||
v.Set("id", id)
|
||||
}
|
||||
if !validIdentifier(id, 1, 128) {
|
||||
return errors.New("西部数码记录编号无效")
|
||||
}
|
||||
return p.call(ctx, action, v, nil)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package dnsprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Zone struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func DiscoverZones(ctx context.Context, name string, c Credential, hint string) ([]Zone, error) {
|
||||
if name == "cloudflare" && c.ZoneID == "" {
|
||||
c.ZoneID = "discovery"
|
||||
}
|
||||
provider, err := New(name, hint, c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 40*time.Second)
|
||||
defer cancel()
|
||||
all := []Zone{}
|
||||
for page := 1; page <= 20; page++ {
|
||||
total := 0
|
||||
switch p := provider.(type) {
|
||||
case *cloudflare:
|
||||
var out struct {
|
||||
Success bool `json:"success"`
|
||||
Result []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"result"`
|
||||
Info struct {
|
||||
TotalCount int `json:"total_count"`
|
||||
} `json:"result_info"`
|
||||
}
|
||||
req, e := http.NewRequestWithContext(ctx, "GET", "https://api.cloudflare.com/client/v4/zones?per_page=100&page="+strconv.Itoa(page), nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.APIToken)
|
||||
if e = doJSON(p.client, req, &out); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if !out.Success {
|
||||
return nil, errors.New("Cloudflare 未授权读取 DNS 区域")
|
||||
}
|
||||
for _, z := range out.Result {
|
||||
all = append(all, Zone{z.ID, z.Name})
|
||||
}
|
||||
total = out.Info.TotalCount
|
||||
case *aliyun:
|
||||
var out struct {
|
||||
Code string `json:"Code"`
|
||||
TotalCount int `json:"TotalCount"`
|
||||
Domains struct {
|
||||
Domain []struct {
|
||||
Name string `json:"DomainName"`
|
||||
} `json:"Domain"`
|
||||
} `json:"Domains"`
|
||||
}
|
||||
if e := p.call(ctx, "DescribeDomains", url.Values{"PageNumber": {strconv.Itoa(page)}, "PageSize": {"100"}}, &out); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if out.Code != "" {
|
||||
return nil, errors.New("阿里云未授权读取域名列表")
|
||||
}
|
||||
for _, z := range out.Domains.Domain {
|
||||
all = append(all, Zone{z.Name, z.Name})
|
||||
}
|
||||
total = out.TotalCount
|
||||
case *tencent:
|
||||
var out struct {
|
||||
Response struct {
|
||||
Error *providerError `json:"Error"`
|
||||
Count int `json:"DomainCountInfoAll"`
|
||||
DomainCount struct {
|
||||
All int `json:"AllTotal"`
|
||||
} `json:"DomainCountInfo"`
|
||||
Domains []struct {
|
||||
ID uint64 `json:"DomainId"`
|
||||
Name string `json:"Name"`
|
||||
} `json:"DomainList"`
|
||||
} `json:"Response"`
|
||||
}
|
||||
if e := p.call(ctx, "DescribeDomainList", map[string]any{"Offset": (page - 1) * 100, "Limit": 100}, &out); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if out.Response.Error != nil {
|
||||
return nil, out.Response.Error
|
||||
}
|
||||
for _, z := range out.Response.Domains {
|
||||
all = append(all, Zone{strconv.FormatUint(z.ID, 10), z.Name})
|
||||
}
|
||||
total = out.Response.DomainCount.All
|
||||
case *west:
|
||||
if c.DomainKey != "" {
|
||||
if hint == "" {
|
||||
return nil, errors.New("单域名密钥请先填写指定域名")
|
||||
}
|
||||
if _, e := p.modernRecords(ctx, hint, "TXT"); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return []Zone{{hint, hint}}, nil
|
||||
}
|
||||
var out struct {
|
||||
Total int `json:"total"`
|
||||
Items []struct {
|
||||
Domain string `json:"domain"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if e := p.call(ctx, "getdomains", url.Values{"page": {strconv.Itoa(page)}, "limit": {"100"}}, &out); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for _, z := range out.Items {
|
||||
all = append(all, Zone{z.Domain, z.Domain})
|
||||
}
|
||||
total = out.Total
|
||||
case *dnsmgr:
|
||||
var out struct {
|
||||
Total *int `json:"total"`
|
||||
Rows []struct {
|
||||
ID jsonID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"rows"`
|
||||
}
|
||||
if e := p.call(ctx, "domain", url.Values{"offset": {strconv.Itoa((page - 1) * 100)}, "limit": {"100"}}, &out); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if out.Total == nil {
|
||||
return nil, errors.New("彩虹 DNS 未返回域名列表")
|
||||
}
|
||||
for _, z := range out.Rows {
|
||||
all = append(all, Zone{string(z.ID), z.Name})
|
||||
}
|
||||
total = *out.Total
|
||||
default:
|
||||
return nil, errors.New("服务商不支持读取区域列表")
|
||||
}
|
||||
if len(all) >= total {
|
||||
return normalizeZones(all), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("域名数量超过 2000,请使用权限更小的 API 票据")
|
||||
}
|
||||
|
||||
type jsonID string
|
||||
|
||||
func (v *jsonID) UnmarshalJSON(raw []byte) error {
|
||||
id := rawID(raw)
|
||||
if !positiveID(id) {
|
||||
return errors.New("域名编号无效")
|
||||
}
|
||||
*v = jsonID(id)
|
||||
return nil
|
||||
}
|
||||
func normalizeZones(items []Zone) []Zone {
|
||||
out := []Zone{}
|
||||
seen := map[string]bool{}
|
||||
for _, z := range items {
|
||||
z.Name = strings.ToLower(strings.TrimSuffix(z.Name, "."))
|
||||
if z.ID != "" && z.Name != "" && !seen[z.Name] {
|
||||
out = append(out, z)
|
||||
seen[z.Name] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in new issue
Block a user