diff --git a/README.md b/README.md index f12303b7..df315119 100644 --- a/README.md +++ b/README.md @@ -63,15 +63,15 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [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/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | | [MythicBeasts](https://go-acme.github.io/lego/dns/mythicbeasts/) | [Name.com](https://go-acme.github.io/lego/dns/namedotcom/) | [Namecheap](https://go-acme.github.io/lego/dns/namecheap/) | [Namesilo](https://go-acme.github.io/lego/dns/namesilo/) | -| [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [Nicmanager](https://go-acme.github.io/lego/dns/nicmanager/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | -| [Njalla](https://go-acme.github.io/lego/dns/njalla/) | [NS1](https://go-acme.github.io/lego/dns/ns1/) | [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) | [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | -| [OVH](https://go-acme.github.io/lego/dns/ovh/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) | [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | -| [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | -| [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [Simply.com](https://go-acme.github.io/lego/dns/simply/) | -| [Sonic](https://go-acme.github.io/lego/dns/sonic/) | [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | -| [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [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/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | -| [Yandex](https://go-acme.github.io/lego/dns/yandex/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | | +| [NearlyFreeSpeech.NET](https://go-acme.github.io/lego/dns/nearlyfreespeech/) | [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [Nicmanager](https://go-acme.github.io/lego/dns/nicmanager/) | +| [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | [Njalla](https://go-acme.github.io/lego/dns/njalla/) | [NS1](https://go-acme.github.io/lego/dns/ns1/) | [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) | +| [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | [OVH](https://go-acme.github.io/lego/dns/ovh/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) | [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | +| [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) | +| [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | +| [Simply.com](https://go-acme.github.io/lego/dns/simply/) | [Sonic](https://go-acme.github.io/lego/dns/sonic/) | [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | +| [TransIP](https://go-acme.github.io/lego/dns/transip/) | [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) | [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/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | [Vultr](https://go-acme.github.io/lego/dns/vultr/) | +| [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex](https://go-acme.github.io/lego/dns/yandex/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index c66ce9c9..6a90ef22 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -80,6 +80,7 @@ func allDNSCodes() string { "namecheap", "namedotcom", "namesilo", + "nearlyfreespeech", "netcup", "netlify", "nicmanager", @@ -1522,6 +1523,28 @@ func displayDNSHelp(name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/namesilo`) + case "nearlyfreespeech": + // generated from: providers/dns/nearlyfreespeech/nearlyfreespeech.toml + ew.writeln(`Configuration for NearlyFreeSpeech.NET.`) + ew.writeln(`Code: 'nearlyfreespeech'`) + ew.writeln(`Since: 'v4.8.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "NEARLYFREESPEECH_API_KEY": API Key for API requests`) + ew.writeln(` - "NEARLYFREESPEECH_LOGIN": Username for API requests`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "NEARLYFREESPEECH_HTTP_TIMEOUT": API request timeout`) + ew.writeln(` - "NEARLYFREESPEECH_POLLING_INTERVAL": Time between DNS propagation check`) + ew.writeln(` - "NEARLYFREESPEECH_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) + ew.writeln(` - "NEARLYFREESPEECH_SEQUENCE_INTERVAL": Time between sequential requests`) + ew.writeln(` - "NEARLYFREESPEECH_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/nearlyfreespeech`) + case "netcup": // generated from: providers/dns/netcup/netcup.toml ew.writeln(`Configuration for Netcup.`) diff --git a/docs/content/dns/zz_gen_nearlyfreespeech.md b/docs/content/dns/zz_gen_nearlyfreespeech.md new file mode 100644 index 00000000..2fec39c8 --- /dev/null +++ b/docs/content/dns/zz_gen_nearlyfreespeech.md @@ -0,0 +1,65 @@ +--- +title: "NearlyFreeSpeech.NET" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: nearlyfreespeech +--- + + + + + +Since: v4.8.0 + +Configuration for [NearlyFreeSpeech.NET](https://nearlyfreespeech.net/). + + + + +- Code: `nearlyfreespeech` + +Here is an example bash command using the NearlyFreeSpeech.NET provider: + +```bash +NEARLYFREESPEECH_API_KEY=xxxxxx \ +NEARLYFREESPEECH_LOGIN=xxxx \ +lego --email myemail@example.com --dns nearlyfreespeech --domains my.example.org run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `NEARLYFREESPEECH_API_KEY` | API Key for API requests | +| `NEARLYFREESPEECH_LOGIN` | Username for API requests | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here](/lego/dns/#configuration-and-credentials). + + +## Additional Configuration + +| Environment Variable Name | Description | +|--------------------------------|-------------| +| `NEARLYFREESPEECH_HTTP_TIMEOUT` | API request timeout | +| `NEARLYFREESPEECH_POLLING_INTERVAL` | Time between DNS propagation check | +| `NEARLYFREESPEECH_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | +| `NEARLYFREESPEECH_SEQUENCE_INTERVAL` | Time between sequential requests | +| `NEARLYFREESPEECH_TTL` | The TTL of the TXT record used for the DNS challenge | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here](/lego/dns/#configuration-and-credentials). + + + + +## More information + +- [API documentation](https://members.nearlyfreespeech.net/wiki/API/Reference) + + + + diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index f71d747c..93822058 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -71,6 +71,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/namecheap" "github.com/go-acme/lego/v4/providers/dns/namedotcom" "github.com/go-acme/lego/v4/providers/dns/namesilo" + "github.com/go-acme/lego/v4/providers/dns/nearlyfreespeech" "github.com/go-acme/lego/v4/providers/dns/netcup" "github.com/go-acme/lego/v4/providers/dns/netlify" "github.com/go-acme/lego/v4/providers/dns/nicmanager" @@ -246,6 +247,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return namedotcom.NewDNSProvider() case "namesilo": return namesilo.NewDNSProvider() + case "nearlyfreespeech": + return nearlyfreespeech.NewDNSProvider() case "netcup": return netcup.NewDNSProvider() case "netlify": diff --git a/providers/dns/nearlyfreespeech/internal/client.go b/providers/dns/nearlyfreespeech/internal/client.go new file mode 100644 index 00000000..5641000e --- /dev/null +++ b/providers/dns/nearlyfreespeech/internal/client.go @@ -0,0 +1,117 @@ +package internal + +import ( + "crypto/sha1" + "encoding/json" + "fmt" + "io" + "math/rand" + "net/http" + "net/url" + "path" + "strconv" + "strings" + "time" + + "github.com/go-acme/lego/v4/challenge/dns01" + querystring "github.com/google/go-querystring/query" +) + +const apiURL = "https://api.nearlyfreespeech.net" + +const authenticationHeader = "X-NFSN-Authentication" + +const saltBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + +type Client struct { + HTTPClient *http.Client + baseURL *url.URL + + login string + apiKey string +} + +func NewClient(login string, apiKey string) *Client { + baseURL, _ := url.Parse(apiURL) + return &Client{ + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + baseURL: baseURL, + login: login, + apiKey: apiKey, + } +} + +func (c Client) AddRecord(domain string, record Record) error { + params, err := querystring.Values(record) + if err != nil { + return err + } + + return c.do(path.Join("dns", dns01.UnFqdn(domain), "addRR"), params) +} + +func (c Client) RemoveRecord(domain string, record Record) error { + params, err := querystring.Values(record) + if err != nil { + return err + } + + return c.do(path.Join("dns", dns01.UnFqdn(domain), "removeRR"), params) +} + +func (c Client) do(uri string, params url.Values) error { + endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, uri)) + if err != nil { + return err + } + + payload := params.Encode() + + req, err := http.NewRequest(http.MethodPost, endpoint.String(), strings.NewReader(payload)) + if err != nil { + return err + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set(authenticationHeader, c.createSignature(endpoint.Path, payload)) + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return err + } + + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + data, _ := io.ReadAll(resp.Body) + + apiErr := &APIError{} + err := json.Unmarshal(data, apiErr) + if err != nil { + return fmt.Errorf("%s: %s", resp.Status, data) + } + + return apiErr + } + + return nil +} + +func (c Client) createSignature(uri string, body string) string { + // This is the only part of this that needs to be serialized. + salt := make([]byte, 16) + for i := 0; i < 16; i++ { + salt[i] = saltBytes[rand.Intn(len(saltBytes))] + } + + // Header is "login;timestamp;salt;hash". + // hash is SHA1("login;timestamp;salt;api-key;request-uri;body-hash") + // and body-hash is SHA1(body). + + bodyHash := sha1.Sum([]byte(body)) + timestamp := strconv.FormatInt(time.Now().Unix(), 10) + + hashInput := fmt.Sprintf("%s;%s;%s;%s;%s;%02x", c.login, timestamp, salt, c.apiKey, uri, bodyHash) + + return fmt.Sprintf("%s;%s;%s;%02x", c.login, timestamp, salt, sha1.Sum([]byte(hashInput))) +} diff --git a/providers/dns/nearlyfreespeech/internal/client_test.go b/providers/dns/nearlyfreespeech/internal/client_test.go new file mode 100644 index 00000000..b5bf30a9 --- /dev/null +++ b/providers/dns/nearlyfreespeech/internal/client_test.go @@ -0,0 +1,148 @@ +package internal + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func setupTest(t *testing.T) (*Client, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + + server := httptest.NewServer(mux) + + client := NewClient("user", "secret") + client.HTTPClient = server.Client() + client.baseURL, _ = url.Parse(server.URL) + + return client, mux +} + +func testHandler(params map[string]string) http.HandlerFunc { + return func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + return + } + + if req.Header.Get(authenticationHeader) == "" { + http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) + return + } + + err := req.ParseForm() + if err != nil { + http.Error(rw, err.Error(), http.StatusBadRequest) + return + } + + for k, v := range params { + if req.PostForm.Get(k) != v { + http.Error(rw, fmt.Sprintf("data: got %s want %s", k, v), http.StatusBadRequest) + return + } + } + } +} + +func testErrorHandler() http.HandlerFunc { + return func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + return + } + + file, err := os.Open("./fixtures/error.json") + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + + rw.WriteHeader(http.StatusUnauthorized) + + _, _ = io.Copy(rw, file) + } +} + +func TestClient_AddRecord(t *testing.T) { + client, mux := setupTest(t) + + params := map[string]string{ + "data": "txtTXTtxt", + "name": "sub", + "type": "TXT", + "ttl": "30", + } + + mux.Handle("/dns/example.com/addRR", testHandler(params)) + + record := Record{ + Name: "sub", + Type: "TXT", + Data: "txtTXTtxt", + TTL: 30, + } + + err := client.AddRecord("example.com", record) + require.NoError(t, err) +} + +func TestClient_AddRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.Handle("/dns/example.com/addRR", testErrorHandler()) + + record := Record{ + Name: "sub", + Type: "TXT", + Data: "txtTXTtxt", + TTL: 30, + } + + err := client.AddRecord("example.com", record) + require.Error(t, err) +} + +func TestClient_RemoveRecord(t *testing.T) { + client, mux := setupTest(t) + + params := map[string]string{ + "data": "txtTXTtxt", + "name": "sub", + "type": "TXT", + } + + mux.Handle("/dns/example.com/removeRR", testHandler(params)) + + record := Record{ + Name: "sub", + Type: "TXT", + Data: "txtTXTtxt", + } + + err := client.RemoveRecord("example.com", record) + require.NoError(t, err) +} + +func TestClient_RemoveRecord_error(t *testing.T) { + client, mux := setupTest(t) + + mux.Handle("/dns/example.com/removeRR", testErrorHandler()) + + record := Record{ + Name: "sub", + Type: "TXT", + Data: "txtTXTtxt", + } + + err := client.RemoveRecord("example.com", record) + require.Error(t, err) +} diff --git a/providers/dns/nearlyfreespeech/internal/fixtures/error.json b/providers/dns/nearlyfreespeech/internal/fixtures/error.json new file mode 100644 index 00000000..96c8a185 --- /dev/null +++ b/providers/dns/nearlyfreespeech/internal/fixtures/error.json @@ -0,0 +1,4 @@ +{ + "error": "The API request could not be authenticated.", + "debug": "The X-NFSN-Authentication header is not present." +} diff --git a/providers/dns/nearlyfreespeech/internal/types.go b/providers/dns/nearlyfreespeech/internal/types.go new file mode 100644 index 00000000..1cc1e294 --- /dev/null +++ b/providers/dns/nearlyfreespeech/internal/types.go @@ -0,0 +1,19 @@ +package internal + +import "fmt" + +type Record struct { + Name string `url:"name,omitempty"` + Type string `url:"type,omitempty"` + Data string `url:"data,omitempty"` + TTL int `url:"ttl,omitempty"` +} + +type APIError struct { + Message string `json:"error"` + Debug string `json:"debug"` +} + +func (a APIError) Error() string { + return fmt.Sprintf("%s: %s", a.Message, a.Debug) +} diff --git a/providers/dns/nearlyfreespeech/nearlyfreespeech.go b/providers/dns/nearlyfreespeech/nearlyfreespeech.go new file mode 100644 index 00000000..b03ba0f9 --- /dev/null +++ b/providers/dns/nearlyfreespeech/nearlyfreespeech.go @@ -0,0 +1,158 @@ +// Package nearlyfreespeech implements a DNS provider for solving the DNS-01 challenge using NearlyFreeSpeech.NET. +package nearlyfreespeech + +import ( + "errors" + "fmt" + "net/http" + "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/nearlyfreespeech/internal" +) + +// Environment variables names. +const ( + envNamespace = "NEARLYFREESPEECH_" + + EnvLogin = envNamespace + "LOGIN" + 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 + Login 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, 3600), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval), + SequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, dns01.DefaultPropagationTimeout), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *internal.Client +} + +// NewDNSProvider returns a DNSProvider instance configured for NearlyFreeSpeech.NET. +// Credentials must be passed in the environment variable: NEARLYFREESPEECH_LOGIN, NEARLYFREESPEECH_API_KEY. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvAPIKey, EnvLogin) + if err != nil { + return nil, fmt.Errorf("nearlyfreespeech: %w", err) + } + + config := NewDefaultConfig() + config.APIKey = values[EnvAPIKey] + config.Login = values[EnvLogin] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for NearlyFreeSpeech.NET. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("nearlyfreespeech: the configuration of the DNS provider is nil") + } + + if config.Login == "" || config.APIKey == "" { + return nil, errors.New("nearlyfreespeech: API credentials are missing") + } + + client := internal.NewClient(config.Login, config.APIKey) + + if config.HTTPClient != nil { + client.HTTPClient = config.HTTPClient + } + + return &DNSProvider{ + config: config, + client: client, + }, 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 { + fqdn, value := dns01.GetRecord(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) + if err != nil { + return fmt.Errorf("nearlyfreespeech: could not determine zone for domain %q: %w", domain, err) + } + + record := internal.Record{ + Name: getRecordName(fqdn, authZone), + Type: "TXT", + Data: value, + TTL: d.config.TTL, + } + + err = d.client.AddRecord(authZone, record) + if err != nil { + return fmt.Errorf("nearlyfreespeech: %w", err) + } + + return nil +} + +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + fqdn, value := dns01.GetRecord(domain, keyAuth) + + authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) + if err != nil { + return fmt.Errorf("nearlyfreespeech: could not determine zone for domain %q: %w", domain, err) + } + + record := internal.Record{ + Name: getRecordName(fqdn, authZone), + Type: "TXT", + Data: value, + } + + err = d.client.RemoveRecord(domain, record) + if err != nil { + return fmt.Errorf("nearlyfreespeech: %w", err) + } + + return nil +} + +func getRecordName(fqdn, authZone string) string { + return fqdn[0 : len(fqdn)-len(authZone)-1] +} diff --git a/providers/dns/nearlyfreespeech/nearlyfreespeech.toml b/providers/dns/nearlyfreespeech/nearlyfreespeech.toml new file mode 100644 index 00000000..482ca5c4 --- /dev/null +++ b/providers/dns/nearlyfreespeech/nearlyfreespeech.toml @@ -0,0 +1,25 @@ +Name = "NearlyFreeSpeech.NET" +Description = '''''' +URL = "https://nearlyfreespeech.net/" +Code = "nearlyfreespeech" +Since = "v4.8.0" + +Example = ''' +NEARLYFREESPEECH_API_KEY=xxxxxx \ +NEARLYFREESPEECH_LOGIN=xxxx \ +lego --email myemail@example.com --dns nearlyfreespeech --domains my.example.org run +''' + +[Configuration] + [Configuration.Credentials] + NEARLYFREESPEECH_API_KEY = "API Key for API requests" + NEARLYFREESPEECH_LOGIN = "Username for API requests" + [Configuration.Additional] + NEARLYFREESPEECH_POLLING_INTERVAL = "Time between DNS propagation check" + NEARLYFREESPEECH_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" + NEARLYFREESPEECH_TTL = "The TTL of the TXT record used for the DNS challenge" + NEARLYFREESPEECH_HTTP_TIMEOUT = "API request timeout" + NEARLYFREESPEECH_SEQUENCE_INTERVAL = "Time between sequential requests" + +[Links] + API = "https://members.nearlyfreespeech.net/wiki/API/Reference" diff --git a/providers/dns/nearlyfreespeech/nearlyfreespeech_test.go b/providers/dns/nearlyfreespeech/nearlyfreespeech_test.go new file mode 100644 index 00000000..adc7efe1 --- /dev/null +++ b/providers/dns/nearlyfreespeech/nearlyfreespeech_test.go @@ -0,0 +1,149 @@ +package nearlyfreespeech + +import ( + "testing" + "time" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvAPIKey, EnvLogin).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvAPIKey: "123", + EnvLogin: "testuser", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{ + EnvAPIKey: "", + EnvLogin: "", + }, + expected: "nearlyfreespeech: some credentials information are missing: NEARLYFREESPEECH_API_KEY,NEARLYFREESPEECH_LOGIN", + }, + { + desc: "missing api key", + envVars: map[string]string{ + EnvAPIKey: "", + EnvLogin: "testuser", + }, + expected: "nearlyfreespeech: some credentials information are missing: NEARLYFREESPEECH_API_KEY", + }, + { + desc: "missing login", + envVars: map[string]string{ + EnvAPIKey: "123", + EnvLogin: "", + }, + expected: "nearlyfreespeech: some credentials information are missing: NEARLYFREESPEECH_LOGIN", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + defer envTest.RestoreEnv() + envTest.ClearEnv() + + envTest.Apply(test.envVars) + + p, err := NewDNSProvider() + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + login string + apikey string + expected string + }{ + { + desc: "success", + login: "login", + apikey: "apikey", + }, + { + desc: "missing credentials", + expected: "nearlyfreespeech: API credentials are missing", + }, + { + desc: "missing login", + login: "", + apikey: "apikey", + expected: "nearlyfreespeech: API credentials are missing", + }, + { + desc: "missing key", + login: "login", + apikey: "", + expected: "nearlyfreespeech: API credentials are missing", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.APIKey = test.apikey + config.Login = test.login + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestLivePresent(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.Present(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} + +func TestLiveCleanUp(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + time.Sleep(1 * time.Second) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +}