From beaa35caf94199294be5c48248943afcd027d0fd Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Fri, 30 Aug 2024 19:46:02 +0200 Subject: [PATCH] Add DNS provider for Mittwald (#2200) --- README.md | 28 +- cmd/zz_gen_cmd_dnshelp.go | 22 ++ docs/content/dns/zz_gen_mittwald.md | 68 +++++ docs/data/zz_cli_help.toml | 2 +- providers/dns/dns_providers.go | 3 + providers/dns/mittwald/internal/client.go | 206 +++++++++++++++ .../dns/mittwald/internal/client_test.go | 173 +++++++++++++ .../fixtures/dns-create-dns-zone.json | 3 + .../internal/fixtures/dns-get-dns-zone.json | 11 + .../internal/fixtures/dns-list-dns-zones.json | 13 + .../fixtures/domain-list-domains.json | 74 ++++++ .../internal/fixtures/error-client.json | 14 + .../dns/mittwald/internal/fixtures/error.json | 4 + providers/dns/mittwald/internal/types.go | 82 ++++++ providers/dns/mittwald/mittwald.go | 241 +++++++++++++++++ providers/dns/mittwald/mittwald.toml | 23 ++ providers/dns/mittwald/mittwald_test.go | 243 ++++++++++++++++++ 17 files changed, 1195 insertions(+), 15 deletions(-) create mode 100644 docs/content/dns/zz_gen_mittwald.md create mode 100644 providers/dns/mittwald/internal/client.go create mode 100644 providers/dns/mittwald/internal/client_test.go create mode 100644 providers/dns/mittwald/internal/fixtures/dns-create-dns-zone.json create mode 100644 providers/dns/mittwald/internal/fixtures/dns-get-dns-zone.json create mode 100644 providers/dns/mittwald/internal/fixtures/dns-list-dns-zones.json create mode 100644 providers/dns/mittwald/internal/fixtures/domain-list-domains.json create mode 100644 providers/dns/mittwald/internal/fixtures/error-client.json create mode 100644 providers/dns/mittwald/internal/fixtures/error.json create mode 100644 providers/dns/mittwald/internal/types.go create mode 100644 providers/dns/mittwald/mittwald.go create mode 100644 providers/dns/mittwald/mittwald.toml create mode 100644 providers/dns/mittwald/mittwald_test.go diff --git a/README.md b/README.md index 0cb04276..011fc5cd 100644 --- a/README.md +++ b/README.md @@ -73,20 +73,20 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [iwantmyname](https://go-acme.github.io/lego/dns/iwantmyname/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Liara](https://go-acme.github.io/lego/dns/liara/) | | [Lima-City](https://go-acme.github.io/lego/dns/limacity/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linode/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [Loopia](https://go-acme.github.io/lego/dns/loopia/) | | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) | [Mail-in-a-Box](https://go-acme.github.io/lego/dns/mailinabox/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | [Metaname](https://go-acme.github.io/lego/dns/metaname/) | -| [mijn.host](https://go-acme.github.io/lego/dns/mijnhost/) | [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/) | [NearlyFreeSpeech.NET](https://go-acme.github.io/lego/dns/nearlyfreespeech/) | [Netcup](https://go-acme.github.io/lego/dns/netcup/) | -| [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [Nicmanager](https://go-acme.github.io/lego/dns/nicmanager/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | [Njalla](https://go-acme.github.io/lego/dns/njalla/) | -| [Nodion](https://go-acme.github.io/lego/dns/nodion/) | [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/) | [plesk.com](https://go-acme.github.io/lego/dns/plesk/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) | [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | -| [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [RcodeZero](https://go-acme.github.io/lego/dns/rcodezero/) | [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 v2](https://go-acme.github.io/lego/dns/selectelv2/) | -| [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [Shellrent](https://go-acme.github.io/lego/dns/shellrent/) | [Simply.com](https://go-acme.github.io/lego/dns/simply/) | -| [Sonic](https://go-acme.github.io/lego/dns/sonic/) | [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | -| [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [Ultradns](https://go-acme.github.io/lego/dns/ultradns/) | [Variomedia](https://go-acme.github.io/lego/dns/variomedia/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | -| [Vercel](https://go-acme.github.io/lego/dns/vercel/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | [VK Cloud](https://go-acme.github.io/lego/dns/vkcloud/) | -| [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Webnames](https://go-acme.github.io/lego/dns/webnames/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | -| [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex 360](https://go-acme.github.io/lego/dns/yandex360/) | [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) | [Yandex PDD](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/) | | | +| [mijn.host](https://go-acme.github.io/lego/dns/mijnhost/) | [Mittwald](https://go-acme.github.io/lego/dns/mittwald/) | [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/) | [NearlyFreeSpeech.NET](https://go-acme.github.io/lego/dns/nearlyfreespeech/) | +| [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [Nicmanager](https://go-acme.github.io/lego/dns/nicmanager/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | +| [Njalla](https://go-acme.github.io/lego/dns/njalla/) | [Nodion](https://go-acme.github.io/lego/dns/nodion/) | [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/) | [plesk.com](https://go-acme.github.io/lego/dns/plesk/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) | +| [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [RcodeZero](https://go-acme.github.io/lego/dns/rcodezero/) | [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 v2](https://go-acme.github.io/lego/dns/selectelv2/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [Shellrent](https://go-acme.github.io/lego/dns/shellrent/) | +| [Simply.com](https://go-acme.github.io/lego/dns/simply/) | [Sonic](https://go-acme.github.io/lego/dns/sonic/) | [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | +| [TransIP](https://go-acme.github.io/lego/dns/transip/) | [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [Ultradns](https://go-acme.github.io/lego/dns/ultradns/) | [Variomedia](https://go-acme.github.io/lego/dns/variomedia/) | +| [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Vercel](https://go-acme.github.io/lego/dns/vercel/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | +| [VK Cloud](https://go-acme.github.io/lego/dns/vkcloud/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Webnames](https://go-acme.github.io/lego/dns/webnames/) | +| [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex 360](https://go-acme.github.io/lego/dns/yandex360/) | [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) | +| [Yandex PDD](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 c39cabcd..d77bc03c 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -93,6 +93,7 @@ func allDNSCodes() string { "mailinabox", "metaname", "mijnhost", + "mittwald", "mydnsjp", "mythicbeasts", "namecheap", @@ -1835,6 +1836,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/mijnhost`) + case "mittwald": + // generated from: providers/dns/mittwald/mittwald.toml + ew.writeln(`Configuration for Mittwald.`) + ew.writeln(`Code: 'mittwald'`) + ew.writeln(`Since: 'v1.48.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "MITTWALD_TOKEN": API token`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "MITTWALD_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "MITTWALD_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "MITTWALD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "MITTWALD_SEQUENCE_INTERVAL": Time between sequential requests`) + ew.writeln(` - "MITTWALD_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/mittwald`) + case "mydnsjp": // generated from: providers/dns/mydnsjp/mydnsjp.toml ew.writeln(`Configuration for MyDNS.jp.`) diff --git a/docs/content/dns/zz_gen_mittwald.md b/docs/content/dns/zz_gen_mittwald.md new file mode 100644 index 00000000..39daa494 --- /dev/null +++ b/docs/content/dns/zz_gen_mittwald.md @@ -0,0 +1,68 @@ +--- +title: "Mittwald" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: mittwald +dnsprovider: + since: "v1.48.0" + code: "mittwald" + url: "https://www.mittwald.de/" +--- + + + + + + +Configuration for [Mittwald](https://www.mittwald.de/). + + + + +- Code: `mittwald` +- Since: v1.48.0 + + +Here is an example bash command using the Mittwald provider: + +```bash +MITTWALD_TOKEN=my-token \ +lego --email you@example.com --dns mittwald --domains my.example.org run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `MITTWALD_TOKEN` | API token | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here]({{% ref "dns#configuration-and-credentials" %}}). + + +## Additional Configuration + +| Environment Variable Name | Description | +|--------------------------------|-------------| +| `MITTWALD_HTTP_TIMEOUT` | API request timeout | +| `MITTWALD_POLLING_INTERVAL` | Time between DNS propagation check | +| `MITTWALD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `MITTWALD_SEQUENCE_INTERVAL` | Time between sequential requests | +| `MITTWALD_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]({{% ref "dns#configuration-and-credentials" %}}). + + + + +## More information + +- [API documentation](https://api.mittwald.de/v2/docs/) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index 6fc40485..7b88974d 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -138,7 +138,7 @@ To display the documentation for a specific DNS provider, run: $ lego dnshelp -c code Supported DNS providers: - acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mijnhost, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi + acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mijnhost, mittwald, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 0bcfdee6..5926f90c 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -84,6 +84,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/mailinabox" "github.com/go-acme/lego/v4/providers/dns/metaname" "github.com/go-acme/lego/v4/providers/dns/mijnhost" + "github.com/go-acme/lego/v4/providers/dns/mittwald" "github.com/go-acme/lego/v4/providers/dns/mydnsjp" "github.com/go-acme/lego/v4/providers/dns/mythicbeasts" "github.com/go-acme/lego/v4/providers/dns/namecheap" @@ -303,6 +304,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return metaname.NewDNSProvider() case "mijnhost": return mijnhost.NewDNSProvider() + case "mittwald": + return mittwald.NewDNSProvider() case "mydnsjp": return mydnsjp.NewDNSProvider() case "mythicbeasts": diff --git a/providers/dns/mittwald/internal/client.go b/providers/dns/mittwald/internal/client.go new file mode 100644 index 00000000..712caf8d --- /dev/null +++ b/providers/dns/mittwald/internal/client.go @@ -0,0 +1,206 @@ +package internal + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" +) + +const defaultBaseURL = "https://api.mittwald.de/v2/" + +const authorizationHeader = "Authorization" + +// Client the Mittwald client. +type Client struct { + token string + + baseURL *url.URL + HTTPClient *http.Client +} + +// NewClient Creates a new Client. +func NewClient(token string) *Client { + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + token: token, + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 5 * time.Second}, + } +} + +// ListDomains List Domains. +// https://api.mittwald.de/v2/docs/#/Domain/domain-list-domains +func (c Client) ListDomains(ctx context.Context) ([]Domain, error) { + endpoint := c.baseURL.JoinPath("domains") + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var result []Domain + err = c.do(req, &result) + if err != nil { + return nil, err + } + + return result, nil +} + +// GetDNSZone Get a DNSZone. +// https://api.mittwald.de/v2/docs/#/Domain/dns-get-dns-zone +func (c Client) GetDNSZone(ctx context.Context, zoneID string) (*DNSZone, error) { + endpoint := c.baseURL.JoinPath("dns-zones", zoneID) + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + result := &DNSZone{} + err = c.do(req, result) + if err != nil { + return nil, err + } + + return result, nil +} + +// ListDNSZones List DNSZones belonging to a Project. +// https://api.mittwald.de/v2/docs/#/Domain/dns-list-dns-zones +func (c Client) ListDNSZones(ctx context.Context, projectID string) ([]DNSZone, error) { + endpoint := c.baseURL.JoinPath("projects", projectID, "dns-zones") + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var result []DNSZone + err = c.do(req, &result) + if err != nil { + return nil, err + } + + return result, nil +} + +// CreateDNSZone Create a DNSZone. +// https://api.mittwald.de/v2/docs/#/Domain/dns-create-dns-zone +func (c Client) CreateDNSZone(ctx context.Context, zone CreateDNSZoneRequest) (*DNSZone, error) { + endpoint := c.baseURL.JoinPath("dns-zones") + + req, err := newJSONRequest(ctx, http.MethodPost, endpoint, zone) + if err != nil { + return nil, err + } + + result := &DNSZone{} + err = c.do(req, result) + if err != nil { + return nil, err + } + + return result, nil +} + +// UpdateTXTRecord Update a record set on a DNSZone. +// https://api.mittwald.de/v2/docs/#/Domain/dns-update-record-set +func (c Client) UpdateTXTRecord(ctx context.Context, zoneID string, record TXTRecord) error { + endpoint := c.baseURL.JoinPath("dns-zones", zoneID, "record-sets", "txt") + + req, err := newJSONRequest(ctx, http.MethodPut, endpoint, record) + if err != nil { + return err + } + + return c.do(req, nil) +} + +// DeleteDNSZone Delete a DNSZone. +// https://api.mittwald.de/v2/docs/#/Domain/dns-delete-dns-zone +func (c Client) DeleteDNSZone(ctx context.Context, zoneID string) error { + endpoint := c.baseURL.JoinPath("dns-zones", zoneID) + + req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil) + if err != nil { + return err + } + + return c.do(req, nil) +} + +func (c Client) do(req *http.Request, result any) error { + req.Header.Set(authorizationHeader, "Bearer "+c.token) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode/100 != 2 { + return parseError(req, resp) + } + + if result == nil { + return nil + } + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return errutils.NewReadResponseError(req, resp.StatusCode, err) + } + + err = json.Unmarshal(raw, result) + if err != nil { + return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err) + } + + return nil +} + +func newJSONRequest(ctx context.Context, method string, endpoint *url.URL, payload any) (*http.Request, error) { + buf := new(bytes.Buffer) + + if payload != nil { + err := json.NewEncoder(buf).Encode(payload) + if err != nil { + return nil, fmt.Errorf("failed to create request JSON body: %w", err) + } + } + + req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + + return req, nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + var response APIError + err := json.Unmarshal(raw, &response) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return fmt.Errorf("[status code %d] %w", resp.StatusCode, response) +} diff --git a/providers/dns/mittwald/internal/client_test.go b/providers/dns/mittwald/internal/client_test.go new file mode 100644 index 00000000..63fc5200 --- /dev/null +++ b/providers/dns/mittwald/internal/client_test.go @@ -0,0 +1,173 @@ +package internal + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T, pattern string, handler http.HandlerFunc) *Client { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + mux.HandleFunc(pattern, handler) + + client := NewClient("secret") + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client +} + +func testHandler(method string, statusCode int, filename string) http.HandlerFunc { + return func(rw http.ResponseWriter, req *http.Request) { + if req.Method != method { + http.Error(rw, fmt.Sprintf(`{"message":"unsupported method: %s"}`, req.Method), http.StatusMethodNotAllowed) + return + } + + auth := req.Header.Get(authorizationHeader) + if auth != "Bearer secret" { + http.Error(rw, fmt.Sprintf("invalid API Token: %s", auth), http.StatusUnauthorized) + return + } + + rw.WriteHeader(statusCode) + + if statusCode == http.StatusNoContent { + return + } + + file, err := os.Open(filepath.Join("fixtures", filename)) + if err != nil { + http.Error(rw, fmt.Sprintf(`{"message":"%v"}`, err), http.StatusInternalServerError) + return + } + + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, fmt.Sprintf(`{"message":"%v"}`, err), http.StatusInternalServerError) + return + } + } +} + +func TestClient_ListDomains(t *testing.T) { + client := setupTest(t, "/domains", testHandler(http.MethodGet, http.StatusOK, "domain-list-domains.json")) + + domains, err := client.ListDomains(context.Background()) + require.NoError(t, err) + + require.Len(t, domains, 1) + + expected := []Domain{{ + Domain: "string", + DomainID: "3fa85f64-5717-4562-b3fc-2c963f66afa6", + ProjectID: "3fa85f64-5717-4562-b3fc-2c963f66afa6", + }} + + assert.Equal(t, expected, domains) +} + +func TestClient_ListDomains_error(t *testing.T) { + client := setupTest(t, "/domains", testHandler(http.MethodGet, http.StatusBadRequest, "error-client.json")) + + _, err := client.ListDomains(context.Background()) + require.EqualError(t, err, "[status code 400] ValidationError: Validation failed [format: should be string (.address.street, email)]") +} + +func TestClient_ListDNSZones(t *testing.T) { + client := setupTest(t, "/projects/my-project-id/dns-zones", testHandler(http.MethodGet, http.StatusOK, "dns-list-dns-zones.json")) + + zones, err := client.ListDNSZones(context.Background(), "my-project-id") + require.NoError(t, err) + + require.Len(t, zones, 1) + + expected := []DNSZone{{ + ID: "3fa85f64-5717-4562-b3fc-2c963f66afa6", + Domain: "string", + RecordSet: &RecordSet{ + TXT: &TXTRecord{}, + }, + }} + + assert.Equal(t, expected, zones) +} + +func TestClient_GetDNSZone(t *testing.T) { + client := setupTest(t, "/dns-zones/my-zone-id", testHandler(http.MethodGet, http.StatusOK, "dns-get-dns-zone.json")) + + zone, err := client.GetDNSZone(context.Background(), "my-zone-id") + require.NoError(t, err) + + expected := &DNSZone{ + ID: "3fa85f64-5717-4562-b3fc-2c963f66afa6", + Domain: "string", + RecordSet: &RecordSet{ + TXT: &TXTRecord{}, + }, + } + + assert.Equal(t, expected, zone) +} + +func TestClient_CreateDNSZone(t *testing.T) { + client := setupTest(t, "/dns-zones", testHandler(http.MethodPost, http.StatusCreated, "dns-create-dns-zone.json")) + + request := CreateDNSZoneRequest{ + Name: "test", + ParentZoneID: "my-parent-zone-id", + } + + zone, err := client.CreateDNSZone(context.Background(), request) + require.NoError(t, err) + + expected := &DNSZone{ + ID: "3fa85f64-5717-4562-b3fc-2c963f66afa6", + } + + assert.Equal(t, expected, zone) +} + +func TestClient_UpdateTXTRecord(t *testing.T) { + client := setupTest(t, "/dns-zones/my-zone-id/record-sets/txt", testHandler(http.MethodPut, http.StatusNoContent, "")) + + record := TXTRecord{ + Settings: Settings{ + TTL: TTL{Auto: true}, + }, + Entries: []string{"txt"}, + } + + err := client.UpdateTXTRecord(context.Background(), "my-zone-id", record) + require.NoError(t, err) +} + +func TestClient_DeleteDNSZone(t *testing.T) { + client := setupTest(t, "/dns-zones/my-zone-id", testHandler(http.MethodDelete, http.StatusOK, "")) + + err := client.DeleteDNSZone(context.Background(), "my-zone-id") + require.NoError(t, err) +} + +func TestClient_DeleteDNSZone_error(t *testing.T) { + client := setupTest(t, "/dns-zones/my-zone-id", testHandler(http.MethodDelete, http.StatusInternalServerError, "error.json")) + + err := client.DeleteDNSZone(context.Background(), "my-zone-id") + assert.EqualError(t, err, "[status code 500] InternalServerError: Something went wrong") +} diff --git a/providers/dns/mittwald/internal/fixtures/dns-create-dns-zone.json b/providers/dns/mittwald/internal/fixtures/dns-create-dns-zone.json new file mode 100644 index 00000000..ef924d5e --- /dev/null +++ b/providers/dns/mittwald/internal/fixtures/dns-create-dns-zone.json @@ -0,0 +1,3 @@ +{ + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6" +} diff --git a/providers/dns/mittwald/internal/fixtures/dns-get-dns-zone.json b/providers/dns/mittwald/internal/fixtures/dns-get-dns-zone.json new file mode 100644 index 00000000..743cf2f0 --- /dev/null +++ b/providers/dns/mittwald/internal/fixtures/dns-get-dns-zone.json @@ -0,0 +1,11 @@ +{ + "domain": "string", + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "recordSet": { + "cname": {}, + "combinedARecords": {}, + "mx": {}, + "srv": {}, + "txt": {} + } +} diff --git a/providers/dns/mittwald/internal/fixtures/dns-list-dns-zones.json b/providers/dns/mittwald/internal/fixtures/dns-list-dns-zones.json new file mode 100644 index 00000000..7b5fd08c --- /dev/null +++ b/providers/dns/mittwald/internal/fixtures/dns-list-dns-zones.json @@ -0,0 +1,13 @@ +[ + { + "domain": "string", + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "recordSet": { + "cname": {}, + "combinedARecords": {}, + "mx": {}, + "srv": {}, + "txt": {} + } + } +] diff --git a/providers/dns/mittwald/internal/fixtures/domain-list-domains.json b/providers/dns/mittwald/internal/fixtures/domain-list-domains.json new file mode 100644 index 00000000..52083086 --- /dev/null +++ b/providers/dns/mittwald/internal/fixtures/domain-list-domains.json @@ -0,0 +1,74 @@ +[ + { + "authCode": { + "expires": "2024-06-04T15:11:59.964Z", + "value": "string" + }, + "authCode2": { + "expires": "2024-06-04T15:11:59.964Z" + }, + "connected": true, + "deleted": true, + "domain": "string", + "domainId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "handles": { + "adminC": { + "current": { + "handleFields": [ + { + "name": "string", + "value": "jnoFDyCBDHC&70Zp&2JMErZBq(),fnsYIvn_bOed5e_.vmsrZ3-IH )Ms)Xc13KDWy2WMH((mJ.-uY_NEBu/3MO8)3" + } + ], + "handleRef": "string" + }, + "desired": { + "handleFields": [ + { + "name": "string", + "value": "1odACmUIyjG Xa-uEX7R+f4,ykqpZ71FFLzkl8B87/+I@s0bVMxA" + } + ], + "handleRef": "string" + } + }, + "ownerC": { + "current": { + "handleFields": [ + { + "name": "string", + "value": "oklq/PU.yBrSFq) .Qx_Uqb8NBZnwA(9jk@x4w Dp6lLd&+a-A.oG5sHw(jcRSOyv0" + } + ], + "handleRef": "string" + }, + "desired": { + "handleFields": [ + { + "name": "string", + "value": "iwt.q,vygqXwZ0_HK+j3kuw/,A,Z)L1Jg&fNgIxWdBc1xnGj(pjj8YQX1DG 9M1/_Vaam," + } + ], + "handleRef": "string" + } + } + }, + "nameservers": [ + "string" + ], + "processes": [ + { + "error": "string", + "lastUpdate": "2024-06-04T15:11:59.973Z", + "processType": "UNSPECIFIED", + "state": "UNSPECIFIED", + "status": "string", + "statusCode": "string", + "transactionId": "string" + } + ], + "projectId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "transferInAuthCode": "string", + "usesDefaultNameserver": true + } +] diff --git a/providers/dns/mittwald/internal/fixtures/error-client.json b/providers/dns/mittwald/internal/fixtures/error-client.json new file mode 100644 index 00000000..d62f8067 --- /dev/null +++ b/providers/dns/mittwald/internal/fixtures/error-client.json @@ -0,0 +1,14 @@ +{ + "type": "ValidationError", + "message": "Validation failed", + "validationErrors": [ + { + "message": "should be string", + "path": ".address.street", + "type": "format", + "context": { + "format": "email" + } + } + ] +} diff --git a/providers/dns/mittwald/internal/fixtures/error.json b/providers/dns/mittwald/internal/fixtures/error.json new file mode 100644 index 00000000..00919f64 --- /dev/null +++ b/providers/dns/mittwald/internal/fixtures/error.json @@ -0,0 +1,4 @@ +{ + "message": "Something went wrong", + "type": "InternalServerError" +} diff --git a/providers/dns/mittwald/internal/types.go b/providers/dns/mittwald/internal/types.go new file mode 100644 index 00000000..df10ab29 --- /dev/null +++ b/providers/dns/mittwald/internal/types.go @@ -0,0 +1,82 @@ +package internal + +import "fmt" + +// https://api.mittwald.de/v2/docs/#/Domain/domain-list-domains + +type Domain struct { + Domain string `json:"domain,omitempty"` + DomainID string `json:"domainId,omitempty"` + ProjectID string `json:"projectId,omitempty"` +} + +// https://api.mittwald.de/v2/docs/#/Domain/dns-list-dns-zones + +type DNSZone struct { + ID string `json:"id,omitempty"` + Domain string `json:"domain,omitempty"` + RecordSet *RecordSet `json:"recordSet,omitempty"` +} + +type RecordSet struct { + TXT *TXTRecord `json:"txt"` +} + +// https://api.mittwald.de/v2/docs/#/Domain/dns-create-dns-zone + +type CreateDNSZoneRequest struct { + Name string `json:"name,omitempty"` + ParentZoneID string `json:"parentZoneId,omitempty"` +} + +type NewDNSZone struct { + ID string `json:"id"` +} + +// https://api.mittwald.de/v2/docs/#/Domain/dns-update-record-set + +type TXTRecord struct { + Settings Settings `json:"settings,omitempty"` + Entries []string `json:"entries,omitempty"` +} + +type Settings struct { + TTL TTL `json:"ttl"` +} + +type TTL struct { + Seconds int `json:"seconds,omitempty"` + Auto bool `json:"auto,omitempty"` +} + +// Error + +type APIError struct { + Type string `json:"type,omitempty"` + Message string `json:"message,omitempty"` + ValidationErrors []ValidationError `json:"validationErrors,omitempty"` +} + +func (a APIError) Error() string { + msg := fmt.Sprintf("%s: %s", a.Type, a.Message) + + if len(a.ValidationErrors) > 0 { + for _, validationError := range a.ValidationErrors { + msg += fmt.Sprintf(" [%s: %s (%s, %s)]", + validationError.Type, validationError.Message, validationError.Path, validationError.Context.Format) + } + } + + return msg +} + +type ValidationError struct { + Message string `json:"message,omitempty"` + Path string `json:"path,omitempty"` + Type string `json:"type,omitempty"` + Context ValidationErrorContext `json:"context,omitempty"` +} + +type ValidationErrorContext struct { + Format string `json:"format,omitempty"` +} diff --git a/providers/dns/mittwald/mittwald.go b/providers/dns/mittwald/mittwald.go new file mode 100644 index 00000000..66aafffb --- /dev/null +++ b/providers/dns/mittwald/mittwald.go @@ -0,0 +1,241 @@ +// Package mittwald implements a DNS provider for solving the DNS-01 challenge using Mittwald. +package mittwald + +import ( + "context" + "errors" + "fmt" + "net/http" + "sync" + "time" + + "github.com/go-acme/lego/v4/challenge/dns01" + "github.com/go-acme/lego/v4/platform/config/env" + "github.com/go-acme/lego/v4/providers/dns/mittwald/internal" + "github.com/miekg/dns" +) + +// Environment variables names. +const ( + envNamespace = "MITTWALD_" + + EnvToken = envNamespace + "TOKEN" + + EnvTTL = envNamespace + "TTL" + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvSequenceInterval = envNamespace + "SEQUENCE_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" +) + +const minTTL = 300 + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + Token string + TTL int + PropagationTimeout time.Duration + PollingInterval time.Duration + SequenceInterval time.Duration + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, minTTL), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 2*time.Minute), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 10*time.Second), + SequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, 2*time.Minute), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *internal.Client + + zoneIDs map[string]string + zoneIDsMu sync.Mutex +} + +// NewDNSProvider returns a DNSProvider instance configured for Mittwald. +// Credentials must be passed in the environment variables: MITTWALD_TOKEN. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvToken) + if err != nil { + return nil, fmt.Errorf("mittwald: %w", err) + } + + config := NewDefaultConfig() + config.Token = values[EnvToken] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Mittwald. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("mittwald: the configuration of the DNS provider is nil") + } + + if config.Token == "" { + return nil, errors.New("mittwald: some credentials information are missing") + } + + if config.TTL < minTTL { + return nil, fmt.Errorf("mittwald: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) + } + + return &DNSProvider{ + config: config, + client: internal.NewClient(config.Token), + zoneIDs: map[string]string{}, + }, 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 +} + +// Sequential All DNS challenges for this provider will be resolved sequentially. +// Returns the interval between each iteration. +func (d *DNSProvider) Sequential() time.Duration { + return d.config.SequenceInterval +} + +// Present creates a TXT record to fulfill the dns-01 challenge. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + ctx := context.Background() + info := dns01.GetChallengeInfo(domain, keyAuth) + + zone, err := d.getOrCreateZone(ctx, info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("mittwald: get effective zone: %w", err) + } + + record := internal.TXTRecord{ + Settings: internal.Settings{ + TTL: internal.TTL{Seconds: d.config.TTL}, + }, + Entries: []string{info.Value}, + } + + err = d.client.UpdateTXTRecord(ctx, zone.ID, record) + if err != nil { + return fmt.Errorf("mittwald: update/add TXT record: %w", err) + } + + d.zoneIDsMu.Lock() + d.zoneIDs[token] = zone.ID + d.zoneIDsMu.Unlock() + + return nil +} + +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + ctx := context.Background() + info := dns01.GetChallengeInfo(domain, keyAuth) + + // get the record's unique ID from when we created it + d.zoneIDsMu.Lock() + zoneID, ok := d.zoneIDs[token] + d.zoneIDsMu.Unlock() + if !ok { + return fmt.Errorf("mittwald: unknown zone ID for '%s'", info.EffectiveFQDN) + } + + record := internal.TXTRecord{Entries: make([]string, 0)} + + err := d.client.UpdateTXTRecord(ctx, zoneID, record) + if err != nil { + return fmt.Errorf("mittwald: update/delete TXT record: %w", err) + } + + return nil +} + +func (d *DNSProvider) getOrCreateZone(ctx context.Context, fqdn string) (*internal.DNSZone, error) { + domains, err := d.client.ListDomains(ctx) + if err != nil { + return nil, fmt.Errorf("list domains: %w", err) + } + + dom, err := findDomain(domains, fqdn) + if err != nil { + return nil, fmt.Errorf("find domain: %w", err) + } + + zones, err := d.client.ListDNSZones(ctx, dom.ProjectID) + if err != nil { + return nil, fmt.Errorf("list DNS zones: %w", err) + } + + for _, zone := range zones { + if zone.Domain == dns01.UnFqdn(fqdn) { + return &zone, nil + } + } + + // Looking for parent zone to create a new zone for the subdomain. + + parentZone, err := findZone(zones, fqdn) + if err != nil { + return nil, fmt.Errorf("find zone: %w", err) + } + + subDomain, err := dns01.ExtractSubDomain(fqdn, parentZone.Domain) + if err != nil { + return nil, err + } + + request := internal.CreateDNSZoneRequest{ + Name: subDomain, + ParentZoneID: parentZone.ID, + } + + zone, err := d.client.CreateDNSZone(ctx, request) + if err != nil { + return nil, fmt.Errorf("create DNS zone: %w", err) + } + + return zone, nil +} + +func findDomain(domains []internal.Domain, fqdn string) (internal.Domain, error) { + labelIndexes := dns.Split(fqdn) + + for _, index := range labelIndexes { + domain := dns01.UnFqdn(fqdn[index:]) + + for _, dom := range domains { + if dom.Domain == domain { + return dom, nil + } + } + } + + return internal.Domain{}, fmt.Errorf("domain %s not found", fqdn) +} + +func findZone(zones []internal.DNSZone, fqdn string) (internal.DNSZone, error) { + labelIndexes := dns.Split(fqdn) + + for _, index := range labelIndexes { + domain := dns01.UnFqdn(fqdn[index:]) + + for _, zon := range zones { + if zon.Domain == domain { + return zon, nil + } + } + } + + return internal.DNSZone{}, fmt.Errorf("zone %s not found", fqdn) +} diff --git a/providers/dns/mittwald/mittwald.toml b/providers/dns/mittwald/mittwald.toml new file mode 100644 index 00000000..2df7d026 --- /dev/null +++ b/providers/dns/mittwald/mittwald.toml @@ -0,0 +1,23 @@ +Name = "Mittwald" +Description = '''''' +URL = "https://www.mittwald.de/" +Code = "mittwald" +Since = "v1.48.0" + +Example = ''' +MITTWALD_TOKEN=my-token \ +lego --email you@example.com --dns mittwald --domains my.example.org run +''' + +[Configuration] + [Configuration.Credentials] + MITTWALD_TOKEN = "API token" + [Configuration.Additional] + MITTWALD_POLLING_INTERVAL = "Time between DNS propagation check" + MITTWALD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + MITTWALD_TTL = "The TTL of the TXT record used for the DNS challenge" + MITTWALD_HTTP_TIMEOUT = "API request timeout" + MITTWALD_SEQUENCE_INTERVAL = "Time between sequential requests" + +[Links] + API = "https://api.mittwald.de/v2/docs/" diff --git a/providers/dns/mittwald/mittwald_test.go b/providers/dns/mittwald/mittwald_test.go new file mode 100644 index 00000000..d8cbdb26 --- /dev/null +++ b/providers/dns/mittwald/mittwald_test.go @@ -0,0 +1,243 @@ +package mittwald + +import ( + "testing" + "time" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/go-acme/lego/v4/providers/dns/mittwald/internal" + "github.com/stretchr/testify/assert" + "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: "secret", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{ + EnvToken: "", + }, + expected: "mittwald: some credentials information are missing: MITTWALD_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 test.expected == "" { + assert.NoError(t, err) + assert.NotNil(t, p) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + token string + ttl int + expected string + }{ + { + desc: "success", + token: "secret", + }, + { + desc: "missing credentials", + expected: "mittwald: some credentials information are missing", + }, + { + desc: "invalid TTL", + token: "secret", + ttl: 10, + expected: "mittwald: invalid TTL, TTL (10) must be greater than 300", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.Token = test.token + + if test.ttl > 0 { + config.TTL = test.ttl + } + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + assert.NoError(t, err) + assert.NotNil(t, p) + } 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(2 * time.Second) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} + +func Test_findDomain(t *testing.T) { + domains := []internal.Domain{ + { + Domain: "example.com", + ProjectID: "a1", + }, + { + Domain: "foo.example.com", + ProjectID: "a2", + }, + { + Domain: "example.org", + ProjectID: "b1", + }, + { + Domain: "foo.example.org", + ProjectID: "b2", + }, + { + Domain: "test.example.org", + ProjectID: "b3", + }, + } + + testCases := []struct { + desc string + fqdn string + expected internal.Domain + }{ + { + desc: "exact match", + fqdn: "example.org.", + expected: internal.Domain{Domain: "example.org", ProjectID: "b1"}, + }, + { + desc: "1 level parent", + fqdn: "_acme-challenge.test.example.org.", + expected: internal.Domain{Domain: "test.example.org", ProjectID: "b3"}, + }, + { + desc: "2 levels parent", + fqdn: "_acme-challenge.test.example.com.", + expected: internal.Domain{Domain: "example.com", ProjectID: "a1"}, + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + domain, err := findDomain(domains, test.fqdn) + require.NoError(t, err) + + assert.Equal(t, test.expected, domain) + }) + } +} + +func Test_findZone(t *testing.T) { + zones := []internal.DNSZone{ + { + Domain: "example.com", + ID: "a1", + }, + { + Domain: "foo.example.com", + ID: "a2", + }, + { + Domain: "example.org", + ID: "b1", + }, + { + Domain: "foo.example.org", + ID: "b2", + }, + { + Domain: "test.example.org", + ID: "b3", + }, + } + + testCases := []struct { + desc string + fqdn string + expected internal.DNSZone + }{ + { + desc: "exact match", + fqdn: "example.org.", + expected: internal.DNSZone{Domain: "example.org", ID: "b1"}, + }, + { + desc: "1 level parent", + fqdn: "_acme-challenge.test.example.org.", + expected: internal.DNSZone{Domain: "test.example.org", ID: "b3"}, + }, + { + desc: "2 levels parent", + fqdn: "_acme-challenge.test.example.com.", + expected: internal.DNSZone{Domain: "example.com", ID: "a1"}, + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + zone, err := findZone(zones, test.fqdn) + require.NoError(t, err) + + assert.Equal(t, test.expected, zone) + }) + } +}