njalla.go raw

   1  // Package njalla implements a DNS provider for solving the DNS-01 challenge using Njalla.
   2  package njalla
   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/internal/clientdebug"
  16  	"github.com/go-acme/lego/v4/providers/dns/njalla/internal"
  17  	"github.com/miekg/dns"
  18  )
  19  
  20  // Environment variables names.
  21  const (
  22  	envNamespace = "NJALLA_"
  23  
  24  	EnvToken = envNamespace + "TOKEN"
  25  
  26  	EnvTTL                = envNamespace + "TTL"
  27  	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
  28  	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
  29  	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
  30  )
  31  
  32  var _ challenge.ProviderTimeout = (*DNSProvider)(nil)
  33  
  34  // Config is used to configure the creation of the DNSProvider.
  35  type Config struct {
  36  	Token              string
  37  	PropagationTimeout time.Duration
  38  	PollingInterval    time.Duration
  39  	TTL                int
  40  	HTTPClient         *http.Client
  41  }
  42  
  43  // NewDefaultConfig returns a default configuration for the DNSProvider.
  44  func NewDefaultConfig() *Config {
  45  	return &Config{
  46  		TTL:                env.GetOrDefaultInt(EnvTTL, 300),
  47  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
  48  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
  49  		HTTPClient: &http.Client{
  50  			Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
  51  		},
  52  	}
  53  }
  54  
  55  // DNSProvider implements the challenge.Provider interface.
  56  type DNSProvider struct {
  57  	config *Config
  58  	client *internal.Client
  59  
  60  	recordIDs   map[string]string
  61  	recordIDsMu sync.Mutex
  62  }
  63  
  64  // NewDNSProvider returns a DNSProvider instance configured for Njalla.
  65  // Credentials must be passed in the environment variable: NJALLA_TOKEN.
  66  func NewDNSProvider() (*DNSProvider, error) {
  67  	values, err := env.Get(EnvToken)
  68  	if err != nil {
  69  		return nil, fmt.Errorf("njalla: %w", err)
  70  	}
  71  
  72  	config := NewDefaultConfig()
  73  	config.Token = values[EnvToken]
  74  
  75  	return NewDNSProviderConfig(config)
  76  }
  77  
  78  // NewDNSProviderConfig return a DNSProvider instance configured for Njalla.
  79  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  80  	if config == nil {
  81  		return nil, errors.New("njalla: the configuration of the DNS provider is nil")
  82  	}
  83  
  84  	if config.Token == "" {
  85  		return nil, errors.New("njalla: missing credentials")
  86  	}
  87  
  88  	client := internal.NewClient(config.Token)
  89  
  90  	if config.HTTPClient != nil {
  91  		client.HTTPClient = config.HTTPClient
  92  	}
  93  
  94  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
  95  
  96  	return &DNSProvider{
  97  		config:    config,
  98  		client:    client,
  99  		recordIDs: make(map[string]string),
 100  	}, nil
 101  }
 102  
 103  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 104  // Adjusting here to cope with spikes in propagation times.
 105  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 106  	return d.config.PropagationTimeout, d.config.PollingInterval
 107  }
 108  
 109  // Present creates a TXT record using the specified parameters.
 110  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
 111  	info := dns01.GetChallengeInfo(domain, keyAuth)
 112  
 113  	rootDomain, subDomain, err := splitDomain(info.EffectiveFQDN)
 114  	if err != nil {
 115  		return fmt.Errorf("njalla: %w", err)
 116  	}
 117  
 118  	record := internal.Record{
 119  		Name:    subDomain,                // TODO need to be tested
 120  		Domain:  dns01.UnFqdn(rootDomain), // TODO need to be tested
 121  		Content: info.Value,
 122  		TTL:     d.config.TTL,
 123  		Type:    "TXT",
 124  	}
 125  
 126  	resp, err := d.client.AddRecord(context.Background(), record)
 127  	if err != nil {
 128  		return fmt.Errorf("njalla: failed to add record: %w", err)
 129  	}
 130  
 131  	d.recordIDsMu.Lock()
 132  	d.recordIDs[token] = resp.ID
 133  	d.recordIDsMu.Unlock()
 134  
 135  	return nil
 136  }
 137  
 138  // CleanUp removes the TXT record matching the specified parameters.
 139  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 140  	info := dns01.GetChallengeInfo(domain, keyAuth)
 141  
 142  	rootDomain, _, err := splitDomain(info.EffectiveFQDN)
 143  	if err != nil {
 144  		return fmt.Errorf("njalla: %w", err)
 145  	}
 146  
 147  	// gets the record's unique ID from when we created it
 148  	d.recordIDsMu.Lock()
 149  	recordID, ok := d.recordIDs[token]
 150  	d.recordIDsMu.Unlock()
 151  
 152  	if !ok {
 153  		return fmt.Errorf("njalla: unknown record ID for '%s' '%s'", info.EffectiveFQDN, token)
 154  	}
 155  
 156  	err = d.client.RemoveRecord(context.Background(), recordID, dns01.UnFqdn(rootDomain))
 157  	if err != nil {
 158  		return fmt.Errorf("njalla: failed to delete TXT records: fqdn=%s, recordID=%s: %w", info.EffectiveFQDN, recordID, err)
 159  	}
 160  
 161  	// deletes record ID from map
 162  	d.recordIDsMu.Lock()
 163  	delete(d.recordIDs, token)
 164  	d.recordIDsMu.Unlock()
 165  
 166  	return nil
 167  }
 168  
 169  func splitDomain(full string) (string, string, error) {
 170  	split := dns.Split(full)
 171  	if len(split) < 2 {
 172  		return "", "", fmt.Errorf("unsupported domain: %s", full)
 173  	}
 174  
 175  	if len(split) == 2 {
 176  		return full, "", nil
 177  	}
 178  
 179  	domain := full[split[len(split)-2]:]
 180  	subDomain := full[:split[len(split)-2]-1]
 181  
 182  	return domain, subDomain, nil
 183  }
 184