Skip to content
Draft
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
41 changes: 35 additions & 6 deletions api/v1alpha1/workerresourcetemplate_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, ",") {
Expand All @@ -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.
Expand Down
44 changes: 44 additions & 0 deletions api/v1alpha1/workerresourcetemplate_webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
}
1 change: 1 addition & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
6 changes: 3 additions & 3 deletions docs/worker-resource-templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -159,7 +159,7 @@ Use `kubectl get <kind>` 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:

Expand All @@ -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

Expand Down
3 changes: 3 additions & 0 deletions helm/temporal-worker-controller/templates/manager.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 -}}
Expand Down
2 changes: 1 addition & 1 deletion internal/controller/execplan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions internal/controller/genplan.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions internal/controller/reconciler_events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
13 changes: 13 additions & 0 deletions internal/k8s/workerresourcetemplates.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
63 changes: 59 additions & 4 deletions internal/k8s/workerresourcetemplates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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{})
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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{})
Expand Down Expand Up @@ -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())
}
8 changes: 8 additions & 0 deletions internal/planner/planner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -276,6 +283,7 @@ func getWorkerResourceApplies(
buildID,
temporalNamespace,
stripTemporalMetricLabelPrefix,
allowedKinds,
)
if renderErr != nil {
l.Error(renderErr, "failed to render WorkerResourceTemplate",
Expand Down
Loading
Loading