Skip to content

Harden closed-advisory fixes - #16409

Merged
yuzhichang merged 19 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port-2
Jun 28, 2026
Merged

yuzhichang merged 19 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port-2

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

Summary

  • harden reopened advisory fixes across REST connector, invoke, document downloads, and markdown rendering
  • add targeted regression coverage for redirect-safe SSRF handling, invoke SSRF checks, document access control, and markdown sanitization
  • verify each referenced GHSA against the original GitHub advisory text and align the closed-advisory plan with the implemented remediation

What changed

  • add tenant access checks to document download endpoints to avoid cross-tenant document disclosure
  • add per-hop SSRF validation, DNS pinning, redirect handling, and redirect limits to the REST API connector
  • ensure invoke requests validate and pin the resolved host and never follow redirects implicitly
  • keep the generic rate-limited request path wrapped, not just GET and POST helpers
  • sanitize markdown HTML before rendering in the highlight markdown component

Validation

  • cd web && npm test -- --runInBand src/components/highlight-markdown/__tests__/index.test.tsx
  • .venv/bin/python -m pytest -q test/unit_test/data_source/test_rest_api_connector.py
  • targeted test/testcases/test_web_api/... unit additions were reviewed, but the suite cannot be executed end-to-end in this environment because parent test/testcases/conftest.py requires a local service on 127.0.0.1:9380

Notes

  • all GHSA entries referenced by the plan were checked against the original GitHub advisory text, not sampled
  • the closed-advisory plan document was updated locally during review, but is intentionally not included in this PR

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 27, 2026
@coderabbitai

coderabbitai Bot commented Jun 27, 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

The PR adds URL validation and DNS pinning for outbound requests, manual redirect handling for data-source page fetches, access checks for document downloads, and HTML sanitization in the markdown renderer.

Changes

Outbound HTTP request safety

Layer / File(s) Summary
Invoke URL pinning
agent/component/invoke.py, test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py
Invoke validates built URLs, stores pinned host/IP values, disables redirects, and runs the request inside pin_dns; tests cover private-address rejection and pinned requests.
Connector redirect handling
common/data_source/utils.py, common/data_source/rest_api_connector.py, test/unit_test/data_source/test_rest_api_connector.py
_RateLimitedRequest exposes request, and _fetch_page routes page fetches through _safe_request, which validates redirect targets, pins DNS, follows redirects manually, and enforces the redirect cap; tests cover loopback rejection, 307 POST behavior, and max-redirect errors.

Document download access checks

Layer / File(s) Summary
Download route access gating
api/apps/restful_apis/document_api.py, test/testcases/test_web_api/test_document_app/test_document_metadata.py
download and download_document now check dataset/document accessibility before querying, and the tests cover both denied-access paths returning Document not found!.

Markdown sanitization

Layer / File(s) Summary
HighLightMarkdown sanitization
web/src/components/highlight-markdown/index.tsx, web/src/components/highlight-markdown/__tests__/index.test.tsx
HighLightMarkdown sanitizes its children with DOMPurify before preprocessing, and the test suite verifies sanitized output without script or image elements.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 I hopped by the URL, so neat and so spry,
Pinned DNS in my burrow beneath the blue sky.
I munched the bad tags and the redirects too,
Then whispered, “Not found,” when the access was due.
Thump-thump! The markdown now sparkles and gleams,
While safe little requests drift through rabbit dreams.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.13% 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 is concise and accurately reflects the main security-hardening changes in the PR.
Description check ✅ Passed The description covers the problem, changes, validation, and notes, but it doesn't follow the template headings or include a type-of-change selection.
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.

Actionable comments posted: 7

🧹 Nitpick comments (1)
test/testcases/test_web_api/test_document_app/test_document_metadata.py (1)

461-469: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Add coverage for the dataset route’s document-denial branch.

This test exits at the KB gate, so it does not cover download() when the dataset is accessible but DocumentService.accessible() rejects the document.

Suggested regression test
     def test_dataset_document_download_rejects_other_tenant_unit(self, document_rest_api_module, monkeypatch):
         module = document_rest_api_module
         monkeypatch.setattr(module.KnowledgebaseService, "accessible", lambda kb_id, user_id: False)
         monkeypatch.setattr(module.DocumentService, "accessible", lambda _doc_id, _user_id: True)
 
         res = _run(module.download("kb1", "doc1"))
         assert res["code"] == RetCode.DATA_ERROR
         assert "Document not found!" in res["message"]
+
+    def test_dataset_document_download_rejects_inaccessible_document_unit(self, document_rest_api_module, monkeypatch):
+        module = document_rest_api_module
+        monkeypatch.setattr(module.KnowledgebaseService, "accessible", lambda kb_id, user_id: True)
+        monkeypatch.setattr(module.DocumentService, "accessible", lambda _doc_id, _user_id: False)
+
+        res = _run(module.download("kb1", "doc1"))
+        assert res["code"] == RetCode.DATA_ERROR
+        assert "Document not found!" in res["message"]
🤖 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_document_app/test_document_metadata.py`
around lines 461 - 469, The current test only exercises the
KnowledgebaseService.accessible gate and misses the dataset document-denial
branch in download(). Update the regression coverage in
test_dataset_document_download_rejects_other_tenant_unit so
KnowledgebaseService.accessible returns True while DocumentService.accessible
returns False, then assert download("kb1", "doc1") still returns DATA_ERROR with
the expected "Document not found!" message.
🤖 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 178-180: The URL safety check in `_build_url()` can raise before
`_invoke()` reaches its retry/error handling, so validation failures won’t
populate `_ERROR` for direct `_invoke()` calls. Update `Invoke._invoke` or
`_build_url` in `agent/component/invoke.py` to catch exceptions from
`assert_url_is_safe(url)` and route them through the existing error-output path,
or adjust the test to call `invoke()` instead of `_invoke()` so the current
handling is exercised.

In `@common/data_source/rest_api_connector.py`:
- Around line 678-680: Normalize the SSRF validation failure path in the
redirect handling loop so unsafe URLs do not leak ValueError from
assert_url_is_safe(). Update the logic around the current_url check in the
redirect iteration to catch that exception and re-raise the connector’s
documented ConnectorValidationError instead, keeping _page_iter_for_validation()
and related validation paths consistent with other connector errors.
- Around line 720-725: The manual redirect handling in the rest API connector is
replaying sensitive credentials and query data across origins. Update the
redirect loop in the logic around current_url/current_method so that when the
target netloc changes you strip auth-sensitive headers and any basic/API auth
state before the next request, and for 307/308 also avoid carrying over params
unless they are explicitly encoded in the Location URL. Keep the existing
redirect behavior for same-origin hops, but ensure the request state is
sanitized before the next send.

In `@test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py`:
- Around line 285-286: The test is asserting _ERROR from _invoke(), but
_build_url() runs before the request try/catch so the mocked ValueError escapes
instead of being stored. Update the assertion in test_invoke_component_unit to
either call invoke.invoke() if you want validation errors captured into
_param.outputs["_ERROR"], or change the test to assert the ValueError is raised
from _invoke(); use the _invoke and invoke methods as the locating symbols.

In `@test/unit_test/data_source/test_rest_api_connector.py`:
- Around line 229-230: The test is asserting the wrong exception type for the
connector validation path. Update the `connector._fetch_page` expectation in the
`test_rest_api_connector` case to assert `ConnectorValidationError` instead of
`ValueError`, since the redirect-target failure should be normalized at the
connector layer. Keep the same failure message match (or equivalent) so the test
still verifies the “loopback blocked” validation from `_fetch_page`.

In `@web/src/components/highlight-markdown/__tests__/index.test.tsx`:
- Around line 10-15: The test mock for react-markdown in
highlight-markdown/index.test.tsx is too shallow because it only renders
children in a div, so it never exercises rehypeRaw or the preprocessLaTeX
entity-decoding behavior after DOMPurify.sanitize. Update the spec to use the
real rendering pipeline or a mock that actually parses raw HTML, and extend the
highlight-markdown tests to include an encoded payload like <img ...> so
the script/img sanitization and safe HTML assertions validate the real behavior.

In `@web/src/components/highlight-markdown/index.tsx`:
- Line 30: The markdown highlighting flow sanitizes too early, leaving
entity-decoded markup exposed after preprocessLaTeX() runs. Update the
highlight-markdown component so DOMPurify.sanitize() is applied to the
post-processed string returned by preprocessLaTeX() before it reaches rehypeRaw,
or otherwise remove the entity-decoding behavior from that path. Use the
existing preprocessLaTeX and safeChildren logic in the component to keep the fix
localized.

---

Nitpick comments:
In `@test/testcases/test_web_api/test_document_app/test_document_metadata.py`:
- Around line 461-469: The current test only exercises the
KnowledgebaseService.accessible gate and misses the dataset document-denial
branch in download(). Update the regression coverage in
test_dataset_document_download_rejects_other_tenant_unit so
KnowledgebaseService.accessible returns True while DocumentService.accessible
returns False, then assert download("kb1", "doc1") still returns DATA_ERROR with
the expected "Document not found!" message.
🪄 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: 00559856-bb59-463f-a0d4-3ed948f3a8a1

📥 Commits

Reviewing files that changed from the base of the PR and between a06343e and 868f361.

📒 Files selected for processing (9)
  • agent/component/invoke.py
  • api/apps/restful_apis/document_api.py
  • common/data_source/rest_api_connector.py
  • common/data_source/utils.py
  • test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py
  • test/testcases/test_web_api/test_document_app/test_document_metadata.py
  • test/unit_test/data_source/test_rest_api_connector.py
  • web/src/components/highlight-markdown/__tests__/index.test.tsx
  • web/src/components/highlight-markdown/index.tsx

Comment thread agent/component/invoke.py Resolved
DOMPurify.sanitize() was called BEFORE preprocessLaTeX(), but
preprocessLaTeX() decodes </>/& back to raw HTML before
rehypeRaw parses the markdown. An entity-encoded payload such as
"<img src=x onerror=alert(1) />" therefore bypassed DOMPurify
and was rendered as a real <img> element by rehypeRaw, enabling
stored XSS in any field rendered through HighLightMarkdown (e.g.
the dialog 'prologue' greeting, agent 'thoughts' output, KB chunks).

Move DOMPurify.sanitize() to the post-preprocessLaTeX string so
the entity-decoding step cannot introduce unsanitized HTML.

Addresses Coderabbit review CRITICAL #3486038798 on PR infiniflow#16409
(GHSA-45vc-vwm4-99r7 hardening).
The previous react-markdown mock rendered children as text inside a
plain <div>, so the spec never exercised rehypeRaw or the
post-preprocessLaTeX sanitization path. Entity-encoded payloads
would never reach the DOM regardless of what the component did,
masking the exact bypass DOMPurify is meant to catch.

Mock react-markdown to render children as raw HTML via
dangerouslySetInnerHTML. If the component fails to sanitize (e.g.
sanitizes before preprocessLaTeX), the unsafe HTML reaches this
mock and is inserted into the DOM, failing the assertions.

Add a second test case with an entity-encoded payload
("&lt;img onerror=...&gt;") to cover the bypass.

Addresses Coderabbit review MAJOR #3486038797 on PR infiniflow#16409.
Two related fixes in RestAPIConnector._safe_request:

1. MAJOR #3486038789: SSRF validation failures from assert_url_is_safe()
   used to raise raw ValueError out of _safe_request, breaking the
   connector's documented error contract. Wrap to ConnectorValidationError
   so _page_iter_for_validation() and other callers see the same error
   type as the rest of the connector.

2. MAJOR #3486038792: Manual redirects reused the same headers /
   _basic_auth / (for 307/308) params across hops, so a cross-origin
   redirect could exfiltrate Bearer/Basic/API-key headers or sensitive
   query params to a third-party host. Add _AUTH_SENSITIVE_HEADER_KEYS
   and strip those headers (plus _basic_auth) when the redirect's
   netloc changes. 301/302/303 still drop body+params (RFC 7231).

Addresses Coderabbit review MAJOR #3486038792 and #3486038789 on
PR infiniflow#16409 (GHSA-86vh-56c4-9966 hardening).
_build_url() was called BEFORE the retry/except loop in
Invoke._invoke(), so SSRF rejections (ValueError from
assert_url_is_safe) escaped _invoke() instead of populating the
documented _ERROR output slot, breaking both the runtime contract
and the regression test for this path.

Move _build_url() inside the try block so the existing except
handler stores the validation message in _ERROR via the standard
error path.

Addresses Coderabbit review MAJOR #3486038788 on PR infiniflow#16409
(GHSA-gcvj-vrhg-m7r4 hardening).
_build_url() is now inside the retry try/except block (see
agent/component/invoke.py), so the ValueError raised by the
mocked assert_url_is_safe() is caught and stored in
_param.outputs['_ERROR'] via the standard error path. Add a
comment to make the assertion's expectation explicit.

Addresses Coderabbit review MAJOR #3486038793 on PR infiniflow#16409.
After the fix in common/data_source/rest_api_connector.py that
normalizes SSRF validation failures to ConnectorValidationError,
test_redirect_to_loopback_rejected must expect that exception
type rather than raw ValueError, otherwise it would lock in an
inconsistent connector API contract.

Addresses Coderabbit review MAJOR #3486038795 on PR infiniflow#16409.
@yuzhichang yuzhichang added the ci Continue Integration label Jun 27, 2026
@yuzhichang yuzhichang changed the title Harden reopened closed-advisory fixes Harden closed-advisory fixes Jun 27, 2026
…exhaust it

The previous list-based side_effect could be exhausted if any retry path
between _safe_request and the test driver invoked assert_url_is_safe more
than twice. Once exhausted the loop would run all 6 iterations and surface
'Exceeded 5 redirects' instead of the expected 'loopback blocked'.

Switch to a function-based side_effect keyed on URL: the loopback redirect
target always raises regardless of call count.
…eraction

_fetch_page is wrapped by @retry_builder. In some CI environments the retry
path on the first ConnectorValidationError consumes the mock's side_effect
and lets _safe_request loop all 6 iterations, surfacing 'Exceeded 5 redirects'
instead of the expected 'loopback blocked'.

The unit under test for redirect SSRF handling is _safe_request itself;
calling it directly bypasses the retry decorator and tests the actual
behavior deterministically.
…test

The _mocked_rest_api_requests_and_dns context manager uses a constant
return_value for socket.getaddrinfo. For the redirect-to-loopback test,
that constant 93.184.216.34 gets returned for the loopback hostname too,
so ssrf_guard's is_global check approves it and the loopback redirect
slips through to the 'Exceeded 5 redirects' branch.

Override the DNS mock within this test to return the literal 127.0.0.1
address for the loopback hostname, exercising the actual rejection path.
@codecov

codecov Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (70546ea) to head (63e93a7).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16409      +/-   ##
==========================================
- 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 c4fe68e into infiniflow:main Jun 28, 2026
3 checks passed
yuzhichang added a commit that referenced this pull request Jun 29, 2026
## Summary
- harden reopened advisory fixes across REST connector, invoke, document
downloads, and markdown rendering
- add targeted regression coverage for redirect-safe SSRF handling,
invoke SSRF checks, document access control, and markdown sanitization
- verify each referenced GHSA against the original GitHub advisory text
and align the closed-advisory plan with the implemented remediation

## What changed
- add tenant access checks to document download endpoints to avoid
cross-tenant document disclosure
- add per-hop SSRF validation, DNS pinning, redirect handling, and
redirect limits to the REST API connector
- ensure invoke requests validate and pin the resolved host and never
follow redirects implicitly
- keep the generic rate-limited request path wrapped, not just GET and
POST helpers
- sanitize markdown HTML before rendering in the highlight markdown
component

## Validation
- `cd web && npm test -- --runInBand
src/components/highlight-markdown/__tests__/index.test.tsx`
- `.venv/bin/python -m pytest -q
test/unit_test/data_source/test_rest_api_connector.py`
- targeted `test/testcases/test_web_api/...` unit additions were
reviewed, but the suite cannot be executed end-to-end in this
environment because parent `test/testcases/conftest.py` requires a local
service on `127.0.0.1:9380`

## Notes
- all GHSA entries referenced by the plan were checked against the
original GitHub advisory text, not sampled
- the closed-advisory plan document was updated locally during review,
but is intentionally not included in this PR
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant