Repository navigation
fix(api): restore DocumentService.accessible check on /preview - #15508
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughRestores a per-user ChangesCross-tenant document preview access control
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
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 |
|
/dosu |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py (1)
179-223: ⚡ Quick winCover the authorized path or assert the
accessible()call.These tests still pass if the handler regresses to
return "Document not found!"for every existing document, so they do not prove thatDocumentService.accessible()is actually gating preview. Please add an owner-allowed case, or at least record/assert theaccessible(doc_id, current_user.id)call in the denial test.Suggested test tightening
def test_cross_tenant_preview_is_denied(self, monkeypatch: pytest.MonkeyPatch) -> None: """A caller whose tenant does NOT own the document gets the same 'Document not found!' response a missing doc would, and storage is never read.""" doc = SimpleNamespace(id="DOC_VICTIM", name="secrets.pdf", type="application") storage_calls: list[tuple] = [] + accessible_calls: list[tuple[str, str]] = [] def _storage_get(*args, **kwargs): storage_calls.append((args, kwargs)) return b"SECRET BYTES" - def _accessible_only_for_owner(_doc_id, user_id): + def _accessible_only_for_owner(_doc_id, user_id): + accessible_calls.append((_doc_id, user_id)) return user_id == "tenant-owner" @@ assert isinstance(result, dict) and result.get("kind") == "data_error", result assert "not found" in result["message"].lower() + assert accessible_calls == [("DOC_VICTIM", "caller-tenant")] assert storage_calls == [], "storage was read despite cross-tenant request" + + def test_owner_preview_reads_storage(self, monkeypatch: pytest.MonkeyPatch) -> None: + doc = SimpleNamespace(id="DOC_OWNER", name="owned.pdf", type="application") + storage_calls: list[tuple] = [] + + def _storage_get(*args, **kwargs): + storage_calls.append((args, kwargs)) + return b"OWNED BYTES" + + module = _load_document_api( + monkeypatch, + doc_get_by_id=(True, doc), + accessible_fn=lambda _doc_id, user_id: user_id == "caller-tenant", + storage_get=_storage_get, + ) + + result = asyncio.run(module.get("DOC_OWNER")) + assert getattr(result, "payload", None) == b"OWNED BYTES" + assert storage_calls == [(("bucket", "key"), {})]🤖 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 `@test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py` around lines 179 - 223, The denial test doesn't verify that DocumentService.accessible() was invoked or that allowed owners can preview; update test_cross_tenant_preview_is_denied to assert the accessible check was called (e.g., track a flag or append to a list inside _accessible_only_for_owner) and add a new positive sub-case (or a separate test) where _accessible_only_for_owner returns True for the current_user id so module.get("DOC_VICTIM") returns the expected preview payload instead of a generic "not found" error; use the existing helpers (_accessible_only_for_owner, storage_get, _load_document_api, and module.get) to implement the assertion and the owner-allowed case.
🤖 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 `@test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py`:
- Around line 179-223: The denial test doesn't verify that
DocumentService.accessible() was invoked or that allowed owners can preview;
update test_cross_tenant_preview_is_denied to assert the accessible check was
called (e.g., track a flag or append to a list inside
_accessible_only_for_owner) and add a new positive sub-case (or a separate test)
where _accessible_only_for_owner returns True for the current_user id so
module.get("DOC_VICTIM") returns the expected preview payload instead of a
generic "not found" error; use the existing helpers (_accessible_only_for_owner,
storage_get, _load_document_api, and module.get) to implement the assertion and
the owner-allowed case.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2af9de04-836e-4063-8bd4-ede89d7762fb
📒 Files selected for processing (2)
api/apps/restful_apis/document_api.pytest/unit_test/api/apps/restful_apis/test_document_preview_accessible.py
|
This fix may affect the preview behavior of embedded chat. |
|
@buua436 Do you have any suggestion on it? |
6ecdf05 to
7c09344
Compare
The /documents/<doc_id>/preview handler gained a duplicate DocumentService.accessible() check (infiniflow#15505) placed before get_by_id, on top of the canonical post-existence check (infiniflow#15508). The early call makes the handler probe access for a missing doc, which the infiniflow#15501 regression test forbids and which leaks a server_error instead of 'Document not found!'. Remove the redundant check (line 1928 still enforces access, so cross-tenant reads stay blocked). Also extend the test's api.apps stub with AUTH_JWT/AUTH_API/AUTH_BETA and a factory-aware login_required so loading document_api.py (which now imports those constants via infiniflow#15581) does not fail at import time.
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 thedoc_id.Root cause
api/apps/restful_apis/document_api.py— theGET /documents/<doc_id>/previewhandler calledDocumentService.get_by_idand went straight toFile2DocumentService.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
current_userto the existingapi.appsimport.get_by_id, callDocumentService.accessible(doc_id, current_user.id); on denial, return the sameget_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).logging.warningwith caller user + doc_id for audit.accessible(doc_id, user_id)(e.g._run_syncatdocument_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 isDocument 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). The loop used here: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 fix(api): check kb ownership in /dify/retrieval #15028 (which restored the sameaccessible()check on/dify/retrieval). The retrieved rule: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 withDocument not found!(indistinguishable from missing) instead. Same auth check, narrower response.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