diff --git a/README.md b/README.md index a430446c32..0e4cf617c4 100644 --- a/README.md +++ b/README.md @@ -182,55 +182,55 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). PowerDNS Rackspace + Rain Yun/雨云 RcodeZero reg.ru Regfish - RFC2136 + RFC2136 RimuHosting Sakura Cloud Scaleway - Selectel + Selectel Selectel v2 SelfHost.(de|eu) Servercow - Shellrent + Shellrent Simply.com Sonic Stackpath - Technitium + Technitium Tencent Cloud DNS Timeweb Cloud TransIP - UKFast SafeDNS + UKFast SafeDNS Ultradns Variomedia VegaDNS - Vercel + Vercel Versio.[nl|eu|uk] VinylDNS VK Cloud - Volcano Engine/火山引擎 + Volcano Engine/火山引擎 Vscale Vultr Webnames - Websupport + Websupport WEDOS Yandex 360 Yandex Cloud - Yandex PDD + Yandex PDD Zone.ee Zonomi - diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 52eb0f11f7..1a9d0fa557 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -115,6 +115,7 @@ func allDNSCodes() string { "plesk", "porkbun", "rackspace", + "rainyun", "rcodezero", "regfish", "regru", @@ -2357,6 +2358,26 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/rackspace`) + case "rainyun": + // generated from: providers/dns/rainyun/rainyun.toml + ew.writeln(`Configuration for Rain Yun/雨云.`) + ew.writeln(`Code: 'rainyun'`) + ew.writeln(`Since: 'v4.21.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "RAINYUN_API_KEY": API key`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "RAINYUN_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "RAINYUN_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "RAINYUN_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "RAINYUN_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/rainyun`) + case "rcodezero": // generated from: providers/dns/rcodezero/rcodezero.toml ew.writeln(`Configuration for RcodeZero.`) diff --git a/docs/content/dns/zz_gen_rainyun.md b/docs/content/dns/zz_gen_rainyun.md new file mode 100644 index 0000000000..c0ff646b85 --- /dev/null +++ b/docs/content/dns/zz_gen_rainyun.md @@ -0,0 +1,67 @@ +--- +title: "Rain Yun/雨云" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: rainyun +dnsprovider: + since: "v4.21.0" + code: "rainyun" + url: "https://www.rainyun.com" +--- + + + + + + +Configuration for [Rain Yun/雨云](https://www.rainyun.com). + + + + +- Code: `rainyun` +- Since: v4.21.0 + + +Here is an example bash command using the Rain Yun/雨云 provider: + +```bash +RAINYUN_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email you@example.com --dns rainyun -d '*.example.com' -d example.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `RAINYUN_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 | +|--------------------------------|-------------| +| `RAINYUN_HTTP_TIMEOUT` | API request timeout | +| `RAINYUN_POLLING_INTERVAL` | Time between DNS propagation check | +| `RAINYUN_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `RAINYUN_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://www.apifox.cn/apidoc/shared-a4595cc8-44c5-4678-a2a3-eed7738dab03/api-151416609) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index ad95fe40df..dd086b795d 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -142,7 +142,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, manual, metaname, mijnhost, mittwald, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, 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, 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, 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, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/rainyun/internal/client.go b/providers/dns/rainyun/internal/client.go new file mode 100644 index 0000000000..3d99bd9be9 --- /dev/null +++ b/providers/dns/rainyun/internal/client.go @@ -0,0 +1,182 @@ +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" + querystring "github.com/google/go-querystring/query" +) + +const defaultBaseURL = "https://api.v2.rainyun.com/product/" + +// Client the Rain Yun API client. +type Client struct { + apiKey string + + baseURL *url.URL + HTTPClient *http.Client +} + +// NewClient creates a new Client. +func NewClient(apiKey string) (*Client, error) { + if apiKey == "" { + return nil, errors.New("credentials missing") + } + + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + apiKey: apiKey, + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + }, nil +} + +func (c *Client) AddRecord(ctx context.Context, domainID int, record Record) error { + endpoint := c.baseURL.JoinPath("domain", strconv.Itoa(domainID), "dns") + + req, err := newJSONRequest(ctx, http.MethodPost, endpoint, record) + if err != nil { + return err + } + + return c.do(req, nil) +} + +func (c *Client) DeleteRecord(ctx context.Context, domainID, recordID int) error { + endpoint := c.baseURL.JoinPath("domain", strconv.Itoa(domainID), "dns") + + values, err := querystring.Values(Record{ID: recordID}) + if err != nil { + return err + } + + endpoint.RawQuery = values.Encode() + + 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 int) ([]Record, error) { + endpoint := c.baseURL.JoinPath("domain", strconv.Itoa(domainID), "dns") + + query := endpoint.Query() + query.Set("limit", "100") + query.Set("page_no", "1") + endpoint.RawQuery = query.Encode() + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var recordData APIResponse[Record] + err = c.do(req, &recordData) + if err != nil { + return nil, err + } + + return recordData.Data.Records, nil +} + +func (c *Client) ListDomains(ctx context.Context) ([]Domain, error) { + endpoint := c.baseURL.JoinPath("domain") + + query := endpoint.Query() + query.Set("options", `{"columnFilters":{"domains.Domain":""},"sort":[],"page":1,"perPage":100}`) + endpoint.RawQuery = query.Encode() + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var domainData APIResponse[Domain] + + err = c.do(req, &domainData) + if err != nil { + return nil, err + } + + return domainData.Data.Records, nil +} + +func (c *Client) do(req *http.Request, result any) error { + req.Header.Add("x-api-key", c.apiKey) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode/100 != 2 { + return parseError(req, resp) + } + + if result == nil { + return nil + } + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return errutils.NewReadResponseError(req, resp.StatusCode, err) + } + + err = json.Unmarshal(raw, result) + if err != nil { + return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err) + } + + return nil +} + +func newJSONRequest(ctx context.Context, method string, endpoint *url.URL, payload any) (*http.Request, error) { + buf := new(bytes.Buffer) + + if payload != nil { + err := json.NewEncoder(buf).Encode(payload) + if err != nil { + return nil, fmt.Errorf("failed to create request JSON body: %w", err) + } + } + + req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + + return req, nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + var errAPI APIError + err := json.Unmarshal(raw, &errAPI) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return &errAPI +} diff --git a/providers/dns/rainyun/internal/client_test.go b/providers/dns/rainyun/internal/client_test.go new file mode 100644 index 0000000000..ee6477c0ce --- /dev/null +++ b/providers/dns/rainyun/internal/client_test.go @@ -0,0 +1,161 @@ +package internal + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T, pattern string, 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 + } + }) + + client, err := NewClient("secret") + require.NoError(t, err) + + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client +} + +func TestClient_ListDomains(t *testing.T) { + client := setupTest(t, "GET /domain", http.StatusOK, "domains.json") + + domains, err := client.ListDomains(context.Background()) + require.NoError(t, err) + + expected := []Domain{ + {ID: 1, Domain: "example.com"}, + {ID: 2, Domain: "example.org"}, + } + + assert.Equal(t, expected, domains) +} + +func TestClient_ListDomains_error(t *testing.T) { + client := setupTest(t, "GET /domain", http.StatusForbidden, "error.json") + + _, err := client.ListDomains(context.Background()) + require.Error(t, err) + + assert.EqualError(t, err, "30039: 密钥认证错误或已失效") +} + +func TestClient_ListRecords(t *testing.T) { + client := setupTest(t, "GET /domain/123/dns", http.StatusOK, "records.json") + + records, err := client.ListRecords(context.Background(), 123) + require.NoError(t, err) + + expected := []Record{ + { + ID: 1, + Host: "_acme-challenge.foo.example.com", + Line: "DEFAULT", + TTL: 120, + Type: "TXT", + Value: "foo", + }, + { + ID: 2, + Host: "_acme-challenge.bar.example.com", + Line: "DEFAULT", + TTL: 300, + Type: "TXT", + Value: "bar", + }, + } + + assert.Equal(t, expected, records) +} + +func TestClient_ListRecords_error(t *testing.T) { + client := setupTest(t, "GET /domain/123/dns", http.StatusForbidden, "error.json") + + _, err := client.ListRecords(context.Background(), 123) + require.Error(t, err) + + assert.EqualError(t, err, "30039: 密钥认证错误或已失效") +} + +func TestClient_AddRecord(t *testing.T) { + client := setupTest(t, "POST /domain/123/dns", http.StatusOK, "") + + record := Record{ + Host: "_acme-challenge.foo.example.com", + Line: "DEFAULT", + TTL: 120, + Type: "TXT", + Value: "foo", + } + + err := client.AddRecord(context.Background(), 123, record) + require.NoError(t, err) +} + +func TestClient_AddRecord_error(t *testing.T) { + client := setupTest(t, "POST /domain/123/dns", http.StatusForbidden, "error.json") + + record := Record{ + Host: "_acme-challenge.foo.example.com", + Line: "DEFAULT", + TTL: 120, + Type: "TXT", + Value: "foo", + } + + err := client.AddRecord(context.Background(), 123, record) + require.Error(t, err) + + assert.EqualError(t, err, "30039: 密钥认证错误或已失效") +} + +func TestClient_DeleteRecord(t *testing.T) { + client := setupTest(t, "DELETE /domain/123/dns", http.StatusOK, "") + + err := client.DeleteRecord(context.Background(), 123, 456) + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client := setupTest(t, "DELETE /domain/123/dns", http.StatusForbidden, "error.json") + + err := client.DeleteRecord(context.Background(), 123, 456) + require.Error(t, err) + + assert.EqualError(t, err, "30039: 密钥认证错误或已失效") +} diff --git a/providers/dns/rainyun/internal/fixtures/domains.json b/providers/dns/rainyun/internal/fixtures/domains.json new file mode 100644 index 0000000000..930e4e189d --- /dev/null +++ b/providers/dns/rainyun/internal/fixtures/domains.json @@ -0,0 +1,16 @@ +{ + "code": 0, + "data": { + "TotalRecords": 2, + "Records": [ + { + "id": 1, + "domain": "example.com" + }, + { + "id": 2, + "domain": "example.org" + } + ] + } +} diff --git a/providers/dns/rainyun/internal/fixtures/error.json b/providers/dns/rainyun/internal/fixtures/error.json new file mode 100644 index 0000000000..31e9f71388 --- /dev/null +++ b/providers/dns/rainyun/internal/fixtures/error.json @@ -0,0 +1,4 @@ +{ + "code": 30039, + "message": "密钥认证错误或已失效" +} diff --git a/providers/dns/rainyun/internal/fixtures/records.json b/providers/dns/rainyun/internal/fixtures/records.json new file mode 100644 index 0000000000..d24c0c9ec7 --- /dev/null +++ b/providers/dns/rainyun/internal/fixtures/records.json @@ -0,0 +1,24 @@ +{ + "code": 0, + "data": { + "TotalRecords": 2, + "Records": [ + { + "record_id": 1, + "host": "_acme-challenge.foo.example.com", + "type": "TXT", + "TTL": 120, + "value": "foo", + "line": "DEFAULT" + }, + { + "record_id": 2, + "host": "_acme-challenge.bar.example.com", + "type": "TXT", + "TTL": 300, + "value": "bar", + "line": "DEFAULT" + } + ] + } +} diff --git a/providers/dns/rainyun/internal/types.go b/providers/dns/rainyun/internal/types.go new file mode 100644 index 0000000000..8ce5591128 --- /dev/null +++ b/providers/dns/rainyun/internal/types.go @@ -0,0 +1,37 @@ +package internal + +import "fmt" + +type APIError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func (a *APIError) Error() string { + return fmt.Sprintf("%d: %s", a.Code, a.Message) +} + +type Record struct { + ID int `json:"record_id,omitempty" url:"record_id,omitempty"` + Host string `json:"host,omitempty" url:"host,omitempty"` + Priority int `json:"level,omitempty" url:"level,omitempty"` + Line string `json:"line,omitempty" url:"line,omitempty"` + TTL int `json:"ttl,omitempty" url:"ttl,omitempty"` + Type string `json:"type,omitempty" url:"type,omitempty"` + Value string `json:"value,omitempty" url:"value,omitempty"` +} + +type Domain struct { + ID int `json:"id,omitempty"` + Domain string `json:"domain,omitempty"` +} + +type APIResponse[T any] struct { + Code int `json:"code"` + Data *Data[T] `json:"data"` +} + +type Data[T any] struct { + TotalRecords int `json:"TotalRecords"` + Records []T `json:"Records"` +} diff --git a/providers/dns/rainyun/rainyun.go b/providers/dns/rainyun/rainyun.go new file mode 100644 index 0000000000..43ef9cb1b6 --- /dev/null +++ b/providers/dns/rainyun/rainyun.go @@ -0,0 +1,197 @@ +// Package rainyun implements a DNS provider for solving the DNS-01 challenge using Rain Yun. +package rainyun + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/go-acme/lego/v4/challenge" + "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/rainyun/internal" +) + +// Environment variables names. +const ( + envNamespace = "RAINYUN_" + + EnvAPIKey = envNamespace + "API_KEY" + + EnvTTL = envNamespace + "TTL" + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" +) + +var _ challenge.ProviderTimeout = (*DNSProvider)(nil) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + APIKey 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, 2*time.Minute), + 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 Rain Yun. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey) + if err != nil { + return nil, fmt.Errorf("rainyun: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Rain Yun. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("rainyun: the configuration of the DNS provider is nil") + } + + client, err := internal.NewClient(config.APIKey) + if err != nil { + return nil, fmt.Errorf("rainyun: %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) + + ctx := context.Background() + + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("rainyun: could not find zone for domain %q: %w", domain, err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) + if err != nil { + return fmt.Errorf("rainyun: %w", err) + } + + domainID, err := d.findDomainID(ctx, dns01.UnFqdn(authZone)) + if err != nil { + return fmt.Errorf("rainyun: find domain ID: %w", err) + } + + record := internal.Record{ + Host: subDomain, + Priority: 10, + Line: "DEFAULT", + TTL: d.config.TTL, + Type: "TXT", + Value: info.Value, + } + + err = d.client.AddRecord(ctx, domainID, record) + if err != nil { + return fmt.Errorf("rainyun: add record: %w", err) + } + + return nil +} + +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + ctx := context.Background() + + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("rainyun: could not find zone for domain %q: %w", domain, err) + } + + domainID, err := d.findDomainID(ctx, dns01.UnFqdn(authZone)) + if err != nil { + return fmt.Errorf("rainyun: find domain ID: %w", err) + } + + recordID, err := d.findRecordID(ctx, domainID, info) + if err != nil { + return fmt.Errorf("rainyun: find record ID: %w", err) + } + + err = d.client.DeleteRecord(ctx, domainID, recordID) + if err != nil { + return fmt.Errorf("rainyun: delete 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) findDomainID(ctx context.Context, domain string) (int, error) { + domains, err := d.client.ListDomains(ctx) + if err != nil { + return 0, err + } + + for _, dom := range domains { + if dom.Domain == domain { + return dom.ID, nil + } + } + + return 0, fmt.Errorf("domain not found: %s", domain) +} + +func (d *DNSProvider) findRecordID(ctx context.Context, domainID int, info dns01.ChallengeInfo) (int, error) { + records, err := d.client.ListRecords(ctx, domainID) + if err != nil { + return 0, fmt.Errorf("list records: %w", err) + } + + zone := dns01.UnFqdn(info.EffectiveFQDN) + + for _, record := range records { + if strings.HasPrefix(zone, record.Host) && record.Value == info.Value { + return record.ID, nil + } + } + + return 0, fmt.Errorf("record not found: domainID=%d, fqdn=%s", domainID, info.EffectiveFQDN) +} diff --git a/providers/dns/rainyun/rainyun.toml b/providers/dns/rainyun/rainyun.toml new file mode 100644 index 0000000000..ea12b475f8 --- /dev/null +++ b/providers/dns/rainyun/rainyun.toml @@ -0,0 +1,22 @@ +Name = "Rain Yun/雨云" +Description = '''''' +URL = "https://www.rainyun.com" +Code = "rainyun" +Since = "v4.21.0" + +Example = ''' +RAINYUN_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email you@example.com --dns rainyun -d '*.example.com' -d example.com run +''' + +[Configuration] + [Configuration.Credentials] + RAINYUN_API_KEY = "API key" + [Configuration.Additional] + RAINYUN_POLLING_INTERVAL = "Time between DNS propagation check" + RAINYUN_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + RAINYUN_TTL = "The TTL of the TXT record used for the DNS challenge" + RAINYUN_HTTP_TIMEOUT = "API request timeout" + +[Links] + API = "https://www.apifox.cn/apidoc/shared-a4595cc8-44c5-4678-a2a3-eed7738dab03/api-151416609" diff --git a/providers/dns/rainyun/rainyun_test.go b/providers/dns/rainyun/rainyun_test.go new file mode 100644 index 0000000000..d0048e5d05 --- /dev/null +++ b/providers/dns/rainyun/rainyun_test.go @@ -0,0 +1,113 @@ +package rainyun + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvAPIKey).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: "missing credentials", + envVars: map[string]string{}, + expected: "rainyun: some credentials information are missing: RAINYUN_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 + expected string + }{ + { + desc: "success", + apiKey: "secret", + }, + { + desc: "missing credentials", + expected: "rainyun: 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) + 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 3d9f4965de..701fc83ffd 100644 --- a/providers/dns/zz_gen_dns_providers.go +++ b/providers/dns/zz_gen_dns_providers.go @@ -109,6 +109,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/plesk" "github.com/go-acme/lego/v4/providers/dns/porkbun" "github.com/go-acme/lego/v4/providers/dns/rackspace" + "github.com/go-acme/lego/v4/providers/dns/rainyun" "github.com/go-acme/lego/v4/providers/dns/rcodezero" "github.com/go-acme/lego/v4/providers/dns/regfish" "github.com/go-acme/lego/v4/providers/dns/regru" @@ -359,6 +360,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return porkbun.NewDNSProvider() case "rackspace": return rackspace.NewDNSProvider() + case "rainyun": + return rainyun.NewDNSProvider() case "rcodezero": return rcodezero.NewDNSProvider() case "regfish":