Skip to content

fix: add document download endpoint and refactor existing download function - #14927

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b049
May 15, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b049

Conversation

@buua436

@buua436 buua436 commented May 14, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

add document download endpoint and refactor existing download function

Type of change

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

@buua436
buua436 requested a review from wangq8 May 14, 2026 09:11
@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: b7baba54-a5ec-4d21-a39d-ab2d26870fe0

📥 Commits

Reviewing files that changed from the base of the PR and between e158911 and e0d61d2.

📒 Files selected for processing (1)
  • api/apps/sdk/doc.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/sdk/doc.py

📝 Walkthrough

Walkthrough

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

Changes

Document Download Endpoints and Backward Compatibility

Layer / File(s) Summary
New SDK direct document download endpoint
api/apps/sdk/doc.py
Adds download_document GET /documents/<document_id>: validates id, queries document by id (no dataset scoping), resolves storage address, loads bytes from storage, errors on empty content, and returns via send_file with original filename and application/octet-stream.
SDK dataset-scoped download signature simplification
api/apps/sdk/doc.py
Removes add_tenant_id_to_kwargs import and drops injected tenant_id parameter from download, changing signature to download(dataset_id, document_id).
REST API backward compatibility for legacy attachment_id
api/apps/restful_apis/document_api.py
download_attachment now sets doc_id = doc_id or attachment_id to support older callers; the shown authorization check using DocumentService.accessible() is removed from that logic path.

Sequence Diagram

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

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • wangq8
  • yingfeng
  • yuzhichang

Poem

🐰 I hopped through routes both old and new,
A document trail for me and you,
One endpoint to fetch, one to simplify,
Legacy paths still catch a skyward try,
Bytes returned with a carrot-sized cue.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description provides only minimal information that essentially repeats the title, lacking substantive detail about the problem being solved or the approach taken. Expand the description to explain the specific problem addressed, why the refactor is necessary, and any breaking changes or migration considerations.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: adding a new document download endpoint and refactoring the existing download function.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 09:12
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 14, 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: 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 win

Remove unused add_tenant_id_to_kwargs import 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_required

As per coding guidelines **/*.py: Use ruff for 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 win

Authorization 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_id before 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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between a98994f and e158911.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
💤 Files with no reviewable changes (1)
  • api/apps/restful_apis/document_api.py

Comment thread api/apps/sdk/doc.py
Comment on lines +115 to +157
@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}.")

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

Comment thread api/apps/sdk/doc.py
Comment on lines +128 to +133
- in: path
name: dataset_id
type: string
required: true
description: ID of the dataset.
- in: path

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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

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 (63df01f) to head (e0d61d2).
⚠️ Report is 1 commits behind head on main.

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

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

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants