diff --git a/providers/dns/hostingnl/hostingnl.go b/providers/dns/hostingnl/hostingnl.go new file mode 100644 index 0000000000..bbcf02543e --- /dev/null +++ b/providers/dns/hostingnl/hostingnl.go @@ -0,0 +1,161 @@ +// Package hostingnl implements a DNS provider for solving the DNS-01 challenge using hosting.nl. +package hostingnl + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "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/hostingnl/internal" +) + +// Environment variables names. +const ( + envNamespace = "HOSTINGNL_" + + 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 + HTTPClient *http.Client + PropagationTimeout time.Duration + PollingInterval time.Duration + TTL int +} + +// 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 + + recordIDs map[string]string + recordIDsMu sync.Mutex +} + +// NewDNSProvider returns a DNSProvider instance configured for hosting.nl. +// Credentials must be passed in the environment variables: +// HOSTINGNL_APIKEY. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey) + if err != nil { + return nil, fmt.Errorf("hostingnl: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for hosting.nl. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("hostingnl: the configuration of the DNS provider is nil") + } + + if config.APIKey == "" { + return nil, errors.New("hostingnl: APIKey is missing") + } + + 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 +} + +// Present creates a TXT record using the specified parameters. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("hostingnl: could not find zone for domain %q: %w", domain, err) + } + + record := internal.Record{ + Name: info.EffectiveFQDN, + Type: "TXT", + Content: strconv.Quote(info.Value), + TTL: strconv.Itoa(d.config.TTL), + Priority: "0", + } + + newRecord, err := d.client.AddRecord(context.Background(), dns01.UnFqdn(authZone), record) + if err != nil { + return fmt.Errorf("hostingnl: failed to create TXT record, fqdn=%s: %w", info.EffectiveFQDN, err) + } + + d.recordIDsMu.Lock() + d.recordIDs[token] = newRecord.ID + d.recordIDsMu.Unlock() + + return nil +} + +// CleanUp removes the TXT records matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("hostingnl: could not find zone for domain %q: %w", domain, err) + } + + // gets the record's unique ID + d.recordIDsMu.Lock() + recordID, ok := d.recordIDs[token] + d.recordIDsMu.Unlock() + if !ok { + return fmt.Errorf("hostingnl: unknown record ID for '%s' '%s'", info.EffectiveFQDN, token) + } + + err = d.client.DeleteRecord(context.Background(), dns01.UnFqdn(authZone), recordID) + if err != nil { + return fmt.Errorf("hostingnl: failed to delete TXT record, id=%s: %w", recordID, err) + } + + // deletes record ID from map + d.recordIDsMu.Lock() + delete(d.recordIDs, token) + d.recordIDsMu.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 +} diff --git a/providers/dns/hostingnl/hostingnl.toml b/providers/dns/hostingnl/hostingnl.toml new file mode 100644 index 0000000000..c1f084ce6a --- /dev/null +++ b/providers/dns/hostingnl/hostingnl.toml @@ -0,0 +1,22 @@ +Name = "Hosting.nl" +Description = '''''' +URL = "https://hosting.nl" +Code = "hostingnl" +Since = "v4.20.0" + +Example = ''' +HOSTINGNL_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email you@example.com --dns hostingnl -d '*.example.com' -d example.com run +''' + +[Configuration] + [Configuration.Credentials] + HOSTINGNL_API_KEY = "The API key" + [Configuration.Additional] + HOSTINGNL_POLLING_INTERVAL = "Time between DNS propagation check" + HOSTINGNL_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + HOSTINGNL_TTL = "The TTL of the TXT record used for the DNS challenge" + HOSTINGNL_HTTP_TIMEOUT = "API request timeout" + +[Links] + API = "https://api.hosting.nl/api/documentation" diff --git a/providers/dns/hostingnl/hostingnl_test.go b/providers/dns/hostingnl/hostingnl_test.go new file mode 100644 index 0000000000..ca2a880806 --- /dev/null +++ b/providers/dns/hostingnl/hostingnl_test.go @@ -0,0 +1,113 @@ +package hostingnl + +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: "key", + }, + }, + { + desc: "missing API key", + envVars: map[string]string{}, + expected: "hostingnl: some credentials information are missing: HOSTINGNL_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: "key", + }, + { + desc: "missing API key", + expected: "hostingnl: APIKey is missing", + }, + } + + 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) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} diff --git a/providers/dns/hostingnl/internal/client.go b/providers/dns/hostingnl/internal/client.go new file mode 100644 index 0000000000..2d3f83f339 --- /dev/null +++ b/providers/dns/hostingnl/internal/client.go @@ -0,0 +1,146 @@ +package internal + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" +) + +const defaultBaseURL = "https://api.hosting.nl" + +type Client struct { + apiKey string + + baseURL *url.URL + HTTPClient *http.Client +} + +func NewClient(apiKey string) *Client { + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + apiKey: apiKey, + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 5 * time.Second}, + } +} + +func (c Client) AddRecord(ctx context.Context, domain string, record Record) (*Record, error) { + endpoint := c.baseURL.JoinPath("domains", domain, "dns") + + query := endpoint.Query() + query.Set("client_id", "0") + endpoint.RawQuery = query.Encode() + + req, err := newJSONRequest(ctx, http.MethodPost, endpoint, []Record{record}) + if err != nil { + return nil, err + } + + var result APIResponse[Record] + err = c.do(req, &result) + if err != nil { + return nil, err + } + + if len(result.Data) != 1 { + return nil, fmt.Errorf("unexpected response data: %s", result.Data) + } + + return &result.Data[0], nil +} + +func (c Client) DeleteRecord(ctx context.Context, domain string, recordID string) error { + endpoint := c.baseURL.JoinPath("domains", domain, "dns") + + query := endpoint.Query() + query.Set("client_id", "0") + endpoint.RawQuery = query.Encode() + + req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, []Record{{ID: recordID}}) + if err != nil { + return err + } + + var result APIResponse[Record] + err = c.do(req, &result) + if err != nil { + return err + } + + return nil +} + +func (c Client) do(req *http.Request, result any) error { + req.Header.Set("API-TOKEN", c.apiKey) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + return parseError(req, resp) + } + + if result == nil { + return nil + } + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return errutils.NewReadResponseError(req, resp.StatusCode, err) + } + + err = json.Unmarshal(raw, result) + if err != nil { + return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err) + } + + return nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + var apiErr APIError + err := json.Unmarshal(raw, &apiErr) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return fmt.Errorf("[status code: %d] %w", resp.StatusCode, apiErr) +} + +func newJSONRequest(ctx context.Context, method string, endpoint *url.URL, payload any) (*http.Request, error) { + buf := new(bytes.Buffer) + + if payload != nil { + err := json.NewEncoder(buf).Encode(payload) + if err != nil { + return nil, fmt.Errorf("failed to create request JSON body: %w", err) + } + } + + req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + + return req, nil +} diff --git a/providers/dns/hostingnl/internal/client_test.go b/providers/dns/hostingnl/internal/client_test.go new file mode 100644 index 0000000000..358871efd0 --- /dev/null +++ b/providers/dns/hostingnl/internal/client_test.go @@ -0,0 +1,100 @@ +package internal + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T, method string, status int, filename string) *Client { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + mux.HandleFunc("/domains/example.com/dns", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != method { + http.Error(rw, fmt.Sprintf("unsupported method %s", req.Method), http.StatusBadRequest) + return + } + + open, err := os.Open(filepath.Join("fixtures", filename)) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + + defer func() { _ = open.Close() }() + + rw.WriteHeader(status) + _, err = io.Copy(rw, open) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + client := NewClient("secret") + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client +} + +func TestClient_AddRecord(t *testing.T) { + client := setupTest(t, http.MethodPost, http.StatusOK, "add-record.json") + + record := Record{ + Name: "example.com", + Type: "TXT", + Content: strconv.Quote("txtxtxt"), + TTL: "3600", + Priority: "0", + } + + newRecord, err := client.AddRecord(context.Background(), "example.com", record) + require.NoError(t, err) + + expected := &Record{ + ID: "12345", + Name: "example.com", + Type: "TXT", + Content: `"txtxtxt"`, + TTL: "3600", + Priority: "0", + } + + assert.Equal(t, expected, newRecord) +} + +func TestClient_DeleteRecord(t *testing.T) { + client := setupTest(t, http.MethodDelete, http.StatusOK, "delete-record.json") + + err := client.DeleteRecord(context.Background(), "example.com", "12345") + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client := setupTest(t, http.MethodDelete, http.StatusUnauthorized, "error.json") + + err := client.DeleteRecord(context.Background(), "example.com", "12345") + require.Error(t, err) +} + +func TestClient_DeleteRecord_error_other(t *testing.T) { + client := setupTest(t, http.MethodDelete, http.StatusNotFound, "error-other.json") + + err := client.DeleteRecord(context.Background(), "example.com", "12345") + require.Error(t, err) +} diff --git a/providers/dns/hostingnl/internal/fixtures/add-record.json b/providers/dns/hostingnl/internal/fixtures/add-record.json new file mode 100644 index 0000000000..aa8551d3fa --- /dev/null +++ b/providers/dns/hostingnl/internal/fixtures/add-record.json @@ -0,0 +1,13 @@ +{ + "success": true, + "data": [ + { + "id": "12345", + "type": "TXT", + "content": "\"txtxtxt\"", + "name": "example.com", + "prio": "0", + "ttl": "3600" + } + ] +} diff --git a/providers/dns/hostingnl/internal/fixtures/delete-record.json b/providers/dns/hostingnl/internal/fixtures/delete-record.json new file mode 100644 index 0000000000..c041c1f6d4 --- /dev/null +++ b/providers/dns/hostingnl/internal/fixtures/delete-record.json @@ -0,0 +1,8 @@ +{ + "success": true, + "data": [ + { + "id": "12345" + } + ] +} diff --git a/providers/dns/hostingnl/internal/fixtures/error-other.json b/providers/dns/hostingnl/internal/fixtures/error-other.json new file mode 100644 index 0000000000..ca7ecab281 --- /dev/null +++ b/providers/dns/hostingnl/internal/fixtures/error-other.json @@ -0,0 +1,3 @@ +{ + "error": "Resource not found" +} diff --git a/providers/dns/hostingnl/internal/fixtures/error.json b/providers/dns/hostingnl/internal/fixtures/error.json new file mode 100644 index 0000000000..170587246d --- /dev/null +++ b/providers/dns/hostingnl/internal/fixtures/error.json @@ -0,0 +1,5 @@ +{ + "errors": { + "message": "Something went wrong" + } +} diff --git a/providers/dns/hostingnl/internal/types.go b/providers/dns/hostingnl/internal/types.go new file mode 100644 index 0000000000..493e905683 --- /dev/null +++ b/providers/dns/hostingnl/internal/types.go @@ -0,0 +1,36 @@ +package internal + +type Record struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + Content string `json:"content,omitempty"` + TTL string `json:"ttl,omitempty"` + Priority string `json:"prio,omitempty"` +} + +type APIResponse[T any] struct { + Success bool `json:"success"` + Data []T `json:"data"` +} + +type APIError struct { + ErrorMsg string `json:"error"` + Errors Error `json:"errors"` +} + +func (e APIError) Error() string { + if e.ErrorMsg != "" { + return e.ErrorMsg + } + + return e.Errors.Error() +} + +type Error struct { + Message string `json:"message"` +} + +func (e Error) Error() string { + return e.Message +} diff --git a/providers/dns/zz_gen_dns_providers.go b/providers/dns/zz_gen_dns_providers.go index 63f16db94e..887f886561 100644 --- a/providers/dns/zz_gen_dns_providers.go +++ b/providers/dns/zz_gen_dns_providers.go @@ -61,6 +61,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/googledomains" "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/hostingnl" "github.com/go-acme/lego/v4/providers/dns/hosttech" "github.com/go-acme/lego/v4/providers/dns/httpnet" "github.com/go-acme/lego/v4/providers/dns/httpreq" @@ -262,6 +263,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return hetzner.NewDNSProvider() case "hostingde": return hostingde.NewDNSProvider() + case "hostingnl": + return hostingnl.NewDNSProvider() case "hosttech": return hosttech.NewDNSProvider() case "httpnet":