arvancloud.go raw

   1  // Package arvancloud implements a DNS provider for solving the DNS-01 challenge using ArvanCloud DNS.
   2  package arvancloud
   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/arvancloud/internal"
  16  	"github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
  17  )
  18  
  19  // Environment variables names.
  20  const (
  21  	envNamespace = "ARVANCLOUD_"
  22  
  23  	EnvAPIKey = envNamespace + "API_KEY"
  24  
  25  	EnvTTL                = envNamespace + "TTL"
  26  	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
  27  	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
  28  	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
  29  )
  30  
  31  const minTTL = 600
  32  
  33  var _ challenge.ProviderTimeout = (*DNSProvider)(nil)
  34  
  35  // Config is used to configure the creation of the DNSProvider.
  36  type Config struct {
  37  	APIKey             string
  38  	PropagationTimeout time.Duration
  39  	PollingInterval    time.Duration
  40  	TTL                int
  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, minTTL),
  48  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second),
  49  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second),
  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]string
  62  	recordIDsMu sync.Mutex
  63  }
  64  
  65  // NewDNSProvider returns a DNSProvider instance configured for ArvanCloud.
  66  // Credentials must be passed in the environment variable: ARVANCLOUD_API_KEY.
  67  func NewDNSProvider() (*DNSProvider, error) {
  68  	values, err := env.Get(EnvAPIKey)
  69  	if err != nil {
  70  		return nil, fmt.Errorf("arvancloud: %w", err)
  71  	}
  72  
  73  	config := NewDefaultConfig()
  74  	config.APIKey = values[EnvAPIKey]
  75  
  76  	return NewDNSProviderConfig(config)
  77  }
  78  
  79  // NewDNSProviderConfig return a DNSProvider instance configured for ArvanCloud.
  80  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  81  	if config == nil {
  82  		return nil, errors.New("arvancloud: the configuration of the DNS provider is nil")
  83  	}
  84  
  85  	if config.APIKey == "" {
  86  		return nil, errors.New("arvancloud: credentials missing")
  87  	}
  88  
  89  	if config.TTL < minTTL {
  90  		return nil, fmt.Errorf("arvancloud: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
  91  	}
  92  
  93  	client := internal.NewClient(config.APIKey)
  94  
  95  	if config.HTTPClient != nil {
  96  		client.HTTPClient = config.HTTPClient
  97  	}
  98  
  99  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
 100  
 101  	return &DNSProvider{
 102  		config:    config,
 103  		client:    client,
 104  		recordIDs: make(map[string]string),
 105  	}, nil
 106  }
 107  
 108  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 109  // Adjusting here to cope with spikes in propagation times.
 110  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 111  	return d.config.PropagationTimeout, d.config.PollingInterval
 112  }
 113  
 114  // Present creates a TXT record to fulfill the dns-01 challenge.
 115  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
 116  	info := dns01.GetChallengeInfo(domain, keyAuth)
 117  
 118  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 119  	if err != nil {
 120  		return fmt.Errorf("arvancloud: could not find zone for domain %q: %w", domain, err)
 121  	}
 122  
 123  	authZone = dns01.UnFqdn(authZone)
 124  
 125  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
 126  	if err != nil {
 127  		return fmt.Errorf("arvancloud: %w", err)
 128  	}
 129  
 130  	record := internal.DNSRecord{
 131  		Type:          "txt",
 132  		Name:          subDomain,
 133  		Value:         internal.TXTRecordValue{Text: info.Value},
 134  		TTL:           d.config.TTL,
 135  		UpstreamHTTPS: "default",
 136  		IPFilterMode: &internal.IPFilterMode{
 137  			Count:     "single",
 138  			GeoFilter: "none",
 139  			Order:     "none",
 140  		},
 141  	}
 142  
 143  	newRecord, err := d.client.CreateRecord(context.Background(), authZone, record)
 144  	if err != nil {
 145  		return fmt.Errorf("arvancloud: failed to add TXT record: fqdn=%s: %w", info.EffectiveFQDN, err)
 146  	}
 147  
 148  	d.recordIDsMu.Lock()
 149  	d.recordIDs[token] = newRecord.ID
 150  	d.recordIDsMu.Unlock()
 151  
 152  	return nil
 153  }
 154  
 155  // CleanUp removes the TXT record matching the specified parameters.
 156  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 157  	info := dns01.GetChallengeInfo(domain, keyAuth)
 158  
 159  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 160  	if err != nil {
 161  		return fmt.Errorf("arvancloud: could not find zone for domain %q: %w", domain, err)
 162  	}
 163  
 164  	authZone = dns01.UnFqdn(authZone)
 165  
 166  	// gets the record's unique ID from when we created it
 167  	d.recordIDsMu.Lock()
 168  	recordID, ok := d.recordIDs[token]
 169  	d.recordIDsMu.Unlock()
 170  
 171  	if !ok {
 172  		return fmt.Errorf("arvancloud: unknown record ID for '%s' '%s'", info.EffectiveFQDN, token)
 173  	}
 174  
 175  	if err := d.client.DeleteRecord(context.Background(), authZone, recordID); err != nil {
 176  		return fmt.Errorf("arvancloud: failed to delete TXT record: id=%s: %w", recordID, err)
 177  	}
 178  
 179  	// deletes record ID from map
 180  	d.recordIDsMu.Lock()
 181  	delete(d.recordIDs, token)
 182  	d.recordIDsMu.Unlock()
 183  
 184  	return nil
 185  }
 186