diff --git a/README.md b/README.md index 57c499e7..596833bc 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,8 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [Ultradns](https://go-acme.github.io/lego/dns/ultradns/) | [Variomedia](https://go-acme.github.io/lego/dns/variomedia/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | | [Vercel](https://go-acme.github.io/lego/dns/vercel/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | [VK Cloud](https://go-acme.github.io/lego/dns/vkcloud/) | | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | -| [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) | [Yandex PDD](https://go-acme.github.io/lego/dns/yandex/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | +| [Yandex 360](https://go-acme.github.io/lego/dns/yandex360/) | [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) | [Yandex PDD](https://go-acme.github.io/lego/dns/yandex/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | +| [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | | | | diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 01363244..51341af4 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -134,6 +134,7 @@ func allDNSCodes() string { "websupport", "wedos", "yandex", + "yandex360", "yandexcloud", "zoneee", "zonomi", @@ -2700,6 +2701,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/yandex`) + case "yandex360": + // generated from: providers/dns/yandex360/yandex360.toml + ew.writeln(`Configuration for Yandex 360.`) + ew.writeln(`Code: 'yandex360'`) + ew.writeln(`Since: 'v4.14.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "YANDEX360_OAUTH_TOKEN": The OAuth Token`) + ew.writeln(` - "YANDEX360_ORG_ID": The organization ID`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "YANDEX360_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "YANDEX360_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "YANDEX360_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "YANDEX360_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/yandex360`) + case "yandexcloud": // generated from: providers/dns/yandexcloud/yandexcloud.toml ew.writeln(`Configuration for Yandex Cloud.`) diff --git a/docs/content/dns/zz_gen_yandex360.md b/docs/content/dns/zz_gen_yandex360.md new file mode 100644 index 00000000..79221ac3 --- /dev/null +++ b/docs/content/dns/zz_gen_yandex360.md @@ -0,0 +1,69 @@ +--- +title: "Yandex 360" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: yandex360 +dnsprovider: + since: "v4.14.0" + code: "yandex360" + url: "https://360.yandex.ru" +--- + + + + + + +Configuration for [Yandex 360](https://360.yandex.ru). + + + + +- Code: `yandex360` +- Since: v4.14.0 + + +Here is an example bash command using the Yandex 360 provider: + +```bash +YANDEX360_OAUTH_TOKEN= \ +YANDEX360_ORG_ID= \ +lego --email you@example.com --dns yandex360 --domains my.example.org run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `YANDEX360_OAUTH_TOKEN` | The OAuth Token | +| `YANDEX360_ORG_ID` | The organization ID | + +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 | +|--------------------------------|-------------| +| `YANDEX360_HTTP_TIMEOUT` | API request timeout | +| `YANDEX360_POLLING_INTERVAL` | Time between DNS propagation check | +| `YANDEX360_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `YANDEX360_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://yandex.ru/dev/api360/doc/ref/DomainDNSService.html) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index ee7aaabf..8b70c793 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -137,7 +137,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, derak, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, manual, metaname, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, servercow, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, websupport, wedos, yandex, yandexcloud, zoneee, zonomi + acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, derak, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, manual, metaname, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, servercow, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index e3078eee..29b087d8 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -125,6 +125,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/websupport" "github.com/go-acme/lego/v4/providers/dns/wedos" "github.com/go-acme/lego/v4/providers/dns/yandex" + "github.com/go-acme/lego/v4/providers/dns/yandex360" "github.com/go-acme/lego/v4/providers/dns/yandexcloud" "github.com/go-acme/lego/v4/providers/dns/zoneee" "github.com/go-acme/lego/v4/providers/dns/zonomi" @@ -375,6 +376,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return wedos.NewDNSProvider() case "yandex": return yandex.NewDNSProvider() + case "yandex360": + return yandex360.NewDNSProvider() case "yandexcloud": return yandexcloud.NewDNSProvider() case "zoneee": diff --git a/providers/dns/safedns/internal/client.go b/providers/dns/safedns/internal/client.go index 254ec097..3e6f9991 100644 --- a/providers/dns/safedns/internal/client.go +++ b/providers/dns/safedns/internal/client.go @@ -50,7 +50,7 @@ func (c *Client) AddRecord(ctx context.Context, zone string, record Record) (*Ad respData := &AddRecordResponse{} err = c.do(req, respData) if err != nil { - return nil, fmt.Errorf("remove record: %w", err) + return nil, fmt.Errorf("add record: %w", err) } return respData, nil diff --git a/providers/dns/yandex/yandex.go b/providers/dns/yandex/yandex.go index e747be33..5bbac230 100644 --- a/providers/dns/yandex/yandex.go +++ b/providers/dns/yandex/yandex.go @@ -1,4 +1,4 @@ -// Package yandex implements a DNS provider for solving the DNS-01 challenge using Yandex. +// Package yandex implements a DNS provider for solving the DNS-01 challenge using Yandex PDD. package yandex import ( diff --git a/providers/dns/yandex360/internal/client.go b/providers/dns/yandex360/internal/client.go new file mode 100644 index 00000000..2bebc6c2 --- /dev/null +++ b/providers/dns/yandex360/internal/client.go @@ -0,0 +1,147 @@ +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" +) + +const defaultBaseURL = "https://api360.yandex.net/" + +type Client struct { + oauthToken string + orgID int64 + + baseURL *url.URL + HTTPClient *http.Client +} + +func NewClient(oauthToken string, orgID int64) (*Client, error) { + if oauthToken == "" { + return nil, errors.New("OAuth token is required") + } + + if orgID == 0 { + return nil, errors.New("orgID is required") + } + + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + oauthToken: oauthToken, + orgID: orgID, + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + }, nil +} + +// AddRecord Adds a DNS record. +// POST https://api30.yandex.net/directory/v1/org/{orgId}/domains/{domain}/dns +// https://yandex.ru/dev/api360/doc/ref/DomainDNSService/DomainDNSService_Create.html +func (c Client) AddRecord(ctx context.Context, domain string, record Record) (*Record, error) { + endpoint := c.baseURL.JoinPath("directory", "v1", "org", strconv.FormatInt(c.orgID, 10), "domains", domain, "dns") + + req, err := newJSONRequest(ctx, http.MethodPost, endpoint, record) + if err != nil { + return nil, err + } + + var newRecord Record + + err = c.do(req, &newRecord) + if err != nil { + return nil, err + } + + return &newRecord, nil +} + +// DeleteRecord Deletes a DNS record. +// DELETE https://api360.yandex.net/directory/v1/org/{orgId}/domains/{domain}/dns/{recordId} +// https://yandex.ru/dev/api360/doc/ref/DomainDNSService/DomainDNSService_Delete.html +func (c Client) DeleteRecord(ctx context.Context, domain string, recordID int64) error { + endpoint := c.baseURL.JoinPath("directory", "v1", "org", strconv.FormatInt(c.orgID, 10), "domains", domain, "dns", 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) do(req *http.Request, result any) error { + req.Header.Set("Authorization", "OAuth "+c.oauthToken) + + 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 apiErr APIError + err := json.Unmarshal(raw, &apiErr) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return fmt.Errorf("[status code: %d] %w", resp.StatusCode, apiErr) +} diff --git a/providers/dns/yandex360/internal/client_test.go b/providers/dns/yandex360/internal/client_test.go new file mode 100644 index 00000000..d0ddac0c --- /dev/null +++ b/providers/dns/yandex360/internal/client_test.go @@ -0,0 +1,108 @@ +package internal + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T, pattern, method 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 req.Method != method { + http.Error(rw, fmt.Sprintf("unsupported method %s", req.Method), http.StatusBadRequest) + return + } + + open, err := os.Open(filepath.Join("fixtures", filename)) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + + defer func() { _ = open.Close() }() + + rw.WriteHeader(status) + _, err = io.Copy(rw, open) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + client, err := NewClient("secret", 123456) + require.NoError(t, err) + + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client +} + +func TestClient_AddRecord(t *testing.T) { + client := setupTest(t, "/directory/v1/org/123456/domains/example.com/dns", http.MethodPost, http.StatusOK, "add-record.json") + + record := Record{ + Name: "_acme-challenge", + Text: "txtxtxt", + TTL: 60, + Type: "TXT", + } + + newRecord, err := client.AddRecord(context.Background(), "example.com", record) + require.NoError(t, err) + + expected := &Record{ + ID: 789465, + Name: "foo", + Text: "_acme-challenge", + TTL: 60, + Type: "txtxtxt", + } + + assert.Equal(t, expected, newRecord) +} + +func TestClient_AddRecord_error(t *testing.T) { + client := setupTest(t, "/directory/v1/org/123456/domains/example.com/dns", http.MethodGet, http.StatusUnauthorized, "error.json") + + record := Record{ + Name: "_acme-challenge", + Text: "txtxtxt", + TTL: 60, + Type: "TXT", + } + + newRecord, err := client.AddRecord(context.Background(), "example.com", record) + require.Error(t, err) + + assert.Nil(t, newRecord) +} + +func TestClient_DeleteRecord(t *testing.T) { + client := setupTest(t, "/directory/v1/org/123456/domains/example.com/dns/789456", http.MethodDelete, http.StatusOK, "delete-record.json") + + err := client.DeleteRecord(context.Background(), "example.com", 789456) + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client := setupTest(t, "/directory/v1/org/123456/domains/example.com/dns/789456", http.MethodDelete, http.StatusUnauthorized, "error.json") + + err := client.DeleteRecord(context.Background(), "example.com", 789456) + require.Error(t, err) +} diff --git a/providers/dns/yandex360/internal/fixtures/add-record.json b/providers/dns/yandex360/internal/fixtures/add-record.json new file mode 100644 index 00000000..3472d9ab --- /dev/null +++ b/providers/dns/yandex360/internal/fixtures/add-record.json @@ -0,0 +1,7 @@ +{ + "recordID": 789465, + "name": "foo", + "text": "_acme-challenge", + "ttl": 60, + "type": "txtxtxt" +} diff --git a/providers/dns/yandex360/internal/fixtures/delete-record.json b/providers/dns/yandex360/internal/fixtures/delete-record.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/providers/dns/yandex360/internal/fixtures/delete-record.json @@ -0,0 +1 @@ +{} diff --git a/providers/dns/yandex360/internal/fixtures/error.json b/providers/dns/yandex360/internal/fixtures/error.json new file mode 100644 index 00000000..6d6801d0 --- /dev/null +++ b/providers/dns/yandex360/internal/fixtures/error.json @@ -0,0 +1,9 @@ +{ + "code": 123, + "details": [ + { + "@type": "foo" + } + ], + "message": "bar" +} diff --git a/providers/dns/yandex360/internal/types.go b/providers/dns/yandex360/internal/types.go new file mode 100644 index 00000000..5e08e0a2 --- /dev/null +++ b/providers/dns/yandex360/internal/types.go @@ -0,0 +1,39 @@ +package internal + +import "fmt" + +type Record struct { + ID int64 `json:"recordId,omitempty"` + Address string `json:"address,omitempty"` + Exchange string `json:"exchange,omitempty"` + Flag int64 `json:"flag,omitempty"` + Name string `json:"name,omitempty"` + Port int64 `json:"port,omitempty"` + Preference int64 `json:"preference,omitempty"` + Priority int64 `json:"priority,omitempty"` + Tag string `json:"tag,omitempty"` + Target string `json:"target,omitempty"` + Text string `json:"text,omitempty"` + TTL int `json:"ttl,omitempty"` + Type string `json:"type,omitempty"` + Value string `json:"value,omitempty"` + Weight int64 `json:"weight,omitempty"` +} + +type APIError struct { + Code int32 `json:"code"` + Details []Detail `json:"details"` + Message string `json:"message"` +} + +func (a APIError) Error() string { + return fmt.Sprintf("%d: %s: %v", a.Code, a.Message, a.Details) +} + +type Detail struct { + Type string `json:"@type"` +} + +func (d Detail) String() string { + return d.Type +} diff --git a/providers/dns/yandex360/yandex360.go b/providers/dns/yandex360/yandex360.go new file mode 100644 index 00000000..837a5e71 --- /dev/null +++ b/providers/dns/yandex360/yandex360.go @@ -0,0 +1,174 @@ +// Package yandex360 implements a DNS provider for solving the DNS-01 challenge using Yandex 360. +package yandex360 + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "sync" + "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/yandex360/internal" +) + +// Environment variables names. +const ( + envNamespace = "YANDEX360_" + + EnvOAuthToken = envNamespace + "OAUTH_TOKEN" + EnvOrgID = envNamespace + "ORG_ID" + + 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 { + OAuthToken string + OrgID int64 + 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, 21600), + 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 { + client *internal.Client + config *Config + + recordIDs map[string]int64 + recordIDsMu sync.Mutex +} + +// NewDNSProvider returns a DNSProvider instance configured for Yandex 360. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvOAuthToken, EnvOrgID) + if err != nil { + return nil, fmt.Errorf("yandex360: %w", err) + } + + config := NewDefaultConfig() + config.OAuthToken = values[EnvOAuthToken] + + orgID, err := strconv.ParseInt(values[EnvOrgID], 10, 64) + if err != nil { + return nil, fmt.Errorf("yandex360: %w", err) + } + + config.OrgID = orgID + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Yandex 360. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("yandex360: the configuration of the DNS provider is nil") + } + + client, err := internal.NewClient(config.OAuthToken, config.OrgID) + if err != nil { + return nil, fmt.Errorf("yandex360: %w", err) + } + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + return &DNSProvider{ + client: client, + config: config, + recordIDs: make(map[string]int64), + }, nil +} + +// Present creates a TXT record to fulfill the dns-01 challenge. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(info.EffectiveFQDN)) + if err != nil { + return fmt.Errorf("yandex360: could not find zone for domain %q (%s): %w", domain, info.EffectiveFQDN, err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) + if err != nil { + return fmt.Errorf("yandex360: %w", err) + } + + authZone = dns01.UnFqdn(authZone) + + record := internal.Record{ + Name: subDomain, + TTL: d.config.TTL, + Text: info.Value, + Type: "TXT", + } + + newRecord, err := d.client.AddRecord(context.Background(), authZone, record) + if err != nil { + return fmt.Errorf("yandex360: add DNS record: %w", err) + } + + d.recordIDsMu.Lock() + d.recordIDs[token] = newRecord.ID + d.recordIDsMu.Unlock() + + 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) + + authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(info.EffectiveFQDN)) + if err != nil { + return fmt.Errorf("yandex360: could not find zone for domain %q (%s): %w", domain, info.EffectiveFQDN, err) + } + + authZone = dns01.UnFqdn(authZone) + + d.recordIDsMu.Lock() + recordID, ok := d.recordIDs[token] + d.recordIDsMu.Unlock() + + if !ok { + return fmt.Errorf("yandex360: unknown recordID for %q", info.EffectiveFQDN) + } + + err = d.client.DeleteRecord(context.Background(), authZone, recordID) + if err != nil { + return fmt.Errorf("yandex360: delete DNS record: %w", err) + } + + d.recordIDsMu.Lock() + delete(d.recordIDs, token) + d.recordIDsMu.Unlock() + + 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 +} diff --git a/providers/dns/yandex360/yandex360.toml b/providers/dns/yandex360/yandex360.toml new file mode 100644 index 00000000..ad0ce0d3 --- /dev/null +++ b/providers/dns/yandex360/yandex360.toml @@ -0,0 +1,25 @@ +Name = "Yandex 360" +Description = ''' +''' +URL = "https://360.yandex.ru" +Code = "yandex360" +Since = "v4.14.0" + +Example = ''' +YANDEX360_OAUTH_TOKEN= \ +YANDEX360_ORG_ID= \ +lego --email you@example.com --dns yandex360 --domains my.example.org run +''' + +[Configuration] + [Configuration.Credentials] + YANDEX360_OAUTH_TOKEN = "The OAuth Token" + YANDEX360_ORG_ID = "The organization ID" + [Configuration.Additional] + YANDEX360_POLLING_INTERVAL = "Time between DNS propagation check" + YANDEX360_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + YANDEX360_HTTP_TIMEOUT = "API request timeout" + YANDEX360_TTL = "The TTL of the TXT record used for the DNS challenge" + +[Links] + API = "https://yandex.ru/dev/api360/doc/ref/DomainDNSService.html" diff --git a/providers/dns/yandex360/yandex360_test.go b/providers/dns/yandex360/yandex360_test.go new file mode 100644 index 00000000..545c9098 --- /dev/null +++ b/providers/dns/yandex360/yandex360_test.go @@ -0,0 +1,130 @@ +package yandex360 + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvOAuthToken, EnvOrgID).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvOAuthToken: "secret", + EnvOrgID: "123456", + }, + }, + { + desc: "missing org ID", + envVars: map[string]string{ + EnvOAuthToken: "secret", + }, + expected: "yandex360: some credentials information are missing: YANDEX360_ORG_ID", + }, + { + desc: "missing token", + envVars: map[string]string{ + EnvOrgID: "123456", + }, + expected: "yandex360: some credentials information are missing: YANDEX360_OAUTH_TOKEN", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + defer envTest.RestoreEnv() + envTest.ClearEnv() + + envTest.Apply(test.envVars) + + p, err := NewDNSProvider() + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + oauthToken string + orgID int64 + expected string + }{ + { + desc: "success", + oauthToken: "secret", + orgID: 123456, + }, + { + desc: "missing org ID", + oauthToken: "secret", + expected: "yandex360: orgID is required", + }, + { + desc: "missing token", + orgID: 123456, + expected: "yandex360: OAuth token is required", + }, + } + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.OAuthToken = test.oauthToken + config.OrgID = test.orgID + + 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) +}