Skip to content

Feature/role based apikeys - #34

Merged
thedevyashsaini merged 5 commits into
mainfrom
feature/role-based-apikeys
May 13, 2026
Merged

Feature/role based apikeys#34
thedevyashsaini merged 5 commits into
mainfrom
feature/role-based-apikeys

Conversation

@thedevyashsaini

@thedevyashsaini thedevyashsaini commented May 13, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • API keys now support role-based access control with three roles (dashboard, production, test), each with appropriate permission restrictions for operations like event registration and checkout.
    • Added support for test and production modes to isolate data and control API key behavior.
  • Chores

    • Updated database schema to persist API key roles and operational modes.

Review Change Stack

- api_keys.role: enum(dashboard, production, test), default dashboard
- events.mode: enum(test, production), default production
- users.mode: enum(test, production), default production
- sessions.mode: enum(test, production), default production
- keyFormat.ts: parseRoleFromApiKey, isValidApiKeyFormat, getModeForRole
- generateAPIKey(role): scrn_dash_, scrn_live_, scrn_test_ prefixes (42 chars total)
- generateInitialApiKey: dashboard key with scrn_dash_ prefix and role in SQL
…, handlers

- apiKeysTable: add role column (dashboard/production/test)
- eventsTable, usersTable, sessionsTable: add mode column (test/production)
- keyFormat.ts: prefix-based role parsing (scrn_dash_, scrn_live_, scrn_test_)
- auth interceptor: parse role from prefix, set AuthContext with apiKeyId+role+mode
- requireRole() guard for endpoint-level permission enforcement
- authenticateHttpApiKey: returns AuthContext with role/mode
- apiKeyCache: stores role and mode
- AuthError: add permissionDenied, invalidRole, roleMismatch
- createAPIKey: dashboard-only, accepts role, generates role-prefixed keys
- registerEvent, streamEvents: reject dashboard keys, pass mode to storage
- createCheckoutLink: production-only, pass mode to storage
- generateAPIKey(role): scrn_dash_/scrn_live_/scrn_test_ prefixes
- generateInitialAPIKey: dashboard key with scrn_dash_ prefix
- createApiKey helper: accepts role param
- findApiKeyByHash: returns role
- eventHelpers: storeEvent accepts AuthContext, passes mode to storage
- Zod: createAPIKeySchema includes role field

BREAKING: Key format changes from scrn_ (37 chars) to scrn_dash_/scrn_live_/scrn_test_ (42 chars). Existing keys invalid.
CreateAPIKey now requires a valid dashboard key. Previously it was
whitelisted with no auth, causing the handler to fail with 'API key
context not found' since the interceptor never set the context.
@coderabbitai

coderabbitai Bot commented May 13, 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 Plus

Run ID: c9ba55a3-e594-4d5c-bcb8-7609c1f68868

📥 Commits

Reviewing files that changed from the base of the PR and between 3365add and 0c49113.

📒 Files selected for processing (19)
  • proto
  • src/context/auth.ts
  • src/errors/auth.ts
  • src/interceptors/auth.ts
  • src/interface/storage/Storage.ts
  • src/interface/types/context.ts
  • src/routes/gRPC/auth/createAPIKey.ts
  • src/routes/gRPC/events/registerEvent.ts
  • src/routes/gRPC/events/streamEvents.ts
  • src/routes/gRPC/payment/createCheckoutLink.ts
  • src/storage/db/postgres/helpers/apiKeys.ts
  • src/storage/db/postgres/schema.ts
  • src/utils/apiKeyCache.ts
  • src/utils/authenticateHttpApiKey.ts
  • src/utils/eventHelpers.ts
  • src/utils/generateAPIKey.ts
  • src/utils/generateInitialAPIKey.ts
  • src/utils/keyFormat.ts
  • src/zod/apikey.ts

📝 Walkthrough

Walkthrough

This PR implements a role-based authorization system for API keys across authentication, gRPC interception, and route handlers. It introduces role types (dashboard, production, test), updates database schemas with role and mode columns, refactors API key generation to derive keys from roles, and enforces authorization checks at key creation, event ingestion, and checkout endpoints.

Changes

Role-Based Authorization Implementation

Layer / File(s) Summary
API Key Role Utilities and Error Contracts
src/utils/keyFormat.ts, src/context/auth.ts, src/errors/auth.ts
Introduces ApiKeyRole type with role-to-prefix mappings (dashboard, production, test), defines AuthContext interface with apiKeyId, role, and mode fields, and adds role-related error types and factory methods (invalidRole, roleMismatch, permissionDenied).
Database Schema, API Key Generation, and Validation
src/storage/db/postgres/schema.ts, src/zod/apikey.ts, src/utils/generateAPIKey.ts, src/utils/generateInitialAPIKey.ts, src/storage/db/postgres/helpers/apiKeys.ts
Updates table schemas to add mode column to usersTable, sessionsTable, and eventsTable with default production, and role column to apiKeysTable with default dashboard. Refactors API key generation to accept optional role parameter and derive prefix accordingly. Updates API key schema validation and initial dashboard key generation to include role. Persists role in database and retrieves it in API key lookups.
HTTP Authentication with Role Parsing and Caching
src/utils/authenticateHttpApiKey.ts, src/utils/apiKeyCache.ts
Updates authenticateHttpApiKey to parse role from API key prefix, validate key format against derived role, enforce role consistency against cached and stored records, compute mode from role, and return AuthContext object instead of plain id string. Extends cache payload to store role and mode alongside existing fields.
gRPC Authentication Interceptor and Role Guard
src/interceptors/auth.ts, src/interface/types/context.ts
Refactors authInterceptor to parse and validate API key roles, enforce role consistency at both cache and database lookups, and set gRPC call context to AuthContext instead of string. Introduces GrpcUntypedHandler, GrpcFlexibleHandler types and requireRole interceptor guard. Updates call context type to reflect AuthContext | undefined for the API key context field. Disables auth bypass whitelist.
Role-Based Authorization in Route Handlers
src/routes/gRPC/auth/createAPIKey.ts, src/routes/gRPC/events/registerEvent.ts, src/routes/gRPC/events/streamEvents.ts, src/routes/gRPC/payment/createCheckoutLink.ts
Enforces authorization at each endpoint: createAPIKey requires dashboard role, registerEvent and streamEvents deny dashboard-role keys, createCheckoutLink denies dashboard and test roles. Routes extract AuthContext from gRPC call context, validate presence, return role-specific errors, and pass authenticated context to downstream storage operations.
Event Storage with AuthContext and Mode Support
src/utils/eventHelpers.ts, src/interface/storage/Storage.ts
Updates storeEvent signature to accept AuthContext instead of plain apiKeyId, and conditionally passes mode parameter to storage adapter add method based on mode presence. Extends StorageAdapter interface to accept optional mode parameter in both add and price methods.

Proto Submodule Update

Layer / File(s) Summary
Proto Submodule Commit Reference
proto
Updates git submodule pointer to a new commit hash.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A system of roles takes shape,
Dashboard, production, test—each finds its place,
Keys now carry their identity with pride,
Authorization guards every stride,
The auth realm is stronger, verified and defined!

✨ 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 feature/role-based-apikeys

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

Signed-off-by: Devyash Saini <dysaini2004@gmail.com>
@thedevyashsaini
thedevyashsaini merged commit 146b104 into main May 13, 2026
1 of 2 checks passed
This was referenced May 14, 2026
@coderabbitai coderabbitai Bot mentioned this pull request May 28, 2026
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.

1 participant