Skip to content

fix(api): tighten collection lookup with workspaceId and preserve HTTPException status codes#1193

Open
shivamashtikar wants to merge 1 commit intomainfrom
fix-agent-api-path
Open

fix(api): tighten collection lookup with workspaceId and preserve HTTPException status codes#1193
shivamashtikar wants to merge 1 commit intomainfrom
fix-agent-api-path

Conversation

@shivamashtikar
Copy link
Contributor

@shivamashtikar shivamashtikar commented Nov 5, 2025

Description

  • Add workspaceId parameter to getRecordBypath and filter collections by that workspace
  • Pass workspaceId from AgentMessageApi to the lookup
  • Update query logic to enforce multi‑workspace isolation
  • Refine API error handler to re‑throw HTTPException instances before falling back to custom APIError, preserving original status codes

Testing

Additional Notes

Summary by CodeRabbit

  • Bug Fixes
    • Fixed error handling to preserve correct HTTP status codes in API responses, ensuring proper error status reporting for client applications

…PException status codes

- Add `workspaceId` parameter to `getRecordBypath` and filter collections by that workspace
- Pass `workspaceId` from `AgentMessageApi` to the lookup
- Update query logic to enforce multi‑workspace isolation
- Refine API error handler to re‑throw `HTTPException` instances before falling back to custom `APIError`, preserving original status codes
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2025

Walkthrough

The changes add workspace-scoped validation to path-based record access by updating the getRecordBypath function signature to require a workspaceId parameter for collection lookup, and updating the agents API to pass this parameter while improving error handling to preserve HTTP status codes.

Changes

Cohort / File(s) Summary
Workspace-scoped path resolution
server/db/knowledgeBase.ts
Function signature updated from getRecordBypath(path: string, trx: TxnOrClient) to getRecordBypath(path: string, workspaceId: number, trx: TxnOrClient). Collection lookup now filters by workspaceId in addition to name and non-deleted status. Returns null if no matching collection found.
Agent API caller update
server/api/chat/agents.ts
AgentMessageApi path handling now passes workspace.id to getRecordBypath() call. Error handling updated to directly rethrow HTTPException to preserve original HTTP status codes, while non-HTTPException errors retain generic APIError handling (e.g., 429 quota handling).

Sequence Diagram(s)

sequenceDiagram
    participant AgentAPI as AgentMessageApi<br/>(agents.ts)
    participant KnowledgeBase as getRecordBypath<br/>(knowledgeBase.ts)
    participant DB as Database

    Note over AgentAPI,DB: New Workspace-Scoped Flow
    AgentAPI->>KnowledgeBase: getRecordBypath(path, workspace.id, trx)
    activate KnowledgeBase
    KnowledgeBase->>DB: Query collection WHERE name = ? AND workspace_id = ? AND deleted = false
    DB-->>KnowledgeBase: collection result
    alt Collection found
        KnowledgeBase-->>AgentAPI: Return record
    else Collection not found
        KnowledgeBase-->>AgentAPI: Return null
    end
    deactivate KnowledgeBase
    
    Note over AgentAPI: Error Handling
    alt HTTPException thrown
        AgentAPI-->>AgentAPI: Rethrow HTTPException (preserves status)
    else Other error
        AgentAPI-->>AgentAPI: Generic APIError handling
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Verify all callers of getRecordBypath throughout the codebase are updated with the new workspaceId parameter
  • Confirm that workspace.id is correctly extracted and passed in the agents API call
  • Review error handling logic to ensure HTTPException status codes are properly preserved while maintaining backward compatibility for other error types
  • Check for any other affected files that may depend on the old function signature

Possibly related PRs

Suggested reviewers

  • zereraz
  • kalpadhwaryu
  • devesh-juspay
  • junaid-shirur

Poem

🐰 A workspace now guards each path with care,
With scoped lookups floating through the air,
HTTPExceptions take their rightful flight,
While errors handled now with perfect sight,
The rabbit hops through logic clean and bright! ✨

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures both main changes: workspace-scoped collection lookup and HTTPException handling improvements.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-agent-api-path

📜 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 12ad1f9 and 0c8b74d.

📒 Files selected for processing (2)
  • server/api/chat/agents.ts (2 hunks)
  • server/db/knowledgeBase.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: Aman-Asrani-Juspay
Repo: xynehq/xyne PR: 777
File: server/db/agent.ts:344-381
Timestamp: 2025-09-04T12:23:59.355Z
Learning: The team prefers to handle workspace scoping and security checks through higher-level backend functions rather than implementing them directly in database query functions like getAgentByExternalId.
📚 Learning: 2025-07-29T09:29:29.401Z
Learnt from: MayankBansal2004
Repo: xynehq/xyne PR: 691
File: server/db/sharedAgentUsage.ts:742-816
Timestamp: 2025-07-29T09:29:29.401Z
Learning: In server/db/sharedAgentUsage.ts, the getAgentFeedbackMessages function intentionally retrieves shareToken from the feedback JSON (feedbackData?.share_chat) rather than from the shared_chats table. This is a privacy design where share tokens are only stored in feedback JSON when users explicitly allow sharing, ensuring consent-based token exposure.

Applied to files:

  • server/api/chat/agents.ts
📚 Learning: 2025-09-16T08:57:58.762Z
Learnt from: rahul1841
Repo: xynehq/xyne PR: 843
File: server/server.ts:996-996
Timestamp: 2025-09-16T08:57:58.762Z
Learning: The DownloadFileApi handler in server/api/knowledgeBase.ts properly uses the clId route parameter to scope and validate file access within the correct collection.

Applied to files:

  • server/db/knowledgeBase.ts
📚 Learning: 2025-09-16T08:57:58.762Z
Learnt from: rahul1841
Repo: xynehq/xyne PR: 843
File: server/server.ts:996-996
Timestamp: 2025-09-16T08:57:58.762Z
Learning: The DownloadFileApi handler in server/api/knowledgeBase.ts properly uses the clId route parameter to scope and validate file access within the correct collection, including fetching the collection, checking permissions, and verifying the file belongs to that collection.

Applied to files:

  • server/db/knowledgeBase.ts
🧬 Code graph analysis (2)
server/api/chat/agents.ts (1)
server/db/knowledgeBase.ts (1)
  • getRecordBypath (1015-1079)
server/db/knowledgeBase.ts (2)
server/types.ts (1)
  • TxnOrClient (320-320)
server/db/schema/knowledgeBase.ts (1)
  • collections (20-66)

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @shivamashtikar, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on improving the application's data security and API robustness. It enforces stricter multi-workspace data isolation by integrating workspaceId into collection lookup queries and refines API error handling to accurately reflect original HTTP status codes, leading to more precise error reporting.

Highlights

  • Multi-workspace Isolation: The getRecordBypath function now requires a workspaceId parameter, ensuring that collection lookups are strictly filtered by the current workspace. This prevents unauthorized cross-workspace data access and enhances data isolation.
  • API Error Handling Refinement: The API error handler in AgentMessageApi has been updated to directly re-throw HTTPException instances. This change ensures that the original HTTP status codes (e.g., 400, 403) are preserved and propagated, rather than being caught and potentially converted to a generic APIError.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces two important fixes. First, it tightens the security of collection lookups by adding a workspaceId filter, ensuring proper data isolation between workspaces. This is a great improvement. Second, it refines the API error handling to preserve original HTTPException status codes, which will make API error responses more accurate for clients. The implementation of these changes is sound. I've added one comment regarding a potential issue in the error handling logic that could be improved for more robustness.

Comment on lines +5184 to +5187
if (error instanceof HTTPException) {
// Re-throw HTTPException to preserve the original status code (400, 403, etc.)
throw error
} else if (error instanceof APIError) {
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This change to re-throw HTTPException is a good improvement for preserving specific error status codes. However, the surrounding catch block has a potential issue. It attempts to write to an SSE stream in a context where an error might have occurred before the stream was initialized (e.g., during chat creation). This could lead to a TypeError if stream is undefined, masking the original error.

Consider refactoring this catch block to only handle pre-stream errors by throwing an HTTPException. Any logic that writes errors to the stream should be located within the streamSSE onError callback to ensure the stream is active.

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