Skip to content

AuthZService: improve authz caching#2

Open
everettbu wants to merge 1 commit into
cache-optimization-baselinefrom
authz-service-improve-caching-pr
Open

AuthZService: improve authz caching#2
everettbu wants to merge 1 commit into
cache-optimization-baselinefrom
authz-service-improve-caching-pr

Conversation

@everettbu

@everettbu everettbu commented Jul 26, 2025

Copy link
Copy Markdown

Test 2

Summary by CodeRabbit

  • New Features

    • Introduced a permission denial cache to improve performance by quickly returning denied responses for repeated permission checks.
    • Enhanced permission caching logic for more efficient authorization checks and permission listing.
  • Bug Fixes

    • Improved cache handling to ensure accurate permission results and prevent outdated cache entries from allowing unauthorized access.
  • Tests

    • Added comprehensive tests for permission check and list methods with cache scenarios.
    • Removed redundant cache test to streamline the test suite.

* remove the use of client side cache for in-proc authz client

Co-authored-by: Gabriel MABILLE <gabriel.mabille@grafana.com>

* add a permission denial cache, fetch perms if not in either of the caches

Co-authored-by: Gabriel MABILLE <gabriel.mabille@grafana.com>

* Clean up tests

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>

* Cache tests

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>

* Add test to list + cache

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>

* Add outdated cache test

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>

* Re-organize metrics

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>

---------

Co-authored-by: Gabriel MABILLE <gabriel.mabille@grafana.com>
@coderabbitai

coderabbitai Bot commented Jul 26, 2025

Copy link
Copy Markdown

Walkthrough

The changes introduce a permission denial cache to the RBAC authorization service, enabling immediate denial responses for cached denials. The code refactors cache handling for permission checks, adds a unified method for retrieving cached permissions, and updates related tests. A new no-op cache implementation and a cache key generator for denials are also added.

Changes

File(s) Change Summary
pkg/services/authz/rbac.go Refactored RBAC client instantiation; removed helper, added NoopCache, and updated cache usage.
pkg/services/authz/rbac/cache.go Added userPermDenialCacheKey function for generating denial cache keys.
pkg/services/authz/rbac/service.go Added permDenialCache, unified cache retrieval, updated Check/List methods, and denial caching logic.
pkg/services/authz/rbac/service_test.go Added tests for denial and permission caches, removed redundant cache test, updated setup.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Service
    participant DenialCache
    participant PermCache
    participant Store

    Client->>Service: Check(namespace, user, action, name, parent)
    Service->>DenialCache: Get(denialKey)
    alt Denial found
        DenialCache-->>Service: Denied
        Service-->>Client: Denied (cached)
    else Denial not found
        Service->>PermCache: Get(permKey)
        alt Permission found and allows
            PermCache-->>Service: Allowed
            Service-->>Client: Allowed (cached)
        else Permission not found or denied
            Service->>Store: Fetch permissions
            Store-->>Service: Permissions
            alt Denied
                Service->>DenialCache: Set(denialKey, true)
                Service-->>Client: Denied
            else Allowed
                Service-->>Client: Allowed
            end
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A cache for denials, a hop for the best,
Now rabbits can rest when permissions are stressed.
With keys made precise and a Noop in the mix,
The service is nimble with clever new tricks.
Hooray for the caches, both deny and allow—
This bunny approves of the changes right now!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e650fa7 and d9dc93c.

📒 Files selected for processing (4)
  • pkg/services/authz/rbac.go (3 hunks)
  • pkg/services/authz/rbac/cache.go (1 hunks)
  • pkg/services/authz/rbac/service.go (6 hunks)
  • pkg/services/authz/rbac/service_test.go (3 hunks)
🔇 Additional comments (10)
pkg/services/authz/rbac/cache.go (1)

30-32: LGTM! Cache key function follows established patterns.

The new userPermDenialCacheKey function correctly follows the existing naming convention and key structure pattern used by other cache key functions in this file.

pkg/services/authz/rbac.go (2)

101-105: Good refactoring - direct client instantiation improves clarity.

Removing the helper function and directly calling authzlib.NewClient with explicit options makes the code more readable and explicit about the caching strategy for in-process clients.


239-251: NoopCache implementation is correct and well-designed.

The NoopCache correctly implements the cache interface with no-op methods. Returning cache.ErrNotFound from Get ensures proper cache miss behavior, while Set and Delete appropriately do nothing.

pkg/services/authz/rbac/service_test.go (3)

893-996: Comprehensive test coverage for cache behavior.

The TestService_CacheCheck function provides excellent coverage of the caching scenarios including:

  • Cache hits for allowed permissions
  • Fallback behavior on cache misses
  • Handling of outdated cache entries
  • Explicit denial cache functionality

The tests are well-structured and verify the expected behavior thoroughly.


1291-1323: Good test coverage for cached list operations.

The TestService_CacheList function properly tests the caching behavior for list operations, verifying that cached permissions are correctly used.


1336-1336: Setup function correctly updated.

The setupService helper properly initializes the new permDenialCache field.

pkg/services/authz/rbac/service.go (4)

56-61: LGTM! Denial cache field properly added to Service struct.

The permDenialCache field is correctly typed and follows the same pattern as other cache fields in the struct.


116-121: Excellent optimization - early denial check improves performance.

Checking the denial cache before attempting any permission lookups is an effective optimization that short-circuits denied requests immediately. The metrics are correctly updated to track cache usage.


153-155: Good caching strategy for denied permissions.

Caching denied permissions after a failed check will help optimize subsequent denial checks for the same permission.


342-368: Well-designed unified cache retrieval method.

The getCachedIdentityPermissions method effectively consolidates cache retrieval logic for different identity types. The method correctly:

  • Handles each identity type appropriately
  • Returns cache.ErrNotFound for render service (which doesn't use caching)
  • Retrieves user identifiers before checking user cache
  • Returns proper error types for cache misses

This unification improves code maintainability and consistency.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch authz-service-improve-caching-pr

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@everettbu

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in 2 weeks if no further activity occurs. Please feel free to give a status update or ping for review. Thank you for your contributions!

@github-actions github-actions Bot added the stale label Aug 28, 2025
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically closed because it has not had any further activity in the last 2 weeks. Thank you for your contributions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants