Repository navigation
Go and Python: fix IDOR issue of search completions - #16864
Conversation
Signed-off-by: Jin Hai <[email protected]>
|
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:
📝 WalkthroughWalkthroughSearch 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. ChangesSearch dataset security and flow
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
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
internal/service/search.go (1)
329-330: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUpdate stale cross-reference comment after tenant-scoping change.
The comment "same as Python
SearchService.delete_by_id" is now inaccurate — the Go delete adds atenant_idfilter that the Pythondelete().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
📒 Files selected for processing (6)
api/apps/restful_apis/search_api.pyinternal/dao/kb.gointernal/dao/search.gointernal/handler/search.gointernal/service/ask_service.gointernal/service/search.go
| # 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}") | ||
|
|
There was a problem hiding this comment.
🔒 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.
| # 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.
| func (dao *SearchDAO) DeleteByID(tenantID, id string) error { | ||
| return DB.Model(&entity.Search{}).Where("tenant_id = ? AND id = ?", tenantID, id).Update("status", "0").Error |
There was a problem hiding this comment.
🗄️ 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 winStale 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()withcode == 102). The test nametest_search_completion_sse_shape_when_kb_ids_providedalso 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
📒 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]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/testcases/restful_api/conftest.py (1)
252-258: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRoute timing output through logging or pytest reporting.
This global hook prints a line for every test, which can pollute
-soutput 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
📒 Files selected for processing (2)
test/testcases/restful_api/conftest.pytest/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
Summary
In Go and python implementation, the dataset / KB id isn't validated if it is accessible by this user.