limacity.go raw

   1  // Package limacity implements a DNS provider for solving the DNS-01 challenge using Lima-City DNS.
   2  package limacity
   3  
   4  import (
   5  	"context"
   6  	"errors"
   7  	"fmt"
   8  	"net/http"
   9  	"strconv"
  10  	"sync"
  11  	"time"
  12  
  13  	"github.com/go-acme/lego/v4/challenge"
  14  	"github.com/go-acme/lego/v4/challenge/dns01"
  15  	"github.com/go-acme/lego/v4/platform/config/env"
  16  	"github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
  17  	"github.com/go-acme/lego/v4/providers/dns/limacity/internal"
  18  )
  19  
  20  // Environment variables names.
  21  const (
  22  	envNamespace = "LIMACITY_"
  23  
  24  	EnvAPIKey = envNamespace + "API_KEY"
  25  
  26  	EnvTTL                = envNamespace + "TTL"
  27  	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
  28  	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
  29  	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
  30  	EnvSequenceInterval   = envNamespace + "SEQUENCE_INTERVAL"
  31  )
  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  	TTL                int
  39  	PropagationTimeout time.Duration
  40  	PollingInterval    time.Duration
  41  	SequenceInterval   time.Duration
  42  	HTTPClient         *http.Client
  43  }
  44  
  45  // NewDefaultConfig returns a default configuration for the DNSProvider.
  46  func NewDefaultConfig() *Config {
  47  	return &Config{
  48  		TTL:                env.GetOrDefaultInt(EnvTTL, 60),
  49  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 8*time.Minute),
  50  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, 80*time.Second),
  51  		SequenceInterval:   env.GetOrDefaultSecond(EnvSequenceInterval, 90*time.Second),
  52  		HTTPClient: &http.Client{
  53  			Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
  54  		},
  55  	}
  56  }
  57  
  58  // DNSProvider implements the challenge.Provider interface.
  59  type DNSProvider struct {
  60  	config *Config
  61  	client *internal.Client
  62  
  63  	domainIDs   map[string]int
  64  	domainIDsMu sync.Mutex
  65  }
  66  
  67  // NewDNSProvider returns a DNSProvider instance configured for Lima-City DNS.
  68  // LIMACITY_API_KEY must be passed in the environment variables.
  69  func NewDNSProvider() (*DNSProvider, error) {
  70  	values, err := env.Get(EnvAPIKey)
  71  	if err != nil {
  72  		return nil, fmt.Errorf("limacity: %w", err)
  73  	}
  74  
  75  	config := NewDefaultConfig()
  76  	config.APIKey = values[EnvAPIKey]
  77  
  78  	return NewDNSProviderConfig(config)
  79  }
  80  
  81  // NewDNSProviderConfig return a DNSProvider instance configured for Lima-City DNS.
  82  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  83  	if config == nil {
  84  		return nil, errors.New("limacity: the configuration of the DNS provider is nil")
  85  	}
  86  
  87  	if config.APIKey == "" {
  88  		return nil, errors.New("limacity: APIKey is missing")
  89  	}
  90  
  91  	client := internal.NewClient(config.APIKey)
  92  
  93  	if config.HTTPClient != nil {
  94  		client.HTTPClient = config.HTTPClient
  95  	}
  96  
  97  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
  98  
  99  	return &DNSProvider{
 100  		config:    config,
 101  		client:    client,
 102  		domainIDs: make(map[string]int),
 103  	}, nil
 104  }
 105  
 106  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 107  // Adjusting here to cope with spikes in propagation times.
 108  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 109  	return d.config.PropagationTimeout, d.config.PollingInterval
 110  }
 111  
 112  // Sequential All DNS challenges for this provider will be resolved sequentially.
 113  // Returns the interval between each iteration.
 114  func (d *DNSProvider) Sequential() time.Duration {
 115  	return d.config.SequenceInterval
 116  }
 117  
 118  // Present creates a TXT record to fulfill the dns-01 challenge.
 119  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
 120  	ctx := context.Background()
 121  
 122  	info := dns01.GetChallengeInfo(domain, keyAuth)
 123  
 124  	domains, err := d.client.GetDomains(ctx)
 125  	if err != nil {
 126  		return fmt.Errorf("limacity: get domains: %w", err)
 127  	}
 128  
 129  	dom, err := findDomain(domains, info.EffectiveFQDN)
 130  	if err != nil {
 131  		return fmt.Errorf("limacity: find domain: %w", err)
 132  	}
 133  
 134  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, dom.UnicodeFqdn)
 135  	if err != nil {
 136  		return fmt.Errorf("limacity: %w", err)
 137  	}
 138  
 139  	record := internal.Record{
 140  		Name:    subDomain,
 141  		Content: info.Value,
 142  		TTL:     d.config.TTL,
 143  		Type:    "TXT",
 144  	}
 145  
 146  	err = d.client.AddRecord(ctx, dom.ID, record)
 147  	if err != nil {
 148  		return fmt.Errorf("limacity: add record: %w", err)
 149  	}
 150  
 151  	d.domainIDsMu.Lock()
 152  	d.domainIDs[token] = dom.ID
 153  	d.domainIDsMu.Unlock()
 154  
 155  	return nil
 156  }
 157  
 158  // CleanUp removes the TXT record.
 159  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 160  	ctx := context.Background()
 161  
 162  	info := dns01.GetChallengeInfo(domain, keyAuth)
 163  
 164  	// gets the domain's unique ID
 165  	d.domainIDsMu.Lock()
 166  	domainID, ok := d.domainIDs[token]
 167  	d.domainIDsMu.Unlock()
 168  
 169  	if !ok {
 170  		return fmt.Errorf("limacity: unknown domain ID for '%s' '%s'", info.EffectiveFQDN, token)
 171  	}
 172  
 173  	records, err := d.client.GetRecords(ctx, domainID)
 174  	if err != nil {
 175  		return fmt.Errorf("limacity: get records: %w", err)
 176  	}
 177  
 178  	var recordID int
 179  
 180  	for _, record := range records {
 181  		if record.Type == "TXT" && record.Content == strconv.Quote(info.Value) {
 182  			recordID = record.ID
 183  			break
 184  		}
 185  	}
 186  
 187  	if recordID == 0 {
 188  		return errors.New("limacity: TXT record not found")
 189  	}
 190  
 191  	err = d.client.DeleteRecord(ctx, domainID, recordID)
 192  	if err != nil {
 193  		return fmt.Errorf("limacity: delete record (domain ID=%d, record ID=%d): %w", domainID, recordID, err)
 194  	}
 195  
 196  	d.domainIDsMu.Lock()
 197  	delete(d.domainIDs, info.EffectiveFQDN)
 198  	d.domainIDsMu.Unlock()
 199  
 200  	return nil
 201  }
 202  
 203  func findDomain(domains []internal.Domain, fqdn string) (internal.Domain, error) {
 204  	for f := range dns01.DomainsSeq(fqdn) {
 205  		domain := dns01.UnFqdn(f)
 206  
 207  		for _, dom := range domains {
 208  			if dom.UnicodeFqdn == domain || dom.UnicodeFqdn == f {
 209  				return dom, nil
 210  			}
 211  		}
 212  	}
 213  
 214  	return internal.Domain{}, fmt.Errorf("domain %s not found", fqdn)
 215  }
 216