Skip to content
Open
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
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,35 @@ Availability is checked at startup; restart the proxy when Capsule or the
selected configuration is installed or removed. Unexpected discovery/read errors still
fail startup.

## GlobalProxySettings subjects

With `ProxyClusterScoped` enabled, the `subjects` of a `GlobalProxySettings` rule can be
of kind `User`, `Group`, `ServiceAccount` or `Tenant`. A `Tenant` subject matches every
caller that currently owns the named Tenant, whether as User, Group or promoted
ServiceAccount, so administrators do not need to know owner names in advance:

```yaml
apiVersion: capsule.clastix.io/v1beta1
kind: GlobalProxySettings
metadata:
name: solar-storageclasses
spec:
rules:
- subjects:
- kind: Tenant
name: solar
clusterResources:
- apiGroups: ["storage.k8s.io"]
resources: ["storageclasses"]
operations: ["List", "Get"]
selector:
matchLabels:
tier: shared
```

Ownership is read from `Tenant.status.owners`, so removing an owner revokes the grant.
Callers that do not own the Tenant receive nothing from the rule.

## Documentation

You can find more detailed documentation [here](https://capsule.clastix.io/docs/general/proxy).
Expand Down
24 changes: 21 additions & 3 deletions api/v1beta1/globalproxysettings_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,28 @@ type GlobalSubjectSpec struct {
ClusterResources []ClusterResource `json:"clusterResources,omitempty"`
}

// GlobalSubjectKind is the kind of a GlobalProxySettings subject.
// +kubebuilder:validation:Enum=User;Group;ServiceAccount;Tenant
type GlobalSubjectKind string

const (
GlobalSubjectKindUser GlobalSubjectKind = GlobalSubjectKind(capsulerbac.UserOwner)
GlobalSubjectKindGroup GlobalSubjectKind = GlobalSubjectKind(capsulerbac.GroupOwner)
GlobalSubjectKindServiceAccount GlobalSubjectKind = GlobalSubjectKind(capsulerbac.ServiceAccountOwner)
// GlobalSubjectKindTenant selects every current owner of the Tenant with the given name.
// Owners are resolved from the Tenant status, so they can be Users, Groups or promoted ServiceAccounts.
GlobalSubjectKindTenant GlobalSubjectKind = "Tenant"
)

func (k GlobalSubjectKind) String() string {
return string(k)
}

type GlobalSubject struct {
// Kind of tenant owner. Possible values are "User", "Group", and "ServiceAccount".
Kind capsulerbac.OwnerKind `json:"kind"`
// Name of tenant owner.
// Kind of the subject. Possible values are "User", "Group", "ServiceAccount" and "Tenant".
// A "Tenant" subject matches every current owner of the named Tenant.
Kind GlobalSubjectKind `json:"kind"`
// Name of the subject. For the "Tenant" kind, the name of the Tenant.
Name string `json:"name"`
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,18 @@ spec:
items:
properties:
kind:
description: Kind of tenant owner. Possible values are
"User", "Group", and "ServiceAccount".
description: |-
Kind of the subject. Possible values are "User", "Group", "ServiceAccount" and "Tenant".
A "Tenant" subject matches every current owner of the named Tenant.
enum:
- User
- Group
- ServiceAccount
- Tenant
type: string
name:
description: Name of tenant owner.
description: Name of the subject. For the "Tenant" kind,
the name of the Tenant.
type: string
required:
- kind
Expand Down
140 changes: 140 additions & 0 deletions e2e/global_tenant_subject_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//go:build e2e

package e2e_test

import (
"context"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
capsulev1beta2 "github.com/projectcapsule/capsule/api/v1beta2"
capsulerbac "github.com/projectcapsule/capsule/pkg/api/rbac"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"

v1beta1 "github.com/projectcapsule/capsule-proxy/api/v1beta1"
)

var _ = Describe("GlobalProxySettings with Tenant subjects", func() {
const sharedRole = "global-tenant-subject-role"

var aliceClient, bobClient *kubernetes.Clientset

ownedBy := func(user string) capsulerbac.OwnerListSpec {
return capsulerbac.OwnerListSpec{{
CoreOwnerSpec: capsulerbac.CoreOwnerSpec{
UserSpec: capsulerbac.UserSpec{Name: user, Kind: capsulerbac.UserOwner},
},
}}
}

// canSeeRole reports whether the user can list the shared ClusterRole through the proxy.
// A forbidden listing counts as not visible.
canSeeRole := func(clientset *kubernetes.Clientset) bool {
list, err := clientset.RbacV1().ClusterRoles().List(context.Background(), metav1.ListOptions{})
if err != nil {
return false
}

for _, role := range list.Items {
if role.Name == sharedRole {
return true
}
}

return false
}

BeforeEach(func() {
var err error

aliceClient, err = loadKubeConfig("alice")
Expect(err).ToNot(HaveOccurred())
bobClient, err = loadKubeConfig("bob")
Expect(err).ToNot(HaveOccurred())

for _, tnt := range []*capsulev1beta2.Tenant{
{ObjectMeta: metav1.ObjectMeta{Name: "global-tenant-subject-alice", Labels: e2eLabels()}, Spec: capsulev1beta2.TenantSpec{Owners: ownedBy("alice")}},
{ObjectMeta: metav1.ObjectMeta{Name: "global-tenant-subject-bob", Labels: e2eLabels()}, Spec: capsulev1beta2.TenantSpec{Owners: ownedBy("bob")}},
} {
Eventually(func() error {
tnt.ResourceVersion = ""

return k8sClient.Create(context.Background(), tnt)
}, defaultTimeoutInterval, defaultPollInterval).Should(Succeed())
}

role := &rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{Name: sharedRole, Labels: e2eLabels()},
Rules: []rbacv1.PolicyRule{{APIGroups: []string{""}, Resources: []string{"pods"}, Verbs: []string{"list"}}},
}
Eventually(func() error {
role.ResourceVersion = ""

return k8sClient.Create(context.Background(), role)
}, defaultTimeoutInterval, defaultPollInterval).Should(Succeed())

settings := &v1beta1.GlobalProxySettings{
ObjectMeta: metav1.ObjectMeta{Name: "global-tenant-subject", Labels: e2eLabels()},
Spec: v1beta1.GlobalProxySettingsSpec{Rules: []v1beta1.GlobalSubjectSpec{{
Subjects: []v1beta1.GlobalSubject{{Kind: v1beta1.GlobalSubjectKindTenant, Name: "global-tenant-subject-alice"}},
ClusterResources: []v1beta1.ClusterResource{{
APIGroups: []string{rbacv1.GroupName},
Resources: []string{"clusterroles"},
Operations: []v1beta1.ClusterResourceOperation{v1beta1.ClusterResourceOperationList},
Selector: &metav1.LabelSelector{MatchLabels: e2eLabels()},
}},
}}},
}
Eventually(func() error {
settings.ResourceVersion = ""

return k8sClient.Create(context.Background(), settings)
}, defaultTimeoutInterval, defaultPollInterval).Should(Succeed())

Eventually(func(g Gomega) {
current := &v1beta1.GlobalProxySettings{}
g.Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: settings.Name}, current)).To(Succeed())
g.Expect(current.Status.ObservedGeneration).To(Equal(current.Generation))
}, defaultTimeoutInterval, defaultPollInterval).Should(Succeed())
})

JustAfterEach(func() {
resources := []client.Object{
&capsulev1beta2.Tenant{},
&v1beta1.GlobalProxySettings{},
&rbacv1.ClusterRole{},
}
Eventually(func() error {
return cleanResources(resources, e2eSelector())
}, defaultTimeoutInterval, defaultPollInterval).Should(Succeed())
})

It("grants the rule to the owners of the referenced Tenant only and follows ownership changes", func() {
By("granting access to the owner of the referenced Tenant")
Eventually(func() bool { return canSeeRole(aliceClient) }, defaultTimeoutInterval, defaultPollInterval).
Should(BeTrue(), "the owner of the referenced Tenant should list the ClusterRole")

By("denying the owner of another Tenant")
Consistently(func() bool { return canSeeRole(bobClient) }, 5*defaultPollInterval, defaultPollInterval).
Should(BeFalse(), "the owner of another Tenant should not list the ClusterRole")

By("revoking access once the user is no longer an owner")
tnt := &capsulev1beta2.Tenant{}
Eventually(func() error {
if err := k8sClient.Get(context.Background(), types.NamespacedName{Name: "global-tenant-subject-alice"}, tnt); err != nil {
return err
}

tnt.Spec.Owners = ownedBy("global-tenant-subject-new-owner")

return k8sClient.Update(context.Background(), tnt)
}, defaultTimeoutInterval, defaultPollInterval).Should(Succeed())

Eventually(func() bool { return canSeeRole(aliceClient) }, defaultTimeoutInterval, defaultPollInterval).
Should(BeFalse(), "a former owner should lose the grant")
})
})
2 changes: 1 addition & 1 deletion e2e/proxysetting_security_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ var _ = Describe("ProxySetting cluster-resource isolation", Ordered, Serial, Con

It("preserves administrator grants through GlobalProxySettings", Label("proxysetting-global"), func() {
global := &v1beta1.GlobalProxySettings{ObjectMeta: metav1.ObjectMeta{Name: f.id + "-global"}, Spec: v1beta1.GlobalProxySettingsSpec{Rules: []v1beta1.GlobalSubjectSpec{{
Subjects: []v1beta1.GlobalSubject{{Kind: capsulerbac.UserOwner, Name: f.subjects["coowner"].username}},
Subjects: []v1beta1.GlobalSubject{{Kind: v1beta1.GlobalSubjectKindUser, Name: f.subjects["coowner"].username}},
ClusterResources: []v1beta1.ClusterResource{
{APIGroups: []string{""}, Resources: []string{"namespaces"}, Selector: &metav1.LabelSelector{MatchLabels: map[string]string{corev1.LabelMetadataName: f.namespaces["b"]}}},
{APIGroups: []string{rbacv1.GroupName}, Resources: []string{"clusterroles"}, Selector: &metav1.LabelSelector{MatchLabels: map[string]string{corev1.LabelMetadataName: f.id + "-foreign"}}},
Expand Down
4 changes: 2 additions & 2 deletions internal/modules/namespace/namespace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ func tenantOwner(name string, namespaces ...string) *tenant.ProxyTenant {

func globalRule(selector map[string]string) *tenant.ProxyTenant {
return tenant.NewClusterProxy("alice", capsulerbac.UserOwner, []v1beta1.GlobalSubjectSpec{{
Subjects: []v1beta1.GlobalSubject{{Kind: capsulerbac.UserOwner, Name: "alice"}},
Subjects: []v1beta1.GlobalSubject{{Kind: v1beta1.GlobalSubjectKindUser, Name: "alice"}},
ClusterResources: []v1beta1.ClusterResource{{
APIGroups: []string{""},
Resources: []string{"namespaces"},
Selector: &metav1.LabelSelector{MatchLabels: selector},
}},
}})
}}, nil)
}

type testRequest struct{ *http.Request }
Expand Down
18 changes: 16 additions & 2 deletions internal/tenant/proxytenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package tenant

import (
"net/http"
"slices"

capsulev1beta2 "github.com/projectcapsule/capsule/api/v1beta2"
capsulerbac "github.com/projectcapsule/capsule/pkg/api/rbac"
Expand Down Expand Up @@ -69,13 +70,18 @@ func NewProxyTenant(

// NewClusterProxy returns a ProxyTenant struct for GlobalProxySettings. These settings are currently not bound to a tenant and therefore
// an empty tenant is returned.
func NewClusterProxy(ownerName string, ownerKind capsulerbac.OwnerKind, owners []v1beta1.GlobalSubjectSpec) *ProxyTenant {
//
// A rule applies when one of its subjects is the caller itself (ownerKind/ownerName) or a Tenant the caller
// currently owns (ownedTenants).
func NewClusterProxy(ownerName string, ownerKind capsulerbac.OwnerKind, owners []v1beta1.GlobalSubjectSpec, ownedTenants []string) *ProxyTenant {
var tenantClusterResources []v1beta1.ClusterResource

for _, global := range owners {
for _, subject := range global.Subjects {
if subject.Name == ownerName && subject.Kind == ownerKind {
if globalSubjectMatches(subject, ownerName, ownerKind, ownedTenants) {
tenantClusterResources = append(tenantClusterResources, global.ClusterResources...)

break
}
}
}
Expand All @@ -85,6 +91,14 @@ func NewClusterProxy(ownerName string, ownerKind capsulerbac.OwnerKind, owners [
}
}

func globalSubjectMatches(subject v1beta1.GlobalSubject, ownerName string, ownerKind capsulerbac.OwnerKind, ownedTenants []string) bool {
if subject.Kind == v1beta1.GlobalSubjectKindTenant {
return slices.Contains(ownedTenants, subject.Name)
}

return subject.Name == ownerName && subject.Kind.String() == ownerKind.String()
}

func (p *ProxyTenant) RequestAllowed(request *http.Request, serviceKind capsulerbac.ProxyServiceKind) (ok bool) {
return p.ProxySetting[serviceKind].IsAllowed(request)
}
74 changes: 74 additions & 0 deletions internal/tenant/proxytenant_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2020-2026 Project Capsule Authors
// SPDX-License-Identifier: Apache-2.0

package tenant

import (
"testing"

capsulerbac "github.com/projectcapsule/capsule/pkg/api/rbac"

"github.com/projectcapsule/capsule-proxy/api/v1beta1"
)

func TestNewClusterProxySubjects(t *testing.T) {
t.Parallel()

rule := func(resource string, subjects ...v1beta1.GlobalSubject) v1beta1.GlobalSubjectSpec {
return v1beta1.GlobalSubjectSpec{
Subjects: subjects,
ClusterResources: []v1beta1.ClusterResource{{APIGroups: []string{""}, Resources: []string{resource}}},
}
}

rules := []v1beta1.GlobalSubjectSpec{
rule("namespaces", v1beta1.GlobalSubject{Kind: v1beta1.GlobalSubjectKindUser, Name: "alice"}),
rule("nodes", v1beta1.GlobalSubject{Kind: v1beta1.GlobalSubjectKindTenant, Name: "solar"}),
// Matching through both subjects must not duplicate the rule.
rule("pods",
v1beta1.GlobalSubject{Kind: v1beta1.GlobalSubjectKindTenant, Name: "solar"},
v1beta1.GlobalSubject{Kind: v1beta1.GlobalSubjectKindUser, Name: "alice"},
),
// A Tenant subject never matches an identity by name.
rule("secrets", v1beta1.GlobalSubject{Kind: v1beta1.GlobalSubjectKindTenant, Name: "alice"}),
}

tests := []struct {
name string
ownerName string
ownerKind capsulerbac.OwnerKind
ownedTenants []string
want []string
}{
{"direct subject only", "alice", capsulerbac.UserOwner, nil, []string{"namespaces", "pods"}},
{"owner of the Tenant", "bob", capsulerbac.UserOwner, []string{"solar"}, []string{"nodes", "pods"}},
{"direct subject and Tenant owner", "alice", capsulerbac.UserOwner, []string{"solar"}, []string{"namespaces", "nodes", "pods"}},
{"owner of another Tenant", "bob", capsulerbac.UserOwner, []string{"wind"}, nil},
{"identity named like a Tenant subject", "alice", capsulerbac.GroupOwner, nil, nil},
{"identity named like a Tenant", "alice", capsulerbac.UserOwner, []string{"lunar"}, []string{"namespaces", "pods"}},
{"Tenant name equal to subject name", "bob", capsulerbac.UserOwner, []string{"alice"}, []string{"secrets"}},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

pt := NewClusterProxy(tc.ownerName, tc.ownerKind, rules, tc.ownedTenants)

var got []string
for _, resource := range pt.ClusterResources {
got = append(got, resource.Resources...)
}

if len(got) != len(tc.want) {
t.Fatalf("got resources %v, want %v", got, tc.want)
}

for i := range got {
if got[i] != tc.want[i] {
t.Fatalf("got resources %v, want %v", got, tc.want)
}
}
})
}
}
Loading