lego/providers/dns/infomaniak/internal/client.go

189 lines
4.4 KiB
Go
Raw Normal View History

package internal
import (
"bytes"
2023-05-05 07:49:38 +00:00
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
2023-02-09 16:19:58 +00:00
"strconv"
"strings"
"time"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/log"
2023-05-05 07:49:38 +00:00
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
"golang.org/x/oauth2"
)
2023-05-05 07:49:38 +00:00
// DefaultBaseURL Default API endpoint.
const DefaultBaseURL = "https://api.infomaniak.com"
// Client the Infomaniak client.
type Client struct {
2023-05-05 07:49:38 +00:00
baseURL *url.URL
httpClient *http.Client
}
// New Creates a new Infomaniak client.
2023-05-05 07:49:38 +00:00
func New(hc *http.Client, apiEndpoint string) (*Client, error) {
baseURL, err := url.Parse(apiEndpoint)
if err != nil {
2023-05-05 07:49:38 +00:00
return nil, err
}
2023-05-05 07:49:38 +00:00
if hc == nil {
hc = &http.Client{Timeout: 5 * time.Second}
}
2023-05-05 07:49:38 +00:00
return &Client{baseURL: baseURL, httpClient: hc}, nil
}
func (c *Client) CreateDNSRecord(ctx context.Context, domain *DNSDomain, record Record) (string, error) {
endpoint := c.baseURL.JoinPath("1", "domain", strconv.FormatUint(domain.ID, 10), "dns", "record")
req, err := newJSONRequest(ctx, http.MethodPost, endpoint, record)
2023-02-09 16:19:58 +00:00
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
2023-05-05 07:49:38 +00:00
result := APIResponse[string]{}
err = c.do(req, &result)
if err != nil {
return "", err
}
2023-05-05 07:49:38 +00:00
return result.Data, err
}
2023-05-05 07:49:38 +00:00
func (c *Client) DeleteDNSRecord(ctx context.Context, domainID uint64, recordID string) error {
endpoint := c.baseURL.JoinPath("1", "domain", strconv.FormatUint(domainID, 10), "dns", "record", recordID)
2023-05-05 07:49:38 +00:00
req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil)
2023-02-09 16:19:58 +00:00
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
2023-05-05 07:49:38 +00:00
return c.do(req, &APIResponse[json.RawMessage]{})
}
// GetDomainByName gets a Domain object from its name.
2023-05-05 07:49:38 +00:00
func (c *Client) GetDomainByName(ctx context.Context, name string) (*DNSDomain, error) {
name = dns01.UnFqdn(name)
// Try to find the most specific domain
// starts with the FQDN, then remove each left label until we have a match
for {
i := strings.Index(name, ".")
if i == -1 {
break
}
2023-05-05 07:49:38 +00:00
domain, err := c.getDomainByName(ctx, name)
if err != nil {
return nil, err
}
if domain != nil {
return domain, nil
}
log.Infof("domain %q not found, trying with %q", name, name[i+1:])
name = name[i+1:]
}
return nil, fmt.Errorf("domain not found %s", name)
}
2023-05-05 07:49:38 +00:00
func (c *Client) getDomainByName(ctx context.Context, name string) (*DNSDomain, error) {
endpoint := c.baseURL.JoinPath("1", "product")
2023-02-09 16:19:58 +00:00
query := endpoint.Query()
query.Add("service_name", "domain")
query.Add("customer_name", name)
2023-02-09 16:19:58 +00:00
endpoint.RawQuery = query.Encode()
2023-05-05 07:49:38 +00:00
req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
2023-05-05 07:49:38 +00:00
result := APIResponse[[]DNSDomain]{}
err = c.do(req, &result)
if err != nil {
return nil, err
}
2023-05-05 07:49:38 +00:00
for _, domain := range result.Data {
if domain.CustomerName == name {
return &domain, nil
}
}
return nil, nil
}
2023-05-05 07:49:38 +00:00
func (c *Client) do(req *http.Request, result Response) error {
resp, err := c.httpClient.Do(req)
if err != nil {
return errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
2023-02-09 16:19:58 +00:00
2023-05-05 07:49:38 +00:00
raw, err := io.ReadAll(resp.Body)
if err != nil {
2023-05-05 07:49:38 +00:00
return errutils.NewReadResponseError(req, resp.StatusCode, err)
}
2023-05-05 07:49:38 +00:00
if err := json.Unmarshal(raw, result); err != nil {
return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
}
if result.GetResult() != "success" {
return fmt.Errorf("%d: unexpected API result (%s): %w", resp.StatusCode, result.GetResult(), result.GetError())
}
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)
}
}
2023-05-05 07:49:38 +00:00
req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf)
if err != nil {
2023-05-05 07:49:38 +00:00
return nil, fmt.Errorf("unable to create request: %w", err)
}
2023-05-05 07:49:38 +00:00
req.Header.Set("Accept", "application/json")
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
}
func OAuthStaticAccessToken(client *http.Client, accessToken string) *http.Client {
if client == nil {
client = &http.Client{Timeout: 5 * time.Second}
}
2023-05-05 07:49:38 +00:00
client.Transport = &oauth2.Transport{
Source: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}),
Base: client.Transport,
}
2023-05-05 07:49:38 +00:00
return client
}