From d4200c6d4c4346c22f46240a472c2fbf02036601 Mon Sep 17 00:00:00 2001 From: SamTV12345 <40429738+SamTV12345@users.noreply.github.com> Date: Thu, 20 Jul 2023 04:16:23 +0200 Subject: [PATCH] Add IPv64 as DNS Provider (#1954) Co-authored-by: Fernandez Ludovic --- .golangci.yml | 2 +- README.md | 32 +-- cmd/zz_gen_cmd_dnshelp.go | 22 ++ docs/content/dns/zz_gen_ipv64.md | 68 ++++++ docs/data/zz_cli_help.toml | 2 +- providers/dns/dns_providers.go | 3 + providers/dns/ipv64/internal/client.go | 142 +++++++++++++ providers/dns/ipv64/internal/client_test.go | 147 +++++++++++++ .../internal/fixtures/add_record-error.json | 5 + .../ipv64/internal/fixtures/add_record.json | 5 + .../internal/fixtures/del_record-error.json | 5 + .../ipv64/internal/fixtures/del_record.json | 5 + .../dns/ipv64/internal/fixtures/error.json | 4 + .../ipv64/internal/fixtures/get_domains.json | 39 ++++ providers/dns/ipv64/internal/types.go | 63 ++++++ providers/dns/ipv64/ipv64.go | 144 +++++++++++++ providers/dns/ipv64/ipv64.toml | 23 +++ providers/dns/ipv64/ipv64_test.go | 195 ++++++++++++++++++ 18 files changed, 888 insertions(+), 18 deletions(-) create mode 100644 docs/content/dns/zz_gen_ipv64.md create mode 100644 providers/dns/ipv64/internal/client.go create mode 100644 providers/dns/ipv64/internal/client_test.go create mode 100644 providers/dns/ipv64/internal/fixtures/add_record-error.json create mode 100644 providers/dns/ipv64/internal/fixtures/add_record.json create mode 100644 providers/dns/ipv64/internal/fixtures/del_record-error.json create mode 100644 providers/dns/ipv64/internal/fixtures/del_record.json create mode 100644 providers/dns/ipv64/internal/fixtures/error.json create mode 100644 providers/dns/ipv64/internal/fixtures/get_domains.json create mode 100644 providers/dns/ipv64/internal/types.go create mode 100644 providers/dns/ipv64/ipv64.go create mode 100644 providers/dns/ipv64/ipv64.toml create mode 100644 providers/dns/ipv64/ipv64_test.go diff --git a/.golangci.yml b/.golangci.yml index b8c1be2d..561ec901 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,5 @@ run: - timeout: 7m + timeout: 10m skip-files: [] linters-settings: diff --git a/README.md b/README.md index 64851bc1..304331cd 100644 --- a/README.md +++ b/README.md @@ -68,22 +68,22 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [Google Domains](https://go-acme.github.io/lego/dns/googledomains/) | [Hetzner](https://go-acme.github.io/lego/dns/hetzner/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [Hosttech](https://go-acme.github.io/lego/dns/hosttech/) | | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Hurricane Electric DNS](https://go-acme.github.io/lego/dns/hurricane/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) | [IBM Cloud (SoftLayer)](https://go-acme.github.io/lego/dns/ibmcloud/) | | [IIJ DNS Platform Service](https://go-acme.github.io/lego/dns/iijdpf/) | [Infoblox](https://go-acme.github.io/lego/dns/infoblox/) | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | -| [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [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/) | [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/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | -| [Metaname](https://go-acme.github.io/lego/dns/metaname/) | [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](https://go-acme.github.io/lego/dns/selectel/) | -| [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [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/) | -| [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [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/) | | | +| [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [IPv64](https://go-acme.github.io/lego/dns/ipv64/) | +| [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/) | +| [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/) | +| [Manual](https://go-acme.github.io/lego/dns/manual/) | [Metaname](https://go-acme.github.io/lego/dns/metaname/) | [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](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [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/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [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 8a042fb1..d9079604 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -76,6 +76,7 @@ func allDNSCodes() string { "internetbs", "inwx", "ionos", + "ipv64", "iwantmyname", "joker", "liara", @@ -1449,6 +1450,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/ionos`) + case "ipv64": + // generated from: providers/dns/ipv64/ipv64.toml + ew.writeln(`Configuration for IPv64.`) + ew.writeln(`Code: 'ipv64'`) + ew.writeln(`Since: 'v4.13.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "IPV64_API_KEY": Account API Key`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "IPV64_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "IPV64_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "IPV64_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "IPV64_SEQUENCE_INTERVAL": Time between sequential requests`) + ew.writeln(` - "IPV64_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/ipv64`) + case "iwantmyname": // generated from: providers/dns/iwantmyname/iwantmyname.toml ew.writeln(`Configuration for iwantmyname.`) diff --git a/docs/content/dns/zz_gen_ipv64.md b/docs/content/dns/zz_gen_ipv64.md new file mode 100644 index 00000000..ac36d839 --- /dev/null +++ b/docs/content/dns/zz_gen_ipv64.md @@ -0,0 +1,68 @@ +--- +title: "IPv64" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: ipv64 +dnsprovider: + since: "v4.13.0" + code: "ipv64" + url: "https://ipv64.net/" +--- + + + + + + +Configuration for [IPv64](https://ipv64.net/). + + + + +- Code: `ipv64` +- Since: v4.13.0 + + +Here is an example bash command using the IPv64 provider: + +```bash +IPV64_API_KEY=xxxxxx \ +lego --email you@example.com --dns ipv64 --domains my.example.org run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `IPV64_API_KEY` | Account API Key | + +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 | +|--------------------------------|-------------| +| `IPV64_HTTP_TIMEOUT` | API request timeout | +| `IPV64_POLLING_INTERVAL` | Time between DNS propagation check | +| `IPV64_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `IPV64_SEQUENCE_INTERVAL` | Time between sequential requests | +| `IPV64_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://ipv64.net/dyndns_updater_api) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index 9cf33068..27296037 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -136,7 +136,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, cloudxns, conoha, constellix, derak, desec, designate, digitalocean, 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, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, manual, metaname, 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, servercow, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, websupport, wedos, yandex, yandexcloud, zoneee, zonomi + acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudxns, conoha, constellix, derak, desec, designate, digitalocean, 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, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, manual, metaname, 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, servercow, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, websupport, wedos, yandex, 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 84033f05..a3a52056 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -67,6 +67,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/internetbs" "github.com/go-acme/lego/v4/providers/dns/inwx" "github.com/go-acme/lego/v4/providers/dns/ionos" + "github.com/go-acme/lego/v4/providers/dns/ipv64" "github.com/go-acme/lego/v4/providers/dns/iwantmyname" "github.com/go-acme/lego/v4/providers/dns/joker" "github.com/go-acme/lego/v4/providers/dns/liara" @@ -255,6 +256,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return inwx.NewDNSProvider() case "ionos": return ionos.NewDNSProvider() + case "ipv64": + return ipv64.NewDNSProvider() case "iwantmyname": return iwantmyname.NewDNSProvider() case "joker": diff --git a/providers/dns/ipv64/internal/client.go b/providers/dns/ipv64/internal/client.go new file mode 100644 index 00000000..e1fdbd19 --- /dev/null +++ b/providers/dns/ipv64/internal/client.go @@ -0,0 +1,142 @@ +package internal + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" +) + +const defaultBaseURL = "https://ipv64.net" + +const authorizationHeader = "Authorization" + +type Client struct { + apiKey string + + baseURL *url.URL + HTTPClient *http.Client +} + +func NewClient(apiKey string) *Client { + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + apiKey: apiKey, + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 15 * time.Second}, + } +} + +func (c Client) GetDomains(ctx context.Context) (*Domains, error) { + endpoint := c.baseURL.JoinPath("api") + + query := endpoint.Query() + query.Set("get_domains", "") + endpoint.RawQuery = query.Encode() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), http.NoBody) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + + results := &Domains{} + + err = c.do(req, results) + if err != nil { + return nil, err + } + + return results, nil +} + +func (c Client) AddRecord(ctx context.Context, domain, prefix, recordType, content string) error { + endpoint := c.baseURL.JoinPath("api") + + data := make(url.Values) + data.Set("add_record", domain) + data.Set("praefix", prefix) + data.Set("type", recordType) + data.Set("content", content) + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), strings.NewReader(data.Encode())) + if err != nil { + return fmt.Errorf("unable to create request: %w", err) + } + + return c.do(req, nil) +} + +func (c Client) DeleteRecord(ctx context.Context, domain, prefix, recordType, content string) error { + endpoint := c.baseURL.JoinPath("api") + + data := make(url.Values) + data.Set("del_record", domain) + data.Set("praefix", prefix) + data.Set("type", recordType) + data.Set("content", content) + + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, endpoint.String(), strings.NewReader(data.Encode())) + if err != nil { + return fmt.Errorf("unable to create request: %w", err) + } + + return c.do(req, nil) +} + +func (c Client) do(req *http.Request, result any) error { + req.Header.Set(authorizationHeader, fmt.Sprintf("Bearer %s", c.apiKey)) + + if req.Method != http.MethodGet { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + + 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) + } + + if string(raw) == "null" { + return fmt.Errorf("unexpected response: %s", string(raw)) + } + + err = json.Unmarshal(raw, result) + if err != nil { + return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err) + } + + return nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + errAPI := &APIError{} + err := json.Unmarshal(raw, errAPI) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return errAPI +} diff --git a/providers/dns/ipv64/internal/client_test.go b/providers/dns/ipv64/internal/client_test.go new file mode 100644 index 00000000..fd2f8991 --- /dev/null +++ b/providers/dns/ipv64/internal/client_test.go @@ -0,0 +1,147 @@ +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, handler http.HandlerFunc) *Client { + t.Helper() + + server := httptest.NewServer(handler) + + client := NewClient("secret") + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client +} + +func testHandler(method, filename string, statusCode int) http.HandlerFunc { + return func(rw http.ResponseWriter, req *http.Request) { + if req.Method != method { + http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed) + return + } + + auth := req.Header.Get(authorizationHeader) + if auth != "Bearer secret" { + http.Error(rw, fmt.Sprintf("invalid API key: %s", auth), http.StatusUnauthorized) + return + } + + file, err := os.Open(filepath.Join("fixtures", filename)) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + + defer func() { _ = file.Close() }() + + rw.WriteHeader(statusCode) + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + } +} + +func TestClient_GetDomains(t *testing.T) { + client := setupTest(t, testHandler(http.MethodGet, "get_domains.json", http.StatusOK)) + + domains, err := client.GetDomains(context.Background()) + require.NoError(t, err) + + expected := &Domains{ + APIResponse: APIResponse{ + Status: "200 OK", + Info: "success", + }, + APICall: "get_domains", + Subdomains: map[string]Subdomain{ + "lego.home64.net": { + Updates: 0, + Wildcard: 1, + DomainUpdateHash: "Dr4l6jFVgkXITqZPEyMHLNsGAfwoSu9v", + Records: []Record{ + { + RecordID: 50665, + Content: "2606:2800:220:1:248:1893:25c8:1946", + TTL: 60, + Type: "AAAA", + Prefix: "", + LastUpdate: "2023-07-19 13:18:59", + RecordKey: "MTA0YzdmMWVjYTFiNDBmZjYwMTU0OGUy", + }, + }, + }, + "lego.ipv64.net": { + Updates: 0, + Wildcard: 1, + DomainUpdateHash: "Dr4l6jFVgkXITqZPEyMHLNsGAfwoSu9v", + Records: []Record{ + { + RecordID: 50664, + Content: "2606:2800:220:1:248:1893:25c8:1946", + TTL: 60, + Type: "AAAA", + Prefix: "", + LastUpdate: "2023-07-19 13:18:59", + RecordKey: "ZDMxOWUxMjZjOTk5MmQ3N2M3ODc4NjJj", + }, + }, + }, + }, + } + + assert.Equal(t, expected, domains) +} + +func TestClient_GetDomains_error(t *testing.T) { + client := setupTest(t, testHandler(http.MethodGet, "error.json", http.StatusUnauthorized)) + + domains, err := client.GetDomains(context.Background()) + require.Error(t, err) + + require.Nil(t, domains) +} + +func TestClient_AddRecord(t *testing.T) { + client := setupTest(t, testHandler(http.MethodPost, "add_record.json", http.StatusCreated)) + + err := client.AddRecord(context.Background(), "lego.ipv64.net", "_acme-challenge", "TXT", "value") + require.NoError(t, err) +} + +func TestClient_AddRecord_error(t *testing.T) { + client := setupTest(t, testHandler(http.MethodPost, "add_record-error.json", http.StatusBadRequest)) + + err := client.AddRecord(context.Background(), "lego.ipv64.net", "_acme-challenge", "TXT", "value") + require.Error(t, err) +} + +func TestClient_DeleteRecord(t *testing.T) { + client := setupTest(t, testHandler(http.MethodDelete, "del_record.json", http.StatusAccepted)) + + err := client.DeleteRecord(context.Background(), "lego.ipv64.net", "_acme-challenge", "TXT", "value") + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client := setupTest(t, testHandler(http.MethodDelete, "del_record-error.json", http.StatusBadRequest)) + + err := client.DeleteRecord(context.Background(), "lego.ipv64.net", "_acme-challenge", "TXT", "value") + require.Error(t, err) +} diff --git a/providers/dns/ipv64/internal/fixtures/add_record-error.json b/providers/dns/ipv64/internal/fixtures/add_record-error.json new file mode 100644 index 00000000..73f3098a --- /dev/null +++ b/providers/dns/ipv64/internal/fixtures/add_record-error.json @@ -0,0 +1,5 @@ +{ + "info": "error", + "status": "400 Bad Request", + "add_record": "dns record already there" +} diff --git a/providers/dns/ipv64/internal/fixtures/add_record.json b/providers/dns/ipv64/internal/fixtures/add_record.json new file mode 100644 index 00000000..2e5a64ed --- /dev/null +++ b/providers/dns/ipv64/internal/fixtures/add_record.json @@ -0,0 +1,5 @@ +{ + "info": "success", + "status": "201 Created", + "add_record": "lego.ipv64.net" +} diff --git a/providers/dns/ipv64/internal/fixtures/del_record-error.json b/providers/dns/ipv64/internal/fixtures/del_record-error.json new file mode 100644 index 00000000..a3d108d7 --- /dev/null +++ b/providers/dns/ipv64/internal/fixtures/del_record-error.json @@ -0,0 +1,5 @@ +{ + "info": "error", + "status": "403 Forbidden", + "del_record": "del_record" +} diff --git a/providers/dns/ipv64/internal/fixtures/del_record.json b/providers/dns/ipv64/internal/fixtures/del_record.json new file mode 100644 index 00000000..4e27626f --- /dev/null +++ b/providers/dns/ipv64/internal/fixtures/del_record.json @@ -0,0 +1,5 @@ +{ + "info": "success", + "status": "202 Accepted", + "del_record": "del_record" +} diff --git a/providers/dns/ipv64/internal/fixtures/error.json b/providers/dns/ipv64/internal/fixtures/error.json new file mode 100644 index 00000000..ba0fe85c --- /dev/null +++ b/providers/dns/ipv64/internal/fixtures/error.json @@ -0,0 +1,4 @@ +{ + "status": "401 Unauthorized", + "info": "Unauthorized" +} diff --git a/providers/dns/ipv64/internal/fixtures/get_domains.json b/providers/dns/ipv64/internal/fixtures/get_domains.json new file mode 100644 index 00000000..3cb1de8b --- /dev/null +++ b/providers/dns/ipv64/internal/fixtures/get_domains.json @@ -0,0 +1,39 @@ +{ + "subdomains": { + "lego.ipv64.net": { + "updates": 0, + "wildcard": 1, + "domain_update_hash": "Dr4l6jFVgkXITqZPEyMHLNsGAfwoSu9v", + "records": [ + { + "record_id": 50664, + "content": "2606:2800:220:1:248:1893:25c8:1946", + "ttl": 60, + "type": "AAAA", + "praefix": "", + "last_update": "2023-07-19 13:18:59", + "record_key": "ZDMxOWUxMjZjOTk5MmQ3N2M3ODc4NjJj" + } + ] + }, + "lego.home64.net": { + "updates": 0, + "wildcard": 1, + "domain_update_hash": "Dr4l6jFVgkXITqZPEyMHLNsGAfwoSu9v", + "records": [ + { + "record_id": 50665, + "content": "2606:2800:220:1:248:1893:25c8:1946", + "ttl": 60, + "type": "AAAA", + "praefix": "", + "last_update": "2023-07-19 13:18:59", + "record_key": "MTA0YzdmMWVjYTFiNDBmZjYwMTU0OGUy" + } + ] + } + }, + "info": "success", + "status": "200 OK", + "add_domain": "get_domains" +} diff --git a/providers/dns/ipv64/internal/types.go b/providers/dns/ipv64/internal/types.go new file mode 100644 index 00000000..e9e357ec --- /dev/null +++ b/providers/dns/ipv64/internal/types.go @@ -0,0 +1,63 @@ +package internal + +import "fmt" + +type APIResponse struct { + Status string `json:"status"` + Info string `json:"info"` +} + +// error + +type APIError struct { + APIResponse + AddRecordMessage string `json:"add_record"` + DelRecordMessage string `json:"del_record"` + AddDomainMessage string `json:"add_domain"` + DelDomainMessage string `json:"del_domain"` +} + +func (a APIError) Error() string { + msg := a.Info + switch { + case a.AddRecordMessage != "": + msg = a.AddRecordMessage + case a.DelRecordMessage != "": + msg = a.DelRecordMessage + case a.AddDomainMessage != "": + msg = a.AddDomainMessage + case a.DelDomainMessage != "": + msg = a.DelDomainMessage + } + + if msg == "" { + return fmt.Sprintf("%s: %s", a.Status, a.Info) + } + + return fmt.Sprintf("%s (%s): %s", a.Info, a.Status, msg) +} + +// get_domains + +type Domains struct { + APIResponse + APICall string `json:"add_domain"` + Subdomains map[string]Subdomain `json:"subdomains"` +} + +type Subdomain struct { + Updates int `json:"updates"` + Wildcard int `json:"wildcard"` + DomainUpdateHash string `json:"domain_update_hash"` + Records []Record `json:"records"` +} + +type Record struct { + RecordID int `json:"record_id"` + Content string `json:"content"` + TTL int `json:"ttl"` + Type string `json:"type"` + Prefix string `json:"praefix"` + LastUpdate string `json:"last_update"` + RecordKey string `json:"record_key"` +} diff --git a/providers/dns/ipv64/ipv64.go b/providers/dns/ipv64/ipv64.go new file mode 100644 index 00000000..b943f311 --- /dev/null +++ b/providers/dns/ipv64/ipv64.go @@ -0,0 +1,144 @@ +// Package ipv64 implements a DNS provider for solving the DNS-01 challenge using IPv64. +// See https://ipv64.net/healthcheck_updater_api for more info on updating TXT records. +package ipv64 + +import ( + "context" + "errors" + "fmt" + "net/http" + "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/ipv64/internal" + "github.com/miekg/dns" +) + +// Environment variables names. +const ( + envNamespace = "IPV64_" + + EnvAPIKey = envNamespace + "API_KEY" + + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" + EnvSequenceInterval = envNamespace + "SEQUENCE_INTERVAL" +) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + APIKey string + 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{ + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval), + SequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, dns01.DefaultPropagationTimeout), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *internal.Client +} + +// NewDNSProvider returns a new DNS provider using +// environment variable IPV64_TOKEN for adding and removing the DNS record. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey) + if err != nil { + return nil, fmt.Errorf("ipv64: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for IPv64. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("ipv64: the configuration of the DNS provider is nil") + } + + if config.APIKey == "" { + return nil, errors.New("ipv64: credentials missing") + } + + client := internal.NewClient(config.APIKey) + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + return &DNSProvider{config: config, client: client}, nil +} + +// Present creates a TXT record to fulfill the dns-01 challenge. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + sub, root, err := splitDomain(dns01.UnFqdn(info.EffectiveFQDN)) + if err != nil { + return fmt.Errorf("ipv64: %w", err) + } + + err = d.client.AddRecord(context.Background(), root, sub, "TXT", info.Value) + if err != nil { + return fmt.Errorf("ipv64: %w", err) + } + + return nil +} + +// CleanUp clears IPv64 TXT record. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + sub, root, err := splitDomain(dns01.UnFqdn(info.EffectiveFQDN)) + if err != nil { + return fmt.Errorf("ipv64: %w", err) + } + + err = d.client.DeleteRecord(context.Background(), root, sub, "TXT", info.Value) + if err != nil { + return fmt.Errorf("ipv64: %w", err) + } + + return 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 +} + +func splitDomain(full string) (string, string, error) { + split := dns.Split(full) + if len(split) < 3 { + return "", "", fmt.Errorf("unsupported domain: %s", full) + } + + if len(split) == 3 { + return "", full, nil + } + + domain := full[split[len(split)-3]:] + subDomain := full[:split[len(split)-3]-1] + + return subDomain, domain, nil +} diff --git a/providers/dns/ipv64/ipv64.toml b/providers/dns/ipv64/ipv64.toml new file mode 100644 index 00000000..e780dbcd --- /dev/null +++ b/providers/dns/ipv64/ipv64.toml @@ -0,0 +1,23 @@ +Name = "IPv64" +Description = '''''' +URL = "https://ipv64.net/" +Code = "ipv64" +Since = "v4.13.0" + +Example = ''' +IPV64_API_KEY=xxxxxx \ +lego --email you@example.com --dns ipv64 --domains my.example.org run +''' + +[Configuration] + [Configuration.Credentials] + IPV64_API_KEY = "Account API Key" + [Configuration.Additional] + IPV64_POLLING_INTERVAL = "Time between DNS propagation check" + IPV64_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + IPV64_TTL = "The TTL of the TXT record used for the DNS challenge" + IPV64_HTTP_TIMEOUT = "API request timeout" + IPV64_SEQUENCE_INTERVAL = "Time between sequential requests" + +[Links] + API = "https://ipv64.net/dyndns_updater_api" diff --git a/providers/dns/ipv64/ipv64_test.go b/providers/dns/ipv64/ipv64_test.go new file mode 100644 index 00000000..114919ee --- /dev/null +++ b/providers/dns/ipv64/ipv64_test.go @@ -0,0 +1,195 @@ +package ipv64 + +import ( + "testing" + "time" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvAPIKey).WithDomain(envDomain) + +func Test_splitDomain(t *testing.T) { + type expected struct { + root string + sub string + requireErr require.ErrorAssertionFunc + } + + testCases := []struct { + desc string + domain string + expected expected + }{ + { + desc: "empty", + domain: "", + expected: expected{ + requireErr: require.Error, + }, + }, + { + desc: "2 levels", + domain: "example.com", + expected: expected{ + requireErr: require.Error, + }, + }, + { + desc: "3 levels", + domain: "_acme-challenge.example.com", + expected: expected{ + root: "_acme-challenge.example.com", + sub: "", + requireErr: require.NoError, + }, + }, + { + desc: "4 levels", + domain: "_acme-challenge.sub.example.com", + expected: expected{ + root: "sub.example.com", + sub: "_acme-challenge", + requireErr: require.NoError, + }, + }, + { + desc: "5 levels", + domain: "_acme-challenge.my.sub.example.com", + expected: expected{ + root: "sub.example.com", + sub: "_acme-challenge.my", + requireErr: require.NoError, + }, + }, + { + desc: "6 levels", + domain: "_acme-challenge.my.sub.sub.example.com", + expected: expected{ + root: "sub.example.com", + sub: "_acme-challenge.my.sub", + requireErr: require.NoError, + }, + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + sub, root, err := splitDomain(test.domain) + test.expected.requireErr(t, err) + + assert.Equal(t, test.expected.root, root) + assert.Equal(t, test.expected.sub, sub) + }) + } +} + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvAPIKey: "123", + }, + }, + { + desc: "missing api key", + envVars: map[string]string{ + EnvAPIKey: "", + }, + expected: "ipv64: some credentials information are missing: IPV64_API_KEY", + }, + } + + 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 == "" { + 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 + apiKey string + expected string + }{ + { + desc: "success", + apiKey: "123", + }, + { + desc: "missing credentials", + expected: "ipv64: credentials missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIKey = test.apiKey + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + 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) +}