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

Hide resource visibility if user is not in defined group #856

Closed
wants to merge 3 commits into from
Closed
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
8 changes: 7 additions & 1 deletion internal/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ var (
type ExtraConfig struct {
APIResourceConfigSource serverstorage.APIResourceConfigSource
MachinePoolletConfig client.MachinePoolletClientConfig

//GroupsToShowPoolResources define the group membership to show the pool resources
GroupsToShowPoolResources []string
}

// Config defines the config for the apiserver
Expand Down Expand Up @@ -98,9 +101,12 @@ func (c completedConfig) New() (*OnmetalAPIServer, error) {
corerest.StorageProvider{},
computerest.StorageProvider{
MachinePoolletClientConfig: c.ExtraConfig.MachinePoolletConfig,
GroupsToShowPoolResources: c.ExtraConfig.GroupsToShowPoolResources,
},
networkingrest.StorageProvider{},
storagerest.StorageProvider{},
storagerest.StorageProvider{
GroupsToShowPoolResources: c.ExtraConfig.GroupsToShowPoolResources,
},
}

var apiGroupsInfos []*genericapiserver.APIGroupInfo
Expand Down
10 changes: 8 additions & 2 deletions internal/app/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ type OnmetalAPIServerOptions struct {
MachinePoolletConfig client.MachinePoolletClientConfig

SharedInformerFactory informers.SharedInformerFactory

GroupsToShowPoolResources []string
}

func (o *OnmetalAPIServerOptions) AddFlags(fs *pflag.FlagSet) {
Expand All @@ -100,6 +102,9 @@ func (o *OnmetalAPIServerOptions) AddFlags(fs *pflag.FlagSet) {

fs.StringVar(&o.MachinePoolletConfig.CAFile, "machinepoollet-certificate-authority", o.MachinePoolletConfig.CAFile,
"Path to a cert file for the certificate authority.")

fs.StringSliceVar(&o.GroupsToShowPoolResources, "pool-status-view-allowed-groups", o.GroupsToShowPoolResources,
"Groups needed to show pool resources.")
}

func NewOnmetalAPIServerOptions() *OnmetalAPIServerOptions {
Expand Down Expand Up @@ -237,8 +242,9 @@ func (o *OnmetalAPIServerOptions) Config() (*apiserver.Config, error) {
config := &apiserver.Config{
GenericConfig: serverConfig,
ExtraConfig: apiserver.ExtraConfig{
APIResourceConfigSource: apiResourceConfig,
MachinePoolletConfig: o.MachinePoolletConfig,
APIResourceConfigSource: apiResourceConfig,
MachinePoolletConfig: o.MachinePoolletConfig,
GroupsToShowPoolResources: o.GroupsToShowPoolResources,
},
}

Expand Down
34 changes: 26 additions & 8 deletions internal/app/app_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@
)

var (
cfg *rest.Config
k8sClient client.Client
cfg *rest.Config
k8sClient client.Client
elevatedK8sClient client.Client

testEnv *envtest.Environment
testEnvExt *utilsenvtest.EnvironmentExtensions
)
Expand Down Expand Up @@ -95,13 +97,16 @@

komega.SetClient(k8sClient)

const showResourcesGroup = "test-resource-group"
apiSrv, err := apiserver.New(cfg, apiserver.Options{
MainPath: "github.com/onmetal/onmetal-api/cmd/onmetal-apiserver",
BuildOptions: []buildutils.BuildOption{buildutils.ModModeMod},
ETCDServers: []string{testEnv.ControlPlane.Etcd.URL.String()},
Host: testEnvExt.APIServiceInstallOptions.LocalServingHost,
Port: testEnvExt.APIServiceInstallOptions.LocalServingPort,
CertDir: testEnvExt.APIServiceInstallOptions.LocalServingCertDir,
MainPath: "github.com/onmetal/onmetal-api/cmd/onmetal-apiserver",
BuildOptions: []buildutils.BuildOption{buildutils.ModModeMod},
ETCDServers: []string{testEnv.ControlPlane.Etcd.URL.String()},
Host: testEnvExt.APIServiceInstallOptions.LocalServingHost,
Port: testEnvExt.APIServiceInstallOptions.LocalServingPort,
CertDir: testEnvExt.APIServiceInstallOptions.LocalServingCertDir,
AttachOutput: true,
GroupsToShowPoolResources: []string{showResourcesGroup},
})
Expect(err).NotTo(HaveOccurred())

Expand All @@ -110,6 +115,19 @@

err = utilsenvtest.WaitUntilAPIServicesReadyWithTimeout(apiServiceTimeout, testEnvExt, k8sClient, scheme.Scheme)
Expect(err).NotTo(HaveOccurred())

usr, err := testEnv.AddUser(envtest.User{
Name: "elevated-user",
Groups: []string{
"system:masters",

Check warning on line 122 in internal/app/app_suite_test.go

View check run for this annotation

In Solidarity / Inclusive Language

Match Found

Please consider an alternative to `master`. Possibilities include: `primary`, `main`, `leader`, `active`, `writer`
Raw output
/\b(?!masterdata|masterdata\w+\b)master/gi
"system:authenticated",
showResourcesGroup,
},
}, nil)
Expect(err).NotTo(HaveOccurred())

elevatedK8sClient, err = client.New(usr.Config(), client.Options{Scheme: scheme.Scheme})
Expect(err).NotTo(HaveOccurred())
})

func SetupTest(ctx context.Context) *corev1.Namespace {
Expand Down
59 changes: 59 additions & 0 deletions internal/app/compute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
. "sigs.k8s.io/controller-runtime/pkg/envtest/komega"
)

var _ = Describe("Compute", func() {
Expand Down Expand Up @@ -304,4 +305,62 @@ var _ = Describe("Compute", func() {
Expect(machineList.Items).To(ConsistOf(HaveField("UID", machine2.UID)))
})
})

Context("MachinePool resources", func() {
It("should be masked", func() {
By("creating a new machine pool")
machinePool := &computev1alpha1.MachinePool{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "machine-pool-",
},
Spec: computev1alpha1.MachinePoolSpec{
ProviderID: "test",
},
}
Expect(k8sClient.Create(ctx, machinePool)).To(Succeed())

By("patching the status")
Eventually(UpdateStatus(machinePool, func() {
machinePool.Status.Capacity = corev1alpha1.ResourceList{
corev1alpha1.ClassCountFor(corev1alpha1.ClassTypeMachineClass, "test-class"): resource.MustParse("10"),
}
machinePool.Status.Allocatable = corev1alpha1.ResourceList{
corev1alpha1.ClassCountFor(corev1alpha1.ClassTypeMachineClass, "test-class"): resource.MustParse("5"),
}
})).Should(Succeed())

By("checking that the resources are hidden by using GET")
Expect(k8sClient.Get(ctx, client.ObjectKeyFromObject(machinePool), machinePool)).To(Succeed())
Expect(machinePool.Status.Allocatable).To(BeNil())
Expect(machinePool.Status.Capacity).To(BeNil())

By("checking that the resources are hidden by using LIST")
machinePools := &computev1alpha1.MachinePoolList{}
Expect(k8sClient.List(ctx, machinePools)).To(Succeed())
Expect(machinePools.Items).To(ContainElement(SatisfyAll(
HaveField("Status.Allocatable", BeNil()),
HaveField("Status.Capacity", BeNil()),
)))

By("checking that the resources are shown using elevated user by using GET")
Expect(elevatedK8sClient.Get(ctx, client.ObjectKeyFromObject(machinePool), machinePool)).To(Succeed())
Expect(machinePool.Status.Capacity).To(Equal(corev1alpha1.ResourceList{
corev1alpha1.ClassCountFor(corev1alpha1.ClassTypeMachineClass, "test-class"): resource.MustParse("10"),
}))
Expect(machinePool.Status.Allocatable).To(Equal(corev1alpha1.ResourceList{
corev1alpha1.ClassCountFor(corev1alpha1.ClassTypeMachineClass, "test-class"): resource.MustParse("5"),
}))

By("checking that the resources are shown using elevated user by using LIST")
Expect(elevatedK8sClient.List(ctx, machinePools)).To(Succeed())
Expect(machinePools.Items).To(ContainElement(SatisfyAll(
HaveField("Status.Capacity", Equal(corev1alpha1.ResourceList{
corev1alpha1.ClassCountFor(corev1alpha1.ClassTypeMachineClass, "test-class"): resource.MustParse("10"),
})),
HaveField("Status.Allocatable", Equal(corev1alpha1.ResourceList{
corev1alpha1.ClassCountFor(corev1alpha1.ClassTypeMachineClass, "test-class"): resource.MustParse("5"),
})),
)))
})
})
})
59 changes: 59 additions & 0 deletions internal/app/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
. "sigs.k8s.io/controller-runtime/pkg/envtest/komega"
)

var _ = Describe("Storage", func() {
Expand Down Expand Up @@ -208,6 +209,64 @@ var _ = Describe("Storage", func() {
})
})

Context("VolumePool resources", func() {
It("should be masked", func() {
By("creating a new volume pool")
volumePool := &storagev1alpha1.VolumePool{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "volume-pool-",
},
Spec: storagev1alpha1.VolumePoolSpec{
ProviderID: "test",
},
}
Expect(k8sClient.Create(ctx, volumePool)).To(Succeed())

By("patching the status")
Eventually(UpdateStatus(volumePool, func() {
volumePool.Status.Capacity = corev1alpha1.ResourceList{
corev1alpha1.ResourceStorage: resource.MustParse("10Gi"),
}
volumePool.Status.Allocatable = corev1alpha1.ResourceList{
corev1alpha1.ResourceStorage: resource.MustParse("5Gi"),
}
})).Should(Succeed())

By("checking that the resources are hidden by using GET")
Expect(k8sClient.Get(ctx, client.ObjectKeyFromObject(volumePool), volumePool)).To(Succeed())
Expect(volumePool.Status.Allocatable).To(BeNil())
Expect(volumePool.Status.Capacity).To(BeNil())

By("checking that the resources are hidden by using LIST")
volumePools := &storagev1alpha1.VolumePoolList{}
Expect(k8sClient.List(ctx, volumePools)).To(Succeed())
Expect(volumePools.Items).To(ContainElement(SatisfyAll(
HaveField("Status.Allocatable", BeNil()),
HaveField("Status.Capacity", BeNil()),
)))

By("checking that the resources are shown using elevated user by using GET")
Expect(elevatedK8sClient.Get(ctx, client.ObjectKeyFromObject(volumePool), volumePool)).To(Succeed())
Expect(volumePool.Status.Capacity).To(Equal(corev1alpha1.ResourceList{
corev1alpha1.ResourceStorage: resource.MustParse("10Gi"),
}))
Expect(volumePool.Status.Allocatable).To(Equal(corev1alpha1.ResourceList{
corev1alpha1.ResourceStorage: resource.MustParse("5Gi"),
}))

By("checking that the resources are shown using elevated user by using LIST")
Expect(elevatedK8sClient.List(ctx, volumePools)).To(Succeed())
Expect(volumePools.Items).To(ContainElement(SatisfyAll(
HaveField("Status.Capacity", Equal(corev1alpha1.ResourceList{
corev1alpha1.ResourceStorage: resource.MustParse("10Gi"),
})),
HaveField("Status.Allocatable", Equal(corev1alpha1.ResourceList{
corev1alpha1.ResourceStorage: resource.MustParse("5Gi"),
})),
)))
})
})

Context("Bucket", func() {
It("should allow listing buckets filtering by bucket pool name", func() {
const (
Expand Down
41 changes: 41 additions & 0 deletions internal/rbac/rbac.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2023 OnMetal 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 rbac

import (
"context"

"golang.org/x/exp/slices"
"k8s.io/apiserver/pkg/endpoints/request"
)

// UserIsMemberOf returns true if the ctx contains user.Info and if the user is member of one of the provided groups
func UserIsMemberOf(ctx context.Context, groups []string) bool {
if groups == nil {
return true
}

user, ok := request.UserFrom(ctx)
if !ok {
return false
}

for _, group := range groups {
if slices.Contains(user.GetGroups(), group) {
return true
}
}
return false
}
95 changes: 95 additions & 0 deletions internal/rbac/rbac_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright 2023 OnMetal 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 rbac

import (
"context"
"testing"

"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/endpoints/request"
)

func TestUserIsMemberOf(t *testing.T) {
type args struct {
ctx context.Context
groups []string
}
tests := []struct {
name string
args args
want bool
}{
{
name: "User is always part of empty groups - 1",
args: args{
ctx: request.WithUser(request.NewContext(), &user.DefaultInfo{}),
groups: nil,
},
want: true,
},
{
name: "User is always part of empty groups - 2",
args: args{
ctx: request.WithUser(request.NewContext(), &user.DefaultInfo{
Name: "test",
Groups: []string{"group-1"},
Extra: nil,
}),
groups: nil,
},
want: true,
},
{
name: "User is member of one of the required groups",
args: args{
ctx: request.WithUser(request.NewContext(), &user.DefaultInfo{
Name: "test",
Groups: []string{"group-1"},
Extra: nil,
}),
groups: []string{"group-1", "group-2", "group-3"},
},
want: true,
},
{
name: "User is not member of one of the required groups",
args: args{
ctx: request.WithUser(request.NewContext(), &user.DefaultInfo{
Name: "test",
Groups: []string{"group-1"},
Extra: nil,
}),
groups: []string{"group-2", "group-3"},
},
want: false,
},
{
name: "Context without user is not part of groups",
args: args{
ctx: request.NewContext(),
groups: []string{"group-1", "group-2", "group-3"},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := UserIsMemberOf(tt.args.ctx, tt.args.groups); got != tt.want {
t.Errorf("UserIsMemberOf() = %v, want %v", got, tt.want)
}
})
}
}
Loading