dynu.go raw

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