-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
300 lines (247 loc) · 7.43 KB
/
main.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"k8s.io/klog/v2"
"github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/jetstack/cert-manager/pkg/acme/webhook/cmd"
certmanagerv1 "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/util"
"github.com/ndemeshchenko/dnsmadeasy"
extAPI "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
providerName = "dnsmadeasy"
defaultTTL = 600
groupNameEnvVar = "GROUP_NAME"
)
func main() {
groupName := os.Getenv("GROUP_NAME")
if groupName == "" {
panic(fmt.Sprintf("%s must be specified", groupNameEnvVar))
}
cmd.RunWebhookServer(groupName,
&dnsmadeasyDNSProviderSolver{},
)
}
type dnsmadeasyDNSProviderSolver struct {
client *kubernetes.Clientset
}
type dnsmadeasyDNSProviderConfig struct {
APIKeyRef certmanagerv1.SecretKeySelector `json:"apiKeyRef"`
APISecretRef certmanagerv1.SecretKeySelector `json:"apiSecretRef"`
TTL *int `json:"ttl"`
Sandbox bool `json:"sandbox"`
}
func (c *dnsmadeasyDNSProviderSolver) validate(cfg *dnsmadeasyDNSProviderConfig) error {
if cfg.APIKeyRef.Name == "" {
return errors.New("API Key field is not provided")
}
if cfg.APISecretRef.Name == "" {
return errors.New("API Secret field is not provided")
}
return nil
}
// Name function returns DNS provider name.
func (c *dnsmadeasyDNSProviderSolver) Name() string {
return providerName
}
func (c *dnsmadeasyDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
klog.Infof("\nIn Present: fqdn:[%s] zone:[%s]\n", ch.ResolvedFQDN, ch.ResolvedZone)
cfg, err := loadConfig(ch.Config)
if err != nil {
printError(err)
return err
}
provider, err := c.provider(&cfg, ch.ResourceNamespace)
if err != nil {
printError(err)
return err
}
domainID, err := getDomainID(provider, ch.ResolvedZone)
if err != nil {
printError(err)
return err
}
existingRecord, err := findTXTRecord(provider, domainID, ch.ResolvedZone, ch.ResolvedFQDN, ch.Key)
if err != nil {
printError(err)
return err
}
if existingRecord == nil {
name := fetchRecordName(ch.ResolvedFQDN, ch.ResolvedZone)
r := &dnsmadeasy.Record{
Name: name,
Type: "TXT",
Value: ch.Key,
GtdLocation: "DEFAULT",
TTL: *cfg.TTL,
}
_, err := provider.CreateRecord(domainID, r)
if err != nil {
printError(err)
return fmt.Errorf("DnsMadeEasy API call failed: %v", err)
}
} else {
existingRecord.TTL = *cfg.TTL
err = provider.UpdateRecord(domainID, existingRecord)
if err != nil {
printError(err)
return fmt.Errorf("DNSMadeEasy API call failed: %v", err)
}
}
klog.Infof("\nOut Present: fqdn:[%s] zone:[%s]\n", ch.ResolvedFQDN, ch.ResolvedZone)
return nil
}
func (c *dnsmadeasyDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
klog.Infof("\nIn CleanUp(): fqdn:[%s] zone:[%s]\n", ch.ResolvedFQDN, ch.ResolvedZone)
cfg, err := loadConfig(ch.Config)
if err != nil {
printError(err)
return err
}
provider, err := c.provider(&cfg, ch.ResourceNamespace)
if err != nil {
printError(err)
return err
}
domainID, err := getDomainID(provider, ch.ResolvedZone)
if err != nil {
printError(err)
return err
}
existingRecord, err := findTXTRecord(provider, domainID, ch.ResolvedZone, ch.ResolvedFQDN, ch.Key)
if err != nil {
printError(err)
return err
}
if existingRecord != nil {
err = provider.DeleteRecord(domainID, existingRecord.ID)
if err != nil {
printError(err)
return fmt.Errorf("DnsMadeEasy API call failed: %v", err)
}
}
return nil
}
// Initialize will be called when the webhook first starts.
// This method can be used to instantiate the webhook, i.e. initialising
// connections or warming up caches.
// Typically, the kubeClientConfig parameter is used to build a Kubernetes
// client that can be used to fetch resources from the Kubernetes API, e.g.
// Secret resources containing credentials used to authenticate with DNS
// provider accounts.
// The stopCh can be used to handle early termination of the webhook, in cases
// where a SIGTERM or similar signal is sent to the webhook process.
func (c *dnsmadeasyDNSProviderSolver) Initialize(kubeClientCfg *rest.Config, stopCh <-chan struct{}) error {
client, err := kubernetes.NewForConfig(kubeClientCfg)
if err != nil {
return err
}
c.client = client
return nil
}
func (c *dnsmadeasyDNSProviderSolver) provider(cfg *dnsmadeasyDNSProviderConfig, namespace string) (*dnsmadeasy.DMEClient, error) {
err := c.validate(cfg)
if err != nil {
return nil, err
}
keysec := make(map[string]string)
for key, ref := range map[string]certmanagerv1.SecretKeySelector{"APIKeyRef": cfg.APIKeyRef, "APISecretRef": cfg.APISecretRef} {
secret, err := c.client.CoreV1().
Secrets(namespace).
Get(context.Background(), ref.Name, metaV1.GetOptions{})
if err != nil {
return nil, err
}
secretBytes, ok := secret.Data[ref.Key]
if !ok {
return nil, fmt.Errorf("no %s for %q in secret '%s/%s'", key, ref.Name, namespace, ref.Key)
}
keysec[key] = string(secretBytes)
}
providerConfig, err := dnsmadeasy.New(&dnsmadeasy.DMEClient{
APIAccessKey: keysec["APIKeyRef"],
APISecretKey: keysec["APISecretRef"],
})
if err != nil {
return nil, err
}
return providerConfig, err
}
func getDomainID(client *dnsmadeasy.DMEClient, zone string) (int, error) {
domains, err := client.Domains()
if err != nil {
return -1, fmt.Errorf("DnsMadeEasy API call failed: %v", err)
}
authZone, err := util.FindZoneByFqdn(zone, util.RecursiveNameservers)
if err != nil {
return -1, err
}
var hostedDomain dnsmadeasy.Domain
for _, domain := range domains {
if domain.Name == util.UnFqdn(authZone) {
hostedDomain = domain
break
}
}
if hostedDomain.ID == 0 {
return -1, fmt.Errorf("zone %s not found in DnsMadeEasy for zone %s", authZone, zone)
}
return hostedDomain.ID, err
}
func findTXTRecord(client *dnsmadeasy.DMEClient, domainID int, zone, fqdn, key string) (*dnsmadeasy.Record, error) {
name := fetchRecordName(fqdn, zone)
records, err := client.Records(domainID)
if err != nil {
return nil, fmt.Errorf("DnsMadeEasy API call failed: %v", err)
}
for _, record := range records {
if record.Name == name && record.Type == "TXT" && trimQuotes(record.Value) == key {
klog.Infof("DNS record found %v\n", record)
return &record, nil
}
}
return nil, nil
}
func fetchRecordName(fqdn, zone string) string {
if idx := strings.Index(fqdn, "."+zone); idx != -1 {
return fqdn[:idx]
}
return util.UnFqdn(fqdn)
}
// DnsMadeEasy wraps TXT value with some unnecessary quotes which break the match
// trimQuotes method removes them
func trimQuotes(s string) string {
if len(s) >= 2 {
if s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
}
return s
}
// loadConfig is a small helper function that decodes JSON configuration into
// the typed config struct.
func loadConfig(cfgJSON *extAPI.JSON) (dnsmadeasyDNSProviderConfig, error) {
ttl := defaultTTL
cfg := dnsmadeasyDNSProviderConfig{TTL: &ttl}
if cfgJSON == nil {
return cfg, nil
}
err := json.Unmarshal(cfgJSON.Raw, &cfg)
if err != nil {
return cfg, fmt.Errorf("can't decode DNS01 solver config: %v", err)
}
return cfg, nil
}
// printError
func printError(err error) {
klog.Errorf("\n\nERROR\n %v \n\n", err)
}