rainyun.go raw

   1  // Package rainyun implements a DNS provider for solving the DNS-01 challenge using Rain Yun.
   2  package rainyun
   3  
   4  import (
   5  	"context"
   6  	"errors"
   7  	"fmt"
   8  	"net/http"
   9  	"strings"
  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/rainyun/internal"
  17  )
  18  
  19  // Environment variables names.
  20  const (
  21  	envNamespace = "RAINYUN_"
  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  var _ challenge.ProviderTimeout = (*DNSProvider)(nil)
  32  
  33  // Config is used to configure the creation of the DNSProvider.
  34  type Config struct {
  35  	APIKey string
  36  
  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, dns01.DefaultTTL),
  47  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 2*time.Minute),
  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  
  61  // NewDNSProvider returns a DNSProvider instance configured for Rain Yun.
  62  func NewDNSProvider() (*DNSProvider, error) {
  63  	values, err := env.Get(EnvAPIKey)
  64  	if err != nil {
  65  		return nil, fmt.Errorf("rainyun: %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 Rain Yun.
  75  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  76  	if config == nil {
  77  		return nil, errors.New("rainyun: the configuration of the DNS provider is nil")
  78  	}
  79  
  80  	client, err := internal.NewClient(config.APIKey)
  81  	if err != nil {
  82  		return nil, fmt.Errorf("rainyun: %w", err)
  83  	}
  84  
  85  	if config.HTTPClient != nil {
  86  		client.HTTPClient = config.HTTPClient
  87  	}
  88  
  89  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
  90  
  91  	return &DNSProvider{
  92  		config: config,
  93  		client: client,
  94  	}, nil
  95  }
  96  
  97  // Present creates a TXT record using the specified parameters.
  98  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
  99  	info := dns01.GetChallengeInfo(domain, keyAuth)
 100  
 101  	ctx := context.Background()
 102  
 103  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 104  	if err != nil {
 105  		return fmt.Errorf("rainyun: could not find zone for domain %q: %w", domain, err)
 106  	}
 107  
 108  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
 109  	if err != nil {
 110  		return fmt.Errorf("rainyun: %w", err)
 111  	}
 112  
 113  	domainID, err := d.findDomainID(ctx, dns01.UnFqdn(authZone))
 114  	if err != nil {
 115  		return fmt.Errorf("rainyun: find domain ID: %w", err)
 116  	}
 117  
 118  	record := internal.Record{
 119  		Host:     subDomain,
 120  		Priority: 10,
 121  		Line:     "DEFAULT",
 122  		TTL:      d.config.TTL,
 123  		Type:     "TXT",
 124  		Value:    info.Value,
 125  	}
 126  
 127  	err = d.client.AddRecord(ctx, domainID, record)
 128  	if err != nil {
 129  		return fmt.Errorf("rainyun: add record: %w", err)
 130  	}
 131  
 132  	return nil
 133  }
 134  
 135  // CleanUp removes the TXT record matching the specified parameters.
 136  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 137  	info := dns01.GetChallengeInfo(domain, keyAuth)
 138  
 139  	ctx := context.Background()
 140  
 141  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 142  	if err != nil {
 143  		return fmt.Errorf("rainyun: could not find zone for domain %q: %w", domain, err)
 144  	}
 145  
 146  	domainID, err := d.findDomainID(ctx, dns01.UnFqdn(authZone))
 147  	if err != nil {
 148  		return fmt.Errorf("rainyun: find domain ID: %w", err)
 149  	}
 150  
 151  	recordID, err := d.findRecordID(ctx, domainID, info)
 152  	if err != nil {
 153  		return fmt.Errorf("rainyun: find record ID: %w", err)
 154  	}
 155  
 156  	err = d.client.DeleteRecord(ctx, domainID, recordID)
 157  	if err != nil {
 158  		return fmt.Errorf("rainyun: delete record: %w", err)
 159  	}
 160  
 161  	return nil
 162  }
 163  
 164  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 165  // Adjusting here to cope with spikes in propagation times.
 166  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 167  	return d.config.PropagationTimeout, d.config.PollingInterval
 168  }
 169  
 170  func (d *DNSProvider) findDomainID(ctx context.Context, domain string) (int, error) {
 171  	domains, err := d.client.ListDomains(ctx)
 172  	if err != nil {
 173  		return 0, err
 174  	}
 175  
 176  	for _, dom := range domains {
 177  		if dom.Domain == domain {
 178  			return dom.ID, nil
 179  		}
 180  	}
 181  
 182  	return 0, fmt.Errorf("domain not found: %s", domain)
 183  }
 184  
 185  func (d *DNSProvider) findRecordID(ctx context.Context, domainID int, info dns01.ChallengeInfo) (int, error) {
 186  	records, err := d.client.ListRecords(ctx, domainID)
 187  	if err != nil {
 188  		return 0, fmt.Errorf("list records: %w", err)
 189  	}
 190  
 191  	zone := dns01.UnFqdn(info.EffectiveFQDN)
 192  
 193  	for _, record := range records {
 194  		if strings.HasPrefix(zone, record.Host) && record.Value == info.Value {
 195  			return record.ID, nil
 196  		}
 197  	}
 198  
 199  	return 0, fmt.Errorf("record not found: domainID=%d, fqdn=%s", domainID, info.EffectiveFQDN)
 200  }
 201