AuthZ: Make cache ttl configurable (#103769)

* AuthZ: Configure cache ttl

Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>

* Client side conf

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>
Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>

* 0 -> No caching

* Make it possible to disable cache on the remote client as well

* Comment

* Move ttl parsing up for in-proc to have it

---------

Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>
Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>
This commit is contained in:
Gabriel MABILLE
2025-04-11 10:09:47 +02:00
committed by GitHub
co-authored by Eric Leijonmarck Ieva
parent 0a8dccc19a
commit 45d6bfe7cf
4 changed files with 58 additions and 26 deletions
+11 -9
View File
@@ -70,7 +70,7 @@ func ProvideAuthZClient(
default:
sql := legacysql.NewDatabaseProvider(db)
rbacSettings := rbac.Settings{}
rbacSettings := rbac.Settings{CacheTTL: authCfg.cacheTTL}
if cfg != nil {
rbacSettings.AnonOrgRole = cfg.Anonymous.OrgRole
}
@@ -163,14 +163,16 @@ func newRemoteRBACClient(clientCfg *authzClientSettings, tracer trace.Tracer) (a
return nil, fmt.Errorf("failed to create authz client to remote server: %w", err)
}
client := authzlib.NewClient(
conn,
authzlib.WithCacheClientOption(cache.NewLocalCache(cache.Config{
Expiry: 30 * time.Second,
// Client side cache
var authzCache cache.Cache = &NoopCache{}
if clientCfg.cacheTTL != 0 {
authzCache = cache.NewLocalCache(cache.Config{
Expiry: clientCfg.cacheTTL,
CleanupInterval: 2 * time.Minute,
})),
authzlib.WithTracerClientOption(tracer),
)
})
}
client := authzlib.NewClient(conn, authzlib.WithCacheClientOption(authzCache), authzlib.WithTracerClientOption(tracer))
return client, nil
}
@@ -215,7 +217,7 @@ func RegisterRBACAuthZService(
tracer,
reg,
cache,
rbac.Settings{}, // anonymous org role can only be set in-proc
rbac.Settings{CacheTTL: cfg.CacheTTL}, // anonymous org role can only be set in-proc
)
srv := handler.GetServer()
+24 -5
View File
@@ -43,7 +43,11 @@ func folderCacheKey(namespace string) string {
return namespace + ".folders"
}
type cacheWrap[T any] struct {
type cacheWrap[T any] interface {
Get(ctx context.Context, key string) (T, bool)
Set(ctx context.Context, key string, value T)
}
type cacheWrapImpl[T any] struct {
cache cache.Cache
logger log.Logger
ttl time.Duration
@@ -51,11 +55,15 @@ type cacheWrap[T any] struct {
// cacheWrap is a wrapper around the authlib Cache that provides typed Get and Set methods
// it handles encoding/decoding for a specific type.
func newCacheWrap[T any](cache cache.Cache, logger log.Logger, ttl time.Duration) *cacheWrap[T] {
return &cacheWrap[T]{cache: cache, logger: logger, ttl: ttl}
func newCacheWrap[T any](cache cache.Cache, logger log.Logger, ttl time.Duration) cacheWrap[T] {
if ttl == 0 {
logger.Info("cache ttl is 0, using noop cache")
return &noopCache[T]{}
}
return &cacheWrapImpl[T]{cache: cache, logger: logger, ttl: ttl}
}
func (c *cacheWrap[T]) Get(ctx context.Context, key string) (T, bool) {
func (c *cacheWrapImpl[T]) Get(ctx context.Context, key string) (T, bool) {
logger := c.logger.FromContext(ctx)
var value T
@@ -76,7 +84,7 @@ func (c *cacheWrap[T]) Get(ctx context.Context, key string) (T, bool) {
return value, true
}
func (c *cacheWrap[T]) Set(ctx context.Context, key string, value T) {
func (c *cacheWrapImpl[T]) Set(ctx context.Context, key string, value T) {
logger := c.logger.FromContext(ctx)
data, err := json.Marshal(value)
@@ -90,3 +98,14 @@ func (c *cacheWrap[T]) Set(ctx context.Context, key string, value T) {
logger.Warn("failed to set to cache", "key", key, "error", err)
}
}
type noopCache[T any] struct{}
func (lc *noopCache[T]) Get(ctx context.Context, key string) (T, bool) {
var value T
return value, false
}
func (lc *noopCache[T]) Set(ctx context.Context, key string, value T) {
// no-op
}
+14 -11
View File
@@ -54,16 +54,19 @@ type Service struct {
sf *singleflight.Group
// Cache for user permissions, user team memberships and user basic roles
idCache *cacheWrap[store.UserIdentifiers]
permCache *cacheWrap[map[string]bool]
permDenialCache *cacheWrap[bool]
teamCache *cacheWrap[[]int64]
basicRoleCache *cacheWrap[store.BasicRole]
folderCache *cacheWrap[folderTree]
idCache cacheWrap[store.UserIdentifiers]
permCache cacheWrap[map[string]bool]
permDenialCache cacheWrap[bool]
teamCache cacheWrap[[]int64]
basicRoleCache cacheWrap[store.BasicRole]
folderCache cacheWrap[folderTree]
}
type Settings struct {
AnonOrgRole string
// CacheTTL is the time to live for the permission cache entries.
// Set to 0 to disable caching.
CacheTTL time.Duration
}
func NewService(
@@ -91,11 +94,11 @@ func NewService(
metrics: newMetrics(reg),
mapper: newMapper(),
idCache: newCacheWrap[store.UserIdentifiers](cache, logger, longCacheTTL),
permCache: newCacheWrap[map[string]bool](cache, logger, shortCacheTTL),
permDenialCache: newCacheWrap[bool](cache, logger, shortCacheTTL),
teamCache: newCacheWrap[[]int64](cache, logger, shortCacheTTL),
basicRoleCache: newCacheWrap[store.BasicRole](cache, logger, shortCacheTTL),
folderCache: newCacheWrap[folderTree](cache, logger, shortCacheTTL),
permCache: newCacheWrap[map[string]bool](cache, logger, settings.CacheTTL),
permDenialCache: newCacheWrap[bool](cache, logger, settings.CacheTTL),
teamCache: newCacheWrap[[]int64](cache, logger, settings.CacheTTL),
basicRoleCache: newCacheWrap[store.BasicRole](cache, logger, settings.CacheTTL),
folderCache: newCacheWrap[folderTree](cache, logger, settings.CacheTTL),
sf: new(singleflight.Group),
}
}
+9 -1
View File
@@ -2,6 +2,7 @@ package authz
import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/setting"
)
@@ -29,6 +30,8 @@ type authzClientSettings struct {
token string
tokenExchangeURL string
tokenNamespace string
cacheTTL time.Duration
}
func readAuthzClientSettings(cfg *setting.Cfg) (*authzClientSettings, error) {
@@ -41,6 +44,9 @@ func readAuthzClientSettings(cfg *setting.Cfg) (*authzClientSettings, error) {
}
s := &authzClientSettings{}
// Cache duration applies to the server cache in proc, so it's relevant for both modes.
s.cacheTTL = authzSection.Key("cache_ttl").MustDuration(30 * time.Second)
s.mode = mode
if s.mode == clientModeInproc {
return s, nil
@@ -48,6 +54,7 @@ func readAuthzClientSettings(cfg *setting.Cfg) (*authzClientSettings, error) {
s.remoteAddress = authzSection.Key("remote_address").MustString("")
s.certFile = authzSection.Key("cert_file").MustString("")
s.token = grpcClientAuthSection.Key("token").MustString("")
s.tokenNamespace = grpcClientAuthSection.Key("token_namespace").MustString("stacks-" + cfg.StackID)
s.tokenExchangeURL = grpcClientAuthSection.Key("token_exchange_url").MustString("")
@@ -61,7 +68,8 @@ func readAuthzClientSettings(cfg *setting.Cfg) (*authzClientSettings, error) {
}
type RBACServerSettings struct {
Folder FolderAPISettings
Folder FolderAPISettings
CacheTTL time.Duration
}
type FolderAPISettings struct {