Repository navigation
Fix: enforce tenant authorization for tenant_rerank_id in retrieval flows - #14782
Conversation
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughRetrieval endpoints now restrict caller-provided ChangesTenant Authorization for Rerank Model Resolution
Sequence DiagramsequenceDiagram
participant Caller as Caller
participant Endpoint as Retrieval Endpoint
participant Service as Dataset/Session Service
participant ModelLookup as get_model_config_by_id
participant DB as TenantLLMService
Caller->>Endpoint: POST request + tenant_rerank_id
Endpoint->>Service: resolve datasets, extract tenant_ids
Service->>Service: build allowed_tenant_ids = {requester_tenant_id, *dataset_tenant_ids}
Service->>ModelLookup: tenant_rerank_id, allowed_tenant_ids, requester_tenant_id
ModelLookup->>DB: fetch TenantLLM by id
DB-->>ModelLookup: model_config
alt model.tenant_id in allowed_tenant_ids
ModelLookup-->>Service: return model_config
Service-->>Endpoint: proceed with rerank
else model.tenant_id not authorized
ModelLookup-->>Service: raise LookupError "not authorized"
Service-->>Endpoint: return error
end
Endpoint-->>Caller: response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
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. 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: 2
🤖 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/services/dataset_api_service.py`:
- Around line 1374-1377: The current allowed_rerank_tenant_ids is built from
tenant_id and tenant_ids which can miss owners of the selected datasets;
instead, build the set by collecting the owner/tenant IDs from the selected
dataset records (e.g., iterate selected_datasets or dataset_records and add each
record.owner_tenant_id), include the current tenant_id as well, and pass that
set to get_model_config_by_id(req["tenant_rerank_id"],
allowed_rerank_tenant_ids). Update the code that constructs
allowed_rerank_tenant_ids (replace the {tenant_id, *tenant_ids} line) so it
aggregates dataset owner tenant IDs plus tenant_id before calling
get_model_config_by_id.
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 34-40: When denying access in the authorization branch (the block
that checks allowed_tenant_ids and raises LookupError), add an audit log entry
before raising the LookupError: use the module logger (e.g., logger =
logging.getLogger(__name__)) and log a structured message including
tenant_model_id, model_config.tenant_id, the computed allowed_tenant_ids set,
and any available caller/requester identifier; log at a level appropriate for
security audits (warning/notice/audit) so denied cross-tenant access attempts
are recorded prior to raising the LookupError.
🪄 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: e2f7a210-d563-48cd-93f4-8d4bdfe819f0
📒 Files selected for processing (6)
api/apps/sdk/doc.pyapi/apps/sdk/session.pyapi/apps/services/dataset_api_service.pyapi/db/joint_services/tenant_model_service.pytest/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py`:
- Around line 226-231: The mock _get_model_config_by_id currently ignores
allowed_tenant_ids and requester_tenant_id causing authorization to be bypassed;
update _get_model_config_by_id to validate authorization (if allowed_tenant_ids
is provided, ensure the returned config's tenant id like "tenant-1" is in
allowed_tenant_ids or matches requester_tenant_id) and raise an appropriate
error or return None when unauthorized so tests exercise auth logic;
alternatively, if you intentionally skip auth, add a clear comment on
_get_model_config_by_id explaining why and add separate tests that assert real
authorization failure cases instead.
In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py`:
- Around line 420-425: The mock _get_model_config_by_id currently ignores
allowed_tenant_ids and requester_tenant_id and always returns
_MockModelConfig2("tenant-1", "model-1").to_dict(), bypassing authorization
checks; update the mock to perform a simple authorization check: if
allowed_tenant_ids is provided ensure the mock's tenant id ("tenant-1" or the
value from _MockModelConfig2) is contained in allowed_tenant_ids and if not
raise or return an authorization-failure-like response (e.g., None or a dict
indicating forbidden) so tests can detect denied access, or alternatively add a
brief comment in the mock explaining why auth is intentionally skipped; locate
and modify the _get_model_config_by_id function and/or _MockModelConfig2
behavior to implement this validation.
🪄 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: df4eeed4-aeda-4acf-8c57-3de979fb44aa
📒 Files selected for processing (7)
api/apps/sdk/doc.pyapi/apps/sdk/session.pyapi/apps/services/dataset_api_service.pyapi/db/joint_services/tenant_model_service.pytest/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.pytest/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (5)
- api/db/joint_services/tenant_model_service.py
- api/apps/services/dataset_api_service.py
- api/apps/sdk/doc.py
- test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
- api/apps/sdk/session.py
|
@Lynn-Inf Could you please take a look when you have time? This PR is related to my earlier PR #14745 in that both address authorization gaps caused by trusting caller-controlled IDs, but they fix different code paths.
So the theme is similar, but this PR is a separate fix rather than a follow-up dependency. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14782 +/- ##
=======================================
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:
|
Related issues
Closes #14781
What problem does this PR solve?
Some retrieval endpoints accepted caller-supplied
tenant_rerank_idand resolved it throughget_model_config_by_id(...). That helper loadedTenantLLMrows by global database id and returned decoded model configuration without checking whether the model belonged to the authenticated tenant or the dataset owner tenant.This meant dataset access was validated, but rerank-model selection was not. A caller who knew or could guess another tenant's
tenant_rerank_idcould attempt retrieval with a foreign rerank model config, creating a cross-tenant authorization gap for model usage.This PR closes that gap by making
tenant_rerank_idresolution tenant-aware across the retrieval paths that accept it.Type of change
Solution
get_model_config_by_id(...)to accept an optionalallowed_tenant_idsset and rejectTenantLLMrows whosetenant_idis outside that set.tenant_rerank_id:api/apps/sdk/doc.pyapi/apps/sdk/session.pyapi/apps/services/dataset_api_service.pytenant_rerank_idvalues are rejected and that the allowed tenant set is propagated correctly.Testing
python -m py_compileon:api/db/joint_services/tenant_model_service.pyapi/apps/services/dataset_api_service.pyapi/apps/sdk/doc.pyapi/apps/sdk/session.pytest/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.pyNotes for reviewers
tenant_rerank_idpath, not the normalrerank_idname-based resolution path.strenum, so the route-test files fail during collection before exercising the updated cases.