Skip to content

fix: authorize beta document downloads by tenant - #14496

Merged
KevinHuSh merged 3 commits into
infiniflow:mainfrom
andesyteoss:fix/cwe862-doc-idor-f141
May 6, 2026
Merged

KevinHuSh merged 3 commits into
infiniflow:mainfrom
andesyteoss:fix/cwe862-doc-idor-f141

Conversation

@andesyteoss

Copy link
Copy Markdown

Summary

This fixes a missing authorization check in the beta API document download endpoint:

  • CWE: CWE-862 (Missing Authorization)
  • Severity: Medium
  • Affected route/file: GET /api/v1/documents/<document_id> in api/apps/sdk/doc.py
  • Data flow: the route reads a bearer beta API token, resolves the token with APIToken.query(beta=token), accepts document_id directly from the URL, loads the document with DocumentService.query(id=document_id), and then fetches the backing object through File2DocumentService.get_storage_address() / settings.STORAGE_IMPL.get().

Before this change, that flow verified that the API token was valid, but it did not verify that the token's tenant owned the document's knowledge base. A caller with any valid beta API token and a known document ID could therefore reach storage for a document belonging to another tenant.

Fix

The endpoint now takes the tenant ID from the resolved API token and checks the document's knowledge base with:

KnowledgebaseService.query(id=doc[0].kb_id, tenant_id=tenant_id)

If the knowledge base is not owned by the token tenant, the request returns an access error before any storage lookup occurs. This mirrors the tenant-scoped ownership checks used by the dataset-scoped document download path and keeps the patch small.

Tests

Added unit coverage for download_doc() to assert that:

  • the beta token tenant ID is used in the knowledge-base ownership lookup;
  • cross-tenant access returns You do not have access to this document.;
  • storage resolution is not called before tenant authorization succeeds;
  • the existing same-tenant empty-file and successful-download paths still run after the authorization gate passes.

I also verified the final patch is limited to api/apps/sdk/doc.py and the related document SDK route unit test. A local pytest invocation could not complete in this checkout because the shared test fixture attempts to log in to a RAGFlow server at 127.0.0.1:9380, which was not running in the local environment.

Security analysis

This is exploitable when an attacker has a valid beta API token for their own tenant and obtains or guesses a document ID from another tenant. The token alone should not grant access to other tenants' files, but the direct document route previously authorized only the token itself and not the requested resource. The new tenant-scoped knowledge-base check binds the requested document back to the token tenant before storage is accessed, preventing cross-tenant document downloads through this endpoint.

Before submitting, we attempted to disprove this by checking whether existing dataset-scoped routes, token validation, or framework protections already enforced ownership. They do not apply to this direct document-ID route: it bypassed the dataset path parameter and used only DocumentService.query(id=document_id) before reading storage.

cc @lewiswigmore

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Apr 29, 2026
@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 107e5dbd-544e-4129-82b8-1e2cc3e28957

📥 Commits

Reviewing files that changed from the base of the PR and between 2ce3c2e and 9dfae48.

📒 Files selected for processing (2)
  • api/apps/sdk/doc.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • api/apps/sdk/doc.py

📝 Walkthrough

Walkthrough

download_doc now enforces tenant-scoped authorization by deriving tenant_id from the validated API token, handling ambiguous/invalid tokens explicitly, and verifying the knowledgebase belongs to that tenant before proceeding to file retrieval or streaming.

Changes

Cohort / File(s) Summary
Tenant-scoped access control
api/apps/sdk/doc.py
Derive tenant_id from validated API token; log token lookup/ambiguities; return explicit config error on multiple matches; add tenant-scoped Knowledgebase query and return "You do not have access to this document" if KB not found for the token's tenant before any storage access.
Access control unit tests
test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
Added tests that mock APIToken.query returning multiple tokens to assert ambiguous-key error; mock KnowledgebaseService.query to return no results and ensure File2DocumentService.get_storage_address is not called; assert access-denied message and that KB query used id="kb-1" and tenant_id="tenant-1".

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Endpoint as download_doc<br/>Endpoint
    participant TokenService as APIToken<br/>Service
    participant KBService as KnowledgebaseService
    participant FileService as File2DocumentService

    Client->>Endpoint: Request document with API token
    Endpoint->>TokenService: Lookup/validate token
    alt token invalid
        TokenService-->>Endpoint: No valid token
        Endpoint-->>Client: Unauthorized / invalid token
    else token ambiguous
        TokenService-->>Endpoint: >1 token matches
        Endpoint-->>Client: "API key configuration is ambiguous"
    else token valid
        TokenService-->>Endpoint: Return token (tenant_id)
        Endpoint->>KBService: Query KB by id and tenant_id
        alt KB found
            KBService-->>Endpoint: KB record
            Endpoint->>FileService: Get storage address / retrieve file
            FileService-->>Endpoint: File stream
            Endpoint-->>Client: Stream file
        else KB not found
            KBService-->>Endpoint: No results
            Endpoint-->>Client: "You do not have access to this document."
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I checked the token, hopped through the gate,
Tenant-bound paths now guard each crate.
No mixed-up keys, no cross-burrow roam,
Each doc streams safely back to home. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding tenant-based authorization to beta document downloads, which is the core security fix in this PR.
Description check ✅ Passed The description covers all required template sections with substantial detail: it explains the problem (missing authorization check with CWE reference), specifies the type of change (bug fix), describes the fix implementation, documents tests added, and provides security analysis.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

@dosubot dosubot Bot added 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Apr 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/apps/sdk/doc.py (1)

116-117: Add observability to the new deny path.

This is a new authorization branch, but it currently returns a denial with no log entry. Please emit a warning/info log so blocked cross-tenant download attempts are traceable. As per coding guidelines, Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/sdk/doc.py` around lines 116 - 117, Before returning the denial from
the KnowledgebaseService.query check, emit a structured log entry (info or
warning) that records the denied tenant_id and the document/kb identifiers
(e.g., doc[0].kb_id and the doc id) plus a short reason like "cross-tenant
access denied"; use the module's existing logger (or create one via
logging.getLogger(__name__) if none exists) and call logger.warning(...)
immediately before the get_error_data_result(...) return so blocked download
attempts are traceable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/sdk/doc.py`:
- Around line 106-109: The beta-token lookup currently reads
APIToken.query(beta=token) and assumes a single match by using
objs[0].tenant_id; change this flow to explicitly detect ambiguity and log
outcomes: call APIToken.query(beta=token) into objs, log the lookup attempt,
then if len(objs) == 0 call get_error_data_result with an authentication error
and log the failure, if len(objs) > 1 reject the request (do not pick objs[0])
and log an ambiguity/error asking for unique token configuration, and only on
len(objs) == 1 proceed to use objs[0].tenant_id and log the successful
authorization; alternatively, if you can change the schema, add a UNIQUE
constraint to the APIToken.beta column/migration to enforce uniqueness at the
database level and keep the added logging around APIToken.query and the
success/failure branches.

---

Nitpick comments:
In `@api/apps/sdk/doc.py`:
- Around line 116-117: Before returning the denial from the
KnowledgebaseService.query check, emit a structured log entry (info or warning)
that records the denied tenant_id and the document/kb identifiers (e.g.,
doc[0].kb_id and the doc id) plus a short reason like "cross-tenant access
denied"; use the module's existing logger (or create one via
logging.getLogger(__name__) if none exists) and call logger.warning(...)
immediately before the get_error_data_result(...) return so blocked download
attempts are traceable.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4506d2b4-3b28-4133-a649-b11cdc48f3a3

📥 Commits

Reviewing files that changed from the base of the PR and between 5018459 and 2ce3c2e.

📒 Files selected for processing (2)
  • api/apps/sdk/doc.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py

Comment thread api/apps/sdk/doc.py Resolved
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Apr 29, 2026
@andesyteoss

Copy link
Copy Markdown
Author

Thanks for the review. I addressed the observability and beta-token ambiguity feedback in commit 9dfae48.\n\nChanges made:\n- Added logging around beta API token lookup attempts, invalid-token failures, ambiguous-token failures, and successful authorization.\n- Explicitly reject ambiguous beta token matches instead of using objs[0].\n- Added a warning log immediately before the cross-tenant document download denial with tenant_id, kb_id, document_id, and the denial reason.\n- Added unit coverage for the ambiguous-token rejection path.\n\nTest note: I attempted to run the targeted pytest file, but the local test bootstrap exits because ZHIPU_AI_API_KEY is not set in this environment.

@yingfeng
yingfeng requested a review from xugangqiang April 30, 2026 05:19
@yingfeng yingfeng added the ci Continue Integration label Apr 30, 2026
@yingfeng
yingfeng marked this pull request as draft April 30, 2026 05:20
@yingfeng
yingfeng marked this pull request as ready for review April 30, 2026 05:20
@codecov

codecov Bot commented Apr 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (a0f9ae1) to head (9dfae48).
⚠️ Report is 24 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14496      +/-   ##
==========================================
- Coverage   95.30%   94.16%   -1.14%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          670      662       -8     
- Misses         16       25       +9     
+ Partials       17       16       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@andesyteoss

Copy link
Copy Markdown
Author

Thanks again. Just to confirm against the latest review pass:

  • Observability for the cross-tenant denial branch (lines 123–129 of api/apps/sdk/doc.py) is in place — logging.warning records tenant_id, kb_id, document_id, and the reason before the get_error_data_result return.
  • Beta-token lookup ambiguity is now explicitly rejected (lines 112–114) with an error log and a dedicated user-facing message, instead of silently picking objs[0].
  • Lookup attempt, invalid-token failure, and successful authorization paths all emit logs.
  • Unit test for the ambiguous-token rejection added in test_doc_sdk_routes_unit.py.

The latest CodeRabbit run also reports "No actionable comments", and the inline comment that surfaced afterwards appears to be an analysis-script fragment with no concrete change request. Happy to address anything further if I missed something.

@xugangqiang

xugangqiang commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

@sebastiondev
May I ask if this API is used other places? If so, we want to change them together.

@xugangqiang xugangqiang self-assigned this Apr 30, 2026
@andesyteoss

Copy link
Copy Markdown
Author

@xugangqiang Thanks for the question. Yes — APIToken.query(beta=token) is used in several other endpoints. A quick grep:

api/apps/sdk/doc.py:108       (this PR)
api/apps/sdk/session.py:148   chatbot_completions
api/apps/sdk/session.py:174   chatbots_inputs
api/apps/sdk/session.py:200   agent_bot_completions
api/apps/sdk/session.py:243   begin_inputs
api/apps/sdk/session.py:264   ask_about_embedded
api/apps/sdk/session.py:303   retrieval_test_embedded
api/apps/sdk/session.py:435   related_questions_embedded
api/apps/sdk/session.py:483   detail_share_embedded
api/apps/sdk/session.py:515   mindmap

Two related concerns apply across these call sites:

  1. Beta-token ambiguity: every site does objs = APIToken.query(beta=token) and then uses objs[0].tenant_id if objs is non-empty, with no check for len(objs) > 1. The right long-term fix is a UNIQUE constraint on APIToken.beta (schema + migration); until then, applying the same explicit len(objs) > 1 rejection used in this PR would harden the other endpoints.

  2. Tenant-scoped resource lookup (the IDOR pattern this PR fixes): of the session.py endpoints, the ones that look up a resource by ID supplied in the URL/body and act on it without joining on tenant_id are the most analogous to the download_doc bug. From a quick read:

    • chatbot_completions / chatbots_inputs resolve dialog_id via DialogService without a tenant filter.
    • agent_bot_completions / begin_inputs resolve agent_id via UserCanvasService without a tenant filter, then pass objs[0].tenant_id into agent_completion / Canvas — this means a valid beta token from tenant A could potentially drive an agent owned by tenant B.
    • ask_about_embedded / retrieval_test_embedded / mindmap accept kb_ids from the request body and don't verify those KBs belong to the token's tenant before retrieval.
    • detail_share_embedded already iterates UserTenantService.query(user_id=tenant_id) and checks ownership, so it looks OK.

I deliberately kept this PR narrowly scoped to the originally reported GET /v1/document/<document_id> IDOR (the issue I tested and have a reproducer for), to keep the diff small and reviewable. If you'd like, I'm happy to do either of the following as a follow-up:

  • Open a separate PR that adds tenant-scoped resource queries + the ambiguous-token rejection across the session.py endpoints listed above, or
  • Extend this PR to cover them all in one go.

Just let me know which you'd prefer and I'll proceed.

@KevinHuSh
KevinHuSh merged commit 7e83c5f into infiniflow:main May 6, 2026
2 checks passed
@lewiswigmore

Copy link
Copy Markdown

Closing this to reduce the open-PR pile-up — we have multiple outstanding security contributions to this repo and that volume is not fair on your review queue. Keeping #14803 (CWE-502: always use RestrictedUnpickler in deserialize_b64 (CWE-502)) as the primary one to focus attention on.

Happy to revisit this finding separately later if it is still relevant. Apologies for the noise.

@lewiswigmore

Copy link
Copy Markdown

Thanks for reviewing.

P.S. Foundation Machines runs Sebastion as a service if continuous security audits would help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants