Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,10 @@ Do not pass raw logger instances across helper boundaries when `ctx` is availabl
| `--cert-rotation-secret-name` | Secret name for the rotated certificate | `""` |
| `--cert-rotation-mutating-webhook` | Mutating webhook names to patch with CA bundle | `[]` |
| `--cert-rotation-validating-webhook` | Validating webhook names to patch with CA bundle | `[]` |
| `--webhook-ca-validity` | Lifetime of a generated webhook CA; not a provided CA | `87600h0m0s` |
| `--webhook-cert-validity` | Lifetime of the webhook serving certificate | `8760h0m0s` |
| `--webhook-cert-renew-before` | Renew the CA and serving certificate this long before expiry | `2160h0m0s` |
| `--webhook-cert-check-interval` | How often the cert rotator checks the certificates | `12h0m0s` |
| `--tdg-migration` | Enable legacy namespace ownership migration mode | `false` |
| `--capi-operator-update-bypass` | Allow capi-operator-manager to skip BindDefinition authorization for Namespace UPDATE requests; protected-label validation still runs | `false` |
| `--strict-sa-namespace-ownership` | On Namespace CREATE, ServiceAccounts with BindDefinition namespace grants do not inherit hosting-namespace ownership; `false` restores the previous inheritance. Transitional, may be removed in a future release | `true` |
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Add the webhook flags `--webhook-ca-validity`, `--webhook-cert-validity`,
`--webhook-cert-renew-before` and `--webhook-cert-check-interval`, and the
matching Helm values under `webhookServer.certificates`, to set the
lifetimes of the certificates the webhook cert rotator generates. Unset,
they keep cert-controller's defaults (CA 10 years, serving certificate
1 year, renewal 90 days before expiry, check every 12 hours). The webhook
server refuses to start unless check interval < renew before < certificate
validity <= CA validity. The CA validity does not apply to a CA provided in
`webhookServer.certificateAuthority` (#661).
- Add the optional Helm values `webhookServer.certificateAuthority.certificate`
and `webhookServer.certificateAuthority.privateKey`. The webhook cert rotator
keeps the provided CA instead of generating one, so the CA can be part of the
Expand Down
16 changes: 15 additions & 1 deletion chart/auth-operator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ Image reference precedence: `digest` > `tag` > `Chart.AppVersion`
| `webhookServer.certificateAuthority.certificate` | PEM CA certificate the cert rotator uses instead of a self-generated CA; set together with `privateKey` | `""` |
| `webhookServer.certificateAuthority.privateKey` | PEM PKCS#1 RSA private key (`BEGIN RSA PRIVATE KEY`) of `certificateAuthority.certificate`; other key formats are rejected | `""` |
| `webhookServer.certificateAuthority.additionalTrustedCertificates` | PEM CA certificates the webhook configurations trust in addition to `certificate`, for example the old CA during a staged CA rotation; requires `certificate` | `""` |
| `webhookServer.certificates.caValidity` | Lifetime of a CA the cert rotator generates, as a Go duration; empty keeps the default of `87600h` (10 years). Does not change the validity of a CA provided in `certificateAuthority` | `""` |
| `webhookServer.certificates.certValidity` | Lifetime of the serving certificate, as a Go duration; empty keeps the default of `8760h` (1 year) | `""` |
| `webhookServer.certificates.renewBefore` | Renew the CA and the serving certificate this long before they expire; empty keeps the default of `2160h` (90 days) | `""` |
| `webhookServer.certificates.checkInterval` | How often the cert rotator checks the certificates; empty keeps the default of `12h` | `""` |
| `webhookServer.resources.limits.cpu` | CPU limit | `150m` |
| `webhookServer.resources.limits.memory` | Memory limit | `256Mi` |
| `webhookServer.resources.requests.cpu` | CPU request | `50m` |
Expand All @@ -137,12 +141,22 @@ development installs that intentionally need unauthenticated callers can set
`webhookServer.allowUnauthenticatedAuthorize=true` while migrating clients to a
shared bearer token. Keep this opt-out disabled in production.

`webhookServer.certificates` sets the lifetimes of the certificates the cert
rotator generates. The webhook server refuses to start unless
`checkInterval < renewBefore < certValidity <= caValidity` after defaults, so
shortening `certValidity` below 90 days also needs a shorter `renewBefore`.
See the
[operator guide](../../docs/operator-guide.md#webhook-certificate-rotation).

By default, the webhook cert rotator generates its own CA after installation.
Set `webhookServer.certificateAuthority` when the CA must be known in advance,
for example to put it into the API server authorization webhook kubeconfig
before the cluster is bootstrapped. The rotator keeps the provided CA and only
issues the serving certificate. It replaces a CA that is not a self-signed CA
with the DNS name `cert`, or that expires within 90 days. The private key must
with the DNS name `cert`, or that expires within
`webhookServer.certificates.renewBefore` (default 90 days). The provided
certificate fixes the CA's validity; `webhookServer.certificates.caValidity`
only applies to a CA the rotator generates. The private key must
be a PKCS#1 RSA key (`BEGIN RSA PRIVATE KEY`); the chart rejects other key
formats, because the rotator cannot sign the serving certificate with them.
To rotate a provided CA without failing admission requests, first add the new
Expand Down
15 changes: 15 additions & 0 deletions chart/auth-operator/templates/webhook-server-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,21 @@ spec:
- --cert-rotation-validating-webhook={{ include "auth-operator.fullname" . }}-namespace-validating-webhook-configuration
{{- end }}
- --cert-rotation-validating-webhook={{ include "auth-operator.fullname" . }}-binder-validating-webhook-configuration
{{- /* Render only when set: empty keeps the rotator defaults, and --reuse-values upgrades lack these keys. */}}
{{- with .Values.webhookServer.certificates }}
{{- with .caValidity }}
- --webhook-ca-validity={{ . }}
{{- end }}
{{- with .certValidity }}
- --webhook-cert-validity={{ . }}
{{- end }}
{{- with .renewBefore }}
- --webhook-cert-renew-before={{ . }}
{{- end }}
{{- with .checkInterval }}
- --webhook-cert-check-interval={{ . }}
{{- end }}
{{- end }}
{{- with .Values.podDeletionGuard }}
{{- if .enabled }}
- --cert-rotation-validating-webhook={{ include "auth-operator.fullname" $ }}-pod-deletion-guard
Expand Down
13 changes: 12 additions & 1 deletion chart/auth-operator/values.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -461,9 +461,20 @@
}
}
},
"certificates": {
"type": "object",
"description": "Lifetimes of the certificates the cert rotator generates, as Go durations. Empty keeps the default. The webhook server refuses to start unless checkInterval < renewBefore < certValidity <= caValidity.",
"additionalProperties": false,
"properties": {
"caValidity": { "type": "string", "pattern": "^$|^\\+?(([0-9]+(\\.[0-9]*)?|\\.[0-9]+)(ns|us|µs|μs|ms|s|m|h))+$", "default": "", "description": "Lifetime of a CA the rotator generates (default 87600h). Does not apply to a CA provided in certificateAuthority." },
"certValidity": { "type": "string", "pattern": "^$|^\\+?(([0-9]+(\\.[0-9]*)?|\\.[0-9]+)(ns|us|µs|μs|ms|s|m|h))+$", "default": "", "description": "Lifetime of the serving certificate (default 8760h)." },
"renewBefore": { "type": "string", "pattern": "^$|^\\+?(([0-9]+(\\.[0-9]*)?|\\.[0-9]+)(ns|us|µs|μs|ms|s|m|h))+$", "default": "", "description": "Renew the CA and the serving certificate this long before they expire (default 2160h)." },
"checkInterval": { "type": "string", "pattern": "^$|^\\+?(([0-9]+(\\.[0-9]*)?|\\.[0-9]+)(ns|us|µs|μs|ms|s|m|h))+$", "default": "", "description": "How often the rotator checks the certificates (default 12h)." }
}
},
"certificateAuthority": {
"type": "object",
"description": "PEM CA used by the cert rotator instead of a self-generated one. Must be a self-signed CA with DNS name \"cert\", valid for more than 90 days; otherwise the rotator replaces it. The private key must be a PKCS#1 RSA key, otherwise the rotator cannot issue the serving certificate.",
"description": "PEM CA used by the cert rotator instead of a self-generated one. Must be a self-signed CA with DNS name \"cert\", valid for longer than certificates.renewBefore (default 90 days); otherwise the rotator replaces it. Its validity is its own; certificates.caValidity does not change it. The private key must be a PKCS#1 RSA key, otherwise the rotator cannot issue the serving certificate.",
"additionalProperties": false,
"properties": {
"certificate": {
Expand Down
21 changes: 20 additions & 1 deletion chart/auth-operator/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,32 @@ webhookServer:
protocol: TCP
certificateAuthority:
# PEM CA used by the cert rotator instead of a self-generated one.
# Must be a self-signed CA with DNS name "cert", valid > 90 days, with a PKCS#1 RSA
# Must be a self-signed CA with DNS name "cert", valid for longer than
# certificates.renewBefore (default 90 days), with a PKCS#1 RSA
# key ("-----BEGIN RSA PRIVATE KEY-----"); other key formats are rejected.
# Its own validity is fixed by the certificate; certificates.caValidity
# does not change it.
certificate: ""
privateKey: ""
# Optional PEM CA certificates the admission webhooks trust in addition to
# `certificate`, e.g. the previous CA during a staged CA rotation.
additionalTrustedCertificates: ""
# Lifetimes of the certificates the cert rotator generates, as Go durations
# (e.g. 8760h, 90m). Empty keeps the default shown in each comment. The
# webhook server refuses to start unless
# checkInterval < renewBefore < certValidity <= caValidity, so shortening
# certValidity below 90 days also needs a shorter renewBefore.
certificates:
# Lifetime of a CA the rotator generates (default 87600h, 10 years).
# Does not apply to a CA provided in certificateAuthority.
caValidity: ""
# Lifetime of the serving certificate (default 8760h, 1 year).
certValidity: ""
# Renew the CA and the serving certificate this long before they expire
# (default 2160h, 90 days).
renewBefore: ""
# How often the rotator checks the certificates (default 12h).
checkInterval: ""

namespaceAdmission:
# Install cluster-wide Namespace mutating/validating webhooks.
Expand Down
53 changes: 53 additions & 0 deletions chart/auth-operator/webhook_certificate_lifetimes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// SPDX-FileCopyrightText: 2026 Deutsche Telekom AG
// SPDX-License-Identifier: Apache-2.0

package authoperator_test

import (
"os/exec"
"testing"
)

// TestWebhookCertificateLifetimes checks that each webhookServer.certificates
// value renders its flag only when set and that the schema rejects values
// that are not Go durations.
func TestWebhookCertificateLifetimes(t *testing.T) {
requireHelm(t)

flags := map[string]string{
"caValidity": "--webhook-ca-validity",
"certValidity": "--webhook-cert-validity",
"renewBefore": "--webhook-cert-renew-before",
"checkInterval": "--webhook-cert-check-interval",
}

defaults := helmTemplate(t)
for _, flag := range flags {
assertNotContains(t, defaults, flag)
}

for value, flag := range flags {
t.Run(value, func(t *testing.T) {
out := helmTemplate(t, "--set", "webhookServer.certificates."+value+"=1h30m")
assertContains(t, out, "- "+flag+"=1h30m\n")
for _, other := range flags {
if other != flag {
assertNotContains(t, out, other)
}
}

// Every spelling time.ParseDuration accepts must pass the schema.
for _, good := range []string{"720h", "1.5h", ".5h", "1.h", "+1h", "100ms", "1us", "1µs", "1μs", "1h2m3s"} {
helmTemplate(t, "--set-string", "webhookServer.certificates."+value+"="+good)
}

for _, bad := range []string{"30d", "-1h", "1"} {
cmd := exec.CommandContext(t.Context(), "helm", "template", "auth-operator", ".", // #nosec G204
"--set-string", "webhookServer.certificates."+value+"="+bad)
if out, err := cmd.CombinedOutput(); err == nil {
t.Errorf("schema must reject %s=%s, got:\n%s", value, bad, out)
}
}
})
}
}
33 changes: 33 additions & 0 deletions cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,11 @@ func TestFlagDefaults(t *testing.T) {
{"webhook", "disable-authorize-request-checks", "false"},
{"webhook", "webhook-tls-go-defaults", "false"},
{"webhook", "binddefinition-namespace-selector-label-group", "[t-caas.telekom.com]"},
// cert-controller's defaults, unchanged from before the flags existed.
{"webhook", "webhook-ca-validity", "87600h0m0s"},
{"webhook", "webhook-cert-validity", "8760h0m0s"},
{"webhook", "webhook-cert-renew-before", "2160h0m0s"},
{"webhook", "webhook-cert-check-interval", "12h0m0s"},
}

for _, tt := range tests {
Expand All @@ -523,6 +528,34 @@ func TestFlagDefaults(t *testing.T) {
}
}

// TestWebhookCmdRejectsInvalidCertLifetimes checks that the webhook command
// fails before creating the manager when the cert rotator lifetimes are
// inconsistent.
func TestWebhookCmdRejectsInvalidCertLifetimes(t *testing.T) {
flags := webhookCmd.Flags()
for name, value := range map[string]string{
"cert-rotation-secret-name": "auth-operator-webhook-certs",
"cert-rotation-dns-name": "auth-operator-webhook-service.ns.svc",
"certs-dir": t.TempDir(),
// Below the default 90-day renew-before.
"webhook-cert-validity": "720h",
} {
def := flags.Lookup(name).DefValue
if err := flags.Set(name, value); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = flags.Set(name, def) })
}
oldNamespace := namespace
namespace = "ns"
t.Cleanup(func() { namespace = oldNamespace })

err := webhookCmd.RunE(webhookCmd, nil)
if err == nil || !strings.Contains(err.Error(), "renew before 2160h0m0s must be less than certificate validity 720h0m0s") {
t.Fatalf("RunE() error = %v, want the cert rotation Validate error", err)
}
}

func TestWebhookTLSOpts(t *testing.T) {
if opts := webhookTLSOpts(true); len(opts) != 0 {
t.Fatalf("expected no TLS options with Go defaults, got %d", len(opts))
Expand Down
53 changes: 40 additions & 13 deletions cmd/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"math"
"os"
"strings"
"time"

authorizationv1alpha1 "github.com/telekom/auth-operator/api/authorization/v1alpha1"
authorizationwebhook "github.com/telekom/auth-operator/internal/webhook/authorization"
Expand Down Expand Up @@ -40,6 +41,10 @@ var (
certRotationSecretName string
certRotationValidatingWebhooks []string
certRotationMutatingWebhooks []string
webhookCAValidity time.Duration
webhookCertValidity time.Duration
webhookCertRenewBefore time.Duration
webhookCertCheckInterval time.Duration
enableTDGMigration bool
enableCAPIOperatorUpdateBypass bool
strictSANamespaceOwnership bool
Expand Down Expand Up @@ -88,6 +93,10 @@ ensuring authorization policies are enforced at creation time.`,
if err := validateEmergencyNamespaceTenant(emergencyNamespaceScope.Tenant); err != nil {
return err
}
certRotation := certRotationConfig()
if err := certRotation.Validate(); err != nil {
return fmt.Errorf("invalid webhook cert rotation flags: %w", err)
}
ctx, cancel := context.WithCancel(ctrl.SetupSignalHandler())
defer cancel()

Expand Down Expand Up @@ -162,19 +171,7 @@ ensuring authorization policies are enforced at creation time.`,
if !disableCertRotation && webhookCertsDir == "" {
return fmt.Errorf("unable to set up cert rotation: certs-dir is undefined. can't enable cert rotator")
}
certificatesReady, err := certrotation.AddRotator(ctx, mgr, certrotation.Config{
Disabled: disableCertRotation,
Namespace: namespace,
SecretName: certRotationSecretName,
DNSName: certRotationDNSName,
CertDir: webhookCertsDir,
CAName: "cert",
CAOrganization: "t-caas",
MutatingWebhooks: certRotationMutatingWebhooks,
ValidatingWebhooks: certRotationValidatingWebhooks,
RequireLeaderElection: true,
RestartOnSecretRefresh: true,
})
certificatesReady, err := certrotation.AddRotator(ctx, mgr, certRotation)
if err != nil {
return fmt.Errorf("unable to set up cert rotation: %w", err)
}
Expand All @@ -201,6 +198,27 @@ ensuring authorization policies are enforced at creation time.`,
},
}

// certRotationConfig builds the webhook cert rotator config from the flags.
func certRotationConfig() certrotation.Config {
return certrotation.Config{
Disabled: disableCertRotation,
Namespace: namespace,
SecretName: certRotationSecretName,
DNSName: certRotationDNSName,
CertDir: webhookCertsDir,
CAName: "cert",
CAOrganization: "t-caas",
MutatingWebhooks: certRotationMutatingWebhooks,
ValidatingWebhooks: certRotationValidatingWebhooks,
RequireLeaderElection: true,
RestartOnSecretRefresh: true,
CAValidity: webhookCAValidity,
CertValidity: webhookCertValidity,
RenewBefore: webhookCertRenewBefore,
CheckInterval: webhookCertCheckInterval,
}
}

func configureWebhooks(ctx context.Context, mgr manager.Manager, tp *tracing.Provider) error {
log := ctrl.LoggerFrom(ctx).WithName("webhook-setup")
if err := authorizationv1alpha1.ValidateNamespaceAdmissionSelectorLabelGroups(bindDefinitionNamespaceSelectorLabelGroups); err != nil {
Expand Down Expand Up @@ -368,6 +386,15 @@ func init() {
[]string{}, "The mutating webhooks")
webhookCmd.Flags().StringSliceVar(&certRotationValidatingWebhooks, "cert-rotation-validating-webhook",
[]string{}, "The validating webhooks")
webhookCmd.Flags().DurationVar(&webhookCAValidity, "webhook-ca-validity", certrotation.DefaultCAValidity,
"Lifetime of a webhook CA generated by the cert rotator. Does not change the validity of a provided CA.")
webhookCmd.Flags().DurationVar(&webhookCertValidity, "webhook-cert-validity", certrotation.DefaultCertValidity,
"Lifetime of the webhook serving certificate generated by the cert rotator.")
webhookCmd.Flags().DurationVar(&webhookCertRenewBefore, "webhook-cert-renew-before", certrotation.DefaultRenewBefore,
"Renew the webhook CA and serving certificate this long before they expire. "+
"Must satisfy --webhook-cert-check-interval < --webhook-cert-renew-before < --webhook-cert-validity <= --webhook-ca-validity.")
webhookCmd.Flags().DurationVar(&webhookCertCheckInterval, "webhook-cert-check-interval", certrotation.DefaultCheckInterval,
"How often the cert rotator checks the webhook certificates for renewal.")

webhookCmd.Flags().BoolVar(&enableTDGMigration, "tdg-migration", false,
"If set, the legacy labels and behavior for TDG migration will be enabled.")
Expand Down
Loading
Loading