safedns.go raw

   1  // Package safedns implements a DNS provider for solving the DNS-01 challenge using UKFast SafeDNS.
   2  package safedns
   3  
   4  import (
   5  	"context"
   6  	"errors"
   7  	"fmt"
   8  	"net/http"
   9  	"sync"
  10  	"time"
  11  
  12  	"github.com/go-acme/lego/v4/challenge"
  13  	"github.com/go-acme/lego/v4/challenge/dns01"
  14  	"github.com/go-acme/lego/v4/platform/config/env"
  15  	"github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
  16  	"github.com/go-acme/lego/v4/providers/dns/safedns/internal"
  17  	"github.com/miekg/dns"
  18  )
  19  
  20  // Environment variables.
  21  const (
  22  	envNamespace = "SAFEDNS_"
  23  
  24  	EnvAuthToken = envNamespace + "AUTH_TOKEN"
  25  
  26  	EnvTTL                = envNamespace + "TTL"
  27  	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
  28  	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
  29  	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
  30  )
  31  
  32  var _ challenge.ProviderTimeout = (*DNSProvider)(nil)
  33  
  34  // Config is used to configure the creation of the DNSProvider.
  35  type Config struct {
  36  	AuthToken string
  37  
  38  	TTL                int
  39  	PropagationTimeout time.Duration
  40  	PollingInterval    time.Duration
  41  	HTTPClient         *http.Client
  42  }
  43  
  44  // NewDefaultConfig returns a default configuration for the DNSProvider.
  45  func NewDefaultConfig() *Config {
  46  	return &Config{
  47  		TTL:                env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),
  48  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
  49  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
  50  		HTTPClient: &http.Client{
  51  			Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
  52  		},
  53  	}
  54  }
  55  
  56  // DNSProvider implements the challenge.Provider interface.
  57  type DNSProvider struct {
  58  	config *Config
  59  	client *internal.Client
  60  
  61  	recordIDs   map[string]int
  62  	recordIDsMu sync.Mutex
  63  }
  64  
  65  // NewDNSProvider returns a DNSProvider instance.
  66  func NewDNSProvider() (*DNSProvider, error) {
  67  	values, err := env.Get(EnvAuthToken)
  68  	if err != nil {
  69  		return nil, fmt.Errorf("safedns: %w", err)
  70  	}
  71  
  72  	config := NewDefaultConfig()
  73  	config.AuthToken = values[EnvAuthToken]
  74  
  75  	return NewDNSProviderConfig(config)
  76  }
  77  
  78  // NewDNSProviderConfig return a DNSProvider instance configured for UKFast SafeDNS.
  79  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  80  	if config == nil {
  81  		return nil, errors.New("safedns: supplied configuration was nil")
  82  	}
  83  
  84  	if config.AuthToken == "" {
  85  		return nil, errors.New("safedns: credentials missing")
  86  	}
  87  
  88  	client := internal.NewClient(config.AuthToken)
  89  
  90  	if config.HTTPClient != nil {
  91  		client.HTTPClient = config.HTTPClient
  92  	}
  93  
  94  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
  95  
  96  	return &DNSProvider{
  97  		config:    config,
  98  		client:    client,
  99  		recordIDs: make(map[string]int),
 100  	}, nil
 101  }
 102  
 103  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 104  // Adjusting here to cope with spikes in propagation times.
 105  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 106  	return d.config.PropagationTimeout, d.config.PollingInterval
 107  }
 108  
 109  // Present creates a TXT record to fulfill the dns-01 challenge.
 110  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
 111  	info := dns01.GetChallengeInfo(domain, keyAuth)
 112  
 113  	zone, err := dns01.FindZoneByFqdn(dns.Fqdn(info.EffectiveFQDN))
 114  	if err != nil {
 115  		return fmt.Errorf("safedns: could not find zone for domain %q: %w", domain, err)
 116  	}
 117  
 118  	record := internal.Record{
 119  		Name:    dns01.UnFqdn(info.EffectiveFQDN),
 120  		Type:    "TXT",
 121  		Content: fmt.Sprintf("%q", info.Value),
 122  		TTL:     d.config.TTL,
 123  	}
 124  
 125  	resp, err := d.client.AddRecord(context.Background(), zone, record)
 126  	if err != nil {
 127  		return fmt.Errorf("safedns: %w", err)
 128  	}
 129  
 130  	d.recordIDsMu.Lock()
 131  	d.recordIDs[token] = resp.Data.ID
 132  	d.recordIDsMu.Unlock()
 133  
 134  	return nil
 135  }
 136  
 137  // CleanUp removes the TXT record previously created.
 138  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 139  	info := dns01.GetChallengeInfo(domain, keyAuth)
 140  
 141  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 142  	if err != nil {
 143  		return fmt.Errorf("safedns: could not find zone for domain %q: %w", domain, err)
 144  	}
 145  
 146  	d.recordIDsMu.Lock()
 147  	recordID, ok := d.recordIDs[token]
 148  	d.recordIDsMu.Unlock()
 149  
 150  	if !ok {
 151  		return fmt.Errorf("safedns: unknown record ID for '%s'", info.EffectiveFQDN)
 152  	}
 153  
 154  	err = d.client.RemoveRecord(context.Background(), authZone, recordID)
 155  	if err != nil {
 156  		return fmt.Errorf("safedns: %w", err)
 157  	}
 158  
 159  	d.recordIDsMu.Lock()
 160  	delete(d.recordIDs, token)
 161  	d.recordIDsMu.Unlock()
 162  
 163  	return nil
 164  }
 165