From 7d7bc7b044ac0c3b635b279f1437dbbba30f2d00 Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Tue, 28 Jan 2025 18:02:12 +0100 Subject: [PATCH] Add DNS provider for myaddr.{tools,dev,io} (#2411) --- README.md | 32 ++-- cmd/zz_gen_cmd_dnshelp.go | 22 +++ docs/content/dns/zz_gen_myaddr.md | 68 ++++++++ docs/data/zz_cli_help.toml | 4 +- providers/dns/myaddr/internal/client.go | 115 +++++++++++++ providers/dns/myaddr/internal/client_test.go | 77 +++++++++ .../dns/myaddr/internal/fixtures/error.txt | 1 + providers/dns/myaddr/internal/types.go | 6 + providers/dns/myaddr/myaddr.go | 160 ++++++++++++++++++ providers/dns/myaddr/myaddr.toml | 23 +++ providers/dns/myaddr/myaddr_test.go | 113 +++++++++++++ providers/dns/zz_gen_dns_providers.go | 3 + 12 files changed, 606 insertions(+), 18 deletions(-) create mode 100644 docs/content/dns/zz_gen_myaddr.md create mode 100644 providers/dns/myaddr/internal/client.go create mode 100644 providers/dns/myaddr/internal/client_test.go create mode 100644 providers/dns/myaddr/internal/fixtures/error.txt create mode 100644 providers/dns/myaddr/internal/types.go create mode 100644 providers/dns/myaddr/myaddr.go create mode 100644 providers/dns/myaddr/myaddr.toml create mode 100644 providers/dns/myaddr/myaddr_test.go diff --git a/README.md b/README.md index cebd033c2..b779a5863 100644 --- a/README.md +++ b/README.md @@ -158,84 +158,84 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). mijn.host Mittwald + myaddr.{tools,dev,io} MyDNS.jp MythicBeasts - Name.com + Name.com Namecheap Namesilo NearlyFreeSpeech.NET - Netcup + Netcup Netlify Nicmanager NIFCloud - Njalla + Njalla Nodion NS1 Open Telekom Cloud - Oracle Cloud + Oracle Cloud OVH plesk.com Porkbun - PowerDNS + PowerDNS Rackspace Rain Yun/雨云 RcodeZero - reg.ru + reg.ru Regfish RFC2136 RimuHosting - Sakura Cloud + Sakura Cloud Scaleway Selectel Selectel v2 - SelfHost.(de|eu) + SelfHost.(de|eu) Servercow Shellrent Simply.com - Sonic + Sonic Stackpath Technitium Tencent Cloud DNS - Timeweb Cloud + Timeweb Cloud TransIP UKFast SafeDNS Ultradns - Variomedia + Variomedia VegaDNS Vercel Versio.[nl|eu|uk] - VinylDNS + VinylDNS VK Cloud Volcano Engine/火山引擎 Vscale - Vultr + Vultr Webnames Websupport WEDOS - West.cn/西部数码 + West.cn/西部数码 Yandex 360 Yandex Cloud Yandex PDD - Zone.ee + Zone.ee Zonomi - diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 203cff36f..f121d6dd2 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -96,6 +96,7 @@ func allDNSCodes() string { "metaname", "mijnhost", "mittwald", + "myaddr", "mydnsjp", "mythicbeasts", "namecheap", @@ -1939,6 +1940,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/mittwald`) + case "myaddr": + // generated from: providers/dns/myaddr/myaddr.toml + ew.writeln(`Configuration for myaddr.{tools,dev,io}.`) + ew.writeln(`Code: 'myaddr'`) + ew.writeln(`Since: 'v4.22.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "MYADDR_PRIVATE_KEYS_MAPPING": Mapping between subdomains and private keys. The format is: ':,:,:'`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "MYADDR_HTTP_TIMEOUT": API request timeout in seconds (Default: 30)`) + ew.writeln(` - "MYADDR_POLLING_INTERVAL": Time between DNS propagation check in seconds (Default: 2)`) + ew.writeln(` - "MYADDR_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation in seconds (Default: 60)`) + ew.writeln(` - "MYADDR_SEQUENCE_INTERVAL": Time between sequential requests in seconds (Default: 2)`) + ew.writeln(` - "MYADDR_TTL": The TTL of the TXT record used for the DNS challenge in seconds (Default: 120)`) + + ew.writeln() + ew.writeln(`More information: https://go-acme.github.io/lego/dns/myaddr`) + case "mydnsjp": // generated from: providers/dns/mydnsjp/mydnsjp.toml ew.writeln(`Configuration for MyDNS.jp.`) diff --git a/docs/content/dns/zz_gen_myaddr.md b/docs/content/dns/zz_gen_myaddr.md new file mode 100644 index 000000000..277a0bf06 --- /dev/null +++ b/docs/content/dns/zz_gen_myaddr.md @@ -0,0 +1,68 @@ +--- +title: "myaddr.{tools,dev,io}" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: myaddr +dnsprovider: + since: "v4.22.0" + code: "myaddr" + url: "https://myaddr.tools/" +--- + + + + + + +Configuration for [myaddr.{tools,dev,io}](https://myaddr.tools/). + + + + +- Code: `myaddr` +- Since: v4.22.0 + + +Here is an example bash command using the myaddr.{tools,dev,io} provider: + +```bash +MYADDR_PRIVATE_KEYS_MAPPING="example:123,test:456" \ +lego --email you@example.com --dns myaddr -d '*.example.com' -d example.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `MYADDR_PRIVATE_KEYS_MAPPING` | Mapping between subdomains and private keys. The format is: `:,:,:` | + +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 | +|--------------------------------|-------------| +| `MYADDR_HTTP_TIMEOUT` | API request timeout in seconds (Default: 30) | +| `MYADDR_POLLING_INTERVAL` | Time between DNS propagation check in seconds (Default: 2) | +| `MYADDR_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation in seconds (Default: 60) | +| `MYADDR_SEQUENCE_INTERVAL` | Time between sequential requests in seconds (Default: 2) | +| `MYADDR_TTL` | The TTL of the TXT record used for the DNS challenge in seconds (Default: 120) | + +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://myaddr.tools/) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index f6674e5e5..11b48a0d5 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -22,7 +22,7 @@ GLOBAL OPTIONS: --domains value, -d value [ --domains value, -d value ] Add a domain to the process. Can be specified multiple times. --server value, -s value CA hostname (and optionally :port). The server certificate must be trusted in order to avoid further modifications to the client. (default: "https://acme-v02.api.letsencrypt.org/directory") [$LEGO_SERVER] --accept-tos, -a By setting this flag to true you indicate that you accept the current Let's Encrypt terms of service. (default: false) - --email value, -m value Email used for registration and recovery contact. + --email value, -m value Email used for registration and recovery contact. [$LEGO_EMAIL] --csr value, -c value Certificate signing request filename, if an external CSR is to be used. --eab Use External Account Binding for account registration. Requires --kid and --hmac. (default: false) [$LEGO_EAB] --kid value Key identifier from External CA. Used for External Account Binding. [$LEGO_EAB_KID] @@ -145,7 +145,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, corenetworks, 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, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, mijnhost, mittwald, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rainyun, rcodezero, regfish, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, selfhostde, servercow, shellrent, simply, sonic, stackpath, technitium, tencentcloud, timewebcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, volcengine, vscale, vultr, webnames, websupport, wedos, westcn, 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, corenetworks, 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, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rainyun, rcodezero, regfish, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, selfhostde, servercow, shellrent, simply, sonic, stackpath, technitium, tencentcloud, timewebcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, volcengine, vscale, vultr, webnames, websupport, wedos, westcn, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/myaddr/internal/client.go b/providers/dns/myaddr/internal/client.go new file mode 100644 index 000000000..40f919c7d --- /dev/null +++ b/providers/dns/myaddr/internal/client.go @@ -0,0 +1,115 @@ +package internal + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sync" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" +) + +const defaultBaseURL = "https://myaddr.tools" + +// Client the myaddr.{tools,dev,io} API client. +type Client struct { + baseURL *url.URL + HTTPClient *http.Client + + credentials map[string]string + credMu sync.Mutex +} + +// NewClient creates a new Client. +func NewClient(credentials map[string]string) (*Client, error) { + if len(credentials) == 0 { + return nil, errors.New("credentials missing") + } + + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + credentials: credentials, + }, nil +} + +func (c *Client) AddTXTRecord(ctx context.Context, subdomain, value string) error { + c.credMu.Lock() + privateKey, ok := c.credentials[subdomain] + c.credMu.Unlock() + + if !ok { + return fmt.Errorf("subdomain %s not found in credentials, check your credentials map", subdomain) + } + + payload := ACMEChallenge{Key: privateKey, Data: value} + + req, err := newJSONRequest(ctx, http.MethodPost, c.baseURL.JoinPath("update"), payload) + if err != nil { + return err + } + + return c.do(req, nil) +} + +func (c *Client) do(req *http.Request, result any) error { + resp, err := c.HTTPClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode/100 != 2 { + raw, _ := io.ReadAll(resp.Body) + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + 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 +} diff --git a/providers/dns/myaddr/internal/client_test.go b/providers/dns/myaddr/internal/client_test.go new file mode 100644 index 000000000..f74e42eb1 --- /dev/null +++ b/providers/dns/myaddr/internal/client_test.go @@ -0,0 +1,77 @@ +package internal + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T, pattern string, status int, filename string) *Client { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + mux.HandleFunc(pattern, func(rw http.ResponseWriter, req *http.Request) { + if filename == "" { + rw.WriteHeader(status) + 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(status) + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + credentials := map[string]string{ + "example": "secret", + } + + client, err := NewClient(credentials) + require.NoError(t, err) + + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client +} + +func TestClient_AddTXTRecord(t *testing.T) { + client := setupTest(t, "POST /update", http.StatusOK, "") + + err := client.AddTXTRecord(context.Background(), "example", "txt") + require.NoError(t, err) +} + +func TestClient_AddTXTRecord_error(t *testing.T) { + client := setupTest(t, "POST /update", http.StatusBadRequest, "error.txt") + + err := client.AddTXTRecord(context.Background(), "example", "txt") + require.EqualError(t, err, `unexpected status code: [status code: 400] body: invalid value for "key"`) +} + +func TestClient_AddTXTRecord_error_credentials(t *testing.T) { + client := setupTest(t, "POST /update", http.StatusOK, "") + + err := client.AddTXTRecord(context.Background(), "nx", "txt") + require.EqualError(t, err, "subdomain nx not found in credentials, check your credentials map") +} diff --git a/providers/dns/myaddr/internal/fixtures/error.txt b/providers/dns/myaddr/internal/fixtures/error.txt new file mode 100644 index 000000000..64a417673 --- /dev/null +++ b/providers/dns/myaddr/internal/fixtures/error.txt @@ -0,0 +1 @@ +invalid value for "key" diff --git a/providers/dns/myaddr/internal/types.go b/providers/dns/myaddr/internal/types.go new file mode 100644 index 000000000..36f057497 --- /dev/null +++ b/providers/dns/myaddr/internal/types.go @@ -0,0 +1,6 @@ +package internal + +type ACMEChallenge struct { + Key string `json:"key"` + Data string `json:"acme_challenge"` +} diff --git a/providers/dns/myaddr/myaddr.go b/providers/dns/myaddr/myaddr.go new file mode 100644 index 000000000..57d46f514 --- /dev/null +++ b/providers/dns/myaddr/myaddr.go @@ -0,0 +1,160 @@ +// Package myaddr implements a DNS provider for solving the DNS-01 challenge using myaddr.{tools,dev,io}. +package myaddr + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "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/myaddr/internal" +) + +// Environment variables names. +const ( + envNamespace = "MYADDR_" + + EnvPrivateKeysMapping = envNamespace + "PRIVATE_KEYS_MAPPING" + + EnvTTL = envNamespace + "TTL" + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvSequenceInterval = envNamespace + "SEQUENCE_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" +) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + Credentials map[string]string + + PropagationTimeout time.Duration + PollingInterval time.Duration + SequenceInterval time.Duration + TTL int + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval), + SequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, dns01.DefaultPollingInterval), + 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 DNSProvider instance configured for myaddr.{tools,dev,io}. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvPrivateKeysMapping) + if err != nil { + return nil, fmt.Errorf("myaddr: %w", err) + } + + config := NewDefaultConfig() + + credentials, err := parseCredentials(values[EnvPrivateKeysMapping]) + if err != nil { + return nil, fmt.Errorf("myaddr: %w", err) + } + + config.Credentials = credentials + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for myaddr.{tools,dev,io}. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("myaddr: the configuration of the DNS provider is nil") + } + + client, err := internal.NewClient(config.Credentials) + if err != nil { + return nil, fmt.Errorf("myaddr: %w", err) + } + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + return &DNSProvider{ + config: config, + client: client, + }, nil +} + +// Present creates a TXT record using the specified parameters. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("myaddr: could not find zone for domain %q: %w", domain, err) + } + + fullSubdomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) + if err != nil { + return fmt.Errorf("myaddr: %w", err) + } + + _, after, found := strings.Cut(fullSubdomain, ".") + if !found { + return fmt.Errorf("myaddr: subdomain not found in: %q (%s)", fullSubdomain, info.EffectiveFQDN) + } + + err = d.client.AddTXTRecord(context.Background(), after, info.Value) + if err != nil { + return fmt.Errorf("myaddr: add TXT record: %w", err) + } + + return nil +} + +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + // There is no API endpoint to delete a TXT record: + // TXT records are automatically removed after a few minutes. + 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 +} + +// 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 +} + +func parseCredentials(raw string) (map[string]string, error) { + credentials := make(map[string]string) + + credStrings := strings.Split(strings.TrimSuffix(raw, ","), ",") + for _, credPair := range credStrings { + data := strings.Split(credPair, ":") + if len(data) != 2 { + return nil, fmt.Errorf("incorrect credential pair: %s", credPair) + } + + credentials[strings.TrimSpace(data[0])] = strings.TrimSpace(data[1]) + } + + return credentials, nil +} diff --git a/providers/dns/myaddr/myaddr.toml b/providers/dns/myaddr/myaddr.toml new file mode 100644 index 000000000..5ff306526 --- /dev/null +++ b/providers/dns/myaddr/myaddr.toml @@ -0,0 +1,23 @@ +Name = "myaddr.{tools,dev,io}" +Description = '''''' +URL = "https://myaddr.tools/" +Code = "myaddr" +Since = "v4.22.0" + +Example = ''' +MYADDR_PRIVATE_KEYS_MAPPING="example:123,test:456" \ +lego --email you@example.com --dns myaddr -d '*.example.com' -d example.com run +''' + +[Configuration] + [Configuration.Credentials] + MYADDR_PRIVATE_KEYS_MAPPING = "Mapping between subdomains and private keys. The format is: `:,:,:`" + [Configuration.Additional] + MYADDR_POLLING_INTERVAL = "Time between DNS propagation check in seconds (Default: 2)" + MYADDR_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation in seconds (Default: 60)" + MYADDR_SEQUENCE_INTERVAL = "Time between sequential requests in seconds (Default: 2)" + MYADDR_TTL = "The TTL of the TXT record used for the DNS challenge in seconds (Default: 120)" + MYADDR_HTTP_TIMEOUT = "API request timeout in seconds (Default: 30)" + +[Links] + API = "https://myaddr.tools/" diff --git a/providers/dns/myaddr/myaddr_test.go b/providers/dns/myaddr/myaddr_test.go new file mode 100644 index 000000000..d95a0cf5c --- /dev/null +++ b/providers/dns/myaddr/myaddr_test.go @@ -0,0 +1,113 @@ +package myaddr + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvPrivateKeysMapping).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvPrivateKeysMapping: "example:123", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{}, + expected: "myaddr: some credentials information are missing: MYADDR_PRIVATE_KEYS_MAPPING", + }, + } + + 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) + require.NotNil(t, p.client) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + credentials map[string]string + expected string + }{ + { + desc: "success", + credentials: map[string]string{"example": "123"}, + }, + { + desc: "missing credentials", + expected: "myaddr: credentials missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.Credentials = test.credentials + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + require.NotNil(t, p.client) + } 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) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} diff --git a/providers/dns/zz_gen_dns_providers.go b/providers/dns/zz_gen_dns_providers.go index 053c3c4e7..762f69832 100644 --- a/providers/dns/zz_gen_dns_providers.go +++ b/providers/dns/zz_gen_dns_providers.go @@ -90,6 +90,7 @@ import ( "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/myaddr" "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" @@ -324,6 +325,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return mijnhost.NewDNSProvider() case "mittwald": return mittwald.NewDNSProvider() + case "myaddr": + return myaddr.NewDNSProvider() case "mydnsjp": return mydnsjp.NewDNSProvider() case "mythicbeasts":