diff --git a/README.md b/README.md index 14ce6184..ad83dee9 100644 --- a/README.md +++ b/README.md @@ -69,14 +69,15 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [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/) | [NearlyFreeSpeech.NET](https://go-acme.github.io/lego/dns/nearlyfreespeech/) | | [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [Nicmanager](https://go-acme.github.io/lego/dns/nicmanager/) | [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/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | -| [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [Ultradns](https://go-acme.github.io/lego/dns/ultradns/) | [Variomedia](https://go-acme.github.io/lego/dns/variomedia/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | -| [Vercel](https://go-acme.github.io/lego/dns/vercel/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | [VK Cloud](https://go-acme.github.io/lego/dns/vkcloud/) | -| [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | -| [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) | [Yandex PDD](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/) | +| [OVH](https://go-acme.github.io/lego/dns/ovh/) | [plesk.com](https://go-acme.github.io/lego/dns/plesk/) | [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/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | +| [TransIP](https://go-acme.github.io/lego/dns/transip/) | [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [Ultradns](https://go-acme.github.io/lego/dns/ultradns/) | [Variomedia](https://go-acme.github.io/lego/dns/variomedia/) | +| [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Vercel](https://go-acme.github.io/lego/dns/vercel/) | [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | +| [VK Cloud](https://go-acme.github.io/lego/dns/vkcloud/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | +| [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) | [Yandex PDD](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 431ea7b2..b70e932a 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -94,6 +94,7 @@ func allDNSCodes() string { "otc", "ovh", "pdns", + "plesk", "porkbun", "rackspace", "regru", @@ -1831,6 +1832,28 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/pdns`) + case "plesk": + // generated from: providers/dns/plesk/plesk.toml + ew.writeln(`Configuration for plesk.com.`) + ew.writeln(`Code: 'plesk'`) + ew.writeln(`Since: 'v4.11.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "PLESK_PASSWORD": API password`) + ew.writeln(` - "PLESK_SERVER_BASE_URL": Base URL of the server (ex: https://plesk.myserver.com:8443)`) + ew.writeln(` - "PLESK_USERNAME": API username`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "PLESK_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "PLESK_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "PLESK_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "PLESK_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/plesk`) + case "porkbun": // generated from: providers/dns/porkbun/porkbun.toml ew.writeln(`Configuration for Porkbun.`) diff --git a/docs/content/dns/zz_gen_plesk.md b/docs/content/dns/zz_gen_plesk.md new file mode 100644 index 00000000..beb092d7 --- /dev/null +++ b/docs/content/dns/zz_gen_plesk.md @@ -0,0 +1,71 @@ +--- +title: "plesk.com" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: plesk +dnsprovider: + since: "v4.11.0" + code: "plesk" + url: "https://www.plesk.com/" +--- + + + + + + +Configuration for [plesk.com](https://www.plesk.com/). + + + + +- Code: `plesk` +- Since: v4.11.0 + + +Here is an example bash command using the plesk.com provider: + +```bash +PLESK_SERVER_BASE_URL="https://plesk.myserver.com:8443" \ +PLESK_USERNAME=xxxxxx \ +PLESK_PASSWORD=yyyyyy \ +lego --email you@example.com --dns plesk --domains my.example.org run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `PLESK_PASSWORD` | API password | +| `PLESK_SERVER_BASE_URL` | Base URL of the server (ex: https://plesk.myserver.com:8443) | +| `PLESK_USERNAME` | API username | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here]({{< ref "dns#configuration-and-credentials" >}}). + + +## Additional Configuration + +| Environment Variable Name | Description | +|--------------------------------|-------------| +| `PLESK_HTTP_TIMEOUT` | API request timeout | +| `PLESK_POLLING_INTERVAL` | Time between DNS propagation check | +| `PLESK_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `PLESK_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]({{< ref "dns#configuration-and-credentials" >}}). + + + + +## More information + +- [API documentation](https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference.28784/) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index f526b603..06dbd48a 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -125,7 +125,7 @@ To display the documentation for a specific DNS provider, run: $ lego dnshelp -c code Supported DNS providers: - acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, bindman, bluecat, checkdomain, civo, clouddns, cloudflare, cloudns, cloudxns, conoha, constellix, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, hetzner, hostingde, hosttech, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, manual, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, ns1, oraclecloud, otc, ovh, pdns, porkbun, rackspace, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, servercow, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, websupport, wedos, yandex, yandexcloud, zoneee, zonomi + acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, bindman, bluecat, checkdomain, civo, clouddns, cloudflare, cloudns, cloudxns, conoha, constellix, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, hetzner, hostingde, hosttech, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, manual, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, servercow, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, websupport, wedos, yandex, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 2d7b7c1c..ee2a3b0d 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -85,6 +85,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/otc" "github.com/go-acme/lego/v4/providers/dns/ovh" "github.com/go-acme/lego/v4/providers/dns/pdns" + "github.com/go-acme/lego/v4/providers/dns/plesk" "github.com/go-acme/lego/v4/providers/dns/porkbun" "github.com/go-acme/lego/v4/providers/dns/rackspace" "github.com/go-acme/lego/v4/providers/dns/regru" @@ -283,6 +284,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return ovh.NewDNSProvider() case "pdns": return pdns.NewDNSProvider() + case "plesk": + return plesk.NewDNSProvider() case "porkbun": return porkbun.NewDNSProvider() case "rackspace": diff --git a/providers/dns/plesk/internal/client.go b/providers/dns/plesk/internal/client.go new file mode 100644 index 00000000..cb61d388 --- /dev/null +++ b/providers/dns/plesk/internal/client.go @@ -0,0 +1,149 @@ +package internal + +import ( + "bytes" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "time" +) + +// Client the Plesk API client. +type Client struct { + HTTPClient *http.Client + baseURL *url.URL + login string + password string +} + +// NewClient created a new Client. +func NewClient(baseURL *url.URL, login string, password string) *Client { + return &Client{ + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + baseURL: baseURL, + login: login, + password: password, + } +} + +// GetSite gets a site. +// https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference/managing-sites-domains/getting-information-about-sites.66583/ +func (c Client) GetSite(domain string) (int, error) { + payload := RequestPacketType{Site: &SiteTypeRequest{Get: SiteGetRequest{Filter: &SiteFilterType{ + Name: domain, + }}}} + + response, err := c.do(payload) + if err != nil { + return 0, err + } + + if response.System != nil { + return 0, response.System + } + + if response == nil || response.Site.Get.Result == nil { + return 0, errors.New("unexpected empty result") + } + + if response.Site.Get.Result.Status != StatusOK { + return 0, response.Site.Get.Result + } + + return response.Site.Get.Result.ID, nil +} + +// AddRecord adds a TXT record. +// https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference/managing-dns/managing-dns-records/adding-dns-record.34798/ +func (c Client) AddRecord(siteID int, host, value string) (int, error) { + payload := RequestPacketType{DNS: &DNSInputType{AddRec: []AddRecRequest{{ + SiteID: siteID, + Type: "TXT", + Host: host, + Value: value, + }}}} + + response, err := c.do(payload) + if err != nil { + return 0, err + } + + if response.System != nil { + return 0, response.System + } + + if len(response.DNS.AddRec) < 1 { + return 0, errors.New("unexpected empty result") + } + + if response.DNS.AddRec[0].Result.Status != StatusOK { + return 0, response.DNS.AddRec[0].Result + } + + return response.DNS.AddRec[0].Result.ID, nil +} + +// DeleteRecord Deletes a TXT record. +// https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference/managing-dns/managing-dns-records/deleting-dns-records.34864/ +func (c Client) DeleteRecord(recordID int) (int, error) { + payload := RequestPacketType{DNS: &DNSInputType{DelRec: []DelRecRequest{{Filter: DNSSelectionFilterType{ + ID: recordID, + }}}}} + + response, err := c.do(payload) + if err != nil { + return 0, err + } + + if response.System != nil { + return 0, response.System + } + + if len(response.DNS.DelRec) < 1 { + return 0, errors.New("unexpected empty result") + } + + if response.DNS.DelRec[0].Result.Status != StatusOK { + return 0, response.DNS.DelRec[0].Result + } + + return response.DNS.DelRec[0].Result.ID, nil +} + +func (c Client) do(payload RequestPacketType) (*ResponsePacketType, error) { + endpoint := c.baseURL.JoinPath("/enterprise/control/agent.php") + + body := &bytes.Buffer{} + err := xml.NewEncoder(body).Encode(payload) + if err != nil { + return nil, err + } + + req, _ := http.NewRequest(http.MethodPost, endpoint.String(), body) + req.Header.Set("Content-Type", "text/xml") + req.Header.Set("Http_auth_login", c.login) + req.Header.Set("Http_auth_passwd", c.password) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return nil, err + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode/100 != 2 { + all, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("API error: %s", string(all)) + } + + var response ResponsePacketType + err = xml.NewDecoder(resp.Body).Decode(&response) + if err != nil { + return nil, err + } + + return &response, nil +} diff --git a/providers/dns/plesk/internal/client_test.go b/providers/dns/plesk/internal/client_test.go new file mode 100644 index 00000000..0f9636e0 --- /dev/null +++ b/providers/dns/plesk/internal/client_test.go @@ -0,0 +1,143 @@ +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" +) + +func setupTest(t *testing.T, filename string) *Client { + t.Helper() + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + serverURL, err := url.Parse(server.URL) + require.NoError(t, err) + + client := NewClient(serverURL, "user", "secret") + client.HTTPClient = server.Client() + + mux.HandleFunc("/enterprise/control/agent.php", func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed) + return + } + + login := req.Header.Get("Http_auth_login") + if login != "user" { + http.Error(rw, fmt.Sprintf("invalid login: %s", login), http.StatusUnauthorized) + return + } + + password := req.Header.Get("Http_auth_passwd") + if password != "secret" { + http.Error(rw, fmt.Sprintf("invalid password: %s", password), http.StatusUnauthorized) + return + } + + file, err := os.Open(filepath.Join("fixtures", filename)) + 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 + } + }) + + return client +} + +func TestClient_GetSite(t *testing.T) { + client := setupTest(t, "get-site.xml") + + siteID, err := client.GetSite("example.com") + require.NoError(t, err) + + assert.Equal(t, 82, siteID) +} + +func TestClient_GetSite_error(t *testing.T) { + client := setupTest(t, "get-site-error.xml") + + siteID, err := client.GetSite("example.com") + require.Error(t, err) + + assert.Equal(t, 0, siteID) +} + +func TestClient_GetSite_system_error(t *testing.T) { + client := setupTest(t, "global-error.xml") + + siteID, err := client.GetSite("example.com") + require.Error(t, err) + + assert.Equal(t, 0, siteID) +} + +func TestClient_AddRecord(t *testing.T) { + client := setupTest(t, "add-record.xml") + + recordID, err := client.AddRecord(123, "_acme-challenge.example.com", "txtTXTtxt") + require.NoError(t, err) + + assert.Equal(t, 4537, recordID) +} + +func TestClient_AddRecord_error(t *testing.T) { + client := setupTest(t, "add-record-error.xml") + + recordID, err := client.AddRecord(123, "_acme-challenge.example.com", "txtTXTtxt") + require.Error(t, err) + + assert.Equal(t, 0, recordID) +} + +func TestClient_AddRecord_system_error(t *testing.T) { + client := setupTest(t, "global-error.xml") + + recordID, err := client.AddRecord(123, "_acme-challenge.example.com", "txtTXTtxt") + require.Error(t, err) + + assert.Equal(t, 0, recordID) +} + +func TestClient_DeleteRecord(t *testing.T) { + client := setupTest(t, "delete-record.xml") + + recordID, err := client.DeleteRecord(4537) + require.NoError(t, err) + + assert.Equal(t, 4537, recordID) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client := setupTest(t, "delete-record-error.xml") + + recordID, err := client.DeleteRecord(4537) + require.Error(t, err) + + assert.Equal(t, 0, recordID) +} + +func TestClient_DeleteRecord_system_error(t *testing.T) { + client := setupTest(t, "global-error.xml") + + recordID, err := client.DeleteRecord(4537) + require.Error(t, err) + + assert.Equal(t, 0, recordID) +} diff --git a/providers/dns/plesk/internal/fixtures/add-record-error.xml b/providers/dns/plesk/internal/fixtures/add-record-error.xml new file mode 100644 index 00000000..84eafe25 --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/add-record-error.xml @@ -0,0 +1,12 @@ + + + + + + error + 1015 + Domain does not exist. + + + + diff --git a/providers/dns/plesk/internal/fixtures/add-record.xml b/providers/dns/plesk/internal/fixtures/add-record.xml new file mode 100644 index 00000000..961db6d1 --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/add-record.xml @@ -0,0 +1,11 @@ + + + + + + ok + 4537 + + + + diff --git a/providers/dns/plesk/internal/fixtures/delete-record-error.xml b/providers/dns/plesk/internal/fixtures/delete-record-error.xml new file mode 100644 index 00000000..b09c608d --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/delete-record-error.xml @@ -0,0 +1,13 @@ + + + + + + error + 1013 + Record does not exist + 453899 + + + + diff --git a/providers/dns/plesk/internal/fixtures/delete-record.xml b/providers/dns/plesk/internal/fixtures/delete-record.xml new file mode 100644 index 00000000..6cc1ba0c --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/delete-record.xml @@ -0,0 +1,11 @@ + + + + + + ok + 4537 + + + + diff --git a/providers/dns/plesk/internal/fixtures/get-site-error.xml b/providers/dns/plesk/internal/fixtures/get-site-error.xml new file mode 100644 index 00000000..00751f5c --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/get-site-error.xml @@ -0,0 +1,13 @@ + + + + + + error + 1013 + Site does not exist + bollox.com + + + + diff --git a/providers/dns/plesk/internal/fixtures/get-site.xml b/providers/dns/plesk/internal/fixtures/get-site.xml new file mode 100644 index 00000000..a1fe4f78 --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/get-site.xml @@ -0,0 +1,28 @@ + + + + + + ok + example.com + 82 + + + 2022-12-31 + example.com + example.com + 0 + 2717782016 + 217.28.1.1 + vrt_hst + e9114a63-e626-4977-ac15-a8e608750a33 + e9114a63-e626-4977-ac15-a8e608750a33 + + 82 + + + + + + + diff --git a/providers/dns/plesk/internal/fixtures/global-error.xml b/providers/dns/plesk/internal/fixtures/global-error.xml new file mode 100644 index 00000000..b43848f6 --- /dev/null +++ b/providers/dns/plesk/internal/fixtures/global-error.xml @@ -0,0 +1,8 @@ + + + + error + 1001 + You have entered incorrect username or password. + + diff --git a/providers/dns/plesk/internal/types.go b/providers/dns/plesk/internal/types.go new file mode 100644 index 00000000..1e3e699a --- /dev/null +++ b/providers/dns/plesk/internal/types.go @@ -0,0 +1,183 @@ +package internal + +import ( + "encoding/xml" + "fmt" +) + +// Response status. +const ( + StatusOK = "ok" + StatusError = "error" +) + +// Request. + +type RequestPacketType struct { + XMLName xml.Name `xml:"packet"` + Text string `xml:",chardata"` + + DNS *DNSInputType `xml:"dns,omitempty"` + Site *SiteTypeRequest `xml:"site,omitempty"` +} + +type DNSInputType struct { + Text string `xml:",chardata"` + + AddRec []AddRecRequest `xml:"add_rec,omitempty"` + DelRec []DelRecRequest `xml:"del_rec,omitempty"` +} + +type AddRecRequest struct { + Text string `xml:",chardata"` + + SiteID int `xml:"site-id,omitempty"` + Type string `xml:"type,omitempty"` + Host string `xml:"host,omitempty"` + Value string `xml:"value,omitempty"` +} + +type DelRecRequest struct { + Text string `xml:",chardata"` + + Filter DNSSelectionFilterType `xml:"filter"` +} + +type DNSSelectionFilterType struct { + Text string `xml:",chardata"` + + ID int `xml:"id"` +} + +type SiteTypeRequest struct { + Text string `xml:",chardata"` + + Get SiteGetRequest `xml:"get"` +} + +type SiteGetRequest struct { + Text string `xml:",chardata"` + + Filter *SiteFilterType `xml:"filter,omitempty"` + Dataset SiteDatasetType `xml:"dataset,omitempty"` +} + +type SiteFilterType struct { + Text string `xml:",chardata"` + + Name string `xml:"name"` +} + +type SiteDatasetType struct { + Text string `xml:",chardata"` + + GenInfo *SiteGenInfoType `xml:"gen_info,omitempty"` +} + +type SiteGenInfoType struct { + Text string `xml:",chardata"` + + CrDate string `xml:"cr_date,omitempty"` + Name string `xml:"name,omitempty"` + ASCIIName string `xml:"ascii-name,omitempty"` + Status string `xml:"status,omitempty"` + RealSize string `xml:"real_size,omitempty"` + DNSIPAddress string `xml:"dns_ip_address,omitempty"` + HType string `xml:"htype,omitempty"` + GUID string `xml:"guid,omitempty"` + WebspaceGUID string `xml:"webspace-guid,omitempty"` + SbSiteUUID string `xml:"sb-site-uuid,omitempty"` + WebspaceID string `xml:"webspace-id,omitempty"` + Description string `xml:"description,omitempty"` +} + +// Response. + +type ResponsePacketType struct { + XMLName xml.Name `xml:"packet"` + Text string `xml:",chardata"` + + DNS DNSResponseType `xml:"dns,omitempty"` + Site SiteResponseType `xml:"site,omitempty"` + System *System `xml:"system,omitempty"` +} + +type System struct { + Text string `xml:",chardata"` + + Status string `xml:"status"` + ErrCode string `xml:"errcode"` + ErrText string `xml:"errtext"` +} + +func (s System) Error() string { + return fmt.Sprintf("%s: %s - %s", s.Status, s.ErrCode, s.ErrText) +} + +type DNSResponseType struct { + Text string `xml:",chardata"` + + AddRec []AddRecResponse `xml:"add_rec,omitempty"` + DelRec []DelRecResponse `xml:"del_rec,omitempty"` +} + +type AddRecResponse struct { + Text string `xml:",chardata"` + + Result RecResult `xml:"result,omitempty"` +} + +type DelRecResponse struct { + Text string `xml:",chardata"` + + Result RecResult `xml:"result"` +} + +type RecResult struct { + Text string `xml:",chardata"` + + ID int `xml:"id"` + + Status string `xml:"status"` + ErrCode string `xml:"errcode"` + ErrText string `xml:"errtext"` +} + +func (r RecResult) Error() string { + return fmt.Sprintf("%s: %s - %s", r.Status, r.ErrCode, r.ErrText) +} + +type SiteResponseType struct { + Text string `xml:",chardata"` + + Get SiteGetResponse `xml:"get"` +} + +type SiteGetResponse struct { + Text string `xml:",chardata"` + + Result *SiteResult `xml:"result,omitempty"` +} + +type SiteResult struct { + Text string `xml:",chardata"` + + ID int `xml:"id"` + FilterID string `xml:"filter-id"` + + Status string `xml:"status"` + ErrCode string `xml:"errcode"` + ErrText string `xml:"errtext"` + + Data *SiteResultData `xml:"data"` +} + +func (s SiteResult) Error() string { + return fmt.Sprintf("%s: %s - %s", s.Status, s.ErrCode, s.ErrText) +} + +type SiteResultData struct { + Text string `xml:",chardata"` + + GenInfo *SiteGenInfoType `xml:"gen_info"` +} diff --git a/providers/dns/plesk/plesk.go b/providers/dns/plesk/plesk.go new file mode 100644 index 00000000..3fed464c --- /dev/null +++ b/providers/dns/plesk/plesk.go @@ -0,0 +1,167 @@ +// Package plesk implements a DNS provider for solving the DNS-01 challenge using Plesk DNS. +package plesk + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "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/plesk/internal" +) + +// Environment variables names. +const ( + envNamespace = "PLESK_" + + EnvServerBaseURL = envNamespace + "SERVER_BASE_URL" + EnvUsername = envNamespace + "USERNAME" + EnvPassword = envNamespace + "PASSWORD" + + 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 { + baseURL string + Username string + Password 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, 300), + 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 Plesk. +// Credentials must be passed in the environment variables: +// PLESK_USERNAME and PLESK_PASSWORD. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvServerBaseURL, EnvUsername, EnvPassword) + if err != nil { + return nil, fmt.Errorf("plesk: %w", err) + } + + config := NewDefaultConfig() + config.baseURL = values[EnvServerBaseURL] + config.Username = values[EnvUsername] + config.Password = values[EnvPassword] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Plesk. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("plesk: the configuration of the DNS provider is nil") + } + + if config.baseURL == "" { + return nil, errors.New("plesk: missing server base URL") + } + + baseURL, err := url.Parse(config.baseURL) + if err != nil { + return nil, fmt.Errorf("plesk: failed to parse base URL (%s): %w", config.baseURL, err) + } + + if config.Username == "" || config.Password == "" { + return nil, errors.New("plesk: incomplete credentials, missing username and/or password") + } + + client := internal.NewClient(baseURL, config.Username, config.Password) + + 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("plesk: could not find zone for domain %q and fqdn %q : %w", domain, fqdn, err) + } + + siteID, err := d.client.GetSite(dns01.UnFqdn(authZone)) + if err != nil { + return fmt.Errorf("plesk: failed to get site: %w", err) + } + + subDomain, err := dns01.ExtractSubDomain(fqdn, authZone) + if err != nil { + return fmt.Errorf("nodion: %w", err) + } + + recordID, err := d.client.AddRecord(siteID, subDomain, value) + if err != nil { + return fmt.Errorf("plesk: failed to add record: %w", err) + } + + d.recordIDsMu.Lock() + d.recordIDs[token] = recordID + 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) + + d.recordIDsMu.Lock() + recordID, ok := d.recordIDs[token] + d.recordIDsMu.Unlock() + if !ok { + return fmt.Errorf("plesk: unknown record ID for '%s' '%s'", fqdn, token) + } + + _, err := d.client.DeleteRecord(recordID) + if err != nil { + return fmt.Errorf("plesk: failed to delete record (%d): %w", recordID, err) + } + + return nil +} diff --git a/providers/dns/plesk/plesk.toml b/providers/dns/plesk/plesk.toml new file mode 100644 index 00000000..96b507cd --- /dev/null +++ b/providers/dns/plesk/plesk.toml @@ -0,0 +1,26 @@ +Name = "plesk.com" +Description = '''''' +URL = "https://www.plesk.com/" +Code = "plesk" +Since = "v4.11.0" + +Example = ''' +PLESK_SERVER_BASE_URL="https://plesk.myserver.com:8443" \ +PLESK_USERNAME=xxxxxx \ +PLESK_PASSWORD=yyyyyy \ +lego --email you@example.com --dns plesk --domains my.example.org run +''' + +[Configuration] + [Configuration.Credentials] + PLESK_SERVER_BASE_URL = "Base URL of the server (ex: https://plesk.myserver.com:8443)" + PLESK_USERNAME = "API username" + PLESK_PASSWORD = "API password" + [Configuration.Additional] + PLESK_POLLING_INTERVAL = "Time between DNS propagation check" + PLESK_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + PLESK_TTL = "The TTL of the TXT record used for the DNS challenge" + PLESK_HTTP_TIMEOUT = "API request timeout" + +[Links] + API = "https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference.28784/" diff --git a/providers/dns/plesk/plesk_test.go b/providers/dns/plesk/plesk_test.go new file mode 100644 index 00000000..417e2c1d --- /dev/null +++ b/providers/dns/plesk/plesk_test.go @@ -0,0 +1,172 @@ +package plesk + +import ( + "testing" + "time" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest( + EnvServerBaseURL, + EnvUsername, + EnvPassword). + WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvServerBaseURL: "https//example.com", + EnvUsername: "user", + EnvPassword: "secret", + }, + }, + { + desc: "missing server base URL", + envVars: map[string]string{ + EnvServerBaseURL: "", + EnvUsername: "user", + EnvPassword: "secret", + }, + expected: "plesk: some credentials information are missing: PLESK_SERVER_BASE_URL", + }, + { + desc: "missing username", + envVars: map[string]string{ + EnvServerBaseURL: "https//example.com", + EnvUsername: "", + EnvPassword: "secret", + }, + expected: "plesk: some credentials information are missing: PLESK_USERNAME", + }, + { + desc: "missing password", + envVars: map[string]string{ + EnvServerBaseURL: "https//example.com", + EnvUsername: "user", + EnvPassword: "", + }, + expected: "plesk: some credentials information are missing: PLESK_PASSWORD", + }, + { + desc: "missing credentials", + envVars: map[string]string{}, + expected: "plesk: some credentials information are missing: PLESK_SERVER_BASE_URL,PLESK_USERNAME,PLESK_PASSWORD", + }, + } + + 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 + baseURL string + username string + password string + expected string + }{ + { + desc: "success", + baseURL: "https://example.com", + username: "user", + password: "secret", + }, + { + desc: "missing base URL", + username: "user", + password: "secret", + expected: "plesk: missing server base URL", + }, + { + desc: "missing username", + baseURL: "https://example.com", + password: "secret", + expected: "plesk: incomplete credentials, missing username and/or password", + }, + { + desc: "missing password", + baseURL: "https://example.com", + username: "user", + expected: "plesk: incomplete credentials, missing username and/or password", + }, + { + desc: "missing credential", + baseURL: "https://example.com", + expected: "plesk: incomplete credentials, missing username and/or password", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.baseURL = test.baseURL + config.Username = test.username + config.Password = test.password + + 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) + + time.Sleep(1 * time.Second) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +}