hostinger.go raw

   1  // Package hostinger implements a DNS provider for solving the DNS-01 challenge using Hostinger.
   2  package hostinger
   3  
   4  import (
   5  	"context"
   6  	"errors"
   7  	"fmt"
   8  	"net/http"
   9  	"strconv"
  10  	"time"
  11  
  12  	"github.com/go-acme/lego/v4/challenge/dns01"
  13  	"github.com/go-acme/lego/v4/platform/config/env"
  14  	"github.com/go-acme/lego/v4/providers/dns/hostinger/internal"
  15  	"github.com/go-acme/lego/v4/providers/dns/internal/clientdebug"
  16  )
  17  
  18  // Environment variables names.
  19  const (
  20  	envNamespace = "HOSTINGER_"
  21  
  22  	EnvAPIToken = envNamespace + "API_TOKEN"
  23  
  24  	EnvTTL                = envNamespace + "TTL"
  25  	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
  26  	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
  27  	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
  28  )
  29  
  30  // Config is used to configure the creation of the DNSProvider.
  31  type Config struct {
  32  	APIToken string
  33  
  34  	PropagationTimeout time.Duration
  35  	PollingInterval    time.Duration
  36  	TTL                int
  37  	HTTPClient         *http.Client
  38  }
  39  
  40  // NewDefaultConfig returns a default configuration for the DNSProvider.
  41  func NewDefaultConfig() *Config {
  42  	return &Config{
  43  		TTL:                env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),
  44  		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
  45  		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
  46  		HTTPClient: &http.Client{
  47  			Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
  48  		},
  49  	}
  50  }
  51  
  52  // DNSProvider implements the challenge.Provider interface.
  53  type DNSProvider struct {
  54  	config *Config
  55  	client *internal.Client
  56  }
  57  
  58  // NewDNSProvider returns a DNSProvider instance configured for Hostinger.
  59  func NewDNSProvider() (*DNSProvider, error) {
  60  	values, err := env.Get(EnvAPIToken)
  61  	if err != nil {
  62  		return nil, fmt.Errorf("hostinger: %w", err)
  63  	}
  64  
  65  	config := NewDefaultConfig()
  66  	config.APIToken = values[EnvAPIToken]
  67  
  68  	return NewDNSProviderConfig(config)
  69  }
  70  
  71  // NewDNSProviderConfig return a DNSProvider instance configured for Hostinger.
  72  func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
  73  	if config == nil {
  74  		return nil, errors.New("hostinger: the configuration of the DNS provider is nil")
  75  	}
  76  
  77  	client, err := internal.NewClient(config.APIToken)
  78  	if err != nil {
  79  		return nil, fmt.Errorf("hostinger: %w", err)
  80  	}
  81  
  82  	if config.HTTPClient != nil {
  83  		client.HTTPClient = config.HTTPClient
  84  	}
  85  
  86  	client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
  87  
  88  	return &DNSProvider{
  89  		config: config,
  90  		client: client,
  91  	}, nil
  92  }
  93  
  94  // Present creates a TXT record using the specified parameters.
  95  func (d *DNSProvider) Present(domain, token, keyAuth string) error {
  96  	info := dns01.GetChallengeInfo(domain, keyAuth)
  97  
  98  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
  99  	if err != nil {
 100  		return fmt.Errorf("hostinger: could not find zone for domain %q: %w", domain, err)
 101  	}
 102  
 103  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
 104  	if err != nil {
 105  		return fmt.Errorf("hostinger: %w", err)
 106  	}
 107  
 108  	ctx := context.Background()
 109  
 110  	request := internal.ZoneRequest{
 111  		Overwrite: false,
 112  		Zone: []internal.RecordSet{{
 113  			Name: subDomain,
 114  			Type: "TXT",
 115  			TTL:  d.config.TTL,
 116  			Records: []internal.Record{
 117  				{Content: info.Value},
 118  			},
 119  		}},
 120  	}
 121  
 122  	err = d.client.UpdateDNSRecords(ctx, dns01.UnFqdn(authZone), request)
 123  	if err != nil {
 124  		return fmt.Errorf("hostinger: update DNS records (add): %w", err)
 125  	}
 126  
 127  	return nil
 128  }
 129  
 130  // CleanUp removes the TXT record matching the specified parameters.
 131  func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
 132  	info := dns01.GetChallengeInfo(domain, keyAuth)
 133  
 134  	authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
 135  	if err != nil {
 136  		return fmt.Errorf("hostinger: could not find zone for domain %q: %w", domain, err)
 137  	}
 138  
 139  	subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
 140  	if err != nil {
 141  		return fmt.Errorf("hostinger: %w", err)
 142  	}
 143  
 144  	ctx := context.Background()
 145  
 146  	recordSet, err := d.findRecordSet(ctx, authZone, subDomain)
 147  	if err != nil {
 148  		return fmt.Errorf("hostinger: %w", err)
 149  	}
 150  
 151  	var newRecords []internal.Record
 152  
 153  	for _, record := range recordSet.Records {
 154  		if record.Content == info.Value || record.Content == strconv.Quote(info.Value) {
 155  			continue
 156  		}
 157  
 158  		newRecords = append(newRecords, record)
 159  	}
 160  
 161  	recordSet.Records = newRecords
 162  
 163  	if len(recordSet.Records) > 0 {
 164  		request := internal.ZoneRequest{
 165  			Overwrite: true,
 166  			Zone:      []internal.RecordSet{recordSet},
 167  		}
 168  
 169  		err = d.client.UpdateDNSRecords(ctx, dns01.UnFqdn(authZone), request)
 170  		if err != nil {
 171  			return fmt.Errorf("hostinger: update DNS records (delete): %w", err)
 172  		}
 173  
 174  		return nil
 175  	}
 176  
 177  	filters := []internal.Filter{{
 178  		Name: subDomain,
 179  		Type: "TXT",
 180  	}}
 181  
 182  	err = d.client.DeleteDNSRecords(ctx, dns01.UnFqdn(authZone), filters)
 183  	if err != nil {
 184  		return fmt.Errorf("hostinger: delete DNS records: %w", err)
 185  	}
 186  
 187  	return nil
 188  }
 189  
 190  // Timeout returns the timeout and interval to use when checking for DNS propagation.
 191  // Adjusting here to cope with spikes in propagation times.
 192  func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
 193  	return d.config.PropagationTimeout, d.config.PollingInterval
 194  }
 195  
 196  func (d *DNSProvider) findRecordSet(ctx context.Context, authZone, subDomain string) (internal.RecordSet, error) {
 197  	recordSets, err := d.client.GetDNSRecords(ctx, dns01.UnFqdn(authZone))
 198  	if err != nil {
 199  		return internal.RecordSet{}, fmt.Errorf("get DNS records: %w", err)
 200  	}
 201  
 202  	for _, recordSet := range recordSets {
 203  		if recordSet.Name != subDomain || recordSet.Type != "TXT" {
 204  			continue
 205  		}
 206  
 207  		return recordSet, nil
 208  	}
 209  
 210  	return internal.RecordSet{}, fmt.Errorf("no record found for domain %q and subdomain %q", authZone, subDomain)
 211  }
 212