From 25ea7ac6b4fa7992f289644503e97b9e68cda94c Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Sun, 10 May 2020 14:03:54 +1000 Subject: [PATCH] Add DNS provider for LuaDNS (#1135) --- README.md | 17 +- cmd/zz_gen_cmd_dnshelp.go | 23 ++ docs/content/dns/zz_gen_luadns.md | 65 ++++++ providers/dns/dns_providers.go | 3 + providers/dns/luadns/internal/client.go | 150 ++++++++++++ providers/dns/luadns/internal/client_test.go | 180 ++++++++++++++ .../internal/fixtures/create_record.json | 10 + .../internal/fixtures/delete_record.json | 10 + .../luadns/internal/fixtures/list_zones.json | 24 ++ providers/dns/luadns/internal/model.go | 36 +++ providers/dns/luadns/luadns.go | 184 +++++++++++++++ providers/dns/luadns/luadns.toml | 25 ++ providers/dns/luadns/luadns_test.go | 221 ++++++++++++++++++ 13 files changed, 940 insertions(+), 8 deletions(-) create mode 100644 docs/content/dns/zz_gen_luadns.md create mode 100644 providers/dns/luadns/internal/client.go create mode 100644 providers/dns/luadns/internal/client_test.go create mode 100644 providers/dns/luadns/internal/fixtures/create_record.json create mode 100644 providers/dns/luadns/internal/fixtures/delete_record.json create mode 100644 providers/dns/luadns/internal/fixtures/list_zones.json create mode 100644 providers/dns/luadns/internal/model.go create mode 100644 providers/dns/luadns/luadns.go create mode 100644 providers/dns/luadns/luadns.toml create mode 100644 providers/dns/luadns/luadns_test.go diff --git a/README.md b/README.md index 38647bdb..e340fc46 100644 --- a/README.md +++ b/README.md @@ -56,13 +56,14 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [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/) | [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/) | [Linode (deprecated)](https://go-acme.github.io/lego/dns/linode/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linodev4/) | -| [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [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/) | [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/) | [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/) | [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/) | [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/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | +| [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/) | [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/) | [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/) | [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/) | +| [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/) | +| [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/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | +| [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | | | | diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index f0a0e598..7d4b98b1 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -58,6 +58,7 @@ func allDNSCodes() string { "linode", "linodev4", "liquidweb", + "luadns", "mydnsjp", "mythicbeasts", "namecheap", @@ -1027,6 +1028,28 @@ func displayDNSHelp(name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/liquidweb`) + case "luadns": + // generated from: providers/dns/luadns/luadns.toml + ew.writeln(`Configuration for LuaDNS.`) + ew.writeln(`Code: 'luadns'`) + ew.writeln(`Since: 'v3.7.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "LUADNS_API_TOKEN": API token`) + ew.writeln(` - "LUADNS_API_USERNAME": Username (your email)`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "LUADNS_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "LUADNS_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "LUADNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "LUADNS_SEQUENCE_INTERVAL": Interval between iteration`) + ew.writeln(` - "LUADNS_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/luadns`) + case "mydnsjp": // generated from: providers/dns/mydnsjp/mydnsjp.toml ew.writeln(`Configuration for MyDNS.jp.`) diff --git a/docs/content/dns/zz_gen_luadns.md b/docs/content/dns/zz_gen_luadns.md new file mode 100644 index 00000000..aeba99ca --- /dev/null +++ b/docs/content/dns/zz_gen_luadns.md @@ -0,0 +1,65 @@ +--- +title: "LuaDNS" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: luadns +--- + + + + + +Since: v3.7.0 + +Configuration for [LuaDNS](https://luadns.com). + + + + +- Code: `luadns` + +Here is an example bash command using the LuaDNS provider: + +```bash +LUADNS_API_USERNAME=youremail \ +LUADNS_API_TOKEN=xxxxxxxx \ +lego --dns luadns --email me@example.com --domains test.example.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `LUADNS_API_TOKEN` | API token | +| `LUADNS_API_USERNAME` | Username (your email) | + +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 | +|--------------------------------|-------------| +| `LUADNS_HTTP_TIMEOUT` | API request timeout | +| `LUADNS_POLLING_INTERVAL` | Time between DNS propagation check | +| `LUADNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `LUADNS_SEQUENCE_INTERVAL` | Interval between iteration | +| `LUADNS_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://luadns.com/api.html) + + + + diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 753c52e8..ce961edd 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -49,6 +49,7 @@ import ( "github.com/go-acme/lego/v3/providers/dns/linode" "github.com/go-acme/lego/v3/providers/dns/linodev4" "github.com/go-acme/lego/v3/providers/dns/liquidweb" + "github.com/go-acme/lego/v3/providers/dns/luadns" "github.com/go-acme/lego/v3/providers/dns/mydnsjp" "github.com/go-acme/lego/v3/providers/dns/mythicbeasts" "github.com/go-acme/lego/v3/providers/dns/namecheap" @@ -173,6 +174,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return linodev4.NewDNSProvider() case "liquidweb": return liquidweb.NewDNSProvider() + case "luadns": + return luadns.NewDNSProvider() case "manual": return dns01.NewDNSProviderManual() case "mydnsjp": diff --git a/providers/dns/luadns/internal/client.go b/providers/dns/luadns/internal/client.go new file mode 100644 index 00000000..565405f4 --- /dev/null +++ b/providers/dns/luadns/internal/client.go @@ -0,0 +1,150 @@ +package internal + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" +) + +// defaultBaseURL represents the API endpoint to call. +const defaultBaseURL = "https://api.luadns.com" + +// Client Lua DNS API client. +type Client struct { + HTTPClient *http.Client + BaseURL string + + apiUsername string + apiToken string +} + +// NewClient creates a new Client. +func NewClient(apiUsername, apiToken string) *Client { + return &Client{ + HTTPClient: http.DefaultClient, + BaseURL: defaultBaseURL, + apiUsername: apiUsername, + apiToken: apiToken, + } +} + +// ListZones gets all the hosted zones. +// https://luadns.com/api.html#list-zones +func (d *Client) ListZones() ([]DNSZone, error) { + resp, err := d.do(http.MethodGet, "/v1/zones", nil) + if err != nil { + return nil, err + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + bodyBytes, _ := ioutil.ReadAll(resp.Body) + + var errResp errorResponse + err = json.Unmarshal(bodyBytes, &errResp) + if err == nil { + return nil, fmt.Errorf("api call error: Status=%v: %w", resp.StatusCode, errResp) + } + + return nil, fmt.Errorf("api call error: Status=%d: %s", resp.StatusCode, string(bodyBytes)) + } + + var zones []DNSZone + err = json.NewDecoder(resp.Body).Decode(&zones) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal response body: %w", err) + } + + return zones, nil +} + +// CreateRecord creates a new record in a zone. +// https://luadns.com/api.html#create-a-record +func (d *Client) CreateRecord(zone DNSZone, newRecord DNSRecord) (*DNSRecord, error) { + body, err := json.Marshal(newRecord) + if err != nil { + return nil, fmt.Errorf("failed to marshal request body: %w", err) + } + + resource := fmt.Sprintf("/v1/zones/%d/records", zone.ID) + + resp, err := d.do(http.MethodPost, resource, bytes.NewReader(body)) + if err != nil { + return nil, err + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + bodyBytes, _ := ioutil.ReadAll(resp.Body) + + var errResp errorResponse + err = json.Unmarshal(bodyBytes, &errResp) + if err == nil { + return nil, fmt.Errorf("could not create record %v: Status=%d: %w", + string(body), resp.StatusCode, errResp) + } + + return nil, fmt.Errorf("could not create record %v: Status=%d: %s", + string(body), resp.StatusCode, string(bodyBytes)) + } + + var record *DNSRecord + err = json.NewDecoder(resp.Body).Decode(&record) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal response body: %w", err) + } + + return record, nil +} + +// DeleteRecord deletes a record. +// https://luadns.com/api.html#delete-a-record +func (d *Client) DeleteRecord(record *DNSRecord) error { + body, err := json.Marshal(record) + if err != nil { + return fmt.Errorf("failed to marshal request body: %w", err) + } + + resource := fmt.Sprintf("/v1/zones/%d/records/%d", record.ZoneID, record.ID) + + resp, err := d.do(http.MethodDelete, resource, bytes.NewReader(body)) + if err != nil { + return err + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + bodyBytes, _ := ioutil.ReadAll(resp.Body) + + var errResp errorResponse + err = json.Unmarshal(bodyBytes, &errResp) + if err == nil { + return fmt.Errorf("could not delete record %v: Status=%d: %w", + string(body), resp.StatusCode, errResp) + } + + return fmt.Errorf("could not delete record %v: Status=%d: %s", + string(body), resp.StatusCode, string(bodyBytes)) + } + + return nil +} + +func (d *Client) do(method, uri string, body io.Reader) (*http.Response, error) { + req, err := http.NewRequest(method, fmt.Sprintf("%s%s", d.BaseURL, uri), body) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/json") + req.SetBasicAuth(d.apiUsername, d.apiToken) + + return d.HTTPClient.Do(req) +} diff --git a/providers/dns/luadns/internal/client_test.go b/providers/dns/luadns/internal/client_test.go new file mode 100644 index 00000000..04f9abc5 --- /dev/null +++ b/providers/dns/luadns/internal/client_test.go @@ -0,0 +1,180 @@ +package internal + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClient_ListZones(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("me", "secretA") + client.BaseURL = server.URL + + mux.HandleFunc("/v1/zones", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet { + http.Error(rw, fmt.Sprintf("invalid method: %s", req.Method), http.StatusMethodNotAllowed) + return + } + + auth := req.Header.Get("Authorization") + if auth != "Basic bWU6c2VjcmV0QQ==" { + http.Error(rw, fmt.Sprintf("invalid authentication: %s", auth), http.StatusUnauthorized) + } + + file, err := os.Open("./fixtures/list_zones.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + zones, err := client.ListZones() + require.NoError(t, err) + + expected := []DNSZone{ + { + ID: 1, + Name: "example.com", + Synced: false, + QueriesCount: 0, + RecordsCount: 3, + AliasesCount: 0, + RedirectsCount: 0, + ForwardsCount: 0, + TemplateID: 0, + }, + { + ID: 2, + Name: "example.net", + Synced: false, + QueriesCount: 0, + RecordsCount: 3, + AliasesCount: 0, + RedirectsCount: 0, + ForwardsCount: 0, + TemplateID: 0, + }, + } + + assert.Equal(t, expected, zones) +} + +func TestClient_CreateRecord(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("me", "secretB") + client.BaseURL = server.URL + + mux.HandleFunc("/v1/zones/1/records", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, fmt.Sprintf("invalid method: %s", req.Method), http.StatusMethodNotAllowed) + return + } + + auth := req.Header.Get("Authorization") + if auth != "Basic bWU6c2VjcmV0Qg==" { + http.Error(rw, fmt.Sprintf("invalid authentication: %s", auth), http.StatusUnauthorized) + } + + file, err := os.Open("./fixtures/create_record.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + zone := DNSZone{ID: 1} + + record := DNSRecord{ + Name: "example.com.", + Type: "MX", + Content: "10 mail.example.com.", + TTL: 300, + } + + newRecord, err := client.CreateRecord(zone, record) + require.NoError(t, err) + + expected := &DNSRecord{ + ID: 100, + Name: "example.com.", + Type: "MX", + Content: "10 mail.example.com.", + TTL: 300, + ZoneID: 1, + } + + assert.Equal(t, expected, newRecord) +} + +func TestClient_DeleteRecord(t *testing.T) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient("me", "secretC") + client.BaseURL = server.URL + + mux.HandleFunc("/v1/zones/1/records/2", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodDelete { + http.Error(rw, fmt.Sprintf("invalid method: %s", req.Method), http.StatusMethodNotAllowed) + return + } + + auth := req.Header.Get("Authorization") + if auth != "Basic bWU6c2VjcmV0Qw==" { + http.Error(rw, fmt.Sprintf("invalid authentication: %s", auth), http.StatusUnauthorized) + } + + file, err := os.Open("./fixtures/delete_record.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + defer func() { _ = file.Close() }() + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + }) + + record := &DNSRecord{ + ID: 2, + Name: "example.com.", + Type: "MX", + Content: "10 mail.example.com.", + TTL: 300, + ZoneID: 1, + } + + err := client.DeleteRecord(record) + require.NoError(t, err) +} diff --git a/providers/dns/luadns/internal/fixtures/create_record.json b/providers/dns/luadns/internal/fixtures/create_record.json new file mode 100644 index 00000000..5b66bb48 --- /dev/null +++ b/providers/dns/luadns/internal/fixtures/create_record.json @@ -0,0 +1,10 @@ +{ + "id": 100, + "name": "example.com.", + "type": "MX", + "content": "10 mail.example.com.", + "ttl": 300, + "zone_id": 1, + "created_at": "2015-01-17T14:04:35.251785849Z", + "updated_at": "2015-01-17T14:04:35.251785972Z" +} \ No newline at end of file diff --git a/providers/dns/luadns/internal/fixtures/delete_record.json b/providers/dns/luadns/internal/fixtures/delete_record.json new file mode 100644 index 00000000..5b66bb48 --- /dev/null +++ b/providers/dns/luadns/internal/fixtures/delete_record.json @@ -0,0 +1,10 @@ +{ + "id": 100, + "name": "example.com.", + "type": "MX", + "content": "10 mail.example.com.", + "ttl": 300, + "zone_id": 1, + "created_at": "2015-01-17T14:04:35.251785849Z", + "updated_at": "2015-01-17T14:04:35.251785972Z" +} \ No newline at end of file diff --git a/providers/dns/luadns/internal/fixtures/list_zones.json b/providers/dns/luadns/internal/fixtures/list_zones.json new file mode 100644 index 00000000..991579b7 --- /dev/null +++ b/providers/dns/luadns/internal/fixtures/list_zones.json @@ -0,0 +1,24 @@ +[ + { + "id": 1, + "name": "example.com", + "synced": false, + "queries_count": 0, + "records_count": 3, + "aliases_count": 0, + "redirects_count": 0, + "forwards_count": 0, + "template_id": 0 + }, + { + "id": 2, + "name": "example.net", + "synced": false, + "queries_count": 0, + "records_count": 3, + "aliases_count": 0, + "redirects_count": 0, + "forwards_count": 0, + "template_id": 0 + } +] \ No newline at end of file diff --git a/providers/dns/luadns/internal/model.go b/providers/dns/luadns/internal/model.go new file mode 100644 index 00000000..58d3235e --- /dev/null +++ b/providers/dns/luadns/internal/model.go @@ -0,0 +1,36 @@ +package internal + +import "fmt" + +type errorResponse struct { + Status string `json:"status"` + RequestID string `json:"request_id"` + Message string `json:"message"` +} + +func (e errorResponse) Error() string { + return fmt.Sprintf("status=%s, message=%s", e.Status, e.Message) +} + +// DNSZone a DNS zone. +type DNSZone struct { + ID int `json:"id"` + Name string `json:"name,omitempty"` + Synced bool `json:"synced,omitempty"` + QueriesCount int `json:"queries_count,omitempty"` + RecordsCount int `json:"records_count,omitempty"` + AliasesCount int `json:"aliases_count,omitempty"` + RedirectsCount int `json:"redirects_count,omitempty"` + ForwardsCount int `json:"forwards_count,omitempty"` + TemplateID int `json:"template_id,omitempty"` +} + +// DNSRecord a DNS record. +type DNSRecord struct { + ID int `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + Content string `json:"content,omitempty"` + TTL int `json:"ttl,omitempty"` + ZoneID int `json:"zone_id,omitempty"` +} diff --git a/providers/dns/luadns/luadns.go b/providers/dns/luadns/luadns.go new file mode 100644 index 00000000..f7776af3 --- /dev/null +++ b/providers/dns/luadns/luadns.go @@ -0,0 +1,184 @@ +// Package luadns implements a DNS provider for solving the DNS-01 challenge using LuaDNS. +package luadns + +import ( + "errors" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/go-acme/lego/v3/challenge/dns01" + "github.com/go-acme/lego/v3/platform/config/env" + "github.com/go-acme/lego/v3/providers/dns/luadns/internal" +) + +const minTTL = 300 + +// Environment variables names. +const ( + envNamespace = "LUADNS_" + + EnvAPIUsername = envNamespace + "API_USERNAME" + 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 { + APIUsername string + 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, minTTL), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *internal.Client + + recordsMu sync.Mutex + records map[string]*internal.DNSRecord +} + +// NewDNSProvider returns a DNSProvider instance configured for LuaDNS. +// Credentials must be passed in the environment variables: +// LUADNS_API_USERNAME and LUADNS_API_TOKEN. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIUsername, EnvAPIToken) + if err != nil { + return nil, fmt.Errorf("luadns: %w", err) + } + + config := NewDefaultConfig() + config.APIUsername = values[EnvAPIUsername] + config.APIToken = values[EnvAPIToken] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for LuaDNS. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("luadns: the configuration of the DNS provider is nil") + } + + if config.APIUsername == "" || config.APIToken == "" { + return nil, errors.New("luadns: credentials missing") + } + + if config.TTL < minTTL { + return nil, fmt.Errorf("luadns: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) + } + + client := internal.NewClient(config.APIUsername, config.APIToken) + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + return &DNSProvider{ + config: config, + client: client, + recordsMu: sync.Mutex{}, + records: make(map[string]*internal.DNSRecord), + }, 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) + + zones, err := d.client.ListZones() + if err != nil { + return fmt.Errorf("luadns: failed to get zones: %w", err) + } + + zone := findZone(zones, domain) + if zone == nil { + return fmt.Errorf("luadns: no matching zone found for domain %s", domain) + } + + newRecord := internal.DNSRecord{ + Name: fqdn, + Type: "TXT", + Content: value, + TTL: d.config.TTL, + } + + record, err := d.client.CreateRecord(*zone, newRecord) + if err != nil { + return fmt.Errorf("luadns: failed to create record: %w", err) + } + + d.recordsMu.Lock() + d.records[token] = record + d.recordsMu.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.recordsMu.Lock() + record, ok := d.records[token] + d.recordsMu.Unlock() + + if !ok { + return fmt.Errorf("luadns: unknown record ID for '%s'", fqdn) + } + + err := d.client.DeleteRecord(record) + if err != nil { + return fmt.Errorf("luadns: failed to delete record: %w", err) + } + + // Delete record from map + d.recordsMu.Lock() + delete(d.records, token) + d.recordsMu.Unlock() + + return nil +} + +func findZone(zones []internal.DNSZone, domain string) *internal.DNSZone { + var result *internal.DNSZone + + for _, zone := range zones { + zone := zone + if zone.Name != "" && strings.HasSuffix(domain, zone.Name) { + if result == nil || len(zone.Name) > len(result.Name) { + result = &zone + } + } + } + + return result +} diff --git a/providers/dns/luadns/luadns.toml b/providers/dns/luadns/luadns.toml new file mode 100644 index 00000000..89ce1659 --- /dev/null +++ b/providers/dns/luadns/luadns.toml @@ -0,0 +1,25 @@ +Name = "LuaDNS" +Description = '''''' +URL = "https://luadns.com" +Code = "luadns" +Since = "v3.7.0" + +Example = ''' +LUADNS_API_USERNAME=youremail \ +LUADNS_API_TOKEN=xxxxxxxx \ +lego --dns luadns --email me@example.com --domains test.example.com run +''' + +[Configuration] + [Configuration.Credentials] + LUADNS_API_USERNAME = "Username (your email)" + LUADNS_API_TOKEN = "API token" + [Configuration.Additional] + LUADNS_POLLING_INTERVAL = "Time between DNS propagation check" + LUADNS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + LUADNS_TTL = "The TTL of the TXT record used for the DNS challenge" + LUADNS_HTTP_TIMEOUT = "API request timeout" + LUADNS_SEQUENCE_INTERVAL = "Interval between iteration" + +[Links] + API = "https://luadns.com/api.html" diff --git a/providers/dns/luadns/luadns_test.go b/providers/dns/luadns/luadns_test.go new file mode 100644 index 00000000..45de0380 --- /dev/null +++ b/providers/dns/luadns/luadns_test.go @@ -0,0 +1,221 @@ +package luadns + +import ( + "testing" + + "github.com/go-acme/lego/v3/platform/tester" + "github.com/go-acme/lego/v3/providers/dns/luadns/internal" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest( + EnvAPIUsername, + EnvAPIToken). + WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvAPIUsername: "123", + EnvAPIToken: "456", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{ + EnvAPIUsername: "", + EnvAPIToken: "", + }, + expected: "luadns: some credentials information are missing: LUADNS_API_USERNAME,LUADNS_API_TOKEN", + }, + { + desc: "missing username", + envVars: map[string]string{ + EnvAPIUsername: "", + EnvAPIToken: "456", + }, + expected: "luadns: some credentials information are missing: LUADNS_API_USERNAME", + }, + { + desc: "missing api token", + envVars: map[string]string{ + EnvAPIUsername: "123", + EnvAPIToken: "", + }, + expected: "luadns: some credentials information are missing: LUADNS_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 len(test.expected) == 0 { + 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 + apiSecret string + tll int + expected string + }{ + { + desc: "success", + apiKey: "123", + apiSecret: "456", + tll: minTTL, + }, + { + desc: "missing credentials", + tll: minTTL, + expected: "luadns: credentials missing", + }, + { + desc: "missing username", + apiSecret: "456", + tll: minTTL, + expected: "luadns: credentials missing", + }, + { + desc: "missing api token", + apiKey: "123", + tll: minTTL, + expected: "luadns: credentials missing", + }, + { + desc: "invalid TTL", + apiKey: "123", + apiSecret: "456", + tll: 30, + expected: "luadns: invalid TTL, TTL (30) must be greater than 300", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIUsername = test.apiKey + config.APIToken = test.apiSecret + config.TTL = test.tll + + 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) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestDNSProvider_findZone(t *testing.T) { + testCases := []struct { + desc string + domain string + zones []internal.DNSZone + expected *internal.DNSZone + }{ + { + desc: "simple domain", + domain: "example.org", + zones: []internal.DNSZone{ + {Name: "example.org"}, + {Name: "example.com"}, + }, + expected: &internal.DNSZone{Name: "example.org"}, + }, + { + desc: "sub domain", + domain: "aaa.example.org", + zones: []internal.DNSZone{ + {Name: "example.org"}, + {Name: "aaa.example.org"}, + {Name: "bbb.example.org"}, + {Name: "example.com"}, + }, + expected: &internal.DNSZone{Name: "aaa.example.org"}, + }, + { + desc: "empty zone name", + domain: "example.org", + zones: []internal.DNSZone{ + {}, + }, + }, + { + desc: "not found", + domain: "example.org", + zones: []internal.DNSZone{ + {Name: "example.net"}, + {Name: "aaa.example.net"}, + {Name: "bbb.example.net"}, + {Name: "example.com"}, + }, + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + zone := findZone(test.zones, test.domain) + assert.Equal(t, test.expected, zone) + }) + } +} + +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) +}