Repository navigation
fix: authorize beta document downloads by tenant - #14496
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthrough
Changes
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
api/apps/sdk/doc.pytest/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
|
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. |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Thanks again. Just to confirm against the latest review pass:
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. |
|
@sebastiondev |
|
@xugangqiang Thanks for the question. Yes — Two related concerns apply across these call sites:
I deliberately kept this PR narrowly scoped to the originally reported
Just let me know which you'd prefer and I'll proceed. |
|
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. |
|
Thanks for reviewing. P.S. Foundation Machines runs Sebastion as a service if continuous security audits would help. |
Summary
This fixes a missing authorization check in the beta API document download endpoint:
GET /api/v1/documents/<document_id>inapi/apps/sdk/doc.pyAPIToken.query(beta=token), acceptsdocument_iddirectly from the URL, loads the document withDocumentService.query(id=document_id), and then fetches the backing object throughFile2DocumentService.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:
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:You do not have access to this document.;I also verified the final patch is limited to
api/apps/sdk/doc.pyand the related document SDK route unit test. A localpytestinvocation could not complete in this checkout because the shared test fixture attempts to log in to a RAGFlow server at127.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