Repository navigation
Conversation
|
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:
📝 WalkthroughWalkthroughDerives tenant_id from APIToken for chatbot endpoints, enforces tenant-scoped DialogService queries (StatusEnum.VALID), validates iframe/session ownership, propagates tenant_id into async_iframe_completion, and updates unit tests for streaming and authorization branches. ChangesTenant-Scoped Access Control for Chatbot Endpoints
Sequence DiagramsequenceDiagram
participant Client
participant SessionAPI as Session API
participant DialogSvc as DialogService
participant ConvSvc as ConversationService
participant DB as Database
rect rgba(100, 150, 200, 0.5)
Note over Client,DB: Chatbot completions with tenant enforcement
Client->>SessionAPI: POST /chatbots/<dialog_id>/completions\nAuthorization: Bearer <token>
SessionAPI->>SessionAPI: Validate token and extract tenant_id
SessionAPI->>DialogSvc: query(id=dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID)
DialogSvc->>DB: fetch dialog by id + tenant
DB-->>DialogSvc: dialog record or none
DialogSvc-->>SessionAPI: dialog or empty
alt dialog not found (access denied)
SessionAPI-->>Client: Authentication error: no access to this chatbot!
else dialog found
SessionAPI->>ConvSvc: async_iframe_completion(dialog_id, question, tenant_id=tenant_id, ...)
ConvSvc->>DialogSvc: query(id=dialog_id, tenant_id=tenant_id)
DialogSvc-->>ConvSvc: dialog record
ConvSvc->>ConvSvc: assert session.dialog_id == dialog_id
ConvSvc->>DB: run completion and stream/save messages
DB-->>ConvSvc: stream chunks / final result
ConvSvc-->>SessionAPI: streamed or final response
SessionAPI-->>Client: streaming or non-stream response
end
end
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested Reviewers
🚥 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. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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: 4
🧹 Nitpick comments (1)
test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py (1)
1339-1343: ⚡ Quick winMissing positive (happy-path) test for
chatbots_inputsThe test coverage for
chatbots_inputsonly exercises the three rejection branches (bad header, invalid key, no dialog). There is no test verifying the success path — i.e., that whenDialogService.queryreturns a valid dialog, the endpoint returns the correct shape (title,avatar,prologue,has_tavily_key). Without this, a regression in the response payload would go undetected.✅ Suggested happy-path test to append inside
test_chatbot_routes_auth_stream_nonstream_unit# Happy path: valid token + owned dialog → correct payload stub_dialog = SimpleNamespace( name="My Bot", icon="avatar.png", prompt_config={"prologue": "Hello!", "tavily_api_key": "key123"}, ) monkeypatch.setattr(module, "request", SimpleNamespace(headers={"Authorization": "Bearer ok"})) monkeypatch.setattr(module.APIToken, "query", lambda **_kwargs: [SimpleNamespace(tenant_id="tenant-1")]) monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [stub_dialog]) res = _run(inspect.unwrap(module.chatbots_inputs)("dialog-1")) assert res["code"] == 0 assert res["data"]["title"] == "My Bot" assert res["data"]["avatar"] == "avatar.png" assert res["data"]["prologue"] == "Hello!" assert res["data"]["has_tavily_key"] is True🤖 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/test_http_api/test_session_management/test_session_sdk_routes_unit.py` around lines 1339 - 1343, Add a happy-path unit test for chatbots_inputs: stub a dialog object with name/icon/prompt_config (including prologue and tavily_api_key), monkeypatch module.request to return a valid Authorization header, monkeypatch module.APIToken.query to return a tenant_id, monkeypatch module.DialogService.query to return the stub dialog, call _run(inspect.unwrap(module.chatbots_inputs)("dialog-1")), and assert res["code"] == 0 and that res["data"]["title"], res["data"]["avatar"], res["data"]["prologue"] and res["data"]["has_tavily_key"] match the expected values.
🤖 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/sdk/session.py`:
- Around line 155-158: The DialogService.query calls in the chatbot endpoint
authorization checks (inside chatbot_completions and chatbots_inputs in
session.py where tenant_id is derived from objs[0]) are missing the status
filter and must include status=StatusEnum.VALID.value to prevent disabled
dialogs from passing auth and later raising AssertionError; update both
DialogService.query invocations to add that parameter and ensure StatusEnum is
imported in the module if not already present.
- Around line 157-158: The new authorization-rejection branches that return
get_error_data_result(message="Authentication error: no access to this
chatbot!") currently emit no log; update both places where this check uses the
dialogs variable to log a structured access-denied entry before returning
(include context such as user id/session id/chatbot id and reason "no access to
this chatbot"), using the module logger (or the existing logger used in this
file) so callers can audit denials; ensure you call logger.warning or
logger.info with a clear message and include the same metadata used elsewhere in
this module prior to returning the error result.
In `@api/db/services/conversation_service.py`:
- Around line 204-211: In async_iframe_completion, the tenant-scoped path uses
DialogService.query then asserts dia silently; change this to explicitly check
the query result (DialogService.query) and emit a structured warning-level log
(include tenant_id, dialog_id, StatusEnum.VALID) when no dialog is found before
raising or returning an error; update the branch that currently does "assert
dia, 'Dialog not found'" to log via the existing logger (e.g., processLogger or
module logger) with context then raise the same AssertionError or return an
appropriate error to preserve behavior.
- Around line 205-211: The current logic falls back to DialogService.get_by_id
when tenant_id is falsy, restoring an IDOR path; update the handler (where
async_iframe_completion or the containing function validates dialog access) to
reject any falsy tenant_id instead of using the else branch — remove or guard
the DialogService.get_by_id fallback and raise an explicit error (e.g.,
ValueError or custom exception) when tenant_id is None or empty; keep using
DialogService.query(id=dialog_id, tenant_id=tenant_id,
status=StatusEnum.VALID.value) and ensure you reference and return the queried
dia (dia = dia[0]) only when tenant_id is present.
---
Nitpick comments:
In
`@test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py`:
- Around line 1339-1343: Add a happy-path unit test for chatbots_inputs: stub a
dialog object with name/icon/prompt_config (including prologue and
tavily_api_key), monkeypatch module.request to return a valid Authorization
header, monkeypatch module.APIToken.query to return a tenant_id, monkeypatch
module.DialogService.query to return the stub dialog, call
_run(inspect.unwrap(module.chatbots_inputs)("dialog-1")), and assert res["code"]
== 0 and that res["data"]["title"], res["data"]["avatar"],
res["data"]["prologue"] and res["data"]["has_tavily_key"] match the expected
values.
🪄 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: 4d020e8a-a04b-4447-8ac4-5a7f908ea68f
📒 Files selected for processing (3)
api/apps/sdk/session.pyapi/db/services/conversation_service.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
api/apps/sdk/session.py (1)
156-158:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd audit logging to the new access-denied branches.
These tenant-scope rejection paths still return silently, which makes denied cross-tenant probes hard to investigate. Please emit a structured warning before each return and include safe identifiers such as
tenant_idanddialog_idrather than the raw token.Suggested minimal change
import logging +logger = logging.getLogger(__name__) ... dialogs = DialogService.query(id=dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value) if not dialogs: + logger.warning( + "Denied chatbot access", + extra={"tenant_id": tenant_id, "dialog_id": dialog_id, "reason": "no_access_to_chatbot"}, + ) return get_error_data_result(message="Authentication error: no access to this chatbot!") ... dialogs = DialogService.query(id=dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value) if not dialogs: + logger.warning( + "Denied chatbot access", + extra={"tenant_id": tenant_id, "dialog_id": dialog_id, "reason": "no_access_to_chatbot"}, + ) return get_error_data_result(message="Authentication error: no access to this chatbot!")As per coding guidelines:
**/*.py: Add logging for new flows.Also applies to: 186-188
🤖 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/sdk/session.py` around lines 156 - 158, Add structured audit logging immediately before the early returns in the tenant-scope reject branches so denied cross-tenant probes are recorded: call the logger (e.g. processLogger or module logger) with a warning that includes safe identifiers tenant_id and dialog_id and a short reason string, just before the return get_error_data_result(...) in the branch where DialogService.query(id=dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value) returns falsy, and do the same for the other similar branch around the later return (the second access-denied path mentioned). Ensure the log message is structured (key/value) and does not include raw tokens.
🤖 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/sdk/session.py`:
- Around line 164-171: The handler must validate authorization before committing
a Response: call the same tenant/session validation used in conversation_service
(or invoke a synchronous pre-check wrapper around iframe_completion) and catch
authorization-related exceptions (the ones raised by conversation_service.py
lines ~204-211) prior to creating the Response object or starting the async
generator; for the streaming branch (where you currently do resp =
Response(iframe_completion(...), ...)) perform the pre-check and return the
appropriate access-denied response (e.g., 403) if it fails, and for the
non-streaming async for branch, call the validation before iterating or catch
and translate those specific exceptions into the same access-denied response
instead of letting them bubble as 500. Ensure you reference iframe_completion
and the conversation_service validation function when adding the
pre-check/exception handling.
---
Duplicate comments:
In `@api/apps/sdk/session.py`:
- Around line 156-158: Add structured audit logging immediately before the early
returns in the tenant-scope reject branches so denied cross-tenant probes are
recorded: call the logger (e.g. processLogger or module logger) with a warning
that includes safe identifiers tenant_id and dialog_id and a short reason
string, just before the return get_error_data_result(...) in the branch where
DialogService.query(id=dialog_id, tenant_id=tenant_id,
status=StatusEnum.VALID.value) returns falsy, and do the same for the other
similar branch around the later return (the second access-denied path
mentioned). Ensure the log message is structured (key/value) and does not
include raw tokens.
🪄 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: 9e4c3984-e7b5-4fb5-9efe-0e1bc18fb503
📒 Files selected for processing (1)
api/apps/sdk/session.py
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/db/services/conversation_service.py`:
- Around line 246-248: Replace the runtime-only asserts around the session
lookup with unconditional exceptions: after calling
API4ConversationService.get_by_id and binding e, conv, remove "assert e" and
"assert conv.dialog_id == dialog_id" and instead raise explicit errors (e.g.,
raise LookupError("Session not found") when e is falsy and raise
PermissionError("Session does not belong to this dialog") when conv.dialog_id !=
dialog_id) so the check is not stripped in optimized runs; also update the
caller in the SDK session code to catch these exceptions
(LookupError/PermissionError) and convert them to the appropriate response/error
handling path.
🪄 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: 7eb0642f-b3da-4956-a36b-27e166a32026
📒 Files selected for processing (2)
api/apps/sdk/session.pyapi/db/services/conversation_service.py
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
api/apps/sdk/session.py (1)
150-157: ⚡ Quick winDuplicated token-extraction boilerplate across chatbot/agent/search endpoints.
The same 7-line pattern (split
Authorization, validate length,APIToken.query(beta=token), derivetenant_id) is repeated inchatbot_completions,chatbots_inputs,agent_bot_completions,begin_inputs,ask_about_embedded,retrieval_test_embedded,related_questions_embedded,detail_share_embedded, andmindmap. A small_resolve_beta_token() -> (tenant_id, error_response)(or a decorator analogous to@token_required) would centralize the parsing rules and reduce the chance of one site drifting from the others (e.g., subtle differences already exist — note the stray trailing"in the'API key is invalid!"'message at line 156/229 etc.).Out of scope of this security fix, but worth a follow-up since the diff already touches two of these sites.
Also applies to: 223-230
🤖 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/sdk/session.py` around lines 150 - 157, Extract the duplicated Authorization parsing into a single helper (e.g., _resolve_beta_token) that takes the request, validates request.headers.get("Authorization") by splitting and checking length, returns (tenant_id, None) on success using APIToken.query(beta=token) and (None, get_error_data_result(...)) on failure; replace the repeated 7-line blocks in chatbot_completions, chatbots_inputs, agent_bot_completions, begin_inputs, ask_about_embedded, retrieval_test_embedded, related_questions_embedded, detail_share_embedded, and mindmap with calls to this helper (or a decorator) and ensure the error messages use get_error_data_result exactly (fix the stray trailing double quote in the 'API key is invalid!"' string) so all endpoints share consistent token-parsing behavior.
🤖 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/sdk/session.py`:
- Line 197: The call to iframe_completion using positional dialog_id and named
tenant_id while also unpacking user-controlled req can raise TypeError when req
contains dialog_id or tenant_id; fix by removing (pop) those reserved keys from
req or constructing an explicit kwargs dict before calling iframe_completion and
Response in both streaming path (iframe_completion(dialog_id,
tenant_id=tenant_id, **req) at line ~197) and the non-streaming call at line
~206 so user-supplied dialog_id/tenant_id cannot collide with the
positional/named args.
- Around line 204-219: The code path can fall through to "return None" when
iframe_completion yields nothing, causing Quart to return a 500; update the end
of the try/except block in the handler that calls _validate_iframe_access() and
async for answer in iframe_completion(...) to return a structured error instead
of None — e.g. if the async iteration never yields, call and return
get_error_data_result(...) with an appropriate message/status (similar to the
Authentication error branch) so clients always receive a JSON error; ensure
existing symbols _validate_iframe_access, iframe_completion, get_result,
get_error_data_result, and logger are used consistently.
- Around line 173-181: The conv.user_id != tenant_id comparison in
_validate_iframe_access is incorrect because conv.user_id is the end-user id,
not a tenant id; remove that check (or replace it with a check against an actual
tenant field such as conv.tenant_id if your API4Conversation model stores tenant
ownership) and rely on the existing DialogService.query(id=dialog_id,
tenant_id=tenant_id, ...) and conv.dialog_id != dialog_id validations for
tenant/dialog ownership; if you do add a tenant-level assertion, compare
tenant_id to a real tenant property (e.g., conv.tenant_id or dialog.tenant_id)
rather than conv.user_id.
---
Nitpick comments:
In `@api/apps/sdk/session.py`:
- Around line 150-157: Extract the duplicated Authorization parsing into a
single helper (e.g., _resolve_beta_token) that takes the request, validates
request.headers.get("Authorization") by splitting and checking length, returns
(tenant_id, None) on success using APIToken.query(beta=token) and (None,
get_error_data_result(...)) on failure; replace the repeated 7-line blocks in
chatbot_completions, chatbots_inputs, agent_bot_completions, begin_inputs,
ask_about_embedded, retrieval_test_embedded, related_questions_embedded,
detail_share_embedded, and mindmap with calls to this helper (or a decorator)
and ensure the error messages use get_error_data_result exactly (fix the stray
trailing double quote in the 'API key is invalid!"' string) so all endpoints
share consistent token-parsing behavior.
🪄 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: ddddfcec-f025-4256-be6e-677c4c2e51dc
📒 Files selected for processing (1)
api/apps/sdk/session.py
|
Hi, @wangq8 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14592 +/- ##
=======================================
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:
|
|
Hi, @wangq8 |
|
Hi @dale053 I left 3 comments, all about one thing, please have a look. |
|
Hi, @wangq8 |
…nfiniflow#14592) Closes infiniflow#14590 ## Self Checks - [x] I have searched for existing issues [search for existing issues](https://github.com/infiniflow/ragflow/issues), including closed ones. - [x] I confirm that I am using English to submit this report ([Language Policy](infiniflow#5910)). - [x] Non-english title submitions will be closed directly ( 非英文标题的提交将会被直接关闭 ) ([Language Policy](infiniflow#5910)). - [x] Please do not modify this template :) and fill in all the required fields. ## RAGFlow workspace code commit ID `a1b2c3d4e5f67890123456789abcdef12345678` ## RAGFlow image version `0.13.1` ## Other environment information - Hardware parameters: N/A - OS type: Linux 6.17.0-22-generic - Others: API key authentication via `Authorization: Bearer <token>` ## Actual behavior The chatbot API endpoints: - `POST /chatbots/<dialog_id>/completions` - `GET /chatbots/<dialog_id>/info` validate only that the bearer token exists in `APIToken`, but do not verify that `dialog_id` belongs to the same tenant as that token. Current flow (simplified): 1. Route extracts bearer token and checks `APIToken.query(beta=token)`. 2. If token exists, request is accepted. 3. Downstream service resolves dialog globally by ID (`DialogService.get_by_id(dialog_id)` in `conversation_service.py`). 4. No tenant ownership check is enforced for `dialog_id`. Impact: Any user with a valid API key can attempt arbitrary `dialog_id` values and access/invoke chatbots outside their own tenant boundary if IDs are known/guessed/leaked. Security classification: - Vulnerability class: Broken Access Control (IDOR, OWASP Top 10 A01) - Severity recommendation: Critical - Exploit prerequisite: any valid API key + discoverable target `dialog_id` ## Expected behavior Requests to `/chatbots/<dialog_id>/completions` and `/chatbots/<dialog_id>/info` must be authorized only when: 1. bearer token is valid, and 2. `dialog_id` belongs to the same `tenant_id` as the token. Otherwise, reject with authorization failure (e.g., 403 or 404-equivalent policy). ## Steps to reproduce 1. Prepare two tenants: - Tenant A with API key `TOKEN_A` - Tenant B with chatbot `dialog_id = DIALOG_B` 2. Send request from Tenant A to Tenant B chatbot completion endpoint: ```bash curl -X POST "https://<host>/chatbots/DIALOG_B/completions" \ -H "Authorization: Bearer TOKEN_A" \ -H "Content-Type: application/json" \ -d '{"question":"hello","stream":false}' ``` 3. Observe request is processed (or reaches dialog resolution) without tenant ownership rejection. 4. Repeat against info endpoint: ```bash curl -X GET "https://<host>/chatbots/DIALOG_B/info" \ -H "Authorization: Bearer TOKEN_A" ``` 5. Observe the same missing ownership enforcement. ## Additional information Affected code paths: - `api/apps/sdk/session.py` - `chatbot_completions(dialog_id)` - `chatbots_inputs(dialog_id)` - `api/db/services/conversation_service.py` - `async_iframe_completion(...)` uses global dialog lookup Suggested fix: 1. In both chatbot endpoints: - Resolve `tenant_id = objs[0].tenant_id` from validated token. - Fetch dialog with tenant-scoped query (`DialogService.query(id=dialog_id, tenant_id=tenant_id)`). - Reject if dialog is not found/owned by tenant. 2. Defense in depth: - Require and enforce `tenant_id` in service-layer dialog resolution for external flows. - Avoid global `get_by_id(dialog_id)` where user-controlled dialog IDs are reachable. 3. Add regression tests: - Positive: same-tenant token + dialog succeeds. - Negative: cross-tenant token + dialog fails for both endpoints.
…nfiniflow#14592) Closes infiniflow#14590 ## Self Checks - [x] I have searched for existing issues [search for existing issues](https://github.com/infiniflow/ragflow/issues), including closed ones. - [x] I confirm that I am using English to submit this report ([Language Policy](infiniflow#5910)). - [x] Non-english title submitions will be closed directly ( 非英文标题的提交将会被直接关闭 ) ([Language Policy](infiniflow#5910)). - [x] Please do not modify this template :) and fill in all the required fields. ## RAGFlow workspace code commit ID `a1b2c3d4e5f67890123456789abcdef12345678` ## RAGFlow image version `0.13.1` ## Other environment information - Hardware parameters: N/A - OS type: Linux 6.17.0-22-generic - Others: API key authentication via `Authorization: Bearer <token>` ## Actual behavior The chatbot API endpoints: - `POST /chatbots/<dialog_id>/completions` - `GET /chatbots/<dialog_id>/info` validate only that the bearer token exists in `APIToken`, but do not verify that `dialog_id` belongs to the same tenant as that token. Current flow (simplified): 1. Route extracts bearer token and checks `APIToken.query(beta=token)`. 2. If token exists, request is accepted. 3. Downstream service resolves dialog globally by ID (`DialogService.get_by_id(dialog_id)` in `conversation_service.py`). 4. No tenant ownership check is enforced for `dialog_id`. Impact: Any user with a valid API key can attempt arbitrary `dialog_id` values and access/invoke chatbots outside their own tenant boundary if IDs are known/guessed/leaked. Security classification: - Vulnerability class: Broken Access Control (IDOR, OWASP Top 10 A01) - Severity recommendation: Critical - Exploit prerequisite: any valid API key + discoverable target `dialog_id` ## Expected behavior Requests to `/chatbots/<dialog_id>/completions` and `/chatbots/<dialog_id>/info` must be authorized only when: 1. bearer token is valid, and 2. `dialog_id` belongs to the same `tenant_id` as the token. Otherwise, reject with authorization failure (e.g., 403 or 404-equivalent policy). ## Steps to reproduce 1. Prepare two tenants: - Tenant A with API key `TOKEN_A` - Tenant B with chatbot `dialog_id = DIALOG_B` 2. Send request from Tenant A to Tenant B chatbot completion endpoint: ```bash curl -X POST "https://<host>/chatbots/DIALOG_B/completions" \ -H "Authorization: Bearer TOKEN_A" \ -H "Content-Type: application/json" \ -d '{"question":"hello","stream":false}' ``` 3. Observe request is processed (or reaches dialog resolution) without tenant ownership rejection. 4. Repeat against info endpoint: ```bash curl -X GET "https://<host>/chatbots/DIALOG_B/info" \ -H "Authorization: Bearer TOKEN_A" ``` 5. Observe the same missing ownership enforcement. ## Additional information Affected code paths: - `api/apps/sdk/session.py` - `chatbot_completions(dialog_id)` - `chatbots_inputs(dialog_id)` - `api/db/services/conversation_service.py` - `async_iframe_completion(...)` uses global dialog lookup Suggested fix: 1. In both chatbot endpoints: - Resolve `tenant_id = objs[0].tenant_id` from validated token. - Fetch dialog with tenant-scoped query (`DialogService.query(id=dialog_id, tenant_id=tenant_id)`). - Reject if dialog is not found/owned by tenant. 2. Defense in depth: - Require and enforce `tenant_id` in service-layer dialog resolution for external flows. - Avoid global `get_by_id(dialog_id)` where user-controlled dialog IDs are reachable. 3. Add regression tests: - Positive: same-tenant token + dialog succeeds. - Negative: cross-tenant token + dialog fails for both endpoints.
Closes #14590
Self Checks
RAGFlow workspace code commit ID
a1b2c3d4e5f67890123456789abcdef12345678RAGFlow image version
0.13.1Other environment information
Authorization: Bearer <token>Actual behavior
The chatbot API endpoints:
POST /chatbots/<dialog_id>/completionsGET /chatbots/<dialog_id>/infovalidate only that the bearer token exists in
APIToken, but do not verify thatdialog_idbelongs to the same tenant as that token.Current flow (simplified):
APIToken.query(beta=token).DialogService.get_by_id(dialog_id)inconversation_service.py).dialog_id.Impact: Any user with a valid API key can attempt arbitrary
dialog_idvalues and access/invoke chatbots outside their own tenant boundary if IDs are known/guessed/leaked.Security classification:
dialog_idExpected behavior
Requests to
/chatbots/<dialog_id>/completionsand/chatbots/<dialog_id>/infomust be authorized only when:dialog_idbelongs to the sametenant_idas the token.Otherwise, reject with authorization failure (e.g., 403 or 404-equivalent policy).
Steps to reproduce
TOKEN_Adialog_id = DIALOG_BAdditional information
Affected code paths:
api/apps/sdk/session.pychatbot_completions(dialog_id)chatbots_inputs(dialog_id)api/db/services/conversation_service.pyasync_iframe_completion(...)uses global dialog lookupSuggested fix:
tenant_id = objs[0].tenant_idfrom validated token.DialogService.query(id=dialog_id, tenant_id=tenant_id)).tenant_idin service-layer dialog resolution for external flows.get_by_id(dialog_id)where user-controlled dialog IDs are reachable.