From 96586b05627c5bf3764949a163688cac59ce2657 Mon Sep 17 00:00:00 2001 From: jwklijnsma Date: Sat, 13 Jul 2024 18:34:58 +0200 Subject: [PATCH 1/8] add directadmin plugin --- README.md | 52 +++---- cmd/zz_gen_cmd_dnshelp.go | 18 +++ docs/data/zz_cli_help.toml | 2 +- providers/dns/directadmin/directadmin.go | 99 +++++++++++++ providers/dns/directadmin/directadmin.toml | 23 +++ providers/dns/directadmin/directadmin_test.go | 134 ++++++++++++++++++ providers/dns/dns_providers.go | 3 + 7 files changed, 304 insertions(+), 27 deletions(-) create mode 100644 providers/dns/directadmin/directadmin.go create mode 100644 providers/dns/directadmin/directadmin.toml create mode 100644 providers/dns/directadmin/directadmin_test.go diff --git a/README.md b/README.md index 060497c245..e28c89ca94 100644 --- a/README.md +++ b/README.md @@ -60,32 +60,32 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [Cloud.ru](https://go-acme.github.io/lego/dns/cloudru/) | [CloudDNS](https://go-acme.github.io/lego/dns/clouddns/) | [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) | [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) | | [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Constellix](https://go-acme.github.io/lego/dns/constellix/) | [CPanel/WHM](https://go-acme.github.io/lego/dns/cpanel/) | | [Derak Cloud](https://go-acme.github.io/lego/dns/derak/) | [deSEC.io](https://go-acme.github.io/lego/dns/desec/) | [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | -| [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | [dnsHome.de](https://go-acme.github.io/lego/dns/dnshomede/) | [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | [DNSPod (deprecated)](https://go-acme.github.io/lego/dns/dnspod/) | -| [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [Domeneshop](https://go-acme.github.io/lego/dns/domeneshop/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | -| [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [Dynu](https://go-acme.github.io/lego/dns/dynu/) | [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | [Efficient IP](https://go-acme.github.io/lego/dns/efficientip/) | -| [Epik](https://go-acme.github.io/lego/dns/epik/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) | [External program](https://go-acme.github.io/lego/dns/exec/) | [freemyip.com](https://go-acme.github.io/lego/dns/freemyip/) | -| [G-Core](https://go-acme.github.io/lego/dns/gcore/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | [Gandi](https://go-acme.github.io/lego/dns/gandi/) | [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/) | [Google Domains](https://go-acme.github.io/lego/dns/googledomains/) | [Hetzner](https://go-acme.github.io/lego/dns/hetzner/) | -| [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [Hosttech](https://go-acme.github.io/lego/dns/hosttech/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [http.net](https://go-acme.github.io/lego/dns/httpnet/) | -| [Hurricane Electric DNS](https://go-acme.github.io/lego/dns/hurricane/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) | [IBM Cloud (SoftLayer)](https://go-acme.github.io/lego/dns/ibmcloud/) | [IIJ DNS Platform Service](https://go-acme.github.io/lego/dns/iijdpf/) | -| [Infoblox](https://go-acme.github.io/lego/dns/infoblox/) | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) | -| [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [IPv64](https://go-acme.github.io/lego/dns/ipv64/) | [iwantmyname](https://go-acme.github.io/lego/dns/iwantmyname/) | -| [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Liara](https://go-acme.github.io/lego/dns/liara/) | [Linode (v4)](https://go-acme.github.io/lego/dns/linode/) | -| [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [Loopia](https://go-acme.github.io/lego/dns/loopia/) | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) | [Mail-in-a-Box](https://go-acme.github.io/lego/dns/mailinabox/) | -| [Manual](https://go-acme.github.io/lego/dns/manual/) | [Metaname](https://go-acme.github.io/lego/dns/metaname/) | [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/) | [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/) | [Nodion](https://go-acme.github.io/lego/dns/nodion/) | [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/) | [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/) | [RcodeZero](https://go-acme.github.io/lego/dns/rcodezero/) | [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 v2](https://go-acme.github.io/lego/dns/selectelv2/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [Shellrent](https://go-acme.github.io/lego/dns/shellrent/) | -| [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/) | [Webnames](https://go-acme.github.io/lego/dns/webnames/) | -| [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex 360](https://go-acme.github.io/lego/dns/yandex360/) | [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/) | | +| [directadmin](https://go-acme.github.io/lego/dns/directadmin/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | [dnsHome.de](https://go-acme.github.io/lego/dns/dnshomede/) | [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | +| [DNSPod (deprecated)](https://go-acme.github.io/lego/dns/dnspod/) | [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [Domeneshop](https://go-acme.github.io/lego/dns/domeneshop/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | +| [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [Dynu](https://go-acme.github.io/lego/dns/dynu/) | [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | +| [Efficient IP](https://go-acme.github.io/lego/dns/efficientip/) | [Epik](https://go-acme.github.io/lego/dns/epik/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) | [External program](https://go-acme.github.io/lego/dns/exec/) | +| [freemyip.com](https://go-acme.github.io/lego/dns/freemyip/) | [G-Core](https://go-acme.github.io/lego/dns/gcore/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | [Gandi](https://go-acme.github.io/lego/dns/gandi/) | +| [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/) | [Google Domains](https://go-acme.github.io/lego/dns/googledomains/) | +| [Hetzner](https://go-acme.github.io/lego/dns/hetzner/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [Hosttech](https://go-acme.github.io/lego/dns/hosttech/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | +| [http.net](https://go-acme.github.io/lego/dns/httpnet/) | [Hurricane Electric DNS](https://go-acme.github.io/lego/dns/hurricane/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) | [IBM Cloud (SoftLayer)](https://go-acme.github.io/lego/dns/ibmcloud/) | +| [IIJ DNS Platform Service](https://go-acme.github.io/lego/dns/iijdpf/) | [Infoblox](https://go-acme.github.io/lego/dns/infoblox/) | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | +| [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [IPv64](https://go-acme.github.io/lego/dns/ipv64/) | +| [iwantmyname](https://go-acme.github.io/lego/dns/iwantmyname/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Liara](https://go-acme.github.io/lego/dns/liara/) | +| [Linode (v4)](https://go-acme.github.io/lego/dns/linode/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [Loopia](https://go-acme.github.io/lego/dns/loopia/) | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) | +| [Mail-in-a-Box](https://go-acme.github.io/lego/dns/mailinabox/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | [Metaname](https://go-acme.github.io/lego/dns/metaname/) | [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/) | +| [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/) | [Nodion](https://go-acme.github.io/lego/dns/nodion/) | [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/) | [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/) | [RcodeZero](https://go-acme.github.io/lego/dns/rcodezero/) | +| [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 v2](https://go-acme.github.io/lego/dns/selectelv2/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | +| [Shellrent](https://go-acme.github.io/lego/dns/shellrent/) | [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/) | +| [Webnames](https://go-acme.github.io/lego/dns/webnames/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex 360](https://go-acme.github.io/lego/dns/yandex360/) | +| [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 0e12e9c882..25df8b7cca 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -931,6 +931,24 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/dynu`) + case "directadmin": + // generated from: providers/dns/directadmin/directadmin.toml + ew.writeln(`Configuration for directadmin.`) + ew.writeln(`Code: 'directadmin'`) + ew.writeln(`Since: ''`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "DIRECTADMIN_PASSWORD": yourpassword`) + ew.writeln(` - "DIRECTADMIN_USERNAME": yourusername`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "DIRECTADMIN_API_URL": The URL of the API`) + + ew.writeln() + ew.writeln(`More information: https://go-acme.github.io/lego/dns/directadmin`) + case "easydns": // generated from: providers/dns/easydns/easydns.toml ew.writeln(`Configuration for EasyDNS.`) diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index 6b3d91c0ec..fe2807f4eb 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -138,7 +138,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, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, cpanel, derak, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi + acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, cpanel, derak, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, directadmin, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go new file mode 100644 index 0000000000..49b0c69bbb --- /dev/null +++ b/providers/dns/directadmin/directadmin.go @@ -0,0 +1,99 @@ +package directadmin + +import ( + "fmt" + "net/http" + "os" + "strings" + + "github.com/go-acme/lego/v4/challenge/dns01" + "github.com/go-acme/lego/v4/log" +) + +// DNSProvider implements the challenge.Provider interface +type DNSProvider struct { + apiURL string + username string + password string +} + +// NewDNSProvider creates a new DNSProvider instance +func NewDNSProvider() (*DNSProvider, error) { + apiURL := getEnv("DIRECTADMIN_API_URL", "https://api.directadmin.com") + username := getEnv("DIRECTADMIN_USERNAME", "default_username") + password := getEnv("DIRECTADMIN_PASSWORD", "default_password") + + return &DNSProvider{ + apiURL: apiURL, + username: username, + password: password, + }, nil +} + +// getEnv reads an environment variable and returns the value or a default value if the environment variable is not set. +func getEnv(key, defaultValue string) string { + if value, exists := os.LookupEnv(key); exists { + return value + } + return defaultValue +} + +// Present creates a TXT record to fulfill the DNS-01 challenge +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + url := fmt.Sprintf("%s/CMD_API_DNS_CONTROL?domain=%s&json=yes", d.apiURL, domain) + data := fmt.Sprintf("action=add&type=TXT&name=_acme-challenge&value=%s", info.Value) + + req, err := http.NewRequest("POST", url, strings.NewReader(data)) + if err != nil { + return fmt.Errorf("failed to create request: %w", err) + } + + req.SetBasicAuth(d.username, d.password) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("failed to execute request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status code: %d", resp.StatusCode) + } + + log.Infof("Presented TXT record for domain %s", domain) + return nil +} + +// CleanUp removes the TXT record created for the DNS-01 challenge +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + url := fmt.Sprintf("%s/CMD_API_DNS_CONTROL?domain=%s&json=yes", d.apiURL, domain) + data := fmt.Sprintf("action=delete&type=TXT&name=_acme-challenge&value=%s", info.Value) + + req, err := http.NewRequest("POST", url, strings.NewReader(data)) + if err != nil { + return fmt.Errorf("failed to create request: %w", err) + } + + req.SetBasicAuth(d.username, d.password) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("failed to execute request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status code: %d", resp.StatusCode) + } + + log.Infof("Cleaned up TXT record for domain %s", domain) + return nil +} diff --git a/providers/dns/directadmin/directadmin.toml b/providers/dns/directadmin/directadmin.toml new file mode 100644 index 0000000000..565d4ae3b9 --- /dev/null +++ b/providers/dns/directadmin/directadmin.toml @@ -0,0 +1,23 @@ +Name = "directadmin" +Description = '''directadmin api''' +URL = "directadmin" +Code = "directadmin" + + +Example = ''' +DIRECTADMIN_API_URL="https://url:2222" \ +DIRECTADMIN_USERNAME="yourusername" \ +DIRECTADMIN_PASSWORD="yourpassword" \ +lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example.org" run +''' + +[Configuration] + [Configuration.Credentials] + DIRECTADMIN_USERNAME = "yourusername" + DIRECTADMIN_PASSWORD = "yourpassword" + + [Configuration.Additional] + DIRECTADMIN_API_URL = "The URL of the API" + +[Links] + API = "https://www.directadmin.com/api.php" \ No newline at end of file diff --git a/providers/dns/directadmin/directadmin_test.go b/providers/dns/directadmin/directadmin_test.go new file mode 100644 index 0000000000..5817c452b9 --- /dev/null +++ b/providers/dns/directadmin/directadmin_test.go @@ -0,0 +1,134 @@ +package directadmin + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const ( + envNamespace = "DIRECTADMIN_" + envAPIURL = envNamespace + "API_URL" + envUsername = envNamespace + "USERNAME" + envPassword = envNamespace + "PASSWORD" + envDomain = envNamespace + "DOMAIN" +) + +var envTest = tester.NewEnvTest(envAPIURL, 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{ + envAPIURL: "https://api.directadmin.com", + envUsername: "username", + envPassword: "password", + }, + }, + { + desc: "missing API URL", + envVars: map[string]string{}, + expected: "directadmin: some credentials information are missing: DIRECTADMIN_API_URL, DIRECTADMIN_USERNAME, DIRECTADMIN_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) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + apiURL string + username string + password string + expected string + }{ + { + desc: "success", + apiURL: "https://api.directadmin.com", + username: "username", + password: "password", + }, + { + desc: "missing API URL", + expected: "directadmin: APIURL is missing", + }, + { + desc: "missing username", + apiURL: "https://api.directadmin.com", + expected: "directadmin: username is missing", + }, + { + desc: "missing password", + apiURL: "https://api.directadmin.com", + username: "username", + expected: "directadmin: password is missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIURL = test.apiURL + config.Username = test.username + config.Password = test.password + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestLivePresent(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.Present(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} + +func TestLiveCleanUp(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index ff26a4921b..78c625d684 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -41,6 +41,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/duckdns" "github.com/go-acme/lego/v4/providers/dns/dyn" "github.com/go-acme/lego/v4/providers/dns/dynu" + "github.com/go-acme/lego/v4/providers/dns/directadmin" "github.com/go-acme/lego/v4/providers/dns/easydns" "github.com/go-acme/lego/v4/providers/dns/edgedns" "github.com/go-acme/lego/v4/providers/dns/efficientip" @@ -212,6 +213,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return dyn.NewDNSProvider() case "dynu": return dynu.NewDNSProvider() + case "directadmin": + return directadmin.NewDNSProvider() case "easydns": return easydns.NewDNSProvider() case "edgedns", "fastdns": // "fastdns" is for compatibility with v3, must be dropped in v5 From ffb2337378104b180df0fe9d29ac4cab41ccf14d Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sat, 13 Jul 2024 19:39:38 +0200 Subject: [PATCH 2/8] review: design --- providers/dns/directadmin/directadmin.go | 139 ++++++++++-------- providers/dns/directadmin/directadmin.toml | 10 +- providers/dns/directadmin/directadmin_test.go | 55 ++++--- providers/dns/directadmin/internal/client.go | 101 +++++++++++++ providers/dns/dns_providers.go | 6 +- 5 files changed, 217 insertions(+), 94 deletions(-) create mode 100644 providers/dns/directadmin/internal/client.go diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go index 49b0c69bbb..7a03d5bbc2 100644 --- a/providers/dns/directadmin/directadmin.go +++ b/providers/dns/directadmin/directadmin.go @@ -1,99 +1,114 @@ package directadmin import ( + "context" + "errors" "fmt" "net/http" - "os" - "strings" + "time" "github.com/go-acme/lego/v4/challenge/dns01" - "github.com/go-acme/lego/v4/log" + "github.com/go-acme/lego/v4/platform/config/env" + "github.com/go-acme/lego/v4/providers/dns/directadmin/internal" ) -// DNSProvider implements the challenge.Provider interface -type DNSProvider struct { - apiURL string - username string - password string -} +// Environment variables names. +const ( + envNamespace = "DIRECTADMIN_" -// NewDNSProvider creates a new DNSProvider instance -func NewDNSProvider() (*DNSProvider, error) { - apiURL := getEnv("DIRECTADMIN_API_URL", "https://api.directadmin.com") - username := getEnv("DIRECTADMIN_USERNAME", "default_username") - password := getEnv("DIRECTADMIN_PASSWORD", "default_password") - - return &DNSProvider{ - apiURL: apiURL, - username: username, - password: password, - }, nil + EnvAPIURL = envNamespace + "API_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 + TTL int + PropagationTimeout time.Duration + PollingInterval time.Duration + HTTPClient *http.Client } -// getEnv reads an environment variable and returns the value or a default value if the environment variable is not set. -func getEnv(key, defaultValue string) string { - if value, exists := os.LookupEnv(key); exists { - return value +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + BaseURL: env.GetOrDefaultString(EnvAPIURL, internal.DefaultBaseURL), + TTL: env.GetOrDefaultInt(EnvTTL, 30), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 60*time.Second), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 5*time.Second), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, } - return defaultValue } -// Present creates a TXT record to fulfill the DNS-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - info := dns01.GetChallengeInfo(domain, keyAuth) - - url := fmt.Sprintf("%s/CMD_API_DNS_CONTROL?domain=%s&json=yes", d.apiURL, domain) - data := fmt.Sprintf("action=add&type=TXT&name=_acme-challenge&value=%s", info.Value) +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + client *internal.Client +} - req, err := http.NewRequest("POST", url, strings.NewReader(data)) +// NewDNSProvider returns a DNSProvider instance configured for DirectAdmin. +// Credentials must be passed in the environment variables: +// DIRECTADMIN_API_URL, DIRECTADMIN_USERNAME, DIRECTADMIN_PASSWORD. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvUsername, EnvPassword) if err != nil { - return fmt.Errorf("failed to create request: %w", err) + return nil, fmt.Errorf("directadmin: %w", err) } - req.SetBasicAuth(d.username, d.password) - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + config := NewDefaultConfig() + config.Username = values[EnvUsername] + config.Password = values[EnvPassword] - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return fmt.Errorf("failed to execute request: %w", err) + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for DirectAdmin. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config.BaseURL == "" { + return nil, errors.New("directadmin: missing API URL") } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("unexpected status code: %d", resp.StatusCode) + if config.Username == "" || config.Password == "" { + return nil, errors.New("directadmin: some credentials information are missing") } - log.Infof("Presented TXT record for domain %s", domain) - return nil + client, err := internal.NewClient(config.BaseURL, config.Username, config.Password) + if err != nil { + return nil, fmt.Errorf("directadmin: %w", err) + } + + return &DNSProvider{client: client}, nil } -// CleanUp removes the TXT record created for the DNS-01 challenge -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { +// Present creates a TXT record using the specified parameters. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { info := dns01.GetChallengeInfo(domain, keyAuth) - url := fmt.Sprintf("%s/CMD_API_DNS_CONTROL?domain=%s&json=yes", d.apiURL, domain) - data := fmt.Sprintf("action=delete&type=TXT&name=_acme-challenge&value=%s", info.Value) - - req, err := http.NewRequest("POST", url, strings.NewReader(data)) + err := d.client.SetRecord(context.Background(), info.EffectiveFQDN, info.Value) if err != nil { - return fmt.Errorf("failed to create request: %w", err) + return fmt.Errorf("directadmin: %w", err) } - req.SetBasicAuth(d.username, d.password) - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + return nil +} - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return fmt.Errorf("failed to execute request: %w", err) - } - defer resp.Body.Close() +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("unexpected status code: %d", resp.StatusCode) + err := d.client.DeleteRecord(context.Background(), info.EffectiveFQDN, info.Value) + if err != nil { + return fmt.Errorf("directadmin: %w", err) } - log.Infof("Cleaned up TXT record for domain %s", domain) return nil } diff --git a/providers/dns/directadmin/directadmin.toml b/providers/dns/directadmin/directadmin.toml index 565d4ae3b9..c2adecc3d8 100644 --- a/providers/dns/directadmin/directadmin.toml +++ b/providers/dns/directadmin/directadmin.toml @@ -6,18 +6,18 @@ Code = "directadmin" Example = ''' DIRECTADMIN_API_URL="https://url:2222" \ -DIRECTADMIN_USERNAME="yourusername" \ -DIRECTADMIN_PASSWORD="yourpassword" \ +DIRECTADMIN_USERNAME=xxxx \ +DIRECTADMIN_PASSWORD=yyy \ lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example.org" run ''' [Configuration] [Configuration.Credentials] - DIRECTADMIN_USERNAME = "yourusername" - DIRECTADMIN_PASSWORD = "yourpassword" + DIRECTADMIN_USERNAME = "API username" + DIRECTADMIN_PASSWORD = "API password" [Configuration.Additional] DIRECTADMIN_API_URL = "The URL of the API" [Links] - API = "https://www.directadmin.com/api.php" \ No newline at end of file + API = "https://www.directadmin.com/api.php" diff --git a/providers/dns/directadmin/directadmin_test.go b/providers/dns/directadmin/directadmin_test.go index 5817c452b9..ff4bbc8a04 100644 --- a/providers/dns/directadmin/directadmin_test.go +++ b/providers/dns/directadmin/directadmin_test.go @@ -7,15 +7,9 @@ import ( "github.com/stretchr/testify/require" ) -const ( - envNamespace = "DIRECTADMIN_" - envAPIURL = envNamespace + "API_URL" - envUsername = envNamespace + "USERNAME" - envPassword = envNamespace + "PASSWORD" - envDomain = envNamespace + "DOMAIN" -) +const envDomain = envNamespace + "DOMAIN" -var envTest = tester.NewEnvTest(envAPIURL, envUsername, envPassword).WithDomain(envDomain) +var envTest = tester.NewEnvTest(EnvAPIURL, EnvUsername, EnvPassword).WithDomain(envDomain) func TestNewDNSProvider(t *testing.T) { testCases := []struct { @@ -26,15 +20,28 @@ func TestNewDNSProvider(t *testing.T) { { desc: "success", envVars: map[string]string{ - envAPIURL: "https://api.directadmin.com", - envUsername: "username", - envPassword: "password", + EnvUsername: "test", + EnvPassword: "secret", }, }, { - desc: "missing API URL", + desc: "missing credentials", envVars: map[string]string{}, - expected: "directadmin: some credentials information are missing: DIRECTADMIN_API_URL, DIRECTADMIN_USERNAME, DIRECTADMIN_PASSWORD", + expected: "directadmin: some credentials information are missing: DIRECTADMIN_USERNAME,DIRECTADMIN_PASSWORD", + }, + { + desc: "missing username", + envVars: map[string]string{ + EnvPassword: "secret", + }, + expected: "directadmin: some credentials information are missing: DIRECTADMIN_USERNAME", + }, + { + desc: "missing password", + envVars: map[string]string{ + EnvUsername: "test", + }, + expected: "directadmin: some credentials information are missing: DIRECTADMIN_PASSWORD", }, } @@ -60,38 +67,38 @@ func TestNewDNSProvider(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) { testCases := []struct { desc string - apiURL string + baseURL string username string password string expected string }{ { desc: "success", - apiURL: "https://api.directadmin.com", - username: "username", - password: "password", + baseURL: "https://api.directadmin.com", + username: "test", + password: "secret", }, { desc: "missing API URL", - expected: "directadmin: APIURL is missing", + expected: "directadmin: missing API URL", }, { desc: "missing username", - apiURL: "https://api.directadmin.com", - expected: "directadmin: username is missing", + baseURL: "https://api.directadmin.com", + expected: "directadmin: some credentials information are missing", }, { desc: "missing password", - apiURL: "https://api.directadmin.com", - username: "username", - expected: "directadmin: password is missing", + baseURL: "https://api.directadmin.com", + username: "test", + expected: "directadmin: some credentials information are missing", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { config := NewDefaultConfig() - config.APIURL = test.apiURL + config.BaseURL = test.baseURL config.Username = test.username config.Password = test.password diff --git a/providers/dns/directadmin/internal/client.go b/providers/dns/directadmin/internal/client.go new file mode 100644 index 0000000000..d6ea1a5c47 --- /dev/null +++ b/providers/dns/directadmin/internal/client.go @@ -0,0 +1,101 @@ +package internal + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" +) + +const DefaultBaseURL = "https://api.directadmin.com" + +// Client the Direct Admin API client. +type Client struct { + baseURL *url.URL + HTTPClient *http.Client + + username string + password string +} + +// NewClient creates a new Client. +func NewClient(baseURL, username, password string) (*Client, error) { + api, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + + return &Client{ + baseURL: api, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + username: username, + password: password, + }, nil +} + +func (c Client) SetRecord(ctx context.Context, domain, value string) error { + endpoint := c.baseURL.JoinPath("CMD_API_DNS_CONTROL") + + query := endpoint.Query() + query.Set("domain", domain) + query.Set("json", "yes") + endpoint.RawQuery = query.Encode() + + data := make(url.Values) + data.Set("action", "add") + data.Set("type", "TXT") + data.Set("name", "_acme-challenge") + data.Set("value", value) + + return c.do(ctx, endpoint, data) +} + +func (c Client) DeleteRecord(ctx context.Context, domain, value string) error { + endpoint := c.baseURL.JoinPath("CMD_API_DNS_CONTROL") + + query := endpoint.Query() + query.Set("domain", domain) + query.Set("json", "yes") + endpoint.RawQuery = query.Encode() + + data := make(url.Values) + data.Set("action", "delete") + data.Set("type", "TXT") + data.Set("name", "_acme-challenge") + data.Set("value", value) + + return c.do(ctx, endpoint, data) +} + +func (c Client) do(ctx context.Context, endpoint *url.URL, data url.Values) error { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), strings.NewReader(data.Encode())) + if err != nil { + return fmt.Errorf("unable to create request: %w", err) + } + + req.SetBasicAuth(c.username, c.password) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return errutils.NewReadResponseError(req, resp.StatusCode, err) + } + + if resp.StatusCode == http.StatusOK { + return nil + } + + return fmt.Errorf("error: %d: %s", resp.StatusCode, string(raw)) +} diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 78c625d684..36a47772ba 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -31,6 +31,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/desec" "github.com/go-acme/lego/v4/providers/dns/designate" "github.com/go-acme/lego/v4/providers/dns/digitalocean" + "github.com/go-acme/lego/v4/providers/dns/directadmin" "github.com/go-acme/lego/v4/providers/dns/dnshomede" "github.com/go-acme/lego/v4/providers/dns/dnsimple" "github.com/go-acme/lego/v4/providers/dns/dnsmadeeasy" @@ -41,7 +42,6 @@ import ( "github.com/go-acme/lego/v4/providers/dns/duckdns" "github.com/go-acme/lego/v4/providers/dns/dyn" "github.com/go-acme/lego/v4/providers/dns/dynu" - "github.com/go-acme/lego/v4/providers/dns/directadmin" "github.com/go-acme/lego/v4/providers/dns/easydns" "github.com/go-acme/lego/v4/providers/dns/edgedns" "github.com/go-acme/lego/v4/providers/dns/efficientip" @@ -193,6 +193,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return designate.NewDNSProvider() case "digitalocean": return digitalocean.NewDNSProvider() + case "directadmin": + return directadmin.NewDNSProvider() case "dnshomede": return dnshomede.NewDNSProvider() case "dnsimple": @@ -213,8 +215,6 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return dyn.NewDNSProvider() case "dynu": return dynu.NewDNSProvider() - case "directadmin": - return directadmin.NewDNSProvider() case "easydns": return easydns.NewDNSProvider() case "edgedns", "fastdns": // "fastdns" is for compatibility with v3, must be dropped in v5 From 181e84c2a1239f5146f7eda5c6fff78a036de0a8 Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sat, 13 Jul 2024 19:40:46 +0200 Subject: [PATCH 3/8] review: generate --- cmd/zz_gen_cmd_dnshelp.go | 37 ++++++++------- docs/content/dns/zz_gen_directadmin.md | 66 ++++++++++++++++++++++++++ docs/data/zz_cli_help.toml | 2 +- 3 files changed, 86 insertions(+), 19 deletions(-) create mode 100644 docs/content/dns/zz_gen_directadmin.md diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 25df8b7cca..85b38a0e9e 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -40,6 +40,7 @@ func allDNSCodes() string { "desec", "designate", "digitalocean", + "directadmin", "dnshomede", "dnsimple", "dnsmadeeasy", @@ -731,6 +732,24 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/digitalocean`) + case "directadmin": + // generated from: providers/dns/directadmin/directadmin.toml + ew.writeln(`Configuration for directadmin.`) + ew.writeln(`Code: 'directadmin'`) + ew.writeln(`Since: ''`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "DIRECTADMIN_PASSWORD": API password`) + ew.writeln(` - "DIRECTADMIN_USERNAME": API username`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "DIRECTADMIN_API_URL": The URL of the API`) + + ew.writeln() + ew.writeln(`More information: https://go-acme.github.io/lego/dns/directadmin`) + case "dnshomede": // generated from: providers/dns/dnshomede/dnshomede.toml ew.writeln(`Configuration for dnsHome.de.`) @@ -931,24 +950,6 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/dynu`) - case "directadmin": - // generated from: providers/dns/directadmin/directadmin.toml - ew.writeln(`Configuration for directadmin.`) - ew.writeln(`Code: 'directadmin'`) - ew.writeln(`Since: ''`) - ew.writeln() - - ew.writeln(`Credentials:`) - ew.writeln(` - "DIRECTADMIN_PASSWORD": yourpassword`) - ew.writeln(` - "DIRECTADMIN_USERNAME": yourusername`) - ew.writeln() - - ew.writeln(`Additional Configuration:`) - ew.writeln(` - "DIRECTADMIN_API_URL": The URL of the API`) - - ew.writeln() - ew.writeln(`More information: https://go-acme.github.io/lego/dns/directadmin`) - case "easydns": // generated from: providers/dns/easydns/easydns.toml ew.writeln(`Configuration for EasyDNS.`) diff --git a/docs/content/dns/zz_gen_directadmin.md b/docs/content/dns/zz_gen_directadmin.md new file mode 100644 index 0000000000..64b8b16fd8 --- /dev/null +++ b/docs/content/dns/zz_gen_directadmin.md @@ -0,0 +1,66 @@ +--- +title: "directadmin" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: directadmin +dnsprovider: + since: "" + code: "directadmin" + url: "directadmin" +--- + + + + + +directadmin api + + + + +- Code: `directadmin` +- Since: + + +Here is an example bash command using the directadmin provider: + +```bash +DIRECTADMIN_API_URL="https://url:2222" \ +DIRECTADMIN_USERNAME=xxxx \ +DIRECTADMIN_PASSWORD=yyy \ +lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example.org" run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `DIRECTADMIN_PASSWORD` | API password | +| `DIRECTADMIN_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 | +|--------------------------------|-------------| +| `DIRECTADMIN_API_URL` | The URL of the API | + +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://www.directadmin.com/api.php) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index fe2807f4eb..edf7d61861 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -138,7 +138,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, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, cpanel, derak, desec, designate, digitalocean, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, directadmin, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi + acme-dns, alidns, allinkl, arvancloud, auroradns, autodns, azure, azuredns, bindman, bluecat, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, constellix, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rcodezero, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ From c931bb8505816320fc8a4a662a1cd3f331dea45e Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Fri, 19 Jul 2024 00:41:50 +0200 Subject: [PATCH 4/8] review: zone and tests --- cmd/zz_gen_cmd_dnshelp.go | 4 +- docs/content/dns/zz_gen_directadmin.md | 11 +- providers/dns/directadmin/directadmin.go | 42 ++++- providers/dns/directadmin/directadmin.toml | 6 +- providers/dns/directadmin/directadmin_test.go | 13 +- providers/dns/directadmin/internal/client.go | 50 +++--- .../dns/directadmin/internal/client_test.go | 143 ++++++++++++++++++ 7 files changed, 224 insertions(+), 45 deletions(-) create mode 100644 providers/dns/directadmin/internal/client_test.go diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 85b38a0e9e..9f7c847653 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -740,13 +740,11 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`Credentials:`) + ew.writeln(` - "DIRECTADMIN_API_URL": URL of the API`) ew.writeln(` - "DIRECTADMIN_PASSWORD": API password`) ew.writeln(` - "DIRECTADMIN_USERNAME": API username`) ew.writeln() - ew.writeln(`Additional Configuration:`) - ew.writeln(` - "DIRECTADMIN_API_URL": The URL of the API`) - ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/directadmin`) diff --git a/docs/content/dns/zz_gen_directadmin.md b/docs/content/dns/zz_gen_directadmin.md index 64b8b16fd8..15be69f6fe 100644 --- a/docs/content/dns/zz_gen_directadmin.md +++ b/docs/content/dns/zz_gen_directadmin.md @@ -25,7 +25,7 @@ directadmin api Here is an example bash command using the directadmin provider: ```bash -DIRECTADMIN_API_URL="https://url:2222" \ +DIRECTADMIN_API_URL="http://example.com:2222" \ DIRECTADMIN_USERNAME=xxxx \ DIRECTADMIN_PASSWORD=yyy \ lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example.org" run @@ -38,6 +38,7 @@ lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example | Environment Variable Name | Description | |-----------------------|-------------| +| `DIRECTADMIN_API_URL` | URL of the API | | `DIRECTADMIN_PASSWORD` | API password | | `DIRECTADMIN_USERNAME` | API username | @@ -45,14 +46,6 @@ The environment variable names can be suffixed by `_FILE` to reference a file in More information [here]({{< ref "dns#configuration-and-credentials" >}}). -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DIRECTADMIN_API_URL` | The URL of the API | - -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" >}}). diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go index 7a03d5bbc2..5944f57bbd 100644 --- a/providers/dns/directadmin/directadmin.go +++ b/providers/dns/directadmin/directadmin.go @@ -40,7 +40,6 @@ type Config struct { // NewDefaultConfig returns a default configuration for the DNSProvider. func NewDefaultConfig() *Config { return &Config{ - BaseURL: env.GetOrDefaultString(EnvAPIURL, internal.DefaultBaseURL), TTL: env.GetOrDefaultInt(EnvTTL, 30), PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 60*time.Second), PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 5*time.Second), @@ -53,18 +52,20 @@ func NewDefaultConfig() *Config { // DNSProvider implements the challenge.Provider interface. type DNSProvider struct { client *internal.Client + config *Config } // NewDNSProvider returns a DNSProvider instance configured for DirectAdmin. // Credentials must be passed in the environment variables: // DIRECTADMIN_API_URL, DIRECTADMIN_USERNAME, DIRECTADMIN_PASSWORD. func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(EnvUsername, EnvPassword) + values, err := env.Get(EnvAPIURL, EnvUsername, EnvPassword) if err != nil { return nil, fmt.Errorf("directadmin: %w", err) } config := NewDefaultConfig() + config.BaseURL = values[EnvAPIURL] config.Username = values[EnvUsername] config.Password = values[EnvPassword] @@ -93,7 +94,24 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { func (d *DNSProvider) Present(domain, token, keyAuth string) error { info := dns01.GetChallengeInfo(domain, keyAuth) - err := d.client.SetRecord(context.Background(), info.EffectiveFQDN, info.Value) + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("directadmin: could not find zone for domain %q: %w", domain, err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) + if err != nil { + return fmt.Errorf("directadmin: %w", err) + } + + record := internal.Record{ + Name: subDomain, + Type: "TXT", + Value: info.Value, + TTL: d.config.TTL, + } + + err = d.client.SetRecord(context.Background(), authZone, record) if err != nil { return fmt.Errorf("directadmin: %w", err) } @@ -105,7 +123,23 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { info := dns01.GetChallengeInfo(domain, keyAuth) - err := d.client.DeleteRecord(context.Background(), info.EffectiveFQDN, info.Value) + authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("directadmin: could not find zone for domain %q: %w", domain, err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) + if err != nil { + return fmt.Errorf("directadmin: %w", err) + } + + record := internal.Record{ + Name: subDomain, + Type: "TXT", + Value: info.Value, + } + + err = d.client.DeleteRecord(context.Background(), authZone, record) if err != nil { return fmt.Errorf("directadmin: %w", err) } diff --git a/providers/dns/directadmin/directadmin.toml b/providers/dns/directadmin/directadmin.toml index c2adecc3d8..6ce25e219e 100644 --- a/providers/dns/directadmin/directadmin.toml +++ b/providers/dns/directadmin/directadmin.toml @@ -5,7 +5,7 @@ Code = "directadmin" Example = ''' -DIRECTADMIN_API_URL="https://url:2222" \ +DIRECTADMIN_API_URL="http://example.com:2222" \ DIRECTADMIN_USERNAME=xxxx \ DIRECTADMIN_PASSWORD=yyy \ lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example.org" run @@ -13,11 +13,9 @@ lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example [Configuration] [Configuration.Credentials] + DIRECTADMIN_API_URL = "URL of the API" DIRECTADMIN_USERNAME = "API username" DIRECTADMIN_PASSWORD = "API password" - [Configuration.Additional] - DIRECTADMIN_API_URL = "The URL of the API" - [Links] API = "https://www.directadmin.com/api.php" diff --git a/providers/dns/directadmin/directadmin_test.go b/providers/dns/directadmin/directadmin_test.go index ff4bbc8a04..eb89d6242e 100644 --- a/providers/dns/directadmin/directadmin_test.go +++ b/providers/dns/directadmin/directadmin_test.go @@ -20,6 +20,7 @@ func TestNewDNSProvider(t *testing.T) { { desc: "success", envVars: map[string]string{ + EnvAPIURL: "https://exmaple.com:2222", EnvUsername: "test", EnvPassword: "secret", }, @@ -27,11 +28,20 @@ func TestNewDNSProvider(t *testing.T) { { desc: "missing credentials", envVars: map[string]string{}, - expected: "directadmin: some credentials information are missing: DIRECTADMIN_USERNAME,DIRECTADMIN_PASSWORD", + expected: "directadmin: some credentials information are missing: DIRECTADMIN_API_URL,DIRECTADMIN_USERNAME,DIRECTADMIN_PASSWORD", + }, + { + desc: "missing API URL", + envVars: map[string]string{ + EnvUsername: "test", + EnvPassword: "secret", + }, + expected: "directadmin: some credentials information are missing: DIRECTADMIN_API_URL", }, { desc: "missing username", envVars: map[string]string{ + EnvAPIURL: "https://exmaple.com:2222", EnvPassword: "secret", }, expected: "directadmin: some credentials information are missing: DIRECTADMIN_USERNAME", @@ -39,6 +49,7 @@ func TestNewDNSProvider(t *testing.T) { { desc: "missing password", envVars: map[string]string{ + EnvAPIURL: "https://exmaple.com:2222", EnvUsername: "test", }, expected: "directadmin: some credentials information are missing: DIRECTADMIN_PASSWORD", diff --git a/providers/dns/directadmin/internal/client.go b/providers/dns/directadmin/internal/client.go index d6ea1a5c47..163ab84bc0 100644 --- a/providers/dns/directadmin/internal/client.go +++ b/providers/dns/directadmin/internal/client.go @@ -10,9 +10,16 @@ import ( "time" "github.com/go-acme/lego/v4/providers/dns/internal/errutils" + querystring "github.com/google/go-querystring/query" ) -const DefaultBaseURL = "https://api.directadmin.com" +// Record represents a DNS record. +type Record struct { + Name string `url:"name,omitempty"` + Type string `url:"type,omitempty"` + Value string `url:"value,omitempty"` + TTL int `url:"ttl,omitempty"` +} // Client the Direct Admin API client. type Client struct { @@ -38,24 +45,29 @@ func NewClient(baseURL, username, password string) (*Client, error) { }, nil } -func (c Client) SetRecord(ctx context.Context, domain, value string) error { - endpoint := c.baseURL.JoinPath("CMD_API_DNS_CONTROL") - - query := endpoint.Query() - query.Set("domain", domain) - query.Set("json", "yes") - endpoint.RawQuery = query.Encode() +func (c Client) SetRecord(ctx context.Context, domain string, record Record) error { + data, err := querystring.Values(record) + if err != nil { + return err + } - data := make(url.Values) data.Set("action", "add") - data.Set("type", "TXT") - data.Set("name", "_acme-challenge") - data.Set("value", value) - return c.do(ctx, endpoint, data) + return c.do(ctx, domain, data) +} + +func (c Client) DeleteRecord(ctx context.Context, domain string, record Record) error { + data, err := querystring.Values(record) + if err != nil { + return err + } + + data.Set("action", "delete") + + return c.do(ctx, domain, data) } -func (c Client) DeleteRecord(ctx context.Context, domain, value string) error { +func (c Client) do(ctx context.Context, domain string, data url.Values) error { endpoint := c.baseURL.JoinPath("CMD_API_DNS_CONTROL") query := endpoint.Query() @@ -63,16 +75,6 @@ func (c Client) DeleteRecord(ctx context.Context, domain, value string) error { query.Set("json", "yes") endpoint.RawQuery = query.Encode() - data := make(url.Values) - data.Set("action", "delete") - data.Set("type", "TXT") - data.Set("name", "_acme-challenge") - data.Set("value", value) - - return c.do(ctx, endpoint, data) -} - -func (c Client) do(ctx context.Context, endpoint *url.URL, data url.Values) error { req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), strings.NewReader(data.Encode())) if err != nil { return fmt.Errorf("unable to create request: %w", err) diff --git a/providers/dns/directadmin/internal/client_test.go b/providers/dns/directadmin/internal/client_test.go new file mode 100644 index 0000000000..5672bd41f3 --- /dev/null +++ b/providers/dns/directadmin/internal/client_test.go @@ -0,0 +1,143 @@ +package internal + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T) (*Client, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client, _ := NewClient(server.URL, "user", "secret") + client.HTTPClient = server.Client() + + return client, mux +} + +func testHandler(kv map[string]string) func(rw http.ResponseWriter, req *http.Request) { + return func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, fmt.Sprintf("unsupported method %s", req.Method), http.StatusBadRequest) + return + } + + domain := req.URL.Query().Get("domain") + if domain != "example.com" { + http.Error(rw, fmt.Sprintf("invalid domain: %s", domain), http.StatusUnauthorized) + return + } + + data, err := io.ReadAll(req.Body) + if err != nil { + http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + + values, err := url.ParseQuery(string(data)) + if err != nil { + http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + + for k, v := range kv { + actual := values.Get(k) + if v != actual { + http.Error(rw, fmt.Sprintf("invalid %q: %s", k, actual), http.StatusBadRequest) + return + } + } + } +} + +func TestClient_SetRecord(t *testing.T) { + client, mux := setupTest(t) + + kv := map[string]string{ + "action": "add", + "name": "foo", + "type": "TXT", + "value": "txtTXTtxt", + "ttl": "123", + } + + mux.HandleFunc("/CMD_API_DNS_CONTROL", testHandler(kv)) + + record := Record{ + Name: "foo", + Type: "TXT", + Value: "txtTXTtxt", + TTL: 123, + } + + err := client.SetRecord(context.Background(), "example.com", record) + require.NoError(t, err) +} + +func TestClient_SetRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/CMD_API_DNS_CONTROL", func(rw http.ResponseWriter, req *http.Request) { + http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + }) + + record := Record{ + Name: "foo", + Type: "TXT", + Value: "txtTXTtxt", + TTL: 123, + } + + err := client.SetRecord(context.Background(), "example.com", record) + require.EqualError(t, err, "error: 500: Internal Server Error\n") +} + +func TestClient_DeleteRecord(t *testing.T) { + client, mux := setupTest(t) + + kv := map[string]string{ + "action": "delete", + "name": "foo", + "type": "TXT", + "value": "txtTXTtxt", + "ttl": "", + } + + mux.HandleFunc("/CMD_API_DNS_CONTROL", testHandler(kv)) + + record := Record{ + Name: "foo", + Type: "TXT", + Value: "txtTXTtxt", + } + + err := client.DeleteRecord(context.Background(), "example.com", record) + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/CMD_API_DNS_CONTROL", func(rw http.ResponseWriter, req *http.Request) { + http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + }) + + record := Record{ + Name: "foo", + Type: "TXT", + Value: "txtTXTtxt", + } + + err := client.DeleteRecord(context.Background(), "example.com", record) + require.EqualError(t, err, "error: 500: Internal Server Error\n") +} From b8c3d56278536169362366cc16a9fc6c92eb326a Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sat, 20 Jul 2024 23:32:57 +0200 Subject: [PATCH 5/8] review: fix --- providers/dns/directadmin/directadmin.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go index 5944f57bbd..2bc820c06e 100644 --- a/providers/dns/directadmin/directadmin.go +++ b/providers/dns/directadmin/directadmin.go @@ -87,7 +87,7 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { return nil, fmt.Errorf("directadmin: %w", err) } - return &DNSProvider{client: client}, nil + return &DNSProvider{client: client, config: config}, nil } // Present creates a TXT record using the specified parameters. From 12072fc14c38cdb4358464328356de95d0a228e5 Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sun, 21 Jul 2024 00:01:38 +0200 Subject: [PATCH 6/8] review: improve error --- providers/dns/directadmin/directadmin.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go index 2bc820c06e..7392938add 100644 --- a/providers/dns/directadmin/directadmin.go +++ b/providers/dns/directadmin/directadmin.go @@ -113,7 +113,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { err = d.client.SetRecord(context.Background(), authZone, record) if err != nil { - return fmt.Errorf("directadmin: %w", err) + return fmt.Errorf("directadmin: set record for zone %s and subdomain %s: %w", authZone, subDomain, err) } return nil @@ -141,7 +141,7 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { err = d.client.DeleteRecord(context.Background(), authZone, record) if err != nil { - return fmt.Errorf("directadmin: %w", err) + return fmt.Errorf("directadmin: delete record for zone %s and subdomain %s: %w", authZone, subDomain, err) } return nil From 1fa51efa28949e2ab5bb4c19d2183615b67a1dd9 Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sun, 21 Jul 2024 00:26:51 +0200 Subject: [PATCH 7/8] review: improve error and add option to force the zone --- cmd/zz_gen_cmd_dnshelp.go | 7 +++++ docs/content/dns/zz_gen_directadmin.md | 12 ++++++++ providers/dns/directadmin/directadmin.go | 23 ++++++++++++--- providers/dns/directadmin/directadmin.toml | 6 ++++ providers/dns/directadmin/directadmin_test.go | 4 +++ providers/dns/directadmin/internal/client.go | 28 +++++++++---------- .../dns/directadmin/internal/client_test.go | 24 ++++++++++++---- providers/dns/directadmin/internal/types.go | 21 ++++++++++++++ 8 files changed, 101 insertions(+), 24 deletions(-) create mode 100644 providers/dns/directadmin/internal/types.go diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 9f7c847653..e488f12930 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -745,6 +745,13 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln(` - "DIRECTADMIN_USERNAME": API username`) ew.writeln() + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "DIRECTADMIN_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "DIRECTADMIN_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "DIRECTADMIN_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "DIRECTADMIN_TTL": The TTL of the TXT record used for the DNS challenge`) + ew.writeln(` - "DIRECTADMIN_ZONE_NAME": API password`) + ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/directadmin`) diff --git a/docs/content/dns/zz_gen_directadmin.md b/docs/content/dns/zz_gen_directadmin.md index 15be69f6fe..bf8d0bf753 100644 --- a/docs/content/dns/zz_gen_directadmin.md +++ b/docs/content/dns/zz_gen_directadmin.md @@ -46,6 +46,18 @@ The environment variable names can be suffixed by `_FILE` to reference a file in More information [here]({{< ref "dns#configuration-and-credentials" >}}). +## Additional Configuration + +| Environment Variable Name | Description | +|--------------------------------|-------------| +| `DIRECTADMIN_HTTP_TIMEOUT` | API request timeout | +| `DIRECTADMIN_POLLING_INTERVAL` | Time between DNS propagation check | +| `DIRECTADMIN_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `DIRECTADMIN_TTL` | The TTL of the TXT record used for the DNS challenge | +| `DIRECTADMIN_ZONE_NAME` | API password | + +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" >}}). diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go index 7392938add..eba4898198 100644 --- a/providers/dns/directadmin/directadmin.go +++ b/providers/dns/directadmin/directadmin.go @@ -19,6 +19,7 @@ const ( EnvAPIURL = envNamespace + "API_URL" EnvUsername = envNamespace + "USERNAME" EnvPassword = envNamespace + "PASSWORD" + EnvZoneName = envNamespace + "ZONE_NAME" EnvTTL = envNamespace + "TTL" EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" @@ -94,9 +95,9 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { func (d *DNSProvider) Present(domain, token, keyAuth string) error { info := dns01.GetChallengeInfo(domain, keyAuth) - authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + authZone, err := getAuthZone(info.EffectiveFQDN) if err != nil { - return fmt.Errorf("directadmin: could not find zone for domain %q: %w", domain, err) + return fmt.Errorf("directadmin: [domain: %q] %w", domain, err) } subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) @@ -123,9 +124,9 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { info := dns01.GetChallengeInfo(domain, keyAuth) - authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN) + authZone, err := getAuthZone(info.EffectiveFQDN) if err != nil { - return fmt.Errorf("directadmin: could not find zone for domain %q: %w", domain, err) + return fmt.Errorf("directadmin: [domain: %q] %w", domain, err) } subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone) @@ -146,3 +147,17 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { return nil } + +func getAuthZone(fqdn string) (string, error) { + authZone := env.GetOrFile(EnvZoneName) + if authZone != "" { + return authZone, nil + } + + authZone, err := dns01.FindZoneByFqdn(fqdn) + if err != nil { + return "", fmt.Errorf("could not find zone for %s: %w", fqdn, err) + } + + return authZone, nil +} diff --git a/providers/dns/directadmin/directadmin.toml b/providers/dns/directadmin/directadmin.toml index 6ce25e219e..b676cf5b45 100644 --- a/providers/dns/directadmin/directadmin.toml +++ b/providers/dns/directadmin/directadmin.toml @@ -16,6 +16,12 @@ lego --email you@example.com --dns directadmin -d "my.example.org" -d "*.example DIRECTADMIN_API_URL = "URL of the API" DIRECTADMIN_USERNAME = "API username" DIRECTADMIN_PASSWORD = "API password" + [Configuration.Additional] + DIRECTADMIN_ZONE_NAME = "API password" + DIRECTADMIN_POLLING_INTERVAL = "Time between DNS propagation check" + DIRECTADMIN_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + DIRECTADMIN_TTL = "The TTL of the TXT record used for the DNS challenge" + DIRECTADMIN_HTTP_TIMEOUT = "API request timeout" [Links] API = "https://www.directadmin.com/api.php" diff --git a/providers/dns/directadmin/directadmin_test.go b/providers/dns/directadmin/directadmin_test.go index eb89d6242e..5d91e8c3b9 100644 --- a/providers/dns/directadmin/directadmin_test.go +++ b/providers/dns/directadmin/directadmin_test.go @@ -68,6 +68,8 @@ func TestNewDNSProvider(t *testing.T) { if test.expected == "" { require.NoError(t, err) require.NotNil(t, p) + require.NotNil(t, p.client) + require.NotNil(t, p.config) } else { require.EqualError(t, err, test.expected) } @@ -118,6 +120,8 @@ func TestNewDNSProviderConfig(t *testing.T) { if test.expected == "" { require.NoError(t, err) require.NotNil(t, p) + require.NotNil(t, p.client) + require.NotNil(t, p.config) } else { require.EqualError(t, err, test.expected) } diff --git a/providers/dns/directadmin/internal/client.go b/providers/dns/directadmin/internal/client.go index 163ab84bc0..fb84257bcf 100644 --- a/providers/dns/directadmin/internal/client.go +++ b/providers/dns/directadmin/internal/client.go @@ -2,6 +2,7 @@ package internal import ( "context" + "encoding/json" "fmt" "io" "net/http" @@ -13,14 +14,6 @@ import ( querystring "github.com/google/go-querystring/query" ) -// Record represents a DNS record. -type Record struct { - Name string `url:"name,omitempty"` - Type string `url:"type,omitempty"` - Value string `url:"value,omitempty"` - TTL int `url:"ttl,omitempty"` -} - // Client the Direct Admin API client. type Client struct { baseURL *url.URL @@ -90,14 +83,21 @@ func (c Client) do(ctx context.Context, domain string, data url.Values) error { defer func() { _ = resp.Body.Close() }() - raw, err := io.ReadAll(resp.Body) - if err != nil { - return errutils.NewReadResponseError(req, resp.StatusCode, err) + if resp.StatusCode != http.StatusOK { + return parseError(req, resp) } - if resp.StatusCode == http.StatusOK { - return nil + return nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + var errInfo APIError + err := json.Unmarshal(raw, &errInfo) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) } - return fmt.Errorf("error: %d: %s", resp.StatusCode, string(raw)) + return fmt.Errorf("[status code %d] %w", resp.StatusCode, errInfo) } diff --git a/providers/dns/directadmin/internal/client_test.go b/providers/dns/directadmin/internal/client_test.go index 5672bd41f3..ded4769e3f 100644 --- a/providers/dns/directadmin/internal/client_test.go +++ b/providers/dns/directadmin/internal/client_test.go @@ -2,6 +2,7 @@ package internal import ( "context" + "encoding/json" "fmt" "io" "net/http" @@ -25,6 +26,17 @@ func setupTest(t *testing.T) (*Client, *http.ServeMux) { return client, mux } +func newJSONErrorf(reason string, a ...any) string { + err := APIError{ + Message: "Cannot View Dns Record", + Result: fmt.Sprintf(reason, a...), + } + + data, _ := json.Marshal(err) + + return string(data) +} + func testHandler(kv map[string]string) func(rw http.ResponseWriter, req *http.Request) { return func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { @@ -34,7 +46,7 @@ func testHandler(kv map[string]string) func(rw http.ResponseWriter, req *http.Re domain := req.URL.Query().Get("domain") if domain != "example.com" { - http.Error(rw, fmt.Sprintf("invalid domain: %s", domain), http.StatusUnauthorized) + http.Error(rw, newJSONErrorf("invalid domain: %s", domain), http.StatusUnauthorized) return } @@ -53,7 +65,7 @@ func testHandler(kv map[string]string) func(rw http.ResponseWriter, req *http.Re for k, v := range kv { actual := values.Get(k) if v != actual { - http.Error(rw, fmt.Sprintf("invalid %q: %s", k, actual), http.StatusBadRequest) + http.Error(rw, newJSONErrorf("invalid %q: %s", k, actual), http.StatusBadRequest) return } } @@ -88,7 +100,7 @@ func TestClient_SetRecord_error(t *testing.T) { client, mux := setupTest(t) mux.HandleFunc("/CMD_API_DNS_CONTROL", func(rw http.ResponseWriter, req *http.Request) { - http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + http.Error(rw, newJSONErrorf("OOPS"), http.StatusInternalServerError) }) record := Record{ @@ -99,7 +111,7 @@ func TestClient_SetRecord_error(t *testing.T) { } err := client.SetRecord(context.Background(), "example.com", record) - require.EqualError(t, err, "error: 500: Internal Server Error\n") + require.EqualError(t, err, "[status code 500] Cannot View Dns Record: OOPS") } func TestClient_DeleteRecord(t *testing.T) { @@ -129,7 +141,7 @@ func TestClient_DeleteRecord_error(t *testing.T) { client, mux := setupTest(t) mux.HandleFunc("/CMD_API_DNS_CONTROL", func(rw http.ResponseWriter, req *http.Request) { - http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + http.Error(rw, newJSONErrorf("OOPS"), http.StatusInternalServerError) }) record := Record{ @@ -139,5 +151,5 @@ func TestClient_DeleteRecord_error(t *testing.T) { } err := client.DeleteRecord(context.Background(), "example.com", record) - require.EqualError(t, err, "error: 500: Internal Server Error\n") + require.EqualError(t, err, "[status code 500] Cannot View Dns Record: OOPS") } diff --git a/providers/dns/directadmin/internal/types.go b/providers/dns/directadmin/internal/types.go new file mode 100644 index 0000000000..461e36f987 --- /dev/null +++ b/providers/dns/directadmin/internal/types.go @@ -0,0 +1,21 @@ +package internal + +import "fmt" + +// Record represents a DNS record. +type Record struct { + Name string `url:"name,omitempty"` + Type string `url:"type,omitempty"` + Value string `url:"value,omitempty"` + TTL int `url:"ttl,omitempty"` +} + +// APIError represents a API error. +type APIError struct { + Message string `json:"error,omitempty"` + Result string `json:"result,omitempty"` +} + +func (a APIError) Error() string { + return fmt.Sprintf("%s: %s", a.Message, a.Result) +} From 8bc916ff9df2e0517922a34d2fd6dbe0dd9615bd Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sun, 21 Jul 2024 12:44:59 +0200 Subject: [PATCH 8/8] review: fix --- providers/dns/directadmin/directadmin.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/dns/directadmin/directadmin.go b/providers/dns/directadmin/directadmin.go index eba4898198..5aab7086ef 100644 --- a/providers/dns/directadmin/directadmin.go +++ b/providers/dns/directadmin/directadmin.go @@ -112,7 +112,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { TTL: d.config.TTL, } - err = d.client.SetRecord(context.Background(), authZone, record) + err = d.client.SetRecord(context.Background(), dns01.UnFqdn(authZone), record) if err != nil { return fmt.Errorf("directadmin: set record for zone %s and subdomain %s: %w", authZone, subDomain, err) } @@ -140,7 +140,7 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { Value: info.Value, } - err = d.client.DeleteRecord(context.Background(), authZone, record) + err = d.client.DeleteRecord(context.Background(), dns01.UnFqdn(authZone), record) if err != nil { return fmt.Errorf("directadmin: delete record for zone %s and subdomain %s: %w", authZone, subDomain, err) }