Skip to content

fix(web): sanitize the parsed markdown tree instead of the string (GHSA-jv5f-3mqh-cxwf) - #17590

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
kah-ja:fix-markdown-tree-sanitize
Aug 20, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
kah-ja:fix-markdown-tree-sanitize

Conversation

@kah-ja

@kah-ja kah-ja commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Summary

The chat and search renderers pass their content to <Markdown rehypePlugins={[rehypeRaw, ...]}>, so raw HTML in a message becomes real nodes. The sanitization in front of that pipeline cannot hold, because preprocessLaTeX() (web/src/utils/chat.ts) decodes &lt;, &gt; and &amp; back into markup after DOMPurify.sanitize() has run: markup delivered entity-encoded is inert text while the allow-list inspects it, and live markup again by the time rehype-raw parses it. FloatingChatWidgetMarkdown and HighLightMarkdown reach rehype-raw with no sanitization at all.

This is the issue reported privately as GHSA-jv5f-3mqh-cxwf (not published yet).

This PR sanitizes the parsed tree instead of the string: rehype-sanitize runs after rehype-raw and before rehype-katex, with one shared schema.

Why not simply move the string sanitizer to the end of the pipeline

I tried that first and withdrew it (#17589): a sanitizer applied to the markdown string cannot be both safe and faithful here. It HTML-escapes text, and the only thing that ever repaired that escaping was the entity decode -- which is the hole itself. Measured in a browser against this plugin stack:

  • $x^2 < y$ renders as a red KaTeX ParseError, because KaTeX receives &lt;.
  • `a < b` in an inline code span displays the literal &lt;.

Sanitizing the tree leaves text nodes untouched, so neither happens. This may also be why the sanitize pass added in #16409 was removed again in #16449 as "ineffective after preprocessLaTeX" -- the ordering was right, the layer was not.

What changed

  • web/src/constants/markdown-rehype-plugins.ts (new): markdownSanitizeSchema = hast-util-sanitize's defaultSchema plus the wrappers replaceThinkToSection / replaceRetrievingToSection inject (think, retrieving, section, details, summary) and className; exported as a ready [rehypeSanitize, schema] tuple.
  • The five renderers insert that tuple directly after rehypeRaw: markdown-content, next-markdown-content, next-search/markdown-content, floating-chat-widget-markdown, highlight-markdown.
  • rehype-sanitize@^6.0.0 and hast-util-sanitize@^5.0.2 added; the lockfile diff is limited to those two entries.

The existing DOMPurify.sanitize() calls are left alone on purpose: they still normalise null/undefined content into the chat.searching placeholder, and they cost nothing as a second layer.

Validation

Measured in headless Chromium against the real stack (react-markdown 9, rehype-raw 7, rehype-katex 7, remark-gfm/math/breaks), comparing main at 611e059 with this branch:

  • Attack side: the entity-encoded <svg><script> case executes on main and produces no element at all here; <style> and <math> are likewise dropped. No on* attribute and no javascript: URL survives in any of the 12 vectors tried.
  • Rendering side: 0 of 22 markdown constructs change -- GFM tables, task lists, blockquotes, headings, nested lists, autolinks, inline code, code fences with Array<number>, <think> and <details class="think"> wrappers, <br>, images, links, citation markers, $…$ and \[…\] math including \right] all render byte-identically.
  • npx jest --runInBand: 5 failed / 71 passed, identical to main (the failures are pre-existing preprocessLaTeX and HighLightMarkdown specs).
  • npx oxlint clean, npx oxfmt reports the touched files correctly formatted.

I did not add a unit test for the schema: the jest transform does not load ESM-only packages, so importing hast-util-sanitize in a spec needs transformIgnorePatterns: ['/node_modules/(?!(hast-util-sanitize|rehype-sanitize|unist-util-position|@ungap)/)'] in jest.config.ts. That change makes the currently non-running HighLightMarkdown specs execute and fail, so I left it out of this PR. Happy to add both the config line and the spec if you want them here.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 30, 2026
@coderabbitai

coderabbitai Bot commented Jul 30, 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 Plus

Run ID: bd593e7d-96ef-4aee-a065-1da537a1c163

📥 Commits

Reviewing files that changed from the base of the PR and between 4304a3b and cd22c8e.

⛔ Files ignored due to path filters (1)
  • web/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • web/package.json
  • web/src/components/floating-chat-widget-markdown.tsx
  • web/src/components/highlight-markdown/index.tsx
  • web/src/components/markdown-content/index.tsx
  • web/src/components/next-markdown-content/index.tsx
  • web/src/constants/markdown-rehype-plugins.ts
  • web/src/pages/next-search/markdown-content/index.tsx
🚧 Files skipped from review as they are similar to previous changes (5)
  • web/src/components/highlight-markdown/index.tsx
  • web/src/components/floating-chat-widget-markdown.tsx
  • web/package.json
  • web/src/pages/next-search/markdown-content/index.tsx
  • web/src/components/markdown-content/index.tsx

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Adds a shared assistant-markdown sanitization schema and integrates it into five React Markdown rendering pipelines. It also adds the hast-util-sanitize and rehype-sanitize runtime dependencies.

Changes

Assistant Markdown Sanitization

Layer / File(s) Summary
Sanitization schema and plugin
web/package.json, web/src/constants/markdown-rehype-plugins.ts
Adds sanitization dependencies. Defines allowed assistant wrapper tags, className attributes, and data: image URLs. Exports the shared rehype sanitization plugin.
Renderer pipeline integration
web/src/components/..., web/src/pages/next-search/...
Adds the sanitization plugin after rehypeRaw and before reference wrapping or KaTeX processing in five markdown renderers.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to cd22c

The PR sanitizes the parsed markdown tree before rendering across the affected renderers, addressing unsafe raw HTML while preserving documented markdown behavior. No actionable merge-blocking risk remains beyond normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant MarkdownRenderer
  participant rehypeRaw
  participant RehypeSanitizeAssistantMarkdown
  participant MarkdownTransformations
  MarkdownRenderer->>rehypeRaw: parse raw HTML
  rehypeRaw->>RehypeSanitizeAssistantMarkdown: pass HTML tree
  RehypeSanitizeAssistantMarkdown->>MarkdownTransformations: pass sanitized tree
  MarkdownTransformations->>MarkdownRenderer: render transformed markdown
Loading

Suggested labels: 🧰 typescript

Suggested reviewers: cike8899, dcc123456

Poem

I’m a rabbit with a sanitizing tune,
Safe tags hop beneath the moon.
Raw HTML enters, clean trees depart,
KaTeX follows with careful art.
Hop, hop—markdown plays its part.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main security fix: sanitizing the parsed Markdown tree instead of the source string.
Description check ✅ Passed The description includes the required Summary section and provides clear background, implementation details, scope, and validation results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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: 2

🤖 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 `@web/src/components/next-markdown-content/index.tsx`:
- Around line 368-373: Update the markdown sanitization configuration used with
rehypeSanitizeAssistantMarkdown so markdownSanitizeSchema extends defaultSchema
with an image-only data: protocol allowance for img[src], preserving the
existing base64-image path before react-markdown’s urlTransform runs. Keep
non-image text/script data URLs rejected, and add or retain coverage for both
behaviors.

In `@web/src/constants/markdown-rehype-plugins.ts`:
- Line 17: Rename the exported top-level constants markdownSanitizeSchema and
rehypeSanitizeAssistantMarkdown to PascalCase, then update all five renderer
imports and usages to reference the renamed symbols consistently.
🪄 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 Plus

Run ID: e22335fa-6a0d-4b57-b452-c0e9225f9a9c

📥 Commits

Reviewing files that changed from the base of the PR and between 611e059 and 85d5f8a.

⛔ Files ignored due to path filters (1)
  • web/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • web/package.json
  • web/src/components/floating-chat-widget-markdown.tsx
  • web/src/components/highlight-markdown/index.tsx
  • web/src/components/markdown-content/index.tsx
  • web/src/components/next-markdown-content/index.tsx
  • web/src/constants/markdown-rehype-plugins.ts
  • web/src/pages/next-search/markdown-content/index.tsx

@cike8899

Copy link
Copy Markdown
Contributor

@kah-ja Please resolve the conflict.

@cike8899 cike8899 added the ci Continue Integration label Aug 20, 2026
kah-ja added 2 commits August 20, 2026 13:25
…SA-jv5f-3mqh-cxwf)

The assistant markdown renderers run rehype-raw, so raw HTML inside a
message becomes real nodes. Sanitizing the markdown string beforehand
cannot hold: preprocessLaTeX() decodes &lt;/&gt;/&amp; back into markup
afterwards, so an entity-encoded payload passes the check inert and is
live again by the time rehype-raw parses it.

Sanitize the parsed tree instead, via rehype-sanitize placed after
rehype-raw and before rehype-katex, using one shared allow-list. This
closes the entity-encoded and raw <svg><script> vectors on all five
renderers (the floating chat widget had no sanitization at all) while
leaving text nodes untouched, so $a < b$ still reaches KaTeX and
Array<number> survives inside code fences. The allow-list keeps data:
URLs on img src so the base64 images next-markdown-content already
supports keep rendering.
@coderabbitai

coderabbitai Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@JinHai-CN
JinHai-CN merged commit c7f22d4 into infiniflow:main Aug 20, 2026
3 checks passed
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 size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants