This commit is contained in:
Meghdad committed 2026-07-12 23:06:00 +03:30
commit eb115daf3b
76 files changed
+22739

No files matched your search

+295
View File
@@ -0,0 +1,295 @@
// Package cloudflare implements DomainOps' provider contracts against the
// documented Cloudflare v4 REST API.
package cloudflare
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
const (
defaultBaseURL = "https://api.cloudflare.com/client/v4/"
defaultUserAgent = "DomainOps/1"
defaultRequestLimit = int64(16 << 20)
)
// HTTPDoer is the portion of http.Client used by Client. It is deliberately
// small so callers can inject tracing, rate limiting, or a deterministic test
// transport without changing provider code.
type HTTPDoer interface {
Do(*http.Request) (*http.Response, error)
}
// Options customizes a Client. BaseURL and HTTPClient are principally useful
// for integration tests and trusted Cloudflare-compatible gateways.
type Options struct {
BaseURL string
HTTPClient HTTPDoer
UserAgent string
Now func() time.Time
}
// Client implements provider.CloudProvider.
type Client struct {
baseURL string
httpClient HTTPDoer
userAgent string
now func() time.Time
}
var _ provider.CloudProvider = (*Client)(nil)
// New returns a production Cloudflare client.
func New() *Client {
c, err := NewWithOptions(Options{})
if err != nil {
// All defaults are compile-time constants, so this can only indicate a
// programming error in this package.
panic(err)
}
return c
}
// NewWithOptions returns a Cloudflare client with injectable HTTP behavior.
func NewWithOptions(opts Options) (*Client, error) {
base := strings.TrimSpace(opts.BaseURL)
if base == "" {
base = defaultBaseURL
}
u, err := url.Parse(base)
if err != nil {
return nil, fmt.Errorf("cloudflare: invalid base URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return nil, fmt.Errorf("cloudflare: base URL must use http or https")
}
if u.Host == "" {
return nil, fmt.Errorf("cloudflare: base URL must include a host")
}
if u.User != nil {
return nil, fmt.Errorf("cloudflare: base URL cannot include user information")
}
if u.RawQuery != "" || u.Fragment != "" {
return nil, fmt.Errorf("cloudflare: base URL cannot include a query or fragment")
}
if !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
}
doer := opts.HTTPClient
if doer == nil {
doer = &http.Client{Timeout: 30 * time.Second}
}
userAgent := strings.TrimSpace(opts.UserAgent)
if userAgent == "" {
userAgent = defaultUserAgent
}
now := opts.Now
if now == nil {
now = time.Now
}
return &Client{
baseURL: u.String(),
httpClient: doer,
userAgent: userAgent,
now: now,
}, nil
}
type responseEnvelope struct {
Success *bool `json:"success"`
Errors []apiMessage `json:"errors"`
Messages []apiMessage `json:"messages"`
Result json.RawMessage `json:"result"`
ResultInfo resultInfo `json:"result_info"`
}
type apiMessage struct {
Code int `json:"code"`
Message string `json:"message"`
DocumentationURL string `json:"documentation_url"`
Source messageSource `json:"source"`
ErrorChain []apiMessage `json:"error_chain"`
}
type messageSource struct {
Pointer string `json:"pointer"`
}
type resultInfo struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Count int `json:"count"`
TotalCount int `json:"total_count"`
TotalPages int `json:"total_pages"`
Cursors struct {
Before string `json:"before"`
After string `json:"after"`
} `json:"cursors"`
}
func (c *Client) do(
ctx context.Context,
auth provider.Auth,
method string,
path string,
query url.Values,
body any,
) (json.RawMessage, resultInfo, error) {
if err := validateAuth(auth); err != nil {
return nil, resultInfo{}, err
}
endpoint := c.baseURL + strings.TrimPrefix(path, "/")
if len(query) > 0 {
endpoint += "?" + query.Encode()
}
var requestBody io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: encode request: %w", err)
}
requestBody = bytes.NewReader(encoded)
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, requestBody)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: create request: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(auth.Token))
req.Header.Set("User-Agent", c.userAgent)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: %s %s: %w", method, path, err)
}
defer resp.Body.Close()
limited := io.LimitReader(resp.Body, defaultRequestLimit+1)
payload, err := io.ReadAll(limited)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: read response: %w", err)
}
if int64(len(payload)) > defaultRequestLimit {
return nil, resultInfo{}, fmt.Errorf("cloudflare: response exceeded %d bytes", defaultRequestLimit)
}
var env responseEnvelope
decodeErr := json.Unmarshal(payload, &env)
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
apiErr := newAPIError(method, path, resp, env.Errors, env.Messages)
if decodeErr != nil || len(payload) == 0 {
apiErr.Message = http.StatusText(resp.StatusCode)
}
if resp.StatusCode == http.StatusTooManyRequests {
return nil, resultInfo{}, newRateLimitError(apiErr, resp.Header, c.now())
}
return nil, resultInfo{}, apiErr
}
if decodeErr != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: decode %s %s response: %w", method, path, decodeErr)
}
if env.Success == nil {
return nil, resultInfo{}, &ResponseError{
Resource: method + " " + path + " envelope",
Err: fmt.Errorf("required success field is missing or null"),
}
}
if !*env.Success {
return nil, resultInfo{}, newAPIError(method, path, resp, env.Errors, env.Messages)
}
return cloneRaw(env.Result), env.ResultInfo, nil
}
func validateAuth(auth provider.Auth) error {
if strings.TrimSpace(auth.Token) == "" {
return &ValidationError{Field: "token", Message: "API token is required"}
}
switch auth.Kind {
case domain.CredentialUserToken:
return nil
case domain.CredentialAccountToken:
if strings.TrimSpace(auth.AccountID) == "" {
return &ValidationError{Field: "account_id", Message: "account-owned tokens require an account ID"}
}
return nil
default:
return &ValidationError{Field: "kind", Message: "only scoped user and account API tokens are supported"}
}
}
func apiPath(segments ...string) (string, error) {
escaped := make([]string, len(segments))
for i, segment := range segments {
if strings.TrimSpace(segment) == "" {
return "", &ValidationError{Field: "identifier", Message: "Cloudflare identifier cannot be empty"}
}
escaped[i] = url.PathEscape(segment)
}
return strings.Join(escaped, "/"), nil
}
func paginationQuery(req provider.PageRequest, defaultPerPage, maxPerPage int) (url.Values, int) {
perPage := req.PerPage
if perPage <= 0 {
perPage = defaultPerPage
}
if perPage > maxPerPage {
perPage = maxPerPage
}
page := req.Page
if page <= 0 {
page = 1
}
q := url.Values{
"page": {strconv.Itoa(page)},
"per_page": {strconv.Itoa(perPage)},
}
if req.Cursor != "" {
if cursorPage, err := strconv.Atoi(req.Cursor); err == nil && cursorPage > 0 {
page = cursorPage
q.Set("page", strconv.Itoa(page))
} else {
q.Set("cursor", req.Cursor)
}
}
return q, page
}
func nextCursor(info resultInfo, page, resultCount, perPage int) string {
if info.Cursors.After != "" {
return info.Cursors.After
}
if info.TotalPages > page {
return strconv.Itoa(page + 1)
}
if info.TotalPages == 0 && perPage > 0 && resultCount == perPage {
return strconv.Itoa(page + 1)
}
return ""
}
func cloneRaw(raw json.RawMessage) json.RawMessage {
if len(raw) == 0 {
return nil
}
return append(json.RawMessage(nil), raw...)
}
@@ -0,0 +1,409 @@
package cloudflare
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
var fixedNow = time.Date(2026, time.July, 11, 9, 30, 0, 0, time.UTC)
func testAuth() provider.Auth {
return provider.Auth{
CredentialID: "cred-1",
Token: "test-secret-token",
Kind: domain.CredentialUserToken,
}
}
func newTestClient(t *testing.T, handler http.HandlerFunc) *Client {
t.Helper()
client, err := NewWithOptions(Options{
BaseURL: "https://api.cloudflare.test/client/v4",
HTTPClient: handlerDoer{handler: handler},
UserAgent: "DomainOps-test/1",
Now: func() time.Time { return fixedNow },
})
if err != nil {
t.Fatalf("NewWithOptions: %v", err)
}
return client
}
type handlerDoer struct{ handler http.Handler }
func (d handlerDoer) Do(request *http.Request) (*http.Response, error) {
recorder := httptest.NewRecorder()
d.handler.ServeHTTP(recorder, request)
return recorder.Result(), nil
}
func writeResult(t *testing.T, w http.ResponseWriter, result any, info any) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
response := map[string]any{
"success": true,
"errors": []any{},
"messages": []any{},
"result": result,
}
if info != nil {
response["result_info"] = info
}
if err := json.NewEncoder(w).Encode(response); err != nil {
t.Errorf("encode response: %v", err)
}
}
func verifyRequestHeaders(t *testing.T, r *http.Request) {
t.Helper()
if got := r.Header.Get("Authorization"); got != "Bearer test-secret-token" {
t.Errorf("Authorization = %q", got)
}
if got := r.Header.Get("User-Agent"); got != "DomainOps-test/1" {
t.Errorf("User-Agent = %q", got)
}
if got := r.Header.Get("Accept"); got != "application/json" {
t.Errorf("Accept = %q", got)
}
}
func TestNewWithOptionsRejectsInvalidBaseURL(t *testing.T) {
t.Parallel()
for _, baseURL := range []string{"ftp://api.example.test", "https:///missing-host", "https://example.test/?bad=1", "https://user:pass@example.test"} {
if _, err := NewWithOptions(Options{BaseURL: baseURL}); err == nil {
t.Errorf("NewWithOptions(%q) unexpectedly succeeded", baseURL)
}
}
}
func TestDNSNameConversionPreservesServiceAndWildcardLabels(t *testing.T) {
t.Parallel()
for input, want := range map[string]string{
"*.bücher.example.": "*.xn--bcher-kva.example",
"_acme-challenge.bücher.example.": "_acme-challenge.xn--bcher-kva.example",
} {
got, err := toASCIIName(input)
if err != nil {
t.Errorf("toASCIIName(%q): %v", input, err)
continue
}
if got != want {
t.Errorf("toASCIIName(%q) = %q, want %q", input, got, want)
}
}
}
func TestVerifyCredentialUserTokenAndCapabilityProbes(t *testing.T) {
t.Parallel()
var calls atomic.Int32
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
verifyRequestHeaders(t, r)
switch r.URL.Path {
case "/client/v4/user/tokens/verify":
writeResult(t, w, map[string]any{"id": "token-1", "status": "active"}, nil)
case "/client/v4/accounts":
writeResult(t, w, []any{
map[string]any{"id": "acct-1", "name": "Production", "created_on": "2024-01-02T03:04:05Z"},
map[string]any{"id": "acct-2", "name": "Labs"},
}, map[string]any{"page": 1, "per_page": 50, "total_pages": 1})
case "/client/v4/zones":
if got := r.URL.Query().Get("per_page"); got != "50" {
t.Errorf("zones per_page = %q", got)
}
writeResult(t, w, []any{map[string]any{
"id": "zone-1", "name": "example.com", "status": "active",
"account": map[string]any{"id": "acct-1", "name": "Production"},
}}, map[string]any{"page": 1, "total_pages": 1})
case "/client/v4/zones/zone-1/dns_records":
writeResult(t, w, []any{}, map[string]any{"page": 1, "total_pages": 1})
case "/client/v4/zones/zone-1/settings/ssl":
writeResult(t, w, map[string]any{"id": "ssl", "value": "strict"}, nil)
default:
http.NotFound(w, r)
}
})
verification, err := client.VerifyCredential(context.Background(), testAuth())
if err != nil {
t.Fatalf("VerifyCredential: %v", err)
}
if verification.Status != domain.CredentialValid {
t.Fatalf("status = %q", verification.Status)
}
capabilities := verification.Capabilities
if !capabilities.ZoneRead || !capabilities.DNSRead || capabilities.DNSWrite || !capabilities.TLSRead || capabilities.TLSWrite {
t.Errorf("capabilities = %+v", capabilities)
}
if got, want := strings.Join(capabilities.Names, ","), "dns:read,tls:read,zone:read"; got != want {
t.Errorf("capability names = %q, want %q", got, want)
}
if len(verification.Accounts) != 2 || verification.Accounts[0].ProviderID != "acct-1" {
t.Fatalf("accounts = %+v", verification.Accounts)
}
if verification.Accounts[0].LastSyncedAt == nil || !verification.Accounts[0].LastSyncedAt.Equal(fixedNow) {
t.Errorf("account sync timestamp = %v", verification.Accounts[0].LastSyncedAt)
}
if got := calls.Load(); got != 5 {
t.Errorf("request count = %d, want 5", got)
}
}
func TestVerifyCredentialAccountTokenUsesAccountNamespace(t *testing.T) {
t.Parallel()
auth := testAuth()
auth.Kind = domain.CredentialAccountToken
auth.AccountID = "account-owned"
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/client/v4/accounts/account-owned/tokens/verify":
writeResult(t, w, map[string]any{"id": "token-2", "status": "active"}, nil)
case "/client/v4/accounts/account-owned":
writeResult(t, w, map[string]any{"id": "account-owned", "name": "Owned account"}, nil)
case "/client/v4/zones":
if got := r.URL.Query().Get("account.id"); got != "account-owned" {
t.Errorf("account.id = %q", got)
}
writeResult(t, w, []any{}, map[string]any{"page": 1, "total_pages": 1})
default:
http.NotFound(w, r)
}
})
verification, err := client.VerifyCredential(context.Background(), auth)
if err != nil {
t.Fatalf("VerifyCredential: %v", err)
}
if verification.Status != domain.CredentialValid || len(verification.Accounts) != 1 {
t.Fatalf("verification = %+v", verification)
}
if !verification.Capabilities.ZoneRead || verification.Capabilities.DNSRead {
t.Errorf("capabilities = %+v", verification.Capabilities)
}
}
func TestVerifyCredentialInactiveAndRejectsUnsupportedAuth(t *testing.T) {
t.Parallel()
var requests atomic.Int32
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
writeResult(t, w, map[string]any{"id": "token", "status": "expired"}, nil)
})
verification, err := client.VerifyCredential(context.Background(), testAuth())
if err != nil {
t.Fatalf("expired token: %v", err)
}
if verification.Status != domain.CredentialInvalid || requests.Load() != 1 {
t.Fatalf("verification = %+v, requests = %d", verification, requests.Load())
}
bad := testAuth()
bad.Kind = domain.CredentialKind("global_api_key")
_, err = client.VerifyCredential(context.Background(), bad)
var validation *ValidationError
if !errors.As(err, &validation) || requests.Load() != 1 {
t.Fatalf("unsupported auth error = %v, requests = %d", err, requests.Load())
}
}
func TestListZonesPaginationAndMapping(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/client/v4/zones" {
http.NotFound(w, r)
return
}
if got := r.URL.Query().Get("page"); got != "2" {
t.Errorf("page = %q", got)
}
if got := r.URL.Query().Get("name"); got != "example.com" {
t.Errorf("name = %q", got)
}
writeResult(t, w, []any{map[string]any{
"id": "zone-2", "name": "xn--bcher-kva.example", "status": "mystery", "paused": true,
"modified_on": "2026-01-02T03:04:05.123Z",
"account": map[string]any{"id": "acct", "name": "Account"},
"plan": map[string]any{"name": "Pro"}, "name_servers": []string{"ada.ns.cloudflare.com"},
}}, map[string]any{"page": 2, "per_page": 1, "total_pages": 3})
})
page, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{Cursor: "2", PerPage: 1, Search: "example.com"})
if err != nil {
t.Fatalf("ListZones: %v", err)
}
if page.Page != 2 || page.NextCursor != "3" || page.TotalPages != 3 {
t.Errorf("page metadata = %+v", page)
}
if len(page.Zones) != 1 {
t.Fatalf("zones = %+v", page.Zones)
}
zone := page.Zones[0]
if zone.ID != "zone-2" || zone.ProviderID != "zone-2" || zone.AccountID != "acct" || zone.Status != domain.ZoneUnknown || zone.Plan != "Pro" || !zone.Paused {
t.Errorf("mapped zone = %+v", zone)
}
if zone.UnicodeName != "bücher.example" {
t.Errorf("unicode name = %q", zone.UnicodeName)
}
}
func TestStructuredAPIErrorsAndRateLimits(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "7")
w.Header().Set("CF-Ray", "ray-test")
w.WriteHeader(http.StatusTooManyRequests)
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"errors": []any{map[string]any{
"code": 1015, "message": "rate limit exceeded",
"source": map[string]any{"pointer": "/zones"},
}},
})
})
_, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{})
if !errors.Is(err, ErrRateLimited) {
t.Fatalf("error = %v", err)
}
var rateLimit *RateLimitError
if !errors.As(err, &rateLimit) {
t.Fatalf("not RateLimitError: %T", err)
}
if rateLimit.RetryAfter != 7*time.Second || !rateLimit.RetryAt.Equal(fixedNow.Add(7*time.Second)) {
t.Errorf("rate metadata = %+v", rateLimit)
}
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.Code != 1015 || apiErr.RequestID != "ray-test" || apiErr.Details[0].Pointer != "/zones" {
t.Errorf("API error = %+v", apiErr)
}
if strings.Contains(err.Error(), testAuth().Token) {
t.Error("error exposed API token")
}
}
func TestSuccessfulHTTPEnvelopeRejectionIsDefinitive(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"errors": []any{map[string]any{
"code": 1004, "message": "DNS validation failed",
}},
})
})
_, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{})
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error = %T %v, want *APIError", err, err)
}
if apiErr.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", apiErr.StatusCode, http.StatusOK)
}
if !apiErr.MutationOutcomeDefinitive() {
t.Fatal("HTTP 200 success:false rejection must be definitive")
}
}
func TestSuccessfulHTTPEnvelopeRequiresExplicitSuccess(t *testing.T) {
t.Parallel()
tests := []struct {
name string
body map[string]any
}{
{
name: "missing",
body: map[string]any{"result": []any{}},
},
{
name: "null",
body: map[string]any{"success": nil, "result": []any{}},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) {
if err := json.NewEncoder(w).Encode(test.body); err != nil {
t.Errorf("encode response: %v", err)
}
})
_, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{})
var responseErr *ResponseError
if !errors.As(err, &responseErr) {
t.Fatalf("error = %T %v, want *ResponseError", err, err)
}
var definitive interface {
MutationOutcomeDefinitive() bool
}
if errors.As(err, &definitive) && definitive.MutationOutcomeDefinitive() {
t.Fatal("missing or null success must leave a mutation outcome ambiguous")
}
})
}
}
func TestCredentialVerificationErrorClassification(t *testing.T) {
t.Parallel()
tests := []struct {
name string
err error
want bool
}{
{name: "local invalid auth", err: &ValidationError{Field: "auth.kind", Message: "unsupported"}, want: true},
{name: "unauthorized", err: &APIError{StatusCode: http.StatusUnauthorized}, want: true},
{name: "forbidden", err: &APIError{StatusCode: http.StatusForbidden}, want: true},
{name: "rate limited", err: newRateLimitError(&APIError{StatusCode: http.StatusTooManyRequests}, http.Header{}, fixedNow), want: false},
{name: "server failure", err: &APIError{StatusCode: http.StatusBadGateway}, want: false},
{name: "ambiguous response", err: &ResponseError{Resource: "token verification", Err: errors.New("malformed")}, want: false},
{name: "network failure", err: errors.New("connection reset"), want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if got := provider.CredentialFailureIsAuthoritative(test.err); got != test.want {
t.Fatalf("CredentialFailureIsAuthoritative(%T) = %v, want %v", test.err, got, test.want)
}
})
}
}
func TestZoneAccessDenialClassification(t *testing.T) {
t.Parallel()
tests := []struct {
name string
err error
want bool
}{
{name: "unauthorized", err: &APIError{StatusCode: http.StatusUnauthorized}, want: true},
{name: "forbidden", err: &APIError{StatusCode: http.StatusForbidden}, want: true},
{name: "rate limited", err: newRateLimitError(&APIError{StatusCode: http.StatusTooManyRequests}, http.Header{}, fixedNow), want: false},
{name: "server failure", err: &APIError{StatusCode: http.StatusServiceUnavailable}, want: false},
{name: "ambiguous response", err: &ResponseError{Resource: "DNS records", Err: errors.New("malformed")}, want: false},
{name: "network failure", err: errors.New("connection reset"), want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if got := provider.AccessFailureIsAuthoritative(test.err); got != test.want {
t.Fatalf("AccessFailureIsAuthoritative(%T) = %v, want %v", test.err, got, test.want)
}
})
}
}
+389
View File
@@ -0,0 +1,389 @@
package cloudflare
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
// ListDNSRecords lists one record page. Every provider response is retained in
// DNSRecord.Raw so record types introduced by Cloudflare remain visible and can
// be round-tripped through DomainOps storage without lossy decoding.
func (c *Client) ListDNSRecords(ctx context.Context, auth provider.Auth, zoneID string, request provider.PageRequest) (provider.RecordPage, error) {
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return provider.RecordPage{}, err
}
query, page := paginationQuery(request, 100, 5000)
if search := strings.TrimSpace(request.Search); search != "" {
query.Set("search", search)
}
raw, info, err := c.do(ctx, auth, http.MethodGet, path, query, nil)
if err != nil {
return provider.RecordPage{}, err
}
records, err := c.mapRecordArray(raw, zoneID)
if err != nil {
return provider.RecordPage{}, err
}
return provider.RecordPage{
Records: records,
NextCursor: nextCursor(info, page, len(records), queryPerPage(request, 100, 5000)),
Page: page,
TotalPages: info.TotalPages,
}, nil
}
// GetDNSRecord retrieves one record by its exact Cloudflare identifier.
func (c *Client) GetDNSRecord(ctx context.Context, auth provider.Auth, zoneID, recordID string) (domain.DNSRecord, error) {
path, err := apiPath("zones", zoneID, "dns_records", recordID)
if err != nil {
return domain.DNSRecord{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, nil, nil)
if err != nil {
return domain.DNSRecord{}, err
}
return mapRecord(raw, zoneID, c.now().UTC())
}
// CreateDNSRecord creates one editable provider-neutral record.
func (c *Client) CreateDNSRecord(ctx context.Context, auth provider.Auth, zoneID string, record domain.DNSRecord) (domain.DNSRecord, error) {
payload, err := makeRecordPayload(record)
if err != nil {
return domain.DNSRecord{}, err
}
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return domain.DNSRecord{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodPost, path, nil, payload)
if err != nil {
return domain.DNSRecord{}, err
}
return mapRecord(raw, zoneID, c.now().UTC())
}
// PatchDNSRecord updates one record without replacing provider-managed fields.
func (c *Client) PatchDNSRecord(ctx context.Context, auth provider.Auth, zoneID, recordID string, record domain.DNSRecord) (domain.DNSRecord, error) {
payload, err := makeRecordPayload(record)
if err != nil {
return domain.DNSRecord{}, err
}
path, err := apiPath("zones", zoneID, "dns_records", recordID)
if err != nil {
return domain.DNSRecord{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodPatch, path, nil, payload)
if err != nil {
return domain.DNSRecord{}, err
}
return mapRecord(raw, zoneID, c.now().UTC())
}
// DeleteDNSRecord permanently removes the exact record identifier.
func (c *Client) DeleteDNSRecord(ctx context.Context, auth provider.Auth, zoneID, recordID string) error {
path, err := apiPath("zones", zoneID, "dns_records", recordID)
if err != nil {
return err
}
_, _, err = c.do(ctx, auth, http.MethodDelete, path, nil, nil)
return err
}
type dnsBatchPayload struct {
Deletes []map[string]any `json:"deletes,omitempty"`
Patches []map[string]any `json:"patches,omitempty"`
Puts []map[string]any `json:"puts,omitempty"`
Posts []map[string]any `json:"posts,omitempty"`
}
type dnsBatchResult struct {
Deletes []json.RawMessage `json:"deletes"`
Patches []json.RawMessage `json:"patches"`
Puts []json.RawMessage `json:"puts"`
Posts []json.RawMessage `json:"posts"`
}
// ApplyDNSBatch sends a zone-scoped Cloudflare batch. Results follow
// Cloudflare's documented execution order: deletes, patches, puts, then posts.
func (c *Client) ApplyDNSBatch(ctx context.Context, auth provider.Auth, zoneID string, mutations []domain.DNSMutation) ([]domain.DNSRecord, error) {
if len(mutations) == 0 {
return []domain.DNSRecord{}, nil
}
payload := dnsBatchPayload{}
for index, mutation := range mutations {
switch mutation.Kind {
case domain.MutationCreate:
if mutation.After == nil {
return nil, mutationError(index, "create requires an after record")
}
record, err := makeRecordPayload(*mutation.After)
if err != nil {
return nil, fmt.Errorf("cloudflare: batch mutation %d: %w", index, err)
}
payload.Posts = append(payload.Posts, record)
case domain.MutationPatch, domain.MutationReplace:
if mutation.After == nil {
return nil, mutationError(index, "update requires an after record")
}
id := mutationRecordID(mutation)
if id == "" {
return nil, mutationError(index, "update requires a record ID")
}
record, err := makeRecordPayload(*mutation.After)
if err != nil {
return nil, fmt.Errorf("cloudflare: batch mutation %d: %w", index, err)
}
record["id"] = id
if mutation.Kind == domain.MutationPatch {
payload.Patches = append(payload.Patches, record)
} else {
payload.Puts = append(payload.Puts, record)
}
case domain.MutationDelete:
id := mutationRecordID(mutation)
if id == "" {
return nil, mutationError(index, "delete requires a record ID")
}
payload.Deletes = append(payload.Deletes, map[string]any{"id": id})
default:
return nil, mutationError(index, "unknown mutation kind "+string(mutation.Kind))
}
}
path, err := apiPath("zones", zoneID, "dns_records", "batch")
if err != nil {
return nil, err
}
raw, _, err := c.do(ctx, auth, http.MethodPost, path, nil, payload)
if err != nil {
return nil, err
}
var batch dnsBatchResult
if err := json.Unmarshal(raw, &batch); err != nil {
return nil, &ResponseError{Resource: "DNS batch", Err: err}
}
ordered := make([]json.RawMessage, 0, len(batch.Deletes)+len(batch.Patches)+len(batch.Puts)+len(batch.Posts))
ordered = append(ordered, batch.Deletes...)
ordered = append(ordered, batch.Patches...)
ordered = append(ordered, batch.Puts...)
ordered = append(ordered, batch.Posts...)
return c.mapRecordWires(ordered, zoneID)
}
// PresentDNS01 creates a single TXT challenge and returns the exact Cloudflare
// ID. The job identifier is recorded only as a non-secret provider comment.
func (c *Client) PresentDNS01(ctx context.Context, auth provider.Auth, zoneID, fqdn, value, jobID string) (string, error) {
comment := "DomainOps ACME DNS-01"
if jobID = strings.TrimSpace(jobID); jobID != "" {
comment += " job=" + jobID
}
// Cloudflare DNS comments are bounded; trimming affects only diagnostics,
// never the challenge owner or value.
if len(comment) > 100 {
comment = comment[:100]
}
record, err := c.CreateDNSRecord(ctx, auth, zoneID, domain.DNSRecord{
ZoneID: zoneID,
Type: domain.RecordTXT,
Name: fqdn,
Content: value,
TTL: 60,
Comment: comment,
})
if err != nil {
return "", err
}
id := record.ProviderID
if id == "" {
id = record.ID
}
if id == "" {
return "", &ResponseError{Resource: "DNS-01 create", Err: errors.New("response omitted record ID")}
}
return id, nil
}
// CleanupDNS01 deletes only the exact record ID returned by PresentDNS01. It
// never searches by owner name or TXT value, avoiding removal of concurrent
// ACME challenges.
func (c *Client) CleanupDNS01(ctx context.Context, auth provider.Auth, zoneID, recordID string) error {
err := c.DeleteDNSRecord(ctx, auth, zoneID, recordID)
if errors.Is(err, ErrNotFound) {
return nil
}
return err
}
// ReconcileDNS01 locates a challenge after an ambiguous create response. The
// job marker is diagnostic rather than secret; the plaintext TXT value is
// compared only through its journaled SHA-256 digest.
func (c *Client) ReconcileDNS01(ctx context.Context, auth provider.Auth, zoneID, fqdn, valueHash, jobID string) (string, bool, error) {
owner, err := toASCIIName(fqdn)
if err != nil {
return "", false, err
}
request := provider.PageRequest{Page: 1, PerPage: 100, Search: owner}
var matches []string
for {
page, listErr := c.ListDNSRecords(ctx, auth, zoneID, request)
if listErr != nil {
return "", false, listErr
}
for _, record := range page.Records {
if record.Type != domain.RecordTXT || !strings.EqualFold(strings.TrimSuffix(record.Name, "."), owner) || !commentContainsJob(record.Comment, jobID) {
continue
}
digest := sha256.Sum256([]byte(record.Content))
if !strings.EqualFold(hex.EncodeToString(digest[:]), strings.TrimSpace(valueHash)) {
continue
}
id := record.ProviderID
if id == "" {
id = record.ID
}
if id != "" {
matches = append(matches, id)
}
}
if page.NextCursor == "" {
break
}
request.Cursor = page.NextCursor
if page.Page > 0 {
request.Page = page.Page
}
}
if len(matches) > 1 {
return "", false, fmt.Errorf("cloudflare: DNS-01 recovery matched %d records for job %s", len(matches), jobID)
}
if len(matches) == 0 {
return "", false, nil
}
return matches[0], true, nil
}
func commentContainsJob(comment, jobID string) bool {
want := "job=" + strings.TrimSpace(jobID)
if want == "job=" {
return false
}
for _, field := range strings.Fields(comment) {
if field == want {
return true
}
}
return false
}
func makeRecordPayload(record domain.DNSRecord) (map[string]any, error) {
if record.Managed {
return nil, &ValidationError{Field: "record.managed", Message: "Cloudflare-managed records are read-only"}
}
recordType := domain.RecordType(strings.ToUpper(string(record.Type)))
if !recordType.Editable() {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedRecordType, recordType)
}
name, err := toASCIIName(record.Name)
if err != nil {
return nil, err
}
if record.TTL < 0 {
return nil, &ValidationError{Field: "record.ttl", Message: "TTL cannot be negative"}
}
ttl := record.TTL
if ttl == 0 {
ttl = 1
}
payload := map[string]any{
"type": string(recordType),
"name": name,
"ttl": ttl,
"comment": record.Comment,
"tags": append([]string(nil), record.Tags...),
}
structured := recordType == domain.RecordCAA || recordType == domain.RecordSRV
hasData := len(record.Data) > 0 && string(record.Data) != "null"
if !structured || !hasData {
payload["content"] = record.Content
}
if record.Priority != nil {
payload["priority"] = *record.Priority
}
if structured && hasData {
if !json.Valid(record.Data) {
return nil, &ValidationError{Field: "record.data", Message: "must contain valid JSON"}
}
payload["data"] = cloneRaw(record.Data)
}
if recordType == domain.RecordA || recordType == domain.RecordAAAA || recordType == domain.RecordCNAME {
payload["proxied"] = record.Proxied
}
if settings := rawRecordField(record.Raw, "settings"); len(settings) > 0 && string(settings) != "null" {
payload["settings"] = settings
}
return payload, nil
}
func rawRecordField(raw json.RawMessage, field string) json.RawMessage {
if len(raw) == 0 {
return nil
}
var values map[string]json.RawMessage
if json.Unmarshal(raw, &values) != nil {
return nil
}
return cloneRaw(values[field])
}
func mutationRecordID(mutation domain.DNSMutation) string {
if mutation.RecordID != "" {
return mutation.RecordID
}
for _, record := range []*domain.DNSRecord{mutation.After, mutation.Before} {
if record == nil {
continue
}
if record.ProviderID != "" {
return record.ProviderID
}
if record.ID != "" {
return record.ID
}
}
return ""
}
func mutationError(index int, message string) error {
return &ValidationError{Field: fmt.Sprintf("mutations[%d]", index), Message: message}
}
func (c *Client) mapRecordArray(raw json.RawMessage, zoneID string) ([]domain.DNSRecord, error) {
var wires []json.RawMessage
if err := json.Unmarshal(raw, &wires); err != nil {
return nil, &ResponseError{Resource: "DNS records", Err: err}
}
return c.mapRecordWires(wires, zoneID)
}
func (c *Client) mapRecordWires(wires []json.RawMessage, zoneID string) ([]domain.DNSRecord, error) {
syncedAt := c.now().UTC()
records := make([]domain.DNSRecord, 0, len(wires))
for _, wire := range wires {
record, err := mapRecord(wire, zoneID, syncedAt)
if err != nil {
return nil, err
}
records = append(records, record)
}
return records, nil
}
+305
View File
@@ -0,0 +1,305 @@
package cloudflare
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"strings"
"sync"
"testing"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
func TestListDNSRecordsPreservesUnknownFields(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/client/v4/zones/zone-1/dns_records" || r.Method != http.MethodGet {
http.NotFound(w, r)
return
}
if got := r.URL.Query().Get("search"); got != "api" {
t.Errorf("search = %q", got)
}
writeResult(t, w, []any{
map[string]any{
"id": "record-a", "type": "A", "name": "api.example.com", "content": "192.0.2.10",
"ttl": 300, "proxied": true, "proxiable": true, "priority": 10,
"comment": "primary", "tags": []string{"owner:ops"},
"modified_on": "2026-07-01T12:00:00Z",
},
map[string]any{
"id": "record-new", "type": "HTTPS", "name": "example.com", "content": ". alpn=h2",
"ttl": 1, "locked": true,
"meta": map[string]any{"managed_by_apps": true},
"data": map[string]any{"priority": 1, "target": "."},
"provider_new_field": map[string]any{"future": true},
},
}, map[string]any{"page": 1, "per_page": 2, "total_pages": 2})
})
page, err := client.ListDNSRecords(context.Background(), testAuth(), "zone-1", provider.PageRequest{PerPage: 2, Search: "api"})
if err != nil {
t.Fatalf("ListDNSRecords: %v", err)
}
if page.NextCursor != "2" || len(page.Records) != 2 {
t.Fatalf("page = %+v", page)
}
first := page.Records[0]
if first.ProviderID != "record-a" || first.Priority == nil || *first.Priority != 10 || !first.Proxied || !first.Proxiable {
t.Errorf("first record = %+v", first)
}
unknown := page.Records[1]
if unknown.Type != domain.RecordType("HTTPS") || unknown.Type.Editable() || !unknown.Managed {
t.Errorf("unknown record = %+v", unknown)
}
if !strings.Contains(string(unknown.Raw), "provider_new_field") || !strings.Contains(string(unknown.Data), "target") {
t.Errorf("raw/data not preserved: raw=%s data=%s", unknown.Raw, unknown.Data)
}
if unknown.LastSyncedAt == nil || !unknown.LastSyncedAt.Equal(fixedNow) {
t.Errorf("sync time = %v", unknown.LastSyncedAt)
}
}
func TestDNSRecordCRUDAndPayloadMapping(t *testing.T) {
t.Parallel()
var mu sync.Mutex
methods := make([]string, 0, 4)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
methods = append(methods, r.Method+" "+r.URL.Path)
mu.Unlock()
switch {
case r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records/record-1":
writeResult(t, w, map[string]any{"id": "record-1", "type": "A", "name": "www.example.com", "content": "192.0.2.1", "ttl": 1}, nil)
case r.Method == http.MethodPost && r.URL.Path == "/client/v4/zones/zone-1/dns_records":
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode create: %v", err)
}
if body["name"] != "xn--bcher-kva.example" || body["type"] != "A" || body["ttl"] != float64(1) || body["proxied"] != true {
t.Errorf("create body = %#v", body)
}
writeResult(t, w, map[string]any{"id": "record-2", "type": "A", "name": body["name"], "content": body["content"], "ttl": 1, "proxied": true, "proxiable": true}, nil)
case r.Method == http.MethodPatch && r.URL.Path == "/client/v4/zones/zone-1/dns_records/record-2":
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode patch: %v", err)
}
if body["content"] != "192.0.2.22" || body["proxied"] != false || body["comment"] != "updated" {
t.Errorf("patch body = %#v", body)
}
writeResult(t, w, map[string]any{"id": "record-2", "type": "A", "name": body["name"], "content": body["content"], "ttl": 300, "proxied": false, "comment": "updated"}, nil)
case r.Method == http.MethodDelete && r.URL.Path == "/client/v4/zones/zone-1/dns_records/record-2":
writeResult(t, w, map[string]any{"id": "record-2"}, nil)
default:
http.NotFound(w, r)
}
})
got, err := client.GetDNSRecord(context.Background(), testAuth(), "zone-1", "record-1")
if err != nil || got.Content != "192.0.2.1" {
t.Fatalf("GetDNSRecord = %+v, %v", got, err)
}
created, err := client.CreateDNSRecord(context.Background(), testAuth(), "zone-1", domain.DNSRecord{
Type: domain.RecordA, Name: "bücher.example", Content: "192.0.2.2", Proxied: true,
})
if err != nil || created.ProviderID != "record-2" || created.UnicodeName != "bücher.example" {
t.Fatalf("CreateDNSRecord = %+v, %v", created, err)
}
patched, err := client.PatchDNSRecord(context.Background(), testAuth(), "zone-1", "record-2", domain.DNSRecord{
Type: domain.RecordA, Name: "xn--bcher-kva.example", Content: "192.0.2.22", TTL: 300, Comment: "updated",
})
if err != nil || patched.Content != "192.0.2.22" || patched.Proxied {
t.Fatalf("PatchDNSRecord = %+v, %v", patched, err)
}
if err := client.DeleteDNSRecord(context.Background(), testAuth(), "zone-1", "record-2"); err != nil {
t.Fatalf("DeleteDNSRecord: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(methods) != 4 {
t.Errorf("methods = %v", methods)
}
}
func TestDNSBatchUsesCloudflareOperationBuckets(t *testing.T) {
t.Parallel()
priority := uint16(20)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/client/v4/zones/zone-1/dns_records/batch" {
http.NotFound(w, r)
return
}
var body struct {
Deletes []map[string]any `json:"deletes"`
Patches []map[string]any `json:"patches"`
Puts []map[string]any `json:"puts"`
Posts []map[string]any `json:"posts"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode batch: %v", err)
}
if len(body.Deletes) != 1 || body.Deletes[0]["id"] != "delete-id" ||
len(body.Patches) != 1 || body.Patches[0]["id"] != "patch-id" ||
len(body.Puts) != 1 || body.Puts[0]["id"] != "put-id" || len(body.Posts) != 1 {
t.Errorf("batch body = %#v", body)
}
writeResult(t, w, map[string]any{
"deletes": []any{map[string]any{"id": "delete-id"}},
"patches": []any{map[string]any{"id": "patch-id", "type": "A", "name": "patch.example.com", "content": "192.0.2.20", "ttl": 60}},
"puts": []any{map[string]any{"id": "put-id", "type": "MX", "name": "example.com", "content": "mail.example.com", "priority": 20, "ttl": 300}},
"posts": []any{map[string]any{"id": "post-id", "type": "TXT", "name": "new.example.com", "content": "hello", "ttl": 60}},
}, nil)
})
mutations := []domain.DNSMutation{
{Kind: domain.MutationCreate, After: &domain.DNSRecord{Type: domain.RecordTXT, Name: "new.example.com", Content: "hello", TTL: 60}},
{Kind: domain.MutationDelete, RecordID: "delete-id"},
{Kind: domain.MutationReplace, RecordID: "put-id", After: &domain.DNSRecord{Type: domain.RecordMX, Name: "example.com", Content: "mail.example.com", Priority: &priority, TTL: 300}},
{Kind: domain.MutationPatch, RecordID: "patch-id", After: &domain.DNSRecord{Type: domain.RecordA, Name: "patch.example.com", Content: "192.0.2.20", TTL: 60}},
}
records, err := client.ApplyDNSBatch(context.Background(), testAuth(), "zone-1", mutations)
if err != nil {
t.Fatalf("ApplyDNSBatch: %v", err)
}
if len(records) != 4 {
t.Fatalf("records = %+v", records)
}
got := []string{records[0].ID, records[1].ID, records[2].ID, records[3].ID}
want := []string{"delete-id", "patch-id", "put-id", "post-id"}
for i := range want {
if got[i] != want[i] {
t.Errorf("result order = %v, want %v", got, want)
break
}
}
}
func TestDNS01CleanupDeletesOnlyReturnedRecordID(t *testing.T) {
t.Parallel()
var calls []string
var mu sync.Mutex
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
calls = append(calls, r.Method+" "+r.URL.Path)
mu.Unlock()
switch {
case r.Method == http.MethodPost && r.URL.Path == "/client/v4/zones/zone-1/dns_records":
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode challenge: %v", err)
}
if body["type"] != "TXT" || body["name"] != "_acme-challenge.example.com" || body["content"] != "challenge-value" {
t.Errorf("challenge body = %#v", body)
}
if !strings.Contains(body["comment"].(string), "job-42") {
t.Errorf("challenge comment = %q", body["comment"])
}
writeResult(t, w, map[string]any{
"id": "exact-created-id", "type": "TXT", "name": body["name"], "content": body["content"], "ttl": 60,
}, nil)
case r.Method == http.MethodDelete && r.URL.Path == "/client/v4/zones/zone-1/dns_records/exact-created-id":
writeResult(t, w, map[string]any{"id": "exact-created-id"}, nil)
default:
http.NotFound(w, r)
}
})
recordID, err := client.PresentDNS01(context.Background(), testAuth(), "zone-1", "_acme-challenge.example.com.", "challenge-value", "job-42")
if err != nil || recordID != "exact-created-id" {
t.Fatalf("PresentDNS01 = %q, %v", recordID, err)
}
if err := client.CleanupDNS01(context.Background(), testAuth(), "zone-1", recordID); err != nil {
t.Fatalf("CleanupDNS01: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(calls) != 2 || strings.Contains(strings.Join(calls, " "), "GET") {
t.Errorf("challenge calls = %v", calls)
}
}
func TestDNS01RecoveryMatchesJobAndValueAndCleanupIsIdempotent(t *testing.T) {
t.Parallel()
value := "challenge-value"
digest := sha256.Sum256([]byte(value))
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records":
if r.URL.Query().Get("search") != "_acme-challenge.example.com" {
t.Errorf("recovery search = %q", r.URL.Query().Get("search"))
}
writeResult(t, w, []any{
map[string]any{"id": "other", "type": "TXT", "name": "_acme-challenge.example.com", "content": value, "comment": "DomainOps ACME DNS-01 job=another"},
map[string]any{"id": "recovered", "type": "TXT", "name": "_acme-challenge.example.com", "content": value, "comment": "DomainOps ACME DNS-01 job=job-42"},
}, map[string]any{"page": 1, "total_pages": 1})
case r.Method == http.MethodDelete && r.URL.Path == "/client/v4/zones/zone-1/dns_records/recovered":
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "errors": []any{map[string]any{"code": 81044, "message": "record does not exist"}}, "result": nil})
default:
http.NotFound(w, r)
}
})
recordID, found, err := client.ReconcileDNS01(context.Background(), testAuth(), "zone-1", "_acme-challenge.example.com.", hex.EncodeToString(digest[:]), "job-42")
if err != nil || !found || recordID != "recovered" {
t.Fatalf("ReconcileDNS01 = %q, %v, %v", recordID, found, err)
}
if err := client.CleanupDNS01(context.Background(), testAuth(), "zone-1", recordID); err != nil {
t.Fatalf("idempotent cleanup: %v", err)
}
}
func TestRejectsReadOnlyRecordsBeforeNetwork(t *testing.T) {
t.Parallel()
var called bool
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
http.Error(w, "unexpected", http.StatusInternalServerError)
})
_, err := client.CreateDNSRecord(context.Background(), testAuth(), "zone", domain.DNSRecord{Type: domain.RecordType("HTTPS"), Name: "example.com"})
if !errors.Is(err, ErrUnsupportedRecordType) {
t.Errorf("unknown type error = %v", err)
}
_, err = client.PatchDNSRecord(context.Background(), testAuth(), "zone", "record", domain.DNSRecord{Type: domain.RecordA, Name: "example.com", Managed: true})
var validation *ValidationError
if !errors.As(err, &validation) {
t.Errorf("managed record error = %v", err)
}
if called {
t.Error("read-only validation contacted Cloudflare")
}
}
func TestStructuredRecordPayloadSelection(t *testing.T) {
t.Parallel()
caaData := json.RawMessage(`{"flags":0,"tag":"issue","value":"letsencrypt.org"}`)
payload, err := makeRecordPayload(domain.DNSRecord{Type: domain.RecordCAA, Name: "example.com", Content: "ignored", Data: caaData})
if err != nil {
t.Fatal(err)
}
if _, ok := payload["content"]; ok || payload["data"] == nil {
t.Fatalf("structured CAA payload = %#v", payload)
}
payload, err = makeRecordPayload(domain.DNSRecord{Type: domain.RecordCAA, Name: "example.com", Content: `0 issue "letsencrypt.org"`, Data: json.RawMessage("null")})
if err != nil {
t.Fatal(err)
}
if payload["content"] == nil || payload["data"] != nil {
t.Fatalf("CAA content fallback payload = %#v", payload)
}
payload, err = makeRecordPayload(domain.DNSRecord{Type: domain.RecordA, Name: "example.com", Content: "192.0.2.1", Data: caaData})
if err != nil {
t.Fatal(err)
}
if payload["content"] != "192.0.2.1" || payload["data"] != nil {
t.Fatalf("unstructured A payload = %#v", payload)
}
}
+224
View File
@@ -0,0 +1,224 @@
package cloudflare
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
var (
ErrUnauthorized = errors.New("cloudflare: unauthorized")
ErrForbidden = errors.New("cloudflare: forbidden")
ErrNotFound = errors.New("cloudflare: resource not found")
ErrConflict = errors.New("cloudflare: conflict")
ErrRateLimited = errors.New("cloudflare: rate limited")
ErrUnsupportedRecordType = errors.New("cloudflare: unsupported writable DNS record type")
)
// ValidationError reports an invalid local request without contacting
// Cloudflare. It intentionally never includes secret material.
type ValidationError struct {
Field string
Message string
}
// ResponseError reports a successful HTTP response whose Cloudflare envelope
// or result does not match the documented schema. It usually indicates an
// upstream API change and leaves a mutation's outcome ambiguous.
type ResponseError struct {
Resource string
Err error
}
func (e *ResponseError) Error() string {
return fmt.Sprintf("cloudflare: decode %s response: %v", e.Resource, e.Err)
}
func (e *ResponseError) Unwrap() error { return e.Err }
func (e *ValidationError) Error() string {
if e.Field == "" {
return "cloudflare: " + e.Message
}
return fmt.Sprintf("cloudflare: invalid %s: %s", e.Field, e.Message)
}
func (e *ValidationError) MutationOutcomeDefinitive() bool { return true }
func (e *ValidationError) MutationNotAttempted() bool { return true }
func (e *ValidationError) CredentialVerificationAuthoritative() bool {
return true
}
// ErrorDetail is one structured error returned by the Cloudflare API.
type ErrorDetail struct {
Code int
Message string
Pointer string
DocumentationURL string
}
// APIError is a redacted, structured Cloudflare API failure.
type APIError struct {
Method string
Path string
StatusCode int
Code int
Message string
Details []ErrorDetail
RequestID string
}
func (e *APIError) Error() string {
message := strings.TrimSpace(e.Message)
if message == "" {
message = http.StatusText(e.StatusCode)
}
if e.Code != 0 {
return fmt.Sprintf("cloudflare API %s %s failed (%d, code %d): %s", e.Method, e.Path, e.StatusCode, e.Code, message)
}
return fmt.Sprintf("cloudflare API %s %s failed (%d): %s", e.Method, e.Path, e.StatusCode, message)
}
func (e *APIError) Is(target error) bool {
switch target {
case ErrUnauthorized:
return e.StatusCode == http.StatusUnauthorized
case ErrForbidden:
return e.StatusCode == http.StatusForbidden
case ErrNotFound:
return e.StatusCode == http.StatusNotFound
case ErrConflict:
return e.StatusCode == http.StatusConflict
default:
return false
}
}
// MutationOutcomeDefinitive distinguishes a provider rejection from a lost or
// ambiguous response. APIError is also returned for a successful HTTP response
// whose Cloudflare envelope explicitly reports success:false. Server errors can
// occur after processing began and remain ambiguous.
func (e *APIError) MutationOutcomeDefinitive() bool {
return e.StatusCode > 0 && e.StatusCode < http.StatusInternalServerError
}
// CredentialVerificationAuthoritative only classifies authentication and
// authorization rejections. In particular, 429 and 5xx responses must leave a
// previously valid credential valid, because they describe provider health or
// throttling rather than the token's state.
func (e *APIError) CredentialVerificationAuthoritative() bool {
return e.StatusCode == http.StatusUnauthorized || e.StatusCode == http.StatusForbidden
}
func (e *APIError) AccessDenialAuthoritative() bool {
return e.StatusCode == http.StatusUnauthorized || e.StatusCode == http.StatusForbidden
}
type mutationNotAttemptedError struct{ err error }
func (e *mutationNotAttemptedError) Error() string { return e.err.Error() }
func (e *mutationNotAttemptedError) Unwrap() error { return e.err }
func (e *mutationNotAttemptedError) MutationNotAttempted() bool { return true }
func markMutationNotAttempted(err error) error {
if err == nil {
return nil
}
return &mutationNotAttemptedError{err: err}
}
// RateLimitError includes Cloudflare's requested retry time where available.
type RateLimitError struct {
APIError *APIError
RetryAfter time.Duration
RetryAt time.Time
}
func (e *RateLimitError) Error() string {
if e.RetryAfter > 0 {
return fmt.Sprintf("%s; retry after %s", e.APIError.Error(), e.RetryAfter)
}
return e.APIError.Error()
}
func (e *RateLimitError) Unwrap() error { return e.APIError }
func (e *RateLimitError) Is(target error) bool {
return target == ErrRateLimited || errors.Is(e.APIError, target)
}
func newAPIError(method, path string, resp *http.Response, errorsList, messages []apiMessage) *APIError {
details := flattenMessages(errorsList)
if len(details) == 0 {
details = flattenMessages(messages)
}
result := &APIError{
Method: method,
Path: path,
StatusCode: resp.StatusCode,
RequestID: resp.Header.Get("CF-Ray"),
Details: details,
}
if len(details) > 0 {
result.Code = details[0].Code
result.Message = details[0].Message
}
return result
}
func flattenMessages(messages []apiMessage) []ErrorDetail {
var result []ErrorDetail
var appendMessage func(apiMessage)
appendMessage = func(message apiMessage) {
result = append(result, ErrorDetail{
Code: message.Code,
Message: message.Message,
Pointer: message.Source.Pointer,
DocumentationURL: message.DocumentationURL,
})
for _, child := range message.ErrorChain {
appendMessage(child)
}
}
for _, message := range messages {
appendMessage(message)
}
return result
}
func newRateLimitError(apiErr *APIError, header http.Header, now time.Time) *RateLimitError {
retryAt, retryAfter := parseRetryAfter(header.Get("Retry-After"), now)
if retryAfter == 0 {
if unix, err := strconv.ParseInt(header.Get("X-RateLimit-Reset"), 10, 64); err == nil && unix > 0 {
retryAt = time.Unix(unix, 0)
retryAfter = retryAt.Sub(now)
if retryAfter < 0 {
retryAfter = 0
}
}
}
return &RateLimitError{APIError: apiErr, RetryAfter: retryAfter, RetryAt: retryAt}
}
func parseRetryAfter(value string, now time.Time) (time.Time, time.Duration) {
value = strings.TrimSpace(value)
if value == "" {
return time.Time{}, 0
}
if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 {
delay := time.Duration(seconds) * time.Second
return now.Add(delay), delay
}
when, err := http.ParseTime(value)
if err != nil {
return time.Time{}, 0
}
delay := when.Sub(now)
if delay < 0 {
delay = 0
}
return when, delay
}
+220
View File
@@ -0,0 +1,220 @@
package cloudflare
import (
"encoding/json"
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/MeghdadFadaee/domainops/internal/domain"
"golang.org/x/net/idna"
)
type accountWire struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedOn string `json:"created_on"`
}
func mapAccount(w accountWire) domain.RemoteAccount {
return domain.RemoteAccount{
ID: w.ID,
Provider: domain.ProviderCloudflare,
ProviderID: w.ID,
Name: w.Name,
CreatedAt: parseTimeValue(w.CreatedOn),
}
}
type zoneWire struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Paused bool `json:"paused"`
NameServers []string `json:"name_servers"`
ModifiedOn string `json:"modified_on"`
Account accountWire `json:"account"`
Plan struct {
Name string `json:"name"`
} `json:"plan"`
}
func mapZone(w zoneWire, credentialID string, syncedAt time.Time) domain.Zone {
modified := optionalTime(w.ModifiedOn)
synced := syncedAt
return domain.Zone{
ID: w.ID,
Provider: domain.ProviderCloudflare,
ProviderID: w.ID,
AccountID: w.Account.ID,
PreferredCredentialID: credentialID,
Name: w.Name,
UnicodeName: toUnicodeName(w.Name),
Status: mapZoneStatus(w.Status),
Paused: w.Paused,
Plan: w.Plan.Name,
NameServers: append([]string(nil), w.NameServers...),
ModifiedAt: modified,
LastSyncedAt: &synced,
}
}
func mapZoneStatus(status string) domain.ZoneStatus {
switch strings.ToLower(status) {
case string(domain.ZoneActive):
return domain.ZoneActive
case string(domain.ZonePending):
return domain.ZonePending
case string(domain.ZoneInitializing):
return domain.ZoneInitializing
case string(domain.ZoneMoved):
return domain.ZoneMoved
case string(domain.ZoneDeactivated):
return domain.ZoneDeactivated
default:
return domain.ZoneUnknown
}
}
type recordWire struct {
ID string `json:"id"`
Type string `json:"type"`
Name string `json:"name"`
Content string `json:"content"`
Priority json.Number `json:"priority"`
TTL int `json:"ttl"`
Proxied bool `json:"proxied"`
Proxiable bool `json:"proxiable"`
Comment string `json:"comment"`
Tags []string `json:"tags"`
Locked bool `json:"locked"`
Data json.RawMessage `json:"data"`
Meta json.RawMessage `json:"meta"`
ModifiedOn string `json:"modified_on"`
}
func mapRecord(raw json.RawMessage, zoneID string, syncedAt time.Time) (domain.DNSRecord, error) {
var w recordWire
decoder := json.NewDecoder(strings.NewReader(string(raw)))
decoder.UseNumber()
if err := decoder.Decode(&w); err != nil {
return domain.DNSRecord{}, fmt.Errorf("cloudflare: decode DNS record: %w", err)
}
priority := parsePriority(w.Priority)
modified := optionalTime(w.ModifiedOn)
synced := syncedAt
return domain.DNSRecord{
ID: w.ID,
ProviderID: w.ID,
ZoneID: zoneID,
Type: domain.RecordType(strings.ToUpper(w.Type)),
Name: w.Name,
UnicodeName: toUnicodeName(w.Name),
Content: w.Content,
Priority: priority,
TTL: w.TTL,
Proxied: w.Proxied,
Proxiable: w.Proxiable,
Comment: w.Comment,
Tags: append([]string(nil), w.Tags...),
Managed: w.Locked || metaManaged(w.Meta),
Data: cloneRaw(w.Data),
Raw: cloneRaw(raw),
ModifiedAt: modified,
LastSyncedAt: &synced,
}, nil
}
func parsePriority(number json.Number) *uint16 {
if number == "" {
return nil
}
value, err := number.Int64()
if err != nil || value < 0 || value > 65535 {
return nil
}
priority := uint16(value)
return &priority
}
func metaManaged(raw json.RawMessage) bool {
if len(raw) == 0 || string(raw) == "null" {
return false
}
var values map[string]any
if json.Unmarshal(raw, &values) != nil {
return false
}
for _, key := range []string{"auto_added", "managed_by_apps", "managed_by_argo_tunnel", "managed_by_tunnel"} {
if value, ok := values[key].(bool); ok && value {
return true
}
}
return false
}
func parseTimeValue(value string) time.Time {
parsed, _ := time.Parse(time.RFC3339Nano, value)
return parsed
}
func optionalTime(value string) *time.Time {
parsed := parseTimeValue(value)
if parsed.IsZero() {
return nil
}
return &parsed
}
func toASCIIName(name string) (string, error) {
name = strings.TrimSpace(strings.TrimSuffix(name, "."))
if name == "" {
return "", &ValidationError{Field: "record.name", Message: "name is required"}
}
if isASCII(name) {
return strings.ToLower(name), nil
}
labels := strings.Split(name, ".")
for i, label := range labels {
if label == "" || label == "*" || strings.HasPrefix(label, "_") {
continue
}
encoded, err := idna.Lookup.ToASCII(label)
if err != nil {
return "", &ValidationError{Field: "record.name", Message: err.Error()}
}
labels[i] = encoded
}
return strings.ToLower(strings.Join(labels, ".")), nil
}
func toUnicodeName(name string) string {
if !strings.Contains(strings.ToLower(name), "xn--") {
return ""
}
labels := strings.Split(name, ".")
changed := false
for i, label := range labels {
decoded, err := idna.Lookup.ToUnicode(label)
if err == nil && decoded != label {
labels[i] = decoded
changed = true
}
}
if !changed {
return ""
}
return strings.Join(labels, ".")
}
func isASCII(value string) bool {
for len(value) > 0 {
r, size := utf8.DecodeRuneInString(value)
if r > 127 {
return false
}
value = value[size:]
}
return true
}
+324
View File
@@ -0,0 +1,324 @@
package cloudflare
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
const (
settingSSL = "ssl"
settingAlwaysHTTPS = "always_use_https"
settingMinimumTLS = "min_tls_version"
settingTLS13 = "tls_1_3"
)
type zoneSettingWire struct {
ID string `json:"id"`
Value json.RawMessage `json:"value"`
Editable bool `json:"editable"`
}
// GetEdgeTLSSettings reads the four intentionally supported Cloudflare zone
// controls and independently determines whether the zone has proxied DNS.
func (c *Client) GetEdgeTLSSettings(ctx context.Context, auth provider.Auth, zoneID string) (domain.EdgeTLSSettings, error) {
mode, err := c.getZoneSetting(ctx, auth, zoneID, settingSSL)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read SSL mode: %w", err)
}
alwaysHTTPS, err := c.getZoneSetting(ctx, auth, zoneID, settingAlwaysHTTPS)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read Always Use HTTPS: %w", err)
}
minimumTLS, err := c.getZoneSetting(ctx, auth, zoneID, settingMinimumTLS)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read minimum TLS: %w", err)
}
tls13, err := c.getZoneSetting(ctx, auth, zoneID, settingTLS13)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read TLS 1.3: %w", err)
}
hasProxiedDNS, err := c.hasProxiedDNS(ctx, auth, zoneID)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: inspect proxied DNS: %w", err)
}
syncedAt := c.now().UTC()
return domain.EdgeTLSSettings{
ZoneID: zoneID,
Mode: settingString(mode),
AlwaysUseHTTPS: settingEnabled(alwaysHTTPS),
MinimumTLS: settingString(minimumTLS),
TLS13: settingEnabled(tls13),
HasProxiedDNS: hasProxiedDNS,
LastSyncedAt: &syncedAt,
}, nil
}
// UpdateEdgeTLSSettings applies the complete provider-neutral settings model.
// Cloudflare exposes these as separate endpoints, so the current exact values
// are read first and only changed settings are patched. A failure names the
// setting that did not apply; callers can immediately refresh to reconcile
// partial state.
func (c *Client) UpdateEdgeTLSSettings(ctx context.Context, auth provider.Auth, zoneID string, baseline, settings domain.EdgeTLSSettings) (domain.EdgeTLSSettings, error) {
mode := strings.ToLower(strings.TrimSpace(settings.Mode))
if !oneOf(mode, "off", "flexible", "full", "strict", "origin_pull") {
return domain.EdgeTLSSettings{}, &ValidationError{Field: "tls.mode", Message: "must be off, flexible, full, strict, or origin_pull"}
}
minimumTLS := strings.TrimSpace(settings.MinimumTLS)
if !oneOf(minimumTLS, "1.0", "1.1", "1.2", "1.3") {
return domain.EdgeTLSSettings{}, &ValidationError{Field: "tls.minimum_tls", Message: "must be 1.0, 1.1, 1.2, or 1.3"}
}
desired := []struct {
id string
baselineValue string
value string
changed bool
}{
{id: settingSSL, baselineValue: strings.ToLower(strings.TrimSpace(baseline.Mode)), value: mode, changed: !strings.EqualFold(strings.TrimSpace(baseline.Mode), mode)},
{id: settingAlwaysHTTPS, baselineValue: onOff(baseline.AlwaysUseHTTPS), value: onOff(settings.AlwaysUseHTTPS), changed: baseline.AlwaysUseHTTPS != settings.AlwaysUseHTTPS},
{id: settingMinimumTLS, baselineValue: strings.TrimSpace(baseline.MinimumTLS), value: minimumTLS, changed: strings.TrimSpace(baseline.MinimumTLS) != minimumTLS},
{id: settingTLS13, baselineValue: onOff(baseline.TLS13), value: onOff(settings.TLS13), changed: baseline.TLS13 != settings.TLS13},
}
effective := make(map[string]zoneSettingWire, len(desired))
for _, setting := range desired {
current, err := c.getZoneSetting(ctx, auth, zoneID, setting.id)
if err != nil {
return domain.EdgeTLSSettings{}, markMutationNotAttempted(fmt.Errorf("cloudflare: read zone setting %s before update: %w", setting.id, err))
}
effective[setting.id] = current
}
// Validate every requested field against the caller's displayed baseline
// before applying the first patch. Unrelated concurrent provider changes are
// preserved; a concurrent change to a requested field fails closed.
for _, update := range desired {
if !update.changed {
continue
}
if !edgeTLSSettingMatches(update.id, effective[update.id], baseline, update.baselineValue) {
return domain.EdgeTLSSettings{}, &ValidationError{
Field: "tls." + update.id,
Message: "changed remotely; refresh before retrying",
}
}
}
for _, update := range desired {
if !update.changed {
continue
}
updated, err := c.patchZoneSetting(ctx, auth, zoneID, update.id, update.value)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: update zone setting %s: %w", update.id, err)
}
effective[update.id] = updated
}
hasProxiedDNS, err := c.hasProxiedDNS(ctx, auth, zoneID)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: inspect proxied DNS after update: %w", err)
}
syncedAt := c.now().UTC()
return domain.EdgeTLSSettings{
ZoneID: zoneID,
Mode: settingString(effective[settingSSL]),
AlwaysUseHTTPS: settingEnabled(effective[settingAlwaysHTTPS]),
MinimumTLS: settingString(effective[settingMinimumTLS]),
TLS13: settingEnabled(effective[settingTLS13]),
HasProxiedDNS: hasProxiedDNS,
LastSyncedAt: &syncedAt,
}, nil
}
func edgeTLSSettingMatches(settingID string, current zoneSettingWire, desired domain.EdgeTLSSettings, desiredValue string) bool {
if settingID == settingTLS13 {
// TLS 1.3's provider-neutral model intentionally collapses Cloudflare's
// "on" and "zrt" modes. Preserve either enabled mode when the caller
// continues to request TLS 1.3 instead of silently disabling 0-RTT.
currentValue := strings.ToLower(strings.TrimSpace(settingString(current)))
if desired.TLS13 {
return currentValue == "on" || currentValue == "zrt"
}
return currentValue == "off"
}
return strings.EqualFold(strings.TrimSpace(settingString(current)), strings.TrimSpace(desiredValue))
}
func (c *Client) getZoneSetting(ctx context.Context, auth provider.Auth, zoneID, settingID string) (zoneSettingWire, error) {
path, err := apiPath("zones", zoneID, "settings", settingID)
if err != nil {
return zoneSettingWire{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, nil, nil)
if err != nil {
return zoneSettingWire{}, err
}
var setting zoneSettingWire
if err := json.Unmarshal(raw, &setting); err != nil {
return zoneSettingWire{}, &ResponseError{Resource: "zone setting " + settingID, Err: err}
}
return setting, nil
}
func (c *Client) patchZoneSetting(ctx context.Context, auth provider.Auth, zoneID, settingID, value string) (zoneSettingWire, error) {
path, err := apiPath("zones", zoneID, "settings", settingID)
if err != nil {
return zoneSettingWire{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodPatch, path, nil, map[string]string{"value": value})
if err != nil {
return zoneSettingWire{}, err
}
var setting zoneSettingWire
if err := json.Unmarshal(raw, &setting); err != nil {
return zoneSettingWire{}, &ResponseError{Resource: "zone setting " + settingID, Err: err}
}
return setting, nil
}
func (c *Client) hasProxiedDNS(ctx context.Context, auth provider.Auth, zoneID string) (bool, error) {
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return false, err
}
query := url.Values{"page": {"1"}, "per_page": {"1"}, "proxied": {"true"}}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, query, nil)
if err != nil {
return false, err
}
var records []json.RawMessage
if err := json.Unmarshal(raw, &records); err != nil {
return false, &ResponseError{Resource: "proxied DNS records", Err: err}
}
return len(records) > 0, nil
}
func settingString(setting zoneSettingWire) string {
var value string
_ = json.Unmarshal(setting.Value, &value)
return value
}
func settingEnabled(setting zoneSettingWire) bool {
switch strings.ToLower(settingString(setting)) {
case "on", "true", "zrt":
return true
default:
return false
}
}
func oneOf(value string, allowed ...string) bool {
for _, candidate := range allowed {
if value == candidate {
return true
}
}
return false
}
func onOff(enabled bool) string {
if enabled {
return "on"
}
return "off"
}
type certificatePackWire struct {
ID string `json:"id"`
Type string `json:"type"`
Status string `json:"status"`
Hosts []string `json:"hosts"`
ExpiresOn string `json:"expires_on"`
Certificates []struct {
ID string `json:"id"`
Status string `json:"status"`
Hosts []string `json:"hosts"`
ExpiresOn string `json:"expires_on"`
} `json:"certificates"`
}
// ListEdgeCertificates inventories Cloudflare certificate packs. Expiry is the
// earliest certificate expiry in a pack, which is the conservative operational
// value for dashboard warnings.
func (c *Client) ListEdgeCertificates(ctx context.Context, auth provider.Auth, zoneID string, request provider.PageRequest) ([]domain.EdgeCertificate, error) {
path, err := apiPath("zones", zoneID, "ssl", "certificate_packs")
if err != nil {
return nil, err
}
query, _ := paginationQuery(request, 50, 50)
query.Set("status", "all")
raw, _, err := c.do(ctx, auth, http.MethodGet, path, query, nil)
if err != nil {
return nil, err
}
var wires []certificatePackWire
if err := json.Unmarshal(raw, &wires); err != nil {
return nil, &ResponseError{Resource: "edge certificates", Err: err}
}
search := strings.ToLower(strings.TrimSpace(request.Search))
certificates := make([]domain.EdgeCertificate, 0, len(wires))
for _, wire := range wires {
certificate := mapCertificatePack(wire, zoneID)
if search != "" && !certificateMatches(certificate, search) {
continue
}
certificates = append(certificates, certificate)
}
return certificates, nil
}
func mapCertificatePack(wire certificatePackWire, zoneID string) domain.EdgeCertificate {
hosts := append([]string(nil), wire.Hosts...)
seenHosts := make(map[string]struct{}, len(hosts))
for _, host := range hosts {
seenHosts[host] = struct{}{}
}
var expiry *time.Time
considerExpiry := func(value string) {
candidate := optionalTime(value)
if candidate != nil && (expiry == nil || candidate.Before(*expiry)) {
expiry = candidate
}
}
considerExpiry(wire.ExpiresOn)
for _, child := range wire.Certificates {
considerExpiry(child.ExpiresOn)
for _, host := range child.Hosts {
if _, exists := seenHosts[host]; exists {
continue
}
seenHosts[host] = struct{}{}
hosts = append(hosts, host)
}
}
return domain.EdgeCertificate{
ID: wire.ID,
ZoneID: zoneID,
Type: wire.Type,
Status: wire.Status,
Hosts: hosts,
ExpiresAt: expiry,
}
}
func certificateMatches(certificate domain.EdgeCertificate, search string) bool {
if strings.Contains(strings.ToLower(certificate.ID), search) ||
strings.Contains(strings.ToLower(certificate.Type), search) ||
strings.Contains(strings.ToLower(certificate.Status), search) {
return true
}
for _, host := range certificate.Hosts {
if strings.Contains(strings.ToLower(host), search) {
return true
}
}
return false
}
+364
View File
@@ -0,0 +1,364 @@
package cloudflare
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
func TestUpdateEdgeTLSSettingsMarksPreflightReadFailureNotAttempted(t *testing.T) {
t.Parallel()
var patches atomic.Int32
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPatch {
patches.Add(1)
}
http.Error(w, "temporary provider failure", http.StatusBadGateway)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true}
desired := baseline
desired.Mode = "full"
_, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, desired)
if err == nil {
t.Fatal("preflight read failure unexpectedly succeeded")
}
var marker interface{ MutationNotAttempted() bool }
if !errors.As(err, &marker) || !marker.MutationNotAttempted() {
t.Fatalf("preflight error lacks MutationNotAttempted marker: %T %v", err, err)
}
if patches.Load() != 0 {
t.Fatalf("patch count = %d, want 0", patches.Load())
}
}
func TestGetEdgeTLSSettings(t *testing.T) {
t.Parallel()
values := map[string]string{
"ssl": "strict",
"always_use_https": "on",
"min_tls_version": "1.2",
"tls_1_3": "zrt",
}
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
value, ok := values[id]
if !ok {
http.NotFound(w, r)
return
}
writeResult(t, w, map[string]any{"id": id, "value": value, "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
if r.URL.Query().Get("proxied") != "true" || r.URL.Query().Get("per_page") != "1" {
t.Errorf("proxied query = %v", r.URL.Query())
}
writeResult(t, w, []any{map[string]any{"id": "proxied-record"}}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
settings, err := client.GetEdgeTLSSettings(context.Background(), testAuth(), "zone-1")
if err != nil {
t.Fatalf("GetEdgeTLSSettings: %v", err)
}
if settings.Mode != "strict" || !settings.AlwaysUseHTTPS || settings.MinimumTLS != "1.2" || !settings.TLS13 || !settings.HasProxiedDNS {
t.Errorf("settings = %+v", settings)
}
if settings.LastSyncedAt == nil || !settings.LastSyncedAt.Equal(fixedNow) {
t.Errorf("sync time = %v", settings.LastSyncedAt)
}
}
func TestUpdateEdgeTLSSettings(t *testing.T) {
t.Parallel()
var mu sync.Mutex
updated := make(map[string]string)
current := map[string]string{
"ssl": "flexible",
"always_use_https": "off",
"min_tls_version": "1.2",
"tls_1_3": "on",
}
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
value, ok := current[id]
if !ok {
http.NotFound(w, r)
return
}
writeResult(t, w, map[string]any{"id": id, "value": value, "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
var body map[string]string
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode setting: %v", err)
}
mu.Lock()
updated[id] = body["value"]
current[id] = body["value"]
mu.Unlock()
writeResult(t, w, map[string]any{"id": id, "value": body["value"], "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "flexible", AlwaysUseHTTPS: false, MinimumTLS: "1.2", TLS13: true}
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, domain.EdgeTLSSettings{
Mode: "full", AlwaysUseHTTPS: true, MinimumTLS: "1.3", TLS13: false,
})
if err != nil {
t.Fatalf("UpdateEdgeTLSSettings: %v", err)
}
if settings.Mode != "full" || !settings.AlwaysUseHTTPS || settings.MinimumTLS != "1.3" || settings.TLS13 || settings.HasProxiedDNS {
t.Errorf("effective settings = %+v", settings)
}
mu.Lock()
defer mu.Unlock()
want := map[string]string{
"ssl": "full", "always_use_https": "on", "min_tls_version": "1.3", "tls_1_3": "off",
}
for id, value := range want {
if updated[id] != value {
t.Errorf("updated[%s] = %q, want %q", id, updated[id], value)
}
}
}
func TestUpdateEdgeTLSSettingsNoOpPreservesZRT(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "strict",
"always_use_https": "on",
"min_tls_version": "1.2",
"tls_1_3": "zrt",
}
patches := 0
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
patches++
http.Error(w, "unexpected patch", http.StatusInternalServerError)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true}
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, domain.EdgeTLSSettings{
Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true,
})
if err != nil {
t.Fatalf("UpdateEdgeTLSSettings: %v", err)
}
if patches != 0 {
t.Fatalf("patch count = %d, want 0", patches)
}
if settings.Mode != "strict" || !settings.AlwaysUseHTTPS || settings.MinimumTLS != "1.2" || !settings.TLS13 {
t.Errorf("effective settings = %+v", settings)
}
}
func TestUpdateEdgeTLSSettingsEnablesTLS13FromOff(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "strict",
"always_use_https": "on",
"min_tls_version": "1.2",
"tls_1_3": "off",
}
updated := make(map[string]string)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
var body map[string]string
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode setting: %v", err)
}
updated[id] = body["value"]
writeResult(t, w, map[string]any{"id": id, "value": body["value"], "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: false}
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, domain.EdgeTLSSettings{
Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true,
})
if err != nil {
t.Fatalf("UpdateEdgeTLSSettings: %v", err)
}
if len(updated) != 1 || updated[settingTLS13] != "on" {
t.Fatalf("updated = %v, want only tls_1_3=on", updated)
}
if !settings.TLS13 {
t.Errorf("effective settings = %+v", settings)
}
}
func TestUpdateEdgeTLSSettingsPreservesUnrelatedConcurrentChange(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "strict", "always_use_https": "on", "min_tls_version": "1.2", "tls_1_3": "zrt",
}
updated := make(map[string]string)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, prefix) {
id := strings.TrimPrefix(r.URL.Path, prefix)
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && strings.HasPrefix(r.URL.Path, prefix) {
id := strings.TrimPrefix(r.URL.Path, prefix)
var body map[string]string
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
}
updated[id] = body["value"]
current[id] = body["value"]
writeResult(t, w, map[string]any{"id": id, "value": body["value"], "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: false, MinimumTLS: "1.2", TLS13: true}
desired := baseline
desired.Mode = "full"
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, desired)
if err != nil {
t.Fatal(err)
}
if len(updated) != 1 || updated[settingSSL] != "full" {
t.Fatalf("patches = %#v, want only ssl=full", updated)
}
if !settings.AlwaysUseHTTPS || !settings.TLS13 {
t.Fatalf("unrelated concurrent state was clobbered: %#v", settings)
}
}
func TestUpdateEdgeTLSSettingsRejectsConcurrentChangeToRequestedFieldBeforePatching(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "flexible", "always_use_https": "off", "min_tls_version": "1.2", "tls_1_3": "on",
}
patches := 0
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, prefix) {
id := strings.TrimPrefix(r.URL.Path, prefix)
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch {
patches++
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", MinimumTLS: "1.2", TLS13: true}
desired := baseline
desired.Mode = "full"
_, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, desired)
if err == nil || !strings.Contains(err.Error(), "changed remotely") || patches != 0 {
t.Fatalf("concurrent field error = %v, patches=%d", err, patches)
}
}
func TestUpdateEdgeTLSSettingsValidatesBeforeNetwork(t *testing.T) {
t.Parallel()
called := false
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
http.Error(w, "unexpected", http.StatusInternalServerError)
})
_, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone", domain.EdgeTLSSettings{}, domain.EdgeTLSSettings{Mode: "unsafe", MinimumTLS: "1.2"})
if err == nil || called {
t.Fatalf("error = %v, called = %v", err, called)
}
}
func TestListEdgeCertificatesUsesEarliestPackExpiry(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/client/v4/zones/zone-1/ssl/certificate_packs" {
http.NotFound(w, r)
return
}
if r.URL.Query().Get("status") != "all" || r.URL.Query().Get("page") != "2" {
t.Errorf("certificate query = %v", r.URL.Query())
}
writeResult(t, w, []any{
map[string]any{
"id": "pack-1", "type": "universal", "status": "active", "hosts": []string{"example.com"},
"certificates": []any{
map[string]any{"id": "rsa", "hosts": []string{"example.com", "*.example.com"}, "status": "active", "expires_on": "2026-10-01T00:00:00Z"},
map[string]any{"id": "ecdsa", "hosts": []string{"example.com"}, "status": "active", "expires_on": "2026-09-01T00:00:00Z"},
},
},
map[string]any{"id": "pack-other", "type": "advanced", "status": "active", "hosts": []string{"other.test"}},
}, map[string]any{"page": 2, "total_pages": 2})
})
certificates, err := client.ListEdgeCertificates(context.Background(), testAuth(), "zone-1", provider.PageRequest{Page: 2, PerPage: 10, Search: "example"})
if err != nil {
t.Fatalf("ListEdgeCertificates: %v", err)
}
if len(certificates) != 1 {
t.Fatalf("certificates = %+v", certificates)
}
certificate := certificates[0]
wantExpiry := time.Date(2026, time.September, 1, 0, 0, 0, 0, time.UTC)
if certificate.ID != "pack-1" || certificate.ExpiresAt == nil || !certificate.ExpiresAt.Equal(wantExpiry) {
t.Errorf("certificate = %+v", certificate)
}
if len(certificate.Hosts) != 2 || certificate.Hosts[1] != "*.example.com" {
t.Errorf("hosts = %v", certificate.Hosts)
}
}
+177
View File
@@ -0,0 +1,177 @@
package cloudflare
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
type tokenVerificationWire struct {
ID string `json:"id"`
Status string `json:"status"`
}
// VerifyCredential verifies the correct token namespace, discovers accessible
// accounts, and performs real zone/DNS/settings reads. Cloudflare's verification
// response does not expose effective permission groups, so read probes never
// claim write access. DomainOps records write capability only after a real write
// succeeds and Cloudflare remains authoritative for every mutation.
func (c *Client) VerifyCredential(ctx context.Context, auth provider.Auth) (provider.Verification, error) {
verification := provider.Verification{Status: domain.CredentialInvalid}
if err := validateAuth(auth); err != nil {
return verification, err
}
verifyPath := "user/tokens/verify"
if auth.Kind == domain.CredentialAccountToken {
var err error
verifyPath, err = apiPath("accounts", auth.AccountID, "tokens", "verify")
if err != nil {
return verification, err
}
}
raw, _, err := c.do(ctx, auth, http.MethodGet, verifyPath, nil, nil)
if err != nil {
return verification, err
}
var token tokenVerificationWire
if err := json.Unmarshal(raw, &token); err != nil {
return verification, &ResponseError{Resource: "token verification", Err: err}
}
if !strings.EqualFold(token.Status, "active") {
return verification, nil
}
verification.Status = domain.CredentialValid
syncedAt := c.now().UTC()
accounts, err := c.discoverAccounts(ctx, auth)
if err != nil {
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.StatusCode >= http.StatusInternalServerError || apiErr.StatusCode == http.StatusTooManyRequests {
return verification, fmt.Errorf("cloudflare: discover accounts: %w", err)
}
// Some Cloudflare bearer tokens cannot use the legacy account listing
// endpoints. Zone results remain the source of truth for discovery.
accounts = nil
}
zones, _, _, zoneErr := c.listZones(ctx, auth, provider.PageRequest{Page: 1, PerPage: 50})
if zoneErr == nil {
verification.Capabilities.ZoneRead = true
accounts = mergeAccounts(accounts, accountsFromZones(zones, syncedAt))
} else if !errors.Is(zoneErr, ErrForbidden) {
return verification, fmt.Errorf("cloudflare: probe zone access: %w", zoneErr)
}
if len(accounts) == 0 && auth.AccountID != "" {
lastSynced := syncedAt
accounts = []domain.RemoteAccount{{
ID: auth.AccountID,
Provider: domain.ProviderCloudflare,
ProviderID: auth.AccountID,
Name: auth.AccountID,
LastSyncedAt: &lastSynced,
}}
}
verification.Accounts = accounts
if len(zones) > 0 {
zoneID := zones[0].ID
if err := c.probeDNSAccess(ctx, auth, zoneID); err == nil {
verification.Capabilities.DNSRead = true
} else if !errors.Is(err, ErrForbidden) {
return verification, fmt.Errorf("cloudflare: probe DNS access: %w", err)
}
if err := c.probeTLSAccess(ctx, auth, zoneID); err == nil {
verification.Capabilities.TLSRead = true
} else if !errors.Is(err, ErrForbidden) {
return verification, fmt.Errorf("cloudflare: probe TLS access: %w", err)
}
}
sortCapabilityNames(&verification.Capabilities)
return verification, nil
}
func (c *Client) discoverAccounts(ctx context.Context, auth provider.Auth) ([]domain.RemoteAccount, error) {
syncedAt := c.now().UTC()
if auth.AccountID != "" {
path, err := apiPath("accounts", auth.AccountID)
if err != nil {
return nil, err
}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, nil, nil)
if errors.Is(err, ErrForbidden) {
return nil, nil
}
if err != nil {
return nil, err
}
var wire accountWire
if err := json.Unmarshal(raw, &wire); err != nil {
return nil, &ResponseError{Resource: "account", Err: err}
}
account := mapAccount(wire)
account.LastSyncedAt = &syncedAt
return []domain.RemoteAccount{account}, nil
}
const maxPages = 100
var accounts []domain.RemoteAccount
for page := 1; page <= maxPages; page++ {
query := url.Values{
"page": {strconv.Itoa(page)},
"per_page": {"50"},
}
raw, info, err := c.do(ctx, auth, http.MethodGet, "accounts", query, nil)
if errors.Is(err, ErrForbidden) {
return accounts, nil
}
if err != nil {
return nil, err
}
var wires []accountWire
if err := json.Unmarshal(raw, &wires); err != nil {
return nil, &ResponseError{Resource: "accounts", Err: err}
}
for _, wire := range wires {
account := mapAccount(wire)
account.LastSyncedAt = &syncedAt
accounts = append(accounts, account)
}
if info.TotalPages > 0 {
if page >= info.TotalPages {
return accounts, nil
}
} else if len(wires) < 50 {
return accounts, nil
}
}
return nil, &ResponseError{Resource: "accounts", Err: errors.New("pagination exceeded 100 pages")}
}
func (c *Client) probeDNSAccess(ctx context.Context, auth provider.Auth, zoneID string) error {
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return err
}
_, _, err = c.do(ctx, auth, http.MethodGet, path, url.Values{"page": {"1"}, "per_page": {"1"}}, nil)
return err
}
func (c *Client) probeTLSAccess(ctx context.Context, auth provider.Auth, zoneID string) error {
path, err := apiPath("zones", zoneID, "settings", "ssl")
if err != nil {
return err
}
_, _, err = c.do(ctx, auth, http.MethodGet, path, nil, nil)
return err
}
+138
View File
@@ -0,0 +1,138 @@
package cloudflare
import (
"context"
"encoding/json"
"net/http"
"sort"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
// ListZones lists one Cloudflare zone page and preserves the provider's stable
// zone and account identifiers for reconciliation.
func (c *Client) ListZones(ctx context.Context, auth provider.Auth, request provider.PageRequest) (provider.ZonePage, error) {
wires, info, page, err := c.listZones(ctx, auth, request)
if err != nil {
return provider.ZonePage{}, err
}
syncedAt := c.now().UTC()
zones := make([]domain.Zone, 0, len(wires))
for _, wire := range wires {
zones = append(zones, mapZone(wire, auth.CredentialID, syncedAt))
}
return provider.ZonePage{
Zones: zones,
NextCursor: nextCursor(info, page, len(zones), queryPerPage(request, 50, 50)),
Page: page,
TotalPages: info.TotalPages,
}, nil
}
func (c *Client) listZones(ctx context.Context, auth provider.Auth, request provider.PageRequest) ([]zoneWire, resultInfo, int, error) {
query, page := paginationQuery(request, 50, 50)
if auth.AccountID != "" {
query.Set("account.id", auth.AccountID)
}
if search := strings.TrimSpace(request.Search); search != "" {
ascii, err := toASCIIName(search)
if err != nil {
return nil, resultInfo{}, 0, err
}
query.Set("name", ascii)
}
raw, info, err := c.do(ctx, auth, http.MethodGet, "zones", query, nil)
if err != nil {
return nil, resultInfo{}, 0, err
}
var zones []zoneWire
if err := json.Unmarshal(raw, &zones); err != nil {
return nil, resultInfo{}, 0, &ResponseError{Resource: "zones", Err: err}
}
return zones, info, page, nil
}
func queryPerPage(request provider.PageRequest, defaultValue, maximum int) int {
value := request.PerPage
if value <= 0 {
value = defaultValue
}
if value > maximum {
value = maximum
}
return value
}
func accountsFromZones(zones []zoneWire, syncedAt time.Time) []domain.RemoteAccount {
seen := make(map[string]struct{})
accounts := make([]domain.RemoteAccount, 0)
for _, zone := range zones {
if zone.Account.ID == "" {
continue
}
if _, ok := seen[zone.Account.ID]; ok {
continue
}
seen[zone.Account.ID] = struct{}{}
account := mapAccount(zone.Account)
timestamp := syncedAt
account.LastSyncedAt = &timestamp
accounts = append(accounts, account)
}
return accounts
}
func mergeAccounts(groups ...[]domain.RemoteAccount) []domain.RemoteAccount {
byID := make(map[string]domain.RemoteAccount)
order := make([]string, 0)
for _, group := range groups {
for _, account := range group {
if account.ProviderID == "" {
continue
}
if current, found := byID[account.ProviderID]; found {
if current.Name == "" && account.Name != "" {
current.Name = account.Name
}
if current.CreatedAt.IsZero() && !account.CreatedAt.IsZero() {
current.CreatedAt = account.CreatedAt
}
if account.LastSyncedAt != nil {
current.LastSyncedAt = account.LastSyncedAt
}
byID[account.ProviderID] = current
continue
}
byID[account.ProviderID] = account
order = append(order, account.ProviderID)
}
}
result := make([]domain.RemoteAccount, 0, len(order))
for _, id := range order {
result = append(result, byID[id])
}
return result
}
func sortCapabilityNames(capabilities *provider.Capabilities) {
capabilities.Names = capabilities.Names[:0]
if capabilities.ZoneRead {
capabilities.Names = append(capabilities.Names, "zone:read")
}
if capabilities.DNSRead {
capabilities.Names = append(capabilities.Names, "dns:read")
}
if capabilities.DNSWrite {
capabilities.Names = append(capabilities.Names, "dns:write")
}
if capabilities.TLSRead {
capabilities.Names = append(capabilities.Names, "tls:read")
}
if capabilities.TLSWrite {
capabilities.Names = append(capabilities.Names, "tls:write")
}
sort.Strings(capabilities.Names)
}