From 5dd9535a6cc6ea793be5db798dd9d39db148cfa6 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:41:01 -0600 Subject: [PATCH 1/2] feat: Limit physical claims to providers A physical claim names a switch port, and NSO copies it without checking any inventory, so only the provider may write one. A cell now refuses physical claims and interfaces from anyone else, and guards the detach finalizer that holds a claim until its port is detached. The policy only matches physical objects and the detach finalizer, and its lists live in the policy rather than a separate ConfigMap, so a missing or wrong list can only stop physical attachment. Key changes: - add a ValidatingAdmissionPolicy to the cell bundle - let only providers write physical claims, and only NSO interfaces - let only the realizer or break-glass remove the detach finalizer - accept boot claims only in listed provider projects - refuse every physical claim until a deployment sets the lists Co-Authored-By: Claude Opus 5.5 --- api/v1alpha/networkinterfaceclaim_types.go | 6 + config/cell/kustomization.yaml | 1 + .../physical-attachment-admission/README.md | 47 +++ .../kustomization.yaml | 5 + .../physical-attachment-policy.yaml | 120 ++++++ .../physicalattachment_test.go | 362 ++++++++++++++++++ 6 files changed, 541 insertions(+) create mode 100644 config/components/physical-attachment-admission/README.md create mode 100644 config/components/physical-attachment-admission/kustomization.yaml create mode 100644 config/components/physical-attachment-admission/physical-attachment-policy.yaml create mode 100644 internal/admissionpolicy/physicalattachment_test.go diff --git a/api/v1alpha/networkinterfaceclaim_types.go b/api/v1alpha/networkinterfaceclaim_types.go index d0a9b48d..e1f6966a 100644 --- a/api/v1alpha/networkinterfaceclaim_types.go +++ b/api/v1alpha/networkinterfaceclaim_types.go @@ -38,6 +38,12 @@ const ( NetworkInterfaceClaimReady = "Ready" ) +// NetworkInterfaceClaimDetachFinalizer holds a physical claim until the +// realizer has taken the claim's network off its switch port. Only the +// operator adds it, and only the realizer, or the operator for a claim no +// port ever carried, removes it. +const NetworkInterfaceClaimDetachFinalizer = "networking.datumapis.com/physical-detach" + const ( // NetworkInterfaceClaimReasonNetworkNotAvailableInLocation means the network // exists and has not reached this location yet, which is a different answer diff --git a/config/cell/kustomization.yaml b/config/cell/kustomization.yaml index 420f6c00..fb8207f1 100644 --- a/config/cell/kustomization.yaml +++ b/config/cell/kustomization.yaml @@ -13,3 +13,4 @@ resources: components: - ../rbac_deployment - ../components/cell-controllers + - ../components/physical-attachment-admission diff --git a/config/components/physical-attachment-admission/README.md b/config/components/physical-attachment-admission/README.md new file mode 100644 index 00000000..39d7de4e --- /dev/null +++ b/config/components/physical-attachment-admission/README.md @@ -0,0 +1,47 @@ +# Physical attachment admission + +Limits who may write a physical `NetworkInterfaceClaim` or +`NetworkInterface` in a cell, meaning one whose attachment mode is +`Physical`. The schemas already refuse an attachment point, purpose or +isolation on any other mode, and keep the mode from changing. + +- Only a listed provider may create or change a physical claim. +- A listed realizer or break-glass operator may update a physical claim, + such as to remove its finalizers, but not create one. The claim's schema + already keeps its spec from changing. +- Only the realizer, or a break-glass operator, may remove the + `networking.datumapis.com/physical-detach` finalizer. +- Only the operator may add that finalizer, or write a physical interface. +- A claim with `purpose: Boot` is accepted only in a namespace whose project, + decoded from its `meta.datumapis.com/upstream-cluster-name` label, is a + listed provider project. + +The lists are the first five variables of the policy, each a CEL list of +strings, in this order: + +| Index | Variable | Holds | +|---|---|---| +| 0 | `operators` | Usernames the operator authenticates as. Exempt from every rule. | +| 1 | `providers` | Usernames allowed to write physical claims. | +| 2 | `realizers` | Usernames of the physical realizer. | +| 3 | `breakGlassGroups` | Groups allowed to remove a stuck detach finalizer. | +| 4 | `providerProjects` | Project names whose namespaces may hold boot claims. | + +The defaults name the cell's own service account as the operator and leave +every other list empty, so every physical claim is refused until a +deployment fills them in. A deployment replaces a list with a JSON patch: + +```yaml +- op: replace + path: /spec/variables/1/expression + value: "['system:serviceaccount:example-provider:provider']" +``` + +The policy only matches physical claims and interfaces, and writes that add +or remove the detach finalizer, so a wrong list can only stop physical +attachment. Every other claim and interface is admitted as before. + +An operator in a break-glass group removes a detach finalizer only after +confirming on the switch that the port no longer carries the claim's +network. Anyone allowed to impersonate a listed username or group holds +the same power. diff --git a/config/components/physical-attachment-admission/kustomization.yaml b/config/components/physical-attachment-admission/kustomization.yaml new file mode 100644 index 00000000..f7a98152 --- /dev/null +++ b/config/components/physical-attachment-admission/kustomization.yaml @@ -0,0 +1,5 @@ +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component + +resources: + - physical-attachment-policy.yaml diff --git a/config/components/physical-attachment-admission/physical-attachment-policy.yaml b/config/components/physical-attachment-admission/physical-attachment-policy.yaml new file mode 100644 index 00000000..fa809a33 --- /dev/null +++ b/config/components/physical-attachment-admission/physical-attachment-policy.yaml @@ -0,0 +1,120 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: physical-attachment-writers +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: + - networking.datumapis.com + apiVersions: + - "*" + operations: + - CREATE + - UPDATE + resources: + - networkinterfaceclaims + - networkinterfaces + matchConditions: + - name: physical-or-detach + expression: >- + (has(object.spec) && has(object.spec.attachmentMode) && object.spec.attachmentMode == 'Physical') || + (has(object.metadata.finalizers) && + 'networking.datumapis.com/physical-detach' in object.metadata.finalizers) || + (request.operation == 'UPDATE' && has(oldObject.metadata.finalizers) && + 'networking.datumapis.com/physical-detach' in oldObject.metadata.finalizers) + # The first five variables are the lists a deployment sets, in this order. + # Each is a CEL list of strings. Leaving a list empty refuses whatever it + # would allow. + variables: + - name: operators + expression: >- + ['system:serviceaccount:network-services-operator-system:controller-manager'] + - name: providers + expression: "[]" + - name: realizers + expression: "[]" + - name: breakGlassGroups + expression: "[]" + - name: providerProjects + expression: "[]" + - name: isClaim + expression: request.resource.resource == 'networkinterfaceclaims' + - name: isOperator + expression: request.userInfo.username in variables.operators + - name: isProvider + expression: request.userInfo.username in variables.providers + - name: isRealizer + expression: request.userInfo.username in variables.realizers + - name: isBreakGlass + expression: >- + has(request.userInfo.groups) && + request.userInfo.groups.exists(g, g in variables.breakGlassGroups) + - name: physical + expression: >- + has(object.spec) && has(object.spec.attachmentMode) && object.spec.attachmentMode == 'Physical' + - name: detachFinalizer + expression: "'networking.datumapis.com/physical-detach'" + - name: hasDetach + expression: >- + has(object.metadata.finalizers) && variables.detachFinalizer in object.metadata.finalizers + - name: hadDetach + expression: >- + request.operation == 'UPDATE' && has(oldObject.metadata.finalizers) && + variables.detachFinalizer in oldObject.metadata.finalizers + - name: projectLabel + expression: >- + has(namespaceObject.metadata.labels) && + 'meta.datumapis.com/upstream-cluster-name' in namespaceObject.metadata.labels + ? namespaceObject.metadata.labels['meta.datumapis.com/upstream-cluster-name'].replace('_', '/') + : '' + - name: projectTrimmed + expression: >- + variables.projectLabel.startsWith('cluster-') + ? variables.projectLabel.substring(8) + : variables.projectLabel + - name: project + expression: >- + variables.projectTrimmed.startsWith('/') + ? variables.projectTrimmed.substring(1) + : variables.projectTrimmed + validations: + - expression: >- + variables.isOperator || !variables.physical || + (variables.isClaim && variables.isProvider) || + (variables.isClaim && request.operation == 'UPDATE' && (variables.isRealizer || variables.isBreakGlass)) + messageExpression: >- + variables.isClaim + ? 'physical network interface claims may only be written by a configured provider, and ' + + request.userInfo.username + ' is not one' + : 'physical network interfaces may only be written by the network services operator' + reason: Forbidden + - expression: >- + variables.isOperator || !variables.hadDetach || variables.hasDetach || + variables.isRealizer || variables.isBreakGlass + messageExpression: >- + 'only the physical realizer may remove the ' + variables.detachFinalizer + + ' finalizer, and ' + request.userInfo.username + ' is not it' + reason: Forbidden + - expression: >- + variables.isOperator || !variables.hasDetach || variables.hadDetach + messageExpression: >- + 'only the network services operator may add the ' + variables.detachFinalizer + ' finalizer' + reason: Forbidden + - expression: >- + variables.isOperator || !(has(object.spec.purpose) && object.spec.purpose == 'Boot') || + (variables.project != '' && variables.project in variables.providerProjects) + messageExpression: >- + 'a boot claim is only accepted in a provider project namespace, and namespace ' + + object.metadata.namespace + ' does not belong to one' + reason: Forbidden +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: physical-attachment-writers +spec: + policyName: physical-attachment-writers + validationActions: + - Deny diff --git a/internal/admissionpolicy/physicalattachment_test.go b/internal/admissionpolicy/physicalattachment_test.go new file mode 100644 index 00000000..c664e893 --- /dev/null +++ b/internal/admissionpolicy/physicalattachment_test.go @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +package admissionpolicy_test + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/yaml" + + k8syaml "k8s.io/apimachinery/pkg/util/yaml" + + networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha" +) + +const ( + operator = "system:serviceaccount:network-services-operator-system:controller-manager" + provider = "system:serviceaccount:fleet-system:fleet-provider" + realizer = "system:serviceaccount:physical-realizer:realizer" + compute = "system:serviceaccount:compute-system:compute" + breakGlas = "physical-attachment-break-glass" + + customerNamespace = "ns-customer-example" + providerNamespace = "ns-provider-example" + unlabelled = "ns-unlabelled" + + componentDir = "../../config/components/physical-attachment-admission" +) + +type env struct { + t *testing.T + ctx context.Context + cfg *rest.Config + admin client.Client + scheme *runtime.Scheme +} + +func startEnv(t *testing.T) *env { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("envtest assets are required") + } + + names := []string{"networkinterfaceclaims", "networkinterfaces"} + crds := make([]*apiextensionsv1.CustomResourceDefinition, 0, len(names)) + for _, name := range names { + data, err := os.ReadFile(filepath.Join("..", "..", "config", "crd", "bases", "networking.datumapis.com_"+name+".yaml")) + require.NoError(t, err) + var crd apiextensionsv1.CustomResourceDefinition + require.NoError(t, yaml.Unmarshal(data, &crd)) + crds = append(crds, &crd) + } + + testEnv := &envtest.Environment{CRDs: crds} + cfg, err := testEnv.Start() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, testEnv.Stop()) }) + + scheme := runtime.NewScheme() + require.NoError(t, clientgoscheme.AddToScheme(scheme)) + require.NoError(t, networkingv1alpha.AddToScheme(scheme)) + admin, err := client.New(cfg, client.Options{Scheme: scheme}) + require.NoError(t, err) + + e := &env{t: t, ctx: context.Background(), cfg: cfg, admin: admin, scheme: scheme} + + for name, project := range map[string]string{ + customerNamespace: "cluster-customer-example", + providerNamespace: "cluster-_provider-example", + unlabelled: "", + } { + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}} + if project != "" { + ns.Labels = map[string]string{"meta.datumapis.com/upstream-cluster-name": project} + } + require.NoError(t, admin.Create(e.ctx, ns)) + } + + require.NoError(t, admin.Create(e.ctx, &rbacv1.ClusterRoleBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "everyone-is-admin"}, + RoleRef: rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: "cluster-admin"}, + Subjects: []rbacv1.Subject{ + {Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: operator}, + {Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: provider}, + {Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: realizer}, + {Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: compute}, + {Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: "an-operator"}, + }, + })) + + e.applyComponent() + return e +} + +func (e *env) applyComponent() { + e.t.Helper() + for _, file := range []string{"physical-attachment-policy.yaml"} { + data, err := os.ReadFile(filepath.Join(componentDir, file)) + require.NoError(e.t, err) + decoder := k8syaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + obj := &unstructured.Unstructured{} + if err := decoder.Decode(&obj.Object); err != nil { + if errors.Is(err, io.EOF) { + break + } + require.NoError(e.t, err) + } + if len(obj.Object) == 0 { + continue + } + require.NoError(e.t, e.admin.Create(e.ctx, obj)) + } + } +} + +// setLists replaces the policy's list variables the way a deployment's patch +// would, by index. +func (e *env) setLists(lists map[int]string) { + e.t.Helper() + policy := &unstructured.Unstructured{} + policy.SetAPIVersion("admissionregistration.k8s.io/v1") + policy.SetKind("ValidatingAdmissionPolicy") + require.NoError(e.t, e.admin.Get(e.ctx, client.ObjectKey{Name: "physical-attachment-writers"}, policy)) + variables, found, err := unstructured.NestedSlice(policy.Object, "spec", "variables") + require.NoError(e.t, err) + require.True(e.t, found) + for index, expression := range lists { + variables[index].(map[string]any)["expression"] = expression + } + require.NoError(e.t, unstructured.SetNestedSlice(policy.Object, variables, "spec", "variables")) + require.NoError(e.t, e.admin.Update(e.ctx, policy)) +} + +func (e *env) as(user string, groups ...string) client.Client { + e.t.Helper() + cfg := rest.CopyConfig(e.cfg) + cfg.Impersonate = rest.ImpersonationConfig{UserName: user, Groups: append([]string{"system:authenticated"}, groups...)} + cl, err := client.New(cfg, client.Options{Scheme: e.scheme}) + require.NoError(e.t, err) + return cl +} + +func physicalClaim(namespace, name string) *networkingv1alpha.NetworkInterfaceClaim { + return &networkingv1alpha.NetworkInterfaceClaim{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, + Spec: networkingv1alpha.NetworkInterfaceClaimSpec{ + Network: networkingv1alpha.LocalNetworkRef{Name: "app"}, + AttachmentMode: networkingv1alpha.NetworkInterfaceAttachmentModePhysical, + AttachmentPoint: &networkingv1alpha.NetworkInterfaceAttachmentPoint{ + MACAddress: "00:00:5e:00:53:01", Switch: "rack-a1-tor-1", Port: "Ethernet1/12", + }, + }, + } +} + +func virtualClaim(namespace, name string) *networkingv1alpha.NetworkInterfaceClaim { + return &networkingv1alpha.NetworkInterfaceClaim{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, + Spec: networkingv1alpha.NetworkInterfaceClaimSpec{Network: networkingv1alpha.LocalNetworkRef{Name: "app"}}, + } +} + +// A refusal is attributed to this policy by name, so a schema rejection of the +// same request cannot pass for one. +func refusedByPolicy(err error) bool { + return err != nil && strings.Contains(err.Error(), "ValidatingAdmissionPolicy 'physical-attachment-writers'") +} + +func requireRefused(t *testing.T, err error) { + t.Helper() + require.True(t, refusedByPolicy(err), "expected the physical attachment policy to refuse, got %v", err) +} + +// The policy takes effect a moment after it is created, so the first refusal +// is waited for rather than assumed. +func (e *env) waitForPolicy() { + e.t.Helper() + intruder := e.as(compute) + require.Eventually(e.t, func() bool { + claim := physicalClaim(customerNamespace, "policy-probe") + err := intruder.Create(e.ctx, claim) + if err == nil { + _ = e.admin.Delete(e.ctx, claim) + } + return refusedByPolicy(err) + }, 30*time.Second, 200*time.Millisecond) +} + +func (e *env) configure() { + e.t.Helper() + e.waitForPolicy() + e.setLists(map[int]string{ + 1: "['" + provider + "']", + 2: "['" + realizer + "']", + 3: "['" + breakGlas + "']", + 4: "['provider-example']", + }) + probe := e.as(provider) + require.Eventually(e.t, func() bool { + claim := physicalClaim(customerNamespace, "lists-probe") + if err := probe.Create(e.ctx, claim); err != nil { + return false + } + require.NoError(e.t, e.admin.Delete(e.ctx, claim)) + return true + }, 30*time.Second, 200*time.Millisecond) +} + +func TestOnlyProvidersWritePhysicalClaims(t *testing.T) { + e := startEnv(t) + e.configure() + + require.NoError(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, "by-provider"))) + requireRefused(t, e.as(compute).Create(e.ctx, physicalClaim(customerNamespace, "by-compute"))) + requireRefused(t, e.as(realizer).Create(e.ctx, physicalClaim(customerNamespace, "by-realizer"))) + requireRefused(t, e.as("an-operator", breakGlas).Create(e.ctx, physicalClaim(customerNamespace, "by-breakglass"))) + + require.NoError(t, e.as(compute).Create(e.ctx, virtualClaim(customerNamespace, "virtual-by-compute")), + "a claim in any other mode is admitted as before") + + var claim networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, client.ObjectKey{Namespace: customerNamespace, Name: "by-provider"}, &claim)) + claim.Labels = map[string]string{"example.com/touched": "true"} + requireRefused(t, e.as(compute).Update(e.ctx, &claim)) +} + +func TestPhysicalClaimsAreRefusedUntilConfigured(t *testing.T) { + e := startEnv(t) + e.waitForPolicy() + + requireRefused(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, "before-configured"))) + require.NoError(t, e.as(operator).Create(e.ctx, physicalClaim(customerNamespace, "by-operator")), + "the operator is listed by default") +} + +// The policy matches only physical objects and the detach finalizer, so a list +// left wrong can only stop physical attachment. +func TestOtherClaimsAreLeftAlone(t *testing.T) { + e := startEnv(t) + e.waitForPolicy() + + require.NoError(t, e.as(compute).Create(e.ctx, virtualClaim(customerNamespace, "virtual"))) + + withDetach := virtualClaim(customerNamespace, "virtual-with-detach") + withDetach.Finalizers = []string{networkingv1alpha.NetworkInterfaceClaimDetachFinalizer} + requireRefused(t, e.as(compute).Create(e.ctx, withDetach)) +} + +func TestRealizerAndBreakGlassMayUpdateButNotCreate(t *testing.T) { + e := startEnv(t) + e.configure() + + require.NoError(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, "touched"))) + key := client.ObjectKey{Namespace: customerNamespace, Name: "touched"} + + for _, cl := range []client.Client{e.as(realizer), e.as("an-operator", breakGlas)} { + var claim networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, key, &claim)) + claim.Labels = map[string]string{"example.com/seen": time.Now().Format("150405.000000")} + require.NoError(t, cl.Update(e.ctx, &claim)) + } +} + +func TestOnlyTheRealizerRemovesTheDetachFinalizer(t *testing.T) { + e := startEnv(t) + e.configure() + + seed := func(name string) client.ObjectKey { + require.NoError(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, name))) + key := client.ObjectKey{Namespace: customerNamespace, Name: name} + var claim networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, key, &claim)) + claim.Finalizers = append(claim.Finalizers, networkingv1alpha.NetworkInterfaceClaimDetachFinalizer) + require.NoError(t, e.as(operator).Update(e.ctx, &claim)) + return key + } + strip := func(cl client.Client, key client.ObjectKey) error { + var claim networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, key, &claim)) + claim.Finalizers = nil + return cl.Update(e.ctx, &claim) + } + + requireRefused(t, strip(e.as(provider), seed("provider-strips"))) + requireRefused(t, strip(e.as(compute), seed("compute-strips"))) + require.NoError(t, strip(e.as(realizer), seed("realizer-strips"))) + require.NoError(t, strip(e.as("an-operator", breakGlas), seed("breakglass-strips"))) + require.NoError(t, strip(e.as(operator), seed("operator-strips"))) +} + +func TestOnlyTheOperatorAddsTheDetachFinalizer(t *testing.T) { + e := startEnv(t) + e.configure() + + withFinalizer := physicalClaim(customerNamespace, "born-with-finalizer") + withFinalizer.Finalizers = []string{networkingv1alpha.NetworkInterfaceClaimDetachFinalizer} + requireRefused(t, e.as(provider).Create(e.ctx, withFinalizer)) + + require.NoError(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, "gains-finalizer"))) + var claim networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, client.ObjectKey{Namespace: customerNamespace, Name: "gains-finalizer"}, &claim)) + claim.Finalizers = []string{networkingv1alpha.NetworkInterfaceClaimDetachFinalizer} + requireRefused(t, e.as(realizer).Update(e.ctx, &claim)) +} + +func TestBootClaimsOnlyInProviderProjects(t *testing.T) { + e := startEnv(t) + e.configure() + + boot := func(namespace, name string) *networkingv1alpha.NetworkInterfaceClaim { + claim := physicalClaim(namespace, name) + claim.Spec.Purpose = networkingv1alpha.NetworkInterfacePurposeBoot + return claim + } + + require.NoError(t, e.as(provider).Create(e.ctx, boot(providerNamespace, "boot-in-provider")), + "the label decodes to the listed project") + requireRefused(t, e.as(provider).Create(e.ctx, boot(customerNamespace, "boot-in-customer"))) + requireRefused(t, e.as(provider).Create(e.ctx, boot(unlabelled, "boot-unlabelled"))) + require.NoError(t, e.as(provider).Create(e.ctx, physicalClaim(customerNamespace, "network-in-customer"))) +} + +func TestOnlyTheOperatorWritesPhysicalInterfaces(t *testing.T) { + e := startEnv(t) + e.configure() + + iface := func(name string) *networkingv1alpha.NetworkInterface { + return &networkingv1alpha.NetworkInterface{ + ObjectMeta: metav1.ObjectMeta{Namespace: customerNamespace, Name: name}, + Spec: networkingv1alpha.NetworkInterfaceSpec{ + Network: networkingv1alpha.LocalNetworkRef{Name: "app"}, + AttachmentMode: networkingv1alpha.NetworkInterfaceAttachmentModePhysical, + AttachmentPoint: &networkingv1alpha.NetworkInterfaceAttachmentPoint{ + MACAddress: "00:00:5e:00:53:01", Switch: "rack-a1-tor-1", Port: "Ethernet1/12", + }, + }, + } + } + + require.NoError(t, e.as(operator).Create(e.ctx, iface("by-operator"))) + requireRefused(t, e.as(provider).Create(e.ctx, iface("by-provider"))) + requireRefused(t, e.as(realizer).Create(e.ctx, iface("by-realizer"))) +} From 69dcf7b57327f90e1883cfdc930deba2a04eaea0 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:51:13 -0600 Subject: [PATCH 2/2] fix: Check boot claims' project only on create Review found the boot rule ran on every update, so emptying the provider-project list would leave an existing boot claim unable to release, even through break-glass. Key changes: - check a boot claim's project only when it is created - test that a boot claim still releases after its project is unlisted - test that the operator default matches the cell's service account - document that the list order is a contract, and what a wrong realizer or break-glass list does Co-Authored-By: Claude Opus 5.5 --- .../physical-attachment-admission/README.md | 17 +++-- .../physical-attachment-policy.yaml | 8 ++- go.mod | 4 +- .../physicalattachment_test.go | 63 +++++++++++++++++++ 4 files changed, 83 insertions(+), 9 deletions(-) diff --git a/config/components/physical-attachment-admission/README.md b/config/components/physical-attachment-admission/README.md index 39d7de4e..70fcb16c 100644 --- a/config/components/physical-attachment-admission/README.md +++ b/config/components/physical-attachment-admission/README.md @@ -12,9 +12,10 @@ isolation on any other mode, and keep the mode from changing. - Only the realizer, or a break-glass operator, may remove the `networking.datumapis.com/physical-detach` finalizer. - Only the operator may add that finalizer, or write a physical interface. -- A claim with `purpose: Boot` is accepted only in a namespace whose project, +- A claim with `purpose: Boot` is created only in a namespace whose project, decoded from its `meta.datumapis.com/upstream-cluster-name` label, is a - listed provider project. + listed provider project. Later updates are not checked again, so changing + the list never strands a boot claim that already exists. The lists are the first five variables of the policy, each a CEL list of strings, in this order: @@ -38,8 +39,16 @@ deployment fills them in. A deployment replaces a list with a JSON patch: ``` The policy only matches physical claims and interfaces, and writes that add -or remove the detach finalizer, so a wrong list can only stop physical -attachment. Every other claim and interface is admitted as before. +or remove the detach finalizer, so a wrong list can only affect physical +attachment. Every other claim and interface is admitted as before. Within +physical attachment, a wrong `realizers` or `breakGlassGroups` list leaves +deleted claims waiting on their detach finalizer, with their addresses held. + +Patches name the lists by index, so the order of the first five variables is +part of this component's contract. The operator's default entry is the cell's +own service account, and a test renders `config/cell` to keep the two in +step. A deployment that renames that service account must replace variable 0 +too. An operator in a break-glass group removes a detach finalizer only after confirming on the switch that the port no longer carries the claim's diff --git a/config/components/physical-attachment-admission/physical-attachment-policy.yaml b/config/components/physical-attachment-admission/physical-attachment-policy.yaml index fa809a33..5bc57c78 100644 --- a/config/components/physical-attachment-admission/physical-attachment-policy.yaml +++ b/config/components/physical-attachment-admission/physical-attachment-policy.yaml @@ -25,8 +25,9 @@ spec: (request.operation == 'UPDATE' && has(oldObject.metadata.finalizers) && 'networking.datumapis.com/physical-detach' in oldObject.metadata.finalizers) # The first five variables are the lists a deployment sets, in this order. - # Each is a CEL list of strings. Leaving a list empty refuses whatever it - # would allow. + # Deployments patch them by index, so the order is a contract: add new + # variables after them, never between. Each is a CEL list of strings, and + # leaving a list empty refuses whatever it would allow. variables: - name: operators expression: >- @@ -103,7 +104,8 @@ spec: 'only the network services operator may add the ' + variables.detachFinalizer + ' finalizer' reason: Forbidden - expression: >- - variables.isOperator || !(has(object.spec.purpose) && object.spec.purpose == 'Boot') || + variables.isOperator || request.operation != 'CREATE' || + !(has(object.spec.purpose) && object.spec.purpose == 'Boot') || (variables.project != '' && variables.project in variables.providerProjects) messageExpression: >- 'a boot claim is only accepted in a provider project namespace, and namespace ' + diff --git a/go.mod b/go.mod index 7d1deb63..c74f960e 100644 --- a/go.mod +++ b/go.mod @@ -332,8 +332,8 @@ require ( sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 // indirect sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 // indirect sigs.k8s.io/kubectl-validate v0.0.5-0.20250915070809-d2f2d68fba09 // indirect - sigs.k8s.io/kustomize/api v0.21.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.21.1 // indirect + sigs.k8s.io/kustomize/api v0.21.1 + sigs.k8s.io/kustomize/kyaml v0.21.1 sigs.k8s.io/mcs-api v0.5.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect diff --git a/internal/admissionpolicy/physicalattachment_test.go b/internal/admissionpolicy/physicalattachment_test.go index c664e893..5a47def4 100644 --- a/internal/admissionpolicy/physicalattachment_test.go +++ b/internal/admissionpolicy/physicalattachment_test.go @@ -24,6 +24,9 @@ import ( "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/kustomize/api/krusty" + kustypes "sigs.k8s.io/kustomize/api/types" + "sigs.k8s.io/kustomize/kyaml/filesys" "sigs.k8s.io/yaml" k8syaml "k8s.io/apimachinery/pkg/util/yaml" @@ -360,3 +363,63 @@ func TestOnlyTheOperatorWritesPhysicalInterfaces(t *testing.T) { requireRefused(t, e.as(provider).Create(e.ctx, iface("by-provider"))) requireRefused(t, e.as(realizer).Create(e.ctx, iface("by-realizer"))) } + +func TestBootClaimsSurviveAProviderProjectChange(t *testing.T) { + e := startEnv(t) + e.configure() + + claim := physicalClaim(providerNamespace, "boot-then-unlisted") + claim.Spec.Purpose = networkingv1alpha.NetworkInterfacePurposeBoot + require.NoError(t, e.as(provider).Create(e.ctx, claim)) + key := client.ObjectKeyFromObject(claim) + + var stored networkingv1alpha.NetworkInterfaceClaim + require.NoError(t, e.admin.Get(e.ctx, key, &stored)) + stored.Finalizers = []string{networkingv1alpha.NetworkInterfaceClaimDetachFinalizer} + require.NoError(t, e.as(operator).Update(e.ctx, &stored)) + + e.setLists(map[int]string{4: "[]"}) + require.Eventually(t, func() bool { + probe := physicalClaim(providerNamespace, "boot-probe") + probe.Spec.Purpose = networkingv1alpha.NetworkInterfacePurposeBoot + err := e.as(provider).Create(e.ctx, probe) + if err == nil { + _ = e.admin.Delete(e.ctx, probe) + } + return refusedByPolicy(err) + }, 30*time.Second, 200*time.Millisecond) + + require.NoError(t, e.admin.Get(e.ctx, key, &stored)) + stored.Finalizers = nil + require.NoError(t, e.as(realizer).Update(e.ctx, &stored), + "an existing boot claim must still release after its project leaves the list") +} + +// The policy exempts the operator by username, and that username comes from the +// service account the cell bundle runs as. +func TestOperatorDefaultMatchesTheCellServiceAccount(t *testing.T) { + opts := krusty.MakeDefaultOptions() + opts.LoadRestrictions = kustypes.LoadRestrictionsNone + resources, err := krusty.MakeKustomizer(opts).Run(filesys.MakeFsOnDisk(), filepath.Join("..", "..", "config", "cell")) + require.NoError(t, err) + + var serviceAccount, namespace string + var operators []string + for _, resource := range resources.Resources() { + switch resource.GetKind() { + case "Deployment": + name, err := resource.GetString("spec.template.spec.serviceAccountName") + require.NoError(t, err) + serviceAccount, namespace = name, resource.GetNamespace() + case "ValidatingAdmissionPolicy": + if resource.GetName() != "physical-attachment-writers" { + continue + } + expression, err := resource.GetString("spec.variables[0].expression") + require.NoError(t, err) + operators = append(operators, expression) + } + } + require.NotEmpty(t, serviceAccount) + require.Equal(t, []string{"['system:serviceaccount:" + namespace + ":" + serviceAccount + "']"}, operators) +}