diff --git a/README.md b/README.md index 4b06b101..a7afe532 100644 --- a/README.md +++ b/README.md @@ -48,21 +48,21 @@ 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/) | | [Checkdomain](https://go-acme.github.io/lego/dns/checkdomain/) | [CloudDNS](https://go-acme.github.io/lego/dns/clouddns/) | [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/) | [Constellix](https://go-acme.github.io/lego/dns/constellix/) | [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/) | -| [Dynu](https://go-acme.github.io/lego/dns/dynu/) | [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/) | [MythicBeasts](https://go-acme.github.io/lego/dns/mythicbeasts/) | [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/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) | -| [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | -| [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/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | -| [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Yandex](https://go-acme.github.io/lego/dns/yandex/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | -| [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | | | | +| [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Constellix](https://go-acme.github.io/lego/dns/constellix/) | [deSEC.io](https://go-acme.github.io/lego/dns/desec/) | +| [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/) | [Dynu](https://go-acme.github.io/lego/dns/dynu/) | [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/) | [MythicBeasts](https://go-acme.github.io/lego/dns/mythicbeasts/) | [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/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | +| [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | +| [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [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/) | +| [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Yandex](https://go-acme.github.io/lego/dns/yandex/) | +| [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | | | diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 2f853a4e..5066d912 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -28,6 +28,7 @@ func allDNSCodes() string { "cloudxns", "conoha", "constellix", + "desec", "designate", "digitalocean", "dnsimple", @@ -401,6 +402,26 @@ func displayDNSHelp(name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/constellix`) + case "desec": + // generated from: providers/dns/desec/desec.toml + ew.writeln(`Configuration for deSEC.io.`) + ew.writeln(`Code: 'desec'`) + ew.writeln(`Since: 'v0.3.7'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "DESEC_TOKEN": Domain token`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "DESEC_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "DESEC_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "DESEC_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "DESEC_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/desec`) + case "designate": // generated from: providers/dns/designate/designate.toml ew.writeln(`Configuration for Designate DNSaaS for Openstack.`) diff --git a/docs/content/dns/zz_gen_desec.md b/docs/content/dns/zz_gen_desec.md new file mode 100644 index 00000000..9315ee9d --- /dev/null +++ b/docs/content/dns/zz_gen_desec.md @@ -0,0 +1,62 @@ +--- +title: "deSEC.io" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: desec +--- + + + + + +Since: v0.3.7 + +Configuration for [deSEC.io](https://desec.io). + + + + +- Code: `desec` + +Here is an example bash command using the deSEC.io provider: + +```bash +DESEC_TOKEN=x-xxxxxxxxxxxxxxxxxxxxxxxxxx \ +lego --dns desec --domains my.domain.com --email my@email.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `DESEC_TOKEN` | Domain 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 | +|--------------------------------|-------------| +| `DESEC_HTTP_TIMEOUT` | API request timeout | +| `DESEC_POLLING_INTERVAL` | Time between DNS propagation check | +| `DESEC_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `DESEC_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://desec.readthedocs.io/en/latest/) + + + + diff --git a/providers/dns/desec/desec.go b/providers/dns/desec/desec.go new file mode 100644 index 00000000..0cf4fd41 --- /dev/null +++ b/providers/dns/desec/desec.go @@ -0,0 +1,177 @@ +// Package desec implements a DNS provider for solving the DNS-01 challenge using deSEC DNS. +package desec + +import ( + "errors" + "fmt" + "net/http" + "time" + + "github.com/go-acme/lego/v3/challenge/dns01" + "github.com/go-acme/lego/v3/platform/config/env" + "github.com/go-acme/lego/v3/providers/dns/desec/internal" +) + +// Environment variables names. +const ( + envNamespace = "DESEC_" + + EnvToken = envNamespace + "TOKEN" + + EnvTTL = envNamespace + "TTL" + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" +) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + Token string + PropagationTimeout time.Duration + PollingInterval time.Duration + TTL int + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, 300), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider is an implementation of the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *internal.Client +} + +// NewDNSProvider returns a DNSProvider instance configured for deSEC. +// Credentials must be passed in the environment variable: DESEC_TOKEN. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvToken) + if err != nil { + return nil, fmt.Errorf("desec: %w", err) + } + + config := NewDefaultConfig() + config.Token = values[EnvToken] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for deSEC. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("desec: the configuration of the DNS provider is nil") + } + + if config.Token == "" { + return nil, errors.New("desec: incomplete credentials, missing token") + } + + client := internal.NewClient(config.Token) + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + return &DNSProvider{config: config, client: client}, nil +} + +// Timeout returns the timeout and interval to use when checking for DNS propagation. +// Adjusting here to cope with spikes in propagation times. +func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { + return d.config.PropagationTimeout, d.config.PollingInterval +} + +// Present creates a TXT record using the specified parameters. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + fqdn, value := dns01.GetRecord(domain, keyAuth) + quotedValue := fmt.Sprintf(`"%s"`, value) + + authZone, err := dns01.FindZoneByFqdn(fqdn) + if err != nil { + return fmt.Errorf("desec: could not find zone for domain %q and fqdn %q : %w", domain, fqdn, err) + } + + recordName := getRecordName(fqdn, authZone) + + rrSet, err := d.client.GetTxtRRSet(dns01.UnFqdn(authZone), recordName) + + var nf *internal.NotFound + if err != nil && !errors.As(err, &nf) { + return fmt.Errorf("desec: failed to get records: %w", err) + } + + if err != nil { + var nf *internal.NotFound + if !errors.As(err, &nf) { + return fmt.Errorf("desec: failed to get records: %w", err) + } + + // Not found case -> create + _, err = d.client.AddTxtRRSet(internal.RRSet{ + Domain: dns01.UnFqdn(authZone), + SubName: recordName, + Type: "TXT", + Records: []string{quotedValue}, + TTL: d.config.TTL, + }) + if err != nil { + return fmt.Errorf("desec: failed to create records: %w", err) + } + + return nil + } + + // update + records := append(rrSet.Records, quotedValue) + + _, err = d.client.UpdateTxtRRSet(dns01.UnFqdn(authZone), recordName, records) + if err != nil { + return fmt.Errorf("desec: failed to update records: %w", err) + } + + return nil +} + +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + fqdn, value := dns01.GetRecord(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(fqdn) + if err != nil { + return fmt.Errorf("desec: could not find zone for domain %q and fqdn %q : %w", domain, fqdn, err) + } + + recordName := getRecordName(fqdn, authZone) + + rrSet, err := d.client.GetTxtRRSet(dns01.UnFqdn(authZone), recordName) + if err != nil { + return fmt.Errorf("desec: failed to create records: %w", err) + } + + records := make([]string, 0) + for _, record := range rrSet.Records { + if record != fmt.Sprintf(`"%s"`, value) { + records = append(records, record) + } + } + + _, err = d.client.UpdateTxtRRSet(dns01.UnFqdn(authZone), recordName, records) + if err != nil { + return fmt.Errorf("desec: failed to update records: %w", err) + } + + return nil +} + +func getRecordName(fqdn, authZone string) string { + return fqdn[0 : len(fqdn)-len(authZone)-1] +} diff --git a/providers/dns/desec/desec.toml b/providers/dns/desec/desec.toml new file mode 100644 index 00000000..5592daec --- /dev/null +++ b/providers/dns/desec/desec.toml @@ -0,0 +1,22 @@ +Name = "deSEC.io" +Description = '''''' +URL = "https://desec.io" +Code = "desec" +Since = "v0.3.7" + +Example = ''' +DESEC_TOKEN=x-xxxxxxxxxxxxxxxxxxxxxxxxxx \ +lego --dns desec --domains my.domain.com --email my@email.com run +''' + +[Configuration] + [Configuration.Credentials] + DESEC_TOKEN = "Domain token" + [Configuration.Additional] + DESEC_POLLING_INTERVAL = "Time between DNS propagation check" + DESEC_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + DESEC_TTL = "The TTL of the TXT record used for the DNS challenge" + DESEC_HTTP_TIMEOUT = "API request timeout" + +[Links] + API = "https://desec.readthedocs.io/en/latest/" diff --git a/providers/dns/desec/desec_test.go b/providers/dns/desec/desec_test.go new file mode 100644 index 00000000..6026c7a1 --- /dev/null +++ b/providers/dns/desec/desec_test.go @@ -0,0 +1,116 @@ +package desec + +import ( + "testing" + "time" + + "github.com/go-acme/lego/v3/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvToken).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvToken: "123", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{ + EnvToken: "", + }, + expected: "desec: some credentials information are missing: DESEC_TOKEN", + }, + } + + 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 + expected string + token string + }{ + { + desc: "success", + token: "api_key", + }, + { + desc: "missing credentials", + expected: "desec: incomplete credentials, missing token", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + 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() + require.NoError(t, err) + + err = provider.Present(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} + +func TestLiveCleanUp(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + time.Sleep(1 * time.Second) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} diff --git a/providers/dns/desec/internal/client.go b/providers/dns/desec/internal/client.go new file mode 100644 index 00000000..fa4662b2 --- /dev/null +++ b/providers/dns/desec/internal/client.go @@ -0,0 +1,233 @@ +package internal + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "path" +) + +const baseURL = "https://desec.io/api/v1/" + +// Client deSec API client. +type Client struct { + HTTPClient *http.Client + BaseURL string + + token string +} + +// NewClient creats a new Client. +func NewClient(token string) *Client { + return &Client{ + HTTPClient: http.DefaultClient, + BaseURL: baseURL, + token: token, + } +} + +// GetTxtRRSet gets a RRSet. +// https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-a-specific-rrset +func (c *Client) GetTxtRRSet(domainName string, subName string) (*RRSet, error) { + if subName == "" { + subName = "@" + } + + endpoint, err := c.createEndpoint("domains", domainName, "rrsets", subName, "TXT") + if err != nil { + return nil, fmt.Errorf("failed to create endpoint: %w", err) + } + + req, err := http.NewRequest(http.MethodGet, endpoint, nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to call API: %w", err) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + if resp.StatusCode == http.StatusNotFound { + var notFound NotFound + err = json.Unmarshal(body, ¬Found) + if err != nil { + return nil, fmt.Errorf("error: %d: %s", resp.StatusCode, string(body)) + } + + return nil, ¬Found + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("error: %d: %s", resp.StatusCode, string(body)) + } + + var rrSet RRSet + err = json.Unmarshal(body, &rrSet) + if err != nil { + return nil, fmt.Errorf("failed to umarshal response body: %w", err) + } + + return &rrSet, nil +} + +// AddTxtRRSet creates a new RRSet. +// https://desec.readthedocs.io/en/latest/dns/rrsets.html#creating-a-tlsa-rrset +func (c *Client) AddTxtRRSet(rrSet RRSet) (*RRSet, error) { + endpoint, err := c.createEndpoint("domains", rrSet.Domain, "rrsets") + if err != nil { + return nil, fmt.Errorf("failed to create endpoint: %w", err) + } + + raw, err := json.Marshal(rrSet) + if err != nil { + return nil, fmt.Errorf("failed to marshal request body: %w", err) + } + + req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(raw)) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to call API: %w", err) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + if resp.StatusCode != http.StatusCreated { + return nil, fmt.Errorf("error: %d: %s", resp.StatusCode, string(body)) + } + + var newRRSet RRSet + err = json.Unmarshal(body, &newRRSet) + if err != nil { + return nil, fmt.Errorf("failed to umarshal response body: %w", err) + } + + return &newRRSet, nil +} + +// UpdateTxtRRSet updates RRSet records. +// https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset +func (c *Client) UpdateTxtRRSet(domainName string, subName string, records []string) (*RRSet, error) { + if subName == "" { + subName = "@" + } + + endpoint, err := c.createEndpoint("domains", domainName, "rrsets", subName, "TXT") + if err != nil { + return nil, fmt.Errorf("failed to create endpoint: %w", err) + } + + raw, err := json.Marshal(RRSet{Records: records}) + if err != nil { + return nil, fmt.Errorf("failed to marshal request body: %w", err) + } + + req, err := http.NewRequest(http.MethodPatch, endpoint, bytes.NewReader(raw)) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to call API: %w", err) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + // when a RRSet is deleted (empty records) + if resp.StatusCode == http.StatusNoContent { + return nil, nil + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("error: %d: %s", resp.StatusCode, string(body)) + } + + var updatedRRSet RRSet + err = json.Unmarshal(body, &updatedRRSet) + if err != nil { + return nil, fmt.Errorf("failed to umarshal response body: %w", err) + } + + return &updatedRRSet, nil +} + +// DeleteTxtRRSet deletes a RRset. +// https://desec.readthedocs.io/en/latest/dns/rrsets.html#deleting-an-rrset +func (c *Client) DeleteTxtRRSet(domainName string, subName string) error { + if subName == "" { + subName = "@" + } + + endpoint, err := c.createEndpoint("domains", domainName, "rrsets", subName, "TXT") + if err != nil { + return fmt.Errorf("failed to create endpoint: %w", err) + } + + req, err := http.NewRequest(http.MethodDelete, endpoint, nil) + if err != nil { + return fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return fmt.Errorf("failed to call API: %w", err) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read response body: %w", err) + } + + if resp.StatusCode != http.StatusNoContent { + return fmt.Errorf("error: %d: %s", resp.StatusCode, string(body)) + } + + return nil +} + +func (c *Client) createEndpoint(parts ...string) (string, error) { + base, err := url.Parse(c.BaseURL) + if err != nil { + return "", err + } + + endpoint, err := base.Parse(path.Join(base.Path, path.Join(parts...))) + if err != nil { + return "", err + } + + endpoint.Path += "/" + + return endpoint.String(), nil +} diff --git a/providers/dns/desec/internal/client_test.go b/providers/dns/desec/internal/client_test.go new file mode 100644 index 00000000..ff2f8a7c --- /dev/null +++ b/providers/dns/desec/internal/client_test.go @@ -0,0 +1,169 @@ +package internal + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetTxtRRSet(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("token") + client.BaseURL = server.URL + + mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet { + http.Error(rw, "invalid method", http.StatusMethodNotAllowed) + return + } + + file, err := os.Open("./fixtures/get_record.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + record, err := client.GetTxtRRSet("example.dedyn.io", "_acme-challenge") + require.NoError(t, err) + + expected := &RRSet{ + Name: "_acme-challenge.example.dedyn.io.", + Domain: "example.dedyn.io", + SubName: "_acme-challenge", + Type: "TXT", + Records: []string{`"txt"`}, + TTL: 300, + } + assert.Equal(t, expected, record) +} + +func TestAddTxtRRSet(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("token") + client.BaseURL = server.URL + + mux.HandleFunc("/domains/example.dedyn.io/rrsets/", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, "invalid method", http.StatusMethodNotAllowed) + return + } + + rw.WriteHeader(http.StatusCreated) + file, err := os.Open("./fixtures/add_record.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + record := RRSet{ + Name: "", + Domain: "example.dedyn.io", + SubName: "_acme-challenge", + Type: "TXT", + Records: []string{`"txt"`}, + TTL: 300, + } + + newRecord, err := client.AddTxtRRSet(record) + require.NoError(t, err) + + expected := &RRSet{ + Name: "_acme-challenge.example.dedyn.io.", + Domain: "example.dedyn.io", + SubName: "_acme-challenge", + Type: "TXT", + Records: []string{`"txt"`}, + TTL: 300, + } + assert.Equal(t, expected, newRecord) +} + +func TestUpdateTxtRRSet(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("token") + client.BaseURL = server.URL + + mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPatch { + http.Error(rw, "invalid method", http.StatusMethodNotAllowed) + return + } + + file, err := os.Open("./fixtures/update_record.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + updatedRecord, err := client.UpdateTxtRRSet("example.dedyn.io", "_acme-challenge", []string{`"updated"`}) + require.NoError(t, err) + + expected := &RRSet{ + Name: "_acme-challenge.example.dedyn.io.", + Domain: "example.dedyn.io", + SubName: "_acme-challenge", + Type: "TXT", + Records: []string{`"updated"`}, + TTL: 300, + } + assert.Equal(t, expected, updatedRecord) +} + +func TestDeleteTxtRRSet(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("token") + client.BaseURL = server.URL + + mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodDelete { + http.Error(rw, "invalid method", http.StatusMethodNotAllowed) + return + } + + rw.WriteHeader(http.StatusNoContent) + }) + + err := client.DeleteTxtRRSet("example.dedyn.io", "_acme-challenge") + require.NoError(t, err) +} diff --git a/providers/dns/desec/internal/fixtures/add_record.json b/providers/dns/desec/internal/fixtures/add_record.json new file mode 100644 index 00000000..96ce5590 --- /dev/null +++ b/providers/dns/desec/internal/fixtures/add_record.json @@ -0,0 +1,11 @@ +{ + "created": "2020-05-06T11:46:07.641885Z", + "domain": "example.dedyn.io", + "subname": "_acme-challenge", + "name": "_acme-challenge.example.dedyn.io.", + "records": [ + "\"txt\"" + ], + "ttl": 300, + "type": "TXT" +} diff --git a/providers/dns/desec/internal/fixtures/get_record.json b/providers/dns/desec/internal/fixtures/get_record.json new file mode 100644 index 00000000..96ce5590 --- /dev/null +++ b/providers/dns/desec/internal/fixtures/get_record.json @@ -0,0 +1,11 @@ +{ + "created": "2020-05-06T11:46:07.641885Z", + "domain": "example.dedyn.io", + "subname": "_acme-challenge", + "name": "_acme-challenge.example.dedyn.io.", + "records": [ + "\"txt\"" + ], + "ttl": 300, + "type": "TXT" +} diff --git a/providers/dns/desec/internal/fixtures/update_record.json b/providers/dns/desec/internal/fixtures/update_record.json new file mode 100644 index 00000000..a2e6b3ee --- /dev/null +++ b/providers/dns/desec/internal/fixtures/update_record.json @@ -0,0 +1,11 @@ +{ + "created": "2020-05-06T11:46:07.641885Z", + "domain": "example.dedyn.io", + "subname": "_acme-challenge", + "name": "_acme-challenge.example.dedyn.io.", + "records": [ + "\"updated\"" + ], + "ttl": 300, + "type": "TXT" +} diff --git a/providers/dns/desec/internal/model.go b/providers/dns/desec/internal/model.go new file mode 100644 index 00000000..6e598f4d --- /dev/null +++ b/providers/dns/desec/internal/model.go @@ -0,0 +1,20 @@ +package internal + +// RRSet DNS Record Set. +type RRSet struct { + Name string `json:"name,omitempty"` + Domain string `json:"domain,omitempty"` + SubName string `json:"subname,omitempty"` + Type string `json:"type,omitempty"` + Records []string `json:"records"` + TTL int `json:"ttl,omitempty"` +} + +// NotFound Not found error. +type NotFound struct { + Detail string `json:"detail"` +} + +func (n NotFound) Error() string { + return n.Detail +} diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 468955b0..d32c5cba 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -19,6 +19,7 @@ import ( "github.com/go-acme/lego/v3/providers/dns/cloudxns" "github.com/go-acme/lego/v3/providers/dns/conoha" "github.com/go-acme/lego/v3/providers/dns/constellix" + "github.com/go-acme/lego/v3/providers/dns/desec" "github.com/go-acme/lego/v3/providers/dns/designate" "github.com/go-acme/lego/v3/providers/dns/digitalocean" "github.com/go-acme/lego/v3/providers/dns/dnsimple" @@ -110,6 +111,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return conoha.NewDNSProvider() case "constellix": return constellix.NewDNSProvider() + case "desec": + return desec.NewDNSProvider() case "designate": return designate.NewDNSProvider() case "digitalocean":