1
0
mirror of https://github.com/go-acme/lego.git synced 2024-12-23 01:07:23 +02:00

Add DNS provider for Timeweb Cloud (#2301)

Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
Pavel Sobolev 2024-10-14 02:03:41 +03:00 committed by GitHub
parent ce0808a122
commit 755164c939
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 751 additions and 7 deletions

View File

@ -82,12 +82,12 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
| [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/) | [SelfHost.(de/eu)](https://go-acme.github.io/lego/dns/selfhostde/) |
| [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/) | [Volcano Engine/火山引擎](https://go-acme.github.io/lego/dns/volcengine/) |
| [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/) | | |
| [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | [Timeweb Cloud](https://go-acme.github.io/lego/dns/timewebcloud/) | [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/) |
| [Volcano Engine/火山引擎](https://go-acme.github.io/lego/dns/volcengine/) | [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/) | |
<!-- END DNS PROVIDERS LIST -->

View File

@ -131,6 +131,7 @@ func allDNSCodes() string {
"sonic",
"stackpath",
"tencentcloud",
"timewebcloud",
"transip",
"ultradns",
"variomedia",
@ -2705,6 +2706,25 @@ func displayDNSHelp(w io.Writer, name string) error {
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/tencentcloud`)
case "timewebcloud":
// generated from: providers/dns/timewebcloud/timewebcloud.toml
ew.writeln(`Configuration for Timeweb Cloud.`)
ew.writeln(`Code: 'timewebcloud'`)
ew.writeln(`Since: 'v4.20.0'`)
ew.writeln()
ew.writeln(`Credentials:`)
ew.writeln(` - "TIMEWEBCLOUD_AUTH_TOKEN": Authentication token`)
ew.writeln()
ew.writeln(`Additional Configuration:`)
ew.writeln(` - "TIMEWEBCLOUD_HTTP_TIMEOUT": API request timeout`)
ew.writeln(` - "TIMEWEBCLOUD_POLLING_INTERVAL": Time between DNS propagation check`)
ew.writeln(` - "TIMEWEBCLOUD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`)
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/timewebcloud`)
case "transip":
// generated from: providers/dns/transip/transip.toml
ew.writeln(`Configuration for TransIP.`)

View File

@ -0,0 +1,66 @@
---
title: "Timeweb Cloud"
date: 2019-03-03T16:39:46+01:00
draft: false
slug: timewebcloud
dnsprovider:
since: "v4.20.0"
code: "timewebcloud"
url: "https://timeweb.cloud/"
---
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/timewebcloud/timewebcloud.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
Configuration for [Timeweb Cloud](https://timeweb.cloud/).
<!--more-->
- Code: `timewebcloud`
- Since: v4.20.0
Here is an example bash command using the Timeweb Cloud provider:
```bash
TIMEWEBCLOUD_AUTH_TOKEN=xxxxxx \
lego --email you@example.com --dns timewebcloud --domains my.example.org run
```
## Credentials
| Environment Variable Name | Description |
|-----------------------|-------------|
| `TIMEWEBCLOUD_AUTH_TOKEN` | Authentication token |
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 |
|--------------------------------|-------------|
| `TIMEWEBCLOUD_HTTP_TIMEOUT` | API request timeout |
| `TIMEWEBCLOUD_POLLING_INTERVAL` | Time between DNS propagation check |
| `TIMEWEBCLOUD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation |
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://timeweb.cloud/api-docs)
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/timewebcloud/timewebcloud.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->

View File

@ -141,7 +141,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, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mijnhost, mittwald, 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, selfhostde, servercow, shellrent, simply, sonic, stackpath, tencentcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, volcengine, 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, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manual, metaname, mijnhost, mittwald, 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, selfhostde, servercow, shellrent, simply, sonic, stackpath, tencentcloud, timewebcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, volcengine, vscale, vultr, webnames, websupport, wedos, yandex, yandex360, yandexcloud, zoneee, zonomi
More information: https://go-acme.github.io/lego/dns
"""

View File

@ -123,6 +123,7 @@ import (
"github.com/go-acme/lego/v4/providers/dns/sonic"
"github.com/go-acme/lego/v4/providers/dns/stackpath"
"github.com/go-acme/lego/v4/providers/dns/tencentcloud"
"github.com/go-acme/lego/v4/providers/dns/timewebcloud"
"github.com/go-acme/lego/v4/providers/dns/transip"
"github.com/go-acme/lego/v4/providers/dns/ultradns"
"github.com/go-acme/lego/v4/providers/dns/variomedia"
@ -385,6 +386,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
return stackpath.NewDNSProvider()
case "tencentcloud":
return tencentcloud.NewDNSProvider()
case "timewebcloud":
return timewebcloud.NewDNSProvider()
case "transip":
return transip.NewDNSProvider()
case "ultradns":

View File

@ -0,0 +1,149 @@
package internal
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
"golang.org/x/oauth2"
)
const defaultBaseURL = "https://api.timeweb.cloud/api"
// Client Timeweb Cloud client.
type Client struct {
baseURL *url.URL
httpClient *http.Client
}
// NewClient creates a Client.
func NewClient(hc *http.Client) *Client {
baseURL, _ := url.Parse(defaultBaseURL)
if hc == nil {
hc = &http.Client{Timeout: 10 * time.Second}
}
return &Client{
baseURL: baseURL,
httpClient: hc,
}
}
// CreateRecord creates a DNS record.
// https://timeweb.cloud/api-docs#tag/Domeny/operation/createDomainDNSRecord
func (c *Client) CreateRecord(ctx context.Context, zone string, record DNSRecord) (*DNSRecord, error) {
endpoint := c.baseURL.JoinPath("v1", "domains", dns01.UnFqdn(zone), "dns-records")
req, err := newJSONRequest(ctx, http.MethodPost, endpoint, record)
if err != nil {
return nil, err
}
respData := &CreateRecordResponse{}
err = c.do(req, respData)
if err != nil {
return nil, err
}
return respData.DNSRecord, nil
}
// DeleteRecord deletes a DNS record.
// https://timeweb.cloud/api-docs#tag/Domeny/operation/deleteDomainDNSRecord
func (c *Client) DeleteRecord(ctx context.Context, zone string, recordID int) error {
endpoint := c.baseURL.JoinPath("v1", "domains", dns01.UnFqdn(zone), "dns-records", strconv.Itoa(recordID))
req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil)
if err != nil {
return err
}
return c.do(req, nil)
}
func (c *Client) do(req *http.Request, result any) error {
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 response ErrorResponse
err := json.Unmarshal(raw, &response)
if err != nil {
return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw)
}
return response
}
func OAuthStaticAccessToken(client *http.Client, accessToken string) *http.Client {
if client == nil {
client = &http.Client{Timeout: 10 * time.Second}
}
client.Transport = &oauth2.Transport{
Source: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}),
Base: client.Transport,
}
return client
}

View File

@ -0,0 +1,152 @@
package internal
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupTest(t *testing.T) (*Client, *http.ServeMux) {
t.Helper()
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client := NewClient(OAuthStaticAccessToken(server.Client(), "secret"))
client.baseURL, _ = url.Parse(server.URL)
return client, mux
}
func checkAuthorizationHeader(req *http.Request) error {
val := req.Header.Get("Authorization")
if val != "Bearer secret" {
return fmt.Errorf("invalid header value, got: %s want %s", val, "Bearer secret")
}
return nil
}
func writeResponse(rw http.ResponseWriter, statusCode int, filename string) error {
file, err := os.Open(filepath.Join("fixtures", filename))
if err != nil {
return err
}
defer func() { _ = file.Close() }()
rw.WriteHeader(statusCode)
_, err = io.Copy(rw, file)
if err != nil {
return err
}
return nil
}
func TestClient_CreateRecord(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("POST /v1/domains/example.com/dns-records", func(rw http.ResponseWriter, req *http.Request) {
err := checkAuthorizationHeader(req)
if err != nil {
http.Error(rw, err.Error(), http.StatusUnauthorized)
return
}
content, err := io.ReadAll(req.Body)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if string(bytes.TrimSpace(content)) != `{"type":"TXT","value":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","subdomain":"_acme-challenge"}` {
http.Error(rw, "invalid request body: "+string(content), http.StatusBadRequest)
return
}
err = writeResponse(rw, http.StatusOK, "createDomainDNSRecord.json")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
})
payload := DNSRecord{
Type: "TXT",
Value: "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI",
SubDomain: "_acme-challenge",
}
response, err := client.CreateRecord(context.Background(), "example.com.", payload)
require.NoError(t, err)
expected := &DNSRecord{
Type: "TXT",
ID: 123,
}
assert.Equal(t, expected, response)
}
func TestClient_CreateRecord_error(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("POST /v1/domains/example.com/dns-records", func(rw http.ResponseWriter, _ *http.Request) {
err := writeResponse(rw, http.StatusBadRequest, "error_bad_request.json")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
})
_, err := client.CreateRecord(context.Background(), "example.com.", DNSRecord{})
require.Error(t, err)
assert.EqualError(t, err, "400: Value must be a number conforming to the specified constraints (bad_request) [15095f25-aac3-4d60-a788-96cb5136f186]")
}
func TestClient_DeleteRecord(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("DELETE /v1/domains/example.com/dns-records/123", func(rw http.ResponseWriter, req *http.Request) {
err := checkAuthorizationHeader(req)
if err != nil {
http.Error(rw, err.Error(), http.StatusUnauthorized)
return
}
rw.WriteHeader(http.StatusNoContent)
})
err := client.DeleteRecord(context.Background(), "example.com.", 123)
require.NoError(t, err)
}
func TestClient_DeleteRecord_error(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("DELETE /v1/domains/example.com/dns-records/123", func(rw http.ResponseWriter, _ *http.Request) {
err := writeResponse(rw, http.StatusBadRequest, "error_unauthorized.json")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
})
err := client.DeleteRecord(context.Background(), "example.com.", 123)
require.Error(t, err)
assert.EqualError(t, err, "401: Unauthorized (unauthorized) [15095f25-aac3-4d60-a788-96cb5136f186]")
}

View File

@ -0,0 +1,12 @@
{
"dns_record": {
"type": "TXT",
"id": 123,
"data": {
"priority": 0,
"subdomain": "example.com",
"value": "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI"
}
},
"response_id": "15095f25-aac3-4d60-a788-96cb5136f186"
}

View File

@ -0,0 +1,8 @@
{
"status_code": 400,
"message": "Value must be a number conforming to the specified constraints",
"error_code": "bad_request",
"response_id": "15095f25-aac3-4d60-a788-96cb5136f186"
}

View File

@ -0,0 +1,6 @@
{
"status_code": 401,
"message": "Unauthorized",
"error_code": "unauthorized",
"response_id": "15095f25-aac3-4d60-a788-96cb5136f186"
}

View File

@ -0,0 +1,8 @@
There is an [official API client](https://github.com/timeweb-cloud/sdk-go) but this client is completely broken:
- the code is generated and the module name is `github.com/GIT_USER_ID/GIT_REPO_ID`
- the code contains redeclared constants
- Even with fixes to the module name and the redeclared constants, the module doesn't compile.
https://github.com/timeweb-cloud/sdk-go/pull/1
So, for now, this API client is unusable.

View File

@ -0,0 +1,25 @@
package internal
import "fmt"
type DNSRecord struct {
ID int `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Value string `json:"value,omitempty"`
SubDomain string `json:"subdomain,omitempty"`
}
type CreateRecordResponse struct {
DNSRecord *DNSRecord `json:"dns_record,omitempty"`
}
type ErrorResponse struct {
StatusCode int `json:"status_code,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Message string `json:"message,omitempty"`
ResponseID string `json:"response_id,omitempty"`
}
func (a ErrorResponse) Error() string {
return fmt.Sprintf("%d: %s (%s) [%s]", a.StatusCode, a.Message, a.ErrorCode, a.ResponseID)
}

View File

@ -0,0 +1,154 @@
// Package timewebcloud implements a DNS provider for solving the DNS-01 challenge using Timeweb Cloud.
package timewebcloud
import (
"context"
"errors"
"fmt"
"net/http"
"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/timewebcloud/internal"
)
// Environment variables names.
const (
envNamespace = "TIMEWEBCLOUD_"
EnvAuthToken = envNamespace + "AUTH_TOKEN"
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 {
AuthToken string
HTTPClient *http.Client
PropagationTimeout time.Duration
PollingInterval time.Duration
}
// NewDefaultConfig returns a default configuration for the DNSProvider.
func NewDefaultConfig() *Config {
return &Config{
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 10*time.Second),
},
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
config *Config
client *internal.Client
recordIDs map[string]int
recordIDsMu sync.Mutex
}
// NewDNSProvider returns a DNSProvider instance configured for Timeweb Cloud.
// API token must be passed in the environment variable TIMEWEBCLOUD_TOKEN.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvAuthToken)
if err != nil {
return nil, fmt.Errorf("timewebcloud: %w", err)
}
config := NewDefaultConfig()
config.AuthToken = values[EnvAuthToken]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig returns a DNSProvider instance configured for Timeweb Cloud.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("timewebcloud: the configuration of the DNS provider is nil")
}
if config.AuthToken == "" {
return nil, errors.New("timewebcloud: authentication token is missing")
}
client := internal.NewClient(internal.OAuthStaticAccessToken(config.HTTPClient, config.AuthToken))
return &DNSProvider{
config: config,
client: client,
recordIDs: 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
}
// 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)
authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("timewebcloud: could not find zone for domain %q: %w", domain, err)
}
subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, authZone)
if err != nil {
return fmt.Errorf("timewebcloud: %w", err)
}
record := internal.DNSRecord{
Type: "TXT",
Value: info.Value,
SubDomain: subDomain,
}
response, err := d.client.CreateRecord(context.Background(), authZone, record)
if err != nil {
return fmt.Errorf("timewebcloud: %w", err)
}
d.recordIDsMu.Lock()
d.recordIDs[token] = response.ID
d.recordIDsMu.Unlock()
return nil
}
// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
info := dns01.GetChallengeInfo(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("timewebcloud: could not find zone for domain %q: %w", domain, err)
}
d.recordIDsMu.Lock()
recordID, ok := d.recordIDs[token]
d.recordIDsMu.Unlock()
if !ok {
return fmt.Errorf("timewebcloud: unknown record ID for '%s'", info.EffectiveFQDN)
}
err = d.client.DeleteRecord(context.Background(), authZone, recordID)
if err != nil {
return fmt.Errorf("timewebcloud: %w", err)
}
d.recordIDsMu.Lock()
delete(d.recordIDs, token)
d.recordIDsMu.Unlock()
return nil
}

View File

@ -0,0 +1,21 @@
Name = "Timeweb Cloud"
Description = ''''''
URL = "https://timeweb.cloud/"
Code = "timewebcloud"
Since = "v4.20.0"
Example = '''
TIMEWEBCLOUD_AUTH_TOKEN=xxxxxx \
lego --email you@example.com --dns timewebcloud --domains my.example.org run
'''
[Configuration]
[Configuration.Credentials]
TIMEWEBCLOUD_AUTH_TOKEN = "Authentication token"
[Configuration.Additional]
TIMEWEBCLOUD_POLLING_INTERVAL = "Time between DNS propagation check"
TIMEWEBCLOUD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
TIMEWEBCLOUD_HTTP_TIMEOUT = "API request timeout"
[Links]
API = "https://timeweb.cloud/api-docs"

View File

@ -0,0 +1,120 @@
package timewebcloud
import (
"testing"
"time"
"github.com/go-acme/lego/v4/platform/tester"
"github.com/stretchr/testify/require"
)
const envDomain = envNamespace + "DOMAIN"
var envTest = tester.NewEnvTest(EnvAuthToken).WithDomain(envDomain)
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
EnvAuthToken: "johndoe",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
EnvAuthToken: "",
},
expected: "timewebcloud: some credentials information are missing: TIMEWEBCLOUD_AUTH_TOKEN",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer envTest.RestoreEnv()
envTest.ClearEnv()
envTest.Apply(test.envVars)
p, err := NewDNSProvider()
if test.expected == "" {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
authToken string
expected string
}{
{
desc: "success",
authToken: "123",
},
{
desc: "missing credentials",
expected: "timewebcloud: authentication token is missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
config := NewDefaultConfig()
config.AuthToken = test.authToken
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)
require.NotNil(t, p.recordIDs)
} 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)
}