feat: Bearer token accountId override for /api/chat#405
Conversation
Bearer token users can now pass accountId in the chat body to override the account context, same as API key users. Access is checked via canAccessAccount (shared org or admin). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important Review skippedReview was skipped due to path filters ⛔ Files ignored due to path filters (3)
CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThis refactoring consolidates authentication and header parsing logic in Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes The reviewer must verify that Possibly related PRs
Poem
🚥 Pre-merge checks | ❌ 1❌ Failed checks (1 warning)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
DRY - what existing lib can we use to simplify the validation logic?
There was a problem hiding this comment.
No issues found across 2 files
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Requires human review: Modifies authorization logic and core API request validation for /api/chat, which requires human review for security implications.
Architecture diagram
sequenceDiagram
participant Client
participant Validator as validateChatRequest
participant Auth as getAuthenticatedAccountId
participant Perm as canAccessAccount
participant CORS as getCorsHeaders
Note over Client,Validator: Request involves Bearer Auth
Client->>Validator: POST /api/chat { prompt, accountId? }
Validator->>Auth: Extract account from JWT
Auth-->>Validator: currentAccountId
alt NEW: Request body has accountId override
Validator->>Perm: NEW: canAccessAccount(current, target)
alt Access Granted (Admin or Org member)
Perm-->>Validator: true
Note over Validator: Use target accountId for context
else Access Denied
Perm-->>Validator: false
Validator->>CORS: Get response headers
CORS-->>Validator: headers
Validator-->>Client: 403 Forbidden (Error Response)
end
else No override provided
Note over Validator: Use currentAccountId from token
end
Note over Validator: Proceed with Chat/Room setup
Replaced manual auth/override/org checks with single validateAuthContext call. Removed imports of getApiKeyAccountId, getAuthenticatedAccountId, validateOverrideAccountId, canAccessAccount, validateOrganizationAccess. Simplified tests to mock validateAuthContext directly. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/chat/validateChatRequest.ts`:
- Around line 91-92: validateChatRequest currently returns the authResult from
validateAuthContext verbatim (when authResult instanceof NextResponse), which
causes mixed error shapes ({error:...} vs {message:...}) in /api/chat; update
the branch handling authResult in validateChatRequest so that if authResult is a
NextResponse you normalize its response body to the canonical { message: string
} shape (e.g., map { error: X } to { message: X } or wrap any existing body text
into message) before returning, ensuring validateChatRequest,
validateAuthContext and any consumers always emit the same error schema.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0d1da634-6eff-405a-bdaa-24c3dc29fe00
⛔ Files ignored due to path filters (1)
lib/chat/__tests__/validateChatRequest.test.tsis excluded by!**/*.test.*,!**/__tests__/**and included bylib/**
📒 Files selected for processing (1)
lib/chat/validateChatRequest.ts
| if (authResult instanceof NextResponse) { | ||
| return authResult; |
There was a problem hiding this comment.
Keep /api/chat error bodies on one schema.
validateAuthContext returns { error: ... } for its XOR-auth and organization-access branches in lib/auth/validateAuthContext.ts:46-118, while this validator and the underlying auth helpers use { message: ... }. Returning the helper response verbatim here makes /api/chat emit mixed error shapes.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/chat/validateChatRequest.ts` around lines 91 - 92, validateChatRequest
currently returns the authResult from validateAuthContext verbatim (when
authResult instanceof NextResponse), which causes mixed error shapes
({error:...} vs {message:...}) in /api/chat; update the branch handling
authResult in validateChatRequest so that if authResult is a NextResponse you
normalize its response body to the canonical { message: string } shape (e.g.,
map { error: X } to { message: X } or wrap any existing body text into message)
before returning, ensuring validateChatRequest, validateAuthContext and any
consumers always emit the same error schema.
Replaced old auth mocks (getApiKeyAccountId, validateOverrideAccountId, etc.) with validateAuthContext mock in handleChatGenerate, handleChatStream, and chatEndToEnd tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Preview Deployment Testing ResultsPreview URL: POST /api/chat/generate with accountId override
|
Summary
accountIdin the chat request body to override the account contextcanAccessAccount(shared org membership or Recoup admin)accountIdoverrideTest plan
🤖 Generated with Claude Code
Summary by cubic
Enables Bearer token users to override
accountIdin/api/chat, matching API key behavior. Auth and org checks are now centralized invalidateAuthContext(REC-52).validateChatRequestviavalidateAuthContext, which returnsaccountId,orgId, andauthToken.validateAuthContext.validateAuthContext(handleChatGenerate,handleChatStream, integration, and request validation).Written for commit 01412fe. Summary will update on new commits.
Summary by CodeRabbit
Note: This update contains no user-facing changes. It consists of internal code improvements to enhance maintainability.