Repository navigation
fix: add document download endpoint and refactor existing download function - #14927
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a new SDK endpoint GET /documents/<document_id>, simplifies the dataset-scoped SDK download handler signature (removes tenant injection), and makes the REST API download_attachment accept legacy attachment_id when doc_id is missing. ChangesDocument Download Endpoints and Backward Compatibility
Sequence DiagramsequenceDiagram
participant Client
participant download_document
participant DocumentService
participant File2DocumentService
participant STORAGE_IMPL
Client->>download_document: GET /documents/<document_id>
download_document->>DocumentService: query(id=document_id)
DocumentService-->>download_document: document record(s)
download_document->>File2DocumentService: get_storage_address(document)
File2DocumentService-->>download_document: storage address
download_document->>STORAGE_IMPL: load(storage address)
STORAGE_IMPL-->>download_document: file bytes
download_document-->>Client: send_file(filename, application/octet-stream)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
api/apps/sdk/doc.py (2)
31-31:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRemove unused
add_tenant_id_to_kwargsimport to unblock CI.Line 31 imports
add_tenant_id_to_kwargs, but it is no longer used and is currently failing Ruff (F401) in CI.Suggested fix
-from api.utils.api_utils import check_duplicate_ids, construct_json_result, get_error_data_result, get_request_json, get_result, server_error_response, token_required, add_tenant_id_to_kwargs +from api.utils.api_utils import check_duplicate_ids, construct_json_result, get_error_data_result, get_request_json, get_result, server_error_response, token_requiredAs per coding guidelines
**/*.py: Userufffor linting and formatting Python code.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/sdk/doc.py` at line 31, The import line in api.apps.sdk.doc imports add_tenant_id_to_kwargs but that symbol is unused and triggers Ruff F401; remove add_tenant_id_to_kwargs from the import list alongside the other helpers (check_duplicate_ids, construct_json_result, get_error_data_result, get_request_json, get_result, server_error_response, token_required) so the import only includes the actually used names, then run the linter to confirm the unused-import error is resolved.
56-96:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winAuthorization check was dropped from dataset-scoped download path.
After the signature simplification, this handler no longer verifies that the logged-in user owns or can access
dataset_idbefore file retrieval.DocumentService.query(kb_id=dataset_id, id=document_id)only validates association, not caller authorization.Please restore an explicit ownership/access check before returning file bytes.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/sdk/doc.py` around lines 56 - 96, The download handler lost an authorization check: before calling DocumentService.query or returning file bytes in download, retrieve the authenticated caller (e.g. current_user / request context) and verify they have access/ownership of dataset_id (call the appropriate dataset/access check method such as DatasetService.has_access(dataset_id, user) or DatasetService.query with a user parameter); if the check fails, return get_error_data_result with an unauthorized message and do not proceed to fetch file bytes. Ensure this authorization check happens before using DocumentService.query(kb_id=dataset_id, id=document_id) or returning any document content.
🧹 Nitpick comments (1)
api/apps/sdk/doc.py (1)
115-170: ⚡ Quick winAdd logging for the new download flow.
The new endpoint introduces a new file-download path without request/outcome logging (success/failure context). Please add structured logs (e.g., document_id, caller identity/tenant, outcome/error) around validation and retrieval.
As per coding guidelines
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/sdk/doc.py` around lines 115 - 170, Add structured logging to the download_document flow: log at validation failure (when document_id is missing), after DocumentService.query (document not found or found), after File2DocumentService.get_storage_address and settings.STORAGE_IMPL.get (storage lookup failure or file empty), and on successful handoff to send_file; include document_id, caller identity/tenant (from login context/session), and outcome/error details. Use the existing logger used elsewhere in the project (e.g., processLogger or module logger) and include error objects/messages in error logs; keep logs concise and structured (fields: document_id, user_id/tenant_id, outcome: success|not_found|empty|error, error/message). Ensure these logs are placed around the calls to DocumentService.query, File2DocumentService.get_storage_address, settings.STORAGE_IMPL.get, and immediately before/after await send_file in download_document.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/sdk/doc.py`:
- Around line 128-133: The OpenAPI parameters in api/apps/sdk/doc.py are
incorrect for the route: remove the path parameter entry for "dataset_id" and
replace it with a required path parameter "document_id" (or rename the existing
path param) so the spec matches the actual route "/documents/<document_id>";
update the "name", "description" and "in: path" fields accordingly for the
parameter used by the endpoint handler (document_id) and ensure "required: true"
remains set.
- Around line 115-157: The download_document endpoint currently calls
DocumentService.query(id=document_id) without scoping, so add an explicit
ownership/ACL check before returning storage content: fetch the document scoped
to the current user/tenant (e.g., call DocumentService.query(id=document_id,
tenant_id=current_tenant.id) or use a helper like
DocumentService.get_for_tenant/document_for_user) or after fetching assert
doc.owner_id == current_user.id (or check doc.allowed_users/acl), and if the
check fails return get_error_data_result(...) with a permission/404-style
message instead of proceeding to stream the file; apply this check inside
download_document before any storage access.
---
Outside diff comments:
In `@api/apps/sdk/doc.py`:
- Line 31: The import line in api.apps.sdk.doc imports add_tenant_id_to_kwargs
but that symbol is unused and triggers Ruff F401; remove add_tenant_id_to_kwargs
from the import list alongside the other helpers (check_duplicate_ids,
construct_json_result, get_error_data_result, get_request_json, get_result,
server_error_response, token_required) so the import only includes the actually
used names, then run the linter to confirm the unused-import error is resolved.
- Around line 56-96: The download handler lost an authorization check: before
calling DocumentService.query or returning file bytes in download, retrieve the
authenticated caller (e.g. current_user / request context) and verify they have
access/ownership of dataset_id (call the appropriate dataset/access check method
such as DatasetService.has_access(dataset_id, user) or DatasetService.query with
a user parameter); if the check fails, return get_error_data_result with an
unauthorized message and do not proceed to fetch file bytes. Ensure this
authorization check happens before using DocumentService.query(kb_id=dataset_id,
id=document_id) or returning any document content.
---
Nitpick comments:
In `@api/apps/sdk/doc.py`:
- Around line 115-170: Add structured logging to the download_document flow: log
at validation failure (when document_id is missing), after DocumentService.query
(document not found or found), after File2DocumentService.get_storage_address
and settings.STORAGE_IMPL.get (storage lookup failure or file empty), and on
successful handoff to send_file; include document_id, caller identity/tenant
(from login context/session), and outcome/error details. Use the existing logger
used elsewhere in the project (e.g., processLogger or module logger) and include
error objects/messages in error logs; keep logs concise and structured (fields:
document_id, user_id/tenant_id, outcome: success|not_found|empty|error,
error/message). Ensure these logs are placed around the calls to
DocumentService.query, File2DocumentService.get_storage_address,
settings.STORAGE_IMPL.get, and immediately before/after await send_file in
download_document.
🪄 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: 30623edd-d3e0-423e-b8e6-51ccfc4fde2a
📒 Files selected for processing (2)
api/apps/restful_apis/document_api.pyapi/apps/sdk/doc.py
💤 Files with no reviewable changes (1)
- api/apps/restful_apis/document_api.py
| @manager.route("/documents/<document_id>", methods=["GET"]) # noqa: F821 | ||
| @login_required | ||
| async def download_document(document_id): | ||
| """ | ||
| Download a document. | ||
| --- | ||
| tags: | ||
| - Documents | ||
| security: | ||
| - ApiKeyAuth: [] | ||
| produces: | ||
| - application/octet-stream | ||
| parameters: | ||
| - in: path | ||
| name: dataset_id | ||
| type: string | ||
| required: true | ||
| description: ID of the dataset. | ||
| - in: path | ||
| name: document_id | ||
| type: string | ||
| required: true | ||
| description: ID of the document to download. | ||
| - in: header | ||
| name: Authorization | ||
| type: string | ||
| required: true | ||
| description: Bearer token for authentication. | ||
| responses: | ||
| 200: | ||
| description: Document file stream. | ||
| schema: | ||
| type: file | ||
| 400: | ||
| description: Error message. | ||
| schema: | ||
| type: object | ||
| """ | ||
| if not document_id: | ||
| return get_error_data_result(message="Specify document_id please.") | ||
| doc = DocumentService.query(id=document_id) | ||
| if not doc: | ||
| return get_error_data_result(message=f"The dataset not own the document {document_id}.") |
There was a problem hiding this comment.
Direct /documents/<document_id> download endpoint is missing tenant/user scoping.
DocumentService.query(id=document_id) fetches by document ID only, then returns storage content. This allows authenticated users to download documents outside their ownership if IDs are discoverable.
Add an explicit authorization guard (tenant/user ownership or ACL check) before fetching storage data.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/apps/sdk/doc.py` around lines 115 - 157, The download_document endpoint
currently calls DocumentService.query(id=document_id) without scoping, so add an
explicit ownership/ACL check before returning storage content: fetch the
document scoped to the current user/tenant (e.g., call
DocumentService.query(id=document_id, tenant_id=current_tenant.id) or use a
helper like DocumentService.get_for_tenant/document_for_user) or after fetching
assert doc.owner_id == current_user.id (or check doc.allowed_users/acl), and if
the check fails return get_error_data_result(...) with a permission/404-style
message instead of proceeding to stream the file; apply this check inside
download_document before any storage access.
| - in: path | ||
| name: dataset_id | ||
| type: string | ||
| required: true | ||
| description: ID of the dataset. | ||
| - in: path |
There was a problem hiding this comment.
OpenAPI parameters don’t match the new route.
The route is /documents/<document_id>, but the spec marks dataset_id as a required path parameter. This will generate incorrect API docs/clients.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/apps/sdk/doc.py` around lines 128 - 133, The OpenAPI parameters in
api/apps/sdk/doc.py are incorrect for the route: remove the path parameter entry
for "dataset_id" and replace it with a required path parameter "document_id" (or
rename the existing path param) so the spec matches the actual route
"/documents/<document_id>"; update the "name", "description" and "in: path"
fields accordingly for the parameter used by the endpoint handler (document_id)
and ensure "required: true" remains set.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14927 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
add document download endpoint and refactor existing download function
Type of change