Skip to content

Commit

Permalink
Add DNS provider for Abion
Browse files Browse the repository at this point in the history
  • Loading branch information
ldez committed Oct 26, 2024
1 parent e3ec3c2 commit 7a2ab9e
Show file tree
Hide file tree
Showing 10 changed files with 976 additions and 0 deletions.
206 changes: 206 additions & 0 deletions providers/dns/abion/abion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
// Package abion implements a DNS provider for solving the DNS-01 challenge using Abion.
package abion

import (
"context"
"errors"
"fmt"
"net/http"
"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/abion/internal"
)

// Environment variables names.
const (
envNamespace = "ABION_"

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, dns01.DefaultTTL),
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 10*time.Second),
},
}
}

// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
config *Config
client *internal.Client
}

// NewDNSProvider returns a DNSProvider instance configured for Abion.
// Credentials must be passed in the environment variable: ABION_API_KEY.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvAPIKey)
if err != nil {
return nil, fmt.Errorf("abion: %w", err)
}

config := NewDefaultConfig()
config.APIKey = values[EnvAPIKey]

return NewDNSProviderConfig(config)
}

// NewDNSProviderConfig return a DNSProvider instance configured for Abion.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("abion: the configuration of the DNS provider is nil")
}

if config.APIKey == "" {
return nil, errors.New("abion: credentials missing")
}

client := internal.NewClient(config.APIKey)

if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}

return &DNSProvider{
config: config,
client: client,
}, nil
}

// Timeout returns the timeout and interval to use when checking for DNS propagation.
// Adjusting here to cope with spikes in propagation times.
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
return d.config.PropagationTimeout, d.config.PollingInterval
}

// Present creates a TXT record to fulfill the dns-01 challenge.
func (d *DNSProvider) Present(domain, _, keyAuth string) error {
ctx := context.Background()
info := dns01.GetChallengeInfo(domain, keyAuth)

authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("abion: could not find zone for domain %q: %w", domain, err)
}

subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
if err != nil {
return fmt.Errorf("abion: %w", err)
}

zones, err := d.client.GetZone(ctx, dns01.UnFqdn(authZone))
if err != nil {
return fmt.Errorf("abion: get zone %w", err)
}

var data []internal.Record
if sub, ok := zones.Data.Attributes.Records[subDomain]; ok {
if records, exist := sub["TXT"]; exist {
data = append(data, records...)
}
}

data = append(data, internal.Record{
TTL: d.config.TTL,
Data: info.Value,
Comments: "lego",
})

patch := internal.ZoneRequest{
Data: internal.Zone{
Type: "zone",
ID: dns01.UnFqdn(authZone),
Attributes: internal.Attributes{
Records: map[string]map[string][]internal.Record{
subDomain: {"TXT": data},
},
},
},
}

_, err = d.client.UpdateZone(ctx, dns01.UnFqdn(authZone), patch)
if err != nil {
return fmt.Errorf("abion: update zone %w", err)
}

return nil
}

// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
ctx := context.Background()
info := dns01.GetChallengeInfo(domain, keyAuth)

authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("abion: could not find zone for domain %q: %w", domain, err)
}

subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
if err != nil {
return fmt.Errorf("abion: %w", err)
}

zones, err := d.client.GetZone(ctx, dns01.UnFqdn(authZone))
if err != nil {
return fmt.Errorf("abion: get zone %w", err)
}

var data []internal.Record
if sub, ok := zones.Data.Attributes.Records[subDomain]; ok {
if records, exist := sub["TXT"]; exist {
for _, record := range records {
if record.Data != info.Value {
data = append(data, record)
}
}
}
}

payload := map[string][]internal.Record{}
if len(data) == 0 {
payload["TXT"] = nil
} else {
payload["TXT"] = data
}

patch := internal.ZoneRequest{
Data: internal.Zone{
Type: "zone",
ID: dns01.UnFqdn(authZone),
Attributes: internal.Attributes{
Records: map[string]map[string][]internal.Record{
subDomain: payload,
},
},
},
}

_, err = d.client.UpdateZone(ctx, dns01.UnFqdn(authZone), patch)
if err != nil {
return fmt.Errorf("abion: update zone %w", err)
}

return nil
}
22 changes: 22 additions & 0 deletions providers/dns/abion/abion.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Name = "Abion"
Description = ''''''
URL = "https://abion.com"
Code = "abion"
Since = "v4.20.0"

Example = '''
ABION_API_KEY="xxxxxxxxxxxx" \
lego --email [email protected] --dns abion --domains my.example.org run
'''

[Configuration]
[Configuration.Credentials]
ABION_API_KEY = "API key"
[Configuration.Additional]
ABION_POLLING_INTERVAL = "Time between DNS propagation check"
ABION_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
ABION_TTL = "The TTL of the TXT record used for the DNS challenge"
ABION_HTTP_TIMEOUT = "API request timeout"

[Links]
API = "https://demo.abion.com/pmapi-doc/openapi-ui/index.html"
115 changes: 115 additions & 0 deletions providers/dns/abion/abion_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package abion

import (
"testing"

"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: "123",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
EnvAPIKey: "",
},
expected: "abion: some credentials information are missing: ABION_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)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}

func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiKey string
ttl int
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "abion: credentials missing",
},
}

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 test.expected == "" {
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)
}
Loading

0 comments on commit 7a2ab9e

Please sign in to comment.