Repository navigation
Harden closed-advisory fixes - #16409
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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. ChangesOutbound HTTP request safety
Document download access checks
Markdown sanitization
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
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 winAdd 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 butDocumentService.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
📒 Files selected for processing (9)
agent/component/invoke.pyapi/apps/restful_apis/document_api.pycommon/data_source/rest_api_connector.pycommon/data_source/utils.pytest/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.pytest/testcases/test_web_api/test_document_app/test_document_metadata.pytest/unit_test/data_source/test_rest_api_connector.pyweb/src/components/highlight-markdown/__tests__/index.test.tsxweb/src/components/highlight-markdown/index.tsx
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
("<img onerror=...>") 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.
…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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
## 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
…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).
…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]>
Summary
What changed
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.pytest/testcases/test_web_api/...unit additions were reviewed, but the suite cannot be executed end-to-end in this environment because parenttest/testcases/conftest.pyrequires a local service on127.0.0.1:9380Notes