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:
📝 WalkthroughWalkthroughThis PR adds tenant authorization enforcement to the document preview endpoint to prevent cross-tenant access, imports the current user context, updates the download handler for backward compatibility with ChangesDocument access guard
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 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. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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.
Actionable comments posted: 1
🤖 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/document_app.py`:
- Around line 37-38: Add a structured audit log before the early return in the
authorization-denied branch: when DocumentService.accessible(doc_id,
current_user.id) is false, emit a logger.warning or logger.info with a
structured payload including user_id=current_user.id, doc_id=doc_id and
outcome="denied" (and any request id if available) and then return
get_data_error_result(...); update the branch where DocumentService.accessible
is checked to call the module/app logger (e.g., logger) with those fields
immediately prior to returning so the denied access is recorded for
traceability.
🪄 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: b4ad041a-f694-43b3-9716-c7cad0833e0f
📒 Files selected for processing (1)
api/apps/document_app.py
| if not DocumentService.accessible(doc_id, current_user.id): | ||
| return get_data_error_result(message="Document not found!") |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add an audit log on the new authorization-denied branch.
The new early-return flow (Line 37–Line 38) should emit a structured warning/info log (e.g., user_id, doc_id, outcome=denied) for traceability and incident response.
Proposed change
+import logging
+
+logger = logging.getLogger(__name__)
...
if not DocumentService.accessible(doc_id, current_user.id):
+ logger.warning(
+ "document_get_denied",
+ extra={"user_id": current_user.id, "doc_id": doc_id},
+ )
return get_data_error_result(message="Document 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/document_app.py` around lines 37 - 38, Add a structured audit log
before the early return in the authorization-denied branch: when
DocumentService.accessible(doc_id, current_user.id) is false, emit a
logger.warning or logger.info with a structured payload including
user_id=current_user.id, doc_id=doc_id and outcome="denied" (and any request id
if available) and then return get_data_error_result(...); update the branch
where DocumentService.accessible is checked to call the module/app logger (e.g.,
logger) with those fields immediately prior to returning so the denied access is
recorded for traceability.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14625 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@test/testcases/test_web_api/test_document_app/test_document_metadata.py`:
- Around line 347-355: The test currently calls module.get("doc1") while only
stubbing DocumentService.accessible, which can yield a false positive if
get_by_id returns None; before invoking module.get in the denial-path branch,
stub DocumentService.get_by_id to return a valid document object (matching
expected shape) and ensure DocumentService.accessible is monkeypatched to return
False, then call module.get("doc1") and assert the response is
RetCode.DATA_ERROR with "Document not found!" and that
DocumentService.accessible was invoked (e.g. via a spy or side-effect) to prove
the denial path exercised the auth check rather than a missing document.
🪄 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: ecc4efce-bf5b-4b19-a180-dd170a519c0e
📒 Files selected for processing (1)
test/testcases/test_web_api/test_document_app/test_document_metadata.py
|
Hi, @wangq8 , |
|
@web-dev0521 this API have been moved to new place, please raise PR to new location. |
The /documents/<doc_id>/preview route in api/apps/restful_apis/document_api.py called DocumentService.get_by_id without verifying that the document's knowledge base belonged to the requesting user's tenant. Any authenticated user could download files from other tenants by knowing a doc id. Add a DocumentService.accessible(doc_id, current_user.id) check before serving the file. The denial response reuses the existing 'Document not found!' error so the endpoint cannot be used to enumerate doc ids across tenants. Tests: pin the new behaviour in the existing unit test by stubbing get_by_id to a valid document inside the denial sub-scenario and asserting that accessible() was actually invoked with (doc_id, current_user.id) - this prevents future regressions from passing for the wrong reason.
|
Hi, @wangq8 , |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)
1892-1909: ⚡ Quick win
/documents/<doc_id>/downloadlacks a document ownership check.The preview endpoint (
/documents/<doc_id>/preview) now enforcesDocumentService.accessiblebefore touching storage, but this sibling endpoint goes directly tosettings.STORAGE_IMPL.get(tenant_id, doc_id)without any DB lookup or authorization gate. Becausetenant_idis the caller's own tenant bucket, cross-tenant IDOR is prevented, but any authenticated member of a shared tenant can fetch arbitrary storage objects within that bucket by guessing or enumerating keys (e.g., doc_ids of other members' private documents).The PR objectives explicitly request auditing adjacent
@login_requiredroutes with this pattern. Consider adding the same guard for consistency:🛡️ Suggested authorization gate
async def download_attachment(tenant_id=None, doc_id=None, attachment_id=None): try: doc_id = doc_id or attachment_id + if not DocumentService.accessible(doc_id, current_user.id): + logging.warning("download_attachment: access denied for doc_id=%s user_id=%s", doc_id, current_user.id) + return get_data_error_result(message="Document not found!") ext = request.args.get("ext", "markdown")🤖 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 1892 - 1909, download_attachment calls settings.STORAGE_IMPL.get directly and must enforce the same authorization as the preview route; before calling thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id) invoke DocumentService.accessible(tenant_id=tenant_id, doc_id=doc_id, user=current_user) (or the equivalent accessible check used by the preview endpoint) and return a 403/appropriate error if it denies access, then proceed to fetch storage and build the response (keep existing ext handling and apply_safe_file_response_headers). Ensure you reference the download_attachment handler, DocumentService.accessible, settings.STORAGE_IMPL.get, thread_pool_exec and apply_safe_file_response_headers so the guard mirrors the preview endpoint.
🤖 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/document_api.py`:
- Around line 1869-1870: The authorization denial path using
DocumentService.accessible(...) lacks any logging; add a log call before
returning get_data_error_result to record the denial, including doc_id and
current_user.id (and any available tenant or request id) and use the module
logger (e.g., logger.warning or logger.info per project convention) so blocked
cross-tenant access attempts are traceable; update the block around
DocumentService.accessible to log the denial with a clear message and contextual
fields, then return get_data_error_result as before.
---
Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1892-1909: download_attachment calls settings.STORAGE_IMPL.get
directly and must enforce the same authorization as the preview route; before
calling thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id) invoke
DocumentService.accessible(tenant_id=tenant_id, doc_id=doc_id,
user=current_user) (or the equivalent accessible check used by the preview
endpoint) and return a 403/appropriate error if it denies access, then proceed
to fetch storage and build the response (keep existing ext handling and
apply_safe_file_response_headers). Ensure you reference the download_attachment
handler, DocumentService.accessible, settings.STORAGE_IMPL.get, thread_pool_exec
and apply_safe_file_response_headers so the guard mirrors the preview endpoint.
🪄 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: e3dfe8c5-20c6-49ef-a311-fd04691e4908
📒 Files selected for processing (2)
api/apps/restful_apis/document_api.pytest/testcases/test_web_api/test_document_app/test_document_metadata.py
🚧 Files skipped from review as they are similar to previous changes (1)
- test/testcases/test_web_api/test_document_app/test_document_metadata.py
| if not DocumentService.accessible(doc_id, current_user.id): | ||
| return get_data_error_result(message="Document not found!") |
There was a problem hiding this comment.
Add a log entry on the authorization denial path.
The new auth gate is silent when it blocks access. Per the coding guidelines, new flows must be logged, and a missing log entry here will make it impossible to distinguish legitimate 404s from blocked cross-tenant access attempts during incident investigation.
if not DocumentService.accessible(doc_id, current_user.id):
+ logging.warning("get_document_preview: access denied for doc_id=%s user_id=%s", doc_id, current_user.id)
return get_data_error_result(message="Document not found!")As per coding guidelines: "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/document_api.py` around lines 1869 - 1870, The
authorization denial path using DocumentService.accessible(...) lacks any
logging; add a log call before returning get_data_error_result to record the
denial, including doc_id and current_user.id (and any available tenant or
request id) and use the module logger (e.g., logger.warning or logger.info per
project convention) so blocked cross-tenant access attempts are traceable;
update the block around DocumentService.accessible to log the denial with a
clear message and contextual fields, then return get_data_error_result as
before.
|
@web-dev0521 should you add to both |
Per review feedback (#14625): the /preview endpoint and the /download endpoint share the same trust boundary - both serve a document's bytes to a logged-in user inside a tenant - so they must share the same authorization rule. The post-#14633 refactor switched the download route's storage key from current_user.id to tenant_id, which means any user in the tenant can now fetch any doc_id under that tenant if the storage layer happens to find it. Add the same DocumentService.accessible(doc_id, current_user.id) check used by the preview route so the endpoint enforces per-document authorization explicitly and stays consistent with /preview. Tests: cover the denial path on download_attachment with the same 'stub get_by_id valid + accessible False + assert accessible_calls' pattern used for the preview test, so a regression cannot pass for the wrong reason.
|
Good catch, thanks @wangq8 🙏 You're right - /preview and /download are basically the same surface from a security standpoint, so they should share the same check. I just pushed 8f40ce9 which adds the same DocumentService.accessible(doc_id, current_user.id) guard to the download handler, and I also extended the unit test to cover the denial path the same way I did for preview. Let me know if you'd like me to tweak anything - happy to iterate. |
|
@web-dev0521 looks good to me. |
|
HI, @wangq8 , |
…niflow#14618) (infiniflow#14625) ### What problem does this PR solve? Closes infiniflow#14618. The `GET /v1/document/get/<doc_id>` endpoint in `api/apps/document_app.py` was protected only by `@login_required` and called `DocumentService.get_by_id(doc_id)` without verifying that the document's knowledge base belonged to the requesting user's tenant. Any authenticated user who knew (or guessed) a document ID could download files belonging to any other tenant — a cross-tenant IDOR. This PR adds a `DocumentService.accessible(doc_id, current_user.id)` check before serving the file. The helper already exists and joins `Document` → `Knowledgebase` → `UserTenant` to verify the requesting user belongs to the tenant that owns the document's KB. The same pattern is already used by `api/apps/restful_apis/document_api.py` and mirrors the tenant scoping in the SDK route at `api/apps/sdk/doc.py`. The check returns the existing `"Document not found!"` error for both non-existent and inaccessible documents, so attackers cannot use the response to enumerate valid doc IDs across tenants. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] Other (please describe): Security fix (cross-tenant IDOR / authorization bypass)
… (#15270) ## Summary Closes #15268. The `UpdateMetadataSetting` handler at `internal/handler/kb.go:126` retrieved the authenticated user via `GetUser(c)` but discarded the user object (`_, errorCode, errorMessage := GetUser(c)`), then forwarded the caller-supplied `kb_id` straight to the service layer with no ownership check. Any authenticated user could mutate the `parser_config` / metadata of any knowledge base in the system by guessing or harvesting a `kb_id` — a classic IDOR (CWE-284, OWASP A01). This is the only handler in `internal/handler/kb.go` missing the check; every sibling (`ListTags`, `ListTagsFromKbs`, `RenameTag`, `KnowledgeGraph`, `DeleteKnowledgeGraph`, `GetMeta`, `GetBasicInfo`) already calls `h.kbService.Accessible(kbID, user.ID)`. The same defensive check on the document preview endpoint was added in PR #14625 — this PR closes the matching gap on the KB metadata endpoint. --------- Co-authored-by: Jin Hai <[email protected]>
…niflow#14618) (infiniflow#14625) ### What problem does this PR solve? Closes infiniflow#14618. The `GET /v1/document/get/<doc_id>` endpoint in `api/apps/document_app.py` was protected only by `@login_required` and called `DocumentService.get_by_id(doc_id)` without verifying that the document's knowledge base belonged to the requesting user's tenant. Any authenticated user who knew (or guessed) a document ID could download files belonging to any other tenant — a cross-tenant IDOR. This PR adds a `DocumentService.accessible(doc_id, current_user.id)` check before serving the file. The helper already exists and joins `Document` → `Knowledgebase` → `UserTenant` to verify the requesting user belongs to the tenant that owns the document's KB. The same pattern is already used by `api/apps/restful_apis/document_api.py` and mirrors the tenant scoping in the SDK route at `api/apps/sdk/doc.py`. The check returns the existing `"Document not found!"` error for both non-existent and inaccessible documents, so attackers cannot use the response to enumerate valid doc IDs across tenants. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] Other (please describe): Security fix (cross-tenant IDOR / authorization bypass)
What problem does this PR solve?
Closes #14618.
The
GET /v1/document/get/<doc_id>endpoint inapi/apps/document_app.pywas protected only by@login_requiredand calledDocumentService.get_by_id(doc_id)without verifying that the document's knowledge base belonged to the requesting user's tenant. Any authenticated user who knew (or guessed) a document ID could download files belonging to any other tenant — a cross-tenant IDOR.This PR adds a
DocumentService.accessible(doc_id, current_user.id)check before serving the file. The helper already exists and joinsDocument→Knowledgebase→UserTenantto verify the requesting user belongs to the tenant that owns the document's KB. The same pattern is already used byapi/apps/restful_apis/document_api.pyand mirrors the tenant scoping in the SDK route atapi/apps/sdk/doc.py.The check returns the existing
"Document not found!"error for both non-existent and inaccessible documents, so attackers cannot use the response to enumerate valid doc IDs across tenants.Type of change