1
0
mirror of https://github.com/rancher/steve.git synced 2025-04-28 11:14:43 +00:00
steve/pkg/accesscontrol/access_store.go

89 lines
1.9 KiB
Go
Raw Normal View History

2019-08-04 17:41:32 +00:00
package accesscontrol
import (
2020-02-08 20:03:57 +00:00
"context"
"crypto/sha256"
"encoding/hex"
"sort"
"time"
v1 "github.com/rancher/wrangler/v3/pkg/generated/controllers/rbac/v1"
2020-02-08 20:03:57 +00:00
"k8s.io/apimachinery/pkg/util/cache"
2019-08-04 17:41:32 +00:00
"k8s.io/apiserver/pkg/authentication/user"
)
//go:generate mockgen --build_flags=--mod=mod -package fake -destination fake/AccessSetLookup.go "github.com/rancher/steve/pkg/accesscontrol" AccessSetLookup
type AccessSetLookup interface {
AccessFor(user user.Info) *AccessSet
PurgeUserData(id string)
}
2019-08-04 17:41:32 +00:00
type AccessStore struct {
2020-03-02 05:23:36 +00:00
users *policyRuleIndex
groups *policyRuleIndex
cache *cache.LRUExpireCache
2020-02-08 20:03:57 +00:00
}
type roleKey struct {
namespace string
name string
2019-08-04 17:41:32 +00:00
}
2020-02-08 20:03:57 +00:00
func NewAccessStore(ctx context.Context, cacheResults bool, rbac v1.Interface) *AccessStore {
2020-03-02 05:23:36 +00:00
revisions := newRoleRevision(ctx, rbac)
2020-02-08 20:03:57 +00:00
as := &AccessStore{
2020-03-02 05:23:36 +00:00
users: newPolicyRuleIndex(true, revisions, rbac),
groups: newPolicyRuleIndex(false, revisions, rbac),
2019-08-04 17:41:32 +00:00
}
2020-02-08 20:03:57 +00:00
if cacheResults {
2020-03-02 05:23:36 +00:00
as.cache = cache.NewLRUExpireCache(50)
2020-02-08 20:03:57 +00:00
}
return as
}
2019-08-04 17:41:32 +00:00
func (l *AccessStore) AccessFor(user user.Info) *AccessSet {
2020-02-08 20:03:57 +00:00
var cacheKey string
if l.cache != nil {
cacheKey = l.CacheKey(user)
val, ok := l.cache.Get(cacheKey)
if ok {
as, _ := val.(*AccessSet)
return as
}
}
2019-08-04 17:41:32 +00:00
result := l.users.get(user.GetName())
for _, group := range user.GetGroups() {
result.Merge(l.groups.get(group))
}
2020-02-08 20:03:57 +00:00
if l.cache != nil {
result.ID = cacheKey
l.cache.Add(cacheKey, result, 24*time.Hour)
}
2019-08-04 17:41:32 +00:00
return result
}
2020-02-08 20:03:57 +00:00
func (l *AccessStore) PurgeUserData(id string) {
l.cache.Remove(id)
}
2020-02-08 20:03:57 +00:00
func (l *AccessStore) CacheKey(user user.Info) string {
2020-03-02 05:23:36 +00:00
d := sha256.New()
2020-02-08 20:03:57 +00:00
2020-03-02 05:23:36 +00:00
l.users.addRolesToHash(d, user.GetName())
2020-02-08 20:03:57 +00:00
2020-03-02 05:23:36 +00:00
groupBase := user.GetGroups()
groups := make([]string, 0, len(groupBase))
copy(groups, groupBase)
sort.Strings(groups)
for _, group := range user.GetGroups() {
l.groups.addRolesToHash(d, group)
2020-02-08 20:03:57 +00:00
}
2020-03-02 05:23:36 +00:00
return hex.EncodeToString(d.Sum(nil))
2020-02-08 20:03:57 +00:00
}