Skip to content

fix: enforce tenant-scoped authorization for chatbot SDK endpoints - #14592

Merged
wangq8 merged 9 commits into
infiniflow:mainfrom
dale053:fix/chatbot-idor-tenant-dialog-authorization
May 8, 2026
Merged

wangq8 merged 9 commits into
infiniflow:mainfrom
dale053:fix/chatbot-idor-tenant-dialog-authorization

Conversation

@dale053

@dale053 dale053 commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #14590

Self Checks

  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report (Language Policy).
  • Non-english title submitions will be closed directly ( 非英文标题的提交将会被直接关闭 ) (Language Policy).
  • 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:
curl -X POST "https://<host>/chatbots/DIALOG_B/completions" \
  -H "Authorization: Bearer TOKEN_A" \
  -H "Content-Type: application/json" \
  -d '{"question":"hello","stream":false}'
  1. Observe request is processed (or reaches dialog resolution) without tenant ownership rejection.
  2. Repeat against info endpoint:
curl -X GET "https://<host>/chatbots/DIALOG_B/info" \
  -H "Authorization: Bearer TOKEN_A"
  1. 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.

@dosubot dosubot Bot added size:S This PR changes 10-29 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 6, 2026
@coderabbitai

coderabbitai Bot commented May 6, 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

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

Changes

Tenant-Scoped Access Control for Chatbot Endpoints

Layer / File(s) Summary
Imports / Logger
api/db/services/conversation_service.py, api/apps/sdk/session.py
Add logging import and module-level logger; add StatusEnum import in session endpoints.
Service signature / Dialog resolution
api/db/services/conversation_service.py
async_iframe_completion(dialog_id, question, session_id=None, stream=True, tenant_id=None, **kwargs) now accepts tenant_id; resolves dialog via tenant-scoped query when provided and asserts session.dialog ownership.
Endpoint access validation
api/apps/sdk/session.py
.../completions, .../info
Endpoints extract tenant_id from validated APIToken, replace global lookup with DialogService.query(id=..., tenant_id=..., status=StatusEnum.VALID), default req["quote"]=False when missing, and return auth error with warning log when dialog not found under tenant.
Iframe/session ownership & streaming wiring
api/apps/sdk/session.py, api/db/services/conversation_service.py
Add _validate_iframe_access() to verify session existence and ownership; streaming and non-stream paths pass tenant_id into iframe_completion.
Tests
test/.../test_session_sdk_routes_unit.py
Add/adjust unit tests: authorized token with no dialog (deny), authorized streaming with tenant propagation, iframe streaming/non-stream branches, non-stream quote branch, and unauthorized dialog access assertions.

Sequence Diagram

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

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested Reviewers

  • xugangqiang
  • yingfeng

"I hopped through code to mend the wall,
Tokens checked so no one can sprawl.
Tenant flags set, streams pass along,
Dialogs guarded, nothing strong—
A rabbit's patch, secure and small." 🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 'fix: enforce tenant-scoped authorization for chatbot SDK endpoints' clearly and concisely summarizes the main change: implementing tenant-scoped authorization checks for chatbot endpoints.
Description check ✅ Passed The description addresses all required template sections: problem statement (cross-tenant IDOR vulnerability), type of change (Bug Fix), and linked issue reference (#14590) with comprehensive context.
Linked Issues check ✅ Passed The code changes fully address all requirements from #14590: tenant-scoped authorization is enforced in SDK endpoints via token-derived tenant_id, dialog queries are tenant-scoped, authorization failures are logged and rejected, and test coverage for both same-tenant and cross-tenant scenarios is added.
Out of Scope Changes check ✅ Passed All changes directly address the IDOR vulnerability: endpoint authorization in session.py, service-layer tenant-scoped resolution in conversation_service.py, and regression test coverage align with the security fix scope.

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

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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: 4

🧹 Nitpick comments (1)
test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py (1)

1339-1343: ⚡ Quick win

Missing positive (happy-path) test for chatbots_inputs

The test coverage for chatbots_inputs only exercises the three rejection branches (bad header, invalid key, no dialog). There is no test verifying the success path — i.e., that when DialogService.query returns 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

📥 Commits

Reviewing files that changed from the base of the PR and between f32034e and 10b44f7.

📒 Files selected for processing (3)
  • api/apps/sdk/session.py
  • api/db/services/conversation_service.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py

Comment thread api/apps/sdk/session.py Resolved
Comment thread api/apps/sdk/session.py Resolved
Comment thread api/db/services/conversation_service.py Resolved
Comment thread api/db/services/conversation_service.py Resolved
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 6, 2026

@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

♻️ Duplicate comments (1)
api/apps/sdk/session.py (1)

156-158: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add 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_id and dialog_id rather 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

📥 Commits

Reviewing files that changed from the base of the PR and between 10b44f7 and 7e94750.

📒 Files selected for processing (1)
  • api/apps/sdk/session.py

Comment thread api/apps/sdk/session.py Resolved

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e94750 and f5cf152.

📒 Files selected for processing (2)
  • api/apps/sdk/session.py
  • api/db/services/conversation_service.py

Comment thread api/db/services/conversation_service.py Resolved

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

🧹 Nitpick comments (1)
api/apps/sdk/session.py (1)

150-157: ⚡ Quick win

Duplicated token-extraction boilerplate across chatbot/agent/search endpoints.

The same 7-line pattern (split Authorization, validate length, APIToken.query(beta=token), derive tenant_id) is repeated in chatbot_completions, chatbots_inputs, agent_bot_completions, begin_inputs, ask_about_embedded, retrieval_test_embedded, related_questions_embedded, detail_share_embedded, and mindmap. 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

📥 Commits

Reviewing files that changed from the base of the PR and between f5cf152 and 8a7e1b6.

📒 Files selected for processing (1)
  • api/apps/sdk/session.py

Comment thread api/apps/sdk/session.py Resolved
Comment thread api/apps/sdk/session.py Resolved
Comment thread api/apps/sdk/session.py Resolved
@dale053

dale053 commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8
All checks have passed.
When you have a chance, could you please review this PR?
Thank you for your time

@yingfeng
yingfeng requested a review from wangq8 May 7, 2026 02:02
@yingfeng yingfeng added the ci Continue Integration label May 7, 2026
@yingfeng
yingfeng marked this pull request as draft May 7, 2026 02:03
@yingfeng
yingfeng marked this pull request as ready for review May 7, 2026 02:03
@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (a82ae4a) to head (db9085a).
⚠️ Report is 3 commits behind head on main.

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

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 7, 2026
@dale053

dale053 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8
Could you please review this PR?

Comment thread api/apps/sdk/session.py Resolved
Comment thread api/apps/sdk/session.py Resolved
Comment thread api/db/services/conversation_service.py Resolved
@wangq8

wangq8 commented May 8, 2026

Copy link
Copy Markdown
Collaborator

Hi @dale053 I left 3 comments, all about one thing, please have a look.

@dale053

dale053 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8
All checks have just passed!
Could you please review this PR?

@wangq8
wangq8 merged commit 26d7018 into infiniflow:main May 8, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…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.
@dosubot dosubot Bot mentioned this pull request May 19, 2026
4 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…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.
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 size:L This PR changes 100-499 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Cross-tenant chatbot access via valid API key (/chatbots/<dialog_id>/completions, /chatbots/<dialog_id>/info)

3 participants