diff --git a/README.md b/README.md index 5fa9c1ed1..aff5052ca 100644 --- a/README.md +++ b/README.md @@ -65,224 +65,224 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). AlibabaCloud ESA all-inkl + Alwaysdata Amazon Lightsail Amazon Route 53 - Anexia CloudDNS + Anexia CloudDNS ArvanCloud Aurora DNS Autodns - Axelname + Axelname Azion Azure (deprecated) Azure DNS - Baidu Cloud + Baidu Cloud Beget.com Binary Lane Bindman - Bluecat + Bluecat BookMyName Brandit (deprecated) Bunny - Checkdomain + Checkdomain Civo Cloud.ru CloudDNS - Cloudflare + Cloudflare ClouDNS CloudXNS (Deprecated) ConoHa v2 - ConoHa v3 + ConoHa v3 Constellix Core-Networks CPanel/WHM - Derak Cloud + Derak Cloud deSEC.io Designate DNSaaS for Openstack Digital Ocean - DirectAdmin + DirectAdmin DNS Made Easy dnsHome.de DNSimple - DNSPod (deprecated) + DNSPod (deprecated) Domain Offensive (do.de) Domeneshop DreamHost - Duck DNS + Duck DNS Dyn DynDnsFree.de Dynu - EasyDNS + EasyDNS EdgeCenter Efficient IP Epik - Exoscale + Exoscale External program F5 XC freemyip.com - G-Core + G-Core Gandi Gandi Live DNS (v5) Gigahost.no - Glesys + Glesys Go Daddy Google Cloud Google Domains - Gravity + Gravity Hetzner Hosting.de Hosting.nl - Hostinger + Hostinger Hosttech HTTP request http.net - Huawei Cloud + Huawei Cloud Hurricane Electric DNS HyperOne IBM Cloud (SoftLayer) - IIJ DNS Platform Service + IIJ DNS Platform Service Infoblox Infomaniak Internet Initiative Japan - Internet.bs + Internet.bs INWX Ionos Ionos Cloud - IPv64 + IPv64 ISPConfig 3 ISPConfig 3 - Dynamic DNS (DDNS) Module iwantmyname (Deprecated) - Joker + Joker Joohoi's ACME-DNS KeyHelp Liara - Lima-City + Lima-City Linode (v4) Liquid Web Loopia - LuaDNS + LuaDNS Mail-in-a-Box ManageEngine CloudDNS Manual - Metaname + Metaname Metaregistrar mijn.host Mittwald - myaddr.{tools,dev,io} + myaddr.{tools,dev,io} MyDNS.jp MythicBeasts Name.com - Namecheap + Namecheap Namesilo NearlyFreeSpeech.NET Neodigit - Netcup + Netcup Netlify Nicmanager NIFCloud - Njalla + Njalla Nodion NS1 Octenium - Open Telekom Cloud + Open Telekom Cloud Oracle Cloud OVH plesk.com - Porkbun + Porkbun PowerDNS Rackspace Rain Yun/雨云 - RcodeZero + RcodeZero reg.ru Regfish RFC2136 - RimuHosting + RimuHosting RU CENTER Sakura Cloud Scaleway - Selectel + Selectel Selectel v2 SelfHost.(de|eu) Servercow - Shellrent + Shellrent Simply.com Sonic Spaceship - Stackpath + Stackpath Syse Technitium Tencent Cloud DNS - Tencent EdgeOne + Tencent EdgeOne Timeweb Cloud TransIP UKFast SafeDNS - Ultradns + Ultradns United-Domains Variomedia VegaDNS - Vercel + Vercel Versio.[nl|eu|uk] VinylDNS Virtualname - VK Cloud + VK Cloud Volcano Engine/火山引擎 Vscale Vultr - webnames.ca + webnames.ca webnames.ru Websupport WEDOS - West.cn/西部数码 + West.cn/西部数码 Yandex 360 Yandex Cloud Yandex PDD - Zone.ee + Zone.ee ZoneEdit Zonomi - diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 601222903..220289242 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -17,6 +17,7 @@ func allDNSCodes() string { "alidns", "aliesa", "allinkl", + "alwaysdata", "anexia", "arvancloud", "auroradns", @@ -306,6 +307,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/allinkl`) + case "alwaysdata": + // generated from: providers/dns/alwaysdata/alwaysdata.toml + ew.writeln(`Configuration for Alwaysdata.`) + ew.writeln(`Code: 'alwaysdata'`) + ew.writeln(`Since: 'v4.31.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "ALWAYSDATA_API_KEY": API Key`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "ALWAYSDATA_ACCOUNT": Account name`) + ew.writeln(` - "ALWAYSDATA_HTTP_TIMEOUT": API request timeout in seconds (Default: 30)`) + ew.writeln(` - "ALWAYSDATA_POLLING_INTERVAL": Time between DNS propagation check in seconds (Default: 2)`) + ew.writeln(` - "ALWAYSDATA_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation in seconds (Default: 60)`) + ew.writeln(` - "ALWAYSDATA_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/alwaysdata`) + case "anexia": // generated from: providers/dns/anexia/anexia.toml ew.writeln(`Configuration for Anexia CloudDNS.`) diff --git a/docs/content/dns/zz_gen_alwaysdata.md b/docs/content/dns/zz_gen_alwaysdata.md new file mode 100644 index 000000000..75f3cb859 --- /dev/null +++ b/docs/content/dns/zz_gen_alwaysdata.md @@ -0,0 +1,68 @@ +--- +title: "Alwaysdata" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: alwaysdata +dnsprovider: + since: "v4.31.0" + code: "alwaysdata" + url: "https://alwaysdata.com/" +--- + + + + + + +Configuration for [Alwaysdata](https://alwaysdata.com/). + + + + +- Code: `alwaysdata` +- Since: v4.31.0 + + +Here is an example bash command using the Alwaysdata provider: + +```bash +ALWAYSDATA_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email you@example.com --dns alwaysdata -d '*.example.com' -d example.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `ALWAYSDATA_API_KEY` | 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 | +|--------------------------------|-------------| +| `ALWAYSDATA_ACCOUNT` | Account name | +| `ALWAYSDATA_HTTP_TIMEOUT` | API request timeout in seconds (Default: 30) | +| `ALWAYSDATA_POLLING_INTERVAL` | Time between DNS propagation check in seconds (Default: 2) | +| `ALWAYSDATA_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation in seconds (Default: 60) | +| `ALWAYSDATA_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://help.alwaysdata.com/en/api/resources/) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index ae2369a9a..ab9ff31c9 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -152,7 +152,7 @@ To display the documentation for a specific DNS provider, run: $ lego dnshelp -c code Supported DNS providers: - acme-dns, active24, alidns, aliesa, allinkl, anexia, arvancloud, auroradns, autodns, axelname, azion, azure, azuredns, baiducloud, beget, binarylane, bindman, bluecat, bookmyname, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, conohav3, constellix, corenetworks, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dyndnsfree, dynu, easydns, edgecenter, edgedns, edgeone, efficientip, epik, exec, exoscale, f5xc, freemyip, gandi, gandiv5, gcloud, gcore, gigahostno, glesys, godaddy, googledomains, gravity, hetzner, hostingde, hostinger, hostingnl, hosttech, httpnet, httpreq, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ionoscloud, ipv64, ispconfig, ispconfigddns, iwantmyname, joker, keyhelp, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, metaregistrar, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, neodigit, netcup, netlify, nicmanager, nicru, nifcloud, njalla, nodion, ns1, octenium, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rainyun, rcodezero, regfish, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, selfhostde, servercow, shellrent, simply, sonic, spaceship, stackpath, syse, technitium, tencentcloud, timewebcloud, transip, ultradns, uniteddomains, variomedia, vegadns, vercel, versio, vinyldns, virtualname, vkcloud, volcengine, vscale, vultr, webnames, webnamesca, websupport, wedos, westcn, yandex, yandex360, yandexcloud, zoneedit, zoneee, zonomi + acme-dns, active24, alidns, aliesa, allinkl, alwaysdata, anexia, arvancloud, auroradns, autodns, axelname, azion, azure, azuredns, baiducloud, beget, binarylane, bindman, bluecat, bookmyname, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, conohav3, constellix, corenetworks, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dyndnsfree, dynu, easydns, edgecenter, edgedns, edgeone, efficientip, epik, exec, exoscale, f5xc, freemyip, gandi, gandiv5, gcloud, gcore, gigahostno, glesys, godaddy, googledomains, gravity, hetzner, hostingde, hostinger, hostingnl, hosttech, httpnet, httpreq, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ionoscloud, ipv64, ispconfig, ispconfigddns, iwantmyname, joker, keyhelp, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, metaregistrar, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, neodigit, netcup, netlify, nicmanager, nicru, nifcloud, njalla, nodion, ns1, octenium, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rainyun, rcodezero, regfish, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, selfhostde, servercow, shellrent, simply, sonic, spaceship, stackpath, syse, technitium, tencentcloud, timewebcloud, transip, ultradns, uniteddomains, variomedia, vegadns, vercel, versio, vinyldns, virtualname, vkcloud, volcengine, vscale, vultr, webnames, webnamesca, websupport, wedos, westcn, yandex, yandex360, yandexcloud, zoneedit, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/alwaysdata/alwaysdata.go b/providers/dns/alwaysdata/alwaysdata.go new file mode 100644 index 000000000..b2e0f3957 --- /dev/null +++ b/providers/dns/alwaysdata/alwaysdata.go @@ -0,0 +1,185 @@ +// Package alwaysdata implements a DNS provider for solving the DNS-01 challenge using Alwaysdata. +package alwaysdata + +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/alwaysdata/internal" + "github.com/go-acme/lego/v4/providers/dns/internal/clientdebug" +) + +// Environment variables names. +const ( + envNamespace = "ALWAYSDATA_" + + EnvAPIKey = envNamespace + "API_KEY" + EnvAccount = envNamespace + "ACCOUNT" + + EnvTTL = envNamespace + "TTL" + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" +) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + APIKey string + Account string + + PropagationTimeout time.Duration + PollingInterval time.Duration + TTL int + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 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 Alwaysdata. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey) + if err != nil { + return nil, fmt.Errorf("alwaysdata: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + config.Account = env.GetOrFile(EnvAccount) + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Alwaysdata. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("alwaysdata: the configuration of the DNS provider is nil") + } + + client, err := internal.NewClient(config.APIKey, config.Account) + if err != nil { + return nil, fmt.Errorf("alwaysdata: %w", err) + } + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + client.HTTPClient = clientdebug.Wrap(client.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 { + ctx := context.Background() + + info := dns01.GetChallengeInfo(domain, keyAuth) + + zone, err := d.findZone(ctx, info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("alwaysdata: %w", err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, zone.Name) + if err != nil { + return fmt.Errorf("alwaysdata: %w", err) + } + + record := internal.RecordRequest{ + DomainID: zone.ID, + Name: subDomain, + Type: "TXT", + Value: info.Value, + TTL: d.config.TTL, + Annotation: "lego", + } + + err = d.client.AddRecord(ctx, record) + if err != nil { + return fmt.Errorf("alwaysdata: 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 { + ctx := context.Background() + + info := dns01.GetChallengeInfo(domain, keyAuth) + + zone, err := d.findZone(ctx, info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("alwaysdata: %w", err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, zone.Name) + if err != nil { + return fmt.Errorf("alwaysdata: %w", err) + } + + records, err := d.client.ListRecords(ctx, zone.ID, subDomain) + if err != nil { + return fmt.Errorf("alwaysdata: list records: %w", err) + } + + for _, record := range records { + if record.Type != "TXT" || record.Value != info.Value { + continue + } + + err = d.client.DeleteRecord(ctx, record.ID) + if err != nil { + return fmt.Errorf("alwaysdata: delete TXT record: %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 (d *DNSProvider) findZone(ctx context.Context, fqdn string) (*internal.Domain, error) { + domains, err := d.client.ListDomains(ctx) + if err != nil { + return nil, fmt.Errorf("list domains: %w", err) + } + + for a := range dns01.UnFqdnDomainsSeq(fqdn) { + for _, domain := range domains { + if a == domain.Name { + return &domain, nil + } + } + } + + return nil, errors.New("domain not found") +} diff --git a/providers/dns/alwaysdata/alwaysdata.toml b/providers/dns/alwaysdata/alwaysdata.toml new file mode 100644 index 000000000..96d8d9616 --- /dev/null +++ b/providers/dns/alwaysdata/alwaysdata.toml @@ -0,0 +1,26 @@ +Name = "Alwaysdata" +Description = '''''' +URL = "https://alwaysdata.com/" +Code = "alwaysdata" +Since = "v4.31.0" + +Example = ''' +ALWAYSDATA_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email you@example.com --dns alwaysdata -d '*.example.com' -d example.com run +''' + +[Configuration] + [Configuration.Credentials] + ALWAYSDATA_API_KEY = "API Key" + [Configuration.Additional] + ALWAYSDATA_ACCOUNT = "Account name" + ALWAYSDATA_POLLING_INTERVAL = "Time between DNS propagation check in seconds (Default: 2)" + ALWAYSDATA_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation in seconds (Default: 60)" + ALWAYSDATA_TTL = "The TTL of the TXT record used for the DNS challenge in seconds (Default: 120)" + ALWAYSDATA_HTTP_TIMEOUT = "API request timeout in seconds (Default: 30)" + +[Links] + API = "https://help.alwaysdata.com/en/api/resources/" + APIDocDomains = "https://api.alwaysdata.com/v1/domain/doc/" + APIDocRecords = "https://api.alwaysdata.com/v1/record/doc/" + APIExamples = "https://help.alwaysdata.com/en/api/examples/" diff --git a/providers/dns/alwaysdata/alwaysdata_test.go b/providers/dns/alwaysdata/alwaysdata_test.go new file mode 100644 index 000000000..6084c2ae4 --- /dev/null +++ b/providers/dns/alwaysdata/alwaysdata_test.go @@ -0,0 +1,187 @@ +package alwaysdata + +import ( + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/go-acme/lego/v4/platform/tester/servermock" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvAPIKey, EnvAccount).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvAPIKey: "secret", + }, + }, + { + desc: "success with an account", + envVars: map[string]string{ + EnvAPIKey: "secret", + EnvAccount: "foo", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{}, + expected: "alwaysdata: some credentials information are missing: ALWAYSDATA_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) + require.NotNil(t, p.client) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + apiKey string + account string + expected string + }{ + { + desc: "success", + apiKey: "secret", + }, + { + desc: "success with an account", + apiKey: "secret", + account: "foo", + }, + { + desc: "missing credentials", + expected: "alwaysdata: credentials missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIKey = test.apiKey + config.Account = test.account + + 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) +} + +func mockBuilder() *servermock.Builder[*DNSProvider] { + return servermock.NewBuilder( + func(server *httptest.Server) (*DNSProvider, error) { + config := NewDefaultConfig() + config.APIKey = "secret" + config.HTTPClient = server.Client() + + p, err := NewDNSProviderConfig(config) + if err != nil { + return nil, err + } + + p.client.BaseURL, _ = url.Parse(server.URL) + + return p, nil + }, + servermock.CheckHeader(). + WithJSONHeaders(). + WithBasicAuth("secret", ""), + ) +} + +func TestDNSProvider_Present(t *testing.T) { + provider := mockBuilder(). + Route("GET /domain/", + servermock.ResponseFromInternal("domains.json")). + Route("POST /record/", + servermock.Noop().WithStatusCode(http.StatusCreated), + servermock.CheckRequestJSONBodyFromInternal("record_add-request.json")). + Build(t) + + err := provider.Present("example.com", "abc", "123d==") + require.NoError(t, err) +} + +func TestDNSProvider_CleanUp(t *testing.T) { + provider := mockBuilder(). + Route("GET /domain/", + servermock.ResponseFromInternal("domains.json")). + Route("GET /record/", + servermock.ResponseFromInternal("records.json"), + servermock.CheckQueryParameter().Strict(). + With("domain", "132"). + With("name", "_acme-challenge"), + ). + Route("DELETE /record/789/", + servermock.Noop()). + Build(t) + + err := provider.CleanUp("example.com", "abc", "123d==") + require.NoError(t, err) +} diff --git a/providers/dns/alwaysdata/internal/client.go b/providers/dns/alwaysdata/internal/client.go new file mode 100644 index 000000000..5db11dcd1 --- /dev/null +++ b/providers/dns/alwaysdata/internal/client.go @@ -0,0 +1,177 @@ +package internal + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" + "github.com/go-acme/lego/v4/providers/dns/internal/useragent" +) + +const defaultBaseURL = "https://api.alwaysdata.com/v1" + +// Client the Alwaysdata API client. +type Client struct { + apiKey string + account string + + BaseURL *url.URL + HTTPClient *http.Client +} + +// NewClient creates a new Client. +func NewClient(apiKey, account string) (*Client, error) { + if apiKey == "" { + return nil, errors.New("credentials missing") + } + + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + apiKey: apiKey, + account: account, + BaseURL: baseURL, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + }, nil +} + +func (c *Client) ListDomains(ctx context.Context) ([]Domain, error) { + endpoint := c.BaseURL.JoinPath("domain", "/") + + 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 +} + +func (c *Client) AddRecord(ctx context.Context, record RecordRequest) error { + endpoint := c.BaseURL.JoinPath("record", "/") + + req, err := newJSONRequest(ctx, http.MethodPost, endpoint, record) + if err != nil { + return err + } + + err = c.do(req, nil) + if err != nil { + return err + } + + return nil +} + +func (c *Client) DeleteRecord(ctx context.Context, recordID int64) error { + endpoint := c.BaseURL.JoinPath("record", strconv.FormatInt(recordID, 10), "/") + + req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil) + if err != nil { + return err + } + + return c.do(req, nil) +} + +func (c *Client) ListRecords(ctx context.Context, domainID int64, name string) ([]Record, error) { + endpoint := c.BaseURL.JoinPath("record", "/") + + query := endpoint.Query() + query.Set("domain", strconv.FormatInt(domainID, 10)) + query.Set("name", name) + endpoint.RawQuery = query.Encode() + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var result []Record + + err = c.do(req, &result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (c *Client) do(req *http.Request, result any) error { + useragent.SetHeader(req.Header) + + user := c.apiKey + + if c.account != "" { + user += "account=" + c.account + } + + req.SetBasicAuth(user, "") + + 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/alwaysdata/internal/client_test.go b/providers/dns/alwaysdata/internal/client_test.go new file mode 100644 index 000000000..e6a349662 --- /dev/null +++ b/providers/dns/alwaysdata/internal/client_test.go @@ -0,0 +1,124 @@ +package internal + +import ( + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/go-acme/lego/v4/platform/tester/servermock" + "github.com/go-acme/lego/v4/providers/dns/internal/clientdebug" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func mockBuilder() *servermock.Builder[*Client] { + return servermock.NewBuilder[*Client]( + func(server *httptest.Server) (*Client, error) { + client, err := NewClient("secret", "") + if err != nil { + return nil, err + } + + client.BaseURL, _ = url.Parse(server.URL) + client.HTTPClient = clientdebug.Wrap(server.Client()) + + return client, nil + }, + servermock.CheckHeader(). + WithJSONHeaders(). + WithBasicAuth("secret", ""), + ) +} + +func TestClient_ListDomains(t *testing.T) { + client := mockBuilder(). + Route("GET /domain/", + servermock.ResponseFromFixture("domains.json")). + Build(t) + + result, err := client.ListDomains(t.Context()) + require.NoError(t, err) + + expected := []Domain{ + {ID: 132, Name: "example.com", Annotation: "test"}, + {ID: 133, Name: "example.net", IsInternal: true}, + {ID: 134, Name: "example.org"}, + } + + assert.Equal(t, expected, result) +} + +func TestClient_AddRecord(t *testing.T) { + t.Setenv("LEGO_DEBUG_DNS_API_HTTP_CLIENT", "true") + + client := mockBuilder(). + Route("POST /record/", + servermock.Noop().WithStatusCode(http.StatusCreated), + servermock.CheckRequestJSONBodyFromFixture("record_add-request.json")). + Build(t) + + record := RecordRequest{ + DomainID: 132, + Name: "_acme-challenge", + Type: "TXT", + Value: "ADw2sEd82DUgXcQ9hNBZThJs7zVJkR5v9JeSbAb9mZY", + TTL: 120, + Annotation: "lego", + } + + err := client.AddRecord(t.Context(), record) + require.NoError(t, err) +} + +func TestClient_DeleteRecord(t *testing.T) { + client := mockBuilder(). + Route("DELETE /record/789/", + servermock.Noop()). + Build(t) + + err := client.DeleteRecord(t.Context(), 789) + require.NoError(t, err) +} + +func TestClient_ListRecords(t *testing.T) { + client := mockBuilder(). + Route("GET /record/", + servermock.ResponseFromFixture("records.json"), + servermock.CheckQueryParameter().Strict(). + With("domain", "132"). + With("name", "_acme-challenge"), + ). + Build(t) + + result, err := client.ListRecords(t.Context(), 132, "_acme-challenge") + require.NoError(t, err) + + expected := []Record{ + { + ID: 789, + Domain: &Domain{ + Href: "/v1/domain/132/", + }, + Type: "TXT", + Name: "_acme-challenge", + Value: "ADw2sEd82DUgXcQ9hNBZThJs7zVJkR5v9JeSbAb9mZY", + TTL: 120, + Annotation: "lego", + }, + { + ID: 11619270, + Domain: &Domain{ + Href: "/v1/domain/118935/", + }, + Name: "home", + Type: "A", + Value: "149.202.90.65", + TTL: 300, + IsUserDefined: true, + IsActive: true, + }, + } + + assert.Equal(t, expected, result) +} diff --git a/providers/dns/alwaysdata/internal/fixtures/domains.json b/providers/dns/alwaysdata/internal/fixtures/domains.json new file mode 100644 index 000000000..dc34a948f --- /dev/null +++ b/providers/dns/alwaysdata/internal/fixtures/domains.json @@ -0,0 +1,16 @@ +[ + { + "id": 132, + "name": "example.com", + "annotation": "test" + }, + { + "id": 133, + "name": "example.net", + "is_internal": true + }, + { + "id": 134, + "name": "example.org" + } +] diff --git a/providers/dns/alwaysdata/internal/fixtures/record_add-request.json b/providers/dns/alwaysdata/internal/fixtures/record_add-request.json new file mode 100644 index 000000000..5b6db2646 --- /dev/null +++ b/providers/dns/alwaysdata/internal/fixtures/record_add-request.json @@ -0,0 +1,8 @@ +{ + "domain": 132, + "name": "_acme-challenge", + "type": "TXT", + "value": "ADw2sEd82DUgXcQ9hNBZThJs7zVJkR5v9JeSbAb9mZY", + "ttl": 120, + "annotation": "lego" +} diff --git a/providers/dns/alwaysdata/internal/fixtures/records.json b/providers/dns/alwaysdata/internal/fixtures/records.json new file mode 100644 index 000000000..fa207395a --- /dev/null +++ b/providers/dns/alwaysdata/internal/fixtures/records.json @@ -0,0 +1,28 @@ +[ + { + "id": 789, + "domain": { + "href": "/v1/domain/132/" + }, + "name": "_acme-challenge", + "type": "TXT", + "value": "ADw2sEd82DUgXcQ9hNBZThJs7zVJkR5v9JeSbAb9mZY", + "ttl": 120, + "annotation": "lego" + }, + { + "id": 11619270, + "domain": { + "href": "/v1/domain/118935/" + }, + "type": "A", + "name": "home", + "value": "149.202.90.65", + "priority": null, + "ttl": 300, + "href": "/v1/record/11619270/", + "annotation": "", + "is_user_defined": true, + "is_active": true + } +] diff --git a/providers/dns/alwaysdata/internal/types.go b/providers/dns/alwaysdata/internal/types.go new file mode 100644 index 000000000..b1e66fa5b --- /dev/null +++ b/providers/dns/alwaysdata/internal/types.go @@ -0,0 +1,33 @@ +package internal + +type RecordRequest struct { + ID int64 `json:"id,omitempty"` + DomainID int64 `json:"domain,omitempty"` + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + Value string `json:"value,omitempty"` + TTL int `json:"ttl,omitempty"` + Annotation string `json:"annotation,omitempty"` + IsUserDefined bool `json:"is_user_defined,omitempty"` + IsActive bool `json:"is_active,omitempty"` +} + +type Record struct { + ID int64 `json:"id,omitempty"` + Domain *Domain `json:"domain,omitempty"` + Type string `json:"type,omitempty"` + Name string `json:"name,omitempty"` + Value string `json:"value,omitempty"` + TTL int `json:"ttl,omitempty"` + Annotation string `json:"annotation,omitempty"` + IsUserDefined bool `json:"is_user_defined,omitempty"` + IsActive bool `json:"is_active,omitempty"` +} + +type Domain struct { + ID int64 `json:"id,omitempty"` + Href string `json:"href,omitempty"` + Name string `json:"name,omitempty"` + IsInternal bool `json:"is_internal,omitempty"` + Annotation string `json:"annotation,omitempty"` +} diff --git a/providers/dns/zz_gen_dns_providers.go b/providers/dns/zz_gen_dns_providers.go index 38155e164..c5db54109 100644 --- a/providers/dns/zz_gen_dns_providers.go +++ b/providers/dns/zz_gen_dns_providers.go @@ -11,6 +11,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/alidns" "github.com/go-acme/lego/v4/providers/dns/aliesa" "github.com/go-acme/lego/v4/providers/dns/allinkl" + "github.com/go-acme/lego/v4/providers/dns/alwaysdata" "github.com/go-acme/lego/v4/providers/dns/anexia" "github.com/go-acme/lego/v4/providers/dns/arvancloud" "github.com/go-acme/lego/v4/providers/dns/auroradns" @@ -199,6 +200,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return aliesa.NewDNSProvider() case "allinkl": return allinkl.NewDNSProvider() + case "alwaysdata": + return alwaysdata.NewDNSProvider() case "anexia": return anexia.NewDNSProvider() case "arvancloud":