Add Vercel DNS provider (#1635)

Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
Gregory Schier 2022-04-29 13:50:39 -07:00 committed by GitHub
parent b2a64f0489
commit 122cdb64e4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 680 additions and 3 deletions

View file

@ -69,9 +69,9 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
| [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/) | [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/) | | | |
| [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/) | | |
<!-- END DNS PROVIDERS LIST -->

View file

@ -106,6 +106,7 @@ func allDNSCodes() string {
"tencentcloud",
"transip",
"vegadns",
"vercel",
"versio",
"vinyldns",
"vscale",
@ -2084,6 +2085,27 @@ func displayDNSHelp(name string) error {
ew.writeln()
ew.writeln(`More information: https://go-acme.github.io/lego/dns/vegadns`)
case "vercel":
// generated from: providers/dns/vercel/vercel.toml
ew.writeln(`Configuration for Vercel.`)
ew.writeln(`Code: 'vercel'`)
ew.writeln(`Since: 'v4.7.0'`)
ew.writeln()
ew.writeln(`Credentials:`)
ew.writeln(` - "VERCEL_API_TOKEN": Authentication token`)
ew.writeln()
ew.writeln(`Additional Configuration:`)
ew.writeln(` - "VERCEL_HTTP_TIMEOUT": API request timeout`)
ew.writeln(` - "VERCEL_POLLING_INTERVAL": Time between DNS propagation check`)
ew.writeln(` - "VERCEL_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`)
ew.writeln(` - "VERCEL_TEAM_ID": Team ID (ex: team_xxxxxxxxxxxxxxxxxxxxxxxx)`)
ew.writeln(` - "VERCEL_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/vercel`)
case "versio":
// generated from: providers/dns/versio/versio.toml
ew.writeln(`Configuration for Versio.[nl|eu|uk].`)

View file

@ -0,0 +1,63 @@
---
title: "Vercel"
date: 2019-03-03T16:39:46+01:00
draft: false
slug: vercel
---
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/vercel/vercel.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
Since: v4.7.0
Configuration for [Vercel](https://vercel.com).
<!--more-->
- Code: `vercel`
Here is an example bash command using the Vercel provider:
```bash
VERCEL_API_TOKEN=xxxxxx \
lego --email myemail@example.com --dns vercel --domains my.example.org run
```
## Credentials
| Environment Variable Name | Description |
|-----------------------|-------------|
| `VERCEL_API_TOKEN` | Authentication token |
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 |
|--------------------------------|-------------|
| `VERCEL_HTTP_TIMEOUT` | API request timeout |
| `VERCEL_POLLING_INTERVAL` | Time between DNS propagation check |
| `VERCEL_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation |
| `VERCEL_TEAM_ID` | Team ID (ex: team_xxxxxxxxxxxxxxxxxxxxxxxx) |
| `VERCEL_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://vercel.com/docs/rest-api#endpoints/dns)
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->
<!-- providers/dns/vercel/vercel.toml -->
<!-- THIS DOCUMENTATION IS AUTO-GENERATED. PLEASE DO NOT EDIT. -->

View file

@ -97,6 +97,7 @@ import (
"github.com/go-acme/lego/v4/providers/dns/tencentcloud"
"github.com/go-acme/lego/v4/providers/dns/transip"
"github.com/go-acme/lego/v4/providers/dns/vegadns"
"github.com/go-acme/lego/v4/providers/dns/vercel"
"github.com/go-acme/lego/v4/providers/dns/versio"
"github.com/go-acme/lego/v4/providers/dns/vinyldns"
"github.com/go-acme/lego/v4/providers/dns/vscale"
@ -296,6 +297,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
return transip.NewDNSProvider()
case "vegadns":
return vegadns.NewDNSProvider()
case "vercel":
return vercel.NewDNSProvider()
case "versio":
return versio.NewDNSProvider()
case "vinyldns":

View file

@ -0,0 +1,143 @@
package internal
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"time"
"github.com/go-acme/lego/v4/challenge/dns01"
)
const defaultBaseURL = "https://api.vercel.com"
// Client Vercel client.
type Client struct {
authToken string
teamID string
baseURL *url.URL
HTTPClient *http.Client
}
// NewClient creates a Client.
func NewClient(authToken string, teamID string) *Client {
baseURL, _ := url.Parse(defaultBaseURL)
return &Client{
authToken: authToken,
teamID: teamID,
baseURL: baseURL,
HTTPClient: &http.Client{Timeout: 10 * time.Second},
}
}
// CreateRecord creates a DNS record.
// https://vercel.com/docs/rest-api#endpoints/dns/create-a-dns-record
func (c *Client) CreateRecord(zone string, record Record) (*CreateRecordResponse, error) {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "v2", "domains", dns01.UnFqdn(zone), "records"))
if err != nil {
return nil, err
}
body, err := json.Marshal(record)
if err != nil {
return nil, err
}
req, err := c.newRequest(http.MethodPost, endpoint.String(), bytes.NewReader(body))
if err != nil {
return nil, err
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 400 {
return nil, readError(req, resp)
}
content, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.New(toUnreadableBodyMessage(req, content))
}
// Everything looks good; but we'll need the ID later to delete the record
respData := &CreateRecordResponse{}
err = json.Unmarshal(content, respData)
if err != nil {
return nil, fmt.Errorf("%w: %s", err, toUnreadableBodyMessage(req, content))
}
return respData, nil
}
// DeleteRecord deletes a DNS record.
// https://vercel.com/docs/rest-api#endpoints/dns/delete-a-dns-record
func (c *Client) DeleteRecord(zone string, recordID string) error {
endpoint, err := c.baseURL.Parse(path.Join(c.baseURL.Path, "v2", "domains", dns01.UnFqdn(zone), "records", recordID))
if err != nil {
return err
}
req, err := c.newRequest(http.MethodDelete, endpoint.String(), nil)
if err != nil {
return err
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 400 {
return readError(req, resp)
}
return nil
}
func (c *Client) newRequest(method, reqURL string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, reqURL, body)
if err != nil {
return nil, err
}
if c.teamID != "" {
query := req.URL.Query()
query.Add("teamId", c.teamID)
req.URL.RawQuery = query.Encode()
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.authToken))
return req, nil
}
func readError(req *http.Request, resp *http.Response) error {
content, err := io.ReadAll(resp.Body)
if err != nil {
return errors.New(toUnreadableBodyMessage(req, content))
}
var errInfo APIErrorResponse
err = json.Unmarshal(content, &errInfo)
if err != nil {
return fmt.Errorf("API Error unmarshaling error: %w: %s", err, toUnreadableBodyMessage(req, content))
}
return fmt.Errorf("HTTP %d: %w", resp.StatusCode, errInfo.Error)
}
func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string {
return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody))
}

View file

@ -0,0 +1,114 @@
package internal
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setup(t *testing.T) (*Client, *http.ServeMux) {
t.Helper()
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client := NewClient("secret", "123")
client.HTTPClient = server.Client()
client.baseURL, _ = url.Parse(server.URL)
return client, mux
}
func TestClient_CreateRecord(t *testing.T) {
client, mux := setup(t)
mux.HandleFunc("/v2/domains/example.com/records", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return
}
auth := req.Header.Get("Authorization")
if auth != "Bearer secret" {
http.Error(rw, fmt.Sprintf("invalid API token: %s", auth), http.StatusUnauthorized)
return
}
teamID := req.URL.Query().Get("teamId")
if teamID != "123" {
http.Error(rw, fmt.Sprintf("invalid team ID: %s", teamID), http.StatusUnauthorized)
return
}
reqBody, err := io.ReadAll(req.Body)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
expectedReqBody := `{"name":"_acme-challenge.example.com.","type":"TXT","value":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":60}`
assert.Equal(t, expectedReqBody, string(reqBody))
rw.WriteHeader(http.StatusOK)
_, err = fmt.Fprintf(rw, `{
"uid": "9e2eab60-0ba5-4dff-b481-2999c9764b84",
"updated": 1
}`)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
})
record := Record{
Name: "_acme-challenge.example.com.",
Type: "TXT",
Value: "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI",
TTL: 60,
}
resp, err := client.CreateRecord("example.com.", record)
require.NoError(t, err)
expected := &CreateRecordResponse{
UID: "9e2eab60-0ba5-4dff-b481-2999c9764b84",
Updated: 1,
}
assert.Equal(t, expected, resp)
}
func TestClient_DeleteRecord(t *testing.T) {
client, mux := setup(t)
mux.HandleFunc("/v2/domains/example.com/records/1234567", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return
}
auth := req.Header.Get("Authorization")
if auth != "Bearer secret" {
http.Error(rw, fmt.Sprintf("invalid API token: %s", auth), http.StatusUnauthorized)
return
}
teamID := req.URL.Query().Get("teamId")
if teamID != "123" {
http.Error(rw, fmt.Sprintf("invalid team ID: %s", teamID), http.StatusUnauthorized)
return
}
rw.WriteHeader(http.StatusOK)
})
err := client.DeleteRecord("example.com.", "1234567")
require.NoError(t, err)
}

View file

@ -0,0 +1,31 @@
package internal
import "fmt"
type Record struct {
ID string `json:"id,omitempty"`
Slug string `json:"slug,omitempty"`
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Value string `json:"value,omitempty"`
TTL int `json:"ttl,omitempty"`
}
// CreateRecordResponse represents a response from Vercel's API after making a DNS record.
type CreateRecordResponse struct {
UID string `json:"uid"`
Updated int `json:"updated,omitempty"`
}
type APIErrorResponse struct {
Error *APIError `json:"error"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (a APIError) Error() string {
return fmt.Sprintf("%s: %s", a.Code, a.Message)
}

View file

@ -0,0 +1,160 @@
// Package vercel implements a DNS provider for solving the DNS-01 challenge using Vercel DNS.
package vercel
import (
"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/vercel/internal"
)
// Environment variables names.
const (
envNamespace = "VERCEL_"
EnvAuthToken = envNamespace + "API_TOKEN"
EnvTeamID = envNamespace + "TEAM_ID"
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 {
AuthToken string
TeamID string
TTL int
PropagationTimeout time.Duration
PollingInterval 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, 60*time.Second),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 5*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
recordIDs map[string]string
recordIDsMu sync.Mutex
}
// NewDNSProvider returns a DNSProvider instance configured for Vercel.
// Credentials must be passed in the environment variables: VERCEL_API_TOKEN, VERCEL_TEAM_ID.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvAuthToken)
if err != nil {
return nil, fmt.Errorf("vercel: %w", err)
}
config := NewDefaultConfig()
config.AuthToken = values[EnvAuthToken]
config.TeamID = env.GetOrDefaultString(EnvTeamID, "")
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for Digital Ocean.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("vercel: the configuration of the DNS provider is nil")
}
if config.AuthToken == "" {
return nil, errors.New("vercel: credentials missing")
}
client := internal.NewClient(config.AuthToken, config.TeamID)
if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}
return &DNSProvider{
config: config,
client: client,
recordIDs: make(map[string]string),
}, nil
}
// Timeout returns the timeout and interval to use when checking for DNS propagation.
// Adjusting here to cope with spikes in propagation times.
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
return d.config.PropagationTimeout, d.config.PollingInterval
}
// Present creates a TXT record using the specified parameters.
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value := dns01.GetRecord(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain))
if err != nil {
return fmt.Errorf("vercel: could not determine zone for domain %q: %w", domain, err)
}
record := internal.Record{
Name: fqdn,
Type: "TXT",
Value: value,
TTL: d.config.TTL,
}
respData, err := d.client.CreateRecord(authZone, record)
if err != nil {
return fmt.Errorf("vercel: %w", err)
}
d.recordIDsMu.Lock()
d.recordIDs[token] = respData.UID
d.recordIDsMu.Unlock()
return nil
}
// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
fqdn, _ := dns01.GetRecord(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return fmt.Errorf("vercel: %w", err)
}
// get the record's unique ID from when we created it
d.recordIDsMu.Lock()
recordID, ok := d.recordIDs[token]
d.recordIDsMu.Unlock()
if !ok {
return fmt.Errorf("vercel: unknown record ID for '%s'", fqdn)
}
err = d.client.DeleteRecord(authZone, recordID)
if err != nil {
return fmt.Errorf("vercel: %w", err)
}
// Delete record ID from map
d.recordIDsMu.Lock()
delete(d.recordIDs, token)
d.recordIDsMu.Unlock()
return nil
}

View file

@ -0,0 +1,23 @@
Name = "Vercel"
Description = ''''''
URL = "https://vercel.com"
Code = "vercel"
Since = "v4.7.0"
Example = '''
VERCEL_API_TOKEN=xxxxxx \
lego --email myemail@example.com --dns vercel --domains my.example.org run
'''
[Configuration]
[Configuration.Credentials]
VERCEL_API_TOKEN = "Authentication token"
[Configuration.Additional]
VERCEL_TEAM_ID = "Team ID (ex: team_xxxxxxxxxxxxxxxxxxxxxxxx)"
VERCEL_POLLING_INTERVAL = "Time between DNS propagation check"
VERCEL_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation"
VERCEL_TTL = "The TTL of the TXT record used for the DNS challenge"
VERCEL_HTTP_TIMEOUT = "API request timeout"
[Links]
API = "https://vercel.com/docs/rest-api#endpoints/dns"

View file

@ -0,0 +1,118 @@
package vercel
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: "123",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
EnvAuthToken: "",
},
expected: "vercel: some credentials information are missing: VERCEL_API_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.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: "vercel: credentials 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.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)
}