Skip to content

fix(agent): enforce tenant ownership on agentbots completions/inputs - #15457

Merged
yuzhichang merged 4 commits into
infiniflow:mainfrom
philluiz2323:fix/agentbots-cross-tenant-idor
Jun 28, 2026
Merged

yuzhichang merged 4 commits into
infiniflow:mainfrom
philluiz2323:fix/agentbots-cross-tenant-idor

Conversation

@philluiz2323

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #15456.

The SDK agent-bot routes POST /api/v1/agentbots/<agent_id>/completions and GET /api/v1/agentbots/<agent_id>/inputs (api/apps/restful_apis/bot_api.py) authenticate the caller with a beta API token — which only yields the caller's tenant_id — but then load and run the agent named in the URL without verifying the agent belongs to the caller's tenant. UserCanvasService.get_agent_dsl_with_release even accepts a tenant_id it never uses, and begin_inputs calls get_by_id directly. Any holder of a single valid beta token could therefore run another tenant's agent (leaking its DSL/prompts/tool config) or read another tenant's agent metadata and begin input form, just by substituting a victim agent_id.

This PR adds the project's existing ownership gate, UserCanvasService.accessible(agent_id, tenant_id), to both endpoints right after token authentication — mirroring the checks already enforced on the equivalent first-party routes in api/apps/restful_apis/agent_api.py (lines 75/578/775) and on the sibling chatbot_completions / create_agent_session / delete_agent_session handlers in the same file. On failure it returns the same Can't find agent by ID: <id> message already used by begin_inputs, so it does not reveal whether an agent_id exists in another tenant.

Added a regression test (test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py, following the existing stubbed-loader pattern from test_get_agent_session.py) asserting that an inaccessible agent_id is rejected before the agent is loaded (begin_inputs) or executed (completions), and that an accessible agent still proceeds.

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

@dosubot dosubot Bot added size:XS This PR changes 0-9 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. labels May 31, 2026
@coderabbitai

coderabbitai Bot commented May 31, 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: 252a7afd-a1a8-47ff-9cc7-731abf382be8

📥 Commits

Reviewing files that changed from the base of the PR and between ad7377a and 86e1035.

📒 Files selected for processing (2)
  • api/apps/restful_apis/bot_api.py
  • test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/bot_api.py

📝 Walkthrough

Walkthrough

Adds tenant-scoped accessibility checks to the agent-bot completions and inputs handlers, returning Can't find agent by ID: {agent_id} when the agent is not accessible. Adds regression tests for denied and allowed paths.

Changes

Cross-tenant Access Control for Agent-Bot Endpoints

Layer / File(s) Summary
Endpoint access guards
api/apps/restful_apis/bot_api.py
agent_bot_completions and begin_inputs now call UserCanvasService.accessible(agent_id, tenant_id) before loading or running the agent, and return Can't find agent by ID: {agent_id} when access is denied.
Regression tests for access control
test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py
New test module dynamically imports bot_api.py with stubbed dependencies and verifies denied responses, short-circuit behavior, and allowed-path get_by_id invocation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped by the agent gate at dawn,
No tenant key? The path was gone.
"Can't find agent" now the rule,
Tests went splat, but code stayed cool,
Cross-tenant sneaks are nudged along.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.14% 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 states the main change: adding tenant ownership checks to agentbot completions and inputs.
Description check ✅ Passed The description includes the problem, background, and type of change, matching the required template.
Linked Issues check ✅ Passed The PR adds the required ownership check to both agentbot endpoints and returns the expected not-found error.
Out of Scope Changes check ✅ Passed The changes stay focused on the access-control fix and regression test, with no obvious unrelated code paths.

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.

@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

🧹 Nitpick comments (1)
test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py (1)

125-159: ⚡ Quick win

Add a positive-path test for agent_bot_completions.

This suite proves the new guard rejects foreign agents, but it still would not catch a regression where completions are rejected for all agents. Please add an accessible=True case that drives agent_bot_completions through its success path and asserts the completion branch is actually entered.

🤖 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/unit_test/api/apps/restful_apis/test_agentbots_access_control.py` around
lines 125 - 159, Add a positive-path test for agent_bot_completions by creating
a new test similar to test_begin_inputs_allowed_for_accessible_agent: call
_load_bot_api(monkeypatch, accessible=True, calls=calls), run
asyncio.run(module.agent_bot_completions(agent_id="own-agent")), then assert
that calls.get("completion") == "own-agent" (to ensure the completion branch
ran) and that result["code"] == 0 to confirm success; place this alongside the
other tests in TestAgentBotAccessControl so it covers the success path for
agent_bot_completions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 275-276: Add warning-level audit logs before each access-denial
return so tenant_id and agent_id are recorded; specifically, before the early
return that follows the call to thread_pool_exec(UserCanvasService.accessible,
agent_id, objs[0].tenant_id) add a process/service logger.warn (or
logger.warning) that includes tenant_id=objs[0].tenant_id and agent_id and a
short message about access denied, and apply the same pattern to the other
access-denial branch referenced (the similar return around lines 363-364) so
both rejection paths emit tenant_id and agent_id in the log.

---

Nitpick comments:
In `@test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py`:
- Around line 125-159: Add a positive-path test for agent_bot_completions by
creating a new test similar to test_begin_inputs_allowed_for_accessible_agent:
call _load_bot_api(monkeypatch, accessible=True, calls=calls), run
asyncio.run(module.agent_bot_completions(agent_id="own-agent")), then assert
that calls.get("completion") == "own-agent" (to ensure the completion branch
ran) and that result["code"] == 0 to confirm success; place this alongside the
other tests in TestAgentBotAccessControl so it covers the success path for
agent_bot_completions.
🪄 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: c461236e-881d-4777-bfe5-a9e84a2b0d12

📥 Commits

Reviewing files that changed from the base of the PR and between cd18cfa and dea37a5.

📒 Files selected for processing (2)
  • api/apps/restful_apis/bot_api.py
  • test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py

Comment thread api/apps/restful_apis/bot_api.py Resolved
…-tenant-idor

# Conflicts:
#	api/apps/restful_apis/bot_api.py
@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49

@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/apps/restful_apis/bot_api.py`:
- Around line 273-281: The tenant lookup in bot_api should be offloaded and
guarded because TenantService.get_by_id(uid) is synchronous and may return no
tenant. Update the chat_llm_name setup near the async stream() path to use
thread_pool_exec for the TenantService.get_by_id call, then check the returned
flag/object before reading tenant_info.llm_id. If the tenant is missing, avoid
crashing by using a safe fallback and add a log in this branch to record the
fallback 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: 846e0e17-22e8-4b6c-9c53-ea1acb9e5093

📥 Commits

Reviewing files that changed from the base of the PR and between 2f6fcd7 and ad7377a.

📒 Files selected for processing (1)
  • api/apps/restful_apis/bot_api.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.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

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/apps/restful_apis/bot_api.py`:
- Around line 273-281: The tenant lookup in bot_api should be offloaded and
guarded because TenantService.get_by_id(uid) is synchronous and may return no
tenant. Update the chat_llm_name setup near the async stream() path to use
thread_pool_exec for the TenantService.get_by_id call, then check the returned
flag/object before reading tenant_info.llm_id. If the tenant is missing, avoid
crashing by using a safe fallback and add a log in this branch to record the
fallback 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: 846e0e17-22e8-4b6c-9c53-ea1acb9e5093

📥 Commits

Reviewing files that changed from the base of the PR and between 2f6fcd7 and ad7377a.

📒 Files selected for processing (1)
  • api/apps/restful_apis/bot_api.py
🛑 Comments failed to post (1)
api/apps/restful_apis/bot_api.py (1)

273-281: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- bot_api.py around target lines ---\n'
sed -n '250,310p' api/apps/restful_apis/bot_api.py

printf '\n--- search TenantService.get_by_id definitions/usages ---\n'
rg -n "def get_by_id|get_by_id\(" api -g '*.py' | sed -n '1,120p'

printf '\n--- search thread_pool_exec usages/imports ---\n'
rg -n "thread_pool_exec" api -g '*.py' | sed -n '1,160p'

Repository: infiniflow/ragflow

Length of output: 247


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- bot_api.py around target lines ---'
sed -n '250,310p' api/apps/restful_apis/bot_api.py

echo
echo '--- search TenantService.get_by_id definitions/usages ---'
rg -n "def get_by_id|get_by_id\(" api -g '*.py' | sed -n '1,120p'

echo
echo '--- search thread_pool_exec usages/imports ---'
rg -n "thread_pool_exec" api -g '*.py' | sed -n '1,160p'

Repository: infiniflow/ragflow

Length of output: 27654


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- common_service get_by_id ---'
sed -n '250,340p' api/db/services/common_service.py

echo
echo '--- tenant_service definition ---'
sed -n '1,220p' api/db/services/tenant_service.py

echo
echo '--- decorators/helpers around tenant_id injection in bot_api.py ---'
sed -n '1,120p' api/apps/restful_apis/bot_api.py

Repository: infiniflow/ragflow

Length of output: 3143


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- locate TenantService definition ---'
rg -n "class TenantService\b" api -g '*.py'

echo
echo '--- bot_api.py top imports and logger ---'
sed -n '1,80p' api/apps/restful_apis/bot_api.py

echo
echo '--- tenant-related get_by_id call sites with handling ---'
rg -n "TenantService\.get_by_id\(" api -g '*.py' | sed -n '1,120p'

Repository: infiniflow/ragflow

Length of output: 5314


Offload and guard the tenant lookup here. api/apps/restful_apis/bot_api.py:273-281 — TenantService.get_by_id(uid) is synchronous and can return (False, None), so calling it directly in this async route can block the event loop and crash on tenant_info.llm_id when the tenant is missing. Use thread_pool_exec, handle the missing-tenant case, and log the fallback path.

🧰 Tools
🪛 ast-grep (0.44.0)

[info] 281-281: use jsonify instead of json.dumps for JSON output
Context: json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/bot_api.py` around lines 273 - 281, The tenant lookup
in bot_api should be offloaded and guarded because TenantService.get_by_id(uid)
is synchronous and may return no tenant. Update the chat_llm_name setup near the
async stream() path to use thread_pool_exec for the TenantService.get_by_id
call, then check the returned flag/object before reading tenant_info.llm_id. If
the tenant is missing, avoid crashing by using a safe fallback and add a log in
this branch to record the fallback path.

Source: Coding guidelines

@yuzhichang yuzhichang added the ci Continue Integration label Jun 28, 2026
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 28, 2026
@yuzhichang
yuzhichang merged commit bf18b59 into infiniflow:main Jun 28, 2026
3 of 9 checks passed
yuzhichang added a commit that referenced this pull request Jun 29, 2026
…15457)

### What problem does this PR solve?

Fixes #15456.

The SDK agent-bot routes `POST /api/v1/agentbots/<agent_id>/completions`
and `GET /api/v1/agentbots/<agent_id>/inputs`
(`api/apps/restful_apis/bot_api.py`) authenticate the caller with a beta
API token — which only yields the caller's `tenant_id` — but then load
and run the agent named in the URL **without verifying the agent belongs
to the caller's tenant**. `UserCanvasService.get_agent_dsl_with_release`
even accepts a `tenant_id` it never uses, and `begin_inputs` calls
`get_by_id` directly. Any holder of a single valid beta token could
therefore run another tenant's agent (leaking its DSL/prompts/tool
config) or read another tenant's agent metadata and begin input form,
just by substituting a victim `agent_id`.

This PR adds the project's existing ownership gate,
`UserCanvasService.accessible(agent_id, tenant_id)`, to both endpoints
right after token authentication — mirroring the checks already enforced
on the equivalent first-party routes in
`api/apps/restful_apis/agent_api.py` (lines 75/578/775) and on the
sibling `chatbot_completions` / `create_agent_session` /
`delete_agent_session` handlers in the same file. On failure it returns
the same `Can't find agent by ID: <id>` message already used by
`begin_inputs`, so it does not reveal whether an `agent_id` exists in
another tenant.

Added a regression test
(`test/unit_test/api/apps/restful_apis/test_agentbots_access_control.py`,
following the existing stubbed-loader pattern from
`test_get_agent_session.py`) asserting that an inaccessible `agent_id`
is rejected before the agent is loaded (`begin_inputs`) or executed
(`completions`), and that an accessible agent still proceeds.

### Type of change

- [x] 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):

---------

Co-authored-by: Zhichang Yu <[email protected]>
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit that referenced this pull request Jun 30, 2026
)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - #15609 ExeSQL SSRF guard + DNS pin
  - #15436 HTTP timeout on external API tools
  - #16363 be_output restore + DeepL error path
  - #15644 switch no longer matches empty condition
  - #15374 session_id bind to path agent_id (DAO idor guard)
  - #16169 sandbox artifact ownership gate
  - #15457 tenant ownership on agentbots
  - #15145 rerun agent document access check
- #15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - #15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - #15238 agentbot thinking-logs beta endpoint
  - #14589 UserFillUp SSE event propagation
  - #14890 anonymous webhook opt-in
- #15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).

Co-authored-by: yzc <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…iniflow#16455)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - infiniflow#15609 ExeSQL SSRF guard + DNS pin
  - infiniflow#15436 HTTP timeout on external API tools
  - infiniflow#16363 be_output restore + DeepL error path
  - infiniflow#15644 switch no longer matches empty condition
  - infiniflow#15374 session_id bind to path agent_id (DAO idor guard)
  - infiniflow#16169 sandbox artifact ownership gate
  - infiniflow#15457 tenant ownership on agentbots
  - infiniflow#15145 rerun agent document access check
- infiniflow#15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - infiniflow#15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - infiniflow#15238 agentbot thinking-logs beta endpoint
  - infiniflow#14589 UserFillUp SSE event propagation
  - infiniflow#14890 anonymous webhook opt-in
- infiniflow#15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cross-tenant agent IDOR: /agentbots/<agent_id>/completions and /inputs load and run any tenant's agent without an ownership check

2 participants