-
Notifications
You must be signed in to change notification settings - Fork 3
/
solver.go
234 lines (195 loc) · 6.61 KB
/
solver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package main
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
"github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
exoscale "github.com/exoscale/egoscale/v2"
exoapi "github.com/exoscale/egoscale/v2/api"
)
const providerName = "exoscale"
var (
recordTypeTXT = "TXT"
recordTTL = 60
)
// ExoscaleSolver implements the `github.com/jetstack/cert-manager/pkg/acme/webhook.Solver`
// interface and allows cert-manager to use [exoscale DNS] for DNS01 challenge.
//
// [exoscale DNS]: https://community.exoscale.com/documentation/dns/
type ExoscaleSolver struct {
kClient *kubernetes.Clientset
logger Logger
}
// Name is used as the name for this DNS solver when referencing it on the ACME
// Issuer resource.
func (c *ExoscaleSolver) Name() string {
return providerName
}
// Initialize will be called when the webhook first starts.
// The kubeClientConfig parameter is used to build a Kubernetes
// client that will be used to fetch Secret resources containing
// credentials used to authenticate with Exoscale API.
func (c *ExoscaleSolver) Initialize(kubeClientConfig *rest.Config, _ <-chan struct{}) error {
c.logger = Logger{}
// debug can be set only through environment.
if os.Getenv(envDebug) != "" {
c.logger.Verbose = true
}
c.logger.Debug("call function Initialize")
cl, err := kubernetes.NewForConfig(kubeClientConfig)
if err != nil {
return err
}
c.kClient = cl
return nil
}
// Present is responsible for actually presenting the DNS record with the
// Exoscale DNS.
func (c *ExoscaleSolver) Present(ch *v1alpha1.ChallengeRequest) error {
c.logger.Debugf("call function Present: namespace=%s, zone=%s, fqdn=%s",
ch.ResourceNamespace, ch.ResolvedZone, ch.ResolvedFQDN)
config, err := LoadConfig(ch.Config)
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
client, err := c.apiClient(ch, config)
if err != nil {
return fmt.Errorf("failed to initialize API client: %w", err)
}
ctx := exoapi.WithEndpoint(
context.Background(),
exoapi.NewReqEndpoint(config.APIEnvironment, config.APIZone),
)
domain, err := c.findDomain(ctx, client, config.APIZone, strings.TrimSuffix(ch.ResolvedZone, "."))
if err != nil {
return err
}
recordName := strings.TrimSuffix(strings.TrimSuffix(ch.ResolvedFQDN, ch.ResolvedZone), ".")
t := int64(recordTTL)
record := exoscale.DNSDomainRecord{
Name: &recordName,
Type: &recordTypeTXT,
TTL: &t,
Content: &ch.Key,
}
_, err = client.CreateDNSDomainRecord(ctx, config.APIZone, *domain.ID, &record)
if err != nil {
return fmt.Errorf("failed to create domain record: %w", err)
}
return nil
}
// CleanUp deletes the relevant TXT record from the Exoscale DNS.
func (c *ExoscaleSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
c.logger.Debugf("call function CleanUp: namespace=%s, zone=%s, fqdn=%s",
ch.ResourceNamespace, ch.ResolvedZone, ch.ResolvedFQDN)
config, err := LoadConfig(ch.Config)
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
client, err := c.apiClient(ch, config)
if err != nil {
return fmt.Errorf("failed to initialize API client: %w", err)
}
ctx := exoapi.WithEndpoint(
context.Background(),
exoapi.NewReqEndpoint(config.APIEnvironment, config.APIZone),
)
domain, err := c.findDomain(ctx, client, config.APIZone, strings.TrimSuffix(ch.ResolvedZone, "."))
if err != nil {
return err
}
records, err := client.ListDNSDomainRecords(ctx, config.APIZone, *domain.ID)
if err != nil {
return err
}
recordName := strings.TrimSuffix(strings.TrimSuffix(ch.ResolvedFQDN, ch.ResolvedZone), ".")
for _, record := range records {
// we must unquote TXT records as we receive "\"123d==\"" when we expect "123d=="
content, _ := strconv.Unquote(*record.Content)
if *record.Type == recordTypeTXT &&
*record.Name == recordName &&
content == ch.Key {
return client.DeleteDNSDomainRecord(ctx, config.APIZone, *domain.ID, &record)
}
}
c.logger.Infof("domain record %q not found, nothing to do", recordName)
return nil
}
// findDomain is a helper that iterates through domain list to find a domain by name.
// This is needed as API can only query by ID (and not name).
// Returns error if domain is not found.
func (c *ExoscaleSolver) findDomain(
ctx context.Context,
client *exoscale.Client,
apiZone string,
domainName string,
) (*exoscale.DNSDomain, error) {
domains, err := client.ListDNSDomains(ctx, apiZone)
if err != nil {
return nil, fmt.Errorf("error retrieving domain list: %w", err)
}
for _, domain := range domains {
if *domain.UnicodeName == domainName {
return &domain, nil
}
}
return nil, fmt.Errorf("domain %q not found", domainName)
}
// apiClient is a helper that initializes Egoscale (Exoscale API) client.
// Resolves any configuration overrides from environment.
func (c *ExoscaleSolver) apiClient(ch *v1alpha1.ChallengeRequest, config Config) (*exoscale.Client, error) {
var apiKey, apiSecret string
switch {
case os.Getenv(envAPIKey) != "" && os.Getenv(envAPISecret) != "":
// env always take precedence over config.
c.logger.Info("found client credentials in environment, ignoring config")
apiKey = os.Getenv(envAPIKey)
apiSecret = os.Getenv(envAPISecret)
case config.APIKeyRef != nil && config.APISecretRef != nil:
apiKeyResource, err := c.kClient.CoreV1().Secrets(ch.ResourceNamespace).Get(
context.Background(),
config.APIKeyRef.Name,
metav1.GetOptions{},
)
if err != nil {
return nil, fmt.Errorf("could not get secret %s: %w", config.APIKeyRef.Name, err)
}
apiSecretResource, err := c.kClient.CoreV1().Secrets(ch.ResourceNamespace).Get(
context.Background(),
config.APISecretRef.Name,
metav1.GetOptions{},
)
if err != nil {
return nil, fmt.Errorf("could not get secret %s: %w", config.APISecretRef.Name, err)
}
apiKeyData, ok := apiKeyResource.Data[config.APIKeyRef.Key]
if !ok {
return nil, fmt.Errorf("could not get key %s in secret %s", config.APIKeyRef.Key, config.APIKeyRef.Name)
}
apiSecretData, ok := apiSecretResource.Data[config.APISecretRef.Key]
if !ok {
return nil, fmt.Errorf("could not get key %s in secret %s", config.APISecretRef.Key, config.APISecretRef.Name)
}
apiKey = string(apiKeyData)
apiSecret = string(apiSecretData)
default:
return nil, errors.New("client credentials not found")
}
return exoscale.NewClient(
apiKey,
apiSecret,
// API trace mode can be set only through environment.
exoscale.ClientOptCond(func() bool {
if v := os.Getenv(envTrace); v != "" {
return true
}
return false
}, exoscale.ClientOptWithTrace()),
)
}