diff --git a/README.md b/README.md index e6f29e4af0..61335fde91 100644 --- a/README.md +++ b/README.md @@ -106,205 +106,205 @@ If your DNS provider is not supported, please open an [issue](https://github.com ClouDNS CloudXNS (Deprecated) + Combell ConoHa v2 ConoHa v3 Constellix - Core-Networks + Core-Networks CPanel/WHM Czechia DDnss (DynDNS Service) - Derak Cloud + Derak Cloud deSEC.io Designate DNSaaS for Openstack Digital Ocean - DirectAdmin + DirectAdmin DNS Made Easy DNSExit dnsHome.de - DNSimple + DNSimple DNSPod (deprecated) Domain Offensive (do.de) Domeneshop - DreamHost + DreamHost Duck DNS Dyn DynDnsFree.de - Dynu + Dynu EasyDNS EdgeCenter Efficient IP - Epik + Epik EuroDNS Excedo Exoscale - External program + External program F5 XC freemyip.com FusionLayer NameSurfer - 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) - JD Cloud + JD Cloud Joker Joohoi's ACME-DNS KeyHelp - Leaseweb + Leaseweb Liara Lima-City Linode (v4) - Liquid Web + Liquid Web Loopia LuaDNS Mail-in-a-Box - ManageEngine CloudDNS + ManageEngine CloudDNS Manual Metaname Metaregistrar - mijn.host + mijn.host Mittwald myaddr.{tools,dev,io} MyDNS.jp - MythicBeasts + MythicBeasts Name.com Namecheap Namesilo - NearlyFreeSpeech.NET + NearlyFreeSpeech.NET Neodigit Netcup Netlify - Netnod + Netnod Nicmanager NIFCloud Njalla - Nodion + Nodion NS1 Octenium Open Telekom Cloud - Oracle Cloud + Oracle Cloud OVH plesk.com Porkbun - PowerDNS + PowerDNS Rackspace Rain Yun/雨云 RcodeZero - reg.ru + reg.ru Regfish RFC2136 RimuHosting - RU CENTER + RU CENTER Sakura Cloud Scaleway Selectel - Selectel v2 + Selectel v2 SelfHost.(de|eu) Servercow Shellrent - Simply.com + Simply.com Sonic Spaceship Stackpath - Syse + Syse Technitium Tencent Cloud DNS Tencent EdgeOne - Timeweb Cloud + Timeweb Cloud TodayNIC/时代互联 TransIP Ultradns - United-Domains + United-Domains Variomedia VegaDNS Vercel - Versio.[nl|eu|uk] + Versio.[nl|eu|uk] VinylDNS Virtualname VK Cloud - Volcano Engine/火山引擎 + Volcano Engine/火山引擎 Vscale Vultr webnames.ca - webnames.ru + webnames.ru Websupport WEDOS West.cn/西部数码 - Yandex 360 + Yandex 360 Yandex Cloud Yandex PDD Zone.ee - ZoneEdit + ZoneEdit Zonomi - diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 9cdc68d94f..53d9c895cc 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -44,6 +44,7 @@ func allDNSCodes() string { "cloudru", "cloudxns", "com35", + "combell", "conoha", "conohav3", "constellix", @@ -919,6 +920,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/com35`) + case "combell": + // generated from: providers/dns/combell/combell.toml + ew.writeln(`Configuration for Combell.`) + ew.writeln(`Code: 'combell'`) + ew.writeln(`Since: 'v4.34.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "COMBELL_API_KEY": The API key`) + ew.writeln(` - "COMBELL_API_SECRET": The API secret`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "COMBELL_HTTP_TIMEOUT": API request timeout in seconds (Default: 30)`) + ew.writeln(` - "COMBELL_POLLING_INTERVAL": Time between DNS propagation check in seconds (Default: 2)`) + ew.writeln(` - "COMBELL_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation in seconds (Default: 60)`) + ew.writeln(` - "COMBELL_TTL": The TTL of the TXT record used for the DNS challenge in seconds (Default: 3600)`) + + ew.writeln() + ew.writeln(`More information: https://go-acme.github.io/lego/dns/combell`) + case "conoha": // generated from: providers/dns/conoha/conoha.toml ew.writeln(`Configuration for ConoHa v2.`) diff --git a/docs/content/dns/zz_gen_combell.md b/docs/content/dns/zz_gen_combell.md new file mode 100644 index 0000000000..792735e216 --- /dev/null +++ b/docs/content/dns/zz_gen_combell.md @@ -0,0 +1,69 @@ +--- +title: "Combell" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: combell +dnsprovider: + since: "v4.34.0" + code: "combell" + url: "https://www.combell.com/" +--- + + + + + + +Configuration for [Combell](https://www.combell.com/). + + + + +- Code: `combell` +- Since: v4.34.0 + + +Here is an example bash command using the Combell provider: + +```bash +COMBELL_API_KEY=xxxxxxxxxxxxxxxxxxxxx \ +COMBELL_API_SECRET=yyyyyyyyyyyyyyyyyyyy \ +lego --dns combell -d '*.example.com' -d example.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `COMBELL_API_KEY` | The API key | +| `COMBELL_API_SECRET` | The API secret | + +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 | +|--------------------------------|-------------| +| `COMBELL_HTTP_TIMEOUT` | API request timeout in seconds (Default: 30) | +| `COMBELL_POLLING_INTERVAL` | Time between DNS propagation check in seconds (Default: 2) | +| `COMBELL_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation in seconds (Default: 60) | +| `COMBELL_TTL` | The TTL of the TXT record used for the DNS challenge in seconds (Default: 3600) | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here]({{% ref "dns#configuration-and-credentials" %}}). + + + + +## More information + +- [API documentation](https://api.combell.com/v2/documentation) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index 9f26366f38..c6dfb79d1f 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, alwaysdata, anexia, artfiles, arvancloud, auroradns, autodns, axelname, azion, azure, azuredns, baiducloud, beget, binarylane, bindman, bluecat, bluecatv2, bookmyname, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, com35, conoha, conohav3, constellix, corenetworks, cpanel, czechia, ddnss, derak, desec, designate, digitalocean, directadmin, dnsexit, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dyndnsfree, dynu, easydns, edgecenter, edgedns, edgeone, efficientip, epik, eurodns, excedo, 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, jdcloud, joker, keyhelp, leaseweb, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, metaregistrar, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, namesurfer, nearlyfreespeech, neodigit, netcup, netlify, netnod, nicmanager, nicru, nifcloud, njalla, nodion, ns1, octenium, onecloudru, 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, todaynic, 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, artfiles, arvancloud, auroradns, autodns, axelname, azion, azure, azuredns, baiducloud, beget, binarylane, bindman, bluecat, bluecatv2, bookmyname, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, com35, combell, conoha, conohav3, constellix, corenetworks, cpanel, czechia, ddnss, derak, desec, designate, digitalocean, directadmin, dnsexit, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dyndnsfree, dynu, easydns, edgecenter, edgedns, edgeone, efficientip, epik, eurodns, excedo, 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, jdcloud, joker, keyhelp, leaseweb, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, metaregistrar, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, namesurfer, nearlyfreespeech, neodigit, netcup, netlify, netnod, nicmanager, nicru, nifcloud, njalla, nodion, ns1, octenium, onecloudru, 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, todaynic, 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/combell/combell.go b/providers/dns/combell/combell.go new file mode 100644 index 0000000000..6690918c03 --- /dev/null +++ b/providers/dns/combell/combell.go @@ -0,0 +1,169 @@ +// Package combell implements a DNS provider for solving the DNS-01 challenge using Combell DNS. +package combell + +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/combell/internal" + "github.com/go-acme/lego/v4/providers/dns/internal/clientdebug" +) + +const ( + minTTL = 60 + maxTTL = 8640 +) + +// Environment variables names. +const ( + envNamespace = "COMBELL_" + + EnvAPIKey = envNamespace + "API_KEY" + EnvAPISecret = envNamespace + "API_SECRET" + + 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 + APISecret string + TTL int + PropagationTimeout time.Duration + PollingInterval time.Duration + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, 3600), + 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 Combell DNS. +// Credentials must be passed in the environment variables: +// COMBELL_API_KEY, COMBELL_API_SECRET. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey, EnvAPISecret) + if err != nil { + return nil, fmt.Errorf("combell: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + config.APISecret = values[EnvAPISecret] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Combell DNS. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("combell: the configuration of the DNS provider is nil") + } + + if config.APIKey == "" || config.APISecret == "" { + return nil, errors.New("combell: some credentials information are missing") + } + + if config.TTL < minTTL { + return nil, fmt.Errorf("combell: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) + } + + if config.TTL > maxTTL { + return nil, fmt.Errorf("combell: invalid TTL, TTL (%d) must be lower than %d", config.TTL, maxTTL) + } + + httpClient := &http.Client{Timeout: 30 * time.Second} + + if config.HTTPClient != nil { + httpClient = config.HTTPClient + } + + client := internal.NewClient(config.APIKey, config.APISecret, clientdebug.Wrap(httpClient)) + + return &DNSProvider{config: config, client: client}, nil +} + +// Timeout returns the timeout and interval to use when checking for DNS propagation. +// Adjusting here to cope with spikes in propagation times. +func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { + return d.config.PropagationTimeout, d.config.PollingInterval +} + +// Present creates a TXT record to fulfill the dns-01 challenge. +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("combell: could not find zone for domain %q (%s): %w", domain, info.EffectiveFQDN, err) + } + + record := internal.Record{ + Type: "TXT", + RecordName: dns01.UnFqdn(strings.TrimSuffix(info.EffectiveFQDN, authZone)), + Content: info.Value, + TTL: d.config.TTL, + } + + err = d.client.CreateRecord(context.Background(), authZone, record) + if err != nil { + return fmt.Errorf("combell: create 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) + + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("combell: could not find zone for domain %q (%s): %w", domain, info.EffectiveFQDN, err) + } + + request := &internal.GetRecordsRequest{ + Type: "TXT", + RecordName: dns01.UnFqdn(strings.TrimSuffix(info.EffectiveFQDN, authZone)), + } + + records, err := d.client.GetRecords(ctx, authZone, request) + if err != nil { + return fmt.Errorf("combell: get records: %w", err) + } + + for _, record := range records { + if record.Content == info.Value { + err = d.client.DeleteRecord(ctx, authZone, record.ID) + if err != nil { + return fmt.Errorf("combell: delete record: %w", err) + } + } + } + + return nil +} diff --git a/providers/dns/combell/combell.toml b/providers/dns/combell/combell.toml new file mode 100644 index 0000000000..810c3b5d0d --- /dev/null +++ b/providers/dns/combell/combell.toml @@ -0,0 +1,24 @@ +Name = "Combell" +Description = '''''' +URL = "https://www.combell.com/" +Code = "combell" +Since = "v4.34.0" + +Example = ''' +COMBELL_API_KEY=xxxxxxxxxxxxxxxxxxxxx \ +COMBELL_API_SECRET=yyyyyyyyyyyyyyyyyyyy \ +lego --dns combell -d '*.example.com' -d example.com run +''' + +[Configuration] + [Configuration.Credentials] + COMBELL_API_KEY = "The API key" + COMBELL_API_SECRET = "The API secret" + [Configuration.Additional] + COMBELL_POLLING_INTERVAL = "Time between DNS propagation check in seconds (Default: 2)" + COMBELL_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation in seconds (Default: 60)" + COMBELL_TTL = "The TTL of the TXT record used for the DNS challenge in seconds (Default: 3600)" + COMBELL_HTTP_TIMEOUT = "API request timeout in seconds (Default: 30)" + +[Links] + API = "https://api.combell.com/v2/documentation" diff --git a/providers/dns/combell/combell_test.go b/providers/dns/combell/combell_test.go new file mode 100644 index 0000000000..f3674de220 --- /dev/null +++ b/providers/dns/combell/combell_test.go @@ -0,0 +1,116 @@ +package combell + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvAPIKey, EnvAPISecret).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvAPIKey: "key", + EnvAPISecret: "secret", + }, + }, + { + desc: "missing API key", + envVars: map[string]string{ + EnvAPISecret: "secret", + }, + expected: "combell: some credentials information are missing: COMBELL_API_KEY", + }, + { + desc: "missing API secret", + envVars: map[string]string{ + EnvAPIKey: "key", + }, + expected: "combell: some credentials information are missing: COMBELL_API_SECRET", + }, + { + desc: "missing credentials", + envVars: map[string]string{}, + expected: "combell: some credentials information are missing: COMBELL_API_KEY,COMBELL_API_SECRET", + }, + } + + 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 + apiSecret string + expected string + }{ + { + desc: "success", + apiKey: "key", + apiSecret: "secret", + }, + { + desc: "missing API key", + apiSecret: "secret", + expected: "combell: some credentials information are missing", + }, + { + desc: "missing API secret", + apiKey: "key", + expected: "combell: some credentials information are missing", + }, + { + desc: "missing credentials", + expected: "combell: some credentials information are missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIKey = test.apiKey + config.APISecret = test.apiSecret + + 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) + } + }) + } +} diff --git a/providers/dns/combell/internal/client.go b/providers/dns/combell/internal/client.go new file mode 100644 index 0000000000..473883105f --- /dev/null +++ b/providers/dns/combell/internal/client.go @@ -0,0 +1,242 @@ +package internal + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/md5" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" + "github.com/go-acme/lego/v4/providers/dns/internal/useragent" + querystring "github.com/google/go-querystring/query" + "github.com/hashicorp/go-retryablehttp" +) + +const defaultBaseURL = "https://api.combell.com/v2" + +// Client a Combell DNS API client. +type Client struct { + apiKey string + apiSecret string + + nonce *Nonce + + httpClient *http.Client + BaseURL *url.URL +} + +// NewClient creates a new Client. +func NewClient(apiKey, apiSecret string, httpClient *http.Client) *Client { + baseURL, _ := url.Parse(defaultBaseURL) + + retryClient := retryablehttp.NewClient() + + retryClient.RetryMax = 5 + if httpClient != nil { + retryClient.HTTPClient = httpClient + } + + retryClient.Logger = log.Default() + + return &Client{ + apiKey: apiKey, + apiSecret: apiSecret, + httpClient: retryClient.StandardClient(), + BaseURL: baseURL, + nonce: NewNonce(), + } +} + +// GetRecords gets the records of a domain. +// https://api.combell.com/v2/documentation#tag/DNS-records/paths/~1dns~1{domainName}~1records/get +func (c Client) GetRecords(ctx context.Context, domainName string, request *GetRecordsRequest) ([]Record, error) { + endpoint := c.BaseURL.JoinPath("dns", domainName, "records") + + if request != nil { + values, err := querystring.Values(request) + if err != nil { + return nil, err + } + + endpoint.RawQuery = values.Encode() + } + + req, err := c.newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, fmt.Errorf("create request: %w", err) + } + + var results []Record + + err = c.do(req, http.StatusOK, &results) + if err != nil { + return nil, err + } + + return results, nil +} + +// CreateRecord creates a record. +// https://api.combell.com/v2/documentation#tag/DNS-records/paths/~1dns~1{domainName}~1records/post +func (c Client) CreateRecord(ctx context.Context, domainName string, record Record) error { + endpoint := c.BaseURL.JoinPath("dns", domainName, "records") + + req, err := c.newJSONRequest(ctx, http.MethodPost, endpoint, record) + if err != nil { + return fmt.Errorf("create request: %w", err) + } + + // TODO(ldez) the "Location" header contains a reference to the created record. + + return c.do(req, http.StatusCreated, nil) +} + +// GetRecord gets a specific record. +// https://api.combell.com/v2/documentation#tag/DNS-records/paths/~1dns~1{domainName}~1records~1{recordId}/get +func (c Client) GetRecord(ctx context.Context, domainName, recordID string) (*Record, error) { + endpoint := c.BaseURL.JoinPath("dns", domainName, "records", recordID) + + req, err := c.newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, fmt.Errorf("create request: %w", err) + } + + var result Record + + err = c.do(req, http.StatusOK, &result) + if err != nil { + return nil, err + } + + return &result, nil +} + +// DeleteRecord deletes a record. +// https://api.combell.com/v2/documentation#tag/DNS-records/paths/~1dns~1{domainName}~1records~1{recordId}/delete +func (c Client) DeleteRecord(ctx context.Context, domainName, recordID string) error { + endpoint := c.BaseURL.JoinPath("dns", domainName, "records", recordID) + + req, err := c.newJSONRequest(ctx, http.MethodDelete, endpoint, nil) + if err != nil { + return err + } + + return c.do(req, http.StatusNoContent, nil) +} + +func (c Client) do(req *http.Request, expectedStatus int, result any) error { + useragent.SetHeader(req.Header) + + resp, err := c.httpClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != expectedStatus { + return parseError(req, resp) + } + + if result == nil { + return nil + } + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return errutils.NewReadResponseError(req, resp.StatusCode, err) + } + + err = json.Unmarshal(raw, result) + if err != nil { + return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err) + } + + return nil +} + +func (c Client) newJSONRequest(ctx context.Context, method string, endpoint *url.URL, payload any) (*http.Request, error) { + buf := new(bytes.Buffer) + + var body []byte + + if payload != nil { + var err error + + body, err = json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("failed to create request JSON body: %w", err) + } + + buf = bytes.NewBuffer(body) + } + + 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") + } + + sign, err := c.sign(req, body) + if err != nil { + return nil, fmt.Errorf("request signature: %w", err) + } + + req.Header.Set("Authorization", sign) + + return req, nil +} + +func (c Client) sign(req *http.Request, body []byte) (string, error) { + unix := time.Now().Unix() + nonce := c.nonce.Generate(10) + + var encodedBody string + + if len(body) > 0 { + sum := md5.Sum(body) + encodedBody = base64.StdEncoding.EncodeToString(sum[:]) + } + + h := hmac.New(sha256.New, []byte(c.apiSecret)) + + _, err := h.Write([]byte( + c.apiKey + strings.ToLower(req.Method) + url.QueryEscape(strings.ToLower(req.URL.RequestURI())) + strconv.FormatInt(unix, 10) + nonce + encodedBody), + ) + if err != nil { + return "", err + } + + hSign := base64.StdEncoding.EncodeToString(h.Sum(nil)) + + return fmt.Sprintf("hmac %s:%s:%s:%d", c.apiKey, hSign, nonce, unix), nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + var response APIError + + err := json.Unmarshal(raw, &response) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return fmt.Errorf("[status code %d] %w", resp.StatusCode, response) +} diff --git a/providers/dns/combell/internal/client_test.go b/providers/dns/combell/internal/client_test.go new file mode 100644 index 0000000000..4641c2b2ae --- /dev/null +++ b/providers/dns/combell/internal/client_test.go @@ -0,0 +1,121 @@ +package internal + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/go-acme/lego/v4/platform/tester/servermock" + "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 := NewClient("key", "secret", server.Client()) + + client.BaseURL, _ = url.Parse(server.URL) + + return client, nil + }, + servermock.CheckHeader(). + WithJSONHeaders(). + WithRegexp("Authorization", `hmac key:.+:.+:\d+`), + ) +} + +func TestClient_GetRecords(t *testing.T) { + client := mockBuilder(). + Route("GET /dns/example.com/records", + servermock.ResponseFromFixture("GetRecords.json")). + Build(t) + + records, err := client.GetRecords(context.Background(), "example.com", nil) + require.NoError(t, err) + + expected := []Record{ + { + ID: "string", + Type: "string", + RecordName: "string", + Content: "string", + TTL: 3600, + Priority: 10, + Service: "string", + Weight: 0, + Target: "string", + Protocol: "TCP", + Port: 0, + }, + } + assert.Equal(t, expected, records) +} + +func TestClient_GetRecord(t *testing.T) { + client := mockBuilder(). + Route("GET /dns/example.com/records/123", + servermock.ResponseFromFixture("GetRecord.json")). + Build(t) + + record, err := client.GetRecord(context.Background(), "example.com", "123") + require.NoError(t, err) + + expected := &Record{ + ID: "string", + Type: "string", + RecordName: "string", + Content: "string", + TTL: 3600, + Priority: 10, + Service: "string", + Weight: 0, + Target: "string", + Protocol: "TCP", + Port: 0, + } + assert.Equal(t, expected, record) +} + +func TestClient_DeleteRecord(t *testing.T) { + client := mockBuilder(). + Route("DELETE /dns/example.com/records/123", + servermock.Noop(). + WithStatusCode(http.StatusNoContent)). + Build(t) + + err := client.DeleteRecord(context.Background(), "example.com", "123") + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client := mockBuilder(). + Route("DELETE /dns/example.com/records/123", + servermock.ResponseFromFixture("error.json"). + WithStatusCode(http.StatusUnauthorized)). + Build(t) + + err := client.DeleteRecord(context.Background(), "example.com", "123") + require.Error(t, err) +} + +func TestClient_sign(t *testing.T) { + client := NewClient("my_key", "my_secret", nil) + + endpoint, err := url.Parse("https://localhost/v2/domains") + require.NoError(t, err) + + query := endpoint.Query() + query.Set("skip", "0") + query.Set("take", "10") + endpoint.RawQuery = query.Encode() + + req := httptest.NewRequest(http.MethodGet, endpoint.String(), nil) + + sign, err := client.sign(req, nil) + require.NoError(t, err) + + assert.Regexp(t, `hmac my_key:[^:]+:[a-zA-Z]{10}:\d{10}`, sign) +} diff --git a/providers/dns/combell/internal/fixtures/GetRecord.json b/providers/dns/combell/internal/fixtures/GetRecord.json new file mode 100644 index 0000000000..901929c51c --- /dev/null +++ b/providers/dns/combell/internal/fixtures/GetRecord.json @@ -0,0 +1,13 @@ +{ + "id": "string", + "type": "string", + "record_name": "string", + "ttl": 3600, + "content": "string", + "priority": 10, + "service": "string", + "weight": 0, + "target": "string", + "protocol": "TCP", + "port": 0 +} diff --git a/providers/dns/combell/internal/fixtures/GetRecords.json b/providers/dns/combell/internal/fixtures/GetRecords.json new file mode 100644 index 0000000000..1d8c30529b --- /dev/null +++ b/providers/dns/combell/internal/fixtures/GetRecords.json @@ -0,0 +1,15 @@ +[ + { + "id": "string", + "type": "string", + "record_name": "string", + "ttl": 3600, + "content": "string", + "priority": 10, + "service": "string", + "weight": 0, + "target": "string", + "protocol": "TCP", + "port": 0 + } +] diff --git a/providers/dns/combell/internal/fixtures/error.json b/providers/dns/combell/internal/fixtures/error.json new file mode 100644 index 0000000000..41dad2f467 --- /dev/null +++ b/providers/dns/combell/internal/fixtures/error.json @@ -0,0 +1,4 @@ +{ + "error_code": "auth_authorization_header_invalid_format", + "error_text": "The authorization header is in an invalid format." +} diff --git a/providers/dns/combell/internal/nonce.go b/providers/dns/combell/internal/nonce.go new file mode 100644 index 0000000000..89db745090 --- /dev/null +++ b/providers/dns/combell/internal/nonce.go @@ -0,0 +1,47 @@ +package internal + +import ( + "math/rand" + "strings" + "time" +) + +const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + +const ( + letterIndexBits = 6 // 6 bits to represent a letter index + letterIndexMask = 1<= 0; { + if remain == 0 { + cache, remain = c.src.Int63(), letterIndexMax + } + + if idx := int(cache & letterIndexMask); idx < len(letterBytes) { + sb.WriteByte(letterBytes[idx]) + + i-- + } + + cache >>= letterIndexBits + remain-- + } + + return sb.String() +} diff --git a/providers/dns/combell/internal/nonce_test.go b/providers/dns/combell/internal/nonce_test.go new file mode 100644 index 0000000000..25bd039ac7 --- /dev/null +++ b/providers/dns/combell/internal/nonce_test.go @@ -0,0 +1,39 @@ +package internal + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNonce_Generate(t *testing.T) { + nonce := NewNonce() + + testCases := []struct { + desc string + length int + }{ + { + desc: "one letter", + length: 1, + }, + { + desc: "10 letters", + length: 10, + }, + { + desc: "100 letters", + length: 100, + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + result := nonce.Generate(test.length) + assert.Len(t, result, test.length) + assert.Regexp(t, `[a-zA-Z]+`, result) + }) + } +} diff --git a/providers/dns/combell/internal/types.go b/providers/dns/combell/internal/types.go new file mode 100644 index 0000000000..bd57deed68 --- /dev/null +++ b/providers/dns/combell/internal/types.go @@ -0,0 +1,34 @@ +package internal + +import "fmt" + +type Record struct { + ID string `json:"id"` + Type string `json:"type,omitempty"` + RecordName string `json:"record_name,omitempty"` + Content string `json:"content,omitempty"` + TTL int `json:"ttl,omitempty"` + Priority int `json:"priority,omitempty"` + Service string `json:"service,omitempty"` + Weight int `json:"weight,omitempty"` + Target string `json:"target,omitempty"` + Protocol string `json:"protocol,omitempty"` + Port int `json:"port,omitempty"` +} + +type GetRecordsRequest struct { + Skip int `url:"skip,omitempty"` + Take int `url:"take,omitempty"` + Type string `url:"type,omitempty"` + RecordName string `url:"record_name,omitempty"` + Service string `url:"service,omitempty"` +} + +type APIError struct { + ErrorCode string `json:"error_code"` + ErrorText string `json:"error_text"` +} + +func (a APIError) Error() string { + return fmt.Sprintf("%s: %s", a.ErrorCode, a.ErrorText) +} diff --git a/providers/dns/zz_gen_dns_providers.go b/providers/dns/zz_gen_dns_providers.go index 3a86fa7df0..97609130c6 100644 --- a/providers/dns/zz_gen_dns_providers.go +++ b/providers/dns/zz_gen_dns_providers.go @@ -38,6 +38,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/cloudru" "github.com/go-acme/lego/v4/providers/dns/cloudxns" "github.com/go-acme/lego/v4/providers/dns/com35" + "github.com/go-acme/lego/v4/providers/dns/combell" "github.com/go-acme/lego/v4/providers/dns/conoha" "github.com/go-acme/lego/v4/providers/dns/conohav3" "github.com/go-acme/lego/v4/providers/dns/constellix" @@ -268,6 +269,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return cloudxns.NewDNSProvider() case "com35": return com35.NewDNSProvider() + case "combell": + return combell.NewDNSProvider() case "conoha": return conoha.NewDNSProvider() case "conohav3":