From 6e1bc3695a83e44bdad6697d162fae3fcbc51f27 Mon Sep 17 00:00:00 2001 From: Eniko Dif Date: Thu, 26 Nov 2026 16:09:16 +0100 Subject: [PATCH 1/2] Replay WRT allowed-kinds validation at reconcile time Deployments without the admission webhook let out-of-allow-list WorkerResourceTemplate specs onto the cluster, where the controller would happily apply them. Replay the webhook's pure spec validation (the same allowed-kinds + structural checks ValidateCreate runs) in the WRT render path, so a rejected spec fails before any object is applied and surfaces as an applyError exactly like a render failure. - Export ValidateWorkerResourceTemplateSpecForApply and a shared AllowedKindsFromEnv helper in api/v1alpha1; the webhook and the reconciler now parse ALLOWED_KINDS through one code path. - RenderWorkerResourceTemplate takes the allow list and validates the spec first; an empty list denies all kinds, mirroring the webhook's fail-closed semantics. - Plumb the list through planner.Config, getWorkerResourceApplies, WorkerDeploymentReconciler, and cmd/main.go. - envtest sets ALLOWED_KINDS in setupTestEnvironment and covers the rejection with a new wrt-rejected-kind case. --- .../workerresourcetemplate_webhook.go | 41 ++++++++-- .../workerresourcetemplate_webhook_test.go | 44 +++++++++++ cmd/main.go | 1 + internal/controller/execplan_test.go | 2 +- internal/controller/genplan.go | 1 + internal/controller/reconciler_events_test.go | 1 + internal/k8s/workerresourcetemplates.go | 13 ++++ internal/k8s/workerresourcetemplates_test.go | 63 ++++++++++++++- internal/planner/planner.go | 8 ++ internal/planner/planner_test.go | 57 ++++++++++++-- pkg/controller/config/config.go | 19 +++++ pkg/controller/config/env_test.go | 24 ++++++ pkg/controller/controller.go | 1 + tests/integration/helpers.go | 5 ++ tests/integration/wrt.go | 77 ++++++++++++++++++- 15 files changed, 338 insertions(+), 19 deletions(-) diff --git a/api/v1alpha1/workerresourcetemplate_webhook.go b/api/v1alpha1/workerresourcetemplate_webhook.go index bd7f6bce0..dafd86123 100644 --- a/api/v1alpha1/workerresourcetemplate_webhook.go +++ b/api/v1alpha1/workerresourcetemplate_webhook.go @@ -66,6 +66,20 @@ var ControllerOwnedMetricLabelKeys = []string{ // Configurable via workerResourceTemplate.allowedResources[*].kinds in values.yaml. // Must be set; when empty or unset, all WorkerResourceTemplate kind submissions are rejected. func NewWorkerResourceTemplateValidator(mgr ctrl.Manager) *WorkerResourceTemplateValidator { + return &WorkerResourceTemplateValidator{ + Client: mgr.GetClient(), + RESTMapper: mgr.GetRESTMapper(), + ControllerSAName: os.Getenv("SERVICE_ACCOUNT_NAME"), + ControllerSANamespace: os.Getenv("POD_NAMESPACE"), + AllowedKinds: AllowedKindsFromEnv(), + } +} + +// AllowedKindsFromEnv parses the ALLOWED_KINDS environment variable (comma-separated +// kind names) into a slice. It is shared by the admission webhook and the controller's +// reconcile-time validation so both paths always see the same list. Returns nil when +// the variable is unset or empty — callers treat an empty list as deny-all. +func AllowedKindsFromEnv() []string { var allowedKinds []string if env := os.Getenv("ALLOWED_KINDS"); env != "" { for _, p := range strings.Split(env, ",") { @@ -74,13 +88,28 @@ func NewWorkerResourceTemplateValidator(mgr ctrl.Manager) *WorkerResourceTemplat } } } - return &WorkerResourceTemplateValidator{ - Client: mgr.GetClient(), - RESTMapper: mgr.GetRESTMapper(), - ControllerSAName: os.Getenv("SERVICE_ACCOUNT_NAME"), - ControllerSANamespace: os.Getenv("POD_NAMESPACE"), - AllowedKinds: allowedKinds, + return allowedKinds +} + +// ValidateWorkerResourceTemplateSpecForApply replays the pure (no-API) spec validation +// that the admission webhook's ValidateCreate runs, for use in the controller's +// reconcile-time apply path. It exists so deployments without the admission webhook +// (where WRTs can be created via kubectl) still reject specs whose kind is outside the +// allow list before any object is applied. The API-dependent checks (RESTMapper scope, +// SubjectAccessReview) are deliberately NOT replayed — they need admission context. +// The HPAMatchLabelsStripTemporalPrefix flag is likewise not replayed: validation runs +// as if the flag were false, so when the webhook is configured to strip the "temporal_" +// prefix it rejects user-set unprefixed matchLabels keys that this replay accepts. +// That gap is harmless — auto-injection overwrites those keys at render time — but it +// makes the replay slightly weaker than ValidateCreate. +// An empty allowedKinds list rejects every kind, mirroring the webhook's fail-closed +// semantics. +func ValidateWorkerResourceTemplateSpecForApply(spec WorkerResourceTemplateSpec, allowedKinds []string) error { + _, errs := validateWorkerResourceTemplateSpec(spec, allowedKinds, false) + if len(errs) == 0 { + return nil } + return errs.ToAggregate() } // SetupWebhookWithManager registers the validating webhook with the manager. diff --git a/api/v1alpha1/workerresourcetemplate_webhook_test.go b/api/v1alpha1/workerresourcetemplate_webhook_test.go index 23e4ad796..8ba1dc80c 100644 --- a/api/v1alpha1/workerresourcetemplate_webhook_test.go +++ b/api/v1alpha1/workerresourcetemplate_webhook_test.go @@ -915,3 +915,47 @@ func TestWorkerResourceTemplate_MultipleErrors(t *testing.T) { assert.Contains(t, err.Error(), "metadata.name is generated by the controller") assert.Contains(t, err.Error(), "minReplicas must not be 0") } + +// TestValidateWorkerResourceTemplateSpecForApply covers the reconcile-time replay of the +// webhook's pure spec validation: in-list specs pass, out-of-list kinds are rejected with +// the same message the admission webhook produces, and an empty allow list rejects all +// kinds (deny-all). +func TestValidateWorkerResourceTemplateSpecForApply(t *testing.T) { + testCases := map[string]struct { + allowedKinds []string + embeddedObj map[string]interface{} + wantErr string + }{ + "in-list kind passes": { + allowedKinds: []string{"HorizontalPodAutoscaler", "PodDisruptionBudget"}, + embeddedObj: validHPAObject(), + }, + "out-of-list kind is rejected": { + allowedKinds: []string{"PodDisruptionBudget"}, + embeddedObj: map[string]interface{}{ + "apiVersion": "apps/v1", + "kind": "Deployment", + "spec": map[string]interface{}{}, + }, + wantErr: "not in the allowed list", + }, + "empty allow list rejects everything": { + allowedKinds: nil, + embeddedObj: validHPAObject(), + wantErr: "not in the allowed list", + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + err := temporaliov1alpha1.ValidateWorkerResourceTemplateSpecForApply( + newWRT("my-wrt", "my-worker", tc.embeddedObj).Spec, tc.allowedKinds) + if tc.wantErr == "" { + require.NoError(t, err) + return + } + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErr) + }) + } +} diff --git a/cmd/main.go b/cmd/main.go index 0d32095e5..4e10ace4e 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -170,6 +170,7 @@ func main() { controller.WithDisableDeprecatedTWD(!deprecatedCRDWatches.TemporalWorkerDeployments), controller.WithDisableClusterConnections(namespaceScoped), controller.WithWRTHPAMatchLabelsStripTemporalPrefix(wrtHPAMatchLabelsStripTemporalPrefix), + controller.WithAllowedKinds(temporaliov1alpha1.AllowedKindsFromEnv()), ) if err != nil { setupLog.Error(err, "unable to create controller", "controller", "WorkerDeployment") diff --git a/internal/controller/execplan_test.go b/internal/controller/execplan_test.go index 7cbf0077e..f2078d788 100644 --- a/internal/controller/execplan_test.go +++ b/internal/controller/execplan_test.go @@ -130,7 +130,7 @@ func makeExecplanWRT(name string, twd *temporaliov1alpha1.WorkerDeployment) *tem // returning the rendered object and its hash. func renderWRT(t *testing.T, wrt *temporaliov1alpha1.WorkerResourceTemplate, dep *appsv1.Deployment, buildID, temporalNamespace string) (*unstructured.Unstructured, string) { t.Helper() - rendered, err := k8s.RenderWorkerResourceTemplate(wrt, dep, buildID, temporalNamespace, false) + rendered, err := k8s.RenderWorkerResourceTemplate(wrt, dep, buildID, temporalNamespace, false, []string{"HorizontalPodAutoscaler", "PodDisruptionBudget"}) require.NoError(t, err) hash := k8s.ComputeRenderedObjectHash(rendered) require.NotEmpty(t, hash) diff --git a/internal/controller/genplan.go b/internal/controller/genplan.go index 720f6f7b9..dfa25f7cb 100644 --- a/internal/controller/genplan.go +++ b/internal/controller/genplan.go @@ -146,6 +146,7 @@ func (r *WorkerDeploymentReconciler) generatePlan( plannerConfig := &planner.Config{ RolloutStrategy: rolloutStrategy, WRTHPAMatchLabelsStripTemporalPrefix: r.Config.WRTHPAMatchLabelsStripTemporalPrefix, + AllowedKinds: r.Config.AllowedKinds, } // Fetch all WorkerResourceTemplates that reference this TWD so that the planner diff --git a/internal/controller/reconciler_events_test.go b/internal/controller/reconciler_events_test.go index d81406023..2625e1098 100644 --- a/internal/controller/reconciler_events_test.go +++ b/internal/controller/reconciler_events_test.go @@ -94,6 +94,7 @@ func newTestReconcilerWithInterceptors(objs []client.Object, funcs interceptor.F } r.Config.DisableRecoverPanic = true r.Config.MaxDeploymentVersionsIneligibleForDeletion = 75 + r.Config.AllowedKinds = []string{"HorizontalPodAutoscaler", "PodDisruptionBudget"} return r, recorder } diff --git a/internal/k8s/workerresourcetemplates.go b/internal/k8s/workerresourcetemplates.go index 161661a99..878017462 100644 --- a/internal/k8s/workerresourcetemplates.go +++ b/internal/k8s/workerresourcetemplates.go @@ -71,17 +71,30 @@ func ComputeWorkerResourceTemplateName(wdName, wrtName, buildID string) string { // WorkerResourceTemplate and versioned Deployment. // // Processing order: +// 0. Replay the admission webhook's pure spec validation (allowed kinds + structural +// checks) — rejected specs fail here, before any rendering or apply. This covers +// deployments without the admission webhook, where an out-of-allow-list WRT can +// exist on the cluster; it is surfaced as an applyError exactly like a render failure. // 1. Unmarshal spec.template into an Unstructured // 2. Substitute per-version metric tokens in string values // 3. Auto-inject scaleTargetRef, matchLabels, and KEDA temporal trigger metadata // 4. Set metadata (name, namespace, labels, owner reference) +// +// An empty allowedKinds list rejects every kind (deny-all), mirroring the webhook's +// fail-closed semantics. func RenderWorkerResourceTemplate( wrt *temporaliov1alpha1.WorkerResourceTemplate, deployment *appsv1.Deployment, buildID string, temporalNamespace string, stripTemporalMetricLabelPrefix bool, + allowedKinds []string, ) (*unstructured.Unstructured, error) { + // Step 0: replay the webhook's pure spec validation before rendering anything. + if err := temporaliov1alpha1.ValidateWorkerResourceTemplateSpecForApply(wrt.Spec, allowedKinds); err != nil { + return nil, fmt.Errorf("spec validation failed: %w", err) + } + // Step 1: unmarshal the raw template directly into an Unstructured object. obj := &unstructured.Unstructured{} if err := json.Unmarshal(wrt.Spec.Template.Raw, &obj.Object); err != nil { diff --git a/internal/k8s/workerresourcetemplates_test.go b/internal/k8s/workerresourcetemplates_test.go index d05724e09..322095390 100644 --- a/internal/k8s/workerresourcetemplates_test.go +++ b/internal/k8s/workerresourcetemplates_test.go @@ -12,6 +12,7 @@ import ( temporaliov1alpha1 "github.com/temporalio/temporal-worker-controller/api/v1alpha1" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ) @@ -515,7 +516,7 @@ func TestRenderWorkerResourceTemplate(t *testing.T) { } buildID := "abc123" - obj, err := RenderWorkerResourceTemplate(wrt, deployment, buildID, "my-temporal-ns", false) + obj, err := RenderWorkerResourceTemplate(wrt, deployment, buildID, "my-temporal-ns", false, []string{"HorizontalPodAutoscaler"}) require.NoError(t, err) // Check metadata — name follows the hash-suffix formula @@ -587,7 +588,7 @@ func TestRenderWorkerResourceTemplate_StripsTemporalMetricLabelPrefix(t *testing ObjectMeta: metav1.ObjectMeta{Name: "my-worker-abc123", Namespace: "default"}, } - obj, err := RenderWorkerResourceTemplate(wrt, deployment, "abc123", "my-temporal-ns", true) + obj, err := RenderWorkerResourceTemplate(wrt, deployment, "abc123", "my-temporal-ns", true, []string{"HorizontalPodAutoscaler"}) require.NoError(t, err) ml := obj.Object["spec"].(map[string]interface{})["metrics"].([]interface{})[0].(map[string]interface{})["external"].(map[string]interface{})["metric"].(map[string]interface{})["selector"].(map[string]interface{})["matchLabels"].(map[string]interface{}) @@ -653,7 +654,7 @@ func TestRenderWorkerResourceTemplate_MetricTemplateVars(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: "my-worker-abc123", Namespace: "default"}, } - obj, err := RenderWorkerResourceTemplate(wrt, deployment, buildID, "my-temporal-ns", false) + obj, err := RenderWorkerResourceTemplate(wrt, deployment, buildID, "my-temporal-ns", false, []string{"ScaledObject"}) require.NoError(t, err) annotations := obj.GetAnnotations() @@ -711,7 +712,7 @@ func TestRenderWorkerResourceTemplate_MetricTemplateVarsStripPrefix(t *testing.T ObjectMeta: metav1.ObjectMeta{Name: "my-worker-abc123", Namespace: "default"}, } - obj, err := RenderWorkerResourceTemplate(wrt, deployment, buildID, "my-temporal-ns", true) + obj, err := RenderWorkerResourceTemplate(wrt, deployment, buildID, "my-temporal-ns", true, []string{"ScaledObject"}) require.NoError(t, err) promMD := obj.Object["spec"].(map[string]interface{})["triggers"].([]interface{})[0].(map[string]interface{})["metadata"].(map[string]interface{}) @@ -889,3 +890,57 @@ func TestHasScaleTarget(t *testing.T) { assert.False(t, HasScaleTarget(raw)) }) } + +// TestRenderWorkerResourceTemplate_RejectsKindOutsideAllowList verifies that the +// reconcile-time replay of the webhook's spec validation runs before any rendering: +// an out-of-allow-list kind (or an empty allow list) errors without producing an +// object, while an in-list spec renders exactly as before. +func TestRenderWorkerResourceTemplate_RejectsKindOutsideAllowList(t *testing.T) { + hpaObject := func() map[string]interface{} { + return map[string]interface{}{ + "apiVersion": "autoscaling/v2", + "kind": "HorizontalPodAutoscaler", + "spec": map[string]interface{}{ + "scaleTargetRef": map[string]interface{}{}, + "minReplicas": float64(2), + "maxReplicas": float64(10), + }, + } + } + renderWRT := func(t *testing.T, embeddedObj map[string]interface{}, allowedKinds []string) (*unstructured.Unstructured, error) { + t.Helper() + rawBytes, err := json.Marshal(embeddedObj) + require.NoError(t, err) + wrt := &temporaliov1alpha1.WorkerResourceTemplate{ + ObjectMeta: metav1.ObjectMeta{Name: "my-wrt", Namespace: "default"}, + Spec: temporaliov1alpha1.WorkerResourceTemplateSpec{ + WorkerDeploymentRef: &temporaliov1alpha1.WorkerDeploymentReference{Name: "my-worker"}, + Template: runtime.RawExtension{Raw: rawBytes}, + }, + } + deployment := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "my-worker-abc123", Namespace: "default"}} + return RenderWorkerResourceTemplate(wrt, deployment, "abc123", "my-temporal-ns", false, allowedKinds) + } + + deploymentKind := map[string]interface{}{ + "apiVersion": "apps/v1", + "kind": "Deployment", + "spec": map[string]interface{}{}, + } + + obj, err := renderWRT(t, deploymentKind, []string{"HorizontalPodAutoscaler"}) + require.Error(t, err) + assert.Nil(t, obj) + assert.Contains(t, err.Error(), "spec validation failed") + assert.Contains(t, err.Error(), "not in the allowed list") + + obj, err = renderWRT(t, hpaObject(), nil) + require.Error(t, err, "empty allow list must reject every kind (deny-all)") + assert.Nil(t, obj) + assert.Contains(t, err.Error(), "not in the allowed list") + + obj, err = renderWRT(t, hpaObject(), []string{"HorizontalPodAutoscaler"}) + require.NoError(t, err) + require.NotNil(t, obj) + assert.Equal(t, "HorizontalPodAutoscaler", obj.GetKind()) +} diff --git a/internal/planner/planner.go b/internal/planner/planner.go index 307cdc9bd..5c5041215 100644 --- a/internal/planner/planner.go +++ b/internal/planner/planner.go @@ -142,6 +142,11 @@ type Config struct { // WRTHPAMatchLabelsStripTemporalPrefix removes the "temporal_" prefix from // controller-managed external metric matchLabels. WRTHPAMatchLabelsStripTemporalPrefix bool + + // AllowedKinds is the list of resource kinds permitted as WorkerResourceTemplate + // objects, replayed at render time (the same check the admission webhook runs). + // Empty or nil means deny-all, mirroring the webhook's fail-closed semantics. + AllowedKinds []string } // GeneratePlan creates a plan for updating the worker deployment @@ -211,6 +216,7 @@ func GeneratePlan( sunsetBuildIDs, versionStatuses, config.WRTHPAMatchLabelsStripTemporalPrefix, + config.AllowedKinds, ) plan.DeleteWorkerResources = getDeleteWorkerResources(wrts, plan.DeleteDeployments, k8sState, sunsetBuildIDs, versionStatuses) plan.EnsureWRTOwnerRefs = getWRTOwnerRefPatches(wrts, twdName, twdUID) @@ -232,6 +238,7 @@ func getWorkerResourceApplies( sunsetBuildIDs map[string]struct{}, versionStatuses map[string]temporaliov1alpha1.VersionStatus, stripTemporalMetricLabelPrefix bool, + allowedKinds []string, ) []WorkerResourceApply { // Build a set of deployment names that are scheduled for deletion so we can // skip rendering WRTs for them. Their rendered resources are deleted explicitly @@ -276,6 +283,7 @@ func getWorkerResourceApplies( buildID, temporalNamespace, stripTemporalMetricLabelPrefix, + allowedKinds, ) if renderErr != nil { l.Error(renderErr, "failed to render WorkerResourceTemplate", diff --git a/internal/planner/planner_test.go b/internal/planner/planner_test.go index 61ea06a7d..b30548d99 100644 --- a/internal/planner/planner_test.go +++ b/internal/planner/planner_test.go @@ -4033,7 +4033,7 @@ func TestGetWorkerResourceApplies(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - applies := getWorkerResourceApplies(logr.Discard(), tc.wrts, tc.k8sState, "test-temporal-ns", tc.deleteDeployments, nil, nil, false) + applies := getWorkerResourceApplies(logr.Discard(), tc.wrts, tc.k8sState, "test-temporal-ns", tc.deleteDeployments, nil, nil, false, testAllowedKinds) assert.Equal(t, tc.expectCount, len(applies), "unexpected number of worker resource applies") }) } @@ -4050,7 +4050,7 @@ func TestGetWorkerResourceApplies_RenderError(t *testing.T) { createTestWRT("my-hpa", "my-worker"), } - applies := getWorkerResourceApplies(logr.Discard(), wrts, k8sState, "test-temporal-ns", nil, nil, nil, false) + applies := getWorkerResourceApplies(logr.Discard(), wrts, k8sState, "test-temporal-ns", nil, nil, nil, false, testAllowedKinds) require.Len(t, applies, 2) var errEntry, okEntry *WorkerResourceApply @@ -4082,7 +4082,7 @@ func TestGetWorkerResourceApplies_ApplyContents(t *testing.T) { }, } - applies := getWorkerResourceApplies(logr.Discard(), []temporaliov1alpha1.WorkerResourceTemplate{wrt}, k8sState, "test-temporal-ns", nil, nil, nil, false) + applies := getWorkerResourceApplies(logr.Discard(), []temporaliov1alpha1.WorkerResourceTemplate{wrt}, k8sState, "test-temporal-ns", nil, nil, nil, false, testAllowedKinds) require.Len(t, applies, 1) apply := applies[0] @@ -4104,6 +4104,10 @@ func TestGetWorkerResourceApplies_ApplyContents(t *testing.T) { // createTestWRT builds a minimal valid WorkerResourceTemplate for use in tests. // The embedded object is a stub HPA with scaleTargetRef opted in for auto-injection. +// testAllowedKinds mirrors the ALLOWED_KINDS list the Helm chart injects by default; +// it covers every kind the planner tests render. +var testAllowedKinds = []string{"HorizontalPodAutoscaler", "PodDisruptionBudget"} + func createTestWRT(name, workerDeploymentRefName string) temporaliov1alpha1.WorkerResourceTemplate { hpaSpec := map[string]interface{}{ "apiVersion": "autoscaling/v2", @@ -4175,7 +4179,7 @@ func TestGetWorkerResourceApplies_MatchLabelsInjection(t *testing.T) { Deployments: map[string]*appsv1.Deployment{"build-abc": deployment}, } - applies := getWorkerResourceApplies(logr.Discard(), []temporaliov1alpha1.WorkerResourceTemplate{wrt}, k8sState, "test-temporal-ns", nil, nil, nil, false) + applies := getWorkerResourceApplies(logr.Discard(), []temporaliov1alpha1.WorkerResourceTemplate{wrt}, k8sState, "test-temporal-ns", nil, nil, nil, false, testAllowedKinds) require.Len(t, applies, 1) spec, ok := applies[0].Resource.Object["spec"].(map[string]interface{}) @@ -4235,6 +4239,7 @@ func TestGetWorkerResourceApplies_StripsTemporalMetricLabelPrefix(t *testing.T) nil, nil, true, + testAllowedKinds, ) require.Len(t, applies, 1) @@ -4932,7 +4937,7 @@ func TestGetWorkerResourceApplies_SunsetBuildIDs(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - applies := getWorkerResourceApplies(logr.Discard(), tc.wrts, k8sState, "test-temporal-ns", nil, tc.sunsetBuildIDs, nil, false) + applies := getWorkerResourceApplies(logr.Discard(), tc.wrts, k8sState, "test-temporal-ns", nil, tc.sunsetBuildIDs, nil, false, testAllowedKinds) assert.ElementsMatch(t, tc.expectKeys, applyKeys(applies)) }) } @@ -5306,7 +5311,7 @@ func TestGetWorkerResourceApplies_VersionStatuses(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - applies := getWorkerResourceApplies(logr.Discard(), tc.wrts, k8sState, "test-temporal-ns", nil, tc.sunsetBuildIDs, versionStatuses, false) + applies := getWorkerResourceApplies(logr.Discard(), tc.wrts, k8sState, "test-temporal-ns", nil, tc.sunsetBuildIDs, versionStatuses, false, testAllowedKinds) assert.ElementsMatch(t, tc.expectKeys, applyKeys(applies)) }) } @@ -5816,3 +5821,43 @@ func TestGetUpdateDeployments_DeploymentLabelsReconcile(t *testing.T) { assert.Equal(t, maxSurge, *d.Spec.Strategy.RollingUpdate.MaxSurge, d.Name) } } + +// TestGetWorkerResourceApplies_AllowedKindsRejection mirrors the render-failure path: +// a WRT whose kind is outside the allow list yields a WorkerResourceApply with +// RenderError set and Resource nil (surfaced as an applyError, never applied). +func TestGetWorkerResourceApplies_AllowedKindsRejection(t *testing.T) { + raw, _ := json.Marshal(map[string]interface{}{ + "apiVersion": "autoscaling/v2", + "kind": "HorizontalPodAutoscaler", + "spec": map[string]interface{}{ + "scaleTargetRef": map[string]interface{}{}, + "minReplicas": float64(1), + "maxReplicas": float64(5), + }, + }) + wrt := temporaliov1alpha1.WorkerResourceTemplate{ + ObjectMeta: metav1.ObjectMeta{Name: "my-hpa", Namespace: "default"}, + Spec: temporaliov1alpha1.WorkerResourceTemplateSpec{ + WorkerDeploymentRef: &temporaliov1alpha1.WorkerDeploymentReference{Name: "my-worker"}, + Template: runtime.RawExtension{Raw: raw}, + }, + } + k8sState := &k8s.DeploymentState{ + Deployments: map[string]*appsv1.Deployment{ + "build-a": createDeploymentWithUID("worker-build-a", "uid-a"), + }, + } + + // Allow list that does NOT include HorizontalPodAutoscaler: rejection, no resource. + applies := getWorkerResourceApplies(logr.Discard(), []temporaliov1alpha1.WorkerResourceTemplate{wrt}, k8sState, "test-temporal-ns", nil, nil, nil, false, []string{"PodDisruptionBudget"}) + require.Len(t, applies, 1) + require.Error(t, applies[0].RenderError) + assert.Nil(t, applies[0].Resource) + assert.Contains(t, applies[0].RenderError.Error(), "not in the allowed list") + + // Same WRT with the kind allowed: a normal apply entry. + applies = getWorkerResourceApplies(logr.Discard(), []temporaliov1alpha1.WorkerResourceTemplate{wrt}, k8sState, "test-temporal-ns", nil, nil, nil, false, testAllowedKinds) + require.Len(t, applies, 1) + assert.NoError(t, applies[0].RenderError) + assert.NotNil(t, applies[0].Resource) +} diff --git a/pkg/controller/config/config.go b/pkg/controller/config/config.go index b4a2bf10c..f1a533c57 100644 --- a/pkg/controller/config/config.go +++ b/pkg/controller/config/config.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" + temporaliov1alpha1 "github.com/temporalio/temporal-worker-controller/api/v1alpha1" "github.com/temporalio/temporal-worker-controller/internal/controller/clientpool" sdkclient "go.temporal.io/sdk/client" "go.temporal.io/sdk/log" @@ -50,6 +51,14 @@ type Config struct { // controller-managed external metric matchLabels in rendered // WorkerResourceTemplates. WRTHPAMatchLabelsStripTemporalPrefix bool + // AllowedKinds is the list of resource kinds permitted as WorkerResourceTemplate + // objects. The reconcile-time WRT apply path replays the admission webhook's pure + // spec validation against this list, so out-of-allow-list WRTs are rejected before + // any object is applied even when the webhook is not deployed. ConfigFromEnv + // populates it from the ALLOWED_KINDS environment variable; WithAllowedKinds + // overrides that default. Empty or nil means deny-all, mirroring the webhook's + // fail-closed semantics. + AllowedKinds []string } // ConfigFromEnv returns a new Config struct popualated with any options read @@ -58,6 +67,7 @@ func ConfigFromEnv() Config { return Config{ PoolLogger: defaultPoolLogger(), MaxDeploymentVersionsIneligibleForDeletion: GetControllerMaxDeploymentVersionsIneligibleForDeletion(), + AllowedKinds: temporaliov1alpha1.AllowedKindsFromEnv(), } } @@ -137,3 +147,12 @@ func WithWRTHPAMatchLabelsStripTemporalPrefix(strip bool) Option { c.WRTHPAMatchLabelsStripTemporalPrefix = strip } } + +// WithAllowedKinds sets the list of resource kinds permitted as +// WorkerResourceTemplate objects; the reconcile-time apply path replays the +// admission webhook's spec validation against it. +func WithAllowedKinds(kinds []string) Option { + return func(c *Config) { + c.AllowedKinds = kinds + } +} diff --git a/pkg/controller/config/env_test.go b/pkg/controller/config/env_test.go index 1a822b9cd..1a26665f8 100644 --- a/pkg/controller/config/env_test.go +++ b/pkg/controller/config/env_test.go @@ -5,6 +5,7 @@ package config_test import ( + "reflect" "testing" "github.com/temporalio/temporal-worker-controller/pkg/controller/config" @@ -31,3 +32,26 @@ func TestGetWRTHPAMatchLabelsStripTemporalPrefix(t *testing.T) { }) } } + +func TestConfigFromEnvAllowedKinds(t *testing.T) { + tests := map[string]struct { + value string + want []string + }{ + "empty rejects all kinds": {"", nil}, + "single kind": {"HorizontalPodAutoscaler", []string{"HorizontalPodAutoscaler"}}, + "comma-separated kinds": {"HorizontalPodAutoscaler,PodDisruptionBudget", []string{"HorizontalPodAutoscaler", "PodDisruptionBudget"}}, + "surrounding spaces are trimmed": {" PodDisruptionBudget , HorizontalPodAutoscaler ", []string{"PodDisruptionBudget", "HorizontalPodAutoscaler"}}, + "empty entries are dropped": {",,PodDisruptionBudget,,", []string{"PodDisruptionBudget"}}, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Setenv("ALLOWED_KINDS", tc.value) + got := config.ConfigFromEnv().AllowedKinds + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("ConfigFromEnv().AllowedKinds = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 91f6855af..5e7ba56cf 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -45,6 +45,7 @@ var ( WithDisableRecoverPanic = config.WithDisableRecoverPanic WithDisableClusterConnections = config.WithDisableClusterConnections WithWRTHPAMatchLabelsStripTemporalPrefix = config.WithWRTHPAMatchLabelsStripTemporalPrefix + WithAllowedKinds = config.WithAllowedKinds ) // New returns a Controller wired with the given manager, or an diff --git a/tests/integration/helpers.go b/tests/integration/helpers.go index 9dbe97575..1458813b2 100644 --- a/tests/integration/helpers.go +++ b/tests/integration/helpers.go @@ -213,6 +213,10 @@ func setupTestEnvironment(t *testing.T) (*rest.Config, client.Client, manager.Ma // set max versions value for testing t.Setenv(config.MaxDeploymentVersionsIneligibleForDeletionEnvKey, fmt.Sprintf("%d", testMaxVersionsIneligibleForDeletion)) + // Set the WRT allow list the same way the Helm chart injects it, so the reconciler's + // replay of the webhook's spec validation does not deny-all the WRTs these tests create. + t.Setenv("ALLOWED_KINDS", "HorizontalPodAutoscaler,PodDisruptionBudget") + // Setup kubebuilder assets for IDE testing if err := setupKubebuilderAssets(); err != nil { t.Logf("Warning: Could not setup kubebuilder assets automatically: %v", err) @@ -273,6 +277,7 @@ func setupTestEnvironment(t *testing.T) (*rest.Config, client.Client, manager.Ma reconciler.Config.DisableRecoverPanic = true reconciler.Config.MaxDeploymentVersionsIneligibleForDeletion = config.GetControllerMaxDeploymentVersionsIneligibleForDeletion() reconciler.Config.WRTHPAMatchLabelsStripTemporalPrefix = config.GetWRTHPAMatchLabelsStripTemporalPrefix() + reconciler.Config.AllowedKinds = temporaliov1alpha1.AllowedKindsFromEnv() err = reconciler.SetupWithManager(mgr) if err != nil { t.Fatalf("failed to set up controller: %v", err) diff --git a/tests/integration/wrt.go b/tests/integration/wrt.go index 8fcd073ad..6b227be86 100644 --- a/tests/integration/wrt.go +++ b/tests/integration/wrt.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "fmt" + "strings" "testing" "time" @@ -14,7 +15,9 @@ import ( "github.com/temporalio/temporal-worker-controller/internal/testhelpers" autoscalingv2 "k8s.io/api/autoscaling/v2" policyv1 "k8s.io/api/policy/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/retry" @@ -429,8 +432,9 @@ func wrtTestCases() []testCase { }, // Apply failure → status entry with non-empty Message and LastAppliedGeneration == 0. - // Uses an unknown GVK that the API server cannot recognise. The controller's SSA apply - // fails and the WRT status must reflect the failure for that Build ID. + // Uses an unknown GVK whose kind is outside the ALLOWED_KINDS list, so the + // controller's reconcile-time spec validation rejects it before the SSA apply and the + // WRT status must reflect the failure for that Build ID. { name: "wrt-apply-failure", builder: testhelpers.NewTestCase(). @@ -464,6 +468,75 @@ func wrtTestCases() []testCase { }), }, + // Reconcile-time allowed-kinds validation — a WRT whose kind is outside the + // ALLOWED_KINDS list is rejected at render time (the same check the admission + // webhook runs), so no rendered object is applied and the per-Build-ID status + // entry records the rejection with the allow-list message. + { + name: "wrt-rejected-kind", + builder: testhelpers.NewTestCase(). + WithInput( + testhelpers.NewWorkerDeploymentBuilder(). + WithAllAtOnceStrategy(). + WithTargetTemplate("v1.0"), + ). + WithExpectedStatus( + testhelpers.NewStatusBuilder(). + WithTargetVersion("v1.0", temporaliov1alpha1.VersionStatusCurrent, -1, true, false). + WithCurrentVersion("v1.0", true, false), + ). + WithValidatorFunction(func(t *testing.T, ctx context.Context, tc testhelpers.TestCase, env testhelpers.TestEnv) { + twd := tc.GetTWD() + buildID := k8s.ComputeBuildID(twd) + wrtName := "rejected-kind" + + // Real apiVersion + real kind, but a kind outside the allow list. + wrt := makeWRTWithRaw(wrtName, twd.Namespace, twd.Name, []byte(`{ + "apiVersion": "apps/v1", + "kind": "Deployment", + "spec": { + "replicas": 1, + "selector": {}, + "template": {"spec": {"containers": [{"name": "c", "image": "nginx"}]}} + } + }`)) + if err := env.K8sClient.Create(ctx, wrt); err != nil { + t.Fatalf("failed to create WRT: %v", err) + } + + // The status entry must record the rejection with the allow-list + // message and LastAppliedGeneration == 0. + eventually(t, 30*time.Second, time.Second, func() error { + var stored temporaliov1alpha1.WorkerResourceTemplate + if err := env.K8sClient.Get(ctx, types.NamespacedName{Name: wrtName, Namespace: twd.Namespace}, &stored); err != nil { + return err + } + for _, v := range stored.Status.Versions { + if v.BuildID == buildID { + if v.ApplyError != "" && strings.Contains(v.ApplyError, "not in the allowed list") && v.LastAppliedGeneration == 0 { + t.Logf("WRT status correctly records the allow-list rejection for build ID %q, message: %s", buildID, v.ApplyError) + return nil + } + return fmt.Errorf("WRT status for build ID %q: lastAppliedGeneration=%d message=%q (want allow-list rejection with gen=0)", buildID, v.LastAppliedGeneration, v.ApplyError) + } + } + return fmt.Errorf("WRT status has no entry for build ID %q (current: %+v)", buildID, stored.Status.Versions) + }) + + // No rendered object may exist for the rejected WRT. + resourceName := k8s.ComputeWorkerResourceTemplateName(twd.Name, wrtName, buildID) + rendered := &unstructured.Unstructured{} + rendered.SetAPIVersion("apps/v1") + rendered.SetKind("Deployment") + err := env.K8sClient.Get(ctx, types.NamespacedName{Name: resourceName, Namespace: twd.Namespace}, rendered) + if err == nil { + t.Fatalf("rendered Deployment %q exists although the WRT kind was rejected by the allow list", resourceName) + } else if !apierrors.IsNotFound(err) { + t.Fatalf("unexpected error checking for rendered Deployment %q: %v", resourceName, err) + } + }), + }, + // SSA idempotency — multiple reconcile loops do not create duplicates. // Verifies that the HPA's resourceVersion and ownerReference count do not change after // additional reconcile loops are triggered by patching the TWD annotation. From d3404654f4b02a2ee8331de7e94c615b71089b3d Mon Sep 17 00:00:00 2001 From: Eniko Dif Date: Thu, 26 Nov 2026 16:26:18 +0100 Subject: [PATCH 2/2] Keep SSA apply-failure test coverage and document reconcile-time allow-list enforcement The wrt-apply-failure envtest case regressed into testing the new validation path: FakeResource was not in the test ALLOWED_KINDS set, so the WRT was rejected at reconcile time and the real SSA apply-failure branch in execplan.go lost its only test. Add FakeResource to the test allow list and restore the original case comment; the validation path stays covered by wrt-rejected-kind (Deployment). Also: gofmt reconciler_events_test.go; move testAllowedKinds above createTestWRT's doc comment and reuse createTestWRT in the AllowedKindsRejection planner test; and note in docs/worker-resource-templates.md and the Helm manager.yaml comment that the controller enforces the allowed-kinds list at reconcile time, not only the webhook. --- docs/worker-resource-templates.md | 6 +++--- .../templates/manager.yaml | 3 +++ internal/planner/planner_test.go | 21 +++---------------- tests/integration/helpers.go | 4 +++- tests/integration/wrt.go | 6 +++--- 5 files changed, 15 insertions(+), 25 deletions(-) diff --git a/docs/worker-resource-templates.md b/docs/worker-resource-templates.md index 6df97f41b..c76bd54c9 100644 --- a/docs/worker-resource-templates.md +++ b/docs/worker-resource-templates.md @@ -13,7 +13,7 @@ This is also the recommended mechanism for metric-based or backlog-based autosca ## How it works 1. You create a `WorkerResourceTemplate` that references a `WorkerDeployment` and contains the resource spec in `spec.template`. -2. The validating webhook checks that you have permission to manage that resource type yourself (SubjectAccessReview), and that the resource kind is on the allowed list (see below). +2. The validating webhook checks that you have permission to manage that resource type yourself (SubjectAccessReview), and that the resource kind is on the allowed list (see below). The controller also replays the allowed-kinds check on each reconcile, so an out-of-list kind is rejected before anything is applied even in deployments that do not run the webhook. 3. On each reconcile loop, the controller renders one copy of `spec.template` per worker version with a running Deployment, injects fields (see below), and applies it via Server-Side Apply. If you set `spec.versionStatuses`, only versions with a listed status get a copy (see [Selecting versions by status](#selecting-versions-by-status)). 4. Each per-version copy is deleted by the controller when its corresponding Kubernetes Deployment is deleted per the sunset policy, or when its version changes to a status that `spec.versionStatuses` does not list. 5. `WorkerResourceTemplate.status.versions` is updated with the applied/failed status for each version. @@ -159,7 +159,7 @@ Use `kubectl get ` after a reconcile to see the created resources and thei ## Allowed resource kinds and RBAC -`workerResourceTemplate.allowedResources` in Helm values serves two purposes at once: it defines which resource kinds the webhook will accept, and it drives the RBAC rules granted to the controller's `ClusterRole`. Only kinds listed here can be embedded in a `WorkerResourceTemplate`. +`workerResourceTemplate.allowedResources` in Helm values serves two purposes at once: it defines which resource kinds the webhook will accept, and it drives the RBAC rules granted to the controller's `ClusterRole`. Only kinds listed here can be embedded in a `WorkerResourceTemplate`. The controller also enforces the same list at reconcile time, so the restriction holds even in deployments without the webhook. The default allows HPAs: @@ -185,7 +185,7 @@ workerResourceTemplate: ``` Each entry has three fields: -- `kinds` — kind names the webhook accepts (case-insensitive) +- `kinds` — kind names the webhook accepts (case-insensitive); the controller enforces the same list at reconcile time, before any resource is applied - `apiGroups` — API groups used to generate the controller's RBAC rules - `resources` — resource names used to generate the controller's RBAC rules diff --git a/helm/temporal-worker-controller/templates/manager.yaml b/helm/temporal-worker-controller/templates/manager.yaml index 98fc1ea15..0ecb01324 100644 --- a/helm/temporal-worker-controller/templates/manager.yaml +++ b/helm/temporal-worker-controller/templates/manager.yaml @@ -95,6 +95,9 @@ spec: # WorkerResourceTemplate validating webhook. Derived from # workerResourceTemplate.allowedResources[*].kinds in values.yaml. # An empty value rejects all kinds — at least one must be configured. + # The controller also enforces this list at reconcile time, before any + # rendered resource is applied, so the restriction holds in deployments + # that do not run the webhook. {{- $allKinds := list -}} {{- range .Values.workerResourceTemplate.allowedResources -}} {{- range .kinds -}} diff --git a/internal/planner/planner_test.go b/internal/planner/planner_test.go index b30548d99..28bf65ce5 100644 --- a/internal/planner/planner_test.go +++ b/internal/planner/planner_test.go @@ -4102,12 +4102,12 @@ func TestGetWorkerResourceApplies_ApplyContents(t *testing.T) { assert.Equal(t, k8s.ComputeWorkerResourceTemplateName("my-worker", "my-hpa", "build-abc"), apply.Resource.GetName()) } -// createTestWRT builds a minimal valid WorkerResourceTemplate for use in tests. -// The embedded object is a stub HPA with scaleTargetRef opted in for auto-injection. // testAllowedKinds mirrors the ALLOWED_KINDS list the Helm chart injects by default; // it covers every kind the planner tests render. var testAllowedKinds = []string{"HorizontalPodAutoscaler", "PodDisruptionBudget"} +// createTestWRT builds a minimal valid WorkerResourceTemplate for use in tests. +// The embedded object is a stub HPA with scaleTargetRef opted in for auto-injection. func createTestWRT(name, workerDeploymentRefName string) temporaliov1alpha1.WorkerResourceTemplate { hpaSpec := map[string]interface{}{ "apiVersion": "autoscaling/v2", @@ -5826,22 +5826,7 @@ func TestGetUpdateDeployments_DeploymentLabelsReconcile(t *testing.T) { // a WRT whose kind is outside the allow list yields a WorkerResourceApply with // RenderError set and Resource nil (surfaced as an applyError, never applied). func TestGetWorkerResourceApplies_AllowedKindsRejection(t *testing.T) { - raw, _ := json.Marshal(map[string]interface{}{ - "apiVersion": "autoscaling/v2", - "kind": "HorizontalPodAutoscaler", - "spec": map[string]interface{}{ - "scaleTargetRef": map[string]interface{}{}, - "minReplicas": float64(1), - "maxReplicas": float64(5), - }, - }) - wrt := temporaliov1alpha1.WorkerResourceTemplate{ - ObjectMeta: metav1.ObjectMeta{Name: "my-hpa", Namespace: "default"}, - Spec: temporaliov1alpha1.WorkerResourceTemplateSpec{ - WorkerDeploymentRef: &temporaliov1alpha1.WorkerDeploymentReference{Name: "my-worker"}, - Template: runtime.RawExtension{Raw: raw}, - }, - } + wrt := createTestWRT("my-hpa", "my-worker") k8sState := &k8s.DeploymentState{ Deployments: map[string]*appsv1.Deployment{ "build-a": createDeploymentWithUID("worker-build-a", "uid-a"), diff --git a/tests/integration/helpers.go b/tests/integration/helpers.go index 1458813b2..15f250c16 100644 --- a/tests/integration/helpers.go +++ b/tests/integration/helpers.go @@ -215,7 +215,9 @@ func setupTestEnvironment(t *testing.T) (*rest.Config, client.Client, manager.Ma // Set the WRT allow list the same way the Helm chart injects it, so the reconciler's // replay of the webhook's spec validation does not deny-all the WRTs these tests create. - t.Setenv("ALLOWED_KINDS", "HorizontalPodAutoscaler,PodDisruptionBudget") + // FakeResource is allowed too, so the wrt-apply-failure case still exercises the real + // SSA apply-failure branch at the API server rather than failing at validation. + t.Setenv("ALLOWED_KINDS", "HorizontalPodAutoscaler,PodDisruptionBudget,FakeResource") // Setup kubebuilder assets for IDE testing if err := setupKubebuilderAssets(); err != nil { diff --git a/tests/integration/wrt.go b/tests/integration/wrt.go index 6b227be86..9514ed86c 100644 --- a/tests/integration/wrt.go +++ b/tests/integration/wrt.go @@ -432,9 +432,9 @@ func wrtTestCases() []testCase { }, // Apply failure → status entry with non-empty Message and LastAppliedGeneration == 0. - // Uses an unknown GVK whose kind is outside the ALLOWED_KINDS list, so the - // controller's reconcile-time spec validation rejects it before the SSA apply and the - // WRT status must reflect the failure for that Build ID. + // Uses an unknown GVK that the API server cannot recognise (FakeResource is in the + // test ALLOWED_KINDS list, so it passes reconcile-time validation). The controller's + // SSA apply fails and the WRT status must reflect the failure for that Build ID. { name: "wrt-apply-failure", builder: testhelpers.NewTestCase().