Add DNS provider for Infomaniak (#1277)

This commit is contained in:
Léopold Jacquot 2020-10-27 01:03:26 +01:00 committed by GitHub
parent 918037b8af
commit dfc346a00b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 830 additions and 10 deletions

View file

@ -55,15 +55,15 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
| [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/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | | [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/) | [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/) | | [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/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) | | [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/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) |
| [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/) | | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [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/) |
| [Linode (v4)](https://go-acme.github.io/lego/dns/linode/) | [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/) | | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linode/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) |
| [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/) | | [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/) |
| [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/) | | [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/) |
| [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/) | | [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/) |
| [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/) | | [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/) |
| [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/) | | [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/) |
| [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/) | | [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/) |
| [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/) | | [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/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | | | | [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 --> <!-- END DNS PROVIDERS LIST -->

View file

@ -54,6 +54,7 @@ func allDNSCodes() string {
"httpreq", "httpreq",
"hyperone", "hyperone",
"iij", "iij",
"infomaniak",
"inwx", "inwx",
"joker", "joker",
"lightsail", "lightsail",
@ -945,6 +946,27 @@ func displayDNSHelp(name string) error {
ew.writeln() ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/iij`) ew.writeln(`More information: https://go-acme.github.io/lego/dns/iij`)
case "infomaniak":
// generated from: providers/dns/infomaniak/infomaniak.toml
ew.writeln(`Configuration for Infomaniak.`)
ew.writeln(`Code: 'infomaniak'`)
ew.writeln(`Since: 'v4.1.0'`)
ew.writeln()
ew.writeln(`Credentials:`)
ew.writeln(` - "INFOMANIAK_ACCESS_TOKEN": Access token`)
ew.writeln()
ew.writeln(`Additional Configuration:`)
ew.writeln(` - "INFOMANIAK_ENDPOINT": https://api.infomaniak.com`)
ew.writeln(` - "INFOMANIAK_HTTP_TIMEOUT": API request timeout`)
ew.writeln(` - "INFOMANIAK_POLLING_INTERVAL": Time between DNS propagation check`)
ew.writeln(` - "INFOMANIAK_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`)
ew.writeln(` - "INFOMANIAK_TTL": The TTL of the TXT record used for the DNS challenge in seconds`)
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/infomaniak`)
case "inwx": case "inwx":
// generated from: providers/dns/inwx/inwx.toml // generated from: providers/dns/inwx/inwx.toml
ew.writeln(`Configuration for INWX.`) ew.writeln(`Configuration for INWX.`)

View file

@ -0,0 +1,68 @@
---
title: "Infomaniak"
date: 2019-03-03T16:39:46+01:00
draft: false
slug: infomaniak
---
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/infomaniak/infomaniak.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
Since: v4.1.0
Configuration for [Infomaniak](https://www.infomaniak.com/).
<!--more-->
- Code: `infomaniak`
Here is an example bash command using the Infomaniak provider:
```bash
INFOMANIAK_ACCESS_TOKEN=1234567898765432 \
lego --dns infomaniak --domains my.domain.com --email my@email.com run
```
## Credentials
| Environment Variable Name | Description |
|-----------------------|-------------|
| `INFOMANIAK_ACCESS_TOKEN` | Access token |
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 |
|--------------------------------|-------------|
| `INFOMANIAK_ENDPOINT` | https://api.infomaniak.com |
| `INFOMANIAK_HTTP_TIMEOUT` | API request timeout |
| `INFOMANIAK_POLLING_INTERVAL` | Time between DNS propagation check |
| `INFOMANIAK_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation |
| `INFOMANIAK_TTL` | The TTL of the TXT record used for the DNS challenge in seconds |
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).
## Access token
Access token can be created at the url https://manager.infomaniak.com/v3/infomaniak-api.
You will need domain scope.
```
## More information
- [API documentation](https://api.infomaniak.com/doc)
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/infomaniak/infomaniak.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->

View file

@ -45,6 +45,7 @@ import (
"github.com/go-acme/lego/v4/providers/dns/httpreq" "github.com/go-acme/lego/v4/providers/dns/httpreq"
"github.com/go-acme/lego/v4/providers/dns/hyperone" "github.com/go-acme/lego/v4/providers/dns/hyperone"
"github.com/go-acme/lego/v4/providers/dns/iij" "github.com/go-acme/lego/v4/providers/dns/iij"
"github.com/go-acme/lego/v4/providers/dns/infomaniak"
"github.com/go-acme/lego/v4/providers/dns/inwx" "github.com/go-acme/lego/v4/providers/dns/inwx"
"github.com/go-acme/lego/v4/providers/dns/joker" "github.com/go-acme/lego/v4/providers/dns/joker"
"github.com/go-acme/lego/v4/providers/dns/lightsail" "github.com/go-acme/lego/v4/providers/dns/lightsail"
@ -167,6 +168,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
return hyperone.NewDNSProvider() return hyperone.NewDNSProvider()
case "iij": case "iij":
return iij.NewDNSProvider() return iij.NewDNSProvider()
case "infomaniak":
return infomaniak.NewDNSProvider()
case "inwx": case "inwx":
return inwx.NewDNSProvider() return inwx.NewDNSProvider()
case "joker": case "joker":

View file

@ -0,0 +1,208 @@
// Package infomaniak implements a DNS provider for solving the DNS-01 challenge using Infomaniak DNS.
package infomaniak
import (
"errors"
"fmt"
"net/http"
"strings"
"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/infomaniak/internal"
)
// Infomaniak API reference: https://api.infomaniak.com/doc
// Create a Token: https://manager.infomaniak.com/v3/infomaniak-api
// Environment variables names.
const (
envNamespace = "INFOMANIAK_"
EnvEndpoint = envNamespace + "ENDPOINT"
EnvAccessToken = envNamespace + "ACCESS_TOKEN"
EnvTTL = envNamespace + "TTL"
EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
EnvPollingInterval = envNamespace + "POLLING_INTERVAL"
EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT"
)
const defaultBaseURL = "https://api.infomaniak.com"
// Config is used to configure the creation of the DNSProvider.
type Config struct {
APIEndpoint string
AccessToken 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{
APIEndpoint: env.GetOrDefaultString(EnvEndpoint, defaultBaseURL),
TTL: env.GetOrDefaultInt(EnvTTL, 7200),
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
},
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
config *Config
client *internal.Client
recordIDs map[string]string
recordIDsMu sync.Mutex
domainIDs map[string]uint64
domainIDsMu sync.Mutex
}
// NewDNSProvider returns a DNSProvider instance configured for Infomaniak.
// Credentials must be passed in the environment variables: INFOMANIAK_ACCESS_TOKEN.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvAccessToken)
if err != nil {
return nil, fmt.Errorf("infomaniak: %w", err)
}
config := NewDefaultConfig()
config.AccessToken = values[EnvAccessToken]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for Infomaniak.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("infomaniak: the configuration of the DNS provider is nil")
}
if config.APIEndpoint == "" {
return nil, errors.New("infomaniak: missing API endpoint")
}
if config.AccessToken == "" {
return nil, errors.New("infomaniak: missing access token")
}
client := internal.New(config.APIEndpoint, config.AccessToken)
if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}
return &DNSProvider{
config: config,
client: client,
recordIDs: make(map[string]string),
domainIDs: make(map[string]uint64),
}, nil
}
// 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 fmt.Errorf("infomaniak: %w", err)
}
ikDomain, err := d.client.GetDomainByName(domain)
if err != nil {
return fmt.Errorf("infomaniak: could not get domain %q: %w", domain, err)
}
d.domainIDsMu.Lock()
d.domainIDs[token] = ikDomain.ID
d.domainIDsMu.Unlock()
record := internal.Record{
Source: extractRecordName(fqdn, authZone),
Target: value,
Type: "TXT",
TTL: d.config.TTL,
}
recordID, err := d.client.CreateDNSRecord(ikDomain, record)
if err != nil {
return fmt.Errorf("infomaniak: error when calling api to create DNS record: %w", err)
}
d.recordIDsMu.Lock()
d.recordIDs[token] = recordID
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)
d.recordIDsMu.Lock()
recordID, ok := d.recordIDs[token]
d.recordIDsMu.Unlock()
if !ok {
return fmt.Errorf("infomaniak: unknown record ID for '%s'", fqdn)
}
d.domainIDsMu.Lock()
domainID, ok := d.domainIDs[token]
d.domainIDsMu.Unlock()
if !ok {
return fmt.Errorf("infomaniak: unknown domain ID for '%s'", fqdn)
}
err := d.client.DeleteDNSRecord(domainID, recordID)
if err != nil {
return fmt.Errorf("infomaniak: could not delete record %q: %w", domain, err)
}
// Delete record ID from map
d.recordIDsMu.Lock()
delete(d.recordIDs, token)
d.recordIDsMu.Unlock()
// Delete domain ID from map
d.domainIDsMu.Lock()
delete(d.domainIDs, token)
d.domainIDsMu.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
}
func getZone(fqdn string) (string, error) {
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return "", err
}
return dns01.UnFqdn(authZone), nil
}
func extractRecordName(fqdn, zone string) string {
name := dns01.UnFqdn(fqdn)
if idx := strings.Index(name, "."+zone); idx != -1 {
return name[:idx]
}
return name
}

View file

@ -0,0 +1,31 @@
Name = "Infomaniak"
Description = ''''''
URL = "https://www.infomaniak.com/"
Code = "infomaniak"
Since = "v4.1.0"
Example = '''
INFOMANIAK_ACCESS_TOKEN=1234567898765432 \
lego --dns infomaniak --domains my.domain.com --email my@email.com run
'''
Additional = '''
## Access token
Access token can be created at the url https://manager.infomaniak.com/v3/infomaniak-api.
You will need domain scope.
```
'''
[Configuration]
[Configuration.Credentials]
INFOMANIAK_ACCESS_TOKEN = "Access token"
[Configuration.Additional]
INFOMANIAK_ENDPOINT = "https://api.infomaniak.com"
INFOMANIAK_POLLING_INTERVAL = "Time between DNS propagation check"
INFOMANIAK_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
INFOMANIAK_TTL = "The TTL of the TXT record used for the DNS challenge in seconds"
INFOMANIAK_HTTP_TIMEOUT = "API request timeout"
[Links]
API = "https://api.infomaniak.com/doc"

View file

@ -0,0 +1,124 @@
package infomaniak
import (
"testing"
"time"
"github.com/go-acme/lego/v4/platform/tester"
"github.com/stretchr/testify/require"
)
const envDomain = envNamespace + "DOMAIN"
var envTest = tester.NewEnvTest(
EnvEndpoint,
EnvAccessToken).
WithDomain(envDomain)
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
EnvAccessToken: "123",
},
},
{
desc: "missing access token",
envVars: map[string]string{
EnvAccessToken: "",
},
expected: "infomaniak: some credentials information are missing: INFOMANIAK_ACCESS_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 len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
accessToken string
expected string
}{
{
desc: "success",
accessToken: "123",
},
{
desc: "missing access token",
accessToken: "",
expected: "infomaniak: missing access token",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
config := NewDefaultConfig()
config.AccessToken = test.accessToken
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
require.NotNil(t, p.recordIDs)
} 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)
}

View file

@ -0,0 +1,182 @@
package internal
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/log"
)
// Client the Infomaniak client.
type Client struct {
apiEndpoint string
apiToken string
HTTPClient *http.Client
}
// New Creates a new Infomaniak client.
func New(apiEndpoint, apiToken string) *Client {
return &Client{
apiEndpoint: apiEndpoint,
apiToken: apiToken,
HTTPClient: &http.Client{},
}
}
func (c *Client) CreateDNSRecord(domain *DNSDomain, record Record) (string, error) {
rawJSON, err := json.Marshal(record)
if err != nil {
return "", err
}
uri := fmt.Sprintf("/1/domain/%d/dns/record", domain.ID)
req, err := c.newRequest(http.MethodPost, uri, bytes.NewBuffer(rawJSON))
if err != nil {
return "", err
}
resp, err := c.do(req)
if err != nil {
return "", err
}
var recordID string
if err = json.Unmarshal(resp.Data, &recordID); err != nil {
return "", fmt.Errorf("expected record, got: %s", string(resp.Data))
}
return recordID, err
}
func (c *Client) DeleteDNSRecord(domainID uint64, recordID string) error {
uri := fmt.Sprintf("/1/domain/%d/dns/record/%s", domainID, recordID)
req, err := c.newRequest(http.MethodDelete, uri, nil)
if err != nil {
return err
}
_, err = c.do(req)
return err
}
// GetDomainByName gets a Domain object from its name.
func (c *Client) GetDomainByName(name string) (*DNSDomain, error) {
name = dns01.UnFqdn(name)
// Try to find the most specific domain
// starts with the FQDN, then remove each left label until we have a match
for {
i := strings.Index(name, ".")
if i == -1 {
break
}
domain, err := c.getDomainByName(name)
if err != nil {
return nil, err
}
if domain != nil {
return domain, nil
}
log.Infof("domain %q not found, trying with %q", name, name[i+1:])
name = name[i+1:]
}
return nil, fmt.Errorf("domain not found %s", name)
}
func (c *Client) getDomainByName(name string) (*DNSDomain, error) {
base, err := url.Parse("/1/product")
if err != nil {
return nil, err
}
query := base.Query()
query.Add("service_name", "domain")
query.Add("customer_name", name)
base.RawQuery = query.Encode()
req, err := c.newRequest(http.MethodGet, base.String(), nil)
if err != nil {
return nil, err
}
resp, err := c.do(req)
if err != nil {
return nil, err
}
var domains []DNSDomain
if err = json.Unmarshal(resp.Data, &domains); err != nil {
return nil, fmt.Errorf("failed to marshal domains: %s", string(resp.Data))
}
for _, domain := range domains {
if domain.CustomerName == name {
return &domain, nil
}
}
return nil, nil
}
func (c *Client) do(req *http.Request) (*APIResponse, error) {
rawResp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to perform API request: %w", err)
}
defer func() { _ = rawResp.Body.Close() }()
content, err := ioutil.ReadAll(rawResp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read the response body, status code: %d", rawResp.StatusCode)
}
var resp APIResponse
if err := json.Unmarshal(content, &resp); err != nil {
return nil, fmt.Errorf("failed to unmarshal the response body: %s", string(content))
}
if resp.Result != "success" {
return nil, fmt.Errorf("unexpected API result (%s): %v", resp.Result, resp.ErrResponse)
}
return &resp, nil
}
func (c *Client) newRequest(method, uri string, body io.Reader) (*http.Request, error) {
baseURL, err := url.Parse(c.apiEndpoint)
if err != nil {
return nil, err
}
endpoint, err := baseURL.Parse(path.Join(baseURL.Path, uri))
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, endpoint.String(), body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiToken)
req.Header.Set("Content-Type", "application/json")
return req, nil
}

View file

@ -0,0 +1,152 @@
package internal
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupTest(t *testing.T) (*Client, *http.ServeMux) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
return New(server.URL, "token"), mux
}
func TestClient_CreateDNSRecord(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("/1/domain/666/dns/record", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if req.Header.Get("Authorization") != "Bearer token" {
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
raw, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
defer func() { _ = req.Body.Close() }()
if string(raw) != `{"source":"foo","type":"TXT","ttl":60,"target":"txtxtxttxt"}` {
http.Error(rw, fmt.Sprintf("invalid request body: %s", string(raw)), http.StatusBadRequest)
return
}
response := `{"result":"success","data": "123"}`
_, err = rw.Write([]byte(response))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
domain := &DNSDomain{
ID: 666,
CustomerName: "test",
}
record := Record{
Source: "foo",
Target: "txtxtxttxt",
Type: "TXT",
TTL: 60,
}
recordID, err := client.CreateDNSRecord(domain, record)
require.NoError(t, err)
assert.Equal(t, "123", recordID)
}
func TestClient_GetDomainByName(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("/1/product", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if req.Header.Get("Authorization") != "Bearer token" {
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
serviceName := req.URL.Query().Get("service_name")
if serviceName != "domain" {
http.Error(rw, fmt.Sprintf("invalid service_name: %s", serviceName), http.StatusBadRequest)
return
}
customerName := req.URL.Query().Get("customer_name")
fmt.Println("customerName", customerName)
if customerName == "" {
http.Error(rw, fmt.Sprintf("invalid customer_name: %s", customerName), http.StatusBadRequest)
return
}
response := `
{
"result": "success",
"data": [
{
"id": 123,
"customer_name": "two.three.example.com"
},
{
"id": 456,
"customer_name": "three.example.com"
}
]
}
`
_, err := rw.Write([]byte(response))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
domain, err := client.GetDomainByName("one.two.three.example.com.")
require.NoError(t, err)
expected := &DNSDomain{ID: 123, CustomerName: "two.three.example.com"}
assert.Equal(t, expected, domain)
}
func TestClient_DeleteDNSRecord(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("/1/domain/123/dns/record/456", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if req.Header.Get("Authorization") != "Bearer token" {
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
_, err := rw.Write([]byte((`{"result":"success"}`)))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
err := client.DeleteDNSRecord(123, "456")
require.NoError(t, err)
}

View file

@ -0,0 +1,30 @@
package internal
import "encoding/json"
// Record a DNS record.
type Record struct {
ID string `json:"id,omitempty"`
Source string `json:"source,omitempty"`
Type string `json:"type,omitempty"`
TTL int `json:"ttl,omitempty"`
Target string `json:"target,omitempty"`
}
type DNSDomain struct {
ID uint64 `json:"id,omitempty"`
CustomerName string `json:"customer_name,omitempty"`
}
type APIResponse struct {
Result string `json:"result"`
Data json.RawMessage `json:"data,omitempty"`
ErrResponse *APIErrorResponse `json:"error,omitempty"`
}
type APIErrorResponse struct {
Code string `json:"code"`
Description string `json:"description,omitempty"`
Context map[string]string `json:"context,omitempty"`
Errors []APIErrorResponse `json:"errors,omitempty"`
}