Skip to content

fix(api): restore DocumentService.accessible check on /preview - #15508

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
dripsmvcp:fix/15501-document-preview-accessible
Jun 4, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
dripsmvcp:fix/15501-document-preview-accessible

Conversation

@dripsmvcp

Copy link
Copy Markdown
Contributor

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). 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 fix(api): check kb ownership in /dify/retrieval #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 fix(api): check kb ownership in /dify/retrieval #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

@dosubot dosubot Bot added size:S This PR changes 10-29 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

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: 3c5c80a8-cebb-4fdc-afc1-bc56c29c5819

📥 Commits

Reviewing files that changed from the base of the PR and between 6ecdf05 and 7c09344.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • api/apps/restful_apis/document_api.py
  • test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py

📝 Walkthrough

Walkthrough

Restores a per-user DocumentService.accessible(doc_id, current_user.id) check in the /documents/<doc_id>/preview handler and adds regression tests that assert denied preview requests return "Document not found!" and never call storage.

Changes

Cross-tenant document preview access control

Layer / File(s) Summary
Access control in preview handler
api/apps/restful_apis/document_api.py
Imports current_user and calls DocumentService.accessible(doc_id, current_user.id) after document lookup; on denial logs a warning and returns "Document not found!" without fetching storage.
Regression tests for cross-tenant access denial
test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py
Adds a test module that dynamically loads the preview handler with monkeypatched dependencies to validate: cross-tenant preview is denied with a data_error "Document not found!" and storage is not invoked; missing documents return the same error and do not trigger accessible().

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15366: Modifies the same preview handler; adds a missing-storage-blob guard and structured 4xx handling.
  • infiniflow/ragflow#14625: Also reintroduces DocumentService.accessible(...) checks for document download/preview routes with tests.

Suggested labels

🐖api, 🧪 test

Suggested reviewers

  • wangq8
  • JinHai-CN

Poem

🐰 A sneaky doc once hopped the fence,

But now accessible() guards commence.
Tests stand watch, storage stays away,
No peeking past the tenant's way.
Hooray—secure hops for another day!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.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 clearly and concisely summarizes the main change: restoring the DocumentService.accessible check on the /preview endpoint to address a cross-tenant access vulnerability.
Description check ✅ Passed The description comprehensively covers the problem, root cause, fix, test plan, and provenance, matching the required template sections with appropriate detail.
Linked Issues check ✅ Passed The PR fully addresses all objectives from #15501: restores DocumentService.accessible check after get_by_id, denies with generic 'Document not found!' to prevent enumeration, preserves missing-doc behavior, matches other secured routes, and includes tests verifying cross-tenant denial and unchanged missing-document behavior.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the stated objectives: the authorization check addition to document_api.py and comprehensive regression tests for the preview endpoint, with no unrelated modifications.

✏️ 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.

@dripsmvcp

Copy link
Copy Markdown
Contributor Author

/dosu

@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)
test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py (1)

179-223: ⚡ Quick win

Cover 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 that DocumentService.accessible() is actually gating preview. Please add an owner-allowed case, or at least record/assert the accessible(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

📥 Commits

Reviewing files that changed from the base of the PR and between 5733e06 and 6ecdf05.

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

@buua436

buua436 commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

This fix may affect the preview behavior of embedded chat.

@dripsmvcp

Copy link
Copy Markdown
Contributor Author

@buua436 Do you have any suggestion on it?

@dripsmvcp
dripsmvcp force-pushed the fix/15501-document-preview-accessible branch from 6ecdf05 to 7c09344 Compare June 4, 2026 01:47
@wangq8
wangq8 merged commit 2196f22 into infiniflow:main Jun 4, 2026
1 check passed
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 4, 2026
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.
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. size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: REST document preview dropped DocumentService.accessible check

3 participants