Skip to content

Improve authorization and async request-path performance#28

Merged
osama1998H merged 2 commits into
masterfrom
performance-audit
Mar 28, 2026
Merged

Improve authorization and async request-path performance#28
osama1998H merged 2 commits into
masterfrom
performance-audit

Conversation

@osama1998H

@osama1998H osama1998H commented Mar 28, 2026

Copy link
Copy Markdown
Owner

Summary

  • add a shared async dispatcher and move audit logging, webhook dispatch, and API key last-used updates off unbounded goroutines
  • optimize RBAC authorization with a single repository query that handles superusers and missing users explicitly
  • scope rate limiting to /api/v1, exempt health endpoints, and add focused router/middleware benchmarks plus supporting tests
  • ignore local benchmark output files and add make bench-perf for repeatable perf runs

Type of change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update
  • Refactoring

Changes

  • improve permission checks with AuthorizeUser and expand RBAC/tenant-scope coverage
  • add health/rate-limit regression tests and benchmark helpers for router and middleware paths
  • wire logger-backed async queues into API key, audit, and webhook services

Testing

  • Not run (not requested)

Summary by CodeRabbit

  • Bug Fixes

    • Rate limiting now applies only to /api/v1, excluding health/readiness endpoints to avoid throttling monitoring.
  • Performance Improvements

    • Audit log writes, API key last-used updates, and webhook dispatches are now processed asynchronously to reduce request latency.
  • Authorization

    • Role-based access checks consolidated and tightened for more consistent permission handling and clearer unauthorized/forbidden outcomes.
  • New Features / Tests

    • Project-level performance benchmarks and router/rate-limit tests added; make target provided to run selected benchmarks.
  • Chores

    • Local benchmark capture files added to .gitignore.

@coderabbitai

coderabbitai Bot commented Mar 28, 2026

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6b7e9931-b382-46ee-ac8c-b0a226120f60

📥 Commits

Reviewing files that changed from the base of the PR and between 05c41f5 and 0abbc66.

📒 Files selected for processing (1)
  • internal/testutil/testcache.go

📝 Walkthrough

Walkthrough

Introduces a generic async dispatcher and migrates background work (audit, API key last-used, webhooks) to it; moves rate-limit middleware scope to /api/v1; adds repo-level AuthorizeUser with superuser bypass; and adds benchmarks and tests for router, middleware, and async components.

Changes

Cohort / File(s) Summary
Build & Dev
/.gitignore, ./Makefile
Ignore local benchmark captures; add bench-perf make target with configurable benchmark pattern and count.
Async infra
internal/service/async.go, internal/service/async_test.go
Add generic asyncDispatcher[T] with worker pool, non-blocking enqueue + tests for concurrency and drop behavior.
API key / Audit / Webhook services
internal/service/apikey.go, internal/service/audit.go, internal/service/webhook.go
Refactor to use async dispatcher for background tasks; APIKey service now accepts logger and enqueues last-used updates; Audit enqueues logs; Webhook enqueues dispatch jobs processed by workers.
RBAC & repository
internal/repository/postgres/roles.go, internal/service/rbac.go, internal/service/rbac_scope_test.go
Add Store.AuthorizeUser returning (userExists, authorized, err); RBAC service delegates to it and maps outcomes to domain errors; add test for missing user case.
Repository tests
internal/repository/postgres/tenant_scope_test.go
Add TestStoreAuthorizeUser covering granted/missing permission, superuser bypass, and non-existent user.
Router & rate-limit
internal/api/router.go, internal/api/router_rate_limit_test.go
Apply rate-limit middleware only to /api/v1 group; pass logger into APIKey service; add tests ensuring health/ready bypass and API routes rate-limited.
Router tests & benchmarks
internal/api/router_authorization_test.go, internal/api/router_benchmark_test.go, internal/api/middleware/benchmark_test.go
Minor test helper signature formatting; add router and middleware benchmarks for health, list users (permitted/superuser), JWT blacklist lookup, and rate-limit perf.
Test utilities
internal/testutil/testcache.go
Add RequireTestCache and RequireEnv test helpers to initialize Redis-backed cache and skip on missing env vars.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Component (e.g., APIKeyService / AuditService / WebhookService)
    participant Dispatcher as asyncDispatcher
    participant Worker as Dispatcher Worker
    participant Store as Store/DB
    participant Logger as slog.Logger

    Caller->>Dispatcher: Enqueue(task)
    Dispatcher-->>Caller: return immediately
    Worker->>Dispatcher: receive task
    Worker->>Logger: Log start / errors
    Worker->>Store: perform DB operation (CreateAuditLog / UpdateAPIKeyLastUsed / List & deliver webhooks)
    Store-->>Worker: result / error
    Worker->>Logger: Log errors if any
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

size/XXL

Poem

🐰 I queued the logs, I queued the keys,
I hopped through rate-limits with nimble ease,
Background workers hum like bees,
Benchmarks race on health and users' pleas,
A rabbit cheers: async makes work breeze!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the PR's main changes: authorization optimization and async performance improvements are both prominent aspects of this changeset.
Description check ✅ Passed The description covers the key changes (async dispatcher, RBAC optimization, rate-limiting scope, benchmarks, and tooling), though the Testing section is incomplete.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch performance-audit

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@osama1998H osama1998H merged commit 17ae512 into master Mar 28, 2026
3 checks passed
@osama1998H osama1998H deleted the performance-audit branch March 28, 2026 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant