Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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. ChangesAttachment Download Missing-Blob Handling
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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.
🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)
2298-2306: ⚡ Quick winConsider adding contextual logging for the missing-blob path.
While
get_data_error_resultlogs the error message, it lacks request context (tenant_id, attachment_id) that would help diagnose orphaned storage objects or tenant mismatches. The similardownload_agent_filehandler 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, tenantAs 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
📒 Files selected for processing (2)
api/apps/restful_apis/agent_api.pytest/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py
|
This PR looks well-reasoned. The bug is real — The fix follows the same guard pattern established in PR #15365 for document preview/image endpoints [2], and A couple of observations:
The test plan with the stub-loader pattern covering To reply, just mention @dosu. Share context across your team and agents. Try Dosu. |
|
@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.
|
@dripsmvcp please help fix the UT. |
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
buua436
left a comment
There was a problem hiding this comment.
Could we change this error message to Attachment not found!? This case is for missing/inaccessible attachments, not documents.
There was a problem hiding this comment.
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 winAdd 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.warningbefore 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
📒 Files selected for processing (1)
api/apps/restful_apis/agent_api.py
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_attachmentreads the blob viaSTORAGE_IMPL.get(tenant_id, attachment_id)and passes the result directly tomake_response(data). When the storage object is missing or empty (orphaned DB metadata, deleted MinIO/S3 object, tenant mismatch),datacomes back asNone/b"". Quart'smake_response(None)raisesTypeError: response value cannot be None, which the blanketexcept Exceptionconverts toserver_error_response→ HTTP 500.Fix
if not data: return get_data_error_result(message="Document not found!")immediately after the storage read, beforemake_response.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").get_data_error_resultatagent_api.py:54).Test plan
Adds
test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.pywith three cases:test_empty_blob_returns_not_found— storage returnsNone; assertsdata_errorresponse with "not found" message, not theserver_errorshapemake_response(None)would produce.test_empty_bytes_returns_not_found— same path withb"".test_nonempty_blob_proceeds— happy path; real bytes flow throughmake_responseuntouched.Stub-loader pattern mirrors
test/unit_test/api/apps/sdk/test_dify_retrieval.py(#15028) andtest_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/Conversationjoin). 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 thanCloses) 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: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