summaryrefslogtreecommitdiffstats
path: root/main.go
diff options
context:
space:
mode:
authorJesper Jensen <jesper@jnsn.dev>2026-11-01 20:33:36 +0100
committerJesper Jensen <jesper@jnsn.dev>2026-11-01 21:34:19 +0100
commita265ee04af9b21379c4f33cf8838e579f71d99d6 (patch)
tree8511a085e413d813f660b0a4efa122959b27b93e /main.go
parentf4475b5f9e2e5e0cbf86e756c0e6a1bebcf1efdd (diff)
downloadcert-manager-webhook-hostinger-a265ee04af9b21379c4f33cf8838e579f71d99d6.tar.gz
cert-manager-webhook-hostinger-a265ee04af9b21379c4f33cf8838e579f71d99d6.zip
Implement Hostinger DNS webhook
Diffstat (limited to 'main.go')
-rw-r--r--main.go182
1 files changed, 140 insertions, 42 deletions
diff --git a/main.go b/main.go
index 3b6f4c8..b602e99 100644
--- a/main.go
+++ b/main.go
@@ -1,11 +1,20 @@
package main
import (
+ "bytes"
+ "context"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
"os"
+ "strings"
+ "sync"
+ "time"
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"
"github.com/cert-manager/cert-manager/pkg/acme/webhook"
@@ -36,13 +45,10 @@ func main() {
// It must implement the [webhook.Solver] interface:
// https://pkg.go.dev/github.com/cert-manager/cert-manager/pkg/acme/webhook#Solver
type customDNSProviderSolver struct {
- // If a Kubernetes 'clientset' is needed, you must:
- // 1. uncomment the additional `client` field in this structure below
- // 2. uncomment the "k8s.io/client-go/kubernetes" import at the top of the file
- // 3. uncomment the relevant code in the Initialize method below
- // 4. ensure your webhook's service account has the required RBAC role
- // assigned to it for interacting with the Kubernetes APIs you need.
- //client kubernetes.Clientset
+ client kubernetes.Interface
+ httpClient *http.Client
+ // Serialize read/modify/write cleanup with other challenges in this process.
+ mu sync.Mutex
}
var _ webhook.Solver = (*customDNSProviderSolver)(nil)
@@ -62,13 +68,10 @@ var _ webhook.Solver = (*customDNSProviderSolver)(nil)
// be used by your provider here, you should reference a Kubernetes Secret
// resource and fetch these credentials using a Kubernetes clientset.
type customDNSProviderConfig struct {
- // Change the two fields below according to the format of the configuration
- // to be decoded.
- // These fields will be set by users in the
- // `issuer.spec.acme.dns01.providers.webhook.config` field.
-
- //Email string `json:"email"`
- //APIKeySecretRef v1alpha1.SecretKeySelector `json:"apiKeySecretRef"`
+ APIKeySecretRef struct {
+ Name string `json:"name"`
+ Key string `json:"key"`
+ } `json:"apiKeySecretRef"`
}
// Name is used as the name for this DNS solver when referencing it on the ACME
@@ -78,7 +81,7 @@ type customDNSProviderConfig struct {
// within a single webhook deployment**.
// For example, `cloudflare` may be used as the name of a solver.
func (c *customDNSProviderSolver) Name() string {
- return "my-custom-solver"
+ return "hostinger"
}
// Present is responsible for actually presenting the DNS record with the
@@ -87,16 +90,7 @@ func (c *customDNSProviderSolver) Name() string {
// cert-manager itself will later perform a self check to ensure that the
// solver has correctly configured the DNS provider.
func (c *customDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
- cfg, err := loadConfig(ch.Config)
- if err != nil {
- return err
- }
-
- // TODO: do something more useful with the decoded configuration
- fmt.Printf("Decoded configuration %v", cfg)
-
- // TODO: add code that sets a record in the DNS provider's console
- return nil
+ return c.updateRecord(ch, false)
}
// CleanUp should delete the relevant TXT record from the DNS provider console.
@@ -106,7 +100,115 @@ func (c *customDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
// This is in order to facilitate multiple DNS validations for the same domain
// concurrently.
func (c *customDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
- // TODO: add code that deletes a record from the DNS provider's console
+ return c.updateRecord(ch, true)
+}
+
+type dnsRecord struct {
+ Content string `json:"content"`
+}
+
+type dnsRecordSet struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ TTL int `json:"ttl"`
+ Records []dnsRecord `json:"records"`
+}
+
+type dnsUpdate struct {
+ Overwrite bool `json:"overwrite"`
+ Zone []dnsRecordSet `json:"zone"`
+}
+
+func (c *customDNSProviderSolver) updateRecord(ch *v1alpha1.ChallengeRequest, cleanup bool) error {
+ cfg, err := loadConfig(ch.Config)
+ if err != nil {
+ return err
+ }
+ zone := strings.ToLower(strings.TrimSuffix(ch.ResolvedZone, "."))
+ fqdn := strings.ToLower(strings.TrimSuffix(ch.ResolvedFQDN, "."))
+ if zone == "" || (fqdn != zone && !strings.HasSuffix(fqdn, "."+zone)) {
+ return fmt.Errorf("resolved FQDN %q is not in zone %q", ch.ResolvedFQDN, ch.ResolvedZone)
+ }
+ name := strings.TrimSuffix(fqdn, "."+zone)
+ if fqdn == zone {
+ name = "@"
+ }
+ secret, err := c.client.CoreV1().Secrets(ch.ResourceNamespace).Get(context.Background(), cfg.APIKeySecretRef.Name, metav1.GetOptions{})
+ if err != nil {
+ return fmt.Errorf("get Hostinger API token secret: %w", err)
+ }
+ token := strings.TrimSpace(string(secret.Data[cfg.APIKeySecretRef.Key]))
+ if token == "" {
+ return fmt.Errorf("secret %s/%s has no token in key %q", ch.ResourceNamespace, cfg.APIKeySecretRef.Name, cfg.APIKeySecretRef.Key)
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if !cleanup {
+ // Append without replacing other challenges at the same name.
+ return c.request(http.MethodPut, zone, token, dnsUpdate{Zone: []dnsRecordSet{{
+ Name: name, Type: "TXT", TTL: 60, Records: []dnsRecord{{Content: ch.Key}},
+ }}}, nil)
+ }
+
+ var sets []dnsRecordSet
+ if err := c.request(http.MethodGet, zone, token, nil, &sets); err != nil {
+ return err
+ }
+ for _, set := range sets {
+ if set.Name != name || set.Type != "TXT" {
+ continue
+ }
+ remaining := make([]dnsRecord, 0, len(set.Records))
+ for _, record := range set.Records {
+ // Hostinger may return TXT content wrapped in DNS quotes.
+ if record.Content != ch.Key && record.Content != `"`+ch.Key+`"` {
+ remaining = append(remaining, record)
+ }
+ }
+ if len(remaining) == len(set.Records) {
+ return nil
+ }
+ if len(remaining) == 0 {
+ return c.request(http.MethodDelete, zone, token, map[string]interface{}{
+ "filters": []map[string]string{{"name": name, "type": "TXT"}},
+ }, nil)
+ }
+ set.Records = remaining
+ return c.request(http.MethodPut, zone, token, dnsUpdate{Overwrite: true, Zone: []dnsRecordSet{set}}, nil)
+ }
+ return nil
+}
+
+func (c *customDNSProviderSolver) request(method, zone, token string, body, result interface{}) error {
+ var data bytes.Buffer
+ if body != nil {
+ if err := json.NewEncoder(&data).Encode(body); err != nil {
+ return err
+ }
+ }
+ req, err := http.NewRequest(method, "https://developers.hostinger.com/api/dns/v1/zones/"+zone, &data)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("Hostinger DNS %s: %w", method, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ return fmt.Errorf("Hostinger DNS %s: %s: %s", method, resp.Status, body)
+ }
+ if result != nil {
+ if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
+ return fmt.Errorf("decode Hostinger DNS response: %w", err)
+ }
+ }
return nil
}
@@ -120,17 +222,12 @@ func (c *customDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
// 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 *customDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {
- ///// UNCOMMENT THE BELOW CODE TO MAKE A KUBERNETES CLIENTSET AVAILABLE TO
- ///// YOUR CUSTOM DNS PROVIDER
-
- //cl, err := kubernetes.NewForConfig(kubeClientConfig)
- //if err != nil {
- // return err
- //}
- //
- //c.client = cl
-
- ///// END OF CODE TO MAKE KUBERNETES CLIENTSET AVAILABLE
+ cl, err := kubernetes.NewForConfig(kubeClientConfig)
+ if err != nil {
+ return err
+ }
+ c.client = cl
+ c.httpClient = &http.Client{Timeout: 30 * time.Second}
return nil
}
@@ -138,12 +235,13 @@ func (c *customDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stop
// the typed config struct.
func loadConfig(cfgJSON *extapi.JSON) (customDNSProviderConfig, error) {
cfg := customDNSProviderConfig{}
- // handle the 'base case' where no configuration has been provided
- if cfgJSON == nil {
- return cfg, nil
+ if cfgJSON != nil {
+ if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil {
+ return cfg, fmt.Errorf("error decoding solver config: %w", err)
+ }
}
- if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil {
- return cfg, fmt.Errorf("error decoding solver config: %v", err)
+ if cfg.APIKeySecretRef.Name == "" || cfg.APIKeySecretRef.Key == "" {
+ return cfg, fmt.Errorf("apiKeySecretRef.name and apiKeySecretRef.key are required")
}
return cfg, nil