octenium.go raw

   1  // Package octenium implements a DNS provider for solving the DNS-01 challenge using Octenium.
   2  package octenium
   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/dns01"
  13  	"github.com/go-acme/lego/v4/log"
  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/octenium/internal"
  17  	"github.com/hashicorp/go-retryablehttp"
  18  )
  19  
  20  // Environment variables names.
  21  const (
  22  	envNamespace = "OCTENIUM_"
  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  )
  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, dns01.DefaultTTL),
  46  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
  47  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
  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  	domainIDs   map[string]string
  60  	domainIDsMu sync.Mutex
  61  }
  62  
  63  // NewDNSProvider returns a DNSProvider instance configured for Octenium.
  64  func NewDNSProvider() (*DNSProvider, error) {
  65  	values, err := env.Get(EnvAPIKey)
  66  	if err != nil {
  67  		return nil, fmt.Errorf("octenium: %w", err)
  68  	}
  69  
  70  	config := NewDefaultConfig()
  71  	config.APIKey = values[EnvAPIKey]
  72  
  73  	return NewDNSProviderConfig(config)
  74  }
  75  
  76  // NewDNSProviderConfig return a DNSProvider instance configured for Octenium.
  77  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  78  	if config == nil {
  79  		return nil, errors.New("octenium: the configuration of the DNS provider is nil")
  80  	}
  81  
  82  	client, err := internal.NewClient(config.APIKey)
  83  	if err != nil {
  84  		return nil, fmt.Errorf("octenium: %w", err)
  85  	}
  86  
  87  	if config.HTTPClient != nil {
  88  		client.HTTPClient = config.HTTPClient
  89  	}
  90  
  91  	retryClient := retryablehttp.NewClient()
  92  	retryClient.RetryMax = 5
  93  	retryClient.HTTPClient = client.HTTPClient
  94  	retryClient.Logger = log.Logger
  95  
  96  	client.HTTPClient = clientdebug.Wrap(retryClient.StandardClient())
  97  
  98  	return &DNSProvider{
  99  		config:    config,
 100  		client:    client,
 101  		domainIDs: make(map[string]string),
 102  	}, nil
 103  }
 104  
 105  // Present creates a TXT record using the specified parameters.
 106  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
 107  	ctx := context.Background()
 108  
 109  	info := dns01.GetChallengeInfo(domain, keyAuth)
 110  
 111  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 112  	if err != nil {
 113  		return fmt.Errorf("octenium: could not find zone for domain '%s': %w", domain, err)
 114  	}
 115  
 116  	domainID, err := d.getDomainID(ctx, authZone)
 117  	if err != nil {
 118  		return fmt.Errorf("octenium: get domain ID: %w", err)
 119  	}
 120  
 121  	d.domainIDsMu.Lock()
 122  	d.domainIDs[token] = domainID
 123  	d.domainIDsMu.Unlock()
 124  
 125  	record := internal.Record{
 126  		Type:  "TXT",
 127  		Name:  info.EffectiveFQDN,
 128  		TTL:   d.config.TTL,
 129  		Value: info.Value,
 130  	}
 131  
 132  	_, err = d.client.AddDNSRecord(ctx, domainID, record)
 133  	if err != nil {
 134  		return fmt.Errorf("octenium: add record: %w", err)
 135  	}
 136  
 137  	return nil
 138  }
 139  
 140  // CleanUp removes the TXT record matching the specified parameters.
 141  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 142  	ctx := context.Background()
 143  
 144  	info := dns01.GetChallengeInfo(domain, keyAuth)
 145  
 146  	d.domainIDsMu.Lock()
 147  	domainID, ok := d.domainIDs[token]
 148  	d.domainIDsMu.Unlock()
 149  
 150  	if !ok {
 151  		return fmt.Errorf("octenium: unknown domain ID for '%s'", info.EffectiveFQDN)
 152  	}
 153  
 154  	records, err := d.client.ListDNSRecords(ctx, domainID, "TXT")
 155  	if err != nil {
 156  		return fmt.Errorf("octenium: list records: %w", err)
 157  	}
 158  
 159  	for _, record := range records {
 160  		if record.Type != "TXT" || record.Name != info.EffectiveFQDN || record.Value != info.Value {
 161  			continue
 162  		}
 163  
 164  		_, err = d.client.DeleteDNSRecord(ctx, domainID, record.ID)
 165  		if err != nil {
 166  			return fmt.Errorf("octenium: delete record: %w", err)
 167  		}
 168  
 169  		break
 170  	}
 171  
 172  	d.domainIDsMu.Lock()
 173  	delete(d.domainIDs, token)
 174  	d.domainIDsMu.Unlock()
 175  
 176  	return nil
 177  }
 178  
 179  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 180  // Adjusting here to cope with spikes in propagation times.
 181  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 182  	return d.config.PropagationTimeout, d.config.PollingInterval
 183  }
 184  
 185  func (d *DNSProvider) getDomainID(ctx context.Context, authZone string) (string, error) {
 186  	domains, err := d.client.ListDomains(ctx, dns01.UnFqdn(authZone))
 187  	if err != nil {
 188  		return "", fmt.Errorf("list domains: %w", err)
 189  	}
 190  
 191  	if len(domains) == 0 {
 192  		return "", errors.New("domain not found")
 193  	}
 194  
 195  	if len(domains) > 1 {
 196  		return "", errors.New("multiple domains found")
 197  	}
 198  
 199  	for id := range domains {
 200  		return id, nil
 201  	}
 202  
 203  	return "", errors.New("domain ID not found")
 204  }
 205