blob: 8daa35358c171b7f29a9453bf7dc0cad081a9f09 [file] [log] [blame]
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +04001package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
Giorgi Lekveishvili5c2c0b92023-12-07 17:35:40 +04009 "os"
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +040010 "strings"
11
12 extapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
13 "k8s.io/client-go/kubernetes"
14 "k8s.io/client-go/rest"
15
16 "github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
17 "github.com/cert-manager/cert-manager/pkg/acme/webhook/cmd"
18)
19
Giorgi Lekveishvili5c2c0b92023-12-07 17:35:40 +040020var (
21 groupName = os.Getenv("API_GROUP_NAME")
22 resolverName = os.Getenv("RESOLVER_NAME")
23)
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +040024
25func main() {
26 if groupName == "" {
Giorgi Lekveishvili5c2c0b92023-12-07 17:35:40 +040027 panic("API_GROUP_NAME must be specified")
28 }
29 if resolverName == "" {
30 panic("RESOLVER_NAME must be specified")
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +040031 }
32 cmd.RunWebhookServer(groupName,
33 &pcloudDNSProviderSolver{},
34 )
35}
36
37type ZoneManager interface {
38 CreateTextRecord(domain, entry, txt string) error
39 DeleteTextRecord(domain, entry, txt string) error
40}
41
42type zoneControllerManager struct {
43 CreateAddr string
44 DeleteAddr string
45}
46
47type createTextRecordReq struct {
48 Domain string `json:"domain,omitempty"`
49 Entry string `json:"entry,omitempty"`
50 Text string `json:"text,omitempty"`
51}
52
53const contentTypeApplicationJSON = "application/json"
54
55func (m *zoneControllerManager) CreateTextRecord(domain, entry, txt string) error {
56 req := createTextRecordReq{domain, entry, txt}
57 var buf bytes.Buffer
58 if err := json.NewEncoder(&buf).Encode(req); err != nil {
59 return err
60 }
61 if resp, err := http.Post(m.CreateAddr, contentTypeApplicationJSON, &buf); err != nil {
62 return err
63 } else if resp.StatusCode != http.StatusOK {
64 var b strings.Builder
65 io.Copy(&b, resp.Body)
66 return fmt.Errorf("Create text record failed: %d %s", resp.StatusCode, b.String())
67 }
68 return nil
69}
70
71func (m *zoneControllerManager) DeleteTextRecord(domain, entry, txt string) error {
72 req := createTextRecordReq{domain, entry, txt}
73 var buf bytes.Buffer
74 if err := json.NewEncoder(&buf).Encode(req); err != nil {
75 return err
76 }
77 if resp, err := http.Post(m.DeleteAddr, contentTypeApplicationJSON, &buf); err != nil {
78 return err
79 } else if resp.StatusCode != http.StatusOK {
80 var b strings.Builder
81 io.Copy(&b, resp.Body)
82 return fmt.Errorf("Delete text record failed: %d %s", resp.StatusCode, b.String())
83 }
84 return nil
85}
86
87type pcloudDNSProviderSolver struct {
88 // If a Kubernetes 'clientset' is needed, you must:
89 // 1. uncomment the additional `client` field in this structure below
90 // 2. uncomment the "k8s.io/client-go/kubernetes" import at the top of the file
91 // 3. uncomment the relevant code in the Initialize method below
92 // 4. ensure your webhook's service account has the required RBAC role
93 // assigned to it for interacting with the Kubernetes APIs you need.
94 client *kubernetes.Clientset
95}
96
97// customDNSProviderConfig is a structure that is used to decode into when
98// solving a DNS01 challenge.
99// This information is provided by cert-manager, and may be a reference to
100// additional configuration that's needed to solve the challenge for this
101// particular certificate or issuer.
102// This typically includes references to Secret resources containing DNS
103// provider credentials, in cases where a 'multi-tenant' DNS solver is being
104// created.
105// If you do *not* require per-issuer or per-certificate configuration to be
106// provided to your webhook, you can skip decoding altogether in favour of
107// using CLI flags or similar to provide configuration.
108// You should not include sensitive information here. If credentials need to
109// be used by your provider here, you should reference a Kubernetes Secret
110// resource and fetch these credentials using a Kubernetes clientset.
111type pcloudDNSProviderConfig struct {
Giorgi Lekveishvili5c2c0b92023-12-07 17:35:40 +0400112 CreateAddress string `json:"createTXTAddr,omitempty"`
113 DeleteAddress string `json:"deleteTXTAddr,omitempty"`
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400114}
115
116// Name is used as the name for this DNS solver when referencing it on the ACME
117// Issuer resource.
118// This should be unique **within the group name**, i.e. you can have two
119// solvers configured with the same Name() **so long as they do not co-exist
120// within a single webhook deployment**.
121// For example, `cloudflare` may be used as the name of a solver.
122func (c *pcloudDNSProviderSolver) Name() string {
Giorgi Lekveishvili5c2c0b92023-12-07 17:35:40 +0400123 return resolverName
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400124}
125
126// Present is responsible for actually presenting the DNS record with the
127// DNS provider.
128// This method should tolerate being called multiple times with the same value.
129// cert-manager itself will later perform a self check to ensure that the
130// solver has correctly configured the DNS provider.
131func (c *pcloudDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
132 fmt.Printf("Received challenge %+v\n", ch)
133 cfg, err := loadConfig(ch.Config)
134 if err != nil {
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400135 return err
136 }
gioe72b54f2024-04-22 10:44:41 +0400137 fmt.Printf("API config: %+v\n", cfg)
138 zm := &zoneControllerManager{cfg.CreateAddress, cfg.DeleteAddress}
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400139 domain, entry := getDomainAndEntry(ch)
Giorgi Lekveishvili9e2fafa2023-12-18 14:12:34 +0400140 fmt.Printf("%s %s\n", domain, entry)
141 err = zm.CreateTextRecord(domain, entry, ch.Key)
142 if err != nil {
143 fmt.Printf("Failed to create TXT record: %s\n", err.Error())
144 return err
145 }
146 return nil
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400147}
148
149// CleanUp should delete the relevant TXT record from the DNS provider console.
150// If multiple TXT records exist with the same record name (e.g.
151// _acme-challenge.example.com) then **only** the record with the same `key`
152// value provided on the ChallengeRequest should be cleaned up.
153// This is in order to facilitate multiple DNS validations for the same domain
154// concurrently.
155func (c *pcloudDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
156 cfg, err := loadConfig(ch.Config)
157 if err != nil {
158 return err
159 }
gioe72b54f2024-04-22 10:44:41 +0400160 fmt.Printf("API config: %+v\n", cfg)
161 zm := &zoneControllerManager{cfg.CreateAddress, cfg.DeleteAddress}
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400162 domain, entry := getDomainAndEntry(ch)
Giorgi Lekveishvili9e2fafa2023-12-18 14:12:34 +0400163 err = zm.DeleteTextRecord(domain, entry, ch.Key)
164 if err != nil {
165 fmt.Printf("Failed to delete TXT record: %s\n", err.Error())
166 return err
167 }
168 return nil
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400169}
170
171// Initialize will be called when the webhook first starts.
172// This method can be used to instantiate the webhook, i.e. initialising
173// connections or warming up caches.
174// Typically, the kubeClientConfig parameter is used to build a Kubernetes
175// client that can be used to fetch resources from the Kubernetes API, e.g.
176// Secret resources containing credentials used to authenticate with DNS
177// provider accounts.
178// The stopCh can be used to handle early termination of the webhook, in cases
179// where a SIGTERM or similar signal is sent to the webhook process.
180func (c *pcloudDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {
181 fmt.Println("Initialization start")
182 client, err := kubernetes.NewForConfig(kubeClientConfig)
183 if err != nil {
184 return err
185 }
186 c.client = client
187 fmt.Println("Initialization done")
188 return nil
189}
190
191// loadConfig is a small helper function that decodes JSON configuration into
192// the typed config struct.
193func loadConfig(cfgJSON *extapi.JSON) (pcloudDNSProviderConfig, error) {
194 cfg := pcloudDNSProviderConfig{}
195 // handle the 'base case' where no configuration has been provided
196 if cfgJSON == nil {
197 return cfg, nil
198 }
199 if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil {
200 return cfg, fmt.Errorf("error decoding solver config: %v", err)
201 }
202
203 return cfg, nil
204}
205
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400206func getDomainAndEntry(ch *v1alpha1.ChallengeRequest) (string, string) {
207 // Both ch.ResolvedZone and ch.ResolvedFQDN end with a dot: '.'
Giorgi Lekveishvili9e2fafa2023-12-18 14:12:34 +0400208 resolvedFQDN := strings.TrimSuffix(ch.ResolvedFQDN, ".")
209 domain := strings.Join(strings.Split(strings.TrimSuffix(ch.DNSName, "."), ".")[1:], ".")
210 entry := strings.TrimSuffix(resolvedFQDN, domain)
211 return strings.TrimSuffix(domain, "."), strings.TrimSuffix(entry, ".")
Giorgi Lekveishviliae1a4a42023-12-07 13:23:17 +0400212}