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
6 changes: 6 additions & 0 deletions pkg/admissionpolicymanager/azconfigs.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ func DefaultPolicyGeneratorConfigsForAzure(annotationBasedPlacementEnabled bool)
ReservedNamespacePrefixes: []string{utils.FleetNSNamePrefix, utils.KubeNSNamePrefix},
WhitelistedUsernames: []string{aksSupportUser},
},
EndpointSliceExportsVAPGeneratorConfig: &EndpointSliceExportsValidatingAdmissionPolicyGenerator{
MemberNamespacePrefix: utils.FleetMemberNamespacePrefix,
},
AnnotatedForPlacementObjectsVAPGeneratorConfig: &AnnotatedForPlacementObjectsValidatingAdmissionPolicyGenerator{
ReservedNamespacePrefixes: []string{utils.FleetNSNamePrefix, utils.KubeNSNamePrefix},
},
Expand All @@ -43,5 +46,8 @@ func DefaultPolicyGeneratorConfigsForAzure(annotationBasedPlacementEnabled bool)
ReservedNamespacePrefixes: []string{utils.FleetNSNamePrefix, utils.KubeNSNamePrefix},
WhitelistedUsernames: []string{aksSupportUser},
},
EndpointSliceExportsVAPGeneratorConfig: &EndpointSliceExportsValidatingAdmissionPolicyGenerator{
MemberNamespacePrefix: utils.FleetMemberNamespacePrefix,
},
}
}
7 changes: 7 additions & 0 deletions pkg/admissionpolicymanager/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
type PolicyGeneratorConfigs struct {
PodsAndReplicaSetsVAPGeneratorConfig *PodsAndReplicaSetsValidatingAdmissionPolicyGenerator `json:"denyPodsAndReplicaSetsOutsideReservedNamespaces,omitempty"`
SvcAccountsAndTokenRequestsVAPGeneratorConfig *ServiceAccountsAndTokenRequestsValidatingAdmissionPolicyGenerator `json:"denyServiceAccountsAndTokenRequestsInReservedNamespaces,omitempty"`
EndpointSliceExportsVAPGeneratorConfig *EndpointSliceExportsValidatingAdmissionPolicyGenerator `json:"denyEndpointSliceExportsOutsideMemberNamespaces,omitempty"`
// The generator is not enabled in any of the default configurations and must be enabled explicitly. It should
// only be enabled if the workload controllers of kube-controller-manager have been disabled in the hub cluster;
// see AnnotatedForPlacementObjectsValidatingAdmissionPolicyGenerator for more information.
Expand All @@ -49,6 +50,9 @@ var DefaultPolicyGeneratorConfigsForV0APIs = &PolicyGeneratorConfigs{
ReservedNamespacePrefixes: []string{utils.FleetNSNamePrefix, utils.KubeNSNamePrefix},
WhitelistedUsernames: []string{aksSupportUser},
},
EndpointSliceExportsVAPGeneratorConfig: &EndpointSliceExportsValidatingAdmissionPolicyGenerator{
MemberNamespacePrefix: utils.FleetMemberNamespacePrefix,
},
}

// DefaultPolicyGeneratorConfigsForV1APIs is the default configuration of admission policy generators
Expand All @@ -63,6 +67,9 @@ var DefaultPolicyGeneratorConfigsForV1APIs = &PolicyGeneratorConfigs{
ReservedNamespacePrefixes: []string{utils.FleetNSNamePrefix, utils.KubeNSNamePrefix},
WhitelistedUsernames: []string{aksSupportUser},
},
EndpointSliceExportsVAPGeneratorConfig: &EndpointSliceExportsValidatingAdmissionPolicyGenerator{
MemberNamespacePrefix: utils.FleetMemberNamespacePrefix,
},
}

// Validate validates each generator configuration in the given PolicyGeneratorConfigs.
Expand Down
127 changes: 127 additions & 0 deletions pkg/admissionpolicymanager/endpointsliceexports.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
Copyright 2026 The KubeFleet Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package admissionpolicymanager

import (
"fmt"

admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"

placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1"
"go.goms.io/fleet/pkg/utils/errors"
)

const (
EndpointSliceExportsVAPGeneratorName = "DenyEndpointSliceExportsOutsideMemberNamespaces"
)

const (
endpointSliceExportsVAPPolicyName = "deny-endpointsliceexports-outside-member-namespaces"
endpointSliceExportsVAPPolicyBindingName = "deny-endpointsliceexports-outside-member-namespaces-binding"
endpointSliceExportsAPIGroup = "networking.fleet.azure.com"
endpointSliceExportsAPIVersion = "v1alpha1"
endpointSliceExportsResourceName = "endpointsliceexports"
endpointSliceExportsDenialMessage = "creating or updating EndpointSliceExport resources outside fleet member namespaces is disallowed"
)

var _ ValidatingAdmissionPolicyGenerator = &EndpointSliceExportsValidatingAdmissionPolicyGenerator{}

// EndpointSliceExportsValidatingAdmissionPolicyGenerator constrains namespace placement; caller authorization
// within Fleet-owned member namespaces remains the responsibility of Kubernetes RBAC and existing guardrails.
type EndpointSliceExportsValidatingAdmissionPolicyGenerator struct {
MemberNamespacePrefix string
}

func (g *EndpointSliceExportsValidatingAdmissionPolicyGenerator) Name() string {
return EndpointSliceExportsVAPGeneratorName
}

func (g *EndpointSliceExportsValidatingAdmissionPolicyGenerator) Validate() error {
if g.MemberNamespacePrefix == "" {
return errors.NewUserError(nil, "member namespace prefix must be specified")
}
if !reservedNamespacePrefixRegexp.MatchString(g.MemberNamespacePrefix) {
return errors.NewUserError(nil, "prefix contains illegal characters; only lowercase alphanumeric characters and hyphens are allowed", "prefix", g.MemberNamespacePrefix)
}
return nil
}

func (g *EndpointSliceExportsValidatingAdmissionPolicyGenerator) PoliciesWithBindings() ([]PolicyWithBindings, error) {
isInMemberNamespace, err := RawCELExpr(fmt.Sprintf(
`request.namespace.startsWith("%s") && has(namespaceObject.metadata.labels) && "%s" in namespaceObject.metadata.labels && namespaceObject.metadata.labels["%s"] == "true"`,
g.MemberNamespacePrefix,
placementv1beta1.FleetResourceLabelKey,
placementv1beta1.FleetResourceLabelKey,
)).Build()
if err != nil {
return nil, errors.Wraps(err, "failed to build CEL expression")
}

policy := &admissionregistrationv1.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: endpointSliceExportsVAPPolicyName,
},
Spec: admissionregistrationv1.ValidatingAdmissionPolicySpec{
FailurePolicy: ptr.To(admissionregistrationv1.Fail),
MatchConstraints: &admissionregistrationv1.MatchResources{
ResourceRules: []admissionregistrationv1.NamedRuleWithOperations{
{
RuleWithOperations: admissionregistrationv1.RuleWithOperations{
Operations: []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{endpointSliceExportsAPIGroup},
APIVersions: []string{endpointSliceExportsAPIVersion},
Resources: []string{endpointSliceExportsResourceName},
},
},
},
},
},
Validations: []admissionregistrationv1.Validation{
{
Expression: isInMemberNamespace,
Message: endpointSliceExportsDenialMessage,
Reason: ptr.To(metav1.StatusReasonForbidden),
},
},
},
}

binding := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: endpointSliceExportsVAPPolicyBindingName,
},
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: endpointSliceExportsVAPPolicyName,
ValidationActions: []admissionregistrationv1.ValidationAction{
admissionregistrationv1.Deny,
},
},
}

return []PolicyWithBindings{
{
Policy: policy,
Bindings: []*admissionregistrationv1.ValidatingAdmissionPolicyBinding{binding},
},
}, nil
}
105 changes: 105 additions & 0 deletions pkg/admissionpolicymanager/endpointsliceexports_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
Copyright 2026 The KubeFleet Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package admissionpolicymanager

import (
"fmt"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"

placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1"
"go.goms.io/fleet/pkg/utils"
)

var endpointSliceExportGVK = schema.GroupVersionKind{
Group: endpointSliceExportsAPIGroup,
Version: endpointSliceExportsAPIVersion,
Kind: "EndpointSliceExport",
}

func newEndpointSliceExport(namespace, name string) *unstructured.Unstructured {
obj := &unstructured.Unstructured{
Object: map[string]any{
"apiVersion": endpointSliceExportGVK.GroupVersion().String(),
"kind": endpointSliceExportGVK.Kind,
"metadata": map[string]any{
"namespace": namespace,
"name": name,
},
"spec": map[string]any{},
},
}
obj.SetGroupVersionKind(endpointSliceExportGVK)
return obj
}

var _ = Describe("deny EndpointSliceExport resources outside member namespaces", Ordered, func() {
suffix := utils.RandStr()
ordinaryNamespace := fmt.Sprintf("work-%s", suffix)
memberNamespace := fmt.Sprintf("%s%s", utils.FleetMemberNamespacePrefix, suffix)
forgedMemberNamespace := fmt.Sprintf("%sforged-%s", utils.FleetMemberNamespacePrefix, suffix)

BeforeAll(func() {
createNamespace(ordinaryNamespace)
createNamespace(forgedMemberNamespace)
Expect(hubUncachedClient.Create(ctx, &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: memberNamespace,
Labels: map[string]string{
placementv1beta1.FleetResourceLabelKey: "true",
},
},
})).To(Succeed())

By("waiting for the EndpointSliceExport admission policy to take effect")
waitUntilPolicyIsEnforced(func() error {
return hubUncachedClient.Create(ctx, newEndpointSliceExport(ordinaryNamespace, fmt.Sprintf("probe-%s", utils.RandStr())))
}, endpointSliceExportsVAPPolicyName, endpointSliceExportsDenialMessage)
})

It("should deny creating an EndpointSliceExport in an ordinary namespace", func() {
err := hubUncachedClient.Create(ctx, newEndpointSliceExport(ordinaryNamespace, fmt.Sprintf("export-%s", utils.RandStr())))
Expect(wantDeniedByPolicy(err, endpointSliceExportsVAPPolicyName, endpointSliceExportsDenialMessage)).To(Succeed())
})

It("should deny a fleet-member-prefixed namespace without the Fleet ownership label", func() {
err := hubUncachedClient.Create(ctx, newEndpointSliceExport(forgedMemberNamespace, fmt.Sprintf("export-%s", utils.RandStr())))
Expect(wantDeniedByPolicy(err, endpointSliceExportsVAPPolicyName, endpointSliceExportsDenialMessage)).To(Succeed())
})

It("should allow creating and updating an EndpointSliceExport in a member namespace", func() {
export := newEndpointSliceExport(memberNamespace, fmt.Sprintf("export-%s", utils.RandStr()))
Expect(hubUncachedClient.Create(ctx, export)).To(Succeed())

export.SetLabels(map[string]string{"test": "updated"})
Expect(hubUncachedClient.Update(ctx, export)).To(Succeed())
})

It("should use a fail-closed policy", func() {
var policy admissionregistrationv1.ValidatingAdmissionPolicy
Expect(hubUncachedClient.Get(ctx, types.NamespacedName{Name: endpointSliceExportsVAPPolicyName}, &policy)).To(Succeed())
Expect(policy.Spec.FailurePolicy).ToNot(BeNil())
Expect(*policy.Spec.FailurePolicy).To(Equal(admissionregistrationv1.Fail))
})
})
114 changes: 114 additions & 0 deletions pkg/admissionpolicymanager/endpointsliceexports_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
Copyright 2026 The KubeFleet Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package admissionpolicymanager

import (
"testing"

admissionregistrationv1 "k8s.io/api/admissionregistration/v1"

"go.goms.io/fleet/pkg/utils"
)

func TestEndpointSliceExportsPoliciesWithBindings(t *testing.T) {
generator := &EndpointSliceExportsValidatingAdmissionPolicyGenerator{
MemberNamespacePrefix: utils.FleetMemberNamespacePrefix,
}
if err := generator.Validate(); err != nil {
t.Fatalf("Validate() = %v, want no error", err)
}

policiesWithBindings, err := generator.PoliciesWithBindings()
if err != nil {
t.Fatalf("PoliciesWithBindings() = %v, want no error", err)
}
if len(policiesWithBindings) != 1 {
t.Fatalf("PoliciesWithBindings() returned %d policies, want 1", len(policiesWithBindings))
}

policyWithBindings := policiesWithBindings[0]
policy := policyWithBindings.Policy
if policy.Name != endpointSliceExportsVAPPolicyName {
t.Errorf("policy name = %q, want %q", policy.Name, endpointSliceExportsVAPPolicyName)
}
if policy.Spec.FailurePolicy == nil || *policy.Spec.FailurePolicy != admissionregistrationv1.Fail {
t.Errorf("failure policy = %v, want Fail", policy.Spec.FailurePolicy)
}
if policy.Spec.MatchConstraints == nil || len(policy.Spec.MatchConstraints.ResourceRules) != 1 {
t.Fatalf("resource rules = %v, want exactly one", policy.Spec.MatchConstraints)
}

rule := policy.Spec.MatchConstraints.ResourceRules[0].RuleWithOperations
if len(rule.Operations) != 2 || rule.Operations[0] != admissionregistrationv1.Create || rule.Operations[1] != admissionregistrationv1.Update {
t.Errorf("operations = %v, want [CREATE UPDATE]", rule.Operations)
}
if len(rule.APIGroups) != 1 || rule.APIGroups[0] != endpointSliceExportsAPIGroup {
t.Errorf("API groups = %v, want [%s]", rule.APIGroups, endpointSliceExportsAPIGroup)
}
if len(rule.APIVersions) != 1 || rule.APIVersions[0] != endpointSliceExportsAPIVersion {
t.Errorf("API versions = %v, want [%s]", rule.APIVersions, endpointSliceExportsAPIVersion)
}
if len(rule.Resources) != 1 || rule.Resources[0] != endpointSliceExportsResourceName {
t.Errorf("resources = %v, want [%s]", rule.Resources, endpointSliceExportsResourceName)
}

if len(policy.Spec.Validations) != 1 {
t.Fatalf("validations = %v, want exactly one", policy.Spec.Validations)
}
wantExpression := `request.namespace.startsWith("fleet-member-") && has(namespaceObject.metadata.labels) && "kubernetes-fleet.io/is-fleet-resource" in namespaceObject.metadata.labels && namespaceObject.metadata.labels["kubernetes-fleet.io/is-fleet-resource"] == "true"`
if policy.Spec.Validations[0].Expression != wantExpression {
t.Errorf("validation expression = %q, want %q", policy.Spec.Validations[0].Expression, wantExpression)
}
if policy.Spec.Validations[0].Message != endpointSliceExportsDenialMessage {
t.Errorf("validation message = %q, want %q", policy.Spec.Validations[0].Message, endpointSliceExportsDenialMessage)
}

if len(policyWithBindings.Bindings) != 1 {
t.Fatalf("bindings = %d, want 1", len(policyWithBindings.Bindings))
}
binding := policyWithBindings.Bindings[0]
if binding.Spec.PolicyName != endpointSliceExportsVAPPolicyName {
t.Errorf("binding policy name = %q, want %q", binding.Spec.PolicyName, endpointSliceExportsVAPPolicyName)
}
if len(binding.Spec.ValidationActions) != 1 || binding.Spec.ValidationActions[0] != admissionregistrationv1.Deny {
t.Errorf("validation actions = %v, want [Deny]", binding.Spec.ValidationActions)
}
}

func TestEndpointSliceExportsValidate(t *testing.T) {
testCases := map[string]struct {
prefix string
wantErr bool
}{
"valid member prefix": {prefix: utils.FleetMemberNamespacePrefix},
"empty prefix": {wantErr: true},
"invalid prefix": {prefix: `fleet-member-"`, wantErr: true},
}

for name, testCase := range testCases {
t.Run(name, func(t *testing.T) {
generator := &EndpointSliceExportsValidatingAdmissionPolicyGenerator{MemberNamespacePrefix: testCase.prefix}
err := generator.Validate()
if testCase.wantErr && err == nil {
t.Fatal("Validate() = nil, want error")
}
if !testCase.wantErr && err != nil {
t.Fatalf("Validate() = %v, want no error", err)
}
})
}
}
Loading