Add DNS provider for hosttech (#1447)

This commit is contained in:
Ludovic Fernandez 2021-07-09 22:50:19 +02:00 committed by GitHub
parent 2dbe8832a5
commit 264d39bbc4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 1088 additions and 27 deletions

View file

@ -56,20 +56,20 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
| [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/) | [freemyip.com](https://go-acme.github.io/lego/dns/freemyip/) | [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/) | [Hurricane Electric DNS](https://go-acme.github.io/lego/dns/hurricane/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) |
| [Infoblox](https://go-acme.github.io/lego/dns/infoblox/) | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) |
| [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [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/) | [Loopia](https://go-acme.github.io/lego/dns/loopia/) | [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/) | [Njalla](https://go-acme.github.io/lego/dns/njalla/) | [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/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) | [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/) |
| [Simply.com](https://go-acme.github.io/lego/dns/simply/) | [Sonic](https://go-acme.github.io/lego/dns/sonic/) | [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/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) |
| [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [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/) | | | |
| [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [Hosttech](https://go-acme.github.io/lego/dns/hosttech/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Hurricane Electric DNS](https://go-acme.github.io/lego/dns/hurricane/) |
| [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) | [Infoblox](https://go-acme.github.io/lego/dns/infoblox/) | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) |
| [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [Joker](https://go-acme.github.io/lego/dns/joker/) |
| [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/) | [Loopia](https://go-acme.github.io/lego/dns/loopia/) |
| [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/) | [Njalla](https://go-acme.github.io/lego/dns/njalla/) | [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/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) |
| [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/) | [Simply.com](https://go-acme.github.io/lego/dns/simply/) | [Sonic](https://go-acme.github.io/lego/dns/sonic/) | [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/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) |
| [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [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

@ -54,6 +54,7 @@ func allDNSCodes() string {
"godaddy",
"hetzner",
"hostingde",
"hosttech",
"httpreq",
"hurricane",
"hyperone",
@ -963,6 +964,27 @@ func displayDNSHelp(name string) error {
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/hostingde`)
case "hosttech":
// generated from: providers/dns/hosttech/hosttech.toml
ew.writeln(`Configuration for Hosttech.`)
ew.writeln(`Code: 'hosttech'`)
ew.writeln(`Since: 'v4.5.0'`)
ew.writeln()
ew.writeln(`Credentials:`)
ew.writeln(` - "HOSTTECH_API_KEY": API login`)
ew.writeln(` - "HOSTTECH_PASSWORD": API password`)
ew.writeln()
ew.writeln(`Additional Configuration:`)
ew.writeln(` - "HOSTTECH_HTTP_TIMEOUT": API request timeout`)
ew.writeln(` - "HOSTTECH_POLLING_INTERVAL": Time between DNS propagation check`)
ew.writeln(` - "HOSTTECH_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`)
ew.writeln(` - "HOSTTECH_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/hosttech`)
case "httpreq":
// generated from: providers/dns/httpreq/httpreq.toml
ew.writeln(`Configuration for HTTP request.`)

View file

@ -0,0 +1,63 @@
---
title: "Hosttech"
date: 2019-03-03T16:39:46+01:00
draft: false
slug: hosttech
---
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/hosttech/hosttech.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
Since: v4.5.0
Configuration for [Hosttech](https://www.hosttech.eu/).
<!--more-->
- Code: `hosttech`
Here is an example bash command using the Hosttech provider:
```bash
HOSTTECH_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxx \
lego --email myemail@example.com --dns hosttech --domains my.example.org run
```
## Credentials
| Environment Variable Name | Description |
|-----------------------|-------------|
| `HOSTTECH_API_KEY` | API login |
| `HOSTTECH_PASSWORD` | API password |
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 |
|--------------------------------|-------------|
| `HOSTTECH_HTTP_TIMEOUT` | API request timeout |
| `HOSTTECH_POLLING_INTERVAL` | Time between DNS propagation check |
| `HOSTTECH_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation |
| `HOSTTECH_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://api.ns1.hosttech.eu/api/documentation)
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/hosttech/hosttech.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/godaddy"
"github.com/go-acme/lego/v4/providers/dns/hetzner"
"github.com/go-acme/lego/v4/providers/dns/hostingde"
"github.com/go-acme/lego/v4/providers/dns/hosttech"
"github.com/go-acme/lego/v4/providers/dns/httpreq"
"github.com/go-acme/lego/v4/providers/dns/hurricane"
"github.com/go-acme/lego/v4/providers/dns/hyperone"
@ -182,6 +183,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
return hetzner.NewDNSProvider()
case "hostingde":
return hostingde.NewDNSProvider()
case "hosttech":
return hosttech.NewDNSProvider()
case "httpreq":
return httpreq.NewDNSProvider()
case "hurricane":

View file

@ -0,0 +1,164 @@
// Package hosttech implements a DNS provider for solving the DNS-01 challenge using hosttech.
package hosttech
import (
"errors"
"fmt"
"net/http"
"strconv"
"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/hosttech/internal"
)
// Environment variables names.
const (
envNamespace = "HOSTTECH_"
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, 3600),
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]int
recordIDsMu sync.Mutex
}
// NewDNSProvider returns a DNSProvider instance configured for hosttech.
// Credentials must be passed in the environment variable: HOSTTECH_API_KEY.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvAPIKey)
if err != nil {
return nil, fmt.Errorf("hosttech: %w", err)
}
config := NewDefaultConfig()
config.APIKey = values[EnvAPIKey]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for hosttech.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("hosttech: the configuration of the DNS provider is nil")
}
if config.APIKey == "" {
return nil, errors.New("hosttech: missing credentials")
}
client := internal.NewClient(config.APIKey)
if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}
return &DNSProvider{
config: config,
client: client,
recordIDs: map[string]int{},
}, 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("hosttech: could not determine zone for domain %q: %w", domain, err)
}
zone, err := d.client.GetZone(dns01.UnFqdn(authZone))
if err != nil {
return fmt.Errorf("hosttech: could not find zone for domain %q (%s): %w", domain, authZone, err)
}
record := internal.Record{
Type: "TXT",
Name: dns01.UnFqdn(strings.TrimSuffix(fqdn, authZone)),
Text: value,
TTL: d.config.TTL,
}
newRecord, err := d.client.AddRecord(strconv.Itoa(zone.ID), record)
if err != nil {
return fmt.Errorf("hosttech: %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 {
fqdn, _ := dns01.GetRecord(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return fmt.Errorf("hosttech: could not determine zone for domain %q: %w", domain, err)
}
zone, err := d.client.GetZone(dns01.UnFqdn(authZone))
if err != nil {
return fmt.Errorf("hosttech: could not find zone for domain %q (%s): %w", domain, authZone, 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("hosttech: unknown record ID for '%s' '%s'", fqdn, token)
}
err = d.client.DeleteRecord(strconv.Itoa(zone.ID), strconv.Itoa(recordID))
if err != nil {
return fmt.Errorf("hosttech: %w", err)
}
return nil
}

View file

@ -0,0 +1,23 @@
Name = "Hosttech"
Description = ''''''
URL = "https://www.hosttech.eu/"
Code = "hosttech"
Since = "v4.5.0"
Example = '''
HOSTTECH_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxx \
lego --email myemail@example.com --dns hosttech --domains my.example.org run
'''
[Configuration]
[Configuration.Credentials]
HOSTTECH_API_KEY = "API login"
HOSTTECH_PASSWORD = "API password"
[Configuration.Additional]
HOSTTECH_POLLING_INTERVAL = "Time between DNS propagation check"
HOSTTECH_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
HOSTTECH_TTL = "The TTL of the TXT record used for the DNS challenge"
HOSTTECH_HTTP_TIMEOUT = "API request timeout"
[Links]
API = "https://api.ns1.hosttech.eu/api/documentation"

View file

@ -0,0 +1,115 @@
package hosttech
import (
"testing"
"time"
"github.com/go-acme/lego/v4/platform/tester"
"github.com/stretchr/testify/require"
)
const envDomain = envNamespace + "DOMAIN"
var envTest = tester.NewEnvTest(EnvAPIKey).WithDomain(envDomain)
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
EnvAPIKey: "secret",
},
},
{
desc: "missing API key",
expected: "hosttech: some credentials information are missing: HOSTTECH_API_KEY",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer envTest.RestoreEnv()
envTest.ClearEnv()
envTest.Apply(test.envVars)
p, err := NewDNSProvider()
if test.expected == "" {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "secret",
},
{
desc: "missing API key",
expected: "hosttech: missing credentials",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
config := NewDefaultConfig()
config.APIKey = test.apiKey
p, err := NewDNSProviderConfig(config)
if test.expected == "" {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !envTest.IsLiveTest() {
t.Skip("skipping live test")
}
envTest.RestoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(envTest.GetDomain(), "", "123d==")
require.NoError(t, err)
}
func TestLiveCleanUp(t *testing.T) {
if !envTest.IsLiveTest() {
t.Skip("skipping live test")
}
envTest.RestoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
time.Sleep(1 * time.Second)
err = provider.CleanUp(envTest.GetDomain(), "", "123d==")
require.NoError(t, err)
}

View file

@ -0,0 +1,228 @@
package internal
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"strconv"
"time"
)
const defaultBaseURL = "https://api.ns1.hosttech.eu/api"
// Client a Hosttech client.
type Client struct {
HTTPClient *http.Client
baseURL *url.URL
apiKey string
}
// NewClient creates a new Client.
func NewClient(apiKey string) *Client {
baseURL, _ := url.Parse(defaultBaseURL)
return &Client{
HTTPClient: &http.Client{Timeout: 10 * time.Second},
baseURL: baseURL,
apiKey: apiKey,
}
}
// GetZones Get a list of all zones.
// https://api.ns1.hosttech.eu/api/documentation/#/Zones/get_api_user_v1_zones
func (c Client) GetZones(query string, limit, offset int) ([]Zone, error) {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "user", "v1", "zones"))
if err != nil {
return nil, fmt.Errorf("parse URL: %w", err)
}
values := endpoint.Query()
values.Set("query", query)
if limit > 0 {
values.Set("limit", strconv.Itoa(limit))
}
if offset > 0 {
values.Set("offset", strconv.Itoa(offset))
}
endpoint.RawQuery = values.Encode()
req, err := http.NewRequest(http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
raw, err := c.do(req)
if err != nil {
return nil, err
}
var r []Zone
err = json.Unmarshal(raw, &r)
if err != nil {
return nil, fmt.Errorf("unmarshal response data: %s: %w", string(raw), err)
}
return r, nil
}
// GetZone Get a single zone.
// https://api.ns1.hosttech.eu/api/documentation/#/Zones/get_api_user_v1_zones__zoneId_
func (c Client) GetZone(zoneID string) (*Zone, error) {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "user", "v1", "zones", zoneID))
if err != nil {
return nil, fmt.Errorf("parse URL: %w", err)
}
req, err := http.NewRequest(http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
raw, err := c.do(req)
if err != nil {
return nil, err
}
var r Zone
err = json.Unmarshal(raw, &r)
if err != nil {
return nil, fmt.Errorf("unmarshal response data: %s: %w", string(raw), err)
}
return &r, nil
}
// GetRecords Returns a list of all records for the given zone.
// https://api.ns1.hosttech.eu/api/documentation/#/Records/get_api_user_v1_zones__zoneId__records
func (c Client) GetRecords(zoneID, recordType string) ([]Record, error) {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "user", "v1", "zones", zoneID, "records"))
if err != nil {
return nil, fmt.Errorf("parse URL: %w", err)
}
values := endpoint.Query()
if recordType != "" {
values.Set("type", recordType)
}
endpoint.RawQuery = values.Encode()
req, err := http.NewRequest(http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
raw, err := c.do(req)
if err != nil {
return nil, err
}
var r []Record
err = json.Unmarshal(raw, &r)
if err != nil {
return nil, fmt.Errorf("unmarshal response data: %s: %w", string(raw), err)
}
return r, nil
}
// AddRecord Adds a new record to the zone and returns the newly created record.
// https://api.ns1.hosttech.eu/api/documentation/#/Records/post_api_user_v1_zones__zoneId__records
func (c Client) AddRecord(zoneID string, record Record) (*Record, error) {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "user", "v1", "zones", zoneID, "records"))
if err != nil {
return nil, fmt.Errorf("parse URL: %w", err)
}
body, err := json.Marshal(record)
if err != nil {
return nil, fmt.Errorf("marshal request data: %w", err)
}
req, err := http.NewRequest(http.MethodPost, endpoint.String(), bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
raw, err := c.do(req)
if err != nil {
return nil, err
}
var r Record
err = json.Unmarshal(raw, &r)
if err != nil {
return nil, fmt.Errorf("unmarshal response data: %s: %w", string(raw), err)
}
return &r, nil
}
// DeleteRecord Deletes a single record for the given id.
// https://api.ns1.hosttech.eu/api/documentation/#/Records/delete_api_user_v1_zones__zoneId__records__recordId_
func (c Client) DeleteRecord(zoneID, recordID string) error {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "user", "v1", "zones", zoneID, "records", recordID))
if err != nil {
return fmt.Errorf("parse URL: %w", err)
}
req, err := http.NewRequest(http.MethodDelete, endpoint.String(), nil)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
_, err = c.do(req)
return err
}
func (c Client) do(req *http.Request) (json.RawMessage, error) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))
resp, errD := c.HTTPClient.Do(req)
if errD != nil {
return nil, fmt.Errorf("send request: %w", errD)
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated:
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
var r apiResponse
err = json.Unmarshal(all, &r)
if err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
return r.Data, nil
case http.StatusNoContent:
return nil, nil
default:
data, _ := ioutil.ReadAll(resp.Body)
e := APIError{StatusCode: resp.StatusCode}
err := json.Unmarshal(data, &e)
if err != nil {
e.Message = string(data)
}
return nil, e
}
}

View file

@ -0,0 +1,262 @@
package internal
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const testAPIKey = "secret"
func TestClient_GetZones(t *testing.T) {
client := setupTest(t, "/user/v1/zones", testHandler(http.MethodGet, http.StatusOK, "zones.json"))
zones, err := client.GetZones("", 100, 0)
require.NoError(t, err)
expected := []Zone{
{
ID: 10,
Name: "user1.ch",
Email: "test@hosttech.ch",
TTL: 10800,
Nameserver: "ns1.hosttech.ch",
Dnssec: false,
DnssecEmail: "test@hosttech.ch",
},
}
assert.Equal(t, expected, zones)
}
func TestClient_GetZones_error(t *testing.T) {
client := setupTest(t, "/user/v1/zones", testHandler(http.MethodGet, http.StatusUnauthorized, "error.json"))
_, err := client.GetZones("", 100, 0)
require.Error(t, err)
}
func TestClient_GetZone(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123", testHandler(http.MethodGet, http.StatusOK, "zone.json"))
zone, err := client.GetZone("123")
require.NoError(t, err)
expected := &Zone{
ID: 10,
Name: "user1.ch",
Email: "test@hosttech.ch",
TTL: 10800,
Nameserver: "ns1.hosttech.ch",
Dnssec: false,
DnssecEmail: "test@hosttech.ch",
}
assert.Equal(t, expected, zone)
}
func TestClient_GetZone_error(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123", testHandler(http.MethodGet, http.StatusUnauthorized, "error.json"))
_, err := client.GetZone("123")
require.Error(t, err)
}
func TestClient_GetRecords(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123/records", testHandler(http.MethodGet, http.StatusOK, "records.json"))
records, err := client.GetRecords("123", "TXT")
require.NoError(t, err)
expected := []Record{
{
ID: 10,
Type: "A",
Name: "www",
TTL: 3600,
Comment: "my first record",
},
{
ID: 11,
Type: "AAAA",
Name: "www",
TTL: 3600,
Comment: "my first record",
},
{
ID: 12,
Type: "CAA",
TTL: 3600,
Comment: "my first record",
},
{
ID: 13,
Type: "CNAME",
Name: "www",
TTL: 3600,
Comment: "my first record",
},
{
ID: 14,
Type: "MX",
Name: "mail.example.com",
TTL: 3600,
Comment: "my first record",
},
{
ID: 14,
Type: "NS",
Name: "ns1.example.com",
TTL: 3600,
Comment: "my first record",
},
{
ID: 15,
Type: "PTR",
Name: "smtp.example.com",
TTL: 3600,
Comment: "my first record",
},
{
ID: 16,
Type: "SRV",
TTL: 3600,
Comment: "my first record",
},
{
ID: 17,
Type: "TXT",
Text: "v=spf1 ip4:1.2.3.4/32 -all",
TTL: 3600,
Comment: "my first record",
},
{
ID: 17,
Type: "TLSA",
Text: "0 0 1 d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971",
TTL: 3600,
Comment: "my first record",
},
}
assert.Equal(t, expected, records)
}
func TestClient_GetRecords_error(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123/records", testHandler(http.MethodGet, http.StatusUnauthorized, "error.json"))
_, err := client.GetRecords("123", "TXT")
require.Error(t, err)
}
func TestClient_AddRecord(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123/records", testHandler(http.MethodPost, http.StatusCreated, "record.json"))
record := Record{
Type: "TXT",
Name: "lego",
Text: "content",
TTL: 3600,
Comment: "example",
}
newRecord, err := client.AddRecord("123", record)
require.NoError(t, err)
expected := &Record{
ID: 10,
Type: "TXT",
Name: "lego",
Text: "content",
TTL: 3600,
Comment: "example",
}
assert.Equal(t, expected, newRecord)
}
func TestClient_AddRecord_error(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123/records", testHandler(http.MethodPost, http.StatusUnauthorized, "error-details.json"))
record := Record{
Type: "TXT",
Name: "lego",
Text: "content",
TTL: 3600,
Comment: "example",
}
_, err := client.AddRecord("123", record)
require.Error(t, err)
}
func TestClient_DeleteRecord(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123/records/6", testHandler(http.MethodDelete, http.StatusUnauthorized, "error.json"))
err := client.DeleteRecord("123", "6")
require.Error(t, err)
}
func TestClient_DeleteRecord_error(t *testing.T) {
client := setupTest(t, "/user/v1/zones/123/records/6", testHandler(http.MethodDelete, http.StatusNoContent, ""))
err := client.DeleteRecord("123", "6")
require.NoError(t, err)
}
func setupTest(t *testing.T, path string, handler http.Handler) *Client {
t.Helper()
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.Handle(path, handler)
client := NewClient(testAPIKey)
client.baseURL, _ = url.Parse(server.URL)
return client
}
func testHandler(method string, statusCode int, filename string) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if req.Method != method {
http.Error(rw, fmt.Sprintf(`{"message":"unsupported method: %s"}`, req.Method), http.StatusMethodNotAllowed)
return
}
if req.Header.Get("Authorization") != "Bearer "+testAPIKey {
http.Error(rw, `{"message":"Unauthenticated"}`, http.StatusUnauthorized)
return
}
rw.WriteHeader(statusCode)
if statusCode == http.StatusNoContent {
return
}
file, err := os.Open(filepath.Join("fixtures", filename))
if err != nil {
http.Error(rw, fmt.Sprintf(`{"message":"%v"}`, err), http.StatusInternalServerError)
return
}
defer func() { _ = file.Close() }()
_, err = io.Copy(rw, file)
if err != nil {
http.Error(rw, fmt.Sprintf(`{"message":"%v"}`, err), http.StatusInternalServerError)
return
}
}
}

View file

@ -0,0 +1,8 @@
{
"message": "The given data was invalid.",
"errors": {
"type": [
"Darf nicht leer sein."
]
}
}

View file

@ -0,0 +1,3 @@
{
"message": "Unauthenticated."
}

View file

@ -0,0 +1,10 @@
{
"data": {
"id": 10,
"type": "TXT",
"name": "lego",
"Text": "content",
"ttl": 3600,
"comment": "example"
}
}

View file

@ -0,0 +1,90 @@
{
"data": [
{
"id": 10,
"type": "A",
"name": "www",
"ipv4": "1.2.3.4",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 11,
"type": "AAAA",
"name": "www",
"ipv6": "2001:db8:1234::1",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 12,
"type": "CAA",
"name": "",
"flag": "0",
"tag": "issue",
"value": "letsencrypt.org",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 13,
"type": "CNAME",
"name": "www",
"cname": "site.example.com",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 14,
"type": "MX",
"ownername": "",
"name": "mail.example.com",
"pref": 10,
"ttl": 3600,
"comment": "my first record"
},
{
"id": 14,
"type": "NS",
"ownername": "sub",
"name": "ns1.example.com",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 15,
"type": "PTR",
"origin": "4.3.2.1",
"name": "smtp.example.com",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 16,
"type": "SRV",
"service": "_autodiscover._tcp",
"priority": 0,
"weight": 0,
"port": 443,
"target": "exchange.example.com",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 17,
"type": "TXT",
"name": "",
"text": "v=spf1 ip4:1.2.3.4/32 -all",
"ttl": 3600,
"comment": "my first record"
},
{
"id": 17,
"type": "TLSA",
"name": "",
"text": "0 0 1 d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971",
"ttl": 3600,
"comment": "my first record"
}
]
}

View file

@ -0,0 +1,13 @@
{
"data": {
"id": 10,
"name": "user1.ch",
"email": "test@hosttech.ch",
"ttl": 10800,
"nameserver": "ns1.hosttech.ch",
"dnssec": false,
"dnssec_email": "test@hosttech.ch",
"ds_records": "[]",
"records": "[{'id': 10, 'type': 'A', 'name': 'www', 'ipv4': '1.2.3.4', 'ttl': 3600, 'comment': 'my first record'}]"
}
}

View file

@ -0,0 +1,13 @@
{
"data": [
{
"id": 10,
"name": "user1.ch",
"email": "test@hosttech.ch",
"ttl": 10800,
"nameserver": "ns1.hosttech.ch",
"dnssec": false,
"dnssec_email": "test@hosttech.ch"
}
]
}

View file

@ -0,0 +1,44 @@
package internal
import (
"encoding/json"
"fmt"
)
type apiResponse struct {
Data json.RawMessage `json:"data"`
}
type APIError struct {
Message string `json:"message,omitempty"`
Errors map[string]interface{} `json:"errors,omitempty"`
StatusCode int `json:"-"`
}
func (a APIError) Error() string {
msg := fmt.Sprintf("%d: %s", a.StatusCode, a.Message)
for k, v := range a.Errors {
msg += fmt.Sprintf(" %s: %v", k, v)
}
return msg
}
type Zone struct {
ID int `json:"id"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
TTL int `json:"ttl,omitempty"`
Nameserver string `json:"nameserver,omitempty"`
Dnssec bool `json:"dnssec,omitempty"`
DnssecEmail string `json:"dnssec_email,omitempty"`
}
type Record struct {
ID int `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
Zone string `json:"zone,omitempty"`
Text string `json:"text,omitempty"`
TTL int `json:"ttl,omitempty"`
Comment string `json:"comment,omitempty"`
}

View file

@ -67,19 +67,6 @@ func TestNewDNSProvider(t *testing.T) {
}
}
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 TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
@ -128,6 +115,19 @@ func TestNewDNSProviderConfig(t *testing.T) {
}
}
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")