forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
48 lines (40 loc) · 1.67 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package util
import (
"errors"
authorizationv1 "k8s.io/api/authorization/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/client-go/kubernetes/typed/authorization/v1"
)
// AddUserToSAR adds the requisite user information to a SubjectAccessReview.
// It returns the modified SubjectAccessReview.
func AddUserToSAR(user user.Info, sar *authorizationv1.SubjectAccessReview) *authorizationv1.SubjectAccessReview {
sar.Spec.User = user.GetName()
// reminiscent of the bad old days of C. Copies copy the min number of elements of both source and dest
sar.Spec.Groups = make([]string, len(user.GetGroups()))
copy(sar.Spec.Groups, user.GetGroups())
sar.Spec.Extra = map[string]authorizationv1.ExtraValue{}
for k, v := range user.GetExtra() {
sar.Spec.Extra[k] = authorizationv1.ExtraValue(v)
}
return sar
}
// Authorize verifies that a given user is permitted to carry out a given
// action. If this cannot be determined, or if the user is not permitted, an
// error is returned.
func Authorize(sarClient v1.SubjectAccessReviewInterface, user user.Info, resourceAttributes *authorizationv1.ResourceAttributes) error {
sar := AddUserToSAR(user, &authorizationv1.SubjectAccessReview{
Spec: authorizationv1.SubjectAccessReviewSpec{
ResourceAttributes: resourceAttributes,
},
})
resp, err := sarClient.Create(sar)
if err == nil && resp != nil && resp.Status.Allowed {
return nil
}
if err == nil {
err = errors.New(resp.Status.Reason)
}
return kerrors.NewForbidden(schema.GroupResource{Group: resourceAttributes.Group, Resource: resourceAttributes.Resource}, resourceAttributes.Name, err)
}