From a265ee04af9b21379c4f33cf8838e579f71d99d6 Mon Sep 17 00:00:00 2001 From: Jesper Jensen Date: Sun, 1 Nov 2026 20:33:36 +0100 Subject: Implement Hostinger DNS webhook --- Dockerfile | 2 +- Makefile | 10 +- README.md | 75 +++++++++++- deploy/example-webhook/Chart.yaml | 4 +- deploy/example-webhook/templates/rbac.yaml | 26 +++++ deploy/example-webhook/values.yaml | 5 +- go.mod | 4 +- hostinger_test.go | 168 ++++++++++++++++++++++++++ main.go | 182 ++++++++++++++++++++++------- main_test.go | 73 ++++++++---- 10 files changed, 470 insertions(+), 79 deletions(-) create mode 100644 hostinger_test.go diff --git a/Dockerfile b/Dockerfile index 18b7e6e..b9de91d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.23-alpine3.19@sha256:5f3336882ad15d10ac1b59fbaba7cb84c35d4623774198b36ae60edeba45fd84 AS build_deps +FROM golang:1.27-alpine3.24@sha256:d200d2dd76b03a99b52651fd1325aff7dcd35422c35c01bac56571b0507f3deb AS build_deps RUN apk add --no-cache git diff --git a/Makefile b/Makefile index 27d294d..b8efd83 100644 --- a/Makefile +++ b/Makefile @@ -13,12 +13,20 @@ ENVTEST_K8S_VERSION=1.35.0 HELM_FILES := $(shell find deploy/example-webhook) # FIXME: The environment variables are required by the test helper in cert-manager, but not required to run the tests. -test: setup-envtest +.PHONY: test test-unit check-test-config +test: check-test-config setup-envtest TEST_ASSET_ETCD=$(LOCALBIN)/k8s/$(ENVTEST_K8S_VERSION)-$(OS)-$(ARCH)/etcd \ TEST_ASSET_KUBE_APISERVER=$(LOCALBIN)/k8s/$(ENVTEST_K8S_VERSION)-$(OS)-$(ARCH)/kube-apiserver \ TEST_ASSET_KUBECTL=$(LOCALBIN)/k8s/$(ENVTEST_K8S_VERSION)-$(OS)-$(ARCH)/kubectl \ + $(GO) test -v -count=1 -tags=conformance -timeout=30m . + +test-unit: $(GO) test -v . +check-test-config: + @test -n "$$TEST_ZONE_NAME" || { echo "TEST_ZONE_NAME is required for live conformance tests" >&2; exit 1; } + @test -n "$$HOSTINGER_API_TOKEN" || { echo "HOSTINGER_API_TOKEN is required for live conformance tests" >&2; exit 1; } + .PHONY: clean clean: chmod -R u+w $(LOCALBIN) $(OUT) 2>/dev/null || true diff --git a/README.md b/README.md index 24ec32c..b0e8712 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,50 @@ expected. ## Creating your own webhook +### Using Hostinger DNS + +The webhook implements the [Hostinger DNS zone API](https://docs.hostinger.com/api-reference/endpoints/dns/zone). +Build and publish the image, then install the chart with a group name under a +domain you own: + +```sh +make build IMAGE_NAME=your-registry/webhook IMAGE_TAG=latest +docker push your-registry/webhook:latest +helm upgrade --install hostinger-webhook ./deploy/example-webhook \ + --namespace cert-manager \ + --set image.repository=your-registry/webhook \ + --set image.tag=latest \ + --set groupName=acme.example.com +``` + +Create a Hostinger API token in hPanel and store it in a Secret in cert-manager's +cluster resource namespace (normally `cert-manager` for a ClusterIssuer): + +```sh +kubectl -n cert-manager create secret generic hostinger-api-token \ + --from-literal=api-token=YOUR_HOSTINGER_API_TOKEN +``` + +Use this solver in your Issuer or ClusterIssuer's `spec.acme.solvers`: + +```yaml +- dns01: + webhook: + groupName: acme.example.com # Must match the Helm groupName. + solverName: hostinger + config: + apiKeySecretRef: + name: hostinger-api-token + key: api-token +``` + +The Secret is read from the challenge's resource namespace. For a namespaced +Issuer, put the Secret in the Issuer's namespace and grant the webhook's service +account `get` access there. The chart grants access to `apiKeySecretName` (default +`hostinger-api-token`) in `certManager.namespace`; adjust these values if needed. +Run a single webhook replica so record cleanup and presentation are serialized. +Presentation appends the TXT value; cleanup preserves other values at that name. + Webhook's themselves are deployed as Kubernetes API services, in order to allow administrators to restrict access to webhooks with Kubernetes RBAC. @@ -51,13 +95,32 @@ else they will have undetermined behaviour when used with cert-manager. **It is essential that you configure and run the test suite when creating a DNS01 webhook.** -An example Go test file has been provided in [main_test.go](https://github.com/cert-manager/webhook-example/blob/master/main_test.go). +```sh +export TEST_ZONE_NAME=example.com. +export HOSTINGER_API_TOKEN # Populate this variable from your secret store. +make test +``` + +`make test` runs the unit tests and cert-manager's actual `RunConformance` suite +against `customDNSProviderSolver`, with strict mode enabled. This includes checking that +deleting one TXT value preserves another at the same name. Missing configuration +fails the command; conformance tests are never silently skipped. Test results +are not cached. + +The suite creates and removes real TXT records under a unique +`_acme-challenge.cert-manager-conformance-.` name and checks public +authoritative DNS. It downloads local Kubernetes test binaries and starts a +temporary API server; no existing cluster is needed. The token is written to a +temporary Secret fixture, applied in each test namespace, and removed afterward. -You can run the test suite with: +Run only the mock API and credential tests without live credentials or local +Kubernetes binaries using: -```bash -$ TEST_ZONE_NAME=example.com. make test +```sh +make test-unit ``` -The example file has a number of areas you must fill in and replace with your -own options in order for tests to pass. +The conformance test is selected with the `conformance` build tag. If running Go +directly, use `go test -tags=conformance -count=1 -timeout=30m ./...` and provide +`TEST_ASSET_ETCD`, `TEST_ASSET_KUBE_APISERVER`, and `TEST_ASSET_KUBECTL` paths as +well as the zone and token. Plain `go test ./...` runs only the unit tests. diff --git a/deploy/example-webhook/Chart.yaml b/deploy/example-webhook/Chart.yaml index 77c6ead..fc4e447 100644 --- a/deploy/example-webhook/Chart.yaml +++ b/deploy/example-webhook/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v1 appVersion: "1.0" -description: A Helm chart for Kubernetes -name: example-webhook +description: cert-manager dns01 webhook for hostinger +name: cert-manager-webhook-hostinger version: 0.1.0 diff --git a/deploy/example-webhook/templates/rbac.yaml b/deploy/example-webhook/templates/rbac.yaml index 605fcf5..f952fd1 100644 --- a/deploy/example-webhook/templates/rbac.yaml +++ b/deploy/example-webhook/templates/rbac.yaml @@ -89,3 +89,29 @@ subjects: kind: ServiceAccount name: {{ .Values.certManager.serviceAccountName }} namespace: {{ .Values.certManager.namespace }} +--- +# Allow reading only the configured Hostinger token Secret. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "example-webhook.fullname" . }}:hostinger-token + namespace: {{ .Values.certManager.namespace }} +rules: + - apiGroups: [""] + resources: ["secrets"] + resourceNames: [{{ .Values.apiKeySecretName | quote }}] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "example-webhook.fullname" . }}:hostinger-token + namespace: {{ .Values.certManager.namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "example-webhook.fullname" . }}:hostinger-token +subjects: + - kind: ServiceAccount + name: {{ include "example-webhook.fullname" . }} + namespace: {{ .Release.Namespace }} diff --git a/deploy/example-webhook/values.yaml b/deploy/example-webhook/values.yaml index 9423bd4..4826719 100644 --- a/deploy/example-webhook/values.yaml +++ b/deploy/example-webhook/values.yaml @@ -8,12 +8,15 @@ # The name will need to be referenced in each Issuer's `webhook` stanza to # inform cert-manager of where to send ChallengePayload resources in order to # solve the DNS01 challenge. -groupName: acme.mycompany.com +groupName: cert-manager-webhook-hostinger.jnsn.dev certManager: namespace: cert-manager serviceAccountName: cert-manager +# Token Secret in certManager.namespace; must match config.apiKeySecretRef.name. +apiKeySecretName: hostinger-api-token + image: repository: mycompany/webhook-image tag: latest diff --git a/go.mod b/go.mod index 68c727c..b9dbd3b 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,9 @@ require ( github.com/cert-manager/cert-manager v1.21.3 github.com/miekg/dns v1.1.73 github.com/stretchr/testify v1.12.1 + k8s.io/api v0.37.2 k8s.io/apiextensions-apiserver v0.37.2 + k8s.io/apimachinery v0.37.2 k8s.io/client-go v0.37.2 ) @@ -98,8 +100,6 @@ require ( gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect - k8s.io/api v0.37.2 // indirect - k8s.io/apimachinery v0.37.2 // indirect k8s.io/apiserver v0.37.2 // indirect k8s.io/component-base v0.37.2 // indirect k8s.io/klog/v2 v2.140.0 // indirect diff --git a/hostinger_test.go b/hostinger_test.go new file mode 100644 index 0000000..88cf799 --- /dev/null +++ b/hostinger_test.go @@ -0,0 +1,168 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + acme "github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1" + corev1 "k8s.io/api/core/v1" + extapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/fake" +) + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestHostingerRecords(t *testing.T) { + type request struct { + method, body, response string + status int + } + tests := []struct { + name string + cleanup bool + fqdn string + requests []request + wantErr string + }{ + { + name: "present appends without replacing other challenges", fqdn: "_acme-challenge.sub.example.com.", + requests: []request{{method: "PUT", body: `{"overwrite":false,"zone":[{"name":"_acme-challenge.sub","type":"TXT","ttl":60,"records":[{"content":"challenge-key"}]}]}`}}, + }, + { + name: "present at zone apex", fqdn: "example.com.", + requests: []request{{method: "PUT", body: `{"overwrite":false,"zone":[{"name":"@","type":"TXT","ttl":60,"records":[{"content":"challenge-key"}]}]}`}}, + }, + { + name: "cleanup preserves other TXT values and TTL", cleanup: true, + requests: []request{ + {method: "GET", response: `[{"name":"@","type":"A","ttl":300,"records":[{"content":"192.0.2.1"}]},{"name":"_acme-challenge","type":"TXT","ttl":120,"records":[{"content":"\"challenge-key\""},{"content":"other-challenge"},{"content":"\"keep quotes\""}]}]`}, + {method: "PUT", body: `{"overwrite":true,"zone":[{"name":"_acme-challenge","type":"TXT","ttl":120,"records":[{"content":"other-challenge"},{"content":"\"keep quotes\""}]}]}`}, + }, + }, + { + name: "cleanup deletes only matching name and type when last value removed", cleanup: true, + requests: []request{ + {method: "GET", response: `[{"name":"_acme-challenge","type":"TXT","ttl":60,"records":[{"content":"challenge-key"}]}]`}, + {method: "DELETE", body: `{"filters":[{"name":"_acme-challenge","type":"TXT"}]}`}, + }, + }, + { + name: "cleanup is idempotent when record set is absent", cleanup: true, + requests: []request{{method: "GET", response: `[]`}}, + }, + { + name: "cleanup does nothing when only other values exist", cleanup: true, + requests: []request{{method: "GET", response: `[{"name":"_acme-challenge","type":"TXT","ttl":60,"records":[{"content":"other-challenge"}]}]`}}, + }, + { + name: "API failures are returned", requests: []request{{method: "PUT", status: 401, response: `{"message":"Unauthenticated"}`}}, + wantErr: "401", + }, + { + name: "malformed GET response is returned", cleanup: true, + requests: []request{{method: "GET", response: `{`}}, wantErr: "decode Hostinger DNS response", + }, + { + name: "cleanup write failures are returned", cleanup: true, + requests: []request{ + {method: "GET", response: `[{"name":"_acme-challenge","type":"TXT","records":[{"content":"challenge-key"}]}]`}, + {method: "DELETE", body: `{"filters":[{"name":"_acme-challenge","type":"TXT"}]}`, status: 422}, + }, wantErr: "422", + }, + {name: "reject FQDN outside zone", fqdn: "_acme-challenge.otherexample.com.", wantErr: "not in zone"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + solver, challenge := hostingerTestSolver() + if tt.fqdn != "" { + challenge.ResolvedFQDN = tt.fqdn + } + calls := 0 + solver.httpClient = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + if calls >= len(tt.requests) { + t.Fatalf("unexpected request: %s %s", r.Method, r.URL) + } + want := tt.requests[calls] + calls++ + if r.Method != want.method || r.URL.String() != "https://developers.hostinger.com/api/dns/v1/zones/example.com" { + t.Errorf("unexpected request: %s %s", r.Method, r.URL) + } + if r.Header.Get("Authorization") != "Bearer test-token" || r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Accept") != "application/json" { + t.Error("missing API headers") + } + if want.body != "" { + var gotBody, wantBody interface{} + if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(want.body), &wantBody); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(gotBody, wantBody) { + t.Errorf("body = %v, want %v", gotBody, wantBody) + } + } + w := httptest.NewRecorder() + if want.status != 0 { + w.WriteHeader(want.status) + } + fmt.Fprint(w, want.response) + return w.Result(), nil + })} + var err error + if tt.cleanup { + err = solver.CleanUp(challenge) + } else { + err = solver.Present(challenge) + } + if (tt.wantErr == "" && err != nil) || (tt.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tt.wantErr))) { + t.Fatalf("error = %v, want %q", err, tt.wantErr) + } + if calls != len(tt.requests) { + t.Errorf("made %d requests, want %d", calls, len(tt.requests)) + } + }) + } +} + +func TestHostingerCredentials(t *testing.T) { + for _, config := range []string{"", "{}", "{", `{"apiKeySecretRef":{"name":"hostinger-api-token"}}`, `{"apiKeySecretRef":{"name":"missing","key":"api-token"}}`, `{"apiKeySecretRef":{"name":"hostinger-api-token","key":"missing"}}`} { + t.Run(config, func(t *testing.T) { + for _, cleanup := range []bool{false, true} { + solver, challenge := hostingerTestSolver() + challenge.Config = nil + if config != "" { + challenge.Config = &extapi.JSON{Raw: []byte(config)} + } + var err error + if cleanup { + err = solver.CleanUp(challenge) + } else { + err = solver.Present(challenge) + } + if err == nil { + t.Fatal("expected invalid credentials to fail") + } + } + }) + } +} + +func hostingerTestSolver() (*customDNSProviderSolver, *acme.ChallengeRequest) { + return &customDNSProviderSolver{client: fake.NewClientset(&corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "hostinger-api-token", Namespace: "issuer-namespace"}, + Data: map[string][]byte{"api-token": []byte("test-token\n")}, + })}, &acme.ChallengeRequest{ + ResolvedZone: "example.com.", ResolvedFQDN: "_acme-challenge.example.com.", + ResourceNamespace: "issuer-namespace", Key: "challenge-key", + Config: &extapi.JSON{Raw: []byte(`{"apiKeySecretRef":{"name":"hostinger-api-token","key":"api-token"}}`)}, + } +} 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 diff --git a/main_test.go b/main_test.go index cd28aec..faadb89 100644 --- a/main_test.go +++ b/main_test.go @@ -1,36 +1,61 @@ +//go:build conformance + package main import ( + "crypto/rand" + "encoding/json" + "os" + "path/filepath" + "strings" "testing" + "time" acmetest "github.com/cert-manager/cert-manager/test/acme" - - "github.com/cert-manager/webhook-example/example" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestRunsSuite(t *testing.T) { - // The manifest path should contain a file named config.json that is a - // snippet of valid configuration that should be included on the - // ChallengeRequest passed as part of the test cases. - // + zone := strings.TrimSuffix(strings.TrimSpace(os.Getenv("TEST_ZONE_NAME")), ".") + if zone == "" { + t.Fatal("TEST_ZONE_NAME must specify a Hostinger-managed DNS zone") + } + token := strings.TrimSpace(os.Getenv("HOSTINGER_API_TOKEN")) + if token == "" { + t.Fatal("HOSTINGER_API_TOKEN must be set to run the live conformance suite") + } - // Uncomment the below fixture when implementing your custom DNS provider - //fixture := acmetest.NewFixture(&customDNSProviderSolver{}, - // acmetest.SetResolvedZone(zone), - // acmetest.SetAllowAmbientCredentials(false), - // acmetest.SetManifestPath("testdata/my-custom-solver"), - // acmetest.SetBinariesPath("_test/kubebuilder/bin"), - //) - solver := example.New("59351") - fixture := acmetest.NewFixture(solver, - acmetest.SetResolvedZone("example.com."), - acmetest.SetManifestPath("testdata/my-custom-solver"), - acmetest.SetDNSServer("127.0.0.1:59351"), - acmetest.SetUseAuthoritative(false), - ) - //need to uncomment and RunConformance delete runBasic and runExtended once https://github.com/cert-manager/cert-manager/pull/4835 is merged - //fixture.RunConformance(t) - fixture.RunBasic(t) - fixture.RunExtended(t) + // The fixture applies this Secret in each test's temporary Kubernetes + // namespace, exercising the solver's normal credential lookup. + manifests := t.TempDir() + secret := &corev1.Secret{ + TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Secret"}, + ObjectMeta: metav1.ObjectMeta{Name: "hostinger-api-token"}, + Data: map[string][]byte{"api-token": []byte(token)}, + } + data, err := json.Marshal(secret) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(manifests, "secret.json"), data, 0600); err != nil { + t.Fatal(err) + } + cfg := customDNSProviderConfig{} + cfg.APIKeySecretRef.Name = secret.Name + cfg.APIKeySecretRef.Key = "api-token" + // Use a fresh DNS name to avoid cached records and overlapping test runs. + domain := "cert-manager-conformance-" + strings.ToLower(rand.Text()) + "." + zone + fixture := acmetest.NewFixture(&customDNSProviderSolver{}, + acmetest.SetResolvedZone(zone+"."), + acmetest.SetResolvedFQDN("_acme-challenge."+domain+"."), + acmetest.SetDNSName(domain), + acmetest.SetAllowAmbientCredentials(false), + acmetest.SetConfig(cfg), + acmetest.SetManifestPath(manifests), + acmetest.SetStrict(true), + acmetest.SetPropagationLimit(5*time.Minute), + ) + fixture.RunConformance(t) } -- cgit v1.2.3