Repository navigation
Fix: dataset document download route - #14910
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)
📝 WalkthroughWalkthroughMigrates downloads from legacy header-token auth to login-required, dataset-scoped endpoints. Backend removed the unauthenticated ChangesDocument download authentication and scope migration
Sequence DiagramsequenceDiagram
participant User
participant DatasetActionCell as DatasetActionCell
participant FileManagerService as downloadDatasetDocument
participant API as request.get
participant Backend as /datasets/{datasetId}/documents/{documentId}
participant Browser as downloadFileFromBlob
User->>DatasetActionCell: Click download
DatasetActionCell->>DatasetActionCell: Extract file extension
DatasetActionCell->>FileManagerService: downloadDatasetDocument(datasetId, docId, ext)
FileManagerService->>API: request.get(endpoint, responseType=blob)
API->>Backend: GET /datasets/{datasetId}/documents/{documentId}?ext={ext}
Backend->>Backend: `@login_required` validate
Backend->>Backend: `@add_tenant_id_to_kwargs` inject tenant_id
Backend->>Backend: DocumentService.query(kb_id=dataset_id, id=document_id)
alt Document accessible
Backend->>API: Return blob + MIME type
API->>FileManagerService: Blob response
FileManagerService->>DatasetActionCell: Blob data
DatasetActionCell->>DatasetActionCell: Wrap in Blob(MIME)
DatasetActionCell->>Browser: downloadFileFromBlob
Browser->>User: File downloaded
else Unauthorized or not found
Backend->>DatasetActionCell: 401/404 error
DatasetActionCell->>DatasetActionCell: console.error(error)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/sdk/doc.py (1)
93-97:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winAdd explicit dataset ownership check before querying document.
The
downloadhandler queries documents bykb_idanddocument_idwithout verifying the caller owns the dataset. Unlike other handlers in this file (lines 156, 247, 375), it skips theKnowledgebaseService.accessible()check, allowing cross-tenant document access if IDs are known.Additionally, this new flow lacks logging as required by coding guidelines.
Required changes
async def download(tenant_id, dataset_id, document_id): + if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): + logging.warning(f"Unauthorized download attempt: tenant_id={tenant_id}, dataset_id={dataset_id}") + return get_error_data_result(message=f"You don't own the dataset {dataset_id}.") if not document_id: return get_error_data_result(message="Specify document_id please.") + logging.info(f"Document download initiated: tenant_id={tenant_id}, document_id={document_id}") doc = DocumentService.query(kb_id=dataset_id, id=document_id)🤖 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 93 - 97, The download handler currently calls DocumentService.query(kb_id=dataset_id, id=document_id) without verifying ownership; add an explicit ownership check using KnowledgebaseService.accessible(kb_id=dataset_id, user=caller) before querying and return an error if inaccessible, then proceed to call DocumentService.query only when accessible; also add an access log entry (use the module's logger, e.g., processLogger or existing logger) that records the dataset_id, document_id and whether access was allowed or denied to satisfy logging guidelines.
🤖 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 54-57: The download route (async def download) needs minimal
structured logging for the new auth/access flow: log an incoming request with
tenant_id/dataset_id/document_id at function entry, log an access denied or
not-found decision when the code returns 403/404 (include
tenant_id/dataset_id/document_id and reason), and log a success when returning
the document (include tenant_id/dataset_id/document_id and size or document id).
Add these logs inside the download handler (the function decorated by
`@manager.route`, `@login_required`, `@add_tenant_id_to_kwargs`) at the request,
deny/not-found, and success paths using the project’s logger so observability
covers attempt/deny/success.
---
Outside diff comments:
In `@api/apps/sdk/doc.py`:
- Around line 93-97: The download handler currently calls
DocumentService.query(kb_id=dataset_id, id=document_id) without verifying
ownership; add an explicit ownership check using
KnowledgebaseService.accessible(kb_id=dataset_id, user=caller) before querying
and return an error if inaccessible, then proceed to call DocumentService.query
only when accessible; also add an access log entry (use the module's logger,
e.g., processLogger or existing logger) that records the dataset_id, document_id
and whether access was allowed or denied to satisfy logging guidelines.
🪄 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: 7c290a67-58a7-4594-9246-482d2bf34e64
📒 Files selected for processing (4)
api/apps/sdk/doc.pyweb/src/pages/dataset/dataset/dataset-action-cell.tsxweb/src/services/file-manager-service.tsweb/src/utils/api.ts
| @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["GET"]) # noqa: F821 | ||
| @token_required | ||
| @login_required | ||
| @add_tenant_id_to_kwargs | ||
| async def download(tenant_id, dataset_id, document_id): |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add logging for the new download flow (attempt/deny/success).
This route changed auth and access behavior but has no observability points. Add minimal structured logs for request, deny/not-found, and success paths.
🧭 Suggested patch
async def download(tenant_id, dataset_id, document_id):
+ logging.info(
+ "sdk.download request tenant_id=%s dataset_id=%s document_id=%s",
+ tenant_id, dataset_id, document_id
+ )
if not document_id:
return get_error_data_result(message="Specify document_id please.")
doc = DocumentService.query(kb_id=dataset_id, id=document_id)
if not doc:
+ logging.warning(
+ "sdk.download denied_or_missing tenant_id=%s dataset_id=%s document_id=%s",
+ tenant_id, dataset_id, document_id
+ )
return get_error_data_result(message=f"The dataset not own the document {document_id}.")
@@
return await send_file(
file,
as_attachment=True,
attachment_filename=doc[0].name,
mimetype="application/octet-stream", # Set a default MIME type
)As per coding guidelines, **/*.py: Add logging for new flows.
Also applies to: 95-103
🤖 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 54 - 57, The download route (async def
download) needs minimal structured logging for the new auth/access flow: log an
incoming request with tenant_id/dataset_id/document_id at function entry, log an
access denied or not-found decision when the code returns 403/404 (include
tenant_id/dataset_id/document_id and reason), and log a success when returning
the document (include tenant_id/dataset_id/document_id and size or document id).
Add these logs inside the download handler (the function decorated by
`@manager.route`, `@login_required`, `@add_tenant_id_to_kwargs`) at the request,
deny/not-found, and success paths using the project’s logger so observability
covers attempt/deny/success.
| import api from '@/utils/api'; | ||
| import registerServer from '@/utils/register-server'; | ||
| import request from '@/utils/request'; | ||
| export { downloadFileFromBlob } from '@/utils/file-util'; |
There was a problem hiding this comment.
The export function here is unnecessary and should be deleted.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14910 +/- ##
=======================================
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? dataset document download route ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
What problem does this PR solve?
dataset document download route
Type of change