Skip to content

Fix: add document delete permission check - #14472

Merged
yingfeng merged 4 commits into
infiniflow:mainfrom
buua436:b029
Apr 30, 2026
Merged

yingfeng merged 4 commits into
infiniflow:mainfrom
buua436:b029

Conversation

@buua436

@buua436 buua436 commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

add document delete permission check

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@buua436 buua436 self-assigned this Apr 29, 2026
@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

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: bb3a6dfb-ed89-47b0-82bc-b063eb35de58

📥 Commits

Reviewing files that changed from the base of the PR and between 1648e54 and 2c4d240.

📒 Files selected for processing (1)
  • test/testcases/test_web_api/test_document_app/test_rm_documents.py
✅ Files skipped from review due to trivial changes (1)
  • test/testcases/test_web_api/test_document_app/test_rm_documents.py

📝 Walkthrough

Walkthrough

Added a pre-deletion validation in delete_documents to ensure all requested document IDs belong to the target dataset; returns an error listing invalid/non-belonging IDs. Tests updated to relax repeated-deletion message check and a new test asserts cross-dataset deletion is rejected.

Changes

Cohort / File(s) Summary
API Validation
api/apps/restful_apis/document_api.py
Added pre-flight check in delete_documents that builds the dataset's doc ID set, computes invalid_ids for requested IDs not in that set, and returns an error listing invalid IDs before duplicate checks or deletion.
HTTP API Tests
test/testcases/test_http_api/test_file_management_within_dataset/test_delete_documents.py
Updated repeated-deletion expected message substring; added test_cross_dataset_deletion_is_blocked which uploads a doc to another dataset and verifies deletion by a different dataset is rejected with error code 102 and no dataset totals change.
Web API Tests
test/testcases/test_web_api/test_document_app/test_rm_documents.py
Relaxed assertion in test_repeated_deletion to check that "Document not found" appears anywhere in the error message (less strict punctuation/formatting match).

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

size:M, 🐖api

Suggested reviewers

  • JinHai-CN
  • yingfeng
  • yuzhichang

Poem

🐰 I hop through files with careful cheer,
I check each doc's home — no stranger near.
If an ID wanders from a different nest,
I thump my foot and stop the quest.
Safe datasets sleep, each document blessed. 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is largely incomplete and vague. It only states 'add document delete permission check' without providing necessary context about what problem this solves or why the change was needed. Expand the 'What problem does this PR solve?' section with specific details about the permission issue being fixed and the security/functional impact of the change.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding a document delete permission check to validate that requested documents belong to the target dataset.
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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@buua436
buua436 marked this pull request as ready for review April 29, 2026 08:52
@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Apr 29, 2026
@buua436 buua436 removed their assignment Apr 29, 2026
@buua436 buua436 added the ci Continue Integration label Apr 29, 2026
@buua436
buua436 marked this pull request as draft April 29, 2026 08:52
@buua436
buua436 marked this pull request as ready for review April 29, 2026 08:52
@dosubot dosubot Bot added 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Apr 29, 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.

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

1030-1035: Add audit logging and avoid the full-dataset scan here.

This new authorization check rejects invalid deletes, but it does so silently and by loading every document in the dataset just to validate a small ID list. Please log the denied attempt before returning and prefer checking only the requested IDs, otherwise large datasets will pay an unnecessary read cost. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 1030 - 1035, The
authorization check currently loads the entire dataset via DocumentService.query
to build dataset_doc_ids and compare against doc_ids; instead query only the
requested IDs (use the service method that accepts an id filter such as
DocumentService.query(kb_id=dataset_id, id__in=doc_ids) or a get_by_ids helper)
to determine which requested IDs exist, compute invalid_ids = [doc_id for doc_id
in doc_ids if doc_id not in found_ids], and before returning
get_error_data_result log an audit message (use the existing logger, include
dataset_id, requesting user/context, and the invalid_ids) so denied attempts are
recorded; update the block referencing dataset_doc_ids, invalid_ids,
DocumentService.query, doc_ids, dataset_id, and get_error_data_result
accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1030-1035: The authorization check currently loads the entire
dataset via DocumentService.query to build dataset_doc_ids and compare against
doc_ids; instead query only the requested IDs (use the service method that
accepts an id filter such as DocumentService.query(kb_id=dataset_id,
id__in=doc_ids) or a get_by_ids helper) to determine which requested IDs exist,
compute invalid_ids = [doc_id for doc_id in doc_ids if doc_id not in found_ids],
and before returning get_error_data_result log an audit message (use the
existing logger, include dataset_id, requesting user/context, and the
invalid_ids) so denied attempts are recorded; update the block referencing
dataset_doc_ids, invalid_ids, DocumentService.query, doc_ids, dataset_id, and
get_error_data_result accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b47dec12-5bd4-4d95-9f1c-368b50633f4a

📥 Commits

Reviewing files that changed from the base of the PR and between 9690923 and 5fe5eb9.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_delete_documents.py

@codecov

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (b493a33) to head (2c4d240).
⚠️ Report is 33 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14472   +/-   ##
=======================================
  Coverage   95.30%   95.30%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          670      670           
  Misses         16       16           
  Partials       17       17           

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

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

1030-1035: Log rejected delete attempts before returning.

This new permission-check path exits silently when invalid_ids is found, which makes cross-dataset delete attempts harder to audit. Please add a warning log with tenant_id, dataset_id, and the rejected IDs before returning.

Suggested change
         invalid_ids = [doc_id for doc_id in doc_ids if doc_id not in dataset_doc_ids]
         if invalid_ids:
+            logging.warning(
+                "delete_documents rejected invalid ids tenant_id=%s dataset_id=%s invalid_ids=%s",
+                tenant_id,
+                dataset_id,
+                invalid_ids,
+            )
             return get_error_data_result(
                 message=f"These documents do not belong to dataset {dataset_id} or do not exist: {', '.join(invalid_ids)}"
             )

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 1030 - 1035, Before
returning the error for invalid_ids after calling DocumentService.query, add a
warning log that records tenant_id, dataset_id and the rejected invalid_ids to
aid auditing; place the log immediately before the get_error_data_result return
in the same branch where invalid_ids is truthy and use the module logger (e.g.,
logger.warning) to emit a concise message like "Rejected delete attempt" with
tenant_id, dataset_id and invalid_ids included.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1030-1035: Before returning the error for invalid_ids after
calling DocumentService.query, add a warning log that records tenant_id,
dataset_id and the rejected invalid_ids to aid auditing; place the log
immediately before the get_error_data_result return in the same branch where
invalid_ids is truthy and use the module logger (e.g., logger.warning) to emit a
concise message like "Rejected delete attempt" with tenant_id, dataset_id and
invalid_ids included.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6666f20d-7182-46b8-bb85-1183fede1b77

📥 Commits

Reviewing files that changed from the base of the PR and between 5fe5eb9 and 6e92588.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/testcases/test_sdk_api/test_file_management_within_dataset/test_delete_documents.py
✅ Files skipped from review due to trivial changes (1)
  • test/testcases/test_sdk_api/test_file_management_within_dataset/test_delete_documents.py

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

Actionable comments posted: 1

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

1028-1031: Avoid duplicate dataset-document queries in the same request path.

Line 1028 and Line 1030 both query all docs for the same dataset. Reuse one query result to reduce DB overhead in delete flows.

♻️ Proposed refactor
         if delete_all:
-            doc_ids = [doc.id for doc in DocumentService.query(kb_id=dataset_id)]
-
-        dataset_doc_ids = {doc.id for doc in DocumentService.query(kb_id=dataset_id)}
+            dataset_docs = DocumentService.query(kb_id=dataset_id)
+            doc_ids = [doc.id for doc in dataset_docs]
+        else:
+            dataset_docs = DocumentService.query(kb_id=dataset_id)
+
+        dataset_doc_ids = {doc.id for doc in dataset_docs}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 1028 - 1031, The code
makes two identical calls to DocumentService.query(kb_id=dataset_id) (used to
build doc_ids and dataset_doc_ids) causing duplicate DB queries; replace both
calls by a single call (e.g., dataset_docs =
list(DocumentService.query(kb_id=dataset_id))) and derive doc_ids and
dataset_doc_ids from that single in-memory result when computing invalid_ids,
ensuring all usages of DocumentService.query in this delete flow (references to
variables doc_ids, dataset_doc_ids, invalid_ids) use the reused dataset_docs
instead of re-querying.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1032-1035: Before returning the error when invalid_ids is
non-empty in the deletion flow, add a warning log call that records the
dataset_id, the invalid_ids list, and the requester identity (if available) to
audit permission-sensitive attempts; place the logger.warning invocation
immediately above the get_error_data_result return in the same block that checks
invalid_ids (referencing invalid_ids, dataset_id and get_error_data_result) and
format the message to clearly state that a blocked cross-dataset/non-existent
delete was attempted.

---

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1028-1031: The code makes two identical calls to
DocumentService.query(kb_id=dataset_id) (used to build doc_ids and
dataset_doc_ids) causing duplicate DB queries; replace both calls by a single
call (e.g., dataset_docs = list(DocumentService.query(kb_id=dataset_id))) and
derive doc_ids and dataset_doc_ids from that single in-memory result when
computing invalid_ids, ensuring all usages of DocumentService.query in this
delete flow (references to variables doc_ids, dataset_doc_ids, invalid_ids) use
the reused dataset_docs instead of re-querying.
🪄 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: 872d69c0-a9d4-4afe-b0db-99861269b52b

📥 Commits

Reviewing files that changed from the base of the PR and between 6e92588 and 1648e54.

📒 Files selected for processing (2)
  • api/apps/restful_apis/document_api.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_delete_documents.py

Comment on lines +1032 to +1035
if invalid_ids:
return get_error_data_result(
message=f"These documents do not belong to dataset {dataset_id} or Document not found: {', '.join(invalid_ids)}"
)

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.

⚠️ Potential issue | 🟡 Minor

Add warning logging for blocked cross-dataset/non-existent deletion attempts.

This is a new rejection flow but it returns without logging; adding a warning helps audit permission-sensitive delete attempts.

🧭 Proposed logging addition
         invalid_ids = [doc_id for doc_id in doc_ids if doc_id not in dataset_doc_ids]
         if invalid_ids:
+            logging.warning(
+                "delete_documents blocked: tenant=%s dataset=%s invalid_doc_ids=%s",
+                tenant_id,
+                dataset_id,
+                invalid_ids,
+            )
             return get_error_data_result(
                 message=f"These documents do not belong to dataset {dataset_id} or Document not found: {', '.join(invalid_ids)}"
             )

As per coding guidelines, "**/*.py: Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 1032 - 1035, Before
returning the error when invalid_ids is non-empty in the deletion flow, add a
warning log call that records the dataset_id, the invalid_ids list, and the
requester identity (if available) to audit permission-sensitive attempts; place
the logger.warning invocation immediately above the get_error_data_result return
in the same block that checks invalid_ids (referencing invalid_ids, dataset_id
and get_error_data_result) and format the message to clearly state that a
blocked cross-dataset/non-existent delete was attempted.

@yingfeng
yingfeng merged commit 06c6da5 into infiniflow:main Apr 30, 2026
1 of 2 checks 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:XS This PR changes 0-9 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants