crbench//

← all cases

AuthZService: improve authz caching

Tier 2 hard go · local · real merged PR from grafana/grafana #103633

Ground-truth defects

d2 · other · low
The test comment says the cached permissions 'allow access', but the map stores false for dashboards:uid:dash1, so checkPermission will still treat this scope as not allowed.
d3 · security · medium
The new permission-denial cache key concatenates namespace, user, action, name and parent with underscores, but underscores are legal in Grafana UIDs, so distinct tuples collide -- a resource named `alerts_prod` in folder `team` produces the same key as `alerts` in folder `prod_team`. A denial recorded for one then short-circuits the check for the other, returning not-allowed without evaluating permissions for the cache lifetime.

The change under review

diff
diff --git a/pkg/services/authz/rbac.go b/pkg/services/authz/rbac.go
index d4cd2b42f5..d3eca94232 100644
--- a/pkg/services/authz/rbac.go
+++ b/pkg/services/authz/rbac.go
@@ -98,7 +98,11 @@ func ProvideAuthZClient(
 			return ctx, nil
 		}))
 		authzv1.RegisterAuthzServiceServer(channel, server)
-		rbacClient := newRBACClient(channel, tracer)
+		rbacClient := authzlib.NewClient(
+			channel,
+			authzlib.WithCacheClientOption(&NoopCache{}),
+			authzlib.WithTracerClientOption(tracer),
+		)
 
 		if features.IsEnabledGlobally(featuremgmt.FlagZanzana) {
 			return zanzana.WithShadowClient(rbacClient, zanzanaClient, reg)
@@ -153,11 +157,7 @@ func newRemoteRBACClient(clientCfg *authzClientSettings, tracer trace.Tracer) (a
 		return nil, fmt.Errorf("failed to create authz client to remote server: %w", err)
 	}
 
-	return newRBACClient(conn, tracer), nil
-}
-
-func newRBACClient(conn grpc.ClientConnInterface, tracer trace.Tracer) authlib.AccessClient {
-	return authzlib.NewClient(
+	client := authzlib.NewClient(
 		conn,
 		authzlib.WithCacheClientOption(cache.NewLocalCache(cache.Config{
 			Expiry:          30 * time.Second,
@@ -165,6 +165,8 @@ func newRBACClient(conn grpc.ClientConnInterface, tracer trace.Tracer) authlib.A
 		})),
 		authzlib.WithTracerClientOption(tracer),
 	)
+
+	return client, nil
 }
 
 func RegisterRBACAuthZService(
@@ -233,3 +235,17 @@ func (t tokenExhangeRoundTripper) RoundTrip(r *http.Request) (*http.Response, er
 	r.Header.Set("X-Access-Token", "Bearer "+res.Token)
 	return t.rt.RoundTrip(r)
 }
+
+type NoopCache struct{}
+
+func (lc *NoopCache) Get(ctx context.Context, key string) ([]byte, error) {
+	return nil, cache.ErrNotFound
+}
+
+func (lc *NoopCache) Set(ctx context.Context, key string, data []byte, exp time.Duration) error {
+	return nil
+}
+
+func (lc *NoopCache) Delete(ctx context.Context, key string) error {
+	return nil
+}
diff --git a/pkg/services/authz/rbac/cache.go b/pkg/services/authz/rbac/cache.go
index 2da8410083..a8a67ec43c 100644
--- a/pkg/services/authz/rbac/cache.go
+++ b/pkg/services/authz/rbac/cache.go
@@ -27,6 +27,10 @@ func userPermCacheKey(namespace, userUID, action string) string {
 	return namespace + ".perm_" + userUID + "_" + action
 }
 
+func userPermDenialCacheKey(namespace, userUID, action, name, parent string) string {
+	return namespace + ".perm_" + userUID + "_" + action + "_" + name + "_" + parent
+}
+
 func userBasicRoleCacheKey(namespace, userUID string) string {
 	return namespace + ".basic_role_" + userUID
 }
diff --git a/pkg/services/authz/rbac/service.go b/pkg/services/authz/rbac/service.go
index 0c84c2d963..61a86c1a56 100644
--- a/pkg/services/authz/rbac/service.go
+++ b/pkg/services/authz/rbac/service.go
@@ -53,11 +53,12 @@ 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]
-	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]
 }
 
 func NewService(
@@ -81,6 +82,7 @@ func NewService(
 		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),
@@ -111,6 +113,29 @@ func (s *Service) Check(ctx context.Context, req *authzv1.CheckRequest) (*authzv
 		attribute.String("folder", checkReq.ParentFolder),
 	)
 
+	permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder)
+	if _, ok := s.permDenialCache.Get(ctx, permDenialKey); ok {
+		s.metrics.permissionCacheUsage.WithLabelValues("true", checkReq.Action).Inc()
+		s.metrics.requestCount.WithLabelValues("false", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc()
+		return &authzv1.CheckResponse{Allowed: false}, nil
+	}
+
+	cachedPerms, err := s.getCachedIdentityPermissions(ctx, checkReq.Namespace, checkReq.IdentityType, checkReq.UserUID, checkReq.Action)
+	if err == nil {
+		allowed, err := s.checkPermission(ctx, cachedPerms, checkReq)
+		if err != nil {
+			ctxLogger.Error("could not check permission", "error", err)
+			s.metrics.requestCount.WithLabelValues("true", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc()
+			return deny, err
+		}
+		if allowed {
+			s.metrics.permissionCacheUsage.WithLabelValues("true", checkReq.Action).Inc()
+			s.metrics.requestCount.WithLabelValues("false", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc()
+			return &authzv1.CheckResponse{Allowed: allowed}, nil
+		}
+	}
+	s.metrics.permissionCacheUsage.WithLabelValues("false", checkReq.Action).Inc()
+
 	permissions, err := s.getIdentityPermissions(ctx, checkReq.Namespace, checkReq.IdentityType, checkReq.UserUID, checkReq.Action)
 	if err != nil {
 		ctxLogger.Error("could not get user permissions", "subject", req.GetSubject(), "error", err)
@@ -125,6 +150,10 @@ func (s *Service) Check(ctx context.Context, req *authzv1.CheckRequest) (*authzv
 		return deny, err
 	}
 
+	if !allowed {
+		s.permDenialCache.Set(ctx, permDenialKey, true)
+	}
+
 	s.metrics.requestCount.WithLabelValues("false", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc()
 	return &authzv1.CheckResponse{Allowed: allowed}, nil
 }
@@ -148,11 +177,18 @@ func (s *Service) List(ctx context.Context, req *authzv1.ListRequest) (*authzv1.
 		attribute.String("action", listReq.Action),
 	)
 
-	permissions, err := s.getIdentityPermissions(ctx, listReq.Namespace, listReq.IdentityType, listReq.UserUID, listReq.Action)
-	if err != nil {
-		ctxLogger.Error("could not get user permissions", "subject", req.GetSubject(), "error", err)
-		s.metrics.requestCount.WithLabelValues("true", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc()
-		return nil, err
+	permissions, err := s.getCachedIdentityPermissions(ctx, listReq.Namespace, listReq.IdentityType, listReq.UserUID, listReq.Action)
+	if err == nil {
+		s.metrics.permissionCacheUsage.WithLabelValues("true", listReq.Action).Inc()
+	} else {
+		s.metrics.permissionCacheUsage.WithLabelValues("false", listReq.Action).Inc()
+
+		permissions, err = s.getIdentityPermissions(ctx, listReq.Namespace, listReq.IdentityType, listReq.UserUID, listReq.Action)
+		if err != nil {
+			ctxLogger.Error("could not get user permissions", "subject", req.GetSubject(), "error", err)
+			s.metrics.requestCount.WithLabelValues("true", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc()
+			return nil, err
+		}
 	}
 
 	resp, err := s.listPermission(ctx, permissions, listReq)
@@ -303,6 +339,34 @@ func (s *Service) getIdentityPermissions(ctx context.Context, ns types.Namespace
 	}
 }
 
+func (s *Service) getCachedIdentityPermissions(ctx context.Context, ns types.NamespaceInfo, idType types.IdentityType, userID, action string) (map[string]bool, error) {
+	ctx, span := s.tracer.Start(ctx, "authz_direct_db.service.getCachedIdentityPermissions")
+	defer span.End()
+
+	switch idType {
+	case types.TypeAnonymous:
+		anonPermKey := anonymousPermCacheKey(ns.Value, action)
+		if cached, ok := s.permCache.Get(ctx, anonPermKey); ok {
+			return cached, nil
+		}
+		return nil, cache.ErrNotFound
+	case types.TypeRenderService:
+		return nil, cache.ErrNotFound
+	case types.TypeUser, types.TypeServiceAccount:
+		userIdentifiers, err := s.GetUserIdentifiers(ctx, ns, userID)
+		if err != nil {
+			return nil, err
+		}
+		userPermKey := userPermCacheKey(ns.Value, userIdentifiers.UID, action)
+		if cached, ok := s.permCache.Get(ctx, userPermKey); ok {
+			return cached, nil
+		}
+		return nil, cache.ErrNotFound
+	default:
+		return nil, fmt.Errorf("unsupported identity type: %s", idType)
+	}
+}
+
 func (s *Service) getUserPermissions(ctx context.Context, ns types.NamespaceInfo, userID, action string, actionSets []string) (map[string]bool, error) {
 	ctx, span := s.tracer.Start(ctx, "authz_direct_db.service.getUserPermissions")
 	defer span.End()
@@ -313,12 +377,6 @@ func (s *Service) getUserPermissions(ctx context.Context, ns types.NamespaceInfo
 	}
 
 	userPermKey := userPermCacheKey(ns.Value, userIdentifiers.UID, action)
-	if cached, ok := s.permCache.Get(ctx, userPermKey); ok {
-		s.metrics.permissionCacheUsage.WithLabelValues("true", action).Inc()
-		return cached, nil
-	}
-	s.metrics.permissionCacheUsage.WithLabelValues("false", action).Inc()
-
 	res, err, _ := s.sf.Do(userPermKey+"_getUserPermissions", func() (interface{}, error) {
 		basicRoles, err := s.getUserBasicRole(ctx, ns, userIdentifiers)
 		if err != nil {
@@ -363,9 +421,6 @@ func (s *Service) getAnonymousPermissions(ctx context.Context, ns types.Namespac
 	defer span.End()
 
 	anonPermKey := anonymousPermCacheKey(ns.Value, action)
-	if cached, ok := s.permCache.Get(ctx, anonPermKey); ok {
-		return cached, nil
-	}
 	res, err, _ := s.sf.Do(anonPermKey+"_getAnonymousPermissions", func() (interface{}, error) {
 		permissions, err := s.permissionStore.GetUserPermissions(ctx, ns, store.PermissionsQuery{Action: action, ActionSets: actionSets, Role: "Viewer"})
 		if err != nil {
diff --git a/pkg/services/authz/rbac/service_test.go b/pkg/services/authz/rbac/service_test.go
index b9df0d9232..454d9406c6 100644
--- a/pkg/services/authz/rbac/service_test.go
+++ b/pkg/services/authz/rbac/service_test.go
@@ -339,14 +339,6 @@ func TestService_getUserPermissions(t *testing.T) {
 	}
 
 	testCases := []testCase{
-		{
-			name: "should return permissions from cache if available",
-			permissions: []accesscontrol.Permission{
-				{Action: "dashboards:read", Scope: "dashboards:uid:some_dashboard"},
-			},
-			cacheHit:      true,
-			expectedPerms: map[string]bool{"dashboards:uid:some_dashboard": true},
-		},
 		{
 			name: "should return permissions from store if not in cache",
 			permissions: []accesscontrol.Permission{
@@ -898,6 +890,111 @@ func TestService_Check(t *testing.T) {
 	})
 }
 
+func TestService_CacheCheck(t *testing.T) {
+	callingService := authn.NewAccessTokenAuthInfo(authn.Claims[authn.AccessTokenClaims]{
+		Claims: jwt.Claims{
+			Subject:  types.NewTypeID(types.TypeAccessPolicy, "some-service"),
+			Audience: []string{"authzservice"},
+		},
+		Rest: authn.AccessTokenClaims{Namespace: "org-12"},
+	})
+
+	ctx := types.WithAuthInfo(context.Background(), callingService)
+	userID := &store.UserIdentifiers{UID: "test-uid", ID: 1}
+
+	t.Run("Allow based on cached permissions", func(t *testing.T) {
+		s := setupService()
+
+		s.idCache.Set(ctx, userIdentifierCacheKey("org-12", "test-uid"), *userID)
+		s.permCache.Set(ctx, userPermCacheKey("org-12", "test-uid", "dashboards:read"), map[string]bool{"dashboards:uid:dash1": true})
+
+		resp, err := s.Check(ctx, &authzv1.CheckRequest{
+			Namespace: "org-12",
+			Subject:   "user:test-uid",
+			Group:     "dashboard.grafana.app",
+			Resource:  "dashboards",
+			Verb:      "get",
+			Name:      "dash1",
+		})
+		require.NoError(t, err)
+		assert.True(t, resp.Allowed)
+	})
+	t.Run("Fallback to the database on cache miss", func(t *testing.T) {
+		s := setupService()
+
+		// Populate database permission but not the cache
+		store := &fakeStore{
+			userID:          userID,
+			userPermissions: []accesscontrol.Permission{{Action: "dashboards:read", Scope: "dashboards:uid:dash2"}},
+		}
+
+		s.store = store
+		s.permissionStore = store
+
+		s.idCache.Set(ctx, userIdentifierCacheKey("org-12", "test-uid"), *userID)
+
+		resp, err := s.Check(ctx, &authzv1.CheckRequest{
+			Namespace: "org-12",
+			Subject:   "user:test-uid",
+			Group:     "dashboard.grafana.app",
+			Resource:  "dashboards",
+			Verb:      "get",
+			Name:      "dash2",
+		})
+		require.NoError(t, err)
+		assert.True(t, resp.Allowed)
+	})
+	t.Run("Fallback to the database on outdated cache", func(t *testing.T) {
+		s := setupService()
+
+		store := &fakeStore{
+			userID:          userID,
+			userPermissions: []accesscontrol.Permission{{Action: "dashboards:read", Scope: "dashboards:uid:dash2"}},
+		}
+
+		s.store = store
+		s.permissionStore = store
+
+		s.idCache.Set(ctx, userIdentifierCacheKey("org-12", "test-uid"), *userID)
+		// The cache does not have the permission for dash2 (outdated)
+		s.permCache.Set(ctx, userPermCacheKey("org-12", "test-uid", "dashboards:read"), map[string]bool{"dashboards:uid:dash1": true})
+
+		resp, err := s.Check(ctx, &authzv1.CheckRequest{
+			Namespace: "org-12",
+			Subject:   "user:test-uid",
+			Group:     "dashboard.grafana.app",
+			Resource:  "dashboards",
+			Verb:      "get",
+			Name:      "dash2",
+		})
+		require.NoError(t, err)
+		assert.True(t, resp.Allowed)
+	})
+	t.Run("Should deny on explicit cache deny entry", func(t *testing.T) {
+		s := setupService()
+
+		s.idCache.Set(ctx, userIdentifierCacheKey("org-12", "test-uid"), *userID)
+
+		// Explicitly deny access to the dashboard
+		s.permDenialCache.Set(ctx, userPermDenialCacheKey("org-12", "test-uid", "dashboards:read", "dash1", "fold1"), true)
+
+		// Allow access to the dashboard to prove this is not checked
+		s.permCache.Set(ctx, userPermCacheKey("org-12", "test-uid", "dashboards:read"), map[string]bool{"dashboards:uid:dash1": false})
+
+		resp, err := s.Check(ctx, &authzv1.CheckRequest{
+			Namespace: "org-12",
+			Subject:   "user:test-uid",
+			Group:     "dashboard.grafana.app",
+			Resource:  "dashboards",
+			Verb:      "get",
+			Name:      "dash1",
+			Folder:    "fold1",
+		})
+		require.NoError(t, err)
+		assert.False(t, resp.Allowed)
+	})
+}
+
 func TestService_List(t *testing.T) {
 	callingService := authn.NewAccessTokenAuthInfo(authn.Claims[authn.AccessTokenClaims]{
 		Claims: jwt.Claims{
@@ -1191,6 +1288,40 @@ func TestService_List(t *testing.T) {
 	})
 }
 
+func TestService_CacheList(t *testing.T) {
+	callingService := authn.NewAccessTokenAuthInfo(authn.Claims[authn.AccessTokenClaims]{
+		Claims: jwt.Claims{
+			Subject:  types.NewTypeID(types.TypeAccessPolicy, "some-service"),
+			Audience: []string{"authzservice"},
+		},
+		Rest: authn.AccessTokenClaims{Namespace: "org-12"},
+	})
+
+	t.Run("List based on cached permissions", func(t *testing.T) {
+		s := setupService()
+		ctx := types.WithAuthInfo(context.Background(), callingService)
+		userID := &store.UserIdentifiers{UID: "test-uid", ID: 1}
+		s.idCache.Set(ctx, userIdentifierCacheKey("org-12", "test-uid"), *userID)
+		s.permCache.Set(ctx,
+			userPermCacheKey("org-12", "test-uid", "dashboards:read"),
+			map[string]bool{"dashboards:uid:dash1": true, "dashboards:uid:dash2": true, "folders:uid:fold1": true},
+		)
+		s.identityStore = &fakeIdentityStore{}
+
+		resp, err := s.List(ctx, &authzv1.ListRequest{
+			Namespace: "org-12",
+			Subject:   "user:test-uid",
+			Group:     "dashboard.grafana.app",
+			Resource:  "dashboards",
+			Verb:      "list",
+		})
+
+		require.NoError(t, err)
+		require.ElementsMatch(t, resp.Items, []string{"dash1", "dash2"})
+		require.ElementsMatch(t, resp.Folders, []string{"fold1"})
+	})
+}
+
 func setupService() *Service {
 	cache := cache.NewLocalCache(cache.Config{Expiry: 5 * time.Minute, CleanupInterval: 5 * time.Minute})
 	logger := log.New("authz-rbac-service")
@@ -1202,6 +1333,7 @@ func setupService() *Service {
 		metrics:         newMetrics(nil),
 		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, longCacheTTL),
 		folderCache:     newCacheWrap[folderTree](cache, logger, shortCacheTTL),

Leaderboard for this case

hard · 0 of 9 bots fully caught it (0% solve rate) · 44% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Cubic partial 1/2 66.7% 2 0
2 cursor partial 1/2 66.7% 1 0
3 Drape (Deep Review) partial 1/2 66.7% 2 0
4 Drape (Review) partial 1/2 66.7% 2 0
5 greptile partial 1/2 66.7% 2 0
6 Mjolnir (Opus 5.5) partial 1/2 66.7% 2 0
7 qodo partial 1/2 66.7% 2 0
8 Claude Code (Opus 5.5) partial 1/2 66.7% 4 1
9 Mjolnir (Sonnet 5.5) miss 0/2 0.0% 1 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ off by one
valid · impact medium
The denial cache is checked before anything else, and every DB-computed deny is written to it for shortCacheTTL. Nothing invalidates these entries. A deny cached after a DB fallback can therefore outlive the original permCache entry and block a later grant for up to 30s, even though the same change added a fallback meant to handle stale cached permissions. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
invalid
checkPermission only fails on an unsupported resource in the mapper or a buildFolderTree error, and neither depends on the contents of the cached scope map. A DB fallback would run the same check and hit the same error, so a malformed or stale cache entry cannot produce the claimed hard error. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · impact low
The in-process client used to have a 30s local cache and now uses a no-op cache. Every check therefore goes through the in-proc service, doing the denial lookup, the identifier lookup and the permission-cache lookup each time. This is real added overhead, though the server-side caches limit it. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
pkg/services/authz/rbac/service.go:153
Every DB-computed deny is now cached per (user, action, name, folder) for shortCacheTTL, and the denial cache is read before anything else. That undoes the 'fall back to the DB when the cached permissions say no' path added in the same change. After a user is denied once, a grant made afterwards (new role, team membership or resource permission) is ignored for up to the full TTL, and the DB is never consulted. Nothing invalidates these entries when permissions change, so the new 'outdated cache' fallback only helps resources the user has never been denied on.
pkg/services/authz/rbac/cache.go:30
userPermDenialCacheKey joins name and parent with '_' and no escaping, but UIDs can contain underscores. For example, dashboard 'a' in folder 'b_c' and dashboard 'a_b' in folder 'c' both produce '..._a_b_c'. A cached deny for one resource then wrongly denies access to the other. The key also shares the '.perm_' prefix and the same backing cache as userPermCacheKey, so a crafted UID/folder combination can overwrite another user's permission-map entry (the type mismatch turns it into a decode failure and a cache miss).
pkg/services/authz/rbac/service.go:127
When checkPermission fails on the cached permission map, Check returns deny with an error right away instead of falling back to the fresh DB lookup. A malformed or stale cache entry therefore turns into a hard error rather than being recomputed.
pkg/services/authz/rbac.go:101
The in-process RBAC client now uses NoopCache instead of the 30s local cache, so every access check makes a full in-process gRPC round trip through the service: denial-cache lookup, identifier lookup, permission-cache lookup, plus a second GetUserIdentifiers call on a miss. That raises per-request overhead on hot paths that used to be served from the client-side cache.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ exact
valid · impact medium
The new denial key leaves out the identity type. Both "anonymous:0" and "render:0" parse to UserUID "0", so they produce the same key. An anonymous denial is therefore cached and returned for renderer checks, even though getRendererPermissions would have granted "*" for dashboards:read. This short-circuit was added by this change. [grounded: diff] [consensus 5/5: valid=5]
valid · matches d3 · impact medium
raw comments (3)
pkg/services/authz/rbac/service.go:116
<!-- cubic:v=4dbc4b6c-a195-4537-a826-13780f0a5735 --> <!-- cubic:review-run=7b25a76e-86a8-536e-b6ac-1164702b9b98 --> <!-- metadata:{"confidence":10} --> P2: When an anonymous check for a dashboard is denied, the cached denial also applies to `render:0` because the key omits the identity type. Renderer reads should match the wildcard permission, so include `checkReq.IdentityType` in the denial key. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/services/authz/rbac/service.go, line 116: <comment>When an anonymous check for a dashboard is denied, the cached denial also applies to `render:0` because the key omits the identity type. Renderer reads should match the wildcard permission, so include `checkReq.IdentityType` in the denial key.</comment> <file context> @@ -111,6 +113,29 @@ func (s *Service) Check(ctx context.Context, req *authzv1.CheckRequest) (*authzv attribute.String("folder", checkReq.ParentFolder), ) + permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder) + if _, ok := s.permDenialCache.Get(ctx, permDenialKey); ok { + s.metrics.permissionCacheUsage.WithLabelValues("true", checkReq.Action).Inc() </file context> ``` </details>
pkg/services/authz/rbac/cache.go:31
<!-- cubic:v=9c9804b0-d67a-4177-b189-3c06b2202114 --> <!-- cubic:review-run=7b25a76e-86a8-536e-b6ac-1164702b9b98 --> <!-- metadata:{"confidence":10} --> P2: When resource UIDs contain underscores, this denial key is ambiguous and reuses one resource's denial for another resource/folder pair. Encode or length-delimit each key component before caching the decision. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/services/authz/rbac/cache.go, line 31: <comment>When resource UIDs contain underscores, this denial key is ambiguous and reuses one resource's denial for another resource/folder pair. Encode or length-delimit each key component before caching the decision.</comment> <file context> @@ -27,6 +27,10 @@ func userPermCacheKey(namespace, userUID, action string) string { } +func userPermDenialCacheKey(namespace, userUID, action, name, parent string) string { + return namespace + ".perm_" + userUID + "_" + action + "_" + name + "_" + parent +} + </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **2 issues found** across 4 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="pkg/services/authz/rbac/service.go"> <violation number="1" location="pkg/services/authz/rbac/service.go:116"> P2: When an anonymous check for a dashboard is denied, the cached denial also applies to `render:0` because the key omits the identity type. Renderer reads should match the wildcard permission, so include `checkReq.IdentityType` in the denial key.</violation> </file> <file name="pkg/services/authz/rbac/cache.go"> <violation number="1" location="pkg/services/authz/rbac/cache.go:31"> P2: When resource UIDs contain underscores, this denial key is ambiguous and reuses one resource's denial for another resource/folder pair. Encode or length-delimit each key component before caching the decision.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/39/ai_pr_review_github_delivery_2f859f4a698204b727d5ab870c6418a9a744a690d550eec6b85f0c3643c5fefe?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F39)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_2f859f4a698204b727d5ab870c6418a9a744a690d550eec6b85f0c3643c5fefe:144cc6c8529157eb48776cfb5f7d531f77599933:7b25a76e-86a8-536e-b6ac-1164702b9b98 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ exact
valid · matches d3 · impact medium
raw comments (2)
pkg/services/authz/rbac/cache.go:32
### Denial cache keys can collide **Medium Severity** <!-- DESCRIPTION START --> `userPermDenialCacheKey` joins `name` and `parent` with underscores, and Grafana UIDs may contain `_`. Different resource and folder pairs can produce the same key, so a cached deny for one pair can make `Check` deny the other until the denial TTL expires, even when `permCache` would allow it. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: ef9a27db-3bde-430b-8fbd-dc2b9e20b649 --> <!-- LOCATIONS START pkg/services/authz/rbac/cache.go#L29-L32 pkg/services/authz/rbac/service.go#L115-L121 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`pkg/services/authz/rbac/service.go#L115-L121`](https://github.com/drape-io/crbench-cursor-2026-09/blob/e7def98911df7556f44d5e6d0869103b40c2b03e/pkg/services/authz/rbac/service.go#L115-L121) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE3MDBjZTVhLTRiNDMtNDg5Zi05NjFlLWY1NDAzYTM0NzJiZCIsImVuY3J5cHRpb25LZXkiOiJILWVrVnBURVpwV1U2MUJrbkljOEQwb0JVd2pEcHpCaGE4ajBWZy1paVZ3IiwiYnJhbmNoIjoidDItZ3JhZmFuYS0xMDM2MzMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE3MDBjZTVhLTRiNDMtNDg5Zi05NjFlLWY1NDAzYTM0NzJiZCIsImVuY3J5cHRpb25LZXkiOiJILWVrVnBURVpwV1U2MUJrbkljOEQwb0JVd2pEcHpCaGE4ajBWZy1paVZ3IiwiYnJhbmNoIjoidDItZ3JhZmFuYS0xMDM2MzMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo0MCwiY29tbWl0U2hhIjoiZTdkZWY5ODkxMWRmNzU1NmY0NGQ1ZTZkMDg2OTEwM2I0MGMyYjAzZSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e7def98911df7556f44d5e6d0869103b40c2b03e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTplMzU1YmZmMC02ODIyLTQwOTAtYTk2MC1kNTk5NzJjZDM4Y2EiLCJlbmNyeXB0aW9uS2V5IjoiRURGMmNBdmZCZDY4YkJ4SG5EdVU2djN3TkhOWlhlbzV5TEN2bGVUWDFHWSIsImJyYW5jaCI6InQyLWdyYWZhbmEtMTAzNjMzIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e7def98911df7556f44d5e6d0869103b40c2b03e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · impact medium
The denial key is built from namespace, UID, action, name and folder only. Subjects "anonymous:0" and "render:0" both parse to UserUID "0", so they get the same key. A denial cached for an anonymous subject is checked before getRendererPermissions runs, so the renderer is wrongly denied even though it would normally get "*" access. Before this change the renderer was always allowed. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
pkg/services/authz/rbac/cache.go:31
**Denial cache key collides for names with underscores** `userPermDenialCacheKey` joins name and folder with `_`, which UIDs may contain, so a denial for name `a_b` in folder `c` also denies name `a` in folder `b_c` until the TTL expires. Use a delimiter UIDs cannot contain, or length-prefix each part. ``` pkg/services/authz/rbac/cache.go:30 func userPermDenialCacheKey(namespace, userUID, action, name, parent string) string { pkg/services/authz/rbac/cache.go:31 return namespace + ".perm_" + userUID + "_" + action + "_" + name + "_" + parent pkg/services/authz/rbac/cache.go:32 } pkg/services/authz/rbac/service.go:116 permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder) pkg/services/authz/rbac/service.go:226 Name: req.GetName(), pkg/services/authz/rbac/service.go:227 ParentFolder: req.GetFolder(), ```
pkg/services/authz/rbac/service.go:116
**Renderer denied after anonymous denial cached** The denial cache key has no identity type, and anonymous and render-service subjects both use UID "0". So when an anonymous user is denied a dashboard, the renderer is also denied that dashboard until the cache entry expires, even though it normally has `*` access. Include `checkReq.IdentityType` in `userPermDenialCacheKey`. ``` pkg/services/authz/rbac/service.go:116 permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder) pkg/services/authz/rbac/service.go:117 if _, ok := s.permDenialCache.Get(ctx, permDenialKey); ok { pkg/services/authz/rbac/service.go:118 s.metrics.permissionCacheUsage.WithLabelValues("true", checkReq.Action).Inc() pkg/services/authz/rbac/service.go:119 s.metrics.requestCount.WithLabelValues("false", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc() pkg/services/user/identity.go:295 case u.IsAnonymous: pkg/services/user/identity.go:296 return claims.TypeAnonymous, "0" pkg/services/user/identity.go:297 case u.AuthenticatedBy == "render" && u.UserID == 0: pkg/services/user/identity.go:298 return claims.TypeRenderService, "0" pkg/services/authn/clients/render.go:43 if renderUsr.UserID <= 0 { pkg/services/authn/clients/render.go:44 identityType := claims.TypeAnonymous ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ off by one
valid · impact low
The denial cache is checked first and is set on every DB-backed denial with no invalidation. A permission granted after a denial is therefore ignored for up to shortCacheTTL (30s), and the new DB-fallback path never runs for that resource. The window is bounded by the TTL and matches the staleness the old permCache-first lookup already had, so the impact is low. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
valid · matches d3 · impact medium
raw comments (2)
pkg/services/authz/rbac/service.go:153
**Cached denials block newly granted access** A denied Check stores a denial entry that is read before the permission cache and the database. Nothing clears it, so a permission granted afterwards is still denied until the entry expires. Drop the denial cache, or clear it when the user's permission cache is refreshed. ``` pkg/services/authz/rbac/service.go:116 permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder) pkg/services/authz/rbac/service.go:117 if _, ok := s.permDenialCache.Get(ctx, permDenialKey); ok { pkg/services/authz/rbac/service.go:118 s.metrics.permissionCacheUsage.WithLabelValues("true", checkReq.Action).Inc() pkg/services/authz/rbac/service.go:119 s.metrics.requestCount.WithLabelValues("false", "true", req.GetVerb(), req.GetGroup(), req.GetResource()).Inc() ```
pkg/services/authz/rbac/cache.go:30
**Denial cache keys can collide** `userPermDenialCacheKey` joins name and parent with `_` and no escaping. Different (name, folder) pairs whose values contain underscores produce the same key, so a denial for one resource is applied to another that may be allowed. Use an unambiguous separator, or hash or length-prefix the name and folder fields. ``` pkg/services/authz/rbac/cache.go:30 func userPermDenialCacheKey(namespace, userUID, action, name, parent string) string { pkg/services/authz/rbac/cache.go:31 return namespace + ".perm_" + userUID + "_" + action + "_" + name + "_" + parent pkg/services/authz/rbac/cache.go:32 } pkg/services/authz/rbac/service.go:116 permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder) ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · impact low
The new denial cache is checked first and returns false without consulting permissions. Nothing invalidates it, so access granted after a denial stays denied until the shortCacheTTL (30s) runs out. The old permCache early-return had similar staleness, but this change removes that path and adds a new stale-deny path in its place, so the impact is a short, TTL-bounded delay. [grounded: diff] [consensus 3/5: valid=3, invalid=2]
raw comments (3)
pkg/services/authz/rbac/cache.go:31
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Denial cache keys collide** The key does not include the identity type and joins request fields with underscores. For example, `(name="a_b", parent="c")` and `(name="a", parent="b_c")` produce the same key. A user and service account with the same UID also share a key. Because `Check` returns a cached denial before evaluating permissions, a denial for one subject or resource can incorrectly deny another. Encode each field unambiguously and include the identity type.
pkg/services/authz/rbac/service.go:154
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Granted access remains denied** A cached denial is not invalidated when permissions, team membership, basic role, or folder authorization changes. After a denied request is cached, granting the required access still makes `Check` return false without consulting the updated permissions. Newly granted access can therefore remain unavailable for the full 30-second cache TTL.
PR-level
<h3>Greptile Summary</h3> This PR moves permission-cache lookup into the Check and List entry points, adds a short-lived per-request denial cache, and disables authzlib client caching for the embedded RBAC service while retaining it for remote clients. - Cached permissions can now satisfy Check and List before database access. - Denied Check results are cached for 30 seconds. - The new denial-cache key can conflate distinct authorization requests. - Denial entries are not invalidated when access is granted. <h3>Confidence Score: 3/5</h3> The PR is not safe to merge until denial-cache keys are isolated correctly and stale denials are invalidated when authorization state changes. Distinct subjects or resource tuples can share a denial entry, and a legitimate permission grant can remain ineffective for 30 seconds because cached denials bypass current permission evaluation. **Files Needing Attention:** pkg/services/authz/rbac/cache.go, pkg/services/authz/rbac/service.go <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | pkg/services/authz/rbac/cache.go | Adds a denial-cache key whose delimiter-based encoding and missing identity type permit collisions between distinct authorization requests. | | pkg/services/authz/rbac/service.go | Adds cache-first authorization and negative-result caching, but denial entries can remain stale after access is granted. | | pkg/services/authz/rbac.go | Replaces embedded authzlib client caching with a no-op cache while retaining local caching for remote clients. | | pkg/services/authz/rbac/service_test.go | Adds coverage for cached Check and List behavior, but does not exercise denial-key isolation or permission changes after a denial. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Check request] --> B{Denial key cached?} B -- Yes --> C[Return denied] B -- No --> D{Permissions cached?} D -- Yes --> E{Cached permissions allow?} E -- Yes --> F[Return allowed] E -- No --> G[Load current permissions] D -- No --> G G --> H{Current permissions allow?} H -- Yes --> F H -- No --> I[Cache denial for 30 seconds] I --> C ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update pkg/services/authz/rbac.go and 3 ..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/0ed336b7c40399209a028b1d033c1d124e847fbe) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284455)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · impact low
The new denial key joins name and parent with '_' and nothing escapes them, so name 'a_b' with folder 'c' gets the same key as name 'a' with folder 'b_c'. Check returns Allowed:false on any denial-cache hit before it looks up permissions, so a denial cached for one resource can wrongly deny the other for the TTL. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
pkg/services/authz/rbac/cache.go:30
[P3] Denial cache key can collide across different name/folder pairs `userPermDenialCacheKey` joins `name` and `parent` with `_`. Grafana dashboard and folder UIDs are allowed to contain `_`, so two different requests can produce the same key. For example, `name="a_b", parent="c"` and `name="a", parent="b_c"` both end in `..._a_b_c`. If one of those checks is denied, `Check` puts the denial in `permDenialCache`, and the other check then returns `Allowed: false` straight from that cache for up to `shortCacheTTL`, even when the user's permissions allow it. This only happens when UIDs line up like this, and the effect is a wrong denial, not a wrong grant. A separator that UIDs can't contain, or encoding each part, would prevent it.
pkg/services/authz/rbac/cache.go:30
[P2] The denial cache key can collide when UIDs contain underscores, causing wrong denials `userPermDenialCacheKey` joins `name` and `parent` with `_`, but Grafana dashboard and folder UIDs may contain underscores. So different (name, folder) pairs can produce the same key. For example, name `a_b` in folder `c` and name `a` in folder `b_c` both become `‹ns›.perm_‹uid›_‹action›_a_b_c`. In `Check`, a hit in `permDenialCache` returns `Allowed: false` before any permission lookup. A denial cached for one resource therefore wrongly denies the other resource for the same user and action for the 30s TTL, even if the user does have access to it. This needs a user to be denied on one resource and then check a second resource whose UIDs happen to collide, so it is rare, but it is a real authorization error. A separator that can't appear in UIDs, or encoding each part (e.g. adding length prefixes), would make the key unambiguous.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✗ —
valid · impact medium
Before the change, getUserPermissions returned the cached permission set, so a denied check never touched the DB. Now, when the cached set denies, Check falls through to getIdentityPermissions, which no longer reads permCache. That means a permissionStore.GetUserPermissions query runs for every distinct denied (name, folder) pair within each 30s denial-cache window. Basic roles and teams are still cached, so 'full reload' overstates it, but the permission-store query is a real regression. [grounded: diff] [consensus 3/3: valid=3]
raw comments (1)
pkg/services/authz/rbac/service.go:134
[P2] Every distinct denied Check now forces a full permission reload from the DB When the cached permissions deny, Check falls through to `getIdentityPermissions`. This diff also removed the `permCache` lookup from `getUserPermissions` and `getAnonymousPermissions`, so that call always runs the basic-role, team and permission-store queries (collapsed only by singleflight) and overwrites the cache. The only guard is `permDenialCache`, which is keyed per (user, action, name, folder). A user whose cached permissions don't cover many resources, such as a limited-access user listing dashboards through per-item Checks, therefore causes one full DB permission fetch per distinct denied name or folder within each 30s window. Previously a cached permission set answered all of those denials without touching the DB. The load grows with the number of distinct denied resources, not the number of users, so a user with narrow access can generate heavy DB traffic
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ exact
valid · impact medium
The denial key leaves out the identity type. Both "anonymous:0" and "render:0" parse to UserUID "0", so they produce the same key. When an anonymous dashboard check is denied, a denial entry is written under that key. A renderer check for the same dashboard then hits that entry and is denied before getRendererPermissions is reached, even though the renderer has a wildcard grant. Before this change, renderer checks never consulted a shared denial cache. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (4)
pkg/services/authz/rbac/service.go:117
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Anonymous denials block rendering <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>Check</i></b> builds <b><i>permDenialKey</i></b> without <b><i>checkReq.IdentityType</i></b> and returns a denial before loading type-specific permissions. Anonymous and renderer subjects both use identifier <b><i>0</i></b>, so an anonymous dashboard denial in an organization suppresses the renderer&#x27;s wildcard read grant for the same dashboard until the 30-second entry expires. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Permission-denial cache keys omit the identity type, allowing identities with the same textual identifier to share denials. Anonymous and renderer identities both use `0`, despite having different authorization behavior. ## Fix Focus Areas - pkg/services/authz/rbac/cache.go[30-32] - pkg/services/authz/rbac/service.go[116-117] - pkg/services/authz/rbac/service.go[153-155] ## Recommended Fix Add the identity type to `userPermDenialCacheKey` and pass `checkReq.IdentityType` at every lookup and write. Add a regression test that caches a denial for `anonymous:0` and verifies that `render:0` still receives its renderer-specific dashboard read permission. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
pkg/services/authz/rbac/cache.go:31
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 2\. A denial blocks a different object <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>userPermDenialCacheKey</i></b> concatenates the object name and parent folder with <b><i>_</i></b>, without escaping or length-prefixing either value. Because underscores are accepted in UIDs, a denial for <b><i>(a_b,c)</i></b> has the same key as <b><i>(a,b_c)</i></b> and makes the second object fail at the cache lookup even when its permissions allow it. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The denial-cache key uses underscore delimiters for variable fields that may themselves contain underscores. Different object and parent-folder pairs can therefore produce an identical key and share a denial. ## Fix Focus Areas - pkg/services/authz/rbac/cache.go[30-32] - pkg/services/authz/rbac/service_test.go[973-995] ## Recommended Fix Construct denial keys with an unambiguous encoding, such as length-prefixed fields or serialization followed by a hash. Add a regression test proving that `(name=a_b, parent=c)` and `(name=a, parent=b_c)` remain independent. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Improve RBAC cache freshness and denial handling <code>🐞 Bug fix</code> <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 20-40 Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Disables redundant in-process client caching while retaining remote client caching. >• Revalidates cached permission misses and briefly caches confirmed denials. >• Covers cache hits, misses, stale entries, denials, and list requests. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD A["AuthZ request"] --> B{"Denial cached?"} B -->|Yes| C["Deny response"] B -->|No| D{"Permission cache?"} D -->|Allows| E["Allow response"] D -->|Miss or stale| F[("Permission store")] --> G{"Permission allows?"} G -->|Yes| E G -->|No| H["Cache denial"] --> C subgraph Legend direction LR _step["Processing step"] ~~~ _decision{"Decision"} ~~~ _store[("Data store")] end ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Event-driven cache invalidation</b></summary> <dl> <dd> - ➕ Provides fresher authorization decisions after permission changes - ➕ Avoids database fallback for every unconfirmed denial - ➖ Requires reliable permission-change events across all stores - ➖ Adds distributed invalidation and failure-handling complexity </dd> </dl> </details> <details> <summary><b>2. Cache resource-level decisions only</b></summary> <dl> <dd> - ➕ Makes check lookups direct and treats allows and denials uniformly - ➕ Avoids reevaluating full permission maps for repeated checks - ➖ Creates substantially more cache entries - ➖ Does not efficiently support list requests - ➖ Still requires an invalidation or bounded-staleness strategy </dd> </dl> </details> >**Recommendation:** The PR&#x27;s layered strategy is appropriate as an incremental fix: disable duplicate in-process caching, trust cached allows, verify uncertain denials against the authoritative store, and suppress repeated denied lookups with a short TTL. Event-driven invalidation could provide stronger freshness later, but it is substantially broader than this change. </dd> </dl> </details> <details> <summary> Files changed (4) <code> +240 / -33 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (1) <code> +4 / -0 </code></summary> <dl> <dd> <details> <summary>cache.go<code>Add resource-specific denial cache keys</code> <code>+4/-0</code></summary> <br/> >Add resource-specific denial cache keys > ><pre> >• Adds a denial key combining namespace, user, action, resource name, and parent folder. This isolates short-lived negative authorization decisions to an exact request scope. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/39/files#diff-9e82c88f61b8c7a6b15ef26d13017e53c4b791558b3b5ebe80a419036b575757'>pkg/services/authz/rbac/cache.go</a> </details> </dd> </dl> </details> <details> <summary>Bug fix (2) <code> +96 / -25 </code></summary> <dl> <dd> <details> <summary>rbac.go<code>Disable duplicate caching for the in-process RBAC client</code> <code>+22/-6</code></summary> <br/> >Disable duplicate caching for the in-process RBAC client > ><pre> >• Constructs the in-process authz client with a no-op cache so the server owns cache freshness decisions. Remote clients retain their 30-second local cache, and a cache-interface-compatible NoopCache implementation is added. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/39/files#diff-18b7d29b8a6def4db6cfb52362d6461e9fe74568b512328051d102b65ab1cc6a'>pkg/services/authz/rbac.go</a> </details> <details> <summary>service.go<code>Use optimistic permission caching with confirmed denial caching</code> <code>+74/-19</code></summary> <br/> >Use optimistic permission caching with confirmed denial caching > ><pre> >• Moves permission-cache reads into Check and List orchestration. Check returns cached allows, falls back to the permission store when cached data cannot authorize, and caches confirmed denials; List serves cached permission maps directly and records hit metrics. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/39/files#diff-1e06afd11b3f74ef3062ef3e5bc87f802090bf795543ae096f98b394b52f60e7'>pkg/services/authz/rbac/service.go</a> </details> </dd> </dl> </details> <details> <summary>Tests (1) <code> +140 / -8 </code></summary> <dl> <dd> <details> <summary>service_test.go<code>Cover RBAC check and list cache behavior</code> <code>+140/-8</code></summary> <br/> >Cover RBAC check and list cache behavior > ><pre> >• Adds tests for cached allows, cache misses, stale permission maps, explicit denial entries, and cached list responses. Removes the lower-level getUserPermissions cache-hit case now that cache lookup occurs at request orchestration level. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/39/files#diff-fa0882f881e78af55889afb5e134869a5f118eec3b37a1b2e7c9ab7de6564b89'>pkg/services/authz/rbac/service_test.go</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (2)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Anonymous denials block rendering <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>Check</i></b> builds <b><i>permDenialKey</i></b> without <b><i>checkReq.IdentityType</i></b> and returns a denial before loading >type-specific permissions. Anonymous and renderer subjects both use identifier <b><i>0</i></b>, so an anonymous >dashboard denial in an organization suppresses the renderer&#x27;s wildcard read grant for the same >dashboard until the 30-second entry expires. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[pkg/services/authz/rbac/service.go[R116-117]](https://github.com/drape-io/crbench-qodo-2026-09/pull/39/files#diff-1e06afd11b3f74ef3062ef3e5bc87f802090bf795543ae096f98b394b52f60e7R116-R117)</code> > >```diff >+ permDenialKey := userPermDenialCacheKey(checkReq.Namespace.Value, checkReq.UserUID, checkReq.Action, checkReq.Name, checkReq.ParentFolder) >+ if _, ok := s.permDenialCache.Get(ctx, permDenialKey); ok { >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The changed lookup uses namespace, user identifier, action, name, and folder but not identity type, >and it returns before type-specific authorization runs. The repository assigns both anonymous and >renderer identities the identifier <b><i>0</i></b>, while renderer permissions independently grant wildcard >dashboard reads. ></pre> > > <code>[pkg/services/authz/rbac/service.go[116-120]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/services/authz/rbac/service.go/#L116-L120)</code> > <code>[pkg/services/authz/rbac/service.go[330-339]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/services/authz/rbac/service.go/#L330-L339)</code> > <code>[pkg/services/authz/rbac/service.go[441-449]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/services/authz/rbac/service.go/#L441-L449)</code> > <code>[pkg/services/user/identity.go[287-299]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/services/user/identity.go/#L287-L299)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Permission-denial cache keys omit the identity type, allowing identities with the same textual identifier to share denials. Anonymous and renderer identities both use `0`, despite having different authorization behavior. > >## Fix Focus Areas >- pkg/services/authz/rbac/cache.go[30-32] >- pkg/services/authz/rbac/service.go[116-117] >- pkg/services/authz/rbac/service.go[153-155] > >## Recommended Fix >Add the identity type to `userPermDenialCacheKey` and pass `checkReq.IdentityType` at every lookup and write. Add a regression test that caches a denial for `anonymous:0` and verifies that `render:0` still receives its renderer-specific dashboard read permission. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 2. A denial blocks a different object <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>userPermDenialCacheKey</i></b> concatenates the object name and parent folder with <b><i>_</i></b>, without escaping >or length-prefixing either value. Because underscores are accepted in UIDs, a denial for <b><i>(a_b,c)</i></b> >has the same key as <b><i>(a,b_c)</i></b> and makes the second object fail at the cache lookup even when its >permissions allow it. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[pkg/services/authz/rbac/cache.go[R30-31]](https://github.com/drape-io/crbench-qodo-2026-09/pull/39/files#diff-9e82c88f61b8c7a6b15ef26d13017e53c4b791558b3b5ebe80a419036b575757R30-R31)</code> > >```diff >+func userPermDenialCacheKey(namespace, userUID, action, name, parent string) string { >+ return namespace + ".perm_" + userUID + "_" + action + "_" + name + "_" + parent >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new key directly joins both values with underscores, while Grafana&#x27;s accepted UID character set >explicitly includes underscores. Since <b><i>Check</i></b> treats any matching entry as authoritative before >evaluating permissions, a tuple collision transfers the cached denial. ></pre> > > <code>[pkg/services/authz/rbac/cache.go[30-32]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/services/authz/rbac/cache.go/#L30-L32)</code> > <code>[pkg/services/authz/rbac/service.go[116-120]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/services/authz/rbac/service.go/#L116-L120)</code> > <code>[pkg/util/shortid_generator.go[32-39]](https://github.com/drape-io/crbench-qodo-2026-09/blob/9a4a994a6d9d97a56db238d9eac43be259fd6cbc/pkg/util/shortid_generator.go/#L32-L39)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The denial-cache key uses underscore delimiters for variable fields that may themselves contain underscores. Different object and parent-folder pairs can therefore produce an identical key and share a denial. > >## Fix Focus Areas >- pkg/services/authz/rbac/cache.go[30-32] >- pkg/services/authz/rbac/service_test.go[973-995] > >## Recommended Fix >Construct denial keys with an unambiguous encoding, such as length-prefixed fields or serialization followed by a hash. Add a regression test proving that `(name=a_b, parent=c)` and `(name=a, parent=b_c)` remain independent. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>⚖️ Balanced</code>: Downgraded extended -&gt; standard: change is below the extended eligibility bar (hunks 16/18, lines 273/200; both must reach the floor). Router rationale: This authorization-cache change adds substantial behavior across multiple RBAC paths, including allow/deny caching and client construction, with many independent logic sites and security-sensitive access-control impact.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/9a4a994a6d9d97a56db238d9eac43be259fd6cbc --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>