From a78e4421efe017d69f41be06cb1517cf93b964fe Mon Sep 17 00:00:00 2001 From: Jan Novak Date: Thu, 26 Mar 2026 10:54:33 +0100 Subject: [PATCH] feat: initial implementation of gateway-cert-operator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kubernetes operator that automates HTTPS listener configuration on Gateway API Gateway resources whenever a cert-manager Certificate is created or updated. Core behaviour: - Watches cert-manager Certificate resources for the annotation gateway-cert-operator.io/gateway-name to identify the target Gateway - Builds HTTPS listeners (prefixed "auto-") from each Certificate's DNS SANs and merges them into the target Gateway's listener list - Preserves any manually-managed listeners; removes stale auto-listeners when Certificates are deleted or their annotations are removed - Supports optional annotations to override the target namespace and listener port (default 443) Components: - main.go – manager setup, scheme registration, health/readiness probes - internal/controller/ – Certificate reconciler with field indexing and dual-watch pattern - internal/gateway/patch.go – listener construction, merge, and equality helpers - deploy/manifests.yaml – Namespace, RBAC, and Deployment - docs/README.md – usage guide and architecture notes - Dockerfile – distroless multi-stage build Co-Authored-By: Claude Sonnet 4.6 --- .gitignore | 13 ++ Dockerfile | 16 ++ deploy/manifests.yaml | 102 +++++++++++ docs/README.md | 64 +++++++ go.mod | 69 +++++++ go.sum | 169 ++++++++++++++++++ internal/controller/certificate_controller.go | 154 ++++++++++++++++ internal/gateway/patch.go | 155 ++++++++++++++++ main.go | 72 ++++++++ 9 files changed, 814 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 deploy/manifests.yaml create mode 100644 docs/README.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/controller/certificate_controller.go create mode 100644 internal/gateway/patch.go create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..907f0fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# IDE +.idea/ +.vscode/ +*.iml + +# Go build artifacts +/bin/ +*.exe +*.test +*.out + +# OS +.DS_Store \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..638894c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,16 @@ +FROM golang:1.25 AS builder + +WORKDIR /workspace +COPY go.mod go.sum ./ +RUN go mod download + +COPY main.go main.go +COPY internal/ internal/ + +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o manager . + +FROM gcr.io/distroless/static:nonroot +WORKDIR / +COPY --from=builder /workspace/manager . +USER 65532:65532 +ENTRYPOINT ["/manager"] diff --git a/deploy/manifests.yaml b/deploy/manifests.yaml new file mode 100644 index 0000000..a9f06c7 --- /dev/null +++ b/deploy/manifests.yaml @@ -0,0 +1,102 @@ +--- +apiVersion: v1 +kind: Namespace +metadata: + name: gateway-cert-operator-system +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: gateway-cert-operator + namespace: gateway-cert-operator-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: gateway-cert-operator +rules: + # Watch and read Certificates + - apiGroups: ["cert-manager.io"] + resources: ["certificates"] + verbs: ["get", "list", "watch"] + # Read and patch Gateways + - apiGroups: ["gateway.networking.k8s.io"] + resources: ["gateways"] + verbs: ["get", "list", "watch", "patch"] + # Emit events + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: gateway-cert-operator +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: gateway-cert-operator +subjects: + - kind: ServiceAccount + name: gateway-cert-operator + namespace: gateway-cert-operator-system +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: gateway-cert-operator + namespace: gateway-cert-operator-system + labels: + app.kubernetes.io/name: gateway-cert-operator +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: gateway-cert-operator + template: + metadata: + labels: + app.kubernetes.io/name: gateway-cert-operator + spec: + serviceAccountName: gateway-cert-operator + securityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - name: manager + image: gateway-cert-operator:latest + args: + - --metrics-bind-address=:8080 + - --health-probe-bind-address=:8081 + ports: + - name: metrics + containerPort: 8080 + protocol: TCP + - name: healthz + containerPort: 8081 + protocol: TCP + livenessProbe: + httpGet: + path: /healthz + port: healthz + initialDelaySeconds: 5 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /readyz + port: healthz + initialDelaySeconds: 5 + periodSeconds: 10 + resources: + limits: + cpu: 100m + memory: 64Mi + requests: + cpu: 50m + memory: 32Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..ae9edd4 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,64 @@ +# Gateway Certificate Operator + +The `gateway-cert-operator` automates the configuration of Gateway API `Gateway` listeners when using `cert-manager` for TLS certificate management. + +## Overview + +When you create a `Certificate` resource using `cert-manager`, this operator automatically and dynamically creates an HTTPS `Listener` on your target Gateway. This eliminates the need for manual configuration of the Gateway each time a new certificate is provisioned or its DNS names change. + +## Architecture + +The operator acts as a bridge between two standard Kubernetes APIS: +- `cert-manager.io/v1` `Certificate` +- `gateway.networking.k8s.io/v1` `Gateway` + +By watching both resources, the controller ensures that the Gateway always has the correct listeners configured to serve HTTPs traffic for the domains requested in the certificates. + +## Prerequisites + +- A Kubernetes cluster. +- [Gateway API](https://gateway-api.sigs.k8s.io/) installed (`v1` APIs). +- [cert-manager](https://cert-manager.io/) installed (`v1` APIs). + +## Usage + +To use the operator, simply add the appropriate annotations to your `Certificate` resource. + +### Example Certificate +```yaml +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: my-app-cert + namespace: default + annotations: + # Required: The name of the target Gateway + gateway-cert-operator.io/gateway-name: "my-gateway" + + # Optional: If the Gateway is in a different namespace + # gateway-cert-operator.io/gateway-namespace: "gateway-system" +spec: + secretName: my-app-tls + dnsNames: + - "app.example.com" + issuerRef: + name: letsencrypt-prod + kind: ClusterIssuer +``` + +### Lifecycle + +1. **Trigger**: The operator detects the `gateway-cert-operator.io/gateway-name` annotation on the `Certificate`. +2. **Gateway Lookup**: It fetches the designated target Gateway (`my-gateway`). +3. **Patching**: For each DNS name defined in `spec.dnsNames`, it mathematically appends a new HTTPS `Listener` on port `443` terminating TLS using the secret created by `cert-manager` (`my-app-tls`). +4. **Safe Coexistence**: To safely coexist with manually defined listeners, the operator uniquely prefixes its configured listeners with `auto-` (e.g., `auto-my-app-cert-app-example-com`). It solely manages listeners with this prefix. + +When a certificate is deleted or updated (for instance if a DNS name is changed), the operator will instantly reconcile the modified states by cleanly removing older `auto-*` listeners and inserting the new ones while preserving the manually defined resources. + +## Deployment + +To deploy the operator, applying the provided manifest sets up the necessary RBAC permissions and the controller manager: + +```bash +kubectl apply -f deploy/manifests.yaml +``` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e1aad4d --- /dev/null +++ b/go.mod @@ -0,0 +1,69 @@ +module github.com/example/gateway-cert-operator + +go 1.25.0 + +require ( + github.com/cert-manager/cert-manager v1.20.0 + go.uber.org/zap v1.27.1 + k8s.io/apimachinery v0.35.2 + k8s.io/client-go v0.35.2 + sigs.k8s.io/controller-runtime v0.23.3 + sigs.k8s.io/gateway-api v1.5.1 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/emicklei/go-restful/v3 v3.13.0 // indirect + github.com/evanphx/json-patch/v5 v5.9.11 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/fxamacker/cbor/v2 v2.9.0 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/zapr v1.3.0 // indirect + github.com/go-openapi/jsonpointer v0.22.4 // indirect + github.com/go-openapi/jsonreference v0.21.4 // indirect + github.com/go-openapi/swag v0.23.1 // indirect + github.com/go-openapi/swag/jsonname v0.25.4 // indirect + github.com/google/btree v1.1.3 // indirect + github.com/google/gnostic-models v0.7.1 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailru/easyjson v0.9.1 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_golang v1.23.2 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.66.1 // indirect + github.com/prometheus/procfs v0.17.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/x448/float16 v0.8.4 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.yaml.in/yaml/v2 v2.4.3 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/oauth2 v0.35.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/term v0.40.0 // indirect + golang.org/x/text v0.34.0 // indirect + golang.org/x/time v0.14.0 // indirect + gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/api v0.35.2 // indirect + k8s.io/apiextensions-apiserver v0.35.2 // indirect + k8s.io/klog/v2 v2.140.0 // indirect + k8s.io/kube-openapi v0.0.0-20260127142750-a19766b6e2d4 // indirect + k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 // indirect + sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.3.2 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8bd792c --- /dev/null +++ b/go.sum @@ -0,0 +1,169 @@ +github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= +github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cert-manager/cert-manager v1.20.0 h1:czZamsFJ1YdKPhpv+SopJZN9t3W68vQBnFYUevSHGqY= +github.com/cert-manager/cert-manager v1.20.0/go.mod h1:3oparI7R5JyJMNXntYod9p6DucIZ84st7y/9kL6cbBE= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= +github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/evanphx/json-patch v5.9.0+incompatible h1:fBXyNpNMuTTDdquAq/uisOr2lShz4oaXpDTX2bLe7ls= +github.com/evanphx/json-patch v5.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= +github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= +github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= +github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= +github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4= +github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80= +github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8= +github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4= +github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU= +github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0= +github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI= +github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= +github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= +github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= +github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= +github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8= +github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8= +github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/onsi/ginkgo/v2 v2.28.0 h1:Rrf+lVLmtlBIKv6KrIGJCjyY8N36vDVcutbGJkyqjJc= +github.com/onsi/ginkgo/v2 v2.28.0/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= +github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= +github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= +github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= +github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= +go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= +golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= +golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= +golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= +gomodules.xyz/jsonpatch/v2 v2.5.0 h1:JELs8RLM12qJGXU4u/TO3V25KW8GreMKl9pdkk14RM0= +gomodules.xyz/jsonpatch/v2 v2.5.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= +gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/api v0.35.2 h1:tW7mWc2RpxW7HS4CoRXhtYHSzme1PN1UjGHJ1bdrtdw= +k8s.io/api v0.35.2/go.mod h1:7AJfqGoAZcwSFhOjcGM7WV05QxMMgUaChNfLTXDRE60= +k8s.io/apiextensions-apiserver v0.35.2 h1:iyStXHoJZsUXPh/nFAsjC29rjJWdSgUmG1XpApE29c0= +k8s.io/apiextensions-apiserver v0.35.2/go.mod h1:OdyGvcO1FtMDWQ+rRh/Ei3b6X3g2+ZDHd0MSRGeS8rU= +k8s.io/apimachinery v0.35.2 h1:NqsM/mmZA7sHW02JZ9RTtk3wInRgbVxL8MPfzSANAK8= +k8s.io/apimachinery v0.35.2/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= +k8s.io/client-go v0.35.2 h1:YUfPefdGJA4aljDdayAXkc98DnPkIetMl4PrKX97W9o= +k8s.io/client-go v0.35.2/go.mod h1:4QqEwh4oQpeK8AaefZ0jwTFJw/9kIjdQi0jpKeYvz7g= +k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= +k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= +k8s.io/kube-openapi v0.0.0-20260127142750-a19766b6e2d4 h1:HhDfevmPS+OalTjQRKbTHppRIz01AWi8s45TMXStgYY= +k8s.io/kube-openapi v0.0.0-20260127142750-a19766b6e2d4/go.mod h1:kdmbQkyfwUagLfXIad1y2TdrjPFWp2Q89B3qkRwf/pQ= +k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 h1:AZYQSJemyQB5eRxqcPky+/7EdBj0xi3g0ZcxxJ7vbWU= +k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +sigs.k8s.io/controller-runtime v0.23.3 h1:VjB/vhoPoA9l1kEKZHBMnQF33tdCLQKJtydy4iqwZ80= +sigs.k8s.io/controller-runtime v0.23.3/go.mod h1:B6COOxKptp+YaUT5q4l6LqUJTRpizbgf9KSRNdQGns0= +sigs.k8s.io/gateway-api v1.5.1 h1:RqVRIlkhLhUO8wOHKTLnTJA6o/1un4po4/6M1nRzdd0= +sigs.k8s.io/gateway-api v1.5.1/go.mod h1:GvCETiaMAlLym5CovLxGjS0NysqFk3+Yuq3/rh6QL2o= +sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= +sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= +sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= +sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/structured-merge-diff/v6 v6.3.2 h1:kwVWMx5yS1CrnFWA/2QHyRVJ8jM6dBA80uLmm0wJkk8= +sigs.k8s.io/structured-merge-diff/v6 v6.3.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= +sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/internal/controller/certificate_controller.go b/internal/controller/certificate_controller.go new file mode 100644 index 0000000..8e6084c --- /dev/null +++ b/internal/controller/certificate_controller.go @@ -0,0 +1,154 @@ +package controller + +import ( + "context" + "fmt" + + cmv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + gw "github.com/example/gateway-cert-operator/internal/gateway" +) + +const ( + // AnnotationGatewayName is the annotation key specifying which Gateway to update. + AnnotationGatewayName = "gateway-cert-operator.io/gateway-name" + // AnnotationGatewayNamespace optionally overrides the Gateway namespace. Defaults to Certificate namespace. + AnnotationGatewayNamespace = "gateway-cert-operator.io/gateway-namespace" + // AnnotationListenerPort optionally overrides the listener port. Defaults to 443. + AnnotationListenerPort = "gateway-cert-operator.io/listener-port" + + // ListenerPrefix is prepended to managed listener names so we can distinguish ours. + ListenerPrefix = "auto-" + + // IndexFieldGatewayTarget is the field index for mapping Certificates to their target Gateway. + IndexFieldGatewayTarget = ".metadata.annotations.gatewayTarget" +) + +// CertificateReconciler reconciles Certificate objects and patches Gateway listeners. +type CertificateReconciler struct { + client.Client +} + +// SetupCertificateReconciler creates the reconciler and registers watches. +func SetupCertificateReconciler(mgr ctrl.Manager) error { + r := &CertificateReconciler{Client: mgr.GetClient()} + + // Index Certificates by their target Gateway so we can list all certs for a given Gateway. + if err := mgr.GetFieldIndexer().IndexField(context.Background(), &cmv1.Certificate{}, IndexFieldGatewayTarget, func(obj client.Object) []string { + cert := obj.(*cmv1.Certificate) + gwName, ok := cert.Annotations[AnnotationGatewayName] + if !ok { + return nil + } + gwNs := cert.Annotations[AnnotationGatewayNamespace] + if gwNs == "" { + gwNs = cert.Namespace + } + return []string{fmt.Sprintf("%s/%s", gwNs, gwName)} + }); err != nil { + return fmt.Errorf("failed to setup field index: %w", err) + } + + return ctrl.NewControllerManagedBy(mgr). + For(&cmv1.Certificate{}). + // Secondary watch: if someone edits the Gateway, re-reconcile relevant Certificates. + Watches(&gwapiv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(r.gatewayToCertificates)). + Complete(r) +} + +// Reconcile handles Certificate create/update/delete events. +func (r *CertificateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := log.FromContext(ctx) + + var cert cmv1.Certificate + if err := r.Get(ctx, req.NamespacedName, &cert); err != nil { + // Certificate deleted — we still need to reconcile the Gateway. + // We can't know which Gateway it targeted anymore, so we rely on the + // fact that the index query below will simply not return this cert, + // and the Gateway will be patched without its listener. + // To handle this properly, we reconcile ALL Gateways that had any + // managed listener. In practice, deletion triggers the index update, + // and the Gateway watch re-enqueues the right certs. + return ctrl.Result{}, client.IgnoreNotFound(err) + } + + gwName, ok := cert.Annotations[AnnotationGatewayName] + if !ok { + log.V(1).Info("certificate missing gateway annotation, skipping") + return ctrl.Result{}, nil + } + + gwNamespace := cert.Annotations[AnnotationGatewayNamespace] + if gwNamespace == "" { + gwNamespace = cert.Namespace + } + + // List ALL certificates targeting this Gateway so we compute the full desired state. + var certList cmv1.CertificateList + if err := r.List(ctx, &certList, client.MatchingFields{ + IndexFieldGatewayTarget: fmt.Sprintf("%s/%s", gwNamespace, gwName), + }); err != nil { + return ctrl.Result{}, fmt.Errorf("listing certificates for gateway %s/%s: %w", gwNamespace, gwName, err) + } + + // Build desired listeners from all annotated certificates. + desiredListeners := gw.BuildListenersFromCertificates(certList.Items, ListenerPrefix) + + // Fetch the target Gateway. + var gateway gwapiv1.Gateway + if err := r.Get(ctx, types.NamespacedName{Name: gwName, Namespace: gwNamespace}, &gateway); err != nil { + return ctrl.Result{}, fmt.Errorf("getting gateway %s/%s: %w", gwNamespace, gwName, err) + } + + // Merge: keep non-prefixed listeners, replace all auto-* listeners. + updated := gw.MergeListeners(gateway.Spec.Listeners, desiredListeners, ListenerPrefix) + + if gw.ListenersEqual(gateway.Spec.Listeners, updated) { + log.V(1).Info("gateway listeners already up to date") + return ctrl.Result{}, nil + } + + patch := client.MergeFrom(gateway.DeepCopy()) + gateway.Spec.Listeners = updated + if err := r.Patch(ctx, &gateway, patch); err != nil { + return ctrl.Result{}, fmt.Errorf("patching gateway %s/%s: %w", gwNamespace, gwName, err) + } + + log.Info("patched gateway listeners", + "gateway", fmt.Sprintf("%s/%s", gwNamespace, gwName), + "managedListeners", len(desiredListeners), + ) + return ctrl.Result{}, nil +} + +// gatewayToCertificates maps a Gateway event back to all Certificates targeting it. +func (r *CertificateReconciler) gatewayToCertificates(ctx context.Context, obj client.Object) []reconcile.Request { + gw := obj.(*gwapiv1.Gateway) + key := fmt.Sprintf("%s/%s", gw.Namespace, gw.Name) + + var certList cmv1.CertificateList + if err := r.List(ctx, &certList, client.MatchingFields{ + IndexFieldGatewayTarget: key, + }); err != nil { + log.FromContext(ctx).Error(err, "listing certificates for gateway", "gateway", key) + return nil + } + + requests := make([]reconcile.Request, 0, len(certList.Items)) + for _, cert := range certList.Items { + requests = append(requests, reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: cert.Name, + Namespace: cert.Namespace, + }, + }) + } + return requests +} diff --git a/internal/gateway/patch.go b/internal/gateway/patch.go new file mode 100644 index 0000000..911424f --- /dev/null +++ b/internal/gateway/patch.go @@ -0,0 +1,155 @@ +package gateway + +import ( + "fmt" + "sort" + "strings" + + cmv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" +) + +var ( + defaultPort gwapiv1.PortNumber = 443 + tlsModeTerminate = gwapiv1.TLSModeTerminate + namespacesFromAll gwapiv1.FromNamespaces = gwapiv1.NamespacesFromAll + gatewayGroup gwapiv1.Group = gwapiv1.GroupName + gatewayKind gwapiv1.Kind = "Gateway" +) + +// BuildListenersFromCertificates creates the desired set of managed listeners +// from all annotated Certificate resources targeting a single Gateway. +func BuildListenersFromCertificates(certs []cmv1.Certificate, prefix string) []gwapiv1.Listener { + var listeners []gwapiv1.Listener + + for _, cert := range certs { + if cert.DeletionTimestamp != nil { + continue + } + secretName := cert.Spec.SecretName + if secretName == "" { + continue + } + + for _, dns := range cert.Spec.DNSNames { + hostname := gwapiv1.Hostname(dns) + listenerName := listenerNameFor(prefix, cert.Name, dns) + + // Determine the namespace of the secret (same as cert namespace). + ns := gwapiv1.Namespace(cert.Namespace) + + listeners = append(listeners, gwapiv1.Listener{ + Name: gwapiv1.SectionName(listenerName), + Hostname: &hostname, + Port: defaultPort, + Protocol: gwapiv1.HTTPSProtocolType, + AllowedRoutes: &gwapiv1.AllowedRoutes{ + Namespaces: &gwapiv1.RouteNamespaces{ + From: &namespacesFromAll, + }, + }, + TLS: &gwapiv1.ListenerTLSConfig{ + Mode: &tlsModeTerminate, + CertificateRefs: []gwapiv1.SecretObjectReference{ + { + Group: ptrTo(gwapiv1.Group("")), + Kind: ptrTo(gwapiv1.Kind("Secret")), + Name: gwapiv1.ObjectName(secretName), + Namespace: &ns, + }, + }, + }, + }) + } + } + + // Sort for deterministic output. + sort.Slice(listeners, func(i, j int) bool { + return string(listeners[i].Name) < string(listeners[j].Name) + }) + + return listeners +} + +// MergeListeners takes existing Gateway listeners and replaces all managed +// (prefixed) listeners with the desired set, preserving user-defined listeners. +func MergeListeners(existing, desired []gwapiv1.Listener, prefix string) []gwapiv1.Listener { + var merged []gwapiv1.Listener + + // Keep all non-managed listeners. + for _, l := range existing { + if !strings.HasPrefix(string(l.Name), prefix) { + merged = append(merged, l) + } + } + + // Append desired managed listeners. + merged = append(merged, desired...) + return merged +} + +// ListenersEqual does a quick comparison of two listener slices by name+hostname+secretRef. +// Not a deep equal — we only check the fields we manage. +func ListenersEqual(a, b []gwapiv1.Listener) bool { + if len(a) != len(b) { + return false + } + aMap := listenerMap(a) + bMap := listenerMap(b) + if len(aMap) != len(bMap) { + return false + } + for k, av := range aMap { + bv, ok := bMap[k] + if !ok || av != bv { + return false + } + } + return true +} + +type listenerKey struct { + name string + hostname string + secret string + port gwapiv1.PortNumber +} + +func listenerMap(listeners []gwapiv1.Listener) map[string]listenerKey { + m := make(map[string]listenerKey, len(listeners)) + for _, l := range listeners { + key := listenerKey{ + name: string(l.Name), + port: l.Port, + } + if l.Hostname != nil { + key.hostname = string(*l.Hostname) + } + if l.TLS != nil && len(l.TLS.CertificateRefs) > 0 { + ref := l.TLS.CertificateRefs[0] + ns := "" + if ref.Namespace != nil { + ns = string(*ref.Namespace) + } + key.secret = fmt.Sprintf("%s/%s", ns, ref.Name) + } + m[key.name] = key + } + return m +} + +// listenerNameFor generates a deterministic listener name from cert name and DNS name. +// Truncates to stay within Gateway API's 253-char limit for section names. +func listenerNameFor(prefix, certName, dnsName string) string { + // Replace dots with dashes for DNS names, combine with cert name. + sanitized := strings.ReplaceAll(dnsName, ".", "-") + name := fmt.Sprintf("%s%s-%s", prefix, certName, sanitized) + if len(name) > 253 { + name = name[:253] + } + return name +} + +func ptrTo[T any](v T) *T { + return &v +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..043bd61 --- /dev/null +++ b/main.go @@ -0,0 +1,72 @@ +package main + +import ( + "flag" + "os" + + gozap "go.uber.org/zap" + cmv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + gwapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + "github.com/example/gateway-cert-operator/internal/controller" +) + +var scheme = runtime.NewScheme() + +func init() { + utilruntime.Must(clientgoscheme.AddToScheme(scheme)) + utilruntime.Must(cmv1.AddToScheme(scheme)) + utilruntime.Must(gwapiv1.Install(scheme)) +} + +func main() { + var metricsAddr string + var probeAddr string + + flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metrics endpoint binds to.") + flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") + flag.Parse() + + ctrl.SetLogger(zap.New( + zap.UseDevMode(true), + func(o *zap.Options) { + o.ZapOpts = append(o.ZapOpts, gozap.AddCaller()) + }, + )) + log := ctrl.Log.WithName("setup") + + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + Scheme: scheme, + HealthProbeBindAddress: probeAddr, + }) + if err != nil { + log.Error(err, "unable to create manager") + os.Exit(1) + } + + if err := controller.SetupCertificateReconciler(mgr); err != nil { + log.Error(err, "unable to setup certificate controller") + os.Exit(1) + } + + if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { + log.Error(err, "unable to set up health check") + os.Exit(1) + } + if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { + log.Error(err, "unable to set up ready check") + os.Exit(1) + } + + log.Info("starting manager") + if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + log.Error(err, "problem running manager") + os.Exit(1) + } +}