traefik/vendor/github.com/xenolf/lego/providers/dns/cloudflare/cloudflare.go

225 lines
5.9 KiB
Go
Raw Normal View History

2017-02-07 21:33:23 +00:00
// Package cloudflare implements a DNS provider for solving the DNS-01
// challenge using cloudflare DNS.
package cloudflare
import (
"bytes"
"encoding/json"
2018-07-03 10:44:04 +00:00
"errors"
2017-02-07 21:33:23 +00:00
"fmt"
"io"
2018-05-31 07:30:04 +00:00
"io/ioutil"
2017-02-07 21:33:23 +00:00
"net/http"
"time"
2018-05-31 07:30:04 +00:00
"github.com/xenolf/lego/acme"
2018-07-03 10:44:04 +00:00
"github.com/xenolf/lego/platform/config/env"
2017-02-07 21:33:23 +00:00
)
// CloudFlareAPIURL represents the API endpoint to call.
// TODO: Unexport?
const CloudFlareAPIURL = "https://api.cloudflare.com/client/v4"
2018-05-31 07:30:04 +00:00
// DNSProvider is an implementation of the acme.ChallengeProvider interface
2017-02-07 21:33:23 +00:00
type DNSProvider struct {
authEmail string
authKey string
2018-07-03 10:44:04 +00:00
client *http.Client
2017-02-07 21:33:23 +00:00
}
// NewDNSProvider returns a DNSProvider instance configured for cloudflare.
// Credentials must be passed in the environment variables: CLOUDFLARE_EMAIL
// and CLOUDFLARE_API_KEY.
func NewDNSProvider() (*DNSProvider, error) {
2018-07-03 10:44:04 +00:00
values, err := env.Get("CLOUDFLARE_EMAIL", "CLOUDFLARE_API_KEY")
if err != nil {
return nil, fmt.Errorf("CloudFlare: %v", err)
}
return NewDNSProviderCredentials(values["CLOUDFLARE_EMAIL"], values["CLOUDFLARE_API_KEY"])
2017-02-07 21:33:23 +00:00
}
// NewDNSProviderCredentials uses the supplied credentials to return a
// DNSProvider instance configured for cloudflare.
func NewDNSProviderCredentials(email, key string) (*DNSProvider, error) {
if email == "" || key == "" {
2018-07-03 10:44:04 +00:00
return nil, errors.New("CloudFlare: some credentials information are missing")
2017-02-07 21:33:23 +00:00
}
return &DNSProvider{
authEmail: email,
authKey: key,
2018-07-03 10:44:04 +00:00
client: &http.Client{Timeout: 30 * time.Second},
2017-02-07 21:33:23 +00:00
}, nil
}
// Timeout returns the timeout and interval to use when checking for DNS
// propagation. Adjusting here to cope with spikes in propagation times.
2018-07-03 10:44:04 +00:00
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
2017-02-07 21:33:23 +00:00
return 120 * time.Second, 2 * time.Second
}
// Present creates a TXT record to fulfil the dns-01 challenge
2018-07-03 10:44:04 +00:00
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value, ttl := acme.DNS01Record(domain, keyAuth)
zoneID, err := d.getHostedZoneID(fqdn)
2017-02-07 21:33:23 +00:00
if err != nil {
return err
}
rec := cloudFlareRecord{
Type: "TXT",
2018-05-31 07:30:04 +00:00
Name: acme.UnFqdn(fqdn),
2017-02-07 21:33:23 +00:00
Content: value,
2018-07-03 10:44:04 +00:00
TTL: ttl,
2017-02-07 21:33:23 +00:00
}
body, err := json.Marshal(rec)
if err != nil {
return err
}
2018-07-03 10:44:04 +00:00
_, err = d.doRequest(http.MethodPost, fmt.Sprintf("/zones/%s/dns_records", zoneID), bytes.NewReader(body))
2018-05-31 07:30:04 +00:00
return err
2017-02-07 21:33:23 +00:00
}
// CleanUp removes the TXT record matching the specified parameters
2018-07-03 10:44:04 +00:00
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
2018-05-31 07:30:04 +00:00
fqdn, _, _ := acme.DNS01Record(domain, keyAuth)
2017-02-07 21:33:23 +00:00
2018-07-03 10:44:04 +00:00
record, err := d.findTxtRecord(fqdn)
2017-02-07 21:33:23 +00:00
if err != nil {
return err
}
2018-07-03 10:44:04 +00:00
_, err = d.doRequest(http.MethodDelete, fmt.Sprintf("/zones/%s/dns_records/%s", record.ZoneID, record.ID), nil)
2018-05-31 07:30:04 +00:00
return err
2017-02-07 21:33:23 +00:00
}
2018-07-03 10:44:04 +00:00
func (d *DNSProvider) getHostedZoneID(fqdn string) (string, error) {
2017-02-07 21:33:23 +00:00
// HostedZone represents a CloudFlare DNS zone
type HostedZone struct {
ID string `json:"id"`
Name string `json:"name"`
}
2018-05-31 07:30:04 +00:00
authZone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers)
2017-02-07 21:33:23 +00:00
if err != nil {
return "", err
}
2018-07-03 10:44:04 +00:00
result, err := d.doRequest(http.MethodGet, "/zones?name="+acme.UnFqdn(authZone), nil)
2017-02-07 21:33:23 +00:00
if err != nil {
return "", err
}
var hostedZone []HostedZone
err = json.Unmarshal(result, &hostedZone)
if err != nil {
return "", err
}
if len(hostedZone) != 1 {
2018-07-03 10:44:04 +00:00
return "", fmt.Errorf("zone %s not found in CloudFlare for domain %s", authZone, fqdn)
2017-02-07 21:33:23 +00:00
}
return hostedZone[0].ID, nil
}
2018-07-03 10:44:04 +00:00
func (d *DNSProvider) findTxtRecord(fqdn string) (*cloudFlareRecord, error) {
zoneID, err := d.getHostedZoneID(fqdn)
2017-02-07 21:33:23 +00:00
if err != nil {
return nil, err
}
2018-07-03 10:44:04 +00:00
result, err := d.doRequest(
http.MethodGet,
2018-05-31 07:30:04 +00:00
fmt.Sprintf("/zones/%s/dns_records?per_page=1000&type=TXT&name=%s", zoneID, acme.UnFqdn(fqdn)),
2017-02-07 21:33:23 +00:00
nil,
)
if err != nil {
return nil, err
}
var records []cloudFlareRecord
err = json.Unmarshal(result, &records)
if err != nil {
return nil, err
}
for _, rec := range records {
2018-05-31 07:30:04 +00:00
if rec.Name == acme.UnFqdn(fqdn) {
2017-02-07 21:33:23 +00:00
return &rec, nil
}
}
2018-05-31 07:30:04 +00:00
return nil, fmt.Errorf("no existing record found for %s", fqdn)
2017-02-07 21:33:23 +00:00
}
2018-07-03 10:44:04 +00:00
func (d *DNSProvider) doRequest(method, uri string, body io.Reader) (json.RawMessage, error) {
2017-02-07 21:33:23 +00:00
req, err := http.NewRequest(method, fmt.Sprintf("%s%s", CloudFlareAPIURL, uri), body)
if err != nil {
return nil, err
}
2018-07-03 10:44:04 +00:00
req.Header.Set("X-Auth-Email", d.authEmail)
req.Header.Set("X-Auth-Key", d.authKey)
2017-02-07 21:33:23 +00:00
2018-07-03 10:44:04 +00:00
resp, err := d.client.Do(req)
2017-02-07 21:33:23 +00:00
if err != nil {
2018-07-03 10:44:04 +00:00
return nil, fmt.Errorf("error querying Cloudflare API -> %v", err)
2017-02-07 21:33:23 +00:00
}
defer resp.Body.Close()
var r APIResponse
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, err
}
if !r.Success {
if len(r.Errors) > 0 {
errStr := ""
for _, apiErr := range r.Errors {
errStr += fmt.Sprintf("\t Error: %d: %s", apiErr.Code, apiErr.Message)
for _, chainErr := range apiErr.ErrorChain {
errStr += fmt.Sprintf("<- %d: %s", chainErr.Code, chainErr.Message)
}
}
return nil, fmt.Errorf("Cloudflare API Error \n%s", errStr)
}
2018-05-31 07:30:04 +00:00
strBody := "Unreadable body"
if body, err := ioutil.ReadAll(resp.Body); err == nil {
strBody = string(body)
}
return nil, fmt.Errorf("Cloudflare API error: the request %s sent a response with a body which is not in JSON format: %s", req.URL.String(), strBody)
2017-02-07 21:33:23 +00:00
}
return r.Result, nil
}
2018-07-03 10:44:04 +00:00
// APIError contains error details for failed requests
type APIError struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
ErrorChain []APIError `json:"error_chain,omitempty"`
}
// APIResponse represents a response from CloudFlare API
type APIResponse struct {
Success bool `json:"success"`
Errors []*APIError `json:"errors"`
Result json.RawMessage `json:"result"`
}
2017-02-07 21:33:23 +00:00
// cloudFlareRecord represents a CloudFlare DNS record
type cloudFlareRecord struct {
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
ID string `json:"id,omitempty"`
TTL int `json:"ttl,omitempty"`
ZoneID string `json:"zone_id,omitempty"`
}