forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_control.go
94 lines (74 loc) · 2.42 KB
/
access_control.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package rbac
import (
"net/http"
"strings"
"github.com/rancher/norman/authorization"
"github.com/rancher/norman/types"
"github.com/rancher/types/apis/rbac.authorization.k8s.io/v1"
)
type AccessControl struct {
authorization.AllAccess
permissionStore *ListPermissionStore
}
func NewAccessControl(rbacClient v1.Interface) *AccessControl {
permissionStore := NewListPermissionStore(rbacClient)
return &AccessControl{
permissionStore: permissionStore,
}
}
func (a *AccessControl) Filter(apiContext *types.APIContext, schema *types.Schema, obj map[string]interface{}, context map[string]string) map[string]interface{} {
apiGroup := context["apiGroup"]
resource := context["resource"]
if resource == "" {
return obj
}
permset := a.getPermissions(apiContext, apiGroup, resource)
if a.canAccess(obj, permset) {
return obj
}
return nil
}
func (a *AccessControl) canAccess(obj map[string]interface{}, permset ListPermissionSet) bool {
namespace, _ := obj["namespaceId"].(string)
id, _ := obj["id"].(string)
if permset.HasAccess(namespace, "*") || permset.HasAccess("*", "*") {
return true
}
return permset.HasAccess(namespace, strings.TrimPrefix(id, namespace+":"))
}
func (a *AccessControl) FilterList(apiContext *types.APIContext, schema *types.Schema, objs []map[string]interface{}, context map[string]string) []map[string]interface{} {
apiGroup := context["apiGroup"]
resource := context["resource"]
if resource == "" {
return objs
}
permset := a.getPermissions(apiContext, apiGroup, resource)
result := make([]map[string]interface{}, 0, len(objs))
all := permset.HasAccess("*", "*")
for _, obj := range objs {
if all {
result = append(result, obj)
} else if a.canAccess(obj, permset) {
result = append(result, obj)
}
}
return result
}
func (a *AccessControl) getPermissions(context *types.APIContext, apiGroup, resource string) ListPermissionSet {
permset := a.permissionStore.UserPermissions(getUser(context), apiGroup, resource)
if permset == nil {
permset = ListPermissionSet{}
}
for _, group := range getGroups(context) {
for k, v := range a.permissionStore.GroupPermissions(group, apiGroup, resource) {
permset[k] = v
}
}
return permset
}
func getUser(apiContext *types.APIContext) string {
return apiContext.Request.Header.Get("Impersonate-User")
}
func getGroups(apiContext *types.APIContext) []string {
return apiContext.Request.Header[http.CanonicalHeaderKey("Impersonate-Group")]
}