diff --git a/app/cetirun-operator/internal/admission/reconcile.go b/app/cetirun-operator/internal/admission/reconcile.go index 4520a5487..4aa546acc 100644 --- a/app/cetirun-operator/internal/admission/reconcile.go +++ b/app/cetirun-operator/internal/admission/reconcile.go @@ -223,17 +223,28 @@ func (h *PodHandler) validateReconciledPod(ctx context.Context, request admissio return reject(podReadFailure("PreviousPod", err)) } if old.UID != pod.UID || old.UID != persisted.UID || pod.ResourceVersion != persisted.ResourceVersion || - old.ResourceVersion != persisted.ResourceVersion || old.Spec.NodeName != persisted.Spec.NodeName { + old.ResourceVersion != persisted.ResourceVersion || old.Spec.NodeName != persisted.Spec.NodeName || + pod.Spec.NodeName != persisted.Spec.NodeName { return reject(podDenied("PreviousPodMismatch", "Pod update does not match its persisted identity")) } - wanted.Template.Spec.NodeName = persisted.Spec.NodeName } - if err := w.ValidateRenderedPod(pod, wanted, owner, revision); err != nil { + var validationErr error + if request.Operation == admissionv1.Update && pod.Spec.NodeName != "" { + node, failure := h.readAssignedNode(ctx, pod) + if failure != nil { + return reject(failure) + } + validationErr = w.ValidateRenderedPodOnNode(pod, node, wanted, owner, revision) + } else { + validationErr = w.ValidateRenderedPod(pod, wanted, owner, revision) + } + if validationErr != nil { message := "Pod differs from the current authorized chart template" var mismatch *w.PodMismatchError - if errors.As(err, &mismatch) { + if errors.As(validationErr, &mismatch) { message = mismatch.Error() } + return reject(podDenied("TemplateMismatch", message)) } confirmed := &corev1.ConfigMap{} @@ -252,6 +263,20 @@ func (h *PodHandler) validateReconciledPod(ctx context.Context, request admissio return admission.Allowed("Pod matches current authorized common chart output"), true } +func (h *PodHandler) readAssignedNode(ctx context.Context, pod *corev1.Pod) (*corev1.Node, *podFailure) { + if pod.Spec.NodeName == "" { + return nil, podDenied("NodeUnavailable", "the current Pod has no assigned Node") + } + node := &corev1.Node{} + if err := h.reader.Get(ctx, client.ObjectKey{Name: pod.Spec.NodeName}, node); err != nil { + return nil, podReadFailure("Node", err) + } + if node.UID == "" || !node.DeletionTimestamp.IsZero() { + return nil, podDenied("NodeUnavailable", "the assigned Node is unavailable") + } + return node, nil +} + func controllerRuntimeDefaults(agent, old *api.Agent) bool { if old == nil || agent.UID != old.UID { return false diff --git a/app/cetirun-operator/internal/admission/terminal.go b/app/cetirun-operator/internal/admission/terminal.go index c53d9628c..24a2d8c9c 100644 --- a/app/cetirun-operator/internal/admission/terminal.go +++ b/app/cetirun-operator/internal/admission/terminal.go @@ -166,8 +166,11 @@ func (h *PodHandler) validateTerminalAuthority(ctx context.Context, expected w.R return podDenied("TerminalTargetUnavailable", "terminal target Pod is not the current ready workload Pod") } wanted := expected.Workloads[index] - wanted.Template.Spec.NodeName = pod.Spec.NodeName - if err := w.ValidateRenderedPod(pod, wanted, podOwner, main.Status.UpdateRevision); err != nil { + node, failure := h.readAssignedNode(ctx, pod) + if failure != nil { + return failure + } + if err := w.ValidateRenderedPodOnNode(pod, node, wanted, podOwner, main.Status.UpdateRevision); err != nil { return podDenied("TerminalTargetUnavailable", "terminal target Pod differs from the current Sandbox template") } return nil diff --git a/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go b/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go index 1ed57562c..cf6069a77 100644 --- a/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go @@ -16,6 +16,7 @@ import ( authorizationv1 "k8s.io/api/authorization/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/rest" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" @@ -42,10 +43,35 @@ func TestCommonCustomTerminalAPIServer(t *testing.T) { } observed := *h.nativeSandboxFixture observed.kube = h.admin + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "terminal-node", + Labels: map[string]string{corev1.LabelTopologyRegion: "example-region", corev1.LabelTopologyZone: "example-zone"}}} + h.create(t, node) for _, workload := range expected.Workloads { pod := reconciledPodForTest(t, &observed, workload) pod.Spec.Overhead = nil h.create(t, pod) + if err := h.admin.SubResource("binding").Create(h.ctx, pod, &corev1.Binding{ + ObjectMeta: metav1.ObjectMeta{Name: pod.Name, Namespace: pod.Namespace, UID: pod.UID}, + Target: corev1.ObjectReference{Kind: "Node", Name: node.Name}, + }); err != nil { + t.Fatal("bind approved workload:", err) + } + if err := h.admin.Get(h.ctx, client.ObjectKeyFromObject(pod), pod); err != nil { + t.Fatal(err) + } + for _, key := range []string{corev1.LabelTopologyRegion, corev1.LabelTopologyZone} { + if pod.Labels[key] != node.Labels[key] { + t.Fatal("API-server binding did not apply observed Node topology") + } + } + if err := h.admin.Update(h.ctx, pod.DeepCopy(), client.DryRunAll); err != nil { + t.Fatal("current bound workload was rejected:", err) + } + forged := pod.DeepCopy() + forged.Labels[corev1.LabelTopologyZone] = "unapproved-zone" + if err := h.admin.Update(h.ctx, forged, client.DryRunAll); err == nil { + t.Fatal("forged bound topology was accepted") + } if workload.Kind == "Deployment" { if pod.Spec.ServiceAccountName != expected.Terminal.ServiceAccountName || (backend == api.SandboxKata) != (len(pod.Spec.Overhead) != 0) { diff --git a/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go b/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go index e0f0f1422..3d1162f88 100644 --- a/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go @@ -179,7 +179,16 @@ func TestCommonCustomTerminalConnectUsesRenderedAuthority(t *testing.T) { pod = candidate } } - pod.Spec.NodeName = "node-a" + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{ + Name: "node-a", UID: "example-node-uid", + Labels: map[string]string{corev1.LabelTopologyRegion: "example-region", corev1.LabelTopologyZone: "example-zone"}, + }} + if err := f.kube.Create(ctx, node); err != nil { + t.Fatal(err) + } + pod.Spec.NodeName = node.Name + pod.Labels[corev1.LabelTopologyRegion] = node.Labels[corev1.LabelTopologyRegion] + pod.Labels[corev1.LabelTopologyZone] = node.Labels[corev1.LabelTopologyZone] pod.Status = corev1.PodStatus{Phase: corev1.PodRunning, ContainerStatuses: []corev1.ContainerStatus{{ Name: "cetirun", Ready: true, ContainerID: "containerd://synthetic-main", State: corev1.ContainerState{Running: &corev1.ContainerStateRunning{}}, @@ -194,6 +203,24 @@ func TestCommonCustomTerminalConnectUsesRenderedAuthority(t *testing.T) { if err != nil { t.Fatal(err) } + pod.TypeMeta = metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"} + update := reconciledPodRequest(t, pod) + update.Operation = admissionv1.Update + update.OldObject = update.Object + if response := handler.Validate(ctx, update); !response.Allowed { + t.Fatal("current bound Pod update was denied:", response.Result) + } + otherNode := node.DeepCopy() + otherNode.Name, otherNode.UID, otherNode.ResourceVersion = "other-node", "other-node-uid", "" + if err := f.kube.Create(ctx, otherNode); err != nil { + t.Fatal(err) + } + moved := pod.DeepCopy() + moved.Spec.NodeName = otherNode.Name + update.Object = reconciledPodRequest(t, moved).Object + if response := handler.Validate(ctx, update); response.Allowed { + t.Fatal("Pod update reassigned a bound Pod to another observed Node") + } options, err := json.Marshal(corev1.PodExecOptions{ Container: "cetirun", Command: []string{"sh", "-i"}, Stdout: true, Stdin: true, TTY: true, }) @@ -228,6 +255,27 @@ func TestCommonCustomTerminalConnectUsesRenderedAuthority(t *testing.T) { t.Fatal("terminal authority admitted a different caller, target or protocol") } } + node.Labels[corev1.LabelTopologyZone] = "changed-zone" + if err := f.kube.Update(ctx, node); err != nil { + t.Fatal(err) + } + if response := handler.Validate(ctx, request); response.Allowed { + t.Fatal("terminal accepted topology from a stale Node observation") + } + node.Labels[corev1.LabelTopologyZone] = "example-zone" + if err := f.kube.Update(ctx, node); err != nil { + t.Fatal(err) + } + if err := f.kube.Delete(ctx, node); err != nil { + t.Fatal(err) + } + if response := handler.Validate(ctx, request); response.Allowed || !strings.Contains(response.Result.Message, "Node") { + t.Fatal("terminal did not fail closed when its assigned Node disappeared:", response.Result) + } + node.ResourceVersion = "" + if err := f.kube.Create(ctx, node); err != nil { + t.Fatal(err) + } agent := f.current(t) agent.Spec.Suspended, agent.Generation = true, agent.Generation+1 if err := f.kube.Update(ctx, agent); err != nil { diff --git a/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go b/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go index f932607d7..9f2379808 100644 --- a/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go @@ -284,6 +284,7 @@ func newNativeStartAPIHarnessWithRuntime(t *testing.T, admissionNative, coordina ControlPlaneStartTimeout: time.Minute, ControlPlaneStopTimeout: 30 * time.Second, } environment.ControlPlane.GetAPIServer().Configure().Set("authorization-mode", "RBAC") + environment.ControlPlane.GetAPIServer().Configure().Set("enable-admission-plugins", "PodTopologyLabels") cfg, err := environment.Start() if err != nil { t.Fatal(errors.Join(err, environment.Stop())) diff --git a/app/cetirun-operator/internal/sandboxworkload/finalpod.go b/app/cetirun-operator/internal/sandboxworkload/finalpod.go index f4b63e0c5..69bafa827 100644 --- a/app/cetirun-operator/internal/sandboxworkload/finalpod.go +++ b/app/cetirun-operator/internal/sandboxworkload/finalpod.go @@ -110,12 +110,21 @@ func ValidatePod(pod *corev1.Pod, expected Expectation) error { // ValidatePodOnNode permits only scheduling and topology labels verified against // the assigned Node. It does not supply independent runtime or fencing evidence. func ValidatePodOnNode(pod *corev1.Pod, node *corev1.Node, expected Expectation) error { + template, err := podTemplateOnNode(pod, node, expected.Template) + if err != nil { + return err + } + expected.Template = template + return ValidatePod(pod, expected) +} + +func podTemplateOnNode(pod *corev1.Pod, node *corev1.Node, template corev1.PodTemplateSpec) (corev1.PodTemplateSpec, error) { if pod == nil || node == nil || node.Name == "" || pod.Spec.NodeName != node.Name { - return &PodMismatchError{[]string{"spec.nodeName"}} + return corev1.PodTemplateSpec{}, &PodMismatchError{[]string{"spec.nodeName"}} } - expected.Template = *expected.Template.DeepCopy() - if expected.Template.Spec.NodeName == "" { - expected.Template.Spec.NodeName = node.Name + template = *template.DeepCopy() + if template.Spec.NodeName == "" { + template.Spec.NodeName = node.Name } for _, key := range []string{corev1.LabelTopologyRegion, corev1.LabelTopologyZone} { value, present := pod.Labels[key] @@ -124,16 +133,16 @@ func ValidatePodOnNode(pod *corev1.Pod, node *corev1.Node, expected Expectation) } current, found := node.Labels[key] if !found || value != current { - return &PodMismatchError{[]string{"metadata.labels"}} + return corev1.PodTemplateSpec{}, &PodMismatchError{[]string{"metadata.labels"}} } - if _, pinned := expected.Template.Labels[key]; !pinned { - if expected.Template.Labels == nil { - expected.Template.Labels = map[string]string{} + if _, pinned := template.Labels[key]; !pinned { + if template.Labels == nil { + template.Labels = map[string]string{} } - expected.Template.Labels[key] = current + template.Labels[key] = current } } - return ValidatePod(pod, expected) + return template, nil } func podDifferencePaths(a, b reflect.Value, path string, fields *[]string) { diff --git a/app/cetirun-operator/internal/sandboxworkload/reconcile.go b/app/cetirun-operator/internal/sandboxworkload/reconcile.go index adc701207..c14361878 100644 --- a/app/cetirun-operator/internal/sandboxworkload/reconcile.go +++ b/app/cetirun-operator/internal/sandboxworkload/reconcile.go @@ -352,6 +352,17 @@ func ReconciledObjectMatches(actual, desired *unstructured.Unstructured) bool { return true } +// ValidateRenderedPodOnNode permits only scheduling and topology additions +// verified against the assigned Node, retaining the approved template constraints. +func ValidateRenderedPodOnNode(pod *corev1.Pod, node *corev1.Node, workload RenderedWorkload, owner metav1.OwnerReference, revision string) error { + template, err := podTemplateOnNode(pod, node, workload.Template) + if err != nil { + return err + } + workload.Template = template + return ValidateRenderedPod(pod, workload, owner, revision) +} + // ValidateRenderedPod checks the current controller-approved template without // fixing helper names or permanently consuming one Pod UID. func ValidateRenderedPod(pod *corev1.Pod, workload RenderedWorkload, owner metav1.OwnerReference, revision string) error { diff --git a/app/cetirun-operator/internal/sandboxworkload/reconciled_node_test.go b/app/cetirun-operator/internal/sandboxworkload/reconciled_node_test.go new file mode 100644 index 000000000..7c071ff84 --- /dev/null +++ b/app/cetirun-operator/internal/sandboxworkload/reconciled_node_test.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sandboxworkload + +import ( + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" +) + +func TestRenderedPodOnNodeKeepsExactTemplateAuthority(t *testing.T) { + for _, kind := range []string{"StatefulSet", "Deployment"} { + t.Run(kind, func(t *testing.T) { + workload := RenderedWorkload{ + Kind: kind, Identity: ObjectIdentity{Name: "example-agent", UID: "workload-uid"}, + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"app": "approved"}}, + Spec: corev1.PodSpec{Containers: []corev1.Container{{ + Name: "cetirun", Image: "registry.example.com/agent:example", + }}}, + }, + } + owner := metav1.OwnerReference{APIVersion: "apps/v1", Kind: kind, Name: workload.Identity.Name, + UID: workload.Identity.UID, Controller: ptr.To(true), BlockOwnerDeletion: ptr.To(true)} + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "example-node", UID: "node-uid", + Labels: map[string]string{corev1.LabelTopologyRegion: "example-region", corev1.LabelTopologyZone: "example-zone"}}} + pod := &corev1.Pod{ObjectMeta: *workload.Template.ObjectMeta.DeepCopy(), Spec: *workload.Template.Spec.DeepCopy()} + pod.OwnerReferences, pod.Spec.NodeName = []metav1.OwnerReference{owner}, node.Name + pod.Labels[corev1.LabelTopologyRegion], pod.Labels[corev1.LabelTopologyZone] = "example-region", "example-zone" + if kind == "StatefulSet" { + pod.Name = workload.Identity.Name + "-0" + pod.Spec.Hostname, pod.Spec.Subdomain = pod.Name, workload.Identity.Name + pod.Labels["statefulset.kubernetes.io/pod-name"], pod.Labels["apps.kubernetes.io/pod-index"] = pod.Name, "0" + pod.Labels["controller-revision-hash"] = "current-revision" + } else { + pod.Name = "example-agent-current-revision-pod" + pod.Labels["pod-template-hash"] = "current-revision" + } + before := workload.Template.DeepCopy() + if err := ValidateRenderedPodOnNode(pod, node, workload, owner, "current-revision"); err != nil { + t.Fatal("current assigned-node topology was rejected:", err) + } + if !equality.Semantic.DeepEqual(before, &workload.Template) { + t.Fatal("node observation changed the persisted template") + } + if err := ValidateRenderedPod(pod, workload, owner, "current-revision"); err == nil { + t.Fatal("unobserved topology or placement was accepted") + } + if err := ValidateRenderedPodOnNode(pod, nil, workload, owner, "current-revision"); err == nil { + t.Fatal("missing node observation was accepted") + } + withoutLabels := pod.DeepCopy() + delete(withoutLabels.Labels, corev1.LabelTopologyRegion) + delete(withoutLabels.Labels, corev1.LabelTopologyZone) + if err := ValidateRenderedPodOnNode(withoutLabels, node, workload, owner, "current-revision"); err != nil { + t.Fatal("bound Pod without copied topology was rejected:", err) + } + for name, change := range map[string]func(*corev1.Pod, *corev1.Node, *RenderedWorkload){ + "region": func(p *corev1.Pod, _ *corev1.Node, _ *RenderedWorkload) { + p.Labels[corev1.LabelTopologyRegion] = "other" + }, + "zone": func(p *corev1.Pod, _ *corev1.Node, _ *RenderedWorkload) { p.Labels[corev1.LabelTopologyZone] = "other" }, + "unrelated label": func(p *corev1.Pod, _ *corev1.Node, _ *RenderedWorkload) { p.Labels["unapproved"] = "true" }, + "wrong node": func(_ *corev1.Pod, n *corev1.Node, _ *RenderedWorkload) { n.Name = "other-node" }, + "missing node label": func(_ *corev1.Pod, n *corev1.Node, _ *RenderedWorkload) { delete(n.Labels, corev1.LabelTopologyZone) }, + "pinned placement": func(_ *corev1.Pod, _ *corev1.Node, w *RenderedWorkload) { w.Template.Spec.NodeName = "other-node" }, + "pinned label": func(_ *corev1.Pod, _ *corev1.Node, w *RenderedWorkload) { + w.Template.Labels[corev1.LabelTopologyZone] = "pinned-zone" + }, + "image": func(p *corev1.Pod, _ *corev1.Node, _ *RenderedWorkload) { + p.Spec.Containers[0].Image = "registry.example.com/unapproved:example" + }, + } { + t.Run(name, func(t *testing.T) { + changed, observed, wanted := pod.DeepCopy(), node.DeepCopy(), workload + wanted.Template = *workload.Template.DeepCopy() + change(changed, observed, &wanted) + if err := ValidateRenderedPodOnNode(changed, observed, wanted, owner, "current-revision"); err == nil { + t.Fatal("unapproved Pod or Node change was accepted") + } + }) + } + }) + } +} diff --git a/site/content/en/docs/reference/agent-harness.md b/site/content/en/docs/reference/agent-harness.md index 753b1fd0a..57d5a09d2 100644 --- a/site/content/en/docs/reference/agent-harness.md +++ b/site/content/en/docs/reference/agent-harness.md @@ -125,6 +125,9 @@ audience override. Protected Pod admission permits only this owned terminal's current named target, main container and shell protocol; it rechecks the execution sources and non-stopping reservation. It mounts neither HOME nor model credentials. Suspension stops both workloads before acknowledging completion. +For bound workloads, admission accepts Kubernetes' copied region/zone labels only +when they match a fresh read of the assigned Node. This applies to terminal +CONNECT and ordinary Pod updates; other labels and template inputs remain exact. Custom receives an immutable, Agent-owned `AGENTS.md` snapshot and a read-only `$HOME/.agents` view. Optional Memory/shared skills compose into that view without