mirror of
https://github.com/go-acme/lego
synced 2026-03-14 14:35:48 +01:00
Add DNS provider for Ionos Cloud (#2752)
Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
parent
bb5e70a4e5
commit
e21ba75da8
15 changed files with 979 additions and 24 deletions
172
providers/dns/ionoscloud/internal/client.go
Normal file
172
providers/dns/ionoscloud/internal/client.go
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
package internal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
|
||||
"github.com/go-acme/lego/v4/providers/dns/internal/useragent"
|
||||
)
|
||||
|
||||
const defaultBaseURL = "https://dns.de-fra.ionos.com"
|
||||
|
||||
const authorizationHeader = "Authorization"
|
||||
|
||||
// Client the Ionos Cloud API client.
|
||||
type Client struct {
|
||||
apiKey string
|
||||
|
||||
BaseURL *url.URL
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
// NewClient creates a new Client.
|
||||
func NewClient(apiKey string) (*Client, error) {
|
||||
if apiKey == "" {
|
||||
return nil, errors.New("credentials missing")
|
||||
}
|
||||
|
||||
baseURL, _ := url.Parse(defaultBaseURL)
|
||||
|
||||
return &Client{
|
||||
apiKey: apiKey,
|
||||
BaseURL: baseURL,
|
||||
HTTPClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RetrieveZones returns a list of the DNS zones.
|
||||
// https://api.ionos.com/docs/dns/v1/#tag/Zones/operation/zonesGet
|
||||
func (c *Client) RetrieveZones(ctx context.Context, zoneName string) ([]Zone, error) {
|
||||
endpoint := c.BaseURL.JoinPath("zones")
|
||||
|
||||
req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := req.URL.Query()
|
||||
query.Add("filter.zoneName", zoneName)
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
result := ZonesResponse{}
|
||||
|
||||
if err := c.do(req, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result.Items, nil
|
||||
}
|
||||
|
||||
// CreateRecord creates a new record for the DNS zone.
|
||||
// https://api.ionos.com/docs/dns/v1/#tag/Records/operation/zonesRecordsPost
|
||||
func (c *Client) CreateRecord(ctx context.Context, zoneID string, record RecordProperties) (*RecordResponse, error) {
|
||||
endpoint := c.BaseURL.JoinPath("zones", zoneID, "records")
|
||||
|
||||
payload := map[string]RecordProperties{
|
||||
"properties": record,
|
||||
}
|
||||
|
||||
req, err := newJSONRequest(ctx, http.MethodPost, endpoint, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := &RecordResponse{}
|
||||
|
||||
if err := c.do(req, result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DeleteRecord deletes a specified record from the DNS zone.
|
||||
// https://api.ionos.com/docs/dns/v1/#tag/Records/operation/zonesRecordsDelete
|
||||
func (c *Client) DeleteRecord(ctx context.Context, zoneID, recordID string) error {
|
||||
endpoint := c.BaseURL.JoinPath("zones", zoneID, "records", recordID)
|
||||
|
||||
req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.do(req, nil)
|
||||
}
|
||||
|
||||
func (c *Client) do(req *http.Request, result any) error {
|
||||
useragent.SetHeader(req.Header)
|
||||
|
||||
req.Header.Set(authorizationHeader, "Bearer "+c.apiKey)
|
||||
|
||||
resp, err := c.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return errutils.NewHTTPDoError(req, err)
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode/100 != 2 {
|
||||
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 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
|
||||
}
|
||||
|
||||
func parseError(req *http.Request, resp *http.Response) error {
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
|
||||
var errAPI APIError
|
||||
|
||||
err := json.Unmarshal(raw, &errAPI)
|
||||
if err != nil {
|
||||
return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
return &errAPI
|
||||
}
|
||||
134
providers/dns/ionoscloud/internal/client_test.go
Normal file
134
providers/dns/ionoscloud/internal/client_test.go
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
package internal
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/platform/tester/servermock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func mockBuilder() *servermock.Builder[*Client] {
|
||||
return servermock.NewBuilder[*Client](
|
||||
func(server *httptest.Server) (*Client, error) {
|
||||
client, err := NewClient("secret")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client.BaseURL, _ = url.Parse(server.URL)
|
||||
client.HTTPClient = server.Client()
|
||||
|
||||
return client, nil
|
||||
},
|
||||
servermock.CheckHeader().
|
||||
WithJSONHeaders().
|
||||
WithAuthorization("Bearer secret"),
|
||||
)
|
||||
}
|
||||
|
||||
func TestClient_RetrieveZones(t *testing.T) {
|
||||
client := mockBuilder().
|
||||
Route("GET /zones",
|
||||
servermock.ResponseFromFixture("zones.json"),
|
||||
servermock.CheckQueryParameter().Strict().
|
||||
With("filter.zoneName", "example.com")).
|
||||
Build(t)
|
||||
|
||||
zones, err := client.RetrieveZones(t.Context(), "example.com")
|
||||
require.NoError(t, err)
|
||||
|
||||
expected := []Zone{{
|
||||
ID: "e74d0d15-f567-4b7b-9069-26ee1f93bae3",
|
||||
Type: "zone",
|
||||
Metadata: ZoneMetadata{
|
||||
CreatedDate: time.Date(2022, time.August, 21, 15, 52, 53, 0, time.UTC),
|
||||
CreatedBy: "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
CreatedByUserID: "87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
LastModifiedDate: time.Date(2022, time.August, 21, 15, 52, 53, 0, time.UTC),
|
||||
LastModifiedBy: "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
LastModifiedByUserID: "63cef532-26fe-4a64-a4e0-de7c8a506c90",
|
||||
ResourceURN: "ionos:<product>:<location>:<contract>:<resource-path>",
|
||||
State: "PROVISIONING",
|
||||
Nameservers: []string{"ns-ic.ui-dns.com", "ns-ic.ui-dns.de", "ns-ic.ui-dns.org", "ns-ic.ui-dns.biz"},
|
||||
},
|
||||
Properties: ZoneProperties{
|
||||
ZoneName: "example.com",
|
||||
Description: "The hosted zone is used for example.com",
|
||||
Enabled: true,
|
||||
},
|
||||
}}
|
||||
|
||||
assert.Equal(t, expected, zones)
|
||||
}
|
||||
|
||||
func TestClient_RetrieveZones_error(t *testing.T) {
|
||||
client := mockBuilder().
|
||||
Route("GET /zones",
|
||||
servermock.ResponseFromFixture("error.json").
|
||||
WithStatusCode(http.StatusUnauthorized)).
|
||||
Build(t)
|
||||
|
||||
_, err := client.RetrieveZones(t.Context(), "example.com")
|
||||
require.EqualError(t, err, "401: paas-auth-1: Unauthorized, wrong or no api key provided to process this request")
|
||||
}
|
||||
|
||||
func TestClient_CreateRecord(t *testing.T) {
|
||||
client := mockBuilder().
|
||||
Route("POST /zones/abc/records",
|
||||
servermock.ResponseFromFixture("create_record.json"),
|
||||
servermock.CheckRequestJSONBodyFromFixture("create_record-request.json")).
|
||||
Build(t)
|
||||
|
||||
record := RecordProperties{
|
||||
Name: "_acme-challenge",
|
||||
Type: "TXT",
|
||||
Content: "ADw2sEd82DUgXcQ9hNBZThJs7zVJkR5v9JeSbAb9mZY",
|
||||
TTL: 120,
|
||||
}
|
||||
|
||||
result, err := client.CreateRecord(t.Context(), "abc", record)
|
||||
require.NoError(t, err)
|
||||
|
||||
expected := &RecordResponse{
|
||||
ID: "90d81ac0-3a30-44d4-95a5-12959effa6ee",
|
||||
Type: "record",
|
||||
Metadata: RecordMetadata{
|
||||
CreatedDate: time.Date(2022, time.August, 21, 15, 52, 53, 0, time.UTC),
|
||||
CreatedBy: "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
CreatedByUserID: "87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
LastModifiedDate: time.Date(2022, time.August, 21, 15, 52, 53, 0, time.UTC),
|
||||
LastModifiedBy: "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
LastModifiedByUserID: "63cef532-26fe-4a64-a4e0-de7c8a506c90",
|
||||
ResourceURN: "ionos:<product>:<location>:<contract>:<resource-path>",
|
||||
State: "PROVISIONING",
|
||||
Fqdn: "app.example.com",
|
||||
ZoneID: "a363f30c-4c0c-4552-9a07-298d87f219bf",
|
||||
},
|
||||
Properties: RecordProperties{
|
||||
Name: "app",
|
||||
Type: "A",
|
||||
Content: "1.2.3.4",
|
||||
TTL: 3600,
|
||||
Priority: 3600,
|
||||
Enabled: true,
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expected, result)
|
||||
}
|
||||
|
||||
func TestClient_DeleteRecord(t *testing.T) {
|
||||
client := mockBuilder().
|
||||
Route("DELETE /zones/abc/records/def",
|
||||
servermock.Noop().
|
||||
WithStatusCode(http.StatusAccepted)).
|
||||
Build(t)
|
||||
|
||||
err := client.DeleteRecord(t.Context(), "abc", "def")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"properties": {
|
||||
"name": "_acme-challenge",
|
||||
"type": "TXT",
|
||||
"content": "ADw2sEd82DUgXcQ9hNBZThJs7zVJkR5v9JeSbAb9mZY",
|
||||
"ttl": 120
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"id": "90d81ac0-3a30-44d4-95a5-12959effa6ee",
|
||||
"type": "record",
|
||||
"href": "<RESOURCE-URI>",
|
||||
"metadata": {
|
||||
"createdDate": "2022-08-21T15:52:53Z",
|
||||
"createdBy": "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
"createdByUserId": "87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
"lastModifiedDate": "2022-08-21T15:52:53Z",
|
||||
"lastModifiedBy": "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
"lastModifiedByUserId": "63cef532-26fe-4a64-a4e0-de7c8a506c90",
|
||||
"resourceURN": "ionos:<product>:<location>:<contract>:<resource-path>",
|
||||
"state": "PROVISIONING",
|
||||
"fqdn": "app.example.com",
|
||||
"zoneId": "a363f30c-4c0c-4552-9a07-298d87f219bf"
|
||||
},
|
||||
"properties": {
|
||||
"name": "app",
|
||||
"type": "A",
|
||||
"content": "1.2.3.4",
|
||||
"ttl": 3600,
|
||||
"priority": 3600,
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
9
providers/dns/ionoscloud/internal/fixtures/error.json
Normal file
9
providers/dns/ionoscloud/internal/fixtures/error.json
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"httpStatus": 401,
|
||||
"messages": [
|
||||
{
|
||||
"errorCode": "paas-auth-1",
|
||||
"message": "Unauthorized, wrong or no api key provided to process this request"
|
||||
}
|
||||
]
|
||||
}
|
||||
40
providers/dns/ionoscloud/internal/fixtures/zones.json
Normal file
40
providers/dns/ionoscloud/internal/fixtures/zones.json
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"id": "e74d0d15-f567-4b7b-9069-26ee1f93bae3",
|
||||
"type": "collection",
|
||||
"href": "<RESOURCE-URI>",
|
||||
"offset": 0,
|
||||
"limit": 1000,
|
||||
"_links": {
|
||||
"prev": "http://PREVIOUS-PAGE-URI",
|
||||
"self": "http://THIS-PAGE-URI",
|
||||
"next": "http://NEXT-PAGE-URI"
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "e74d0d15-f567-4b7b-9069-26ee1f93bae3",
|
||||
"type": "zone",
|
||||
"href": "<RESOURCE-URI>",
|
||||
"metadata": {
|
||||
"createdDate": "2022-08-21T15:52:53Z",
|
||||
"createdBy": "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
"createdByUserId": "87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
"lastModifiedDate": "2022-08-21T15:52:53Z",
|
||||
"lastModifiedBy": "ionos:iam:cloud:31960002:users/87f9a82e-b28d-49ed-9d04-fba2c0459cd3",
|
||||
"lastModifiedByUserId": "63cef532-26fe-4a64-a4e0-de7c8a506c90",
|
||||
"resourceURN": "ionos:<product>:<location>:<contract>:<resource-path>",
|
||||
"state": "PROVISIONING",
|
||||
"nameservers": [
|
||||
"ns-ic.ui-dns.com",
|
||||
"ns-ic.ui-dns.de",
|
||||
"ns-ic.ui-dns.org",
|
||||
"ns-ic.ui-dns.biz"
|
||||
]
|
||||
},
|
||||
"properties": {
|
||||
"zoneName": "example.com",
|
||||
"description": "The hosted zone is used for example.com",
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
97
providers/dns/ionoscloud/internal/types.go
Normal file
97
providers/dns/ionoscloud/internal/types.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type APIError struct {
|
||||
HTTPStatus int `json:"httpStatus"`
|
||||
Messages []ErrorMessage `json:"messages"`
|
||||
}
|
||||
|
||||
func (a *APIError) Error() string {
|
||||
var msg strings.Builder
|
||||
|
||||
msg.WriteString(strconv.Itoa(a.HTTPStatus))
|
||||
|
||||
for _, m := range a.Messages {
|
||||
msg.WriteString(": ")
|
||||
msg.WriteString(m.String())
|
||||
}
|
||||
|
||||
return msg.String()
|
||||
}
|
||||
|
||||
type ErrorMessage struct {
|
||||
ErrorCode string `json:"errorCode"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e ErrorMessage) String() string {
|
||||
return fmt.Sprintf("%s: %s", e.ErrorCode, e.Message)
|
||||
}
|
||||
|
||||
type ZonesResponse struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Offset int `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
Items []Zone `json:"items"`
|
||||
}
|
||||
|
||||
type Zone struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Metadata ZoneMetadata `json:"metadata"`
|
||||
Properties ZoneProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type ZoneMetadata struct {
|
||||
CreatedDate time.Time `json:"createdDate"`
|
||||
CreatedBy string `json:"createdBy"`
|
||||
CreatedByUserID string `json:"createdByUserId"`
|
||||
LastModifiedDate time.Time `json:"lastModifiedDate"`
|
||||
LastModifiedBy string `json:"lastModifiedBy"`
|
||||
LastModifiedByUserID string `json:"lastModifiedByUserId"`
|
||||
ResourceURN string `json:"resourceURN"`
|
||||
State string `json:"state"`
|
||||
Nameservers []string `json:"nameservers"`
|
||||
}
|
||||
|
||||
type ZoneProperties struct {
|
||||
ZoneName string `json:"zoneName"`
|
||||
Description string `json:"description"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type RecordResponse struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Metadata RecordMetadata `json:"metadata"`
|
||||
Properties RecordProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type RecordMetadata struct {
|
||||
CreatedDate time.Time `json:"createdDate"`
|
||||
CreatedBy string `json:"createdBy"`
|
||||
CreatedByUserID string `json:"createdByUserId"`
|
||||
LastModifiedDate time.Time `json:"lastModifiedDate"`
|
||||
LastModifiedBy string `json:"lastModifiedBy"`
|
||||
LastModifiedByUserID string `json:"lastModifiedByUserId"`
|
||||
ResourceURN string `json:"resourceURN"`
|
||||
State string `json:"state"`
|
||||
Fqdn string `json:"fqdn"`
|
||||
ZoneID string `json:"zoneId"`
|
||||
}
|
||||
|
||||
type RecordProperties struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
TTL int `json:"ttl,omitempty"`
|
||||
Priority int `json:"priority,omitempty"`
|
||||
Enabled bool `json:"enabled,omitempty"`
|
||||
}
|
||||
184
providers/dns/ionoscloud/ionoscloud.go
Normal file
184
providers/dns/ionoscloud/ionoscloud.go
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// Package ionoscloud implements a DNS provider for solving the DNS-01 challenge using Ionos Cloud.
|
||||
package ionoscloud
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"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/internal/clientdebug"
|
||||
"github.com/go-acme/lego/v4/providers/dns/ionoscloud/internal"
|
||||
)
|
||||
|
||||
// Environment variables names.
|
||||
const (
|
||||
envNamespace = "IONOSCLOUD_"
|
||||
|
||||
EnvAPIToken = envNamespace + "API_TOKEN"
|
||||
|
||||
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 {
|
||||
APIToken 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, 120*time.Second),
|
||||
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
|
||||
|
||||
zoneIDs map[string]string
|
||||
recordIDs map[string]string
|
||||
recordIDsMu sync.Mutex
|
||||
}
|
||||
|
||||
// NewDNSProvider returns a DNSProvider instance configured for Ionos Cloud.
|
||||
func NewDNSProvider() (*DNSProvider, error) {
|
||||
values, err := env.Get(EnvAPIToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ionoscloud: %w", err)
|
||||
}
|
||||
|
||||
config := NewDefaultConfig()
|
||||
config.APIToken = values[EnvAPIToken]
|
||||
|
||||
return NewDNSProviderConfig(config)
|
||||
}
|
||||
|
||||
// NewDNSProviderConfig return a DNSProvider instance configured for Ionos Cloud.
|
||||
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("ionoscloud: the configuration of the DNS provider is nil")
|
||||
}
|
||||
|
||||
client, err := internal.NewClient(config.APIToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ionoscloud: %w", err)
|
||||
}
|
||||
|
||||
if config.HTTPClient != nil {
|
||||
client.HTTPClient = config.HTTPClient
|
||||
}
|
||||
|
||||
client.HTTPClient = clientdebug.Wrap(client.HTTPClient)
|
||||
|
||||
return &DNSProvider{
|
||||
config: config,
|
||||
client: client,
|
||||
zoneIDs: make(map[string]string),
|
||||
recordIDs: make(map[string]string),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Present creates a TXT record using the specified parameters.
|
||||
func (d *DNSProvider) Present(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("ionoscloud: could not find zone for domain %q: %w", domain, err)
|
||||
}
|
||||
|
||||
zones, err := d.client.RetrieveZones(ctx, dns01.UnFqdn(authZone))
|
||||
if err != nil {
|
||||
return fmt.Errorf("ionoscloud: retrieve zones: %w", err)
|
||||
}
|
||||
|
||||
if len(zones) != 1 {
|
||||
return fmt.Errorf("ionoscloud: zone ID not found for domain %q", domain)
|
||||
}
|
||||
|
||||
subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ionoscloud: %w", err)
|
||||
}
|
||||
|
||||
zoneID := zones[0].ID
|
||||
|
||||
request := internal.RecordProperties{
|
||||
Name: subDomain,
|
||||
Type: "TXT",
|
||||
Content: info.Value,
|
||||
TTL: d.config.TTL,
|
||||
}
|
||||
|
||||
record, err := d.client.CreateRecord(ctx, zoneID, request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ionoscloud: create record: %w", err)
|
||||
}
|
||||
|
||||
d.recordIDsMu.Lock()
|
||||
d.zoneIDs[token] = zoneID
|
||||
d.recordIDs[token] = record.ID
|
||||
d.recordIDsMu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanUp removes the TXT record matching the specified parameters.
|
||||
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
|
||||
info := dns01.GetChallengeInfo(domain, keyAuth)
|
||||
|
||||
d.recordIDsMu.Lock()
|
||||
zoneID, ok := d.zoneIDs[token]
|
||||
d.recordIDsMu.Unlock()
|
||||
|
||||
if !ok {
|
||||
return fmt.Errorf("ionoscloud: unknown zone ID for '%s' '%s'", info.EffectiveFQDN, token)
|
||||
}
|
||||
|
||||
d.recordIDsMu.Lock()
|
||||
recordID, ok := d.recordIDs[token]
|
||||
d.recordIDsMu.Unlock()
|
||||
|
||||
if !ok {
|
||||
return fmt.Errorf("ionoscloud: unknown record ID for '%s' '%s'", info.EffectiveFQDN, token)
|
||||
}
|
||||
|
||||
err := d.client.DeleteRecord(context.Background(), zoneID, recordID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ionoscloud: delete record: %w", err)
|
||||
}
|
||||
|
||||
d.recordIDsMu.Lock()
|
||||
delete(d.zoneIDs, token)
|
||||
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
|
||||
}
|
||||
22
providers/dns/ionoscloud/ionoscloud.toml
Normal file
22
providers/dns/ionoscloud/ionoscloud.toml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
Name = "Ionos Cloud"
|
||||
Description = ''''''
|
||||
URL = "https://cloud.ionos.de/network/cloud-dns"
|
||||
Code = "ionoscloud"
|
||||
Since = "v4.30.0"
|
||||
|
||||
Example = '''
|
||||
IONOSCLOUD_API_TOKEN="xxxxxxxxxxxxxxxxxxxxx" \
|
||||
lego --email you@example.com --dns ionoscloud -d '*.example.com' -d example.com run
|
||||
'''
|
||||
|
||||
[Configuration]
|
||||
[Configuration.Credentials]
|
||||
IONOSCLOUD_API_TOKEN = "API token"
|
||||
[Configuration.Additional]
|
||||
IONOSCLOUD_POLLING_INTERVAL = "Time between DNS propagation check in seconds (Default: 2)"
|
||||
IONOSCLOUD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation in seconds (Default: 120)"
|
||||
IONOSCLOUD_TTL = "The TTL of the TXT record used for the DNS challenge in seconds (Default: 120)"
|
||||
IONOSCLOUD_HTTP_TIMEOUT = "API request timeout in seconds (Default: 30)"
|
||||
|
||||
[Links]
|
||||
API = "https://api.ionos.com/docs/dns/v1/"
|
||||
173
providers/dns/ionoscloud/ionoscloud_test.go
Normal file
173
providers/dns/ionoscloud/ionoscloud_test.go
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
package ionoscloud
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/go-acme/lego/v4/platform/tester/servermock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const envDomain = envNamespace + "DOMAIN"
|
||||
|
||||
var envTest = tester.NewEnvTest(EnvAPIToken).WithDomain(envDomain)
|
||||
|
||||
func TestNewDNSProvider(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
envVars map[string]string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
envVars: map[string]string{
|
||||
EnvAPIToken: "secret",
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "missing credentials",
|
||||
envVars: map[string]string{},
|
||||
expected: "ionoscloud: some credentials information are missing: IONOSCLOUD_API_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 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
|
||||
apiToken string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
apiToken: "secret",
|
||||
},
|
||||
{
|
||||
desc: "missing credentials",
|
||||
expected: "ionoscloud: credentials missing",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
config := NewDefaultConfig()
|
||||
config.APIToken = test.apiToken
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func mockBuilder() *servermock.Builder[*DNSProvider] {
|
||||
return servermock.NewBuilder(
|
||||
func(server *httptest.Server) (*DNSProvider, error) {
|
||||
config := NewDefaultConfig()
|
||||
config.APIToken = "secret"
|
||||
config.HTTPClient = server.Client()
|
||||
|
||||
p, err := NewDNSProviderConfig(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p.client.BaseURL, _ = url.Parse(server.URL)
|
||||
|
||||
return p, nil
|
||||
},
|
||||
servermock.CheckHeader().
|
||||
WithJSONHeaders().
|
||||
WithAuthorization("Bearer secret"),
|
||||
)
|
||||
}
|
||||
|
||||
func TestDNSProvider_Present(t *testing.T) {
|
||||
provider := mockBuilder().
|
||||
Route("GET /zones",
|
||||
servermock.ResponseFromInternal("zones.json"),
|
||||
servermock.CheckQueryParameter().Strict().
|
||||
With("filter.zoneName", "example.com")).
|
||||
Route("POST /zones/e74d0d15-f567-4b7b-9069-26ee1f93bae3/records",
|
||||
servermock.ResponseFromInternal("create_record.json"),
|
||||
servermock.CheckRequestJSONBodyFromInternal("create_record-request.json")).
|
||||
Build(t)
|
||||
|
||||
err := provider.Present("example.com", "abc", "123d==")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestDNSProvider_CleanUp(t *testing.T) {
|
||||
provider := mockBuilder().
|
||||
Route("DELETE /zones/e74d0d15-f567-4b7b-9069-26ee1f93bae3/records/90d81ac0-3a30-44d4-95a5-12959effa6ee",
|
||||
servermock.Noop().
|
||||
WithStatusCode(http.StatusAccepted)).
|
||||
Build(t)
|
||||
|
||||
token := "abc"
|
||||
|
||||
provider.zoneIDs[token] = "e74d0d15-f567-4b7b-9069-26ee1f93bae3"
|
||||
provider.recordIDs[token] = "90d81ac0-3a30-44d4-95a5-12959effa6ee"
|
||||
|
||||
err := provider.CleanUp("example.com", token, "123d==")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
3
providers/dns/zz_gen_dns_providers.go
generated
3
providers/dns/zz_gen_dns_providers.go
generated
|
|
@ -92,6 +92,7 @@ import (
|
|||
"github.com/go-acme/lego/v4/providers/dns/internetbs"
|
||||
"github.com/go-acme/lego/v4/providers/dns/inwx"
|
||||
"github.com/go-acme/lego/v4/providers/dns/ionos"
|
||||
"github.com/go-acme/lego/v4/providers/dns/ionoscloud"
|
||||
"github.com/go-acme/lego/v4/providers/dns/ipv64"
|
||||
"github.com/go-acme/lego/v4/providers/dns/iwantmyname"
|
||||
"github.com/go-acme/lego/v4/providers/dns/joker"
|
||||
|
|
@ -358,6 +359,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
|
|||
return inwx.NewDNSProvider()
|
||||
case "ionos":
|
||||
return ionos.NewDNSProvider()
|
||||
case "ionoscloud":
|
||||
return ionoscloud.NewDNSProvider()
|
||||
case "ipv64":
|
||||
return ipv64.NewDNSProvider()
|
||||
case "iwantmyname":
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue