alwaysdata.go raw

   1  // Package alwaysdata implements a DNS provider for solving the DNS-01 challenge using Alwaysdata.
   2  package alwaysdata
   3  
   4  import (
   5  	"context"
   6  	"errors"
   7  	"fmt"
   8  	"net/http"
   9  	"time"
  10  
  11  	"github.com/go-acme/lego/v4/challenge/dns01"
  12  	"github.com/go-acme/lego/v4/platform/config/env"
  13  	"github.com/go-acme/lego/v4/providers/dns/alwaysdata/internal"
  14  	"github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
  15  )
  16  
  17  // Environment variables names.
  18  const (
  19  	envNamespace = "ALWAYSDATA_"
  20  
  21  	EnvAPIKey  = envNamespace + "API_KEY"
  22  	EnvAccount = envNamespace + "ACCOUNT"
  23  
  24  	EnvTTL                = envNamespace + "TTL"
  25  	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
  26  	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
  27  	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
  28  )
  29  
  30  // Config is used to configure the creation of the DNSProvider.
  31  type Config struct {
  32  	APIKey  string
  33  	Account string
  34  
  35  	PropagationTimeout time.Duration
  36  	PollingInterval    time.Duration
  37  	TTL                int
  38  	HTTPClient         *http.Client
  39  }
  40  
  41  // NewDefaultConfig returns a default configuration for the DNSProvider.
  42  func NewDefaultConfig() *Config {
  43  	return &Config{
  44  		TTL:                env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),
  45  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
  46  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
  47  		HTTPClient: &http.Client{
  48  			Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
  49  		},
  50  	}
  51  }
  52  
  53  // DNSProvider implements the challenge.Provider interface.
  54  type DNSProvider struct {
  55  	config *Config
  56  	client *internal.Client
  57  }
  58  
  59  // NewDNSProvider returns a DNSProvider instance configured for Alwaysdata.
  60  func NewDNSProvider() (*DNSProvider, error) {
  61  	values, err := env.Get(EnvAPIKey)
  62  	if err != nil {
  63  		return nil, fmt.Errorf("alwaysdata: %w", err)
  64  	}
  65  
  66  	config := NewDefaultConfig()
  67  	config.APIKey = values[EnvAPIKey]
  68  	config.Account = env.GetOrFile(EnvAccount)
  69  
  70  	return NewDNSProviderConfig(config)
  71  }
  72  
  73  // NewDNSProviderConfig return a DNSProvider instance configured for Alwaysdata.
  74  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  75  	if config == nil {
  76  		return nil, errors.New("alwaysdata: the configuration of the DNS provider is nil")
  77  	}
  78  
  79  	client, err := internal.NewClient(config.APIKey, config.Account)
  80  	if err != nil {
  81  		return nil, fmt.Errorf("alwaysdata: %w", err)
  82  	}
  83  
  84  	if config.HTTPClient != nil {
  85  		client.HTTPClient = config.HTTPClient
  86  	}
  87  
  88  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
  89  
  90  	return &DNSProvider{
  91  		config: config,
  92  		client: client,
  93  	}, nil
  94  }
  95  
  96  // Present creates a TXT record using the specified parameters.
  97  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
  98  	ctx := context.Background()
  99  
 100  	info := dns01.GetChallengeInfo(domain, keyAuth)
 101  
 102  	zone, err := d.findZone(ctx, info.EffectiveFQDN)
 103  	if err != nil {
 104  		return fmt.Errorf("alwaysdata: %w", err)
 105  	}
 106  
 107  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, zone.Name)
 108  	if err != nil {
 109  		return fmt.Errorf("alwaysdata: %w", err)
 110  	}
 111  
 112  	record := internal.RecordRequest{
 113  		DomainID:   zone.ID,
 114  		Name:       subDomain,
 115  		Type:       "TXT",
 116  		Value:      info.Value,
 117  		TTL:        d.config.TTL,
 118  		Annotation: "lego",
 119  	}
 120  
 121  	err = d.client.AddRecord(ctx, record)
 122  	if err != nil {
 123  		return fmt.Errorf("alwaysdata: add TXT record: %w", err)
 124  	}
 125  
 126  	return nil
 127  }
 128  
 129  // CleanUp removes the TXT record matching the specified parameters.
 130  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 131  	ctx := context.Background()
 132  
 133  	info := dns01.GetChallengeInfo(domain, keyAuth)
 134  
 135  	zone, err := d.findZone(ctx, info.EffectiveFQDN)
 136  	if err != nil {
 137  		return fmt.Errorf("alwaysdata: %w", err)
 138  	}
 139  
 140  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, zone.Name)
 141  	if err != nil {
 142  		return fmt.Errorf("alwaysdata: %w", err)
 143  	}
 144  
 145  	records, err := d.client.ListRecords(ctx, zone.ID, subDomain)
 146  	if err != nil {
 147  		return fmt.Errorf("alwaysdata: list records: %w", err)
 148  	}
 149  
 150  	for _, record := range records {
 151  		if record.Type != "TXT" || record.Value != info.Value {
 152  			continue
 153  		}
 154  
 155  		err = d.client.DeleteRecord(ctx, record.ID)
 156  		if err != nil {
 157  			return fmt.Errorf("alwaysdata: delete TXT record: %w", err)
 158  		}
 159  	}
 160  
 161  	return nil
 162  }
 163  
 164  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 165  // Adjusting here to cope with spikes in propagation times.
 166  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 167  	return d.config.PropagationTimeout, d.config.PollingInterval
 168  }
 169  
 170  func (d *DNSProvider) findZone(ctx context.Context, fqdn string) (*internal.Domain, error) {
 171  	domains, err := d.client.ListDomains(ctx)
 172  	if err != nil {
 173  		return nil, fmt.Errorf("list domains: %w", err)
 174  	}
 175  
 176  	for a := range dns01.UnFqdnDomainsSeq(fqdn) {
 177  		for _, domain := range domains {
 178  			if a == domain.Name {
 179  				return &domain, nil
 180  			}
 181  		}
 182  	}
 183  
 184  	return nil, errors.New("domain not found")
 185  }
 186