Skip to content

Fix: dataset document download route - #14910

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
buua436:d002
May 14, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
buua436:d002

Conversation

@buua436

@buua436 buua436 commented May 14, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

dataset document download route

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 708bfb4d-dc81-453e-9586-64c4bab13996

📥 Commits

Reviewing files that changed from the base of the PR and between eba9535 and 92efce2.

📒 Files selected for processing (1)
  • web/src/services/file-manager-service.ts

📝 Walkthrough

Walkthrough

Migrates downloads from legacy header-token auth to login-required, dataset-scoped endpoints. Backend removed the unauthenticated /documents/<document_id> handler and now validates document access via kb_id=dataset_id. Frontend calls a new downloadDatasetDocument service and saves the returned blob.

Changes

Document download authentication and scope migration

Layer / File(s) Summary
Backend endpoint authentication and document access
api/apps/sdk/doc.py
Switched from token_required to login_required + add_tenant_id_to_kwargs. Document access validated via DocumentService.query(kb_id=dataset_id, id=document_id). Removed legacy /documents/<document_id> handler and cleaned unused imports.
Frontend API endpoint and download service
web/src/utils/api.ts, web/src/services/file-manager-service.ts
Added getDatasetDocumentFileDownload(datasetId, documentId) URL builder and exported downloadDatasetDocument({datasetId, docId, ext}) which requests a blob response and passes ext as query param.
UI component async download flow
web/src/pages/dataset/dataset/dataset-action-cell.tsx
Reworked download action to async: derive file extension, call downloadDatasetDocument, construct Blob from response/MIME type, call downloadFileFromBlob, and log errors in try/catch.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

🐞 bug, size:L, 🐖api, 🧰 typescript

Suggested reviewers

  • wangq8
  • yuzhichang
  • JinHai-CN
  • yingfeng

Poem

🐰 A little rabbit hops with glee,
Tokens tucked away, now login's key,
Blobs arrive with mime in hand,
Downloads land across the land,
Tenants safe — hop, dance, and stand!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is largely incomplete; it provides minimal context about the specific problem being solved and lacks substantive detail beyond the checkbox selection. Expand the description with specific details about what issue the download route fix addresses, why it was necessary, and what changes were made to resolve it.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: fixing the dataset document download route, which aligns with the primary modifications across backend and frontend files.
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

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

@buua436 buua436 added the ci Continue Integration label May 14, 2026
@buua436
buua436 marked this pull request as ready for review May 14, 2026 02:27
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 14, 2026
@wangq8
wangq8 requested a review from cike8899 May 14, 2026 02:27

@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

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 win

Add explicit dataset ownership check before querying document.

The download handler queries documents by kb_id and document_id without verifying the caller owns the dataset. Unlike other handlers in this file (lines 156, 247, 375), it skips the KnowledgebaseService.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

📥 Commits

Reviewing files that changed from the base of the PR and between b2b6360 and eba9535.

📒 Files selected for processing (4)
  • api/apps/sdk/doc.py
  • web/src/pages/dataset/dataset/dataset-action-cell.tsx
  • web/src/services/file-manager-service.ts
  • web/src/utils/api.ts

Comment thread api/apps/sdk/doc.py
Comment on lines 54 to 57
@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):

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.

🛠️ 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';

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.

The export function here is unnecessary and should be deleted.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 14, 2026
@codecov

codecov Bot commented May 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (b18640d) to head (92efce2).
⚠️ Report is 16 commits behind head on main.

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.
📢 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.

@JinHai-CN
JinHai-CN merged commit b89878c into infiniflow:main May 14, 2026
1 check passed
tmimmanuel pushed a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
### What problem does this PR solve?

dataset document download route
### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants