Skip to content

Fix: enforce tenant authorization for tenant_rerank_id in retrieval flows - #14782

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
pekar9781:fix/authorize-tenant-rerank-id
May 13, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
pekar9781:fix/authorize-tenant-rerank-id

Conversation

@pekar9781

Copy link
Copy Markdown

Related issues

Closes #14781

What problem does this PR solve?

Some retrieval endpoints accepted caller-supplied tenant_rerank_id and resolved it through get_model_config_by_id(...). That helper loaded TenantLLM rows 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_id could 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_id resolution tenant-aware across the retrieval paths that accept it.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

Solution

  • Extend get_model_config_by_id(...) to accept an optional allowed_tenant_ids set and reject TenantLLM rows whose tenant_id is outside that set.
  • Pass the allowed tenant scope from retrieval endpoints that accept tenant_rerank_id:
    • api/apps/sdk/doc.py
    • api/apps/sdk/session.py
    • api/apps/services/dataset_api_service.py
  • Use the authenticated tenant plus dataset-owner tenant ids already derived by each retrieval flow as the authorization boundary for rerank model selection.
  • Add focused unit coverage to assert unauthorized tenant_rerank_id values are rejected and that the allowed tenant set is propagated correctly.

Testing

  • python -m py_compile on:
    • api/db/joint_services/tenant_model_service.py
    • api/apps/services/dataset_api_service.py
    • api/apps/sdk/doc.py
    • api/apps/sdk/session.py
  • Added unit tests in:
    • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
    • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py

Notes for reviewers

  • This change is intentionally narrow: it affects only the tenant_rerank_id path, not the normal rerank_id name-based resolution path.
  • Local lint/syntax checks passed.
  • Full pytest execution could not be completed in this environment because the local test runtime is missing strenum, so the route-test files fail during collection before exercising the updated cases.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 11, 2026
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
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: ae65cf49-ad9e-48ba-a449-f34efa722536

📥 Commits

Reviewing files that changed from the base of the PR and between d409c57 and 5f1fab6.

📒 Files selected for processing (3)
  • test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py

📝 Walkthrough

Walkthrough

Retrieval endpoints now restrict caller-provided tenant_rerank_id by passing an allowed-tenant set (requester plus dataset owners) into get_model_config_by_id, which enforces tenant membership and raises if unauthorized.

Changes

Tenant Authorization for Rerank Model Resolution

Layer / File(s) Summary
Service Authorization Contract
api/db/joint_services/tenant_model_service.py
get_model_config_by_id() signature extended to accept allowed_tenant_ids and requester_tenant_id; normalizes allowed ids and raises LookupError if the model's tenant_id is not allowed.
Dataset API: single-dataset search
api/apps/services/dataset_api_service.py
In search(), when tenant_rerank_id is provided, compute allowed_rerank_tenant_ids = {requester_tenant_id, kb.tenant_id} and pass it (plus requester_tenant_id) to get_model_config_by_id.
Dataset API: multi-dataset search
api/apps/services/dataset_api_service.py
In search_datasets(), when tenant_rerank_id is provided, compute allowed_rerank_tenant_ids = {requester_tenant_id, *[dataset.tenant_id for dataset in kbs]} and pass it to get_model_config_by_id.
SDK Retrieval Endpoint
api/apps/sdk/doc.py
In retrieval_test, compute allowed tenant IDs from requester and datasets and pass them into get_model_config_by_id when resolving tenant_rerank_id.
SDK Session Retrieval
api/apps/sdk/session.py
In retrieval_test_embedded internal flow, compute allowed tenant IDs from requester and datasets and pass them into get_model_config_by_id when resolving tenant_rerank_id.
Tests / Mocks
test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py, test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py, test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
Mocks for tenant_model_service.get_model_config_by_id updated to accept optional allowed_tenant_ids and requester_tenant_id parameters and enforce authorization in the stub.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

ci

Suggested reviewers

  • oeuvre
  • qinling0210

Poem

🐰
I hopped through code and counted tenants well,
No foreign rerank model slips the spell.
Requester and datasets form the gate,
Only allowed models make the fate.
Hooray — secure retrieval, snug as a shell!

🚥 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 and concisely describes the main change: enforcing tenant authorization for tenant_rerank_id in retrieval flows, which aligns perfectly with the PR's core objective.
Description check ✅ Passed The description includes all required template sections with substantial detail: the problem statement, type of change (Bug Fix), and the solution approach with affected files and testing strategy.
Linked Issues check ✅ Passed The PR fully addresses #14781 by extending get_model_config_by_id with allowed_tenant_ids authorization, propagating this constraint across all three affected retrieval endpoints, and adding unit tests to verify the enforcement.
Out of Scope Changes check ✅ Passed All changes directly support the authorization fix: core service modifications enforce the constraint, callers pass proper allowed_tenant_ids, and test mocks align with the new signatures.

✏️ 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

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

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 592dba1 and 551fddf.

📒 Files selected for processing (6)
  • api/apps/sdk/doc.py
  • api/apps/sdk/session.py
  • api/apps/services/dataset_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 551fddf and d409c57.

📒 Files selected for processing (7)
  • api/apps/sdk/doc.py
  • api/apps/sdk/session.py
  • api/apps/services/dataset_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/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

@pekar9781

Copy link
Copy Markdown
Author

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

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 12, 2026
@wangq8
wangq8 self-requested a review May 12, 2026 03:41
@wangq8 wangq8 added the ci Continue Integration label May 12, 2026
@wangq8
wangq8 marked this pull request as draft May 12, 2026 03:42
@wangq8
wangq8 marked this pull request as ready for review May 12, 2026 03:42
@Lynn-Inf
Lynn-Inf self-requested a review May 12, 2026 03:43

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

LGTM

@codecov

codecov Bot commented May 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (592dba1) to head (5f1fab6).
⚠️ Report is 15 commits behind head on main.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants