Skip to content

fix: move agent attachment download api - #15146

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b053
May 22, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b053

Conversation

@buua436

@buua436 buua436 commented May 22, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

move agent attachment download api to the correct route and update frontend callers

Type of change

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

Notes

  • Move the attachment download endpoint from document routes to agent routes.
  • Update frontend download callers to use the agent attachment endpoint.
  • Reuse the shared file response header helper instead of duplicating it in agent_api.py.

@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a tenant-scoped agent attachment download endpoint, replaces legacy document download with dataset-scoped and global endpoints using send_file, removes duplicate download handlers from the SDK module, and updates frontend/service callers to use the new agent download route.

Changes

Download Endpoint Refactoring

Layer / File(s) Summary
Agent Attachment Download - Backend
api/apps/restful_apis/agent_api.py
New GET /agents/<attachment_id>/download route retrieves bytes from storage, sets Content-Type from ext via CONTENT_TYPE_MAP, applies apply_safe_file_response_headers, and returns the response with make_response.
Document Download Refactor - Backend
api/apps/restful_apis/document_api.py
Removes legacy /documents/<doc_id>/download and adds GET /datasets/<dataset_id>/documents/<document_id> and GET /documents/<document_id> endpoints that resolve storage via File2DocumentService and stream bytes with send_file(BytesIO(...)); also removes an authorization guard from preview/get.
API Routing Definitions
web/src/utils/api.ts
Removes getDocumentFileDownload(docId), adds getDatasetDocumentFileDownload(datasetId, documentId), and adds getAttachmentFileDownload(docId) for agent attachments.
File Manager Service - Agent Download
web/src/services/file-manager-service.ts
Renames downloadFile → downloadAgentFile and switches the request helper from getDocumentFileDownload to getAttachmentFileDownload.
Component Updates
web/src/components/document-download-button/index.tsx, web/src/components/next-message-item/group-button.tsx
Components now call downloadAgentFile with { docId, ext } and keep the same blob/filename download flow.
SDK doc cleanup
api/apps/sdk/doc.py
Removes duplicate download route handlers from SDK module and relocates two constants earlier in the file; no behavior change to the constants.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AgentAPI as AgentAPI:download_attachment
  participant DocumentAPI_dataset as DocumentAPI:download(dataset)
  participant File2DocumentService
  participant STORAGE_IMPL
  participant send_file
  Client->>AgentAPI: GET /agents/{attachment_id}/download?ext=markdown
  AgentAPI->>STORAGE_IMPL: get(tenant_id, attachment_id)
  STORAGE_IMPL-->>AgentAPI: file_bytes
  AgentAPI-->>Client: response with Content-Type and safe headers
  Client->>DocumentAPI_dataset: GET /datasets/{dataset_id}/documents/{document_id}
  DocumentAPI_dataset->>File2DocumentService: get_storage_address(document_id, dataset_id)
  File2DocumentService-->>DocumentAPI_dataset: storage_info
  DocumentAPI_dataset->>STORAGE_IMPL: get(tenant_id, attachment_id)
  STORAGE_IMPL-->>DocumentAPI_dataset: file_bytes
  DocumentAPI_dataset->>send_file: send_file(BytesIO(file_bytes), attachment_filename)
  send_file-->>Client: attachment response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

🐖api, 🌈 python, 🧰 typescript, size:M

Suggested reviewers

  • wangq8
  • JinHai-CN
  • yingfeng

Poem

🐰 I hopped from route to route today,
New paths for files to find their way.
Agents serve and datasets stream,
Bytes wrapped up in safe headers' gleam.
A carrot click — download hooray! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: move agent attachment download api' clearly and concisely summarizes the main change—relocating an attachment download endpoint from document routes to agent routes.
Description check ✅ Passed The description includes the required 'What problem does this PR solve?' section with clear context and the 'Type of change' section with Bug Fix selected, plus additional implementation notes explaining the changes.
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 marked this pull request as ready for review May 22, 2026 05:26
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 22, 2026
@buua436 buua436 added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 22, 2026
@buua436
buua436 marked this pull request as draft May 22, 2026 05:27
@buua436
buua436 marked this pull request as ready for review May 22, 2026 05:27
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 22, 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: 3

🧹 Nitpick comments (2)
api/apps/restful_apis/document_api.py (1)

1867-1922: ⚡ Quick win

Add logging for these new download flows.

Both handlers are new backend entry points, but they do not log request, miss, or failure outcomes. As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 1924-1979

🤖 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/restful_apis/document_api.py` around lines 1867 - 1922, Add
structured logging to the download flow in the download function: log the
incoming request (dataset_id and document_id and current user/context) at start
of download, log a warning when DocumentService.query(dataset_id, document_id)
returns no doc, log errors when File2DocumentService.get_storage_address or
settings.STORAGE_IMPL.get fail or return empty (include exception details if
any), and log a success/info entry when send_file is about to return (include
filename and size/mime if available). Use the existing project logger (e.g.,
processLogger or the module logger) and place logs around calls to
DocumentService.query, File2DocumentService.get_storage_address,
settings.STORAGE_IMPL.get, and before/after send_file to capture request, miss,
failure, and success outcomes.
api/apps/restful_apis/agent_api.py (1)

2272-2284: ⚡ Quick win

Add logging around this new download flow.

This endpoint is new, but it has no request/not-found/failure logging, which makes download issues hard to trace in production. 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/restful_apis/agent_api.py` around lines 2272 - 2284, Add structured
logging around the new download flow in the try block: log an incoming request
with tenant_id, attachment_id and ext before calling thread_pool_exec (use the
module logger), log a not-found/404 event and return path if
settings.STORAGE_IMPL.get returns no data, and log a success event (including
content length or response status) after
make_response/apply_safe_file_response_headers; also log exceptions with full
stack/exception when calling server_error_response. Target the block surrounding
thread_pool_exec, make_response and apply_safe_file_response_headers so logs
cover request, not-found, success and failure cases.
🤖 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/restful_apis/agent_api.py`:
- Around line 2272-2279: The code reads the attachment from storage using
tenant_id + attachment_id without verifying the caller can access that
attachment; first load the attachment metadata and perform an access check
before calling settings.STORAGE_IMPL.get. Specifically, before the
thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id) call,
fetch the attachment record (using your existing attachment/agent lookup helper
or DB API), verify it is associated with an agent the current user/request can
access (use the same permission check used elsewhere for agent access), and only
if that check passes proceed to call settings.STORAGE_IMPL.get and then
make_response/apply_safe_file_response_headers; return an appropriate 403/404 if
the check fails.

In `@api/apps/restful_apis/document_api.py`:
- Around line 1911-1918: The route is performing blocking storage reads directly
(File2DocumentService.get_storage_address and settings.STORAGE_IMPL.get) inside
an async handler before calling send_file; change the synchronous storage access
to run in the thread pool (use await thread_pool_exec(...) to call
settings.STORAGE_IMPL.get with the doc_id/doc_location obtained from
File2DocumentService.get_storage_address) and preserve the existing empty-file
handling, filename/MIME handling for send_file; apply the same conversion for
the other occurrence at the 1968-1975 block so both downloads no longer block
the Quart event loop.
- Around line 1867-1922: The download handler bypasses per-tenant/document
authorization: before calling DocumentService.query or
File2DocumentService.get_storage_address and returning bytes in download, fetch
the current tenant/user context and call
KnowledgebaseService.accessible(dataset_id, tenant_id) and/or
DocumentService.accessible(document_id, tenant_id) to ensure the caller has
access; if access is denied return an error (e.g., get_error_data_result or
appropriate HTTP 403) and only then proceed to call
File2DocumentService.get_storage_address and send_file. Update the download
function to use the tenant/user identity used elsewhere in the app (the same
context used by other endpoints) and check accessibility via
KnowledgebaseService.accessible and/or DocumentService.accessible before reading
or streaming the file.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 2272-2284: Add structured logging around the new download flow in
the try block: log an incoming request with tenant_id, attachment_id and ext
before calling thread_pool_exec (use the module logger), log a not-found/404
event and return path if settings.STORAGE_IMPL.get returns no data, and log a
success event (including content length or response status) after
make_response/apply_safe_file_response_headers; also log exceptions with full
stack/exception when calling server_error_response. Target the block surrounding
thread_pool_exec, make_response and apply_safe_file_response_headers so logs
cover request, not-found, success and failure cases.

In `@api/apps/restful_apis/document_api.py`:
- Around line 1867-1922: Add structured logging to the download flow in the
download function: log the incoming request (dataset_id and document_id and
current user/context) at start of download, log a warning when
DocumentService.query(dataset_id, document_id) returns no doc, log errors when
File2DocumentService.get_storage_address or settings.STORAGE_IMPL.get fail or
return empty (include exception details if any), and log a success/info entry
when send_file is about to return (include filename and size/mime if available).
Use the existing project logger (e.g., processLogger or the module logger) and
place logs around calls to DocumentService.query,
File2DocumentService.get_storage_address, settings.STORAGE_IMPL.get, and
before/after send_file to capture request, miss, failure, and success outcomes.
🪄 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: 56ad4d58-bd51-45d8-a428-3b7e3f5adf60

📥 Commits

Reviewing files that changed from the base of the PR and between a9ec78c and 6d212b4.

📒 Files selected for processing (7)
  • api/apps/restful_apis/agent_api.py
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
  • web/src/components/document-download-button/index.tsx
  • web/src/components/next-message-item/group-button.tsx
  • web/src/services/file-manager-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (1)
  • api/apps/sdk/doc.py

Comment on lines +2272 to +2279
try:
# Keep backward compatibility with older callers and unit tests that still
# pass `attachment_id` instead of the route parameter name.
ext = request.args.get("ext", "markdown")
data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
response = await make_response(data)
content_type = CONTENT_TYPE_MAP.get(ext, f"application/{ext}")
apply_safe_file_response_headers(response, content_type, ext)

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 | 🟠 Major | ⚡ Quick win

Reintroduce an attachment access check before reading storage.

Line 2276 downloads by tenant_id + attachment_id only. This route never proves that the attachment is linked to an agent the caller can access, so any authenticated user who knows a valid attachment id in the tenant can fetch it directly.

🤖 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/restful_apis/agent_api.py` around lines 2272 - 2279, The code reads
the attachment from storage using tenant_id + attachment_id without verifying
the caller can access that attachment; first load the attachment metadata and
perform an access check before calling settings.STORAGE_IMPL.get. Specifically,
before the thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
call, fetch the attachment record (using your existing attachment/agent lookup
helper or DB API), verify it is associated with an agent the current
user/request can access (use the same permission check used elsewhere for agent
access), and only if that check passes proceed to call settings.STORAGE_IMPL.get
and then make_response/apply_safe_file_response_headers; return an appropriate
403/404 if the check fails.

Comment on lines +1867 to +1922
@manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["GET"]) # noqa: F821
@login_required
@add_tenant_id_to_kwargs
async def download_attachment(tenant_id=None, doc_id=None, attachment_id=None):
"""Stream a document's underlying file to the requesting user.

Mirrors the authorization model of the preview endpoint: the user must belong
to the tenant that owns the document's knowledge base. A denial returns the
same "Document not found!" response so the endpoint cannot be used to
enumerate doc ids across tenants.
async def download(dataset_id, document_id):
"""
try:
# Keep backward compatibility with older callers and unit tests that still
# pass `attachment_id` instead of the route parameter name.
doc_id = doc_id or attachment_id
ext = request.args.get("ext", "markdown")
data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id)
response = await make_response(data)
content_type = CONTENT_TYPE_MAP.get(ext, f"application/{ext}")
apply_safe_file_response_headers(response, content_type, ext)

return response
Download a document from a dataset.
---
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(kb_id=dataset_id, id=document_id)
if not doc:
return get_error_data_result(message=f"The dataset not own the document {document_id}.")
# The process of downloading
doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
file_stream = settings.STORAGE_IMPL.get(doc_id, doc_location)
if not file_stream:
return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
file = BytesIO(file_stream)
# Use send_file with a proper filename and MIME type
return await send_file(
file,
as_attachment=True,
attachment_filename=doc[0].name,
mimetype="application/octet-stream", # Set a default MIME type
)

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

These download endpoints bypass document authorization.

Line 1907 only verifies dataset membership, and Line 1964 only verifies existence. Neither handler injects tenant_id nor checks KnowledgebaseService.accessible(...) / DocumentService.accessible(...) before returning file bytes, so any authenticated user with a valid id can download another user's document.

Also applies to: 1924-1979

🤖 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/restful_apis/document_api.py` around lines 1867 - 1922, The download
handler bypasses per-tenant/document authorization: before calling
DocumentService.query or File2DocumentService.get_storage_address and returning
bytes in download, fetch the current tenant/user context and call
KnowledgebaseService.accessible(dataset_id, tenant_id) and/or
DocumentService.accessible(document_id, tenant_id) to ensure the caller has
access; if access is denied return an error (e.g., get_error_data_result or
appropriate HTTP 403) and only then proceed to call
File2DocumentService.get_storage_address and send_file. Update the download
function to use the tenant/user identity used elsewhere in the app (the same
context used by other endpoints) and check accessibility via
KnowledgebaseService.accessible and/or DocumentService.accessible before reading
or streaming the file.

Comment on lines +1911 to +1918
doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
file_stream = settings.STORAGE_IMPL.get(doc_id, doc_location)
if not file_stream:
return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
file = BytesIO(file_stream)
# Use send_file with a proper filename and MIME type
return await send_file(
file,

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 | 🟠 Major | ⚡ Quick win

Move the storage reads off the async request path.

Both new handlers call settings.STORAGE_IMPL.get(...) synchronously inside an async route. The rest of this module already uses await thread_pool_exec(...) for the same storage call, and this path will otherwise block the Quart event loop during every download.

♻️ Suggested change
-    file_stream = settings.STORAGE_IMPL.get(doc_id, doc_location)
+    file_stream = await thread_pool_exec(settings.STORAGE_IMPL.get, doc_id, doc_location)
...
-    file_stream = settings.STORAGE_IMPL.get(doc_id, doc_location)
+    file_stream = await thread_pool_exec(settings.STORAGE_IMPL.get, doc_id, doc_location)

Also applies to: 1968-1975

🤖 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/restful_apis/document_api.py` around lines 1911 - 1918, The route is
performing blocking storage reads directly
(File2DocumentService.get_storage_address and settings.STORAGE_IMPL.get) inside
an async handler before calling send_file; change the synchronous storage access
to run in the thread pool (use await thread_pool_exec(...) to call
settings.STORAGE_IMPL.get with the doc_id/doc_location obtained from
File2DocumentService.get_storage_address) and preserve the existing empty-file
handling, filename/MIME handling for send_file; apply the same conversion for
the other occurrence at the 1968-1975 block so both downloads no longer block
the Quart event loop.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/document_api.py (1)

1837-1865: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Preview endpoint also lacks tenant authorization.

Per the AI summary, the authorization guard DocumentService.accessible(..., current_user.id) was removed from this endpoint. Now any authenticated user can preview any document by knowing its ID, similar to the download endpoints.

Consider adding @add_tenant_id_to_kwargs and verifying DocumentService.accessible(doc_id, tenant_id) before returning file bytes—or confirm this is intentionally public for authenticated users.

🛡️ Suggested fix to add authorization check
 `@manager.route`("/documents/<doc_id>/preview", methods=["GET"])  # noqa: F821
 `@login_required`
-async def get(doc_id):
+@add_tenant_id_to_kwargs
+async def get(tenant_id, doc_id):
     """Return the raw file bytes for a document the requesting user is authorized to read.
 
     The user must belong to the tenant that owns the document's knowledge base; otherwise
     the response is indistinguishable from a missing document to avoid cross-tenant ID
     enumeration.
     """
     try:
+        if not DocumentService.accessible(doc_id, tenant_id):
+            return get_data_error_result(message="Document not found!")
 
         e, doc = DocumentService.get_by_id(doc_id)
         if not e:
             return get_data_error_result(message="Document not found!")
🤖 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/restful_apis/document_api.py` around lines 1837 - 1865, The preview
endpoint function get(doc_id) is missing the tenant authorization guard; add
`@add_tenant_id_to_kwargs` to the route (or otherwise obtain tenant_id) and call
DocumentService.accessible(doc_id, tenant_id or current_user.id) before fetching
storage via File2DocumentService.get_storage_address and thread_pool_exec; if
accessible is False return the same "Document not found" get_data_error_result
to avoid leaking existence, otherwise continue to build the response and call
apply_safe_file_response_headers as before.
🤖 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.

Outside diff comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1837-1865: The preview endpoint function get(doc_id) is missing
the tenant authorization guard; add `@add_tenant_id_to_kwargs` to the route (or
otherwise obtain tenant_id) and call DocumentService.accessible(doc_id,
tenant_id or current_user.id) before fetching storage via
File2DocumentService.get_storage_address and thread_pool_exec; if accessible is
False return the same "Document not found" get_data_error_result to avoid
leaking existence, otherwise continue to build the response and call
apply_safe_file_response_headers as before.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 91b49c31-db62-4f9f-8e81-5e7495f72fef

📥 Commits

Reviewing files that changed from the base of the PR and between 6d212b4 and 72fd462.

📒 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/sdk/doc.py

@codecov

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (57ddd79) to head (72fd462).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15146      +/-   ##
==========================================
- Coverage   94.53%   93.12%   -1.41%     
==========================================
  Files          10       10              
  Lines         713      713              
  Branches      116      116              
==========================================
- Hits          674      664      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

@wangq8
wangq8 merged commit 71a52d5 into infiniflow:main May 22, 2026
1 check passed
@wangq8 wangq8 mentioned this pull request May 25, 2026
1 task done
wangq8 added a commit that referenced this pull request May 25, 2026
Follow on PR #15146 to reslove the backwad compatability issue.

1. /agents/<attachment_id>/download ->
/agents/attachments/<attachment_id>/download

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
nickmopen added a commit to nickmopen/ragflow that referenced this pull request May 27, 2026
Mirror GetDetail's pattern (internal/service/kb.go:198-214) and have
KnowledgebaseService.UpdateMetadataSetting itself call kbDAO.Accessible
before mutating parser_config. The handler-level guard still fires first
in the normal HTTP path, but if a future caller invokes the service
directly (or a handler refactor drops its own check the way infiniflow#15146 did
to the document preview endpoint), the service still refuses the write.

Handler now passes user.ID into the service and translates the "authorized"
sentinel to CodeAuthenticationError exactly like GetDetail does, so the
two layers return a consistent error to the client.
wangq8 pushed a commit that referenced this pull request Jun 4, 2026
## Summary
Restore the `DocumentService.accessible(doc_id, current_user.id)` check
that PR #15146 dropped from the REST document preview handler. Any
authenticated caller could download any tenant's document bytes by
guessing/knowing the `doc_id`.

## Root cause
`api/apps/restful_apis/document_api.py` — the `GET
/documents/<doc_id>/preview` handler called `DocumentService.get_by_id`
and went straight to `File2DocumentService.get_storage_address` +
`STORAGE_IMPL.get`, with no tenant check between the lookup and the
read. The handler's docstring even promises "user must belong to the
tenant that owns the document's knowledge base" — the code didn't
enforce it.

## Fix
- Add `current_user` to the existing `api.apps` import.
- Immediately after `get_by_id`, call
`DocumentService.accessible(doc_id, current_user.id)`; on denial, return
the **same** `get_data_error_result(message="Document not found!")`
shape used for the missing-doc branch. That makes a cross-tenant probe
indistinguishable from a missing-doc probe, preventing ID enumeration
(the issue body calls this out explicitly).
- Emit `logging.warning` with caller user + doc_id for audit.
- Restores symmetry with peer routes that already call
`accessible(doc_id, user_id)` (e.g. `_run_sync` at
`document_api.py:1380`).

## Test plan
Adds
`test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py`:

- **`test_cross_tenant_preview_is_denied`** — owner tenant ≠ caller
tenant; asserts the response shape is `Document not found!` and the
storage backend (`thread_pool_exec(STORAGE_IMPL.get, ...)`) is **never**
invoked.
- **`test_missing_doc_returns_not_found`** — missing-doc behaviour
unchanged.

Stub-loader pattern mirrors
`test/unit_test/api/apps/sdk/test_dify_retrieval.py` (added in #15028,
passing in CI).

## Provenance — how this fix was produced

This PR was authored against a small cited knowledge base committed in
the working tree as a `.vouch/` (see
[vouchdev/vouch](https://github.com/vouchdev/vouch)). The loop used
here:

1. **Grounding first.** Before reading the handler, queried the KB for
prior context: `vouch context "tenant scoped accessible authorization"`
→ retrieved a cited claim distilled from PR #15028 (which restored the
same `accessible()` check on `/dify/retrieval`). The retrieved rule:

> *ragflow REST endpoints that load by tenant-scoped id must call
`<Service>.accessible(id, tenant_id)` after `get_by_id` and before
storage/DB read; deny with code 109 'No authorization.' and log a
warning. Established by PR #15028.*

2. **Applied the pattern with a domain refinement.** For an API/JSON
endpoint, `No authorization.` is the right denial shape. For a
**byte-streaming, browser-facing** endpoint like `/preview`, leaking
*existence* itself enables enumeration — so per the issue's expected
behaviour, this PR denies with `Document not found!` (indistinguishable
from missing) instead. Same auth check, narrower response.

3. **Recorded the refinement back into the KB** as a new cited claim, so
the next IDOR-class issue starts already grounded in both the general
pattern and the byte-route nuance.

Net effect of the workflow: the fix replicates a known-good pattern
instead of reinventing it, *and* the place where the pattern was nuanced
is now retrievable for the next pass. Mechanism is fully independent of
this PR — it's not a runtime dependency, just process discipline.

Closes #15501
wangq8 pushed a commit that referenced this pull request Jun 4, 2026
Restore `DocumentService.accessible` on `GET
/api/v1/documents/{doc_id}/preview` so cross-tenant users cannot stream
documents by UUID.

Fixes #15501

### What problem does this PR solve?

PR #15146 (`71a52d579`) moved the agent attachment download route and
accidentally removed the `DocumentService.accessible(doc_id,
current_user.id)` guard from the REST preview handler. The endpoint
still requires login, but any authenticated user who knows another
tenant's `doc_id` can download the raw file bytes.

This restores the same authorization check that existed before #15146,
returning a generic `"Document not found!"` when access is denied (no
cross-tenant ID enumeration). SDK download routes tracked in #15125 are
unchanged.

### 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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants