diff --git a/README.md b/README.md index 9b756d79..0cb04276 100644 --- a/README.md +++ b/README.md @@ -71,22 +71,22 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [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/) | [mijn.host](https://go-acme.github.io/lego/dns/mijnhost/) | -| [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/) | | | | +| [Lima-City](https://go-acme.github.io/lego/dns/limacity/) | [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/) | +| [mijn.host](https://go-acme.github.io/lego/dns/mijnhost/) | [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 34b36be9..c39cabcd 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -85,6 +85,7 @@ func allDNSCodes() string { "joker", "liara", "lightsail", + "limacity", "linode", "liquidweb", "loopia", @@ -1666,6 +1667,27 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/lightsail`) + case "limacity": + // generated from: providers/dns/limacity/limacity.toml + ew.writeln(`Configuration for Lima-City.`) + ew.writeln(`Code: 'limacity'`) + ew.writeln(`Since: 'v4.18.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "LIMACITY_API_KEY": The API key`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "LIMACITY_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "LIMACITY_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "LIMACITY_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "LIMACITY_SEQUENCE_INTERVAL": Time between sequential requests`) + ew.writeln(` - "LIMACITY_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/limacity`) + case "linode": // generated from: providers/dns/linode/linode.toml ew.writeln(`Configuration for Linode (v4).`) diff --git a/docs/content/dns/zz_gen_limacity.md b/docs/content/dns/zz_gen_limacity.md new file mode 100644 index 00000000..80e7390c --- /dev/null +++ b/docs/content/dns/zz_gen_limacity.md @@ -0,0 +1,68 @@ +--- +title: "Lima-City" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: limacity +dnsprovider: + since: "v4.18.0" + code: "limacity" + url: "https://www.lima-city.de" +--- + + + + + + +Configuration for [Lima-City](https://www.lima-city.de). + + + + +- Code: `limacity` +- Since: v4.18.0 + + +Here is an example bash command using the Lima-City provider: + +```bash +LIMACITY_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email myemail@example.com --dns limacity --domains my.example.org run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `LIMACITY_API_KEY` | The API key | + +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 | +|--------------------------------|-------------| +| `LIMACITY_HTTP_TIMEOUT` | API request timeout | +| `LIMACITY_POLLING_INTERVAL` | Time between DNS propagation check | +| `LIMACITY_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `LIMACITY_SEQUENCE_INTERVAL` | Time between sequential requests | +| `LIMACITY_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://www.lima-city.de/hilfe/lima-city-api) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index b237cf7b..6fc40485 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, 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, mijnhost, 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, limacity, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mijnhost, 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/dns_providers.go b/providers/dns/dns_providers.go index 52e4fc94..0bcfdee6 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -76,6 +76,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/joker" "github.com/go-acme/lego/v4/providers/dns/liara" "github.com/go-acme/lego/v4/providers/dns/lightsail" + "github.com/go-acme/lego/v4/providers/dns/limacity" "github.com/go-acme/lego/v4/providers/dns/linode" "github.com/go-acme/lego/v4/providers/dns/liquidweb" "github.com/go-acme/lego/v4/providers/dns/loopia" @@ -284,6 +285,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return liara.NewDNSProvider() case "lightsail": return lightsail.NewDNSProvider() + case "limacity": + return limacity.NewDNSProvider() case "linode", "linodev4": // "linodev4" is for compatibility with v3, must be dropped in v5 return linode.NewDNSProvider() case "liquidweb": diff --git a/providers/dns/limacity/internal/client.go b/providers/dns/limacity/internal/client.go new file mode 100644 index 00000000..8a8b93ad --- /dev/null +++ b/providers/dns/limacity/internal/client.go @@ -0,0 +1,186 @@ +package internal + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/go-acme/lego/v4/providers/dns/internal/errutils" +) + +const defaultBaseURL = "https://www.lima-city.de/usercp" + +type Client struct { + apiKey string + baseURL *url.URL + HTTPClient *http.Client +} + +func NewClient(apiKey string) *Client { + baseURL, _ := url.Parse(defaultBaseURL) + + return &Client{ + apiKey: apiKey, + baseURL: baseURL, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + } +} + +func (c Client) GetDomains(ctx context.Context) ([]Domain, error) { + endpoint := c.baseURL.JoinPath("domains.json") + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var results DomainsResponse + err = c.do(req, &results) + if err != nil { + return nil, err + } + + return results.Data, nil +} + +func (c Client) GetRecords(ctx context.Context, domainID int) ([]Record, error) { + endpoint := c.baseURL.JoinPath("domains", strconv.Itoa(domainID), "records.json") + + req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + + var results RecordsResponse + err = c.do(req, &results) + if err != nil { + return nil, err + } + + return results.Data, nil +} + +func (c Client) AddRecord(ctx context.Context, domainID int, record Record) error { + endpoint := c.baseURL.JoinPath("domains", strconv.Itoa(domainID), "records.json") + + req, err := newJSONRequest(ctx, http.MethodPost, endpoint, NameserverRecordPayload{Data: record}) + if err != nil { + return err + } + + var results APIResponse + err = c.do(req, &results) + if err != nil { + return err + } + + return nil +} + +func (c Client) UpdateRecord(ctx context.Context, domainID, recordID int, record Record) error { + endpoint := c.baseURL.JoinPath("domains", strconv.Itoa(domainID), "records", strconv.Itoa(recordID)) + + req, err := newJSONRequest(ctx, http.MethodPut, endpoint, NameserverRecordPayload{Data: record}) + if err != nil { + return err + } + + var results APIResponse + err = c.do(req, &results) + if err != nil { + return err + } + + return nil +} + +func (c Client) DeleteRecord(ctx context.Context, domainID, recordID int) error { + // /domains/{domainId}/records/{recordId} DELETE + endpoint := c.baseURL.JoinPath("domains", strconv.Itoa(domainID), "records", strconv.Itoa(recordID)) + + req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil) + if err != nil { + return err + } + + var results APIResponse + err = c.do(req, &results) + if err != nil { + return err + } + + return nil +} + +func (c Client) do(req *http.Request, result any) error { + req.SetBasicAuth("api", c.apiKey) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return errutils.NewHTTPDoError(req, err) + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode/100 != 2 { + return parseError(req, resp) + } + + if result == nil { + return nil + } + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return errutils.NewReadResponseError(req, resp.StatusCode, err) + } + + err = json.Unmarshal(raw, result) + if err != nil { + return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err) + } + + return nil +} + +func newJSONRequest(ctx context.Context, method string, endpoint *url.URL, payload any) (*http.Request, error) { + buf := new(bytes.Buffer) + + if payload != nil { + err := json.NewEncoder(buf).Encode(payload) + if err != nil { + return nil, fmt.Errorf("failed to create request JSON body: %w", err) + } + } + + req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + + return req, nil +} + +func parseError(req *http.Request, resp *http.Response) error { + raw, _ := io.ReadAll(resp.Body) + + var errAPI APIResponse + err := json.Unmarshal(raw, &errAPI) + if err != nil { + return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw) + } + + return fmt.Errorf("[status code: %d] %w", resp.StatusCode, &errAPI) +} diff --git a/providers/dns/limacity/internal/client_test.go b/providers/dns/limacity/internal/client_test.go new file mode 100644 index 00000000..b9a13bda --- /dev/null +++ b/providers/dns/limacity/internal/client_test.go @@ -0,0 +1,193 @@ +package internal + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const apiKey = "secret" + +func setupTest(t *testing.T) (*Client, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + client := NewClient(apiKey) + client.baseURL, _ = url.Parse(server.URL) + + return client, mux +} + +func testHandler(filename string, method string, statusCode int) http.HandlerFunc { + return func(rw http.ResponseWriter, req *http.Request) { + if req.Method != method { + http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed) + return + } + + username, key, ok := req.BasicAuth() + if username != "api" || key != apiKey || !ok { + http.Error(rw, http.StatusText(http.StatusUnauthorized), 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() }() + + rw.WriteHeader(statusCode) + + _, err = io.Copy(rw, file) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + } +} + +func TestClient_GetDomains(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains.json", testHandler("get-domains.json", http.MethodGet, http.StatusOK)) + + domains, err := client.GetDomains(context.Background()) + require.NoError(t, err) + + expected := []Domain{{ + ID: 123, + UnicodeFqdn: "example.com", + Domain: "example", + TLD: "com", + Status: "ok", + }} + assert.Equal(t, expected, domains) +} + +func TestClient_GetDomains_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains.json", testHandler("error.json", http.MethodGet, http.StatusBadRequest)) + + _, err := client.GetDomains(context.Background()) + require.EqualError(t, err, "[status code: 400] status: invalid_resource, details: name: [muss ausgefüllt werden]") +} + +func TestClient_GetRecords(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records.json", testHandler("get-records.json", http.MethodGet, http.StatusOK)) + + records, err := client.GetRecords(context.Background(), 123) + require.NoError(t, err) + + expected := []Record{ + { + ID: 1234, + Content: "ns1.lima-city.de", + Name: "example.com", + TTL: 36000, + Type: "NS", + }, + { + ID: 5678, + Content: `"foobar"`, + Name: "_acme-challenge.example.com", + TTL: 36000, + Type: "TXT", + }, + } + assert.Equal(t, expected, records) +} + +func TestClient_GetRecords_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records.json", testHandler("error.json", http.MethodGet, http.StatusBadRequest)) + + _, err := client.GetRecords(context.Background(), 123) + require.EqualError(t, err, "[status code: 400] status: invalid_resource, details: name: [muss ausgefüllt werden]") +} + +func TestClient_AddRecord(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records.json", testHandler("ok.json", http.MethodPost, http.StatusOK)) + + record := Record{ + Name: "foo", + Content: "bar", + TTL: 12, + Type: "TXT", + } + + err := client.AddRecord(context.Background(), 123, record) + require.NoError(t, err) +} + +func TestClient_AddRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records.json", testHandler("error.json", http.MethodPost, http.StatusBadRequest)) + + record := Record{ + Name: "foo", + Content: "bar", + TTL: 12, + Type: "TXT", + } + + err := client.AddRecord(context.Background(), 123, record) + require.EqualError(t, err, "[status code: 400] status: invalid_resource, details: name: [muss ausgefüllt werden]") +} + +func TestClient_UpdateRecord(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records/456", testHandler("ok.json", http.MethodPut, http.StatusOK)) + + err := client.UpdateRecord(context.Background(), 123, 456, Record{}) + require.NoError(t, err) +} + +func TestClient_UpdateRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records/456", testHandler("error.json", http.MethodPut, http.StatusBadRequest)) + + err := client.UpdateRecord(context.Background(), 123, 456, Record{}) + require.EqualError(t, err, "[status code: 400] status: invalid_resource, details: name: [muss ausgefüllt werden]") +} + +func TestClient_DeleteRecord(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records/456", testHandler("ok.json", http.MethodDelete, http.StatusOK)) + + err := client.DeleteRecord(context.Background(), 123, 456) + require.NoError(t, err) +} + +func TestClient_DeleteRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.HandleFunc("/domains/123/records/456", testHandler("error.json", http.MethodDelete, http.StatusBadRequest)) + + err := client.DeleteRecord(context.Background(), 123, 456) + require.EqualError(t, err, "[status code: 400] status: invalid_resource, details: name: [muss ausgefüllt werden]") +} diff --git a/providers/dns/limacity/internal/fixtures/error.json b/providers/dns/limacity/internal/fixtures/error.json new file mode 100644 index 00000000..99dee169 --- /dev/null +++ b/providers/dns/limacity/internal/fixtures/error.json @@ -0,0 +1,8 @@ +{ + "status": "invalid_resource", + "errors": { + "name": [ + "muss ausgefüllt werden" + ] + } +} diff --git a/providers/dns/limacity/internal/fixtures/get-domains.json b/providers/dns/limacity/internal/fixtures/get-domains.json new file mode 100644 index 00000000..1643a176 --- /dev/null +++ b/providers/dns/limacity/internal/fixtures/get-domains.json @@ -0,0 +1,16 @@ +{ + "domains": [ + { + "id": 123, + "mode": "CREATE", + "tld": "com", + "domain": "example", + "in_subscription": false, + "auto_renew": false, + "status": "ok", + "unicode_fqdn": "example.com", + "registered_at": "1970-01-01T00:00:00+00:00", + "registered_until": "2000-01-01T00:00:00+00:00" + } + ] +} diff --git a/providers/dns/limacity/internal/fixtures/get-records.json b/providers/dns/limacity/internal/fixtures/get-records.json new file mode 100644 index 00000000..10f54346 --- /dev/null +++ b/providers/dns/limacity/internal/fixtures/get-records.json @@ -0,0 +1,21 @@ +{ + "records": [ + { + "id": 1234, + "content": "ns1.lima-city.de", + "name": "example.com", + "ttl": 36000, + "type": "NS", + "priority": null + }, + { + "id": 5678, + "content": "\"foobar\"", + "name": "_acme-challenge.example.com", + "subdomain": "_acme-challenge", + "ttl": 36000, + "type": "TXT", + "priority": null + } + ] +} diff --git a/providers/dns/limacity/internal/fixtures/ok.json b/providers/dns/limacity/internal/fixtures/ok.json new file mode 100644 index 00000000..bc4e0102 --- /dev/null +++ b/providers/dns/limacity/internal/fixtures/ok.json @@ -0,0 +1,3 @@ +{ + "status": "ok" +} diff --git a/providers/dns/limacity/internal/types.go b/providers/dns/limacity/internal/types.go new file mode 100644 index 00000000..5fdbacef --- /dev/null +++ b/providers/dns/limacity/internal/types.go @@ -0,0 +1,48 @@ +package internal + +import ( + "fmt" + "strings" +) + +type RecordsResponse struct { + Data []Record `json:"records,omitempty"` +} + +type NameserverRecordPayload struct { + Data Record `json:"nameserver_record,omitempty"` +} + +type DomainsResponse struct { + Data []Domain `json:"domains,omitempty"` +} + +type APIResponse struct { + Status string `json:"status,omitempty"` + Details map[string][]string `json:"errors,omitempty"` +} + +func (a APIResponse) Error() string { + var details []string + for k, v := range a.Details { + details = append(details, fmt.Sprintf("%s: %s", k, v)) + } + + return fmt.Sprintf("status: %s, details: %s", a.Status, strings.Join(details, ",")) +} + +type Record struct { + ID int `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Content string `json:"content,omitempty"` + TTL int `json:"ttl,omitempty"` + Type string `json:"type,omitempty"` +} + +type Domain struct { + ID int `json:"id,omitempty"` + UnicodeFqdn string `json:"unicode_fqdn,omitempty"` + Domain string `json:"domain,omitempty"` + TLD string `json:"tld,omitempty"` + Status string `json:"status,omitempty"` +} diff --git a/providers/dns/limacity/limacity.go b/providers/dns/limacity/limacity.go new file mode 100644 index 00000000..87b7d37a --- /dev/null +++ b/providers/dns/limacity/limacity.go @@ -0,0 +1,199 @@ +// Package limacity implements a DNS provider for solving the DNS-01 challenge using Lima-City DNS. +package limacity + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "sync" + "time" + + "github.com/go-acme/lego/v4/challenge/dns01" + "github.com/go-acme/lego/v4/platform/config/env" + "github.com/go-acme/lego/v4/providers/dns/limacity/internal" + "github.com/miekg/dns" +) + +// Environment variables names. +const ( + envNamespace = "LIMACITY_" + + EnvAPIKey = envNamespace + "API_KEY" + + EnvTTL = envNamespace + "TTL" + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" + EnvSequenceInterval = envNamespace + "SEQUENCE_INTERVAL" +) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + APIKey string + TTL int + PropagationTimeout time.Duration + PollingInterval time.Duration + SequenceInterval time.Duration + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, 60), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 8*time.Minute), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 80*time.Second), + SequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, 90*time.Second), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *internal.Client + + domainIDs map[string]int + domainIDsMu sync.Mutex +} + +// NewDNSProvider returns a DNSProvider instance configured for Lima-City DNS. +// LIMACITY_API_KEY must be passed in the environment variables. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey) + if err != nil { + return nil, fmt.Errorf("limacity: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Lima-City DNS. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("limacity: the configuration of the DNS provider is nil") + } + + if config.APIKey == "" { + return nil, errors.New("limacity: APIKey is missing") + } + + client := internal.NewClient(config.APIKey) + + return &DNSProvider{ + config: config, + client: client, + domainIDs: make(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 +} + +// Sequential All DNS challenges for this provider will be resolved sequentially. +// Returns the interval between each iteration. +func (d *DNSProvider) Sequential() time.Duration { + return d.config.SequenceInterval +} + +// 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) + + domains, err := d.client.GetDomains(context.Background()) + if err != nil { + return fmt.Errorf("limacity: get domains: %w", err) + } + + dom, err := findDomain(domains, info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("limacity: find domain: %w", err) + } + + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, dom.UnicodeFqdn) + if err != nil { + return fmt.Errorf("limacity: %w", err) + } + + record := internal.Record{ + Name: subDomain, + Content: info.Value, + TTL: d.config.TTL, + Type: "TXT", + } + + err = d.client.AddRecord(context.Background(), dom.ID, record) + if err != nil { + return fmt.Errorf("limacity: add record: %w", err) + } + + d.domainIDsMu.Lock() + d.domainIDs[token] = dom.ID + d.domainIDsMu.Unlock() + + return nil +} + +// CleanUp removes the TXT record. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + // gets the domain's unique ID + d.domainIDsMu.Lock() + domainID, ok := d.domainIDs[token] + d.domainIDsMu.Unlock() + if !ok { + return fmt.Errorf("liara: unknown domain ID for '%s' '%s'", info.EffectiveFQDN, token) + } + + records, err := d.client.GetRecords(context.Background(), domainID) + if err != nil { + return fmt.Errorf("limacity: get records: %w", err) + } + + var recordID int + for _, record := range records { + if record.Type == "TXT" && record.Content == strconv.Quote(info.Value) { + recordID = record.ID + break + } + } + + if recordID == 0 { + return errors.New("limacity: TXT record not found") + } + + err = d.client.DeleteRecord(context.Background(), domainID, recordID) + if err != nil { + return fmt.Errorf("limacity: delete record (domain ID=%d, record ID=%d): %w", domainID, recordID, err) + } + + return nil +} + +func findDomain(domains []internal.Domain, fqdn string) (internal.Domain, error) { + labelIndexes := dns.Split(fqdn) + + for _, index := range labelIndexes { + f := fqdn[index:] + domain := dns01.UnFqdn(f) + + for _, dom := range domains { + if dom.UnicodeFqdn == domain || dom.UnicodeFqdn == f { + return dom, nil + } + } + } + + return internal.Domain{}, fmt.Errorf("domain %s not found", fqdn) +} diff --git a/providers/dns/limacity/limacity.toml b/providers/dns/limacity/limacity.toml new file mode 100644 index 00000000..68766a31 --- /dev/null +++ b/providers/dns/limacity/limacity.toml @@ -0,0 +1,23 @@ +Name = "Lima-City" +Description = '''''' +URL = "https://www.lima-city.de" +Code = "limacity" +Since = "v4.18.0" + +Example = ''' +LIMACITY_API_KEY="xxxxxxxxxxxxxxxxxxxxx" \ +lego --email myemail@example.com --dns limacity --domains my.example.org run +''' + +[Configuration] + [Configuration.Credentials] + LIMACITY_API_KEY = "The API key" + [Configuration.Additional] + LIMACITY_POLLING_INTERVAL = "Time between DNS propagation check" + LIMACITY_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + LIMACITY_SEQUENCE_INTERVAL = "Time between sequential requests" + LIMACITY_TTL = "The TTL of the TXT record used for the DNS challenge" + LIMACITY_HTTP_TIMEOUT = "API request timeout" + +[Links] + API = "https://www.lima-city.de/hilfe/lima-city-api" diff --git a/providers/dns/limacity/limacity_test.go b/providers/dns/limacity/limacity_test.go new file mode 100644 index 00000000..2834a5f1 --- /dev/null +++ b/providers/dns/limacity/limacity_test.go @@ -0,0 +1,113 @@ +package limacity + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvAPIKey).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvAPIKey: "key", + }, + }, + { + desc: "missing API key", + envVars: map[string]string{}, + expected: "limacity: some credentials information are missing: LIMACITY_API_KEY", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + defer envTest.RestoreEnv() + envTest.ClearEnv() + + envTest.Apply(test.envVars) + + p, err := NewDNSProvider() + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + require.NotNil(t, p.client) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + apiKey string + expected string + }{ + { + desc: "success", + apiKey: "key", + }, + { + desc: "missing API key", + expected: "limacity: APIKey is missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIKey = test.apiKey + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + require.NotNil(t, p.client) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestLivePresent(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.Present(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} + +func TestLiveCleanUp(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +}