Skip to content

fix(api): return 4xx not 500 when attachment blob is missing - #15509

Merged
wangq8 merged 6 commits into
infiniflow:mainfrom
dripsmvcp:fix/15502-attachment-download-missing-blob
Jun 15, 2026
Merged

wangq8 merged 6 commits into
infiniflow:mainfrom
dripsmvcp:fix/15502-attachment-download-missing-blob

Conversation

@dripsmvcp

Copy link
Copy Markdown
Contributor

Summary

Guard the agent-attachment download against a missing or empty storage blob so the caller gets a structured 4xx (Document not found!) instead of an HTTP 500. Same bug class as #15365 on document preview.

Root cause

api/apps/restful_apis/agent_api.py — download_attachment reads the blob via STORAGE_IMPL.get(tenant_id, attachment_id) and passes the result directly to make_response(data). When the storage object is missing or empty (orphaned DB metadata, deleted MinIO/S3 object, tenant mismatch), data comes back as None / b"". Quart's make_response(None) raises TypeError: response value cannot be None, which the blanket except Exception converts to server_error_response → HTTP 500.

Fix

  • Add if not data: return get_data_error_result(message="Document not found!") immediately after the storage read, before make_response.
  • Reuse the same Document not found! shape the document preview route uses on its missing-record path — byte-streaming endpoints now respond consistently on a not-found, which also prevents the missing-blob path from being used to enumerate attachment ids across tenants (the auth-fact "exists but empty" is no longer distinguishable from "doesn't exist at all").
  • Imports already in scope (get_data_error_result at agent_api.py:54).

Test plan

Adds test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py with three cases:

  • test_empty_blob_returns_not_found — storage returns None; asserts data_error response with "not found" message, not the server_error shape make_response(None) would produce.
  • test_empty_bytes_returns_not_found — same path with b"".
  • test_nonempty_blob_proceeds — happy path; real bytes flow through make_response untouched.

Stub-loader pattern mirrors test/unit_test/api/apps/sdk/test_dify_retrieval.py (#15028) and test_get_agent_session.py (#15327), both passing in CI.

Scope — what this PR does NOT do

Issue #15502 also raises a separate within-tenant authorization concern: any user in tenant T can download another user-in-T's attachment because there is no attachment→session/user ownership table. Fixing that properly requires a schema change (an attachment-ownership metadata table, or sourcing attachments through an AgentSession/Conversation join). That belongs in a separate PR with maintainer design input on the storage model. This PR addresses only bug (2) Missing empty-blob guard, which is self-contained, sees real production HTTP 500s today (per the issue body), and lands cleanly.

Refs #15502 (rather than Closes) so the bigger authz item stays tracked.

Provenance — how this fix was produced

Authored against a small in-repo cited knowledge base (vouchdev/vouch) seeded from prior work on the sibling fix #15028 / #15508.

Before reading the handler, vouch context "agent attachment download missing authorization tenant" returned the rule recorded after the previous IDOR fix:

ragflow REST byte-streaming routes (preview, download) must deny cross-tenant access with the same response shape as missing-record (e.g. "Document not found!") to prevent ID enumeration.

That claim directly informed the denial shape used here ("Document not found!" rather than a generic 4xx body or a "forbidden" message). The grounding step ran before any code was read, so the design decision was derived from prior precedent rather than re-improvised. Mechanism is not a runtime dependency of this PR — it's process discipline, fully external to the codebase.

Refs #15502

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a falsy-blob guard to download_attachment to return a structured "Attachment not found!" data_error when storage returns None or empty bytes, and a regression test module that verifies None, empty bytes, and non-empty bytes behaviors.

Changes

Attachment Download Missing-Blob Handling

Layer / File(s) Summary
Guard check in download_attachment
api/apps/restful_apis/agent_api.py
After fetching the storage blob, the handler now returns get_data_error_result(message="Attachment not found!") if the retrieved object is falsy (None or empty bytes) instead of calling make_response(data) with None.
Regression test for missing-blob handling
test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py
New test module with helpers and a dynamic loader that stubs imports and STORAGE_IMPL.get; runs three cases: storage -> None, storage -> b"" (both assert data_error with "not found"), and storage -> non-empty bytes (assert response payload equals bytes).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

"I hopped through code with careful paws,
Found a missing blob and fixed the cause,
None and empty bytes now meet my test,
Downloads behave and hop to rest,
🐇📦✨"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a guard to return a 4xx error instead of 500 when attachment blob is missing, which directly matches the changeset modifications.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering the problem, root cause, fix, test plan, scope, and provenance. However, the required template sections (What problem does this PR solve? and Type of change) are not explicitly formatted with their template checkboxes.
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.

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

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

2298-2306: ⚡ Quick win

Consider adding contextual logging for the missing-blob path.

While get_data_error_result logs the error message, it lacks request context (tenant_id, attachment_id) that would help diagnose orphaned storage objects or tenant mismatches. The similar download_agent_file handler at line 449 logs these details.

📊 Proposed logging addition
 data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
 if not data:
+    logging.info(
+        "Attachment download failed: missing blob tenant_id=%s attachment_id=%s",
+        tenant_id,
+        attachment_id,
+    )
     # Storage object missing or empty (orphaned DB metadata, tenant

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 2298 - 2306, The
missing-blob branch that returns get_data_error_result("Document not found!")
lacks contextual logging; add a log statement before the return that records
relevant request context (e.g., tenant_id and attachment_id or equivalent
identifiers available in this handler) so orphaned storage/tenant-mismatch cases
can be diagnosed — mirror the approach used in download_agent_file by logging
those fields alongside a clear message immediately before calling
get_data_error_result.
🤖 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.

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 2298-2306: The missing-blob branch that returns
get_data_error_result("Document not found!") lacks contextual logging; add a log
statement before the return that records relevant request context (e.g.,
tenant_id and attachment_id or equivalent identifiers available in this handler)
so orphaned storage/tenant-mismatch cases can be diagnosed — mirror the approach
used in download_agent_file by logging those fields alongside a clear message
immediately before calling get_data_error_result.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ad0b7c58-44ec-4a66-b442-24df3741b58f

📥 Commits

Reviewing files that changed from the base of the PR and between 4018f02 and 4e80d78.

📒 Files selected for processing (2)
  • api/apps/restful_apis/agent_api.py
  • test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py

@dripsmvcp

Copy link
Copy Markdown
Contributor Author

@dosu

@dosubot

dosubot Bot commented Jun 4, 2026

Copy link
Copy Markdown

This PR looks well-reasoned. The bug is real — download_attachment currently passes the storage result directly to make_response(data) without any null/empty check [1], which means a missing or empty blob triggers TypeError → blanket except → HTTP 500.

The fix follows the same guard pattern established in PR #15365 for document preview/image endpoints [2], and get_data_error_result is already imported in the file [3], so the change is minimal and consistent with existing precedent.

A couple of observations:

  1. Message consistency — PR [Bug]: Document preview and image endpoints return HTTP 500 when storage blob is missing #15365 used "This file is empty." while this PR uses "Document not found!". The "not found" framing is arguably better for a missing blob (vs. a file that exists but has zero bytes), and it matches the document preview route's missing-record path. Just noting the slight divergence in wording across the two PRs.

  2. Scope is appropriate — keeping the authz concern (any user in a tenant downloading another user's attachment) as a separate tracked item makes sense given it requires schema changes.

The test plan with the stub-loader pattern covering None, b"", and the happy path is solid. Looks good to me overall.

To reply, just mention @dosu.


Share context across your team and agents. Try Dosu.

Leave Feedback Learn about ragflow with Dosu Add Dosu to your team

@dripsmvcp

Copy link
Copy Markdown
Contributor Author

@yingfeng Getting attention here. Would you check this PR?

…nfiniflow#15509)

The test stubbed quart and api.utils.api_utils with an incomplete name set, so loading agent_api.py raised ImportError (cannot import name 'Response' / 'validate_request') before any assertion ran — the regression was never actually exercised. Complete the stubs (Response/jsonify, validate_request as an identity decorator factory, pagination_utils, common.constants, common.misc_utils with an async thread_pool_exec, peewee, and STORAGE_IMPL on common.settings) and make stub modules lenient so a future agent_api.py import addition can't silently disable the test again.
@wangq8 wangq8 added the ci Continue Integration label Jun 11, 2026
@wangq8

wangq8 commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

@dripsmvcp please help fix the UT.

@wangq8

wangq8 commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

@buua436

@wangq8
wangq8 requested a review from buua436 June 11, 2026 09:33
The sys.modules stubs guarantee only that agent_api.py imports; in the full test environment 'from common import settings' bound the real common.settings (STORAGE_IMPL=None) instead of the stub, so download_attachment 500'd with "'NoneType' object has no attribute 'get'" and all three cases failed in ragflow_tests. Override the module globals download_attachment reads after exec_module so behaviour is identical in the bare-stub (local) and full-dependency (CI) environments.
@codecov

codecov Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (83e2180) to head (09ab03f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15509   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

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

Could we change this error message to Attachment not found!? This case is for missing/inaccessible attachments, not documents.

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 15, 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.

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/agent_api.py (1)

2368-2376: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add an explicit log for the new not-found early-return path.

The new branch at Line 2368-Line 2376 returns early for missing/empty blobs but does not log the decision at the handler level; please add a structured logging.info/logging.warning before returning so this flow is traceable in ops.

Suggested patch
         data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
         if not data:
+            logging.info(
+                "Attachment download not found: tenant_id=%s attachment_id=%s",
+                tenant_id,
+                attachment_id,
+            )
             # Storage object missing or empty (orphaned DB metadata, tenant
             # mismatch). Without this guard `make_response(None)` raises
             # `TypeError: response value cannot be None` and the caller
             # sees HTTP 500 — same bug class as `#15365` on document
             # preview. Return the same "Attachment not found!" shape used
             # by the preview route's missing-record path so byte-streaming
             # endpoints respond consistently on a not-found.
             return get_data_error_result(message="Attachment not found!")

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 2368 - 2376, The early
return path in the `if not data:` condition (which returns
`get_data_error_result(message="Attachment not found!")`) is missing logging
that would make this flow traceable in operations. Add a structured
`logging.info` or `logging.warning` call before the `get_data_error_result`
return statement to log that the attachment was not found due to missing or
empty storage data, including relevant context like the attachment identifier or
request details to aid debugging.

Source: Coding 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.

Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 2368-2376: The early return path in the `if not data:` condition
(which returns `get_data_error_result(message="Attachment not found!")`) is
missing logging that would make this flow traceable in operations. Add a
structured `logging.info` or `logging.warning` call before the
`get_data_error_result` return statement to log that the attachment was not
found due to missing or empty storage data, including relevant context like the
attachment identifier or request details to aid debugging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 777bbe02-e99a-462b-bfe8-b19f96af4675

📥 Commits

Reviewing files that changed from the base of the PR and between ae8a177 and 09ab03f.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

@wangq8
wangq8 merged commit 53d4d9b into infiniflow:main Jun 15, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants