Add DNS provider for reg.ru (#1078)

This commit is contained in:
Ludovic Fernandez 2020-03-10 11:08:32 +01:00 committed by GitHub
parent e01131f2f4
commit 006012200e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 725 additions and 4 deletions

View file

@ -58,9 +58,9 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
| [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | [Name.com](https://go-acme.github.io/lego/dns/namedotcom/) |
| [Namecheap](https://go-acme.github.io/lego/dns/namecheap/) | [Namesilo](https://go-acme.github.io/lego/dns/namesilo/) | [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) |
| [NS1](https://go-acme.github.io/lego/dns/ns1/) | [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) | [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | [OVH](https://go-acme.github.io/lego/dns/ovh/) |
| [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) |
| [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) |
| [TransIP](https://go-acme.github.io/lego/dns/transip/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) |
| [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | | |
| [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) |
| [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) |
| [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) |
| [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | |
<!-- END DNS PROVIDERS LIST -->

View file

@ -66,6 +66,7 @@ func allDNSCodes() string {
"ovh",
"pdns",
"rackspace",
"regru",
"rfc2136",
"route53",
"sakuracloud",
@ -1193,6 +1194,27 @@ func displayDNSHelp(name string) error {
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/rackspace`)
case "regru":
// generated from: providers/dns/regru/regru.toml
ew.writeln(`Configuration for reg.ru.`)
ew.writeln(`Code: 'regru'`)
ew.writeln(`Since: 'v3.5.0'`)
ew.writeln()
ew.writeln(`Credentials:`)
ew.writeln(` - "REGRU_PASSWORD": API password`)
ew.writeln(` - "REGRU_USERNAME": API username`)
ew.writeln()
ew.writeln(`Additional Configuration:`)
ew.writeln(` - "REGRU_HTTP_TIMEOUT": API request timeout`)
ew.writeln(` - "REGRU_POLLING_INTERVAL": Time between DNS propagation check`)
ew.writeln(` - "REGRU_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`)
ew.writeln(` - "REGRU_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/regru`)
case "rfc2136":
// generated from: providers/dns/rfc2136/rfc2136.toml
ew.writeln(`Configuration for RFC2136.`)

View file

@ -0,0 +1,64 @@
---
title: "reg.ru"
date: 2019-03-03T16:39:46+01:00
draft: false
slug: regru
---
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/regru/regru.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
Since: v3.5.0
Configuration for [reg.ru](https://www.reg.ru/).
<!--more-->
- Code: `regru`
Here is an example bash command using the reg.ru provider:
```bash
REGRU_USERNAME=xxxxxx \
REGRU_PASSWORD=yyyyyyy \
lego --dns regru --domains my.domain.com --email my@email.com run
```
## Credentials
| Environment Variable Name | Description |
|-----------------------|-------------|
| `REGRU_PASSWORD` | API password |
| `REGRU_USERNAME` | API username |
The environment variable names can be suffixed by `_FILE` to reference a file instead of a value.
More information [here](/lego/dns/#configuration-and-credentials).
## Additional Configuration
| Environment Variable Name | Description |
|--------------------------------|-------------|
| `REGRU_HTTP_TIMEOUT` | API request timeout |
| `REGRU_POLLING_INTERVAL` | Time between DNS propagation check |
| `REGRU_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation |
| `REGRU_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](/lego/dns/#configuration-and-credentials).
## More information
- [API documentation](https://www.reg.ru/support/help/api2)
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/regru/regru.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->

View file

@ -57,6 +57,7 @@ import (
"github.com/go-acme/lego/v3/providers/dns/ovh"
"github.com/go-acme/lego/v3/providers/dns/pdns"
"github.com/go-acme/lego/v3/providers/dns/rackspace"
"github.com/go-acme/lego/v3/providers/dns/regru"
"github.com/go-acme/lego/v3/providers/dns/rfc2136"
"github.com/go-acme/lego/v3/providers/dns/route53"
"github.com/go-acme/lego/v3/providers/dns/sakuracloud"
@ -181,6 +182,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
return pdns.NewDNSProvider()
case "rackspace":
return rackspace.NewDNSProvider()
case "regru":
return regru.NewDNSProvider()
case "route53":
return route53.NewDNSProvider()
case "rfc2136":

View file

@ -0,0 +1,131 @@
package internal
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
)
const defaultBaseURL = "https://api.reg.ru/api/regru2/"
// Client the reg.ru client.
type Client struct {
username string
password string
BaseURL string
HTTPClient *http.Client
}
// NewClient Creates a reg.ru client.
func NewClient(username string, password string) *Client {
return &Client{
username: username,
password: password,
BaseURL: defaultBaseURL,
HTTPClient: http.DefaultClient,
}
}
// RemoveTxtRecord removes a TXT record.
// https://www.reg.ru/support/help/api2#zone_remove_record
func (c Client) RemoveTxtRecord(domain, subDomain string, content string) error {
request := RemoveRecordRequest{
Username: c.username,
Password: c.password,
Domains: []Domain{
{DName: domain},
},
SubDomain: subDomain,
Content: content,
RecordType: "TXT",
OutputContentType: "plain",
}
resp, err := c.do(request, "zone", "remove_record")
if err != nil {
return err
}
return resp.HasError()
}
// AddTXTRecord adds a TXT record.
// https://www.reg.ru/support/help/api2#zone_add_txt
func (c Client) AddTXTRecord(domain, subDomain string, content string) error {
request := AddTxtRequest{
Username: c.username,
Password: c.password,
Domains: []Domain{
{DName: domain},
},
SubDomain: subDomain,
Text: content,
OutputContentType: "plain",
}
resp, err := c.do(request, "zone", "add_txt")
if err != nil {
return err
}
return resp.HasError()
}
func (c Client) do(request interface{}, fragments ...string) (*APIResponse, error) {
endpoint, err := c.createEndpoint(fragments...)
if err != nil {
return nil, err
}
inputData, err := json.Marshal(request)
if err != nil {
return nil, err
}
query := endpoint.Query()
query.Add("input_data", string(inputData))
query.Add("input_format", "json")
endpoint.RawQuery = query.Encode()
resp, err := http.Get(endpoint.String())
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("API error, status code: %d", resp.StatusCode)
}
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var apiResp APIResponse
err = json.Unmarshal(all, &apiResp)
if err != nil {
return nil, err
}
return &apiResp, nil
}
func (c Client) createEndpoint(fragments ...string) (*url.URL, error) {
baseURL, err := url.Parse(c.BaseURL)
if err != nil {
return nil, err
}
endpoint, err := baseURL.Parse(path.Join(baseURL.Path, path.Join(fragments...)))
if err != nil {
return nil, err
}
return endpoint, nil
}

View file

@ -0,0 +1,107 @@
package internal
import (
"testing"
"github.com/stretchr/testify/require"
)
const (
noopBaseURL = "https://api.reg.ru/api/regru2/nop"
officialTestUser = "test"
officialTestPassword = "test"
)
func TestRemoveRecord(t *testing.T) {
client := NewClient(officialTestUser, officialTestPassword)
err := client.RemoveTxtRecord("test.ru", "_acme-challenge", "txttxttxt")
require.NoError(t, err)
}
func TestRemoveRecord_errors(t *testing.T) {
testCases := []struct {
desc string
domain string
username string
password string
baseURL string
expected string
}{
{
desc: "authentication failed",
domain: "test.ru",
username: "",
password: "",
baseURL: noopBaseURL,
expected: "API error: NO_AUTH: No authorization mechanism selected",
},
{
desc: "domain error",
domain: "",
username: officialTestUser,
password: officialTestPassword,
baseURL: defaultBaseURL,
expected: "API error: NO_DOMAIN: domain_name not given or empty",
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
client := NewClient(test.username, test.username)
err := client.RemoveTxtRecord(test.domain, "_acme-challenge", "txttxttxt")
require.EqualError(t, err, test.expected)
})
}
}
func TestAddTXTRecord(t *testing.T) {
client := NewClient(officialTestUser, officialTestPassword)
err := client.AddTXTRecord("test.ru", "_acme-challenge", "txttxttxt")
require.NoError(t, err)
}
func TestAddTXTRecord_errors(t *testing.T) {
testCases := []struct {
desc string
domain string
username string
password string
baseURL string
expected string
}{
{
desc: "authentication failed",
domain: "test.ru",
username: "",
password: "",
baseURL: noopBaseURL,
expected: "API error: NO_AUTH: No authorization mechanism selected",
},
{
desc: "domain error",
domain: "",
username: officialTestUser,
password: officialTestPassword,
baseURL: defaultBaseURL,
expected: "API error: NO_DOMAIN: domain_name not given or empty",
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
client := NewClient(test.username, test.username)
err := client.AddTXTRecord(test.domain, "_acme-challenge", "txttxttxt")
require.EqualError(t, err, test.expected)
})
}
}

View file

@ -0,0 +1,83 @@
package internal
import "fmt"
const successResult = "success"
// APIResponse is the representation of an API response.
type APIResponse struct {
Result string `json:"result"`
Answer *Answer `json:"answer,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
ErrorText string `json:"error_text,omitempty"`
}
func (a APIResponse) Error() string {
return fmt.Sprintf("API %s: %s: %s", a.Result, a.ErrorCode, a.ErrorText)
}
// HasError returns an error is the response contains an error.
func (a APIResponse) HasError() error {
if a.Result != successResult {
return a
}
if a.Answer != nil {
for _, domResp := range a.Answer.Domains {
if domResp.Result != successResult {
return domResp
}
}
}
return nil
}
// Answer is the representation of an API response answer.
type Answer struct {
Domains []DomainResponse `json:"domains,omitempty"`
}
// DomainResponse is the representation of an API response answer domain.
type DomainResponse struct {
Result string `json:"result"`
DName string `json:"dname"`
ErrorCode string `json:"error_code,omitempty"`
ErrorText string `json:"error_text,omitempty"`
}
func (d DomainResponse) Error() string {
return fmt.Sprintf("API %s: %s: %s", d.Result, d.ErrorCode, d.ErrorText)
}
// AddTxtRequest is the representation of the payload of a request to add a TXT record.
type AddTxtRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Domains []Domain `json:"domains,omitempty"`
SubDomain string `json:"subdomain,omitempty"`
Text string `json:"text,omitempty"`
OutputContentType string `json:"output_content_type,omitempty"`
}
// RemoveRecordRequest is the representation of the payload of a request to remove a record.
type RemoveRecordRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Domains []Domain `json:"domains,omitempty"`
SubDomain string `json:"subdomain,omitempty"`
Content string `json:"content,omitempty"`
RecordType string `json:"record_type,omitempty"`
OutputContentType string `json:"output_content_type,omitempty"`
}
// Domain is the representation of a Domain.
type Domain struct {
DName string `json:"dname"`
}

View file

@ -0,0 +1,135 @@
// Package regru implements a DNS provider for solving the DNS-01 challenge using reg.ru DNS.
package regru
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-acme/lego/v3/challenge/dns01"
"github.com/go-acme/lego/v3/platform/config/env"
"github.com/go-acme/lego/v3/providers/dns/regru/internal"
)
// Environment variables names.
const (
envNamespace = "REGRU_"
EnvUsername = envNamespace + "USERNAME"
EnvPassword = envNamespace + "PASSWORD"
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 {
Username string
Password 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, 300),
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
},
}
}
// DNSProvider is an implementation of the challenge.Provider interface.
type DNSProvider struct {
config *Config
client *internal.Client
}
// NewDNSProvider returns a DNSProvider instance configured for reg.ru.
// Credentials must be passed in the environment variables:
// REGRU_USERNAME and REGRU_PASSWORD.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvUsername, EnvPassword)
if err != nil {
return nil, fmt.Errorf("regru: %w", err)
}
config := NewDefaultConfig()
config.Username = values[EnvUsername]
config.Password = values[EnvPassword]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for reg.ru.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("regru: the configuration of the DNS provider is nil")
}
if config.Username == "" || config.Password == "" {
return nil, errors.New("regru: incomplete credentials, missing username and/or password")
}
client := internal.NewClient(config.Username, config.Password)
if config.HTTPClient != nil {
client.HTTPClient = config.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 using the specified parameters
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value := dns01.GetRecord(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return fmt.Errorf("regru: could not find zone for domain %q and fqdn %q : %w", domain, fqdn, err)
}
subDomain := dns01.UnFqdn(strings.TrimSuffix(fqdn, authZone))
err = d.client.AddTXTRecord(dns01.UnFqdn(authZone), subDomain, value)
if err != nil {
return fmt.Errorf("regru: failed to create TXT records [domain: %s, sub domain: %s]: %w",
dns01.UnFqdn(authZone), subDomain, err)
}
return nil
}
// CleanUp removes the TXT record matching the specified parameters
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
fqdn, value := dns01.GetRecord(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return fmt.Errorf("regru: could not find zone for domain %q and fqdn %q : %w", domain, fqdn, err)
}
subDomain := dns01.UnFqdn(strings.TrimSuffix(fqdn, authZone))
err = d.client.RemoveTxtRecord(dns01.UnFqdn(authZone), subDomain, value)
if err != nil {
return fmt.Errorf("regru: failed to remove TXT records [domain: %s, sub domain: %s]: %w",
dns01.UnFqdn(authZone), subDomain, err)
}
return nil
}

View file

@ -0,0 +1,24 @@
Name = "reg.ru"
Description = ''''''
URL = "https://www.reg.ru/"
Code = "regru"
Since = "v3.5.0"
Example = '''
REGRU_USERNAME=xxxxxx \
REGRU_PASSWORD=yyyyyyy \
lego --dns regru --domains my.domain.com --email my@email.com run
'''
[Configuration]
[Configuration.Credentials]
REGRU_USERNAME = "API username"
REGRU_PASSWORD = "API password"
[Configuration.Additional]
REGRU_POLLING_INTERVAL = "Time between DNS propagation check"
REGRU_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
REGRU_TTL = "The TTL of the TXT record used for the DNS challenge"
REGRU_HTTP_TIMEOUT = "API request timeout"
[Links]
API = "https://www.reg.ru/support/help/api2"

View file

@ -0,0 +1,152 @@
package regru
import (
"testing"
"time"
"github.com/go-acme/lego/v3/platform/tester"
"github.com/stretchr/testify/require"
)
const envDomain = envNamespace + "_DOMAIN"
var envTest = tester.NewEnvTest(
EnvUsername,
EnvPassword).
WithDomain(envDomain)
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
EnvUsername: "123",
EnvPassword: "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
EnvUsername: "",
EnvPassword: "",
},
expected: "regru: some credentials information are missing: REGRU_USERNAME,REGRU_PASSWORD",
},
{
desc: "missing api key",
envVars: map[string]string{
EnvUsername: "",
EnvPassword: "api_password",
},
expected: "regru: some credentials information are missing: REGRU_USERNAME",
},
{
desc: "missing secret key",
envVars: map[string]string{
EnvUsername: "api_username",
EnvPassword: "",
},
expected: "regru: some credentials information are missing: REGRU_PASSWORD",
},
}
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 len(test.expected) == 0 {
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
username string
password string
expected string
}{
{
desc: "success",
username: "api_username",
password: "api_password",
},
{
desc: "missing credentials",
expected: "regru: incomplete credentials, missing username and/or password",
},
{
desc: "missing username",
username: "",
password: "api_password",
expected: "regru: incomplete credentials, missing username and/or password",
},
{
desc: "missing password",
username: "api_username",
password: "",
expected: "regru: incomplete credentials, missing username and/or password",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
config := NewDefaultConfig()
config.Username = test.username
config.Password = test.password
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} 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)
time.Sleep(1 * time.Second)
err = provider.CleanUp(envTest.GetDomain(), "", "123d==")
require.NoError(t, err)
}