Skip to content

feat: Bearer token accountId override for /api/chat#405

Merged
sweetmantech merged 3 commits intotestfrom
feat/chat-bearer-accountid-override
Apr 6, 2026
Merged

feat: Bearer token accountId override for /api/chat#405
sweetmantech merged 3 commits intotestfrom
feat/chat-bearer-accountid-override

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented Apr 6, 2026

Summary

  • Bearer token users can now pass accountId in the chat request body to override the account context
  • Access is checked via canAccessAccount (shared org membership or Recoup admin)
  • Previously only API key auth supported accountId override
  • Part of REC-52: enables email-based account lookup for chat override

Test plan

  • RED: 2 failing tests for Bearer override (grant + deny)
  • GREEN: all 45 tests pass
  • Verify on preview deployment

🤖 Generated with Claude Code


Summary by cubic

Enables Bearer token users to override accountId in /api/chat, matching API key behavior. Auth and org checks are now centralized in validateAuthContext (REC-52).

  • Refactors
    • Consolidated auth and override handling in validateChatRequest via validateAuthContext, which returns accountId, orgId, and authToken.
    • Removed manual header checks and override/org validation; auth errors now come from validateAuthContext.
    • Updated chat tests to mock validateAuthContext (handleChatGenerate, handleChatStream, integration, and request validation).

Written for commit 01412fe. Summary will update on new commits.

Summary by CodeRabbit

  • Refactor
    • Optimized internal authentication validation process for improved code efficiency.

Note: This update contains no user-facing changes. It consists of internal code improvements to enhance maintainability.

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>
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 6, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Apr 6, 2026 10:15pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 6, 2026

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (3)
  • lib/chat/__tests__/handleChatGenerate.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chat/__tests__/handleChatStream.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chat/__tests__/integration/chatEndToEnd.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 40da1ce9-bd05-4fd6-b738-bfd7ea1c3f9f

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This refactoring consolidates authentication and header parsing logic in validateChatRequest.ts by replacing ~82 lines of inline auth validation with a centralized validateAuthContext() call, improving code maintainability and reducing duplication.

Changes

Cohort / File(s) Summary
Auth Validation Consolidation
lib/chat/validateChatRequest.ts
Replaced inline authentication/header parsing logic with centralized validateAuthContext() call, delegating auth mechanism validation, accountId override validation, and organizationId access checks. Extracted authToken and accountId/orgId from consolidated function result.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

The reviewer must verify that validateAuthContext() comprehensively handles all previously inlined validation steps (auth type detection, override validation, org access enforcement) and confirm correct extraction and forwarding of authToken and account identifiers to downstream operations.

Possibly related PRs

Poem

🧹 Lines of auth once sprawled and long,
Now sing in one harmonious song,
Validation flows through channels clean,
The neatest auth cascade you've seen! ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning Refactoring improves DRY and KISS principles by consolidating auth logic, but introduces inconsistent error response schemas between validateAuthContext and validateChatRequest. Normalize error responses by transforming validateAuthContext errors from {error:...} to {message:...} format before returning at line 91-92 to maintain API schema consistency.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/chat-bearer-accountid-override

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DRY - what existing lib can we use to simplify the validation logic?

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Loading

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>
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Requires human review: This PR modifies authentication and authorization logic for a core API endpoint, introducing account overrides for Bearer tokens which requires human security review.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between e5b1284 and a52f5ea.

⛔ Files ignored due to path filters (1)
  • lib/chat/__tests__/validateChatRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (1)
  • lib/chat/validateChatRequest.ts

Comment on lines +91 to +92
if (authResult instanceof NextResponse) {
return authResult;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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>
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Requires human review: This PR modifies core authentication and authorization logic for the chat API, which is a security-sensitive area that requires human review.

@sweetmantech
Copy link
Copy Markdown
Contributor Author

Preview Deployment Testing Results

Preview URL: recoup-api-git-feat-chat-bearer-acco-01b5d5-recoupable-ad724970.vercel.app

POST /api/chat/generate with accountId override

  • API key auth with accountId: "85d66a3b-..." (Rostrum Records) correctly overrides account context
  • AI responds as Jessica's agent: "Hey Jessica — nice to see you"
  • Room created successfully with override account
  • validateAuthContext handles both auth + accountId override in a single call

@sweetmantech sweetmantech merged commit 1f5ddac into test Apr 6, 2026
5 of 6 checks passed
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