Add DNS provider for ArvanCloud (#1173)

Co-authored-by: FaRzad-845 <f.shami@barox.ir>
This commit is contained in:
Sajjad Hashemian 2020-05-28 19:27:29 +04:30 committed by GitHub
parent 3d63e3ec07
commit 7c3689d08a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 1095 additions and 20 deletions

View file

@ -45,25 +45,25 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
| | | | |
|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [Alibaba Cloud DNS](https://go-acme.github.io/lego/dns/alidns/) | [Amazon Lightsail](https://go-acme.github.io/lego/dns/lightsail/) | [Amazon Route 53](https://go-acme.github.io/lego/dns/route53/) | [Aurora DNS](https://go-acme.github.io/lego/dns/auroradns/) |
| [Autodns](https://go-acme.github.io/lego/dns/autodns/) | [Azure](https://go-acme.github.io/lego/dns/azure/) | [Bindman](https://go-acme.github.io/lego/dns/bindman/) | [Bluecat](https://go-acme.github.io/lego/dns/bluecat/) |
| [Checkdomain](https://go-acme.github.io/lego/dns/checkdomain/) | [CloudDNS](https://go-acme.github.io/lego/dns/clouddns/) | [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) | [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) |
| [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Constellix](https://go-acme.github.io/lego/dns/constellix/) | [deSEC.io](https://go-acme.github.io/lego/dns/desec/) |
| [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) |
| [DNSPod](https://go-acme.github.io/lego/dns/dnspod/) | [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) |
| [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [Dynu](https://go-acme.github.io/lego/dns/dynu/) | [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) |
| [External program](https://go-acme.github.io/lego/dns/exec/) | [FastDNS](https://go-acme.github.io/lego/dns/fastdns/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | [Gandi](https://go-acme.github.io/lego/dns/gandi/) |
| [Glesys](https://go-acme.github.io/lego/dns/glesys/) | [Go Daddy](https://go-acme.github.io/lego/dns/godaddy/) | [Google Cloud](https://go-acme.github.io/lego/dns/gcloud/) | [Hetzner](https://go-acme.github.io/lego/dns/hetzner/) |
| [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) |
| [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Linode (deprecated)](https://go-acme.github.io/lego/dns/linode/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linodev4/) |
| [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) |
| [MythicBeasts](https://go-acme.github.io/lego/dns/mythicbeasts/) | [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/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [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/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) |
| [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/) | [Yandex](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/) | | | |
| [Alibaba Cloud DNS](https://go-acme.github.io/lego/dns/alidns/) | [Amazon Lightsail](https://go-acme.github.io/lego/dns/lightsail/) | [Amazon Route 53](https://go-acme.github.io/lego/dns/route53/) | [ArvanCloud](https://go-acme.github.io/lego/dns/arvancloud/) |
| [Aurora DNS](https://go-acme.github.io/lego/dns/auroradns/) | [Autodns](https://go-acme.github.io/lego/dns/autodns/) | [Azure](https://go-acme.github.io/lego/dns/azure/) | [Bindman](https://go-acme.github.io/lego/dns/bindman/) |
| [Bluecat](https://go-acme.github.io/lego/dns/bluecat/) | [Checkdomain](https://go-acme.github.io/lego/dns/checkdomain/) | [CloudDNS](https://go-acme.github.io/lego/dns/clouddns/) | [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) |
| [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) | [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Constellix](https://go-acme.github.io/lego/dns/constellix/) |
| [deSEC.io](https://go-acme.github.io/lego/dns/desec/) | [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) |
| [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | [DNSPod](https://go-acme.github.io/lego/dns/dnspod/) | [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) |
| [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [Dynu](https://go-acme.github.io/lego/dns/dynu/) | [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) |
| [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) | [External program](https://go-acme.github.io/lego/dns/exec/) | [FastDNS](https://go-acme.github.io/lego/dns/fastdns/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) |
| [Gandi](https://go-acme.github.io/lego/dns/gandi/) | [Glesys](https://go-acme.github.io/lego/dns/glesys/) | [Go Daddy](https://go-acme.github.io/lego/dns/godaddy/) | [Google Cloud](https://go-acme.github.io/lego/dns/gcloud/) |
| [Hetzner](https://go-acme.github.io/lego/dns/hetzner/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) |
| [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Linode (deprecated)](https://go-acme.github.io/lego/dns/linode/) |
| [Linode (v4)](https://go-acme.github.io/lego/dns/linodev4/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) | [Manual](https://go-acme.github.io/lego/dns/manual/) |
| [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | [MythicBeasts](https://go-acme.github.io/lego/dns/mythicbeasts/) | [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/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [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/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) |
| [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) | [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/) | [Yandex](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/) | | |
<!-- END DNS PROVIDERS LIST -->

View file

@ -16,6 +16,7 @@ func allDNSCodes() string {
"manual",
"acme-dns",
"alidns",
"arvancloud",
"auroradns",
"autodns",
"azure",
@ -136,6 +137,27 @@ func displayDNSHelp(name string) error {
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/alidns`)
case "arvancloud":
// generated from: providers/dns/arvancloud/arvancloud.toml
ew.writeln(`Configuration for ArvanCloud.`)
ew.writeln(`Code: 'arvancloud'`)
ew.writeln(`Since: 'v3.8.0'`)
ew.writeln()
ew.writeln(`Credentials:`)
ew.writeln(` - "ARVANCLOUD_API_KEY": API key`)
ew.writeln()
ew.writeln(`Additional Configuration:`)
ew.writeln(` - "ARVANCLOUD_HTTP_TIMEOUT": API request timeout`)
ew.writeln(` - "ARVANCLOUD_POLLING_INTERVAL": Time between DNS propagation check`)
ew.writeln(` - "ARVANCLOUD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`)
ew.writeln(` - "ARVANCLOUD_SEQUENCE_INTERVAL": Interval between iteration`)
ew.writeln(` - "ARVANCLOUD_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/arvancloud`)
case "auroradns":
// generated from: providers/dns/auroradns/auroradns.toml
ew.writeln(`Configuration for Aurora DNS.`)

View file

@ -0,0 +1,63 @@
---
title: "ArvanCloud"
date: 2019-03-03T16:39:46+01:00
draft: false
slug: arvancloud
---
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/arvancloud/arvancloud.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
Since: v3.8.0
Configuration for [ArvanCloud](https://arvancloud.com).
<!--more-->
- Code: `arvancloud`
Here is an example bash command using the ArvanCloud provider:
```bash
ARVANCLOUD_API_KEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \
lego --dns arvancloud --domains my.domain.com --email my@email.com run
```
## Credentials
| Environment Variable Name | Description |
|-----------------------|-------------|
| `ARVANCLOUD_API_KEY` | API key |
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 |
|--------------------------------|-------------|
| `ARVANCLOUD_HTTP_TIMEOUT` | API request timeout |
| `ARVANCLOUD_POLLING_INTERVAL` | Time between DNS propagation check |
| `ARVANCLOUD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation |
| `ARVANCLOUD_SEQUENCE_INTERVAL` | Interval between iteration |
| `ARVANCLOUD_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.arvancloud.com/docs/api/cdn/4.0)
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/arvancloud/arvancloud.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->

View file

@ -0,0 +1,186 @@
// Package arvancloud implements a DNS provider for solving the DNS-01 challenge using ArvanCloud DNS.
package arvancloud
import (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"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/arvancloud/internal"
)
const minTTL = 600
// Environment variables names.
const (
envNamespace = "ARVANCLOUD_"
EnvAPIKey = envNamespace + "API_KEY"
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
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, minTTL),
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
},
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
config *Config
client *internal.Client
recordIDs map[string]string
recordIDsMu sync.Mutex
}
// NewDNSProvider returns a DNSProvider instance configured for ArvanCloud.
// Credentials must be passed in the environment variable: ARVANCLOUD_API_KEY.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvAPIKey)
if err != nil {
return nil, fmt.Errorf("arvancloud: %w", err)
}
config := NewDefaultConfig()
config.APIKey = values[EnvAPIKey]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for ArvanCloud.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("arvancloud: the configuration of the DNS provider is nil")
}
if config.APIKey == "" {
return nil, errors.New("arvancloud: credentials missing")
}
if config.TTL < minTTL {
return nil, fmt.Errorf("arvancloud: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
}
client := internal.NewClient(config.APIKey)
if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}
return &DNSProvider{
config: config,
client: client,
recordIDs: make(map[string]string),
}, 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 {
fqdn, value := dns01.GetRecord(domain, keyAuth)
authZone, err := getZone(fqdn)
if err != nil {
return err
}
record := internal.DNSRecord{
Type: "txt",
Name: d.extractRecordName(fqdn, domain),
Value: internal.TXTRecordValue{Text: value},
TTL: d.config.TTL,
UpstreamHTTPS: "default",
IPFilterMode: &internal.IPFilterMode{
Count: "single",
GeoFilter: "none",
Order: "none",
},
}
newRecord, err := d.client.CreateRecord(authZone, record)
if err != nil {
return fmt.Errorf("arvancloud: failed to add TXT record: fqdn=%s: %w", fqdn, 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 {
fqdn, _ := dns01.GetRecord(domain, keyAuth)
authZone, err := getZone(fqdn)
if err != nil {
return err
}
// gets the record's unique ID from when we created it
d.recordIDsMu.Lock()
recordID, ok := d.recordIDs[token]
d.recordIDsMu.Unlock()
if !ok {
return fmt.Errorf("arvancloud: unknown record ID for '%s' '%s'", fqdn, token)
}
if err := d.client.DeleteRecord(authZone, recordID); err != nil {
return fmt.Errorf("arvancloud: failed to delate TXT record: id=%s: %w", recordID, err)
}
// deletes record ID from map
d.recordIDsMu.Lock()
delete(d.recordIDs, token)
d.recordIDsMu.Unlock()
return nil
}
func getZone(fqdn string) (string, error) {
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return "", err
}
return dns01.UnFqdn(authZone), nil
}
func (d *DNSProvider) extractRecordName(fqdn, domain string) string {
name := dns01.UnFqdn(fqdn)
if idx := strings.Index(name, "."+domain); idx != -1 {
return name[:idx]
}
return name
}

View file

@ -0,0 +1,23 @@
Name = "ArvanCloud"
Description = ''''''
URL = "https://arvancloud.com"
Code = "arvancloud"
Since = "v3.8.0"
Example = '''
ARVANCLOUD_API_KEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \
lego --dns arvancloud --domains my.domain.com --email my@email.com run
'''
[Configuration]
[Configuration.Credentials]
ARVANCLOUD_API_KEY = "API key"
[Configuration.Additional]
ARVANCLOUD_POLLING_INTERVAL = "Time between DNS propagation check"
ARVANCLOUD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
ARVANCLOUD_TTL = "The TTL of the TXT record used for the DNS challenge"
ARVANCLOUD_HTTP_TIMEOUT = "API request timeout"
ARVANCLOUD_SEQUENCE_INTERVAL = "Interval between iteration"
[Links]
API = "https://www.arvancloud.com/docs/api/cdn/4.0"

View file

@ -0,0 +1,125 @@
package arvancloud
import (
"testing"
"github.com/go-acme/lego/v3/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: "123",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
EnvAPIKey: "",
},
expected: "arvancloud: some credentials information are missing: ARVANCLOUD_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 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
apiKey string
ttl int
expected string
}{
{
desc: "success",
ttl: minTTL,
apiKey: "123",
},
{
desc: "missing credentials",
ttl: minTTL,
expected: "arvancloud: credentials missing",
},
{
desc: "invalid TTL",
apiKey: "123",
ttl: 60,
expected: "arvancloud: invalid TTL, TTL (60) must be greater than 600",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.TTL = test.ttl
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)
err = provider.CleanUp(envTest.GetDomain(), "", "123d==")
require.NoError(t, err)
}

View file

@ -0,0 +1,205 @@
package internal
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
)
// defaultBaseURL represents the API endpoint to call.
const defaultBaseURL = "https://napi.arvancloud.com"
const authHeader = "Authorization"
// Client the ArvanCloud client.
type Client struct {
HTTPClient *http.Client
BaseURL string
apiKey string
}
// NewClient Creates a new ArvanCloud client.
func NewClient(apiKey string) *Client {
return &Client{
HTTPClient: http.DefaultClient,
BaseURL: defaultBaseURL,
apiKey: apiKey,
}
}
// GetTxtRecord gets a TXT record.
func (c *Client) GetTxtRecord(domain, name, value string) (*DNSRecord, error) {
records, err := c.getRecords(domain, name)
if err != nil {
return nil, err
}
for _, record := range records {
if equalsTXTRecord(record, name, value) {
return &record, nil
}
}
return nil, fmt.Errorf("could not find record: Domain: %s; Record: %s", domain, name)
}
// https://www.arvancloud.com/docs/api/cdn/4.0#operation/dns_records.list
func (c *Client) getRecords(domain, search string) ([]DNSRecord, error) {
endpoint, err := c.createEndpoint("cdn", "4.0", "domains", domain, "dns-records")
if err != nil {
return nil, fmt.Errorf("failed to create endpoint: %w", err)
}
if search != "" {
query := endpoint.Query()
query.Set("search", strings.ReplaceAll(search, "_", ""))
endpoint.RawQuery = query.Encode()
}
resp, err := c.do(http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("could not get records %s: Domain: %s; Status: %s; Body: %s",
search, domain, resp.Status, string(body))
}
response := &apiResponse{}
err = json.Unmarshal(body, response)
if err != nil {
return nil, fmt.Errorf("failed to decode response body: %w", err)
}
var records []DNSRecord
err = json.Unmarshal(response.Data, &records)
if err != nil {
return nil, fmt.Errorf("failed to decode records: %w", err)
}
return records, nil
}
// CreateRecord creates a DNS record.
// https://www.arvancloud.com/docs/api/cdn/4.0#operation/dns_records.create
func (c *Client) CreateRecord(domain string, record DNSRecord) (*DNSRecord, error) {
reqBody, err := json.Marshal(record)
if err != nil {
return nil, err
}
endpoint, err := c.createEndpoint("cdn", "4.0", "domains", domain, "dns-records")
if err != nil {
return nil, fmt.Errorf("failed to create endpoint: %w", err)
}
resp, err := c.do(http.MethodPost, endpoint.String(), bytes.NewReader(reqBody))
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("could not create record %s; Domain: %s; Status: %s; Body: %s", string(reqBody), domain, resp.Status, string(body))
}
response := &apiResponse{}
err = json.Unmarshal(body, response)
if err != nil {
return nil, fmt.Errorf("failed to decode response body: %w", err)
}
var newRecord DNSRecord
err = json.Unmarshal(response.Data, &newRecord)
if err != nil {
return nil, fmt.Errorf("failed to decode record: %w", err)
}
return &newRecord, nil
}
// DeleteRecord deletes a DNS record.
// https://www.arvancloud.com/docs/api/cdn/4.0#operation/dns_records.remove
func (c *Client) DeleteRecord(domain, id string) error {
endpoint, err := c.createEndpoint("cdn", "4.0", "domains", domain, "dns-records", id)
if err != nil {
return fmt.Errorf("failed to create endpoint: %w", err)
}
resp, err := c.do(http.MethodDelete, endpoint.String(), nil)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("could not delete record %s; Domain: %s; Status: %s; Body: %s", id, domain, resp.Status, string(body))
}
return nil
}
func (c *Client) do(method, endpoint string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set(authHeader, c.apiKey)
return c.HTTPClient.Do(req)
}
func (c *Client) createEndpoint(parts ...string) (*url.URL, error) {
baseURL, err := url.Parse(c.BaseURL)
if err != nil {
return nil, err
}
endpoint, err := baseURL.Parse(path.Join(parts...))
if err != nil {
return nil, err
}
return endpoint, nil
}
func equalsTXTRecord(record DNSRecord, name, value string) bool {
if record.Type != "txt" {
return false
}
if record.Name != name {
return false
}
data, ok := record.Value.(map[string]interface{})
if !ok {
return false
}
return data["text"] == value
}

View file

@ -0,0 +1,145 @@
package internal
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClient_GetTxtRecord(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
const domain = "example.com"
const apiKey = "myKeyA"
mux.HandleFunc("/cdn/4.0/domains/"+domain+"/dns-records", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed)
return
}
auth := req.Header.Get(authHeader)
if auth != apiKey {
http.Error(rw, fmt.Sprintf("invalid API key: %s", auth), http.StatusUnauthorized)
return
}
file, err := os.Open("./fixtures/get_txt_record.json")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
defer func() { _ = file.Close() }()
_, err = io.Copy(rw, file)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
})
client := NewClient(apiKey)
client.BaseURL = server.URL
_, err := client.GetTxtRecord(domain, "_acme-challenge", "txtxtxt")
require.NoError(t, err)
}
func TestClient_CreateRecord(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
const domain = "example.com"
const apiKey = "myKeyB"
mux.HandleFunc("/cdn/4.0/domains/"+domain+"/dns-records", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed)
return
}
auth := req.Header.Get(authHeader)
if auth != apiKey {
http.Error(rw, fmt.Sprintf("invalid API key: %s", auth), http.StatusUnauthorized)
return
}
file, err := os.Open("./fixtures/create_txt_record.json")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
defer func() { _ = file.Close() }()
rw.WriteHeader(http.StatusCreated)
_, err = io.Copy(rw, file)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
})
client := NewClient(apiKey)
client.BaseURL = server.URL
record := DNSRecord{
Name: "_acme-challenge",
Type: "txt",
Value: &TXTRecordValue{Text: "txtxtxt"},
TTL: 600,
}
newRecord, err := client.CreateRecord(domain, record)
require.NoError(t, err)
expected := &DNSRecord{
ID: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
Type: "txt",
Value: map[string]interface{}{"text": "txtxtxt"},
Name: "_acme-challenge",
TTL: 120,
UpstreamHTTPS: "default",
IPFilterMode: &IPFilterMode{
Count: "single",
Order: "none",
GeoFilter: "none",
},
}
assert.Equal(t, expected, newRecord)
}
func TestClient_DeleteRecord(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
const domain = "example.com"
const apiKey = "myKeyC"
const recordID = "recordId"
mux.HandleFunc("/cdn/4.0/domains/"+domain+"/dns-records/"+recordID, func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed)
return
}
auth := req.Header.Get(authHeader)
if auth != apiKey {
http.Error(rw, fmt.Sprintf("invalid API key: %s", auth), http.StatusUnauthorized)
return
}
})
client := NewClient(apiKey)
client.BaseURL = server.URL
err := client.DeleteRecord(domain, recordID)
require.NoError(t, err)
}

View file

@ -0,0 +1,28 @@
{
"data": {
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "txt",
"name": "_acme-challenge",
"value": {
"text": "txtxtxt"
},
"ttl": 120,
"cloud": false,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-27T23:57:02Z",
"updated_at": "2020-05-27T23:57:02Z"
},
"message": "DNS record created successfully"
}

View file

@ -0,0 +1,244 @@
{
"data": [
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "a",
"name": "@",
"value": [
{
"ip": "xx.xxx.xxx.xxx",
"port": null,
"weight": 1,
"country": ""
}
],
"ttl": 120,
"cloud": true,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-19T15:05:12Z",
"updated_at": "2020-05-23T22:06:00Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "a",
"name": "www",
"value": [
{
"ip": "xx.xxx.xxx.xxx",
"port": null,
"weight": 1,
"country": ""
}
],
"ttl": 120,
"cloud": true,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-19T15:05:12Z",
"updated_at": "2020-05-23T22:05:55Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "a",
"name": "thatcher",
"value": [
{
"ip": "xx.xxx.xxx.xxx",
"port": null,
"weight": 100,
"country": ""
}
],
"ttl": 120,
"cloud": false,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-20T18:45:10Z",
"updated_at": "2020-05-21T13:19:46Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "a",
"name": "api",
"value": [
{
"ip": "xx.xxx.xxx.xxx",
"port": null,
"weight": 100,
"country": ""
}
],
"ttl": 120,
"cloud": true,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-20T18:45:35Z",
"updated_at": "2020-05-22T20:22:27Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "a",
"name": "rock",
"value": [
{
"ip": "xx.xxx.xxx.xxx",
"port": null,
"weight": 100,
"country": ""
}
],
"ttl": 120,
"cloud": true,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-22T10:29:27Z",
"updated_at": "2020-05-22T13:35:26Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "ns",
"name": "@",
"value": {
"host": "z.ns.arvancdn.com."
},
"ttl": 7200,
"cloud": false,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": false,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-19T15:05:09Z",
"updated_at": "2020-05-19T15:05:09Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "ns",
"name": "@",
"value": {
"host": "g.ns.arvancdn.com."
},
"ttl": 7200,
"cloud": false,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": false,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-19T15:05:12Z",
"updated_at": "2020-05-19T15:05:12Z"
},
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"type": "txt",
"name": "_acme-challenge",
"value": {
"text": "txtxtxt"
},
"ttl": 120,
"cloud": false,
"upstream_https": "default",
"ip_filter_mode": {
"count": "single",
"order": "none",
"geo_filter": "none"
},
"can_delete": true,
"health_check_status": false,
"health_check_setting": {
"protocol": "http",
"port": "",
"uri": ""
},
"created_at": "2020-05-27T20:53:54Z",
"updated_at": "2020-05-27T20:53:54Z"
}
],
"links": {
"first": "https://napi.arvancloud.com/4.0/domains/example.ir/dns-records?page=1",
"last": "https://napi.arvancloud.com/4.0/domains/example.ir/dns-records?page=1",
"prev": null,
"next": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "https://napi.arvancloud.com/4.0/domains/example.ir/dns-records",
"per_page": 300,
"to": 8,
"total": 8
}
}

View file

@ -0,0 +1,31 @@
package internal
import "encoding/json"
type apiResponse struct {
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
// DNSRecord a DNS record.
type DNSRecord struct {
ID string `json:"id,omitempty"`
Type string `json:"type"`
Value interface{} `json:"value,omitempty"`
Name string `json:"name,omitempty"`
TTL int `json:"ttl,omitempty"`
UpstreamHTTPS string `json:"upstream_https,omitempty"`
IPFilterMode *IPFilterMode `json:"ip_filter_mode,omitempty"`
}
// TXTRecordValue represents a TXT record value.
type TXTRecordValue struct {
Text string `json:"text,omitempty"` // only for TXT Record.
}
// IPFilterMode a DNS ip_filter_mode.
type IPFilterMode struct {
Count string `json:"count,omitempty"`
Order string `json:"order,omitempty"`
GeoFilter string `json:"geo_filter,omitempty"`
}

View file

@ -7,6 +7,7 @@ import (
"github.com/go-acme/lego/v3/challenge/dns01"
"github.com/go-acme/lego/v3/providers/dns/acmedns"
"github.com/go-acme/lego/v3/providers/dns/alidns"
"github.com/go-acme/lego/v3/providers/dns/arvancloud"
"github.com/go-acme/lego/v3/providers/dns/auroradns"
"github.com/go-acme/lego/v3/providers/dns/autodns"
"github.com/go-acme/lego/v3/providers/dns/azure"
@ -90,6 +91,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
return acmedns.NewDNSProvider()
case "alidns":
return alidns.NewDNSProvider()
case "arvancloud":
return arvancloud.NewDNSProvider()
case "azure":
return azure.NewDNSProvider()
case "auroradns":