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" "github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1" "github.com/cert-manager/cert-manager/pkg/acme/webhook/cmd" ) var GroupName = os.Getenv("GROUP_NAME") func main() { if GroupName == "" { panic("GROUP_NAME must be specified") } // This will register our custom DNS provider with the webhook serving // library, making it available as an API under the provided GroupName. // You can register multiple DNS provider implementations with a single // webhook, where the Name() method will be used to disambiguate between // the different implementations. cmd.RunWebhookServer(GroupName, &customDNSProviderSolver{}, ) } // customDNSProviderSolver implements the provider-specific logic needed to // 'present' an ACME challenge TXT record for your own DNS provider. // // It must implement the [webhook.Solver] interface: // https://pkg.go.dev/github.com/cert-manager/cert-manager/pkg/acme/webhook#Solver type customDNSProviderSolver struct { 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) // customDNSProviderConfig is a structure that is used to decode into when // solving a DNS01 challenge. // This information is provided by cert-manager, and may be a reference to // additional configuration that's needed to solve the challenge for this // particular certificate or issuer. // This typically includes references to Secret resources containing DNS // provider credentials, in cases where a 'multi-tenant' DNS solver is being // created. // If you do *not* require per-issuer or per-certificate configuration to be // provided to your webhook, you can skip decoding altogether in favour of // using CLI flags or similar to provide configuration. // You should not include sensitive information here. If credentials need to // be used by your provider here, you should reference a Kubernetes Secret // resource and fetch these credentials using a Kubernetes clientset. type customDNSProviderConfig struct { 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 // Issuer resource. // This should be unique **within the group name**, i.e. you can have two // solvers configured with the same Name() **so long as they do not co-exist // within a single webhook deployment**. // For example, `cloudflare` may be used as the name of a solver. func (c *customDNSProviderSolver) Name() string { return "hostinger" } // Present is responsible for actually presenting the DNS record with the // DNS provider. // This method should tolerate being called multiple times with the same value. // 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 { return c.updateRecord(ch, false) } // CleanUp should delete the relevant TXT record from the DNS provider console. // If multiple TXT records exist with the same record name (e.g. // _acme-challenge.example.com) then **only** the record with the same `key` // value provided on the ChallengeRequest should be cleaned up. // This is in order to facilitate multiple DNS validations for the same domain // concurrently. func (c *customDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error { 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 } // 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 *customDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error { cl, err := kubernetes.NewForConfig(kubeClientConfig) if err != nil { return err } c.client = cl c.httpClient = &http.Client{Timeout: 30 * time.Second} return nil } // loadConfig is a small helper function that decodes JSON configuration into // the typed config struct. func loadConfig(cfgJSON *extapi.JSON) (customDNSProviderConfig, error) { cfg := customDNSProviderConfig{} if cfgJSON != nil { if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil { return cfg, fmt.Errorf("error decoding solver config: %w", err) } } if cfg.APIKeySecretRef.Name == "" || cfg.APIKeySecretRef.Key == "" { return cfg, fmt.Errorf("apiKeySecretRef.name and apiKeySecretRef.key are required") } return cfg, nil }