Skip to content

Commit

Permalink
Allow users to create their own settings (#163)
Browse files Browse the repository at this point in the history
  • Loading branch information
bastjan authored May 17, 2023
1 parent 17dccc4 commit 7239094
Show file tree
Hide file tree
Showing 7 changed files with 228 additions and 70 deletions.
4 changes: 4 additions & 0 deletions config/user-rbac/basic-user-role.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@ rules:
- apiGroups: ["user.appuio.io"]
resources: ["invitationredeemrequests"]
verbs: ["create"]
# Allow users to create themselves, user create requests are validated by the users validation webhook
- apiGroups: ["appuio.io"]
resources: ["users"]
verbs: ["create"]
31 changes: 31 additions & 0 deletions pkg/sar/resource_attributes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package sar

// ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface.
// From https://github.com/kubernetes/api/blob/2f9553831ec24dc60e3e1c3a374fb63ca091688f/authorization/v1/types.go#L92-L118.
// Importing the whole package confuses go mod.
type ResourceAttributes struct {
// Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces
// "" (empty) is defaulted for LocalSubjectAccessReviews
// "" (empty) is empty for cluster-scoped resources
// "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview
// +optional
Namespace string `json:"namespace,omitempty" protobuf:"bytes,1,opt,name=namespace"`
// Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all.
// +optional
Verb string `json:"verb,omitempty" protobuf:"bytes,2,opt,name=verb"`
// Group is the API Group of the Resource. "*" means all.
// +optional
Group string `json:"group,omitempty" protobuf:"bytes,3,opt,name=group"`
// Version is the API Version of the Resource. "*" means all.
// +optional
Version string `json:"version,omitempty" protobuf:"bytes,4,opt,name=version"`
// Resource is one of the existing resource types. "*" means all.
// +optional
Resource string `json:"resource,omitempty" protobuf:"bytes,5,opt,name=resource"`
// Subresource is one of the existing resource types. "" means none.
// +optional
Subresource string `json:"subresource,omitempty" protobuf:"bytes,6,opt,name=subresource"`
// Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all.
// +optional
Name string `json:"name,omitempty" protobuf:"bytes,7,opt,name=name"`
}
85 changes: 85 additions & 0 deletions pkg/sar/sar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package sar

import (
"context"
"errors"
"fmt"

authenticationv1 "k8s.io/api/authentication/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// AuthorizeResource checks if the given user is allowed to access the given resource, using SubjectAccessReviews.
func AuthorizeResource(ctx context.Context, c client.Client, user authenticationv1.UserInfo, resource ResourceAttributes) error {
// I could not find a way to create a SubjectAccessReview object with the client.
// `no kind "CreateOptions" is registered for the internal version of group "authorization.k8s.io" in scheme`
// even after installing the authorization scheme.
rawSAR := &unstructured.Unstructured{
Object: map[string]any{
"spec": sarSpec{
ResourceAttributes: resource,

User: user.Username,
Groups: user.Groups,
Extra: user.Extra,
UID: user.UID,
},
}}
rawSAR.SetGroupVersionKind(schema.GroupVersionKind{Group: "authorization.k8s.io", Version: "v1", Kind: "SubjectAccessReview"})

if err := c.Create(ctx, rawSAR); err != nil {
return fmt.Errorf("failed to create SubjectAccessReview: %w", err)
}

allowed, _, err := unstructured.NestedBool(rawSAR.Object, "status", "allowed")
if err != nil {
return fmt.Errorf("failed to get SubjectAccessReview status.allowed: %w", err)
}

if !allowed {
return fmt.Errorf("%q is not allowed by %q", resource, user)
}

return nil
}

// MOCK_SubjectAccessReviewResponder is a wrapper for client.WithWatch that responds to SubjectAccessReview create requests
// and allows or denies the request based on the AllowedUser name.
type MOCK_SubjectAccessReviewResponder struct {
client.WithWatch

AllowedUser string
}

func (r MOCK_SubjectAccessReviewResponder) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error {
if sar, ok := obj.(*unstructured.Unstructured); ok {
if sar.GetKind() == "SubjectAccessReview" {
o, ok, err := unstructured.NestedFieldNoCopy(sar.Object, "spec")
if err != nil {
return err
}
if !ok {
return errors.New("spec not found")
}
s, ok := o.(sarSpec)
if !ok {
return errors.New("unknown spec type, might not originate from this package")
}

unstructured.SetNestedField(sar.Object, s.User == r.AllowedUser, "status", "allowed")
return nil
}
}
return r.WithWatch.Create(ctx, obj, opts...)
}

type sarSpec struct {
ResourceAttributes ResourceAttributes `json:"resourceAttributes"`

User string `json:"user,omitempty"`
Groups []string `json:"groups,omitempty"`
Extra map[string]authenticationv1.ExtraValue `json:"extra,omitempty"`
UID string `json:"uid,omitempty"`
}
50 changes: 11 additions & 39 deletions webhooks/invitation_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import (

"go.uber.org/multierr"
authenticationv1 "k8s.io/api/authentication/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

userv1 "github.com/appuio/control-api/apis/user/v1"
"github.com/appuio/control-api/controllers/targetref"
"github.com/appuio/control-api/pkg/sar"
)

// +kubebuilder:webhook:path=/validate-user-appuio-io-v1-invitation,mutating=false,failurePolicy=fail,groups="user.appuio.io",resources=invitations,verbs=create;update,versions=v1,name=validate-invitations.user.appuio.io,admissionReviewVersions=v1,sideEffects=None
Expand Down Expand Up @@ -81,55 +81,27 @@ func canEditTarget(ctx context.Context, c client.Client, user authenticationv1.U
if err != nil {
return err
}
ra["verb"] = verb

// I could not find a way to create a SubjectAccessReview object with the client.
// `no kind "CreateOptions" is registered for the internal version of group "authorization.k8s.io" in scheme`
// even after installing the authorization scheme.
rawSAR := &unstructured.Unstructured{
Object: map[string]any{
"spec": map[string]any{
"resourceAttributes": ra,

"user": user.Username,
"groups": user.Groups,
"uid": user.UID,
},
}}
rawSAR.SetGroupVersionKind(schema.GroupVersionKind{Group: "authorization.k8s.io", Version: "v1", Kind: "SubjectAccessReview"})

if err := c.Create(ctx, rawSAR); err != nil {
return fmt.Errorf("failed to create SubjectAccessReview: %w", err)
}

allowed, _, err := unstructured.NestedBool(rawSAR.Object, "status", "allowed")
if err != nil {
return fmt.Errorf("failed to get SubjectAccessReview status.allowed: %w", err)
}
ra.Verb = verb

if !allowed {
return fmt.Errorf("%q on target %q.%q/%q in namespace %q is not allowed", verb, target.APIGroup, target.Kind, target.Name, target.Namespace)
}

return nil
return sar.AuthorizeResource(ctx, c, user, ra)
}

func mapTargetRefToResourceAttribute(c client.Client, target userv1.TargetRef) (map[string]any, error) {
func mapTargetRefToResourceAttribute(c client.Client, target userv1.TargetRef) (sar.ResourceAttributes, error) {
rm, err := c.RESTMapper().RESTMapping(schema.GroupKind{
Group: target.APIGroup,
Kind: target.Kind,
})

if err != nil {
return nil, fmt.Errorf("failed to get REST mapping for %q.%q: %w", target.APIGroup, target.Kind, err)
return sar.ResourceAttributes{}, fmt.Errorf("failed to get REST mapping for %q.%q: %w", target.APIGroup, target.Kind, err)
}

return map[string]any{
"group": target.APIGroup,
"version": rm.Resource.Version,
"resource": rm.Resource.Resource,
return sar.ResourceAttributes{
Group: target.APIGroup,
Version: rm.Resource.Version,
Resource: rm.Resource.Resource,

"namespace": target.Namespace,
"name": target.Name,
Namespace: target.Namespace,
Name: target.Name,
}, nil
}
34 changes: 4 additions & 30 deletions webhooks/invitation_webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package webhooks
import (
"context"
"encoding/json"
"errors"
"net/http"
"testing"

Expand All @@ -14,7 +13,6 @@ import (
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
Expand All @@ -25,6 +23,7 @@ import (
orgv1 "github.com/appuio/control-api/apis/organization/v1"
userv1 "github.com/appuio/control-api/apis/user/v1"
controlv1 "github.com/appuio/control-api/apis/v1"
"github.com/appuio/control-api/pkg/sar"
)

func TestInvitationValidator_Handle(t *testing.T) {
Expand Down Expand Up @@ -338,9 +337,9 @@ func prepareInvitationValidatorTest(t *testing.T, sarAllowedUser string, initObj
WithRESTMapper(drm).
Build()

client = subjectAccessReviewResponder{
client,
sarAllowedUser,
client = sar.MOCK_SubjectAccessReviewResponder{
WithWatch: client,
AllowedUser: sarAllowedUser,
}

iv := &InvitationValidator{}
Expand All @@ -349,28 +348,3 @@ func prepareInvitationValidatorTest(t *testing.T, sarAllowedUser string, initObj

return iv
}

// subjectAccessReviewResponder is a wrapper for client.WithWatch that responds to SubjectAccessReview create requests
// and allows or denies the request based on the allowedUser name.
type subjectAccessReviewResponder struct {
client.WithWatch

allowedUser string
}

func (r subjectAccessReviewResponder) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error {
if sar, ok := obj.(*unstructured.Unstructured); ok {
if sar.GetKind() == "SubjectAccessReview" {
u, p, err := unstructured.NestedString(sar.Object, "spec", "user")
if err != nil {
return err
}
if !p {
return errors.New("spec.user not found")
}
unstructured.SetNestedField(sar.Object, u == r.allowedUser, "status", "allowed")
return nil
}
}
return r.WithWatch.Create(ctx, obj, opts...)
}
17 changes: 17 additions & 0 deletions webhooks/user_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import (
"fmt"
"net/http"

admissionv1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

controlv1 "github.com/appuio/control-api/apis/v1"
"github.com/appuio/control-api/pkg/sar"
)

// +kubebuilder:webhook:path=/validate-appuio-io-v1-user,mutating=false,failurePolicy=fail,groups="appuio.io",resources=users,verbs=create;update,versions=v1,name=validate-users.appuio.io,admissionReviewVersions=v1,sideEffects=None
Expand All @@ -27,6 +29,21 @@ type UserValidator struct {
func (v *UserValidator) Handle(ctx context.Context, req admission.Request) admission.Response {
log := log.FromContext(ctx).WithName("webhook.validate-users.appuio.io")

// Allow the user to create or update itself.
// A special permission, used for controllers, `create rbac.appuio.io users` can override this.
if req.AdmissionRequest.Operation == admissionv1.Create && req.UserInfo.Username != req.Name {
if err := sar.AuthorizeResource(ctx, v.client, req.UserInfo, sar.ResourceAttributes{
Verb: "create",
Group: "rbac.appuio.io",
Resource: req.Resource.Group,
Version: req.Resource.Version,
Name: req.Name,
}); err != nil {
return admission.Denied(fmt.Sprintf("user %q is not allowed to create or update %q", req.UserInfo.Username, req.Name))
}
log.Info("User authorized to create other users", "user", req.AdmissionRequest.UserInfo)
}

user := &controlv1.User{}
if err := v.decoder.Decode(req, user); err != nil {
return admission.Errored(http.StatusBadRequest, err)
Expand Down
Loading

0 comments on commit 7239094

Please sign in to comment.