Skip to content

fix(agent): enforce document access on POST /api/v1/agents/rerun - #15145

Merged
yuzhichang merged 8 commits into
infiniflow:mainfrom
pekar9781:fix/agents-rerun-pipeline-idor
Jun 28, 2026
Merged

yuzhichang merged 8 commits into
infiniflow:mainfrom
pekar9781:fix/agents-rerun-pipeline-idor

Conversation

@pekar9781

Copy link
Copy Markdown

Related issues

Closes #15144

What problem does this PR solve?

POST /api/v1/agents/rerun loaded a pipeline operation log by UUID via PipelineOperationLogService.get_documents_info with no authorization, then wiped chunks, reset document counters, deleted tasks, and re-queued dataflow for the victim document.

Any authenticated user who knew a victim's pipeline log id could disrupt parsing on documents they did not own.

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

Changes

File Change
api/apps/restful_apis/agent_api.py Call DocumentService.accessible(doc["id"], tenant_id) before destructive rerun operations; deny with generic "Document not found."
test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py Unit tests: cross-tenant log rejected, missing/unauthorized same message, authorized rerun proceeds

Security notes

  • CWE-639: Closes cross-tenant pipeline rerun / chunk wipe via leaked log UUID.
  • tenant_id from @add_tenant_id_to_kwargs is current_user.id; DocumentService.accessible covers team-shared KBs.

Test plan

  • pytest test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py
  • Manual: attacker cannot rerun victim pipeline log id
cd ragflow
uv run pytest test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py -q

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label May 22, 2026
@coderabbitai

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

This PR adds a tenant accessibility check to rerun_agent before rerun side effects run, and adds regression tests for missing, unauthorized, and authorized rerun requests.

Changes

Rerun Agent Authorization Fix

Layer / File(s) Summary
Authorization guard in rerun_agent
api/apps/restful_apis/agent_api.py
Added DocumentService.accessible(doc["id"], tenant_id) before rerun processing and returns "Document not found." when access is denied.
Authorization test suite
test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py
Adds a dynamic import test harness with monkeypatched services plus three tests for cross-tenant rejection, consistent missing/unauthorized messaging, and successful authorized rerun behavior.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A rabbit hopped where reruns start,
And checked each doc with careful art.
"Not found" for doors that shouldn't swing,
While rightful requests still take wing.
🐰

Suggested labels

🐞 bug, 🐖api

🚥 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 clearly and concisely describes the main change: enforcing document access on the rerun agent endpoint.
Description check ✅ Passed The description matches the template and includes the problem, change type, implementation details, security notes, and test plan.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

949-950: ⚡ Quick win

Add audit logging for the new authorization deny branch.

The generic error response is correct, but this new security path should log denied rerun attempts (tenant + doc/log context) for incident triage.

Proposed change
     doc = doc[0]
     if not DocumentService.accessible(doc["id"], tenant_id):
+        logging.warning(
+            "rerun_agent denied: tenant_id=%s log_id=%s doc_id=%s",
+            tenant_id,
+            req.get("id"),
+            doc.get("id"),
+        )
         return get_data_error_result(message="Document not found.")

As per coding guidelines: **/*.py: Add logging for new flows.

🤖 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/agent_api.py` around lines 949 - 950, The new
authorization-deny branch that returns get_data_error_result needs audit
logging: inside the if block that checks DocumentService.accessible(doc["id"],
tenant_id) add a structured audit log (using the module logger) recording the
denied action (e.g., "document rerun denied"), the tenant_id and doc["id"], and
any available request/context identifier (user id or request id) so incident
triage can correlate events; ensure the log level is appropriate for audits
(info/warn) and keep the existing return 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.

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 949-950: The new authorization-deny branch that returns
get_data_error_result needs audit logging: inside the if block that checks
DocumentService.accessible(doc["id"], tenant_id) add a structured audit log
(using the module logger) recording the denied action (e.g., "document rerun
denied"), the tenant_id and doc["id"], and any available request/context
identifier (user id or request id) so incident triage can correlate events;
ensure the log level is appropriate for audits (info/warn) and keep the existing
return behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 16acee75-756f-4c95-81f0-03a3e8b6bd5b

📥 Commits

Reviewing files that changed from the base of the PR and between b2bf915 and 4e21cbc.

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

@pekar9781

Copy link
Copy Markdown
Author

Hi @wangq8
If you have time, could you please check my PR? Thanks.

@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

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

1048-1049: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Log denied rerun attempts on this new auth branch.

This adds a new authorization failure path on a destructive endpoint, but the denial is silent server-side. Please keep the generic "Document not found." response, but log the tenant/document context before returning so cross-tenant probes are observable. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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/agent_api.py` around lines 1048 - 1049, The new
authorization failure path in the destructive document flow is returning a
generic response without any server-side trace. In the branch that checks
DocumentService.accessible inside the agent API handler, keep the existing
"Document not found." result but add a log entry before returning, including the
tenant_id and document id so denied cross-tenant rerun attempts are observable.
Use the surrounding handler logic and the DocumentService.accessible check to
place the log in the new auth branch.

Source: Coding guidelines

🤖 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/agent_api.py`:
- Line 377: The direct calls to validate_rest_api_page_size in the agent API
request handlers are letting ValueError escape and turn bad page_size query
params into 500s. Update the affected request flows in agent_api (including the
code paths that use items_per_page/page_size) to catch validation failures and
convert them into a structured client error response, using the existing
request-handling error pattern in this module so malformed or oversized
page_size values return a 4xx instead of bubbling up.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1048-1049: The new authorization failure path in the destructive
document flow is returning a generic response without any server-side trace. In
the branch that checks DocumentService.accessible inside the agent API handler,
keep the existing "Document not found." result but add a log entry before
returning, including the tenant_id and document id so denied cross-tenant rerun
attempts are observable. Use the surrounding handler logic and the
DocumentService.accessible check to place the log in the new auth branch.
🪄 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: d23a369e-ea6e-454b-8425-db96fdd1b1b4

📥 Commits

Reviewing files that changed from the base of the PR and between 4e21cbc and eae2be7.

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

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

1048-1049: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Log denied rerun attempts on this new auth branch.

This adds a new authorization failure path on a destructive endpoint, but the denial is silent server-side. Please keep the generic "Document not found." response, but log the tenant/document context before returning so cross-tenant probes are observable. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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/agent_api.py` around lines 1048 - 1049, The new
authorization failure path in the destructive document flow is returning a
generic response without any server-side trace. In the branch that checks
DocumentService.accessible inside the agent API handler, keep the existing
"Document not found." result but add a log entry before returning, including the
tenant_id and document id so denied cross-tenant rerun attempts are observable.
Use the surrounding handler logic and the DocumentService.accessible check to
place the log in the new auth branch.

Source: Coding guidelines

🤖 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/agent_api.py`:
- Line 377: The direct calls to validate_rest_api_page_size in the agent API
request handlers are letting ValueError escape and turn bad page_size query
params into 500s. Update the affected request flows in agent_api (including the
code paths that use items_per_page/page_size) to catch validation failures and
convert them into a structured client error response, using the existing
request-handling error pattern in this module so malformed or oversized
page_size values return a 4xx instead of bubbling up.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1048-1049: The new authorization failure path in the destructive
document flow is returning a generic response without any server-side trace. In
the branch that checks DocumentService.accessible inside the agent API handler,
keep the existing "Document not found." result but add a log entry before
returning, including the tenant_id and document id so denied cross-tenant rerun
attempts are observable. Use the surrounding handler logic and the
DocumentService.accessible check to place the log in the new auth branch.
🪄 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: d23a369e-ea6e-454b-8425-db96fdd1b1b4

📥 Commits

Reviewing files that changed from the base of the PR and between 4e21cbc and eae2be7.

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

377-377: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Handle page_size validation failures as request errors.

Line 377 and Line 600 call validate_rest_api_page_size(...) directly. That helper raises ValueError, so an oversized or malformed page_size now turns a bad query string into an HTTP 500 instead of a structured 4xx response.

Also applies to: 600-600

🤖 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/agent_api.py` at line 377, The direct calls to
validate_rest_api_page_size in the agent API request handlers are letting
ValueError escape and turn bad page_size query params into 500s. Update the
affected request flows in agent_api (including the code paths that use
items_per_page/page_size) to catch validation failures and convert them into a
structured client error response, using the existing request-handling error
pattern in this module so malformed or oversized page_size values return a 4xx
instead of bubbling up.

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

codecov Bot commented Jun 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (f90be41) to head (8126346).
⚠️ Report is 14 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15145      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Harness.
📢 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.

@yuzhichang
yuzhichang merged commit 08c807a into infiniflow:main Jun 28, 2026
3 checks passed
yuzhichang added a commit that referenced this pull request Jun 29, 2026
)

## Related issues

Closes #15144

### What problem does this PR solve?

`POST /api/v1/agents/rerun` loaded a pipeline operation log by UUID via
`PipelineOperationLogService.get_documents_info` with no authorization,
then wiped chunks, reset document counters, deleted tasks, and re-queued
dataflow for the victim document.

Any authenticated user who knew a victim's pipeline log id could disrupt
parsing on documents they did not own.

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

### Changes

| File | Change |
|------|--------|
| `api/apps/restful_apis/agent_api.py` | Call
`DocumentService.accessible(doc["id"], tenant_id)` before destructive
rerun operations; deny with generic `"Document not found."` |
|
`test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py`
| Unit tests: cross-tenant log rejected, missing/unauthorized same
message, authorized rerun proceeds |

### Security notes

- **CWE-639:** Closes cross-tenant pipeline rerun / chunk wipe via
leaked log UUID.
- `tenant_id` from `@add_tenant_id_to_kwargs` is `current_user.id`;
`DocumentService.accessible` covers team-shared KBs.

### Test plan

- [ ] `pytest
test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py`
- [ ] Manual: attacker cannot rerun victim pipeline log id

```bash
cd ragflow
uv run pytest test/unit_test/api/apps/restful_apis/test_rerun_agent_authorization.py -q
```

---------

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.
euvre added a commit to euvre/ragflow that referenced this pull request Sep 1, 2026
The Go port of POST /api/v1/agents/rerun failed every request with
"500 server misconfiguration: document service not wired". Two defects
stacked:

1. The fail-closed gate from infiniflow#15145 required a documentService, but
   cmd/ragflow_server.go never chained WithDocumentService onto
   NewAgentHandler.
2. It could never have compiled if it had: the injected
   documentAccessChecker interface declared Accessible(docID, userID)
   while the concrete DocumentService.Accessible takes a context, so
   the production service did not satisfy the interface. A compile-time
   assertion now pins the contract.

Beyond the 500, the handler treated body.id as a document id, but the
front-end (web useRerunDataflow) sends the pipeline operation LOG id —
Python resolves log -> document via get_documents_info before gating.
Even with the service wired the rerun would have been rejected with
"Document not found." and, if it ever passed, silently did nothing.

Implement the rerun properly on DocumentService.RerunDataflow:
resolve the log to its document, enforce accessibility, refuse while
the document is mid-run (0 < progress < 1), persist the edited DSL with
dsl.path = [component_id] on the log row (Python update_by_id parity),
then clear prior parse results and enqueue a fresh ingestion run via
the existing StartParseDocuments(RerunWithDelete) machinery. The Go
pipeline has no partial-resume entry point, so the rerun re-executes
the full pipeline instead of resuming from component_id.
euvre added a commit to euvre/ragflow that referenced this pull request Sep 2, 2026
The Go port of POST /api/v1/agents/rerun failed every request with
"500 server misconfiguration: document service not wired". Two defects
stacked:

1. The fail-closed gate from infiniflow#15145 required a documentService, but
   cmd/ragflow_server.go never chained WithDocumentService onto
   NewAgentHandler.
2. It could never have compiled if it had: the injected
   documentAccessChecker interface declared Accessible(docID, userID)
   while the concrete DocumentService.Accessible takes a context, so
   the production service did not satisfy the interface. A compile-time
   assertion now pins the contract.

Beyond the 500, the handler treated body.id as a document id, but the
front-end (web useRerunDataflow) sends the pipeline operation LOG id —
Python resolves log -> document via get_documents_info before gating.
Even with the service wired the rerun would have been rejected with
"Document not found." and, if it ever passed, silently did nothing.

Implement the rerun properly on DocumentService.RerunDataflow:
resolve the log to its document, enforce accessibility, refuse while
the document is mid-run (0 < progress < 1), persist the edited DSL with
dsl.path = [component_id] on the log row (Python update_by_id parity),
then clear prior parse results and enqueue a fresh ingestion run via
the existing StartParseDocuments(RerunWithDelete) machinery. The Go
pipeline has no partial-resume entry point, so the rerun re-executes
the full pipeline instead of resuming from component_id.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants