Skip to content

fix(agent): add SSRF guard to Invoke HTTP component - #15426

Merged
yuzhichang merged 8 commits into
infiniflow:mainfrom
glorysr1209-png:fix/invoke-ssrf-guard
Jun 28, 2026
Merged

yuzhichang merged 8 commits into
infiniflow:mainfrom
glorysr1209-png:fix/invoke-ssrf-guard

Conversation

@glorysr1209-png

Copy link
Copy Markdown
Contributor

Summary

Closes #15425. The agent Invoke (HTTP Request) component now calls assert_url_is_safe and pin_dns before requests.*, matching Crawler and SearXNG.

Changes

  • agent/component/invoke.py: SSRF guard + DNS pinning on outbound requests.
  • test_invoke_component_unit.py: unit test blocks loopback URL without calling requests.get.

Test plan

  • pytest test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py::test_invoke_blocks_loopback_url_with_ssrf_guard (requires project test env / ZHIPU_AI_API_KEY in CI)

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 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: 05094a17-e415-4fa9-a1e3-7eeb2921117f

📥 Commits

Reviewing files that changed from the base of the PR and between 4c69ea5 and 86396cb.

📒 Files selected for processing (1)
  • agent/component/invoke.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • agent/component/invoke.py

📝 Walkthrough

Walkthrough

Adds SSRF validation and DNS pinning to the agent Invoke component, normalizes proxy handling, disables redirect following, and adds unit tests covering blocked targets and request behavior.

Changes

SSRF Protection for Agent Invoke Component

Layer / File(s) Summary
SSRF imports and URL parsing
agent/component/invoke.py
Add URL parsing and SSRF guard support for validation and DNS pinning.
Proxy normalization and redirect handling
agent/component/invoke.py
Add proxy URL normalization and SSRF log target formatting, update proxy presence checks, and disable HTTP redirects in _send_request.
Invoke URL guard and DNS pinning
agent/component/invoke.py
Validate configured proxy and destination URLs in _invoke, fail fast on unsafe URLs, and wrap request retries in pin_dns for destination and proxy resolution.
Unit tests for blocked targets and redirects
test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py
Add unit tests for loopback, metadata, missing-scheme, and loopback-proxy blocking, plus redirect suppression on outgoing requests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#16409: Shares the same Invoke hardening pattern: assert_url_is_safe, pin_dns, proxy safety checks, and allow_redirects=False.

Suggested reviewers

  • xugangqiang

Poem

🐰 I hop through URLs, careful and bright,
No loopback shadows will slip through tonight.
DNS pinned firm, redirects held tight,
Safe little requests take a safer flight.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is missing the required template sections for the problem statement and type of change. Add the missing template sections and fill in the problem statement plus the change type checkbox.
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately describes the main change: adding an SSRF guard to the Invoke HTTP component.
Linked Issues check ✅ Passed The changes match #15425 by adding URL safety checks, DNS pinning, unsafe-target rejection, and unit coverage before outbound requests.
Out of Scope Changes check ✅ Passed The modified files and tests are focused on Invoke SSRF protection and redirect handling, with no clear unrelated changes.

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)
agent/component/invoke.py (1)

227-232: ⚡ Quick win

Log the SSRF-block decision.

This new short-circuit path sets _ERROR and returns but emits no log, leaving blocked (potentially malicious) requests invisible in operations/audit. Add a log on the block branch. As per coding guidelines, "Add logging for new flows".

🪵 Proposed change
         try:
             ssrf_hostname, ssrf_ip = assert_url_is_safe(url)
         except ValueError as e:
+            logging.warning("Invoke SSRF guard blocked url=%r: %s", url, e)
             self.set_output("_ERROR", str(e))
             return f"Http request error: SSRF guard blocked {url!r}: {e}"
🤖 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 `@agent/component/invoke.py` around lines 227 - 232, The SSRF short-circuit
currently sets self.set_output("_ERROR", ...) and returns without logging;
update the except ValueError block in the invoke flow (where assert_url_is_safe
is called) to emit a log entry (e.g., self.logger.warning or self.logger.info)
that records the blocked URL and error message before returning, so the
SSRF-block decision is visible in audit/ops logs while keeping the existing
set_output and 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.

Inline comments:
In `@agent/component/invoke.py`:
- Around line 234-243: The SSRF guard only validates the initial url and pinned
hostname in _invoke but misses redirects and proxy targets; update _send_request
to disable automatic redirect following (set allow_redirects=False) or implement
per-redirect validation that calls assert_url_is_safe() and updates pin_dns()
for each redirect target before following it, validate the proxy host created by
_build_proxies by running assert_url_is_safe() and pinning its hostname (or
reject user-controlled proxies), and ensure the ValueError path from
assert_url_is_safe() sets _ERROR and logs the incident via the existing logger
(include the URL and error) so SSRF rejections are recorded.

---

Nitpick comments:
In `@agent/component/invoke.py`:
- Around line 227-232: The SSRF short-circuit currently sets
self.set_output("_ERROR", ...) and returns without logging; update the except
ValueError block in the invoke flow (where assert_url_is_safe is called) to emit
a log entry (e.g., self.logger.warning or self.logger.info) that records the
blocked URL and error message before returning, so the SSRF-block decision is
visible in audit/ops logs while keeping the existing set_output and return
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: 5ec08a45-f931-4b10-975e-5a66bc73a924

📥 Commits

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

📒 Files selected for processing (2)
  • agent/component/invoke.py
  • test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py

Comment thread agent/component/invoke.py Resolved
glorysr1209-png and others added 2 commits June 5, 2026 13:12
Validate and pin proxy targets, disable redirect following, and redact
blocked URL details in security logs per review feedback.

Co-authored-by: Cursor <[email protected]>
@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 Jun 5, 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.

🧹 Nitpick comments (3)
test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py (3)

289-298: 💤 Low value

Consider checking invoke.output("_ERROR") for consistency.

This test correctly verifies the metadata IP is blocked, but line 286 checks both the return value AND invoke.output("_ERROR"). For consistency across SSRF tests, consider adding:

assert invoke.output("_ERROR") == "URL not valid"
🤖 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_web_api/test_canvas_app/test_invoke_component_unit.py`
around lines 289 - 298, Add an assertion that checks the internal error output
for consistency with other SSRF tests: after calling invoke._invoke() in
test_invoke_blocks_metadata_ip (which uses _load_invoke_module and
_make_invoke), assert that invoke.output("_ERROR") == "URL not valid" in
addition to the existing checks so the test verifies both the return value and
the invoke output channel.

289-331: ⚖️ Poor tradeoff

Consider adding IPv6 loopback coverage.

The SSRF guard tests comprehensively cover IPv4 scenarios, but IPv6 loopback addresses (e.g., http://[::1]:8080) and IPv4-mapped IPv6 addresses (e.g., http://[::ffff:127.0.0.1]:8080) are not tested. Since common.ssrf_guard.assert_url_is_safe uses ip.is_global (which handles IPv6), adding a test for IPv6 loopback would strengthen the security test suite.

🔒 Suggested IPv6 loopback test
`@pytest.mark.p2`
def test_invoke_blocks_ipv6_loopback(monkeypatch):
    """Verify IPv6 loopback addresses are blocked by SSRF guard."""
    module = _load_invoke_module(monkeypatch)
    invoke = _make_invoke(module, url="http://[::1]:8080/api")
    mock_get = MagicMock(return_value=SimpleNamespace(text="should not run"))
    monkeypatch.setattr(module.requests, "get", mock_get)
    result = invoke._invoke()
    mock_get.assert_not_called()
    assert "URL not valid" in result
🤖 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_web_api/test_canvas_app/test_invoke_component_unit.py`
around lines 289 - 331, Add tests to cover IPv6 loopback and IPv4-mapped IPv6
addresses so the SSRF guard blocks them; create tests mirroring
test_invoke_blocks_loopback_proxy (use _load_invoke_module, _make_invoke and
call invoke._invoke) with URLs like "http://[::1]:8080/..." and
"http://[::ffff:127.0.0.1]:8080/..." (and assert module.requests.get is not
called and the result contains "URL not valid") to ensure
common.ssrf_guard.assert_url_is_safe handles IPv6 cases.

312-321: 💤 Low value

Consider checking invoke.output("_ERROR") for consistency.

Same suggestion as the metadata IP test: for consistency with line 286, consider adding:

assert invoke.output("_ERROR") == "URL not valid"
🤖 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_web_api/test_canvas_app/test_invoke_component_unit.py`
around lines 312 - 321, Add an assertion to verify the component's error output
matches the expected message: after calling invoke._invoke() in
test_invoke_blocks_loopback_proxy (and after mock_get.assert_not_called()),
assert that invoke.output("_ERROR") == "URL not valid" so the test checks both
the return string and the component's error channel (use the existing invoke
object and its output method).
🤖 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 `@test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py`:
- Around line 289-298: Add an assertion that checks the internal error output
for consistency with other SSRF tests: after calling invoke._invoke() in
test_invoke_blocks_metadata_ip (which uses _load_invoke_module and
_make_invoke), assert that invoke.output("_ERROR") == "URL not valid" in
addition to the existing checks so the test verifies both the return value and
the invoke output channel.
- Around line 289-331: Add tests to cover IPv6 loopback and IPv4-mapped IPv6
addresses so the SSRF guard blocks them; create tests mirroring
test_invoke_blocks_loopback_proxy (use _load_invoke_module, _make_invoke and
call invoke._invoke) with URLs like "http://[::1]:8080/..." and
"http://[::ffff:127.0.0.1]:8080/..." (and assert module.requests.get is not
called and the result contains "URL not valid") to ensure
common.ssrf_guard.assert_url_is_safe handles IPv6 cases.
- Around line 312-321: Add an assertion to verify the component's error output
matches the expected message: after calling invoke._invoke() in
test_invoke_blocks_loopback_proxy (and after mock_get.assert_not_called()),
assert that invoke.output("_ERROR") == "URL not valid" so the test checks both
the return string and the component's error channel (use the existing invoke
object and its output method).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 064d9302-6ac9-4304-924e-389969f6c3c5

📥 Commits

Reviewing files that changed from the base of the PR and between 59e5d21 and 4c69ea5.

📒 Files selected for processing (2)
  • agent/component/invoke.py
  • test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • agent/component/invoke.py

@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49
@yuzhichang yuzhichang added the ci Continue Integration label Jun 28, 2026
@yuzhichang
yuzhichang merged commit e16d1a0 into infiniflow:main Jun 28, 2026
2 of 3 checks passed
yuzhichang added a commit that referenced this pull request Jun 29, 2026
## Summary

Closes #15425. The agent **Invoke** (HTTP Request) component now calls
`assert_url_is_safe` and `pin_dns` before `requests.*`, matching Crawler
and SearXNG.

## Changes

- `agent/component/invoke.py`: SSRF guard + DNS pinning on outbound
requests.
- `test_invoke_component_unit.py`: unit test blocks loopback URL without
calling `requests.get`.

## Test plan

- [x] `pytest
test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py::test_invoke_blocks_loopback_url_with_ssrf_guard`
(requires project test env / `ZHIPU_AI_API_KEY` in CI)

---------

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

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 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#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…hunker file support

Two regressions caught in code review of a00ef0d:

1. Invoke proxy path did not actually pin DNS
   The previous code said (in a comment) "we layer our own pin
   around the proxy dial target" but the implementation was
   just http.Transport{Proxy: http.ProxyURL(...)} — no
   custom DialContext, so the proxy host got re-resolved at
   connect time, re-opening the TOCTOU window the SSRF
   guard was supposed to close.

   Fix: wrap the proxy transport in a custom DialContext
   that intercepts the proxy-host dial and replaces the
   target with the validated public IP (the same pattern
   utility.PinnedHTTPClient uses for the direct path). The
   connection now goes to the IP we validated, even if a
   subsequent DNS lookup returns a different answer.

   New TestInvoke_ProxyDNSPin exercises the pin path.

2. PipelineChunker accepted only text — not file input
   The previous commit documented "accepts TEXT input" and
   ran the chunk engine on whatever string the caller
   passed. The Python PR's contract is chunk(filename) —
   it does file-format extraction (PDF/DOCX/table/...) AND
   chunking in one step. The Go port silently downgraded
   the contract.

   Fix: PipelineChunker now reads file_bytes / file_ref /
   text / content from the inputs map, and the dispatch
   keys on parser_id (not just validation):

   - text / content  → run through chunk engine
   - file_bytes      → run through chunk engine (caller
                       has done the extraction)
   - file_ref (with bytes) → run through chunk engine
   - non-UTF-8 bytes → reject with a clear error (PDF
                       extraction is a follow-up)
   - parser_id       → selects a real chunk strategy
                       (naive→paragraph, paper/laws→sentence,
                       qa→paragraph, etc.) so the output
                       actually differs by parser_id

   File-format extraction (PDF/DOCX/table/...) remains a
   documented follow-up — the Go file→text layer is not
   unified the way Python's rag.app.*.chunk functions are.
   The component now rejects non-UTF-8 bytes explicitly so
   a downstream caller that mistakenly passes a PDF
   without extraction sees a clear error rather than a
   silent garbled chunk.

   7 new PipelineChunker tests cover: text input, content
   alias, parser_id dispatch (paper > naive chunk count
   on the same input), file_bytes UTF-8, file_ref
   resolution, non-UTF-8 rejection, empty input.

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

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 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#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…hunker file support

Two regressions caught in code review of a00ef0d:

1. Invoke proxy path did not actually pin DNS
   The previous code said (in a comment) "we layer our own pin
   around the proxy dial target" but the implementation was
   just http.Transport{Proxy: http.ProxyURL(...)} — no
   custom DialContext, so the proxy host got re-resolved at
   connect time, re-opening the TOCTOU window the SSRF
   guard was supposed to close.

   Fix: wrap the proxy transport in a custom DialContext
   that intercepts the proxy-host dial and replaces the
   target with the validated public IP (the same pattern
   utility.PinnedHTTPClient uses for the direct path). The
   connection now goes to the IP we validated, even if a
   subsequent DNS lookup returns a different answer.

   New TestInvoke_ProxyDNSPin exercises the pin path.

2. PipelineChunker accepted only text — not file input
   The previous commit documented "accepts TEXT input" and
   ran the chunk engine on whatever string the caller
   passed. The Python PR's contract is chunk(filename) —
   it does file-format extraction (PDF/DOCX/table/...) AND
   chunking in one step. The Go port silently downgraded
   the contract.

   Fix: PipelineChunker now reads file_bytes / file_ref /
   text / content from the inputs map, and the dispatch
   keys on parser_id (not just validation):

   - text / content  → run through chunk engine
   - file_bytes      → run through chunk engine (caller
                       has done the extraction)
   - file_ref (with bytes) → run through chunk engine
   - non-UTF-8 bytes → reject with a clear error (PDF
                       extraction is a follow-up)
   - parser_id       → selects a real chunk strategy
                       (naive→paragraph, paper/laws→sentence,
                       qa→paragraph, etc.) so the output
                       actually differs by parser_id

   File-format extraction (PDF/DOCX/table/...) remains a
   documented follow-up — the Go file→text layer is not
   unified the way Python's rag.app.*.chunk functions are.
   The component now rejects non-UTF-8 bytes explicitly so
   a downstream caller that mistakenly passes a PDF
   without extraction sees a clear error rather than a
   silent garbled chunk.

   7 new PipelineChunker tests cover: text input, content
   alias, parser_id dispatch (paper > naive chunk count
   on the same input), file_bytes UTF-8, file_ref
   resolution, non-UTF-8 rejection, empty input.

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

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 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#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…hunker file support

Two regressions caught in code review of a00ef0d:

1. Invoke proxy path did not actually pin DNS
   The previous code said (in a comment) "we layer our own pin
   around the proxy dial target" but the implementation was
   just http.Transport{Proxy: http.ProxyURL(...)} — no
   custom DialContext, so the proxy host got re-resolved at
   connect time, re-opening the TOCTOU window the SSRF
   guard was supposed to close.

   Fix: wrap the proxy transport in a custom DialContext
   that intercepts the proxy-host dial and replaces the
   target with the validated public IP (the same pattern
   utility.PinnedHTTPClient uses for the direct path). The
   connection now goes to the IP we validated, even if a
   subsequent DNS lookup returns a different answer.

   New TestInvoke_ProxyDNSPin exercises the pin path.

2. PipelineChunker accepted only text — not file input
   The previous commit documented "accepts TEXT input" and
   ran the chunk engine on whatever string the caller
   passed. The Python PR's contract is chunk(filename) —
   it does file-format extraction (PDF/DOCX/table/...) AND
   chunking in one step. The Go port silently downgraded
   the contract.

   Fix: PipelineChunker now reads file_bytes / file_ref /
   text / content from the inputs map, and the dispatch
   keys on parser_id (not just validation):

   - text / content  → run through chunk engine
   - file_bytes      → run through chunk engine (caller
                       has done the extraction)
   - file_ref (with bytes) → run through chunk engine
   - non-UTF-8 bytes → reject with a clear error (PDF
                       extraction is a follow-up)
   - parser_id       → selects a real chunk strategy
                       (naive→paragraph, paper/laws→sentence,
                       qa→paragraph, etc.) so the output
                       actually differs by parser_id

   File-format extraction (PDF/DOCX/table/...) remains a
   documented follow-up — the Go file→text layer is not
   unified the way Python's rag.app.*.chunk functions are.
   The component now rejects non-UTF-8 bytes explicitly so
   a downstream caller that mistakenly passes a PDF
   without extraction sees a clear error rather than a
   silent garbled chunk.

   7 new PipelineChunker tests cover: text input, content
   alias, parser_id dispatch (paper > naive chunk count
   on the same input), file_bytes UTF-8, file_ref
   resolution, non-UTF-8 rejection, empty input.

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

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 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#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
…hunker file support

Two regressions caught in code review of a00ef0d:

1. Invoke proxy path did not actually pin DNS
   The previous code said (in a comment) "we layer our own pin
   around the proxy dial target" but the implementation was
   just http.Transport{Proxy: http.ProxyURL(...)} — no
   custom DialContext, so the proxy host got re-resolved at
   connect time, re-opening the TOCTOU window the SSRF
   guard was supposed to close.

   Fix: wrap the proxy transport in a custom DialContext
   that intercepts the proxy-host dial and replaces the
   target with the validated public IP (the same pattern
   utility.PinnedHTTPClient uses for the direct path). The
   connection now goes to the IP we validated, even if a
   subsequent DNS lookup returns a different answer.

   New TestInvoke_ProxyDNSPin exercises the pin path.

2. PipelineChunker accepted only text — not file input
   The previous commit documented "accepts TEXT input" and
   ran the chunk engine on whatever string the caller
   passed. The Python PR's contract is chunk(filename) —
   it does file-format extraction (PDF/DOCX/table/...) AND
   chunking in one step. The Go port silently downgraded
   the contract.

   Fix: PipelineChunker now reads file_bytes / file_ref /
   text / content from the inputs map, and the dispatch
   keys on parser_id (not just validation):

   - text / content  → run through chunk engine
   - file_bytes      → run through chunk engine (caller
                       has done the extraction)
   - file_ref (with bytes) → run through chunk engine
   - non-UTF-8 bytes → reject with a clear error (PDF
                       extraction is a follow-up)
   - parser_id       → selects a real chunk strategy
                       (naive→paragraph, paper/laws→sentence,
                       qa→paragraph, etc.) so the output
                       actually differs by parser_id

   File-format extraction (PDF/DOCX/table/...) remains a
   documented follow-up — the Go file→text layer is not
   unified the way Python's rag.app.*.chunk functions are.
   The component now rejects non-UTF-8 bytes explicitly so
   a downstream caller that mistakenly passes a PDF
   without extraction sees a clear error rather than a
   silent garbled chunk.

   7 new PipelineChunker tests cover: text input, content
   alias, parser_id dispatch (paper > naive chunk count
   on the same input), file_bytes UTF-8, file_ref
   resolution, non-UTF-8 rejection, empty input.

Refs: a00ef0d (Wave 4 partial — infiniflow#15068)
Refs: infiniflow#15068 infiniflow#15426
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.
@dosubot dosubot Bot mentioned this pull request Jul 22, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Agent Invoke component lacks SSRF guard on outbound requests

2 participants