Skip to content

Commit

Permalink
Adding CEL validation for permission claims on bindings and exports
Browse files Browse the repository at this point in the history
* Validate that empty group means only internal types that are valid
* Validate that if a group is set, that an identityHash must also be
  set.
  • Loading branch information
Shawn Hurley committed Jul 15, 2022
1 parent 0b9bb45 commit aed23f7
Show file tree
Hide file tree
Showing 6 changed files with 247 additions and 0 deletions.
6 changes: 6 additions & 0 deletions config/crds/apis.kcp.dev_apibindings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ spec:
required:
- resource
type: object
x-kubernetes-validations:
- message: if claim for core group must only be one of configmaps,
namespaes, secrets, serviceaccounts' or if group is specified,
must have an identityHash
rule: |
(((has(self.group) && self.group == '') || !(has(self.group))) && self.resource in ['configmaps', 'namespaces', 'secrets', 'serviceaccounts']) || ((has(self.group) && self.group != '') && (has(self.identityHash) && self.identityHash != ''))
type: array
reference:
description: reference uniquely identifies an API to bind to.
Expand Down
6 changes: 6 additions & 0 deletions config/crds/apis.kcp.dev_apibindings.yaml-patch
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@
path: /spec/versions/name=v1alpha1/schema/openAPIV3Schema/properties/spec/properties/reference/properties/workspace/oneOf
value:
- required: ["path"]
- op: add
path: /spec/versions/name=v1alpha1/schema/openAPIV3Schema/properties/spec/properties/acceptedPermissionClaims/items/x-kubernetes-validations
value:
- rule: |
(((has(self.group) && self.group == '') || !(has(self.group))) && self.resource in ['configmaps', 'namespaces', 'secrets', 'serviceaccounts']) || ((has(self.group) && self.group != '') && (has(self.identityHash) && self.identityHash != ''))
message: "if claim for core group must only be one of configmaps, namespaes, secrets, serviceaccounts' or if group is specified, must have an identityHash"
6 changes: 6 additions & 0 deletions config/crds/apis.kcp.dev_apiexports.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ spec:
required:
- resource
type: object
x-kubernetes-validations:
- message: if claim for core group must only be one of configmaps,
namespaes, secrets, serviceaccounts' or if group is specified,
must have an identityHash
rule: |
(((has(self.group) && self.group == '') || !(has(self.group))) && self.resource in ['configmaps', 'namespaces', 'secrets', 'serviceaccounts']) || ((has(self.group) && self.group != '') && (has(self.identityHash) && self.identityHash != ''))
type: array
x-kubernetes-list-map-keys:
- group
Expand Down
6 changes: 6 additions & 0 deletions config/crds/apis.kcp.dev_apiexports.yaml-patch
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@
- op: add
path: /spec/versions/name=v1alpha1/schema/openAPIV3Schema/properties/spec/properties/permissionClaims/items/properties/group/default
value: ""
- op: add
path: /spec/versions/name=v1alpha1/schema/openAPIV3Schema/properties/spec/properties/permissionClaims/items/x-kubernetes-validations
value:
- rule: |
(((has(self.group) && self.group == '') || !(has(self.group))) && self.resource in ['configmaps', 'namespaces', 'secrets', 'serviceaccounts']) || ((has(self.group) && self.group != '') && (has(self.identityHash) && self.identityHash != ''))
message: "if claim for core group must only be one of configmaps, namespaes, secrets, serviceaccounts' or if group is specified, must have an identityHash"
100 changes: 100 additions & 0 deletions test/e2e/apibinding/apibinding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"path"
"reflect"
"sort"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -304,3 +305,102 @@ func apiexportVWConfig(t *testing.T, kubeconfig clientcmdapi.Config, clusterName

return rest.AddUserAgent(rest.CopyConfig(config), t.Name())
}

// TestAPIBindingPermissionClaimCELValidation will validate the permission claims for an otherwise valid APIBinding.
func TestAPIBindingPermissionClaimCELValidation(t *testing.T) {
testCases := []struct {
name string
claim apisv1alpha1.PermissionClaim
validBinding bool
}{
{
name: "valid",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "",
Resource: "configmaps",
},
},
validBinding: true,
},
{
name: "invalid core resource",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "",
Resource: "fakeresources",
},
},
validBinding: false,
},
{
name: "invalid non core resource",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "new.core.resources",
Resource: "fakeresources",
},
},
validBinding: false,
},
{
name: "valid non core resource",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "new.core.resources",
Resource: "fakeresources",
},
IdentityHash: "fakehashhere",
},
validBinding: true,
},
}

ctx, cancel := context.WithCancel(context.Background())
server := framework.SharedKcpServer(t)
orgClusterName := framework.NewOrganizationFixture(t, server)
serviceProvider1Workspace := framework.NewWorkspaceFixture(t, server, orgClusterName)

t.Cleanup(cancel)

cfg := server.DefaultConfig(t)

kcpClients, err := clientset.NewClusterForConfig(cfg)
require.NoError(t, err, "failed to construct kcp cluster client for server")

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
consumer1Workspace := framework.NewWorkspaceFixture(t, server, orgClusterName)

// create API Bindings here
binding := apisv1alpha1.APIBinding{
ObjectMeta: metav1.ObjectMeta{
Name: strings.ToLower(strings.Join(strings.Split(tc.name, " "), "-")),
},
Spec: apisv1alpha1.APIBindingSpec{
Reference: apisv1alpha1.ExportReference{
Workspace: &apisv1alpha1.WorkspaceExportReference{
Path: serviceProvider1Workspace.String(),
ExportName: "wild.west",
},
},
AcceptedPermissionClaims: []apisv1alpha1.PermissionClaim{
tc.claim,
},
},
}

t.Logf("creating binding - %#v", binding.Spec)
_, err := kcpClients.Cluster(consumer1Workspace).ApisV1alpha1().APIBindings().Create(ctx, &binding, metav1.CreateOptions{})
if err != nil && !tc.validBinding {
t.Logf("invalid binding did get an error")
return
}
if tc.validBinding && err == nil {
t.Logf("valid binding created successfully")
return
}
t.Errorf("test case expected: %v but instead got %v", tc.validBinding, err)
})
}
}
123 changes: 123 additions & 0 deletions test/e2e/apiexport/apiexport_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
Copyright 2022 The KCP 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 apiexport

import (
"context"
"strings"
"testing"

"github.com/stretchr/testify/require"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

apisv1alpha1 "github.com/kcp-dev/kcp/pkg/apis/apis/v1alpha1"
clientset "github.com/kcp-dev/kcp/pkg/client/clientset/versioned"
"github.com/kcp-dev/kcp/test/e2e/framework"
)

// TestAPIExportCELValidation will test the validation the permission claims for an otherwise valid APIExport.
func TestAPIExportCELValidation(t *testing.T) {

testCases := []struct {
name string
claim apisv1alpha1.PermissionClaim
validExport bool
}{
{
name: "valid",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "",
Resource: "configmaps",
},
},
validExport: true,
},
{
name: "invalid core resource",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "",
Resource: "fakeresources",
},
},
validExport: false,
},
{
name: "invalid non core resource",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "new.core.resources",
Resource: "fakeresources",
},
},
validExport: false,
},
{
name: "valid non core resource",
claim: apisv1alpha1.PermissionClaim{
GroupResource: apisv1alpha1.GroupResource{
Group: "new.core.resources",
Resource: "fakeresources",
},
IdentityHash: "fakehashhere",
},
validExport: true,
},
}

ctx, cancel := context.WithCancel(context.Background())
server := framework.SharedKcpServer(t)
orgClusterName := framework.NewOrganizationFixture(t, server)

t.Cleanup(cancel)

cfg := server.DefaultConfig(t)

kcpClients, err := clientset.NewClusterForConfig(cfg)
require.NoError(t, err, "failed to construct kcp cluster client for server")

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
providerWorkspace := framework.NewWorkspaceFixture(t, server, orgClusterName)

// create API Bindings here
export := apisv1alpha1.APIExport{
ObjectMeta: metav1.ObjectMeta{
Name: strings.ToLower(strings.Join(strings.Split(tc.name, " "), "-")),
},
Spec: apisv1alpha1.APIExportSpec{
PermissionClaims: []apisv1alpha1.PermissionClaim{
tc.claim,
},
},
}

_, err := kcpClients.Cluster(providerWorkspace).ApisV1alpha1().APIExports().Create(ctx, &export, metav1.CreateOptions{})
if err != nil && !tc.validExport {
t.Logf("invalid binding did get an error")
return
}
if tc.validExport && err == nil {
t.Logf("valid binding created successfully")
return
}
t.Errorf("test case expected: %v but instead got %v", tc.validExport, err)
})
}
}

0 comments on commit aed23f7

Please sign in to comment.