diff --git a/.golangci.toml b/.golangci.toml index e5821edc..b6aed20b 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -118,3 +118,6 @@ [[issues.exclude-rules]] path = "cmd/zz_gen_cmd_dnshelp.go" linters = ["gocyclo", "funlen"] + [[issues.exclude-rules]] + path = "providers/dns/checkdomain/client.go" + text = "`payed` is a misspelling of `paid`" diff --git a/README.md b/README.md index 704caccf..fb8bf88b 100644 --- a/README.md +++ b/README.md @@ -45,17 +45,17 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). |---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------| | [Alibaba Cloud DNS](https://go-acme.github.io/lego/dns/alidns/) | [Amazon Lightsail](https://go-acme.github.io/lego/dns/lightsail/) | [Amazon Route 53](https://go-acme.github.io/lego/dns/route53/) | [Aurora DNS](https://go-acme.github.io/lego/dns/auroradns/) | | [Autodns](https://go-acme.github.io/lego/dns/autodns/) | [Azure](https://go-acme.github.io/lego/dns/azure/) | [Bindman](https://go-acme.github.io/lego/dns/bindman/) | [Bluecat](https://go-acme.github.io/lego/dns/bluecat/) | -| [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) | [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) | [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | -| [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | -| [DNSPod](https://go-acme.github.io/lego/dns/dnspod/) | [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | -| [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) | [External program](https://go-acme.github.io/lego/dns/exec/) | -| [FastDNS](https://go-acme.github.io/lego/dns/fastdns/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | [Gandi](https://go-acme.github.io/lego/dns/gandi/) | [Glesys](https://go-acme.github.io/lego/dns/glesys/) | -| [Go Daddy](https://go-acme.github.io/lego/dns/godaddy/) | [Google Cloud](https://go-acme.github.io/lego/dns/gcloud/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | -| [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns) | -| [Linode (deprecated)](https://go-acme.github.io/lego/dns/linode/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linodev4/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | -| [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | [Name.com](https://go-acme.github.io/lego/dns/namedotcom/) | [Namecheap](https://go-acme.github.io/lego/dns/namecheap/) | [Namesilo](https://go-acme.github.io/lego/dns/namesilo/) | -| [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | [NS1](https://go-acme.github.io/lego/dns/ns1/) | [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) | -| [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | [OVH](https://go-acme.github.io/lego/dns/ovh/) | [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | -| [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | -| [TransIP](https://go-acme.github.io/lego/dns/transip/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Versio](https://go-acme.github.io/lego/dns/versio/) | -| [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) +| [Checkdomain](https://go-acme.github.io/lego/dns/checkdomain/) | [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) | [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) | [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | +| [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | +| [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | [DNSPod](https://go-acme.github.io/lego/dns/dnspod/) | [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | +| [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) | +| [External program](https://go-acme.github.io/lego/dns/exec/) | [FastDNS](https://go-acme.github.io/lego/dns/fastdns/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | [Gandi](https://go-acme.github.io/lego/dns/gandi/) | +| [Glesys](https://go-acme.github.io/lego/dns/glesys/) | [Go Daddy](https://go-acme.github.io/lego/dns/godaddy/) | [Google Cloud](https://go-acme.github.io/lego/dns/gcloud/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | +| [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | +| [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns) | [Linode (deprecated)](https://go-acme.github.io/lego/dns/linode/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linodev4/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | +| [Manual](https://go-acme.github.io/lego/dns/manual/) | [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | [Name.com](https://go-acme.github.io/lego/dns/namedotcom/) | [Namecheap](https://go-acme.github.io/lego/dns/namecheap/) | +| [Namesilo](https://go-acme.github.io/lego/dns/namesilo/) | [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | [NS1](https://go-acme.github.io/lego/dns/ns1/) | +| [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) | [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | [OVH](https://go-acme.github.io/lego/dns/ovh/) | [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | +| [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | +| [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | +| [Versio](https://go-acme.github.io/lego/dns/versio/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | | diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 5dbe76ce..b52b9923 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -21,6 +21,7 @@ func allDNSCodes() string { "azure", "bindman", "bluecat", + "checkdomain", "cloudflare", "cloudns", "cloudxns", @@ -233,6 +234,27 @@ func displayDNSHelp(name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/bluecat`) + case "checkdomain": + // generated from: providers/dns/checkdomain/checkdomain.toml + ew.writeln(`Configuration for Checkdomain.`) + ew.writeln(`Code: 'checkdomain'`) + ew.writeln(`Since: 'v3.3.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "CHECKDOMAIN_TOKEN": API token`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "CHECKDOMAIN_ENDPOINT": API endpoint URL, defaults to https://api.checkdomain.de`) + ew.writeln(` - "CHECKDOMAIN_HTTP_TIMEOUT": API request timeout, defaults to 30 seconds`) + ew.writeln(` - "CHECKDOMAIN_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "CHECKDOMAIN_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "CHECKDOMAIN_TTL": The TTL of the TXT record used for the DNS challenge`) + + ew.writeln() + ew.writeln(`More information: https://go-acme.github.io/lego/dns/checkdomain`) + case "cloudflare": // generated from: providers/dns/cloudflare/cloudflare.toml ew.writeln(`Configuration for Cloudflare.`) diff --git a/docs/content/dns/zz_gen_checkdomain.md b/docs/content/dns/zz_gen_checkdomain.md new file mode 100644 index 00000000..de63006e --- /dev/null +++ b/docs/content/dns/zz_gen_checkdomain.md @@ -0,0 +1,63 @@ +--- +title: "Checkdomain" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: checkdomain +--- + + + + + +Since: v3.3.0 + +Configuration for [Checkdomain](https://checkdomain.de/). + + + + +- Code: `checkdomain` + +Here is an example bash command using the Checkdomain provider: + +```bash +CHECKDOMAIN_TOKEN=yoursecrettoken \ +lego --dns checkdomain --domains my.domain.com --email my@email.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `CHECKDOMAIN_TOKEN` | API token | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here](/lego/dns/#configuration-and-credentials). + + +## Additional Configuration + +| Environment Variable Name | Description | +|--------------------------------|-------------| +| `CHECKDOMAIN_ENDPOINT` | API endpoint URL, defaults to https://api.checkdomain.de | +| `CHECKDOMAIN_HTTP_TIMEOUT` | API request timeout, defaults to 30 seconds | +| `CHECKDOMAIN_POLLING_INTERVAL` | Time between DNS propagation check | +| `CHECKDOMAIN_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `CHECKDOMAIN_TTL` | The TTL of the TXT record used for the DNS challenge | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here](/lego/dns/#configuration-and-credentials). + + + + +## More information + +- [API documentation](https://developer.checkdomain.de/reference/) + + + + diff --git a/providers/dns/checkdomain/checkdomain.go b/providers/dns/checkdomain/checkdomain.go new file mode 100644 index 00000000..4235e839 --- /dev/null +++ b/providers/dns/checkdomain/checkdomain.go @@ -0,0 +1,152 @@ +package checkdomain + +import ( + "fmt" + "net/http" + "net/url" + "sync" + "time" + + "github.com/go-acme/lego/v3/challenge/dns01" + "github.com/go-acme/lego/v3/platform/config/env" +) + +const ( + envEndpoint = "CHECKDOMAIN_ENDPOINT" + envToken = "CHECKDOMAIN_TOKEN" + envTTL = "CHECKDOMAIN_TTL" + envHTTPTimeout = "CHECKDOMAIN_HTTP_TIMEOUT" + envPropagationTimeout = "CHECKDOMAIN_PROPAGATION_TIMEOUT" + envPollingInterval = "CHECKDOMAIN_POLLING_INTERVAL" +) + +const ( + defaultEndpoint = "https://api.checkdomain.de" + defaultTTL = 300 +) + +// Config is used to configure the creation of the DNSProvider +type Config struct { + Endpoint *url.URL + Token string + TTL int + PropagationTimeout time.Duration + PollingInterval time.Duration + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(envTTL, defaultTTL), + PropagationTimeout: env.GetOrDefaultSecond(envPropagationTimeout, 5*time.Minute), + PollingInterval: env.GetOrDefaultSecond(envPollingInterval, 7*time.Second), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(envHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements challenge.Provider for the checkdomain API +// specified at https://developer.checkdomain.de/reference/. +type DNSProvider struct { + config *Config + + domainIDMu sync.Mutex + domainIDMapping map[string]int +} + +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(envToken) + if err != nil { + return nil, fmt.Errorf("checkdomain: %v", err) + } + + config := NewDefaultConfig() + config.Token = values[envToken] + + endpoint, err := url.Parse(env.GetOrDefaultString(envEndpoint, defaultEndpoint)) + if err != nil { + return nil, fmt.Errorf("checkdomain: invalid %s: %v", envEndpoint, err) + } + config.Endpoint = endpoint + + return NewDNSProviderConfig(config) +} + +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config.Endpoint == nil { + return nil, fmt.Errorf("checkdomain: invalid endpoint") + } + + if config.Token == "" { + return nil, fmt.Errorf("checkdomain: missing token") + } + + if config.HTTPClient == nil { + config.HTTPClient = http.DefaultClient + } + + return &DNSProvider{ + config: config, + domainIDMapping: make(map[string]int), + }, nil +} + +// Present creates a TXT record to fulfill the dns-01 challenge +func (p *DNSProvider) Present(domain, token, keyAuth string) error { + domainID, err := p.getDomainIDByName(domain) + if err != nil { + return fmt.Errorf("checkdomain: %v", err) + } + + err = p.checkNameservers(domainID) + if err != nil { + return fmt.Errorf("checkdomain: %v", err) + } + + name, value := dns01.GetRecord(domain, keyAuth) + + err = p.createRecord(domainID, &Record{ + Name: name, + TTL: p.config.TTL, + Type: "TXT", + Value: value, + }) + + if err != nil { + return fmt.Errorf("checkdomain: %v", err) + } + + return nil +} + +// CleanUp removes the TXT record previously created +func (p *DNSProvider) CleanUp(domain, token, keyAuth string) error { + domainID, err := p.getDomainIDByName(domain) + if err != nil { + return fmt.Errorf("checkdomain: %v", err) + } + + err = p.checkNameservers(domainID) + if err != nil { + return fmt.Errorf("checkdomain: %v", err) + } + + name, value := dns01.GetRecord(domain, keyAuth) + + err = p.deleteTXTRecord(domainID, name, value) + if err != nil { + return fmt.Errorf("checkdomain: %v", err) + } + + p.domainIDMu.Lock() + delete(p.domainIDMapping, name) + p.domainIDMu.Unlock() + + return nil +} + +func (p *DNSProvider) Timeout() (timeout, interval time.Duration) { + return p.config.PropagationTimeout, p.config.PollingInterval +} diff --git a/providers/dns/checkdomain/checkdomain.toml b/providers/dns/checkdomain/checkdomain.toml new file mode 100644 index 00000000..ff251751 --- /dev/null +++ b/providers/dns/checkdomain/checkdomain.toml @@ -0,0 +1,25 @@ +Name = "Checkdomain" +Description = '''''' +URL = "https://checkdomain.de/" +Code = "checkdomain" +Since = "v3.3.0" + +Example = ''' +CHECKDOMAIN_TOKEN=yoursecrettoken \ +lego --dns checkdomain --domains my.domain.com --email my@email.com run +''' + +[Configuration] + [Configuration.Credentials] + CHECKDOMAIN_TOKEN = "API token" + [Configuration.Additional] + CHECKDOMAIN_ENDPOINT = "API endpoint URL, defaults to https://api.checkdomain.de" + CHECKDOMAIN_TTL = "The TTL of the TXT record used for the DNS challenge" + CHECKDOMAIN_POLLING_INTERVAL = "Time between DNS propagation check" + CHECKDOMAIN_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + CHECKDOMAIN_HTTP_TIMEOUT = "API request timeout, defaults to 30 seconds" + +[Links] + API = "https://developer.checkdomain.de/reference/" + Guide = "https://developer.checkdomain.de/guide/" + Settings = "https://www.checkdomain.net/en/login/data/api/" diff --git a/providers/dns/checkdomain/checkdomain_test.go b/providers/dns/checkdomain/checkdomain_test.go new file mode 100644 index 00000000..091fb5af --- /dev/null +++ b/providers/dns/checkdomain/checkdomain_test.go @@ -0,0 +1,124 @@ +package checkdomain + +import ( + "net/url" + "testing" + + "github.com/go-acme/lego/v3/platform/tester" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var envTest = tester.NewEnvTest(envEndpoint, envToken) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + envToken: "dummy", + }, + }, + { + desc: "no token", + envVars: map[string]string{}, + expected: "checkdomain: some credentials information are missing: CHECKDOMAIN_TOKEN", + }, + { + desc: "invalid endpoint", + envVars: map[string]string{ + envToken: "dummy", + envEndpoint: ":", + }, + expected: "checkdomain: invalid CHECKDOMAIN_ENDPOINT: parse :: missing protocol scheme", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + defer envTest.RestoreEnv() + envTest.ClearEnv() + + envTest.Apply(test.envVars) + + p, err := NewDNSProvider() + + if len(test.expected) == 0 { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + token string + expected string + }{ + { + desc: "success", + token: "dummy", + }, + { + desc: "missing token", + token: "", + expected: "checkdomain: missing token", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.Endpoint, _ = url.Parse(defaultEndpoint) + + if test.token != "" { + config.Token = test.token + } + + p, err := NewDNSProviderConfig(config) + + if len(test.expected) == 0 { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestLivePresent(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + assert.NoError(t, err) + + err = provider.Present(envTest.GetDomain(), "", "123d==") + assert.NoError(t, err) +} + +func TestLiveCleanUp(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + assert.NoError(t, err) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + assert.NoError(t, err) +} diff --git a/providers/dns/checkdomain/client.go b/providers/dns/checkdomain/client.go new file mode 100644 index 00000000..e1656721 --- /dev/null +++ b/providers/dns/checkdomain/client.go @@ -0,0 +1,416 @@ +package checkdomain + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" + "strconv" + "strings" +) + +const ( + ns1 = "ns.checkdomain.de" + ns2 = "ns2.checkdomain.de" +) + +const domainNotFound = -1 + +// max page limit that the checkdomain api allows +const maxLimit = 100 + +// max integer value +const maxInt = int((^uint(0)) >> 1) + +type ( + // Some fields have been omitted from the structs + // because they are not required for this application. + + DomainListingResponse struct { + Page int `json:"page"` + Limit int `json:"limit"` + Pages int `json:"pages"` + Total int `json:"total"` + Embedded EmbeddedDomainList `json:"_embedded"` + } + + EmbeddedDomainList struct { + Domains []*Domain `json:"domains"` + } + + Domain struct { + ID int `json:"id"` + Name string `json:"name"` + } + + DomainResponse struct { + ID int `json:"id"` + Name string `json:"name"` + Created string `json:"created"` + PaidUp string `json:"payed_up"` + Active bool `json:"active"` + } + + NameserverResponse struct { + General NameserverGeneral `json:"general"` + Nameservers []*Nameserver `json:"nameservers"` + SOA NameserverSOA `json:"soa"` + } + + NameserverGeneral struct { + IPv4 string `json:"ip_v4"` + IPv6 string `json:"ip_v6"` + IncludeWWW bool `json:"include_www"` + } + + NameserverSOA struct { + Mail string `json:"mail"` + Refresh int `json:"refresh"` + Retry int `json:"retry"` + Expiry int `json:"expiry"` + TTL int `json:"ttl"` + } + + Nameserver struct { + Name string `json:"name"` + } + + RecordListingResponse struct { + Page int `json:"page"` + Limit int `json:"limit"` + Pages int `json:"pages"` + Total int `json:"total"` + Embedded EmbeddedRecordList `json:"_embedded"` + } + + EmbeddedRecordList struct { + Records []*Record `json:"records"` + } + + Record struct { + Name string `json:"name"` + Value string `json:"value"` + TTL int `json:"ttl"` + Priority int `json:"priority"` + Type string `json:"type"` + } +) + +func (p *DNSProvider) getDomainIDByName(name string) (int, error) { + // Load from cache if exists + p.domainIDMu.Lock() + id, ok := p.domainIDMapping[name] + p.domainIDMu.Unlock() + if ok { + return id, nil + } + + // Find out by querying API + domains, err := p.listDomains() + if err != nil { + return domainNotFound, err + } + + // Linear search over all registered domains + for _, domain := range domains { + if domain.Name == name || strings.HasSuffix(name, "."+domain.Name) { + p.domainIDMu.Lock() + p.domainIDMapping[name] = domain.ID + p.domainIDMu.Unlock() + + return domain.ID, nil + } + } + + return domainNotFound, fmt.Errorf("domain not found") +} + +func (p *DNSProvider) listDomains() ([]*Domain, error) { + req, err := p.makeRequest(http.MethodGet, "/v1/domains", http.NoBody) + if err != nil { + return nil, fmt.Errorf("failed to make request: %v", err) + } + + // Checkdomain also provides a query param 'query' which allows filtering domains for a string. + // But that functionality is kinda broken, + // so we scan through the whole list of registered domains to later find the one that is of interest to us. + q := req.URL.Query() + q.Set("limit", strconv.Itoa(maxLimit)) + + currentPage := 1 + totalPages := maxInt + + var domainList []*Domain + for currentPage <= totalPages { + q.Set("page", strconv.Itoa(currentPage)) + req.URL.RawQuery = q.Encode() + + var res DomainListingResponse + if err := p.sendRequest(req, &res); err != nil { + return nil, fmt.Errorf("failed to send domain listing request: %v", err) + } + + // This is the first response, + // so we update totalPages and allocate the slice memory. + if totalPages == maxInt { + totalPages = res.Pages + domainList = make([]*Domain, 0, res.Total) + } + + domainList = append(domainList, res.Embedded.Domains...) + currentPage++ + } + + return domainList, nil +} + +func (p *DNSProvider) getNameserverInfo(domainID int) (*NameserverResponse, error) { + req, err := p.makeRequest(http.MethodGet, fmt.Sprintf("/v1/domains/%d/nameservers", domainID), http.NoBody) + if err != nil { + return nil, err + } + + res := &NameserverResponse{} + if err := p.sendRequest(req, res); err != nil { + return nil, err + } + + return res, nil +} + +func (p *DNSProvider) checkNameservers(domainID int) error { + info, err := p.getNameserverInfo(domainID) + if err != nil { + return err + } + + var found1, found2 bool + for _, item := range info.Nameservers { + switch item.Name { + case ns1: + found1 = true + case ns2: + found2 = true + } + } + + if !found1 || !found2 { + return fmt.Errorf("not using checkdomain nameservers, can not update records") + } + + return nil +} + +func (p *DNSProvider) createRecord(domainID int, record *Record) error { + bs, err := json.Marshal(record) + if err != nil { + return fmt.Errorf("encoding record failed: %v", err) + } + + req, err := p.makeRequest(http.MethodPost, fmt.Sprintf("/v1/domains/%d/nameservers/records", domainID), bytes.NewReader(bs)) + if err != nil { + return err + } + + return p.sendRequest(req, nil) +} + +// Checkdomain doesn't seem provide a way to delete records but one can replace all records at once. +// The current solution is to fetch all records and then use that list minus the record deleted as the new record list. +// TODO: Simplify this function once Checkdomain do provide the functionality. +func (p *DNSProvider) deleteTXTRecord(domainID int, recordName, recordValue string) error { + domainInfo, err := p.getDomainInfo(domainID) + if err != nil { + return err + } + + nsInfo, err := p.getNameserverInfo(domainID) + if err != nil { + return err + } + + allRecords, err := p.listRecords(domainID, "") + if err != nil { + return err + } + + recordName = strings.TrimSuffix(recordName, "."+domainInfo.Name+".") + + var recordsToKeep []*Record + + // Find and delete matching records + for _, record := range allRecords { + if skipRecord(recordName, recordValue, record, nsInfo) { + continue + } + + // Checkdomain API can return records without any TTL set (indicated by the value of 0). + // The API Call to replace the records would fail if we wouldn't specify a value. + // Thus, we use the default TTL queried beforehand + if record.TTL == 0 { + record.TTL = nsInfo.SOA.TTL + } + + recordsToKeep = append(recordsToKeep, record) + } + + return p.replaceRecords(domainID, recordsToKeep) +} + +func (p *DNSProvider) getDomainInfo(domainID int) (*DomainResponse, error) { + req, err := p.makeRequest(http.MethodGet, fmt.Sprintf("/v1/domains/%d", domainID), http.NoBody) + if err != nil { + return nil, err + } + + var res DomainResponse + err = p.sendRequest(req, &res) + if err != nil { + return nil, err + } + + return &res, nil +} + +func (p *DNSProvider) listRecords(domainID int, recordType string) ([]*Record, error) { + req, err := p.makeRequest(http.MethodGet, fmt.Sprintf("/v1/domains/%d/nameservers/records", domainID), http.NoBody) + if err != nil { + return nil, fmt.Errorf("failed to make request: %v", err) + } + + q := req.URL.Query() + q.Set("limit", strconv.Itoa(maxLimit)) + if recordType != "" { + q.Set("type", recordType) + } + + currentPage := 1 + totalPages := maxInt + + var recordList []*Record + for currentPage <= totalPages { + q.Set("page", strconv.Itoa(currentPage)) + req.URL.RawQuery = q.Encode() + + var res RecordListingResponse + if err := p.sendRequest(req, &res); err != nil { + return nil, fmt.Errorf("failed to send record listing request: %v", err) + } + + // This is the first response, so we update totalPages and allocate the slice memory. + if totalPages == maxInt { + totalPages = res.Pages + recordList = make([]*Record, 0, res.Total) + } + + recordList = append(recordList, res.Embedded.Records...) + currentPage++ + } + + return recordList, nil +} + +func (p *DNSProvider) replaceRecords(domainID int, records []*Record) error { + bs, err := json.Marshal(records) + if err != nil { + return fmt.Errorf("encoding record failed: %v", err) + } + + req, err := p.makeRequest(http.MethodPut, fmt.Sprintf("/v1/domains/%d/nameservers/records", domainID), bytes.NewReader(bs)) + if err != nil { + return err + } + + return p.sendRequest(req, nil) +} + +func skipRecord(recordName, recordValue string, record *Record, nsInfo *NameserverResponse) bool { + // Skip empty records + if record.Value == "" { + return true + } + + // Skip some special records, otherwise we would get a "Nameserver update failed" + if record.Type == "SOA" || record.Type == "NS" || record.Name == "@" || (nsInfo.General.IncludeWWW && record.Name == "www") { + return true + } + + nameMatch := recordName == "" || record.Name == recordName + valueMatch := recordValue == "" || record.Value == recordValue + + // Skip our matching record + if record.Type == "TXT" && nameMatch && valueMatch { + return true + } + + return false +} + +func (p *DNSProvider) makeRequest(method, resource string, body io.Reader) (*http.Request, error) { + uri, err := p.config.Endpoint.Parse(resource) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(method, uri.String(), body) + if err != nil { + return nil, err + } + + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+p.config.Token) + if method != http.MethodGet { + req.Header.Set("Content-Type", "application/json") + } + + return req, nil +} + +func (p *DNSProvider) sendRequest(req *http.Request, result interface{}) error { + resp, err := p.config.HTTPClient.Do(req) + if err != nil { + return err + } + + if err = checkResponse(resp); err != nil { + return err + } + + defer func() { _ = resp.Body.Close() }() + + if result == nil { + return nil + } + + raw, err := ioutil.ReadAll(resp.Body) + if err != nil { + return err + } + + err = json.Unmarshal(raw, result) + if err != nil { + return fmt.Errorf("unmarshaling %T error [status code=%d]: %v: %s", result, resp.StatusCode, err, string(raw)) + } + return nil +} + +func checkResponse(resp *http.Response) error { + if resp.StatusCode < http.StatusBadRequest { + return nil + } + + if resp.Body == nil { + return fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) + } + + defer func() { _ = resp.Body.Close() }() + + raw, err := ioutil.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) + } + + return fmt.Errorf("status code=%d: %s", resp.StatusCode, string(raw)) +} diff --git a/providers/dns/checkdomain/client_test.go b/providers/dns/checkdomain/client_test.go new file mode 100644 index 00000000..a28a35bb --- /dev/null +++ b/providers/dns/checkdomain/client_test.go @@ -0,0 +1,228 @@ +package checkdomain + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "testing" + + "github.com/go-acme/lego/v3/challenge/dns01" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux, func()) { + handler := http.NewServeMux() + svr := httptest.NewServer(handler) + + config := NewDefaultConfig() + config.Endpoint, _ = url.Parse(svr.URL) + config.Token = "secret" + + prd, err := NewDNSProviderConfig(config) + require.NoError(t, err) + + return prd, handler, svr.Close +} + +func Test_getDomainIDByName(t *testing.T) { + prd, handler, tearDown := setupTestProvider(t) + defer tearDown() + + handler.HandleFunc("/v1/domains", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet { + http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) + } + + domainList := DomainListingResponse{ + Embedded: EmbeddedDomainList{Domains: []*Domain{ + {ID: 1, Name: "test.com"}, + {ID: 2, Name: "test.org"}, + }}, + } + + err := json.NewEncoder(rw).Encode(domainList) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + id, err := prd.getDomainIDByName("test.com") + require.NoError(t, err) + + assert.Equal(t, 1, id) +} + +func Test_checkNameservers(t *testing.T) { + prd, handler, tearDown := setupTestProvider(t) + defer tearDown() + + handler.HandleFunc("/v1/domains/1/nameservers", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet { + http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) + } + + nsResp := NameserverResponse{ + Nameservers: []*Nameserver{ + {Name: ns1}, + {Name: ns2}, + // {Name: "ns.fake.de"}, + }, + } + + err := json.NewEncoder(rw).Encode(nsResp) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + err := prd.checkNameservers(1) + require.NoError(t, err) +} + +func Test_createRecord(t *testing.T) { + prd, handler, tearDown := setupTestProvider(t) + defer tearDown() + + handler.HandleFunc("/v1/domains/1/nameservers/records", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) + } + + content, err := ioutil.ReadAll(req.Body) + if err != nil { + http.Error(rw, err.Error(), http.StatusBadRequest) + return + } + + if string(content) != `{"name":"test.com","value":"value","ttl":300,"priority":0,"type":"TXT"}` { + http.Error(rw, "invalid request body: "+string(content), http.StatusBadRequest) + return + } + }) + + record := &Record{ + Name: "test.com", + TTL: 300, + Type: "TXT", + Value: "value", + } + + err := prd.createRecord(1, record) + require.NoError(t, err) +} + +func Test_deleteTXTRecord(t *testing.T) { + prd, handler, tearDown := setupTestProvider(t) + defer tearDown() + + domainName := "lego.test" + recordValue := "test" + + records := []*Record{ + { + Name: "_acme-challenge", + Value: recordValue, + Type: "TXT", + }, + { + Name: "_acme-challenge", + Value: recordValue, + Type: "A", + }, + { + Name: "foobar", + Value: recordValue, + Type: "TXT", + }, + } + + expectedRecords := []*Record{ + { + Name: "_acme-challenge", + Value: recordValue, + Type: "A", + }, + { + Name: "foobar", + Value: recordValue, + Type: "TXT", + }, + } + + handler.HandleFunc("/v1/domains/1", func(rw http.ResponseWriter, req *http.Request) { + resp := DomainResponse{ + ID: 1, + Name: domainName, + } + + err := json.NewEncoder(rw).Encode(resp) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + handler.HandleFunc("/v1/domains/1/nameservers", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet { + http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) + } + + nsResp := NameserverResponse{ + Nameservers: []*Nameserver{{Name: ns1}, {Name: ns2}}, + } + + err := json.NewEncoder(rw).Encode(nsResp) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + handler.HandleFunc("/v1/domains/1/nameservers/records", func(rw http.ResponseWriter, req *http.Request) { + switch req.Method { + case http.MethodGet: + resp := RecordListingResponse{ + Embedded: EmbeddedRecordList{ + Records: records, + }, + } + + err := json.NewEncoder(rw).Encode(resp) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + + case http.MethodPut: + var records []*Record + err := json.NewDecoder(req.Body).Decode(&records) + if err != nil { + http.Error(rw, err.Error(), http.StatusBadRequest) + return + } + + if len(records) == 0 { + http.Error(rw, "empty request body", http.StatusBadRequest) + return + } + + if !reflect.DeepEqual(expectedRecords, records) { + http.Error(rw, fmt.Sprintf("invalid records: %v", records), http.StatusBadRequest) + return + } + default: + http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) + } + }) + + fqdn, _ := dns01.GetRecord(domainName, "abc") + err := prd.deleteTXTRecord(1, fqdn, recordValue) + require.NoError(t, err) +} diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 6928e5ec..9f5c2d83 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -12,6 +12,7 @@ import ( "github.com/go-acme/lego/v3/providers/dns/azure" "github.com/go-acme/lego/v3/providers/dns/bindman" "github.com/go-acme/lego/v3/providers/dns/bluecat" + "github.com/go-acme/lego/v3/providers/dns/checkdomain" "github.com/go-acme/lego/v3/providers/dns/cloudflare" "github.com/go-acme/lego/v3/providers/dns/cloudns" "github.com/go-acme/lego/v3/providers/dns/cloudxns" @@ -85,6 +86,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return bindman.NewDNSProvider() case "bluecat": return bluecat.NewDNSProvider() + case "checkdomain": + return checkdomain.NewDNSProvider() case "cloudflare": return cloudflare.NewDNSProvider() case "cloudns":