Skip to content

Go and Python: fix IDOR issue of search completions - #16864

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix542
Jul 13, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix542

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

In Go and python implementation, the dataset / KB id isn't validated if it is accessible by this user.

@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 13, 2026
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Search completion now validates dataset access, propagates dataset IDs through retrieval streaming, scopes search deletion by tenant and search ID, and updates related REST test validation and timing.

Changes

Search dataset security and flow

Layer / File(s) Summary
Completion authorization and plan contract
api/apps/restful_apis/search_api.py, internal/service/search.go, internal/dao/kb.go, test/testcases/restful_api/test_searches.py
Completion requests and prepared plans validate dataset accessibility, derive dataset IDs from search configuration or request input, expose DatasetIDs, and assert the JSON authorization error response.
Dataset ID streaming propagation
internal/handler/search.go, internal/service/ask_service.go
The completion handler passes DatasetIDs through StreamWithOptions, which forwards them to retrieval requests.
Tenant-scoped search deletion
internal/service/search.go, internal/dao/search.go
Search deletion passes the user identifier and soft-deletes only records matching both tenant ID and search ID.
REST test validation and timing support
test/testcases/restful_api/conftest.py, test/testcases/restful_api/test_openai_compatible.py
REST tests report execution durations, adjust one priority marker, and increase selected non-streaming request timeouts.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant SearchHandler
  participant SearchService
  participant KnowledgebaseDAO
  participant AskService
  Client->>SearchHandler: Submit completion request
  SearchHandler->>SearchService: Prepare completion
  SearchService->>KnowledgebaseDAO: Validate dataset accessibility
  SearchService-->>SearchHandler: Return DatasetIDs and options
  SearchHandler->>AskService: StreamWithOptions(DatasetIDs)
  AskService-->>Client: Stream retrieval completion deltas
Loading

Possibly related PRs

Suggested labels: 🧪 test

Poem

A bunny checked each dataset gate,
Then sent clean IDs to stream their fate.
Search rows hide by tenant’s sign,
Retrieval hops along the line.
Squeak—secure results now align!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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 matches the main change: fixing an IDOR issue in search completion handling for Go and Python.
Description check ✅ Passed The description includes the required Summary section and states the core problem being fixed.
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.

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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 13, 2026 10:23
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 13, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 13, 2026 10:23
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 13, 2026 10:23
Signed-off-by: Jin Hai <[email protected]>

@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: 2

🧹 Nitpick comments (1)
internal/service/search.go (1)

329-330: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Update stale cross-reference comment after tenant-scoping change.

The comment "same as Python SearchService.delete_by_id" is now inaccurate — the Go delete adds a tenant_id filter that the Python delete().where(cls.model.id == pid) does not have. As per coding guidelines, keep documentation comments aligned with the current runtime path rather than migration history.

♻️ Proposed fix
 // Step 2: Execute delete (same as Python SearchService.delete_by_id)
-// Python: cls.model.delete().where(cls.model.id == pid).execute()
+// Filters by tenant_id and id to scope deletion to the owning tenant.
 if err = s.searchDAO.DeleteByID(userID, searchID); err != nil {
🤖 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 `@internal/service/search.go` around lines 329 - 330, Update the comments in
the delete flow near the “Step 2: Execute delete” marker to remove the
inaccurate Python SearchService.delete_by_id comparison and its
migration-oriented reference. Keep the comments aligned with the current Go
delete behavior, including tenant_id scoping.

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.

Inline comments:
In `@api/apps/restful_apis/search_api.py`:
- Around line 223-227: Update the per-dataset authorization failure in the
kb_ids loop to return get_data_error_result with RetCode.AUTHENTICATION_ERROR,
matching the existing search-level check and Go implementation; leave successful
accessibility handling unchanged.

In `@internal/dao/search.go`:
- Around line 200-201: The SearchService.DeleteSearch call to
SearchDAO.DeleteByID currently supplies userID where tenantID is required. Pass
the authenticated tenant ID as the first argument, and update the deletion flow
to reject or report a zero RowsAffected result so missing searches are not
reported as successfully deleted.

---

Nitpick comments:
In `@internal/service/search.go`:
- Around line 329-330: Update the comments in the delete flow near the “Step 2:
Execute delete” marker to remove the inaccurate Python
SearchService.delete_by_id comparison and its migration-oriented reference. Keep
the comments aligned with the current Go delete behavior, including tenant_id
scoping.
🪄 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: b349249a-a481-4816-9f38-e97daf59975d

📥 Commits

Reviewing files that changed from the base of the PR and between 45862bf and cf3c7d6.

📒 Files selected for processing (6)
  • api/apps/restful_apis/search_api.py
  • internal/dao/kb.go
  • internal/dao/search.go
  • internal/handler/search.go
  • internal/service/ask_service.go
  • internal/service/search.go

Comment on lines +223 to +227
# check if the kb_ids is accessible for this user
for kb_id in kb_ids:
if not KnowledgebaseService.accessible(kb_id=kb_id, user_id=uid):
return get_data_error_result(message=f"You don't own the dataset {kb_id}")

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.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Use AUTHENTICATION_ERROR for per-dataset access denial, not DATA_ERROR.

The per-dataset authorization check returns get_data_error_result (defaults to RetCode.DATA_ERROR), but this is an authorization failure, not a data error. Both the search-level check at lines 198-203 and the Go implementation (CodeAuthenticationError) correctly use AUTHENTICATION_ERROR. This inconsistency could confuse API consumers.

🛡️ Proposed fix
     # check if the kb_ids is accessible for this user
     for kb_id in kb_ids:
         if not KnowledgebaseService.accessible(kb_id=kb_id, user_id=uid):
-            return get_data_error_result(message=f"You don't own the dataset {kb_id}")
+            return get_json_result(
+                data=False,
+                message=f"No authorization for dataset {kb_id}",
+                code=RetCode.AUTHENTICATION_ERROR,
+            )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# check if the kb_ids is accessible for this user
for kb_id in kb_ids:
if not KnowledgebaseService.accessible(kb_id=kb_id, user_id=uid):
return get_data_error_result(message=f"You don't own the dataset {kb_id}")
# check if the kb_ids is accessible for this user
for kb_id in kb_ids:
if not KnowledgebaseService.accessible(kb_id=kb_id, user_id=uid):
return get_json_result(
data=False,
message=f"No authorization for dataset {kb_id}",
code=RetCode.AUTHENTICATION_ERROR,
)
🤖 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/search_api.py` around lines 223 - 227, Update the
per-dataset authorization failure in the kb_ids loop to return
get_data_error_result with RetCode.AUTHENTICATION_ERROR, matching the existing
search-level check and Go implementation; leave successful accessibility
handling unchanged.

Comment thread internal/dao/search.go
Comment on lines +200 to +201
func (dao *SearchDAO) DeleteByID(tenantID, id string) error {
return DB.Model(&entity.Search{}).Where("tenant_id = ? AND id = ?", tenantID, id).Update("status", "0").Error

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not pass userID as tenantID.

DeleteByID now correctly filters on Search.tenant_id, but SearchService.DeleteSearch calls it as DeleteByID(userID, searchID). Since tenant_id and created_by are distinct fields, this can match no row and leave the search undeleted while the service reports success. Pass the authenticated tenant ID from the service, and consider checking RowsAffected to reject zero-match deletions.

🤖 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 `@internal/dao/search.go` around lines 200 - 201, The
SearchService.DeleteSearch call to SearchDAO.DeleteByID currently supplies
userID where tenantID is required. Pass the authenticated tenant ID as the first
argument, and update the deletion flow to reject or report a zero RowsAffected
result so missing searches are not reported as successfully deleted.

Signed-off-by: Jin Hai <[email protected]>
@codecov

codecov Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (45862bf) to head (3e7cb46).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16864   +/-   ##
=======================================
  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.
📢 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.

Signed-off-by: Jin Hai <[email protected]>

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/testcases/restful_api/test_searches.py (1)

141-144: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Stale comment and misleading test name should be updated.

The comment on lines 143–144 still references SSE contract and "error event in-stream," but the test now asserts a JSON error response (res.json() with code == 102). The test name test_search_completion_sse_shape_when_kb_ids_provided also no longer reflects the behavior — it tests dataset authorization, not SSE shape. As per coding guidelines, remove stale documentation and converge naming to the actual behavior.

♻️ Proposed fix
 `@pytest.mark.p2`
-def test_search_completion_sse_shape_when_kb_ids_provided(rest_client, search_resource):
+def test_search_completion_unauthorized_dataset(rest_client, search_resource):
     search_id = search_resource
-    # Even with kb_ids provided, runtime may return an error event in-stream, but
-    # contract remains SSE with JSON data lines and terminal boolean event.
+    # Providing an unowned dataset ID should return a JSON error, not an SSE stream.
     res = rest_client.post(
🤖 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/testcases/restful_api/test_searches.py` around lines 141 - 144, Rename
test_search_completion_sse_shape_when_kb_ids_provided to describe dataset
authorization behavior, and remove the stale SSE/error-event comment in that
test. Keep the existing assertions for the JSON error response and code 102
unchanged.

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.

Inline comments:
In `@test/testcases/restful_api/test_searches.py`:
- Around line 151-153: Update the assertion in the test search response
validation to match the backend message exactly by removing the leading stray
backtick from the expected substring. Keep the existing payload and status-code
assertions unchanged.

---

Outside diff comments:
In `@test/testcases/restful_api/test_searches.py`:
- Around line 141-144: Rename
test_search_completion_sse_shape_when_kb_ids_provided to describe dataset
authorization behavior, and remove the stale SSE/error-event comment in that
test. Keep the existing assertions for the JSON error response and code 102
unchanged.
🪄 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: 2f5d01dd-6683-47f9-8aa1-64a6e45af75b

📥 Commits

Reviewing files that changed from the base of the PR and between c06db41 and c2f1327.

📒 Files selected for processing (1)
  • test/testcases/restful_api/test_searches.py

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>

@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/testcases/restful_api/conftest.py (1)

252-258: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Route timing output through logging or pytest reporting.

This global hook prints a line for every test, which can pollute -s output and violate the repository rule: “**/*.py: Add logging for new flows.” Use the project logger or pytest’s reporting mechanism, and verify whether direct stdout is an intentional test-run contract.

🤖 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/testcases/restful_api/conftest.py` around lines 252 - 258, Update
pytest_runtest_protocol to stop writing test durations directly with print;
route the timing information through the project logger or pytest reporting
mechanism instead, preserving the existing duration measurement and per-test
reporting behavior. Verify that direct stdout is not an intentional test-run
contract before removing it.

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.

Nitpick comments:
In `@test/testcases/restful_api/conftest.py`:
- Around line 252-258: Update pytest_runtest_protocol to stop writing test
durations directly with print; route the timing information through the project
logger or pytest reporting mechanism instead, preserving the existing duration
measurement and per-test reporting behavior. Verify that direct stdout is not an
intentional test-run contract before removing it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c22c899a-ddd2-4a5a-b97b-f6712990204a

📥 Commits

Reviewing files that changed from the base of the PR and between d4fb3fb and 3e7cb46.

📒 Files selected for processing (2)
  • test/testcases/restful_api/conftest.py
  • test/testcases/restful_api/test_openai_compatible.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/restful_api/test_openai_compatible.py

@JinHai-CN
JinHai-CN merged commit 844e3ea into infiniflow:main Jul 13, 2026
5 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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant