Files
capsule/pkg/webhook/utils/is_capsule_user.go
Oliver Bähler cb029a1d70 feat(config): add usernames property identify specific users as capsule users (#1606)
* feat(config): add usernames property identify specific users as capsule users

Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>

* feat(helm): improve admission configurations

Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>

* feat(helm): improve admission configurations

Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>

* feat(config): add usernames property identify specific users as capsule users

Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>

* feat(config): add usernames property identify specific users as capsule users

Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>

---------

Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>
2025-08-22 15:03:50 +02:00

66 lines
1.8 KiB
Go

// Copyright 2020-2025 Project Capsule Authors
// SPDX-License-Identifier: Apache-2.0
package utils
import (
"context"
"strings"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
capsulev1beta2 "github.com/projectcapsule/capsule/api/v1beta2"
"github.com/projectcapsule/capsule/pkg/utils"
)
func IsCapsuleUser(ctx context.Context, req admission.Request, clt client.Client, users []string, userGroups []string, ignoreGroups []string) bool {
groupList := utils.NewUserGroupList(req.UserInfo.Groups)
// if the user is a ServiceAccount belonging to the kube-system namespace, definitely, it's not a Capsule user
// and we can skip the check in case of Capsule user group assigned to system:authenticated
// (ref: https://github.com/projectcapsule/capsule/issues/234)
if groupList.Find("system:serviceaccounts:kube-system") {
return false
}
//nolint:nestif
if sets.NewString(req.UserInfo.Groups...).Has("system:serviceaccounts") {
parts := strings.Split(req.UserInfo.Username, ":")
if len(parts) == 4 {
targetNamespace := parts[2]
tl := &capsulev1beta2.TenantList{}
if err := clt.List(ctx, tl, client.MatchingFieldsSelector{Selector: fields.OneTermEqualSelector(".status.namespaces", targetNamespace)}); err != nil {
return false
}
if len(tl.Items) == 1 {
return true
}
}
}
for _, group := range userGroups {
if groupList.Find(group) {
if len(ignoreGroups) > 0 {
for _, ignoreGroup := range ignoreGroups {
if groupList.Find(ignoreGroup) {
return false
}
}
}
return true
}
}
if len(users) > 0 && sets.New[string](users...).Has(req.UserInfo.Username) {
return true
}
return false
}