Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support resource sum. #463

Merged
merged 7 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
72 changes: 44 additions & 28 deletions client/rbac_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ import (
"strings"

"github.com/emicklei/go-restful/v3"
kerrors "github.com/katanomi/pkg/errors"
authnv1 "k8s.io/api/authentication/v1"
authv1 "k8s.io/api/authorization/v1"
"k8s.io/apiserver/pkg/authentication/user"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"

// metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kerrors "github.com/katanomi/pkg/errors"

"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
)
Expand Down Expand Up @@ -58,40 +59,47 @@ type SubjectAccessReviewClientGetter interface {
// DynamicSubjectReviewFilter makes a subject review and the ResourceAttribute can be dynamically obtained
func DynamicSubjectReviewFilter(ctx context.Context, resourceAttGetter ResourceAttributeGetter) restful.FilterFunction {
return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
resourceAtt, err := resourceAttGetter.GetResourceAttributes(ctx, req)
err := RequestSubjectAccessReview(ctx, req, resourceAttGetter)
if err != nil {
kerrors.HandleError(req, resp, err)
return
}
reqCtx := req.Request.Context()
log := logging.FromContext(reqCtx).With(
"resource", resourceAtt.Resource,
"group", resourceAtt.Group,
"verb", resourceAtt.Verb,
)
reqCtx = logging.WithLogger(reqCtx, log)
review := makeSelfSubjectAccessReview(resourceAtt)

var clt client.Client
if clientGetter, ok := resourceAttGetter.(SubjectAccessReviewClientGetter); ok {
clt, err = clientGetter.GetClient(ctx, req)
if err != nil {
log.Debugw("get custom client for authentication failed", "err", err)
kerrors.HandleError(req, resp, err)
return
}
}
if clt == nil {
clt = Client(reqCtx)
}
err = postSubjectAccessReview(reqCtx, clt, review)
chain.ProcessFilter(req, resp)
}
}

// RequestSubjectAccessReview request the SubjectAccessReview resource to check whether it has permission.
func RequestSubjectAccessReview(ctx context.Context, req *restful.Request, resourceAttGetter ResourceAttributeGetter) error {
resourceAtt, err := resourceAttGetter.GetResourceAttributes(ctx, req)
if err != nil {
return err
}
reqCtx := req.Request.Context()
log := logging.FromContext(reqCtx).With(
"resource", resourceAtt.Resource,
"group", resourceAtt.Group,
"verb", resourceAtt.Verb,
)
reqCtx = logging.WithLogger(reqCtx, log)
review := makeSelfSubjectAccessReview(resourceAtt)

var clt client.Client
if clientGetter, ok := resourceAttGetter.(SubjectAccessReviewClientGetter); ok {
clt, err = clientGetter.GetClient(ctx, req)
if err != nil {
log.Debugw("error verifying user permissions", "err", err, "review", review.GetObject())
kerrors.HandleError(req, resp, err)
return
log.Debugw("get custom client for authentication failed", "err", err)
return err
}
chain.ProcessFilter(req, resp)
}
if clt == nil {
clt = Client(reqCtx)
}
err = postSubjectAccessReview(reqCtx, clt, review)
if err != nil {
log.Debugw("error verifying user permissions", "err", err, "review", review.GetObject())
return err
}
return nil
}

// SubjectReviewFilterForResource makes a self subject review based a configuration already present inside the
Expand All @@ -111,6 +119,14 @@ func SubjectReviewFilterForResource(ctx context.Context, resourceAtt authv1.Reso
return DynamicSubjectReviewFilter(ctx, getter)
}

// CheckSubjectAccessReview check if relevant permissions are included
func CheckSubjectAccessReview(ctx context.Context, req *restful.Request, resourceAtt authv1.ResourceAttributes) error {
kycheng marked this conversation as resolved.
Show resolved Hide resolved
getter := GetResourceAttributesFunc(func(ctx context.Context, req *restful.Request) (authv1.ResourceAttributes, error) {
return resourceAtt, nil
})
return RequestSubjectAccessReview(ctx, req, getter)
}

func makeSubjectAccessReview(resourceAtt authv1.ResourceAttributes, user user.Info) subjectAccessReviewObjInterface {
review := &authv1.SubjectAccessReview{
Spec: authv1.SubjectAccessReviewSpec{
Expand Down
40 changes: 40 additions & 0 deletions client/rbac_filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,46 @@ func TestRBACFilter(t *testing.T) {

g.Expect(recorder.Code).Should(Not(BeEquivalentTo(http.StatusOK)))
})

t.Run("Check resource permissions", func(t *testing.T) {
g := NewGomegaWithT(t)
mockCtl := gomock.NewController(t)

ctx := context.TODO()

mockClient := mockfakeclient.NewMockClient(mockCtl)
mockClient.EXPECT().Create(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx interface{}, obj client.Object, opts ...client.CreateOption) error {
subject := obj.(*authv1.SelfSubjectAccessReview)
if subject.Spec.ResourceAttributes.Name == "allowed" {
subject.Status.Denied = false
subject.Status.Allowed = true
} else {
subject.Status.Denied = true
subject.Status.Allowed = false
}
return nil
}).Times(2)

ctx = WithClient(ctx, mockClient)
config := &rest.Config{Impersonate: rest.ImpersonationConfig{UserName: "dev"}}
ctx = injection.WithConfig(ctx, config)
ctx = apiserverrequest.WithUser(ctx, &user.DefaultInfo{Name: "dev"})

req := httptest.NewRequest("GET", "http://localhost", nil)
request := restful.NewRequest(req)
request.Request = request.Request.WithContext(ctx)

err := CheckSubjectAccessReview(ctx, request, authv1.ResourceAttributes{
Name: "allowed",
})

g.Expect(err).Should(Succeed())
err = CheckSubjectAccessReview(ctx, request, authv1.ResourceAttributes{
Name: "not_allowed",
})
g.Expect(err.Error()).To(Equal("forbidden: access not allowed"))
})
}

func TestGetResourceAttributesFunc_GetResourceAttributes(t *testing.T) {
Expand Down
19 changes: 19 additions & 0 deletions multicluster/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package multicluster

import (
authv1 "k8s.io/api/authorization/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
Expand Down Expand Up @@ -172,3 +173,21 @@ type ClusterCondition struct {
// +optional
Message string `json:"message,omitempty" protobuf:"bytes,6,opt,name=message"`
}

// ClusterList represents a list of clusters
type ClusterList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`

Items []Cluster `json:"items"`
}

// ClusterResourceAttributes returns a ResourceAttribute object to be used in a filter
func ClusterResourceAttributes(verb string) authv1.ResourceAttributes {
return authv1.ResourceAttributes{
Group: ClusterRegistryGroupVersion.Group,
Version: ClusterRegistryGroupVersion.Version,
Resource: ClusterGVR.Resource,
Verb: verb,
}
}
18 changes: 18 additions & 0 deletions resource/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
Copyright 2023 The Katanomi 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 resource provides some common operations on ResourceRequirements resources.
package resource
49 changes: 49 additions & 0 deletions resource/resources.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
Copyright 2023 The Katanomi 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 resource

import corev1 "k8s.io/api/core/v1"

// SumResources sums two ResourceRequirements resources.
// Note: No operations are performed on Claims. only the sum of Limits and Requests is completed.
func SumResources(param1, param2 corev1.ResourceRequirements) corev1.ResourceRequirements {
kycheng marked this conversation as resolved.
Show resolved Hide resolved
return corev1.ResourceRequirements{
Limits: SumResourceList(param1.Limits, param2.Limits),
Requests: SumResourceList(param1.Requests, param2.Requests),
}
}

// SumResourceList sums two ResourceList resources.
func SumResourceList(param1, param2 corev1.ResourceList) corev1.ResourceList {
result := corev1.ResourceList{}
for key, itemQuantity := range param1 {
tmpQuantity := itemQuantity
if quantity, ok := param2[key]; ok {
tmpQuantity.Add(quantity)
result[key] = tmpQuantity
delete(param2, key)
kycheng marked this conversation as resolved.
Show resolved Hide resolved
} else {
result[key] = tmpQuantity
}
}

for key, itemQuantity := range param2 {
tmpQuantity := itemQuantity
result[key] = tmpQuantity
}
return result
}
Loading