Skip to content

fix(web): sanitize markdown after preprocessLaTeX (GHSA-jv5f-3mqh-cxwf) - #17589

Closed
kah-ja wants to merge 7 commits into
infiniflow:mainfrom
kah-ja:fix-markdown-sanitize-order
Closed

kah-ja wants to merge 7 commits into
infiniflow:mainfrom
kah-ja:fix-markdown-sanitize-order

Conversation

@kah-ja

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

Copy link
Copy Markdown
Contributor

Summary

preprocessLaTeX() in web/src/utils/chat.ts decodes &lt;, &gt; and &amp; back into raw markup, and every chat/search renderer hands its result to <Markdown rehypePlugins={[rehypeRaw, ...]}>. Those renderers ran DOMPurify.sanitize() before that decode, so markup that arrives entity-encoded is inert text when the allow-list inspects it and live markup again by the time rehypeRaw parses it — the sanitizer can be walked past. FloatingChatWidgetMarkdown passed message content to rehypeRaw with no sanitization at all.

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

This PR moves sanitization to the end of the render pipeline, so the allow-list applies to exactly the string that gets parsed.

What changed

  • web/src/utils/chat.ts — new sanitizeMarkdown() holding the allow-list in one place (think, section, details, summary, retrieving, plus class; unchanged from the options that were inlined in the renderers).
  • markdown-content, next-markdown-content, next-search/markdown-content — the leading DOMPurify.sanitize() call becomes the final step of the existing pipe(...).
  • floating-chat-widget-markdown — gains sanitization; it had none.
  • highlight-markdown — restores the sanitize pass added in Harden closed-advisory fixes #16409. It was removed again in fix: user-setting modal fixes and DOMPurify cleanup #16449 as "ineffective after preprocessLaTeX", but the ordering is the other way round: after preprocessLaTeX is the only point where it is effective, which is what the explanatory comment still sitting in that file already describes.
  • web/src/utils/tests/chat.test.ts — three tests pinning the ordering, the event-handler stripping, and the tags the chat renderers depend on.

Validation

cd web && npx jest --runInBand src/utils/tests/chat.test.ts — the three new tests pass.

Two pre-existing failures are untouched by this PR; both reproduce identically on main at 611e059:

  • chat.test.ts — handles double-escaped inline LaTeX and handles mixed double-escaped delimiters with HTML entities already fail on main.
  • highlight-markdown/__tests__/index.test.tsx — both cases currently error with ReferenceError: React is not defined under the esbuild-jest transform (classic JSX runtime, and the component has no React import), so the regression guard added in Harden closed-advisory fixes #16409 does not assert anything at the moment. I left that alone to keep this PR focused, happy to fix it here if you prefer.

Rendering was checked in a browser against the real plugin stack (react-markdown 9, rehype-raw 7, rehype-katex 7, dompurify 3.3.2): GFM tables, <think> / <retrieving> sections, inline and block KaTeX, and the \right] / \big) delimiter handling all render as before. One visible difference: a literal < inside an inline code span now renders escaped, because the sanitizer HTML-escapes text before the markdown parser sees it. If that trade-off is unwelcome, the alternative is sanitizing the tree rather than the string — rehype-sanitize placed after rehypeRaw with a schema extended for the tags listed above — which costs a new dependency, so I went with the smaller change 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

📝 Walkthrough

Walkthrough

A shared sanitizeMarkdown helper now sanitizes fully preprocessed markdown. Multiple chat markdown renderers apply it after transformations and LaTeX preprocessing, with tests covering unsafe decoded markup and preserved chat-specific tags.

Changes

Markdown sanitization

Layer / File(s) Summary
Sanitizer contract and coverage
web/src/utils/chat.ts, web/src/utils/tests/chat.test.ts
Adds a DOMPurify-based sanitizeMarkdown helper with chat-specific allowed tags and tests for scripts, event attributes, and preserved structure.
Markdown pipeline migration
web/src/components/markdown-content/index.tsx, web/src/components/next-markdown-content/index.tsx, web/src/pages/next-search/markdown-content/index.tsx
Moves sanitization from initial content preparation to the final stage after transformations and preprocessLaTeX, before rehypeRaw.
Renderer integrations
web/src/components/floating-chat-widget-markdown.tsx, web/src/components/highlight-markdown/index.tsx
Applies the shared sanitizer to floating-chat and highlighted markdown processing pipelines.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChatContent
  participant preprocessLaTeX
  participant sanitizeMarkdown
  participant rehypeRaw
  ChatContent->>preprocessLaTeX: process markdown content
  preprocessLaTeX->>sanitizeMarkdown: return decoded markdown
  sanitizeMarkdown->>rehypeRaw: provide sanitized markdown
  rehypeRaw->>ChatContent: render parsed content
Loading

Suggested labels: 🧰 typescript

Suggested reviewers: cike8899

Poem

A bunny checks each markdown line,
Keeps think and details neat and fine.
Scripts hop out, bad handlers flee,
Safe tags remain for all to see.
Carrots cheer the sanitized flow! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: sanitizing markdown after preprocessLaTeX.
Description check ✅ Passed The description includes the required Summary and provides enough context, change details, and validation for reviewers.
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: 1

🤖 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/utils/tests/chat.test.ts`:
- Around line 49-55: Add assertions in the sanitizeMarkdown test for the custom
think and retrieving allow-list entries. Verify the sanitized output preserves
the relevant think and retrieving tags, rather than only checking the details
class and summary elements.
🪄 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: c5e66670-48e4-44d2-916f-a7ea0246d70b

📥 Commits

Reviewing files that changed from the base of the PR and between 611e059 and 13d6021.

📒 Files selected for processing (7)
  • 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/pages/next-search/markdown-content/index.tsx
  • web/src/utils/chat.ts
  • web/src/utils/tests/chat.test.ts

Comment on lines +49 to +55
test('sanitizeMarkdown keeps the tags the chat renderers rely on', () => {
const sanitized = sanitizeMarkdown(
'<details class="think"><summary>Thinking...</summary>why</details>',
);
expect(sanitized).toContain('<details class="think">');
expect(sanitized).toContain('<summary>');
});

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Files matching chat.test.ts:\n'
fd -a 'chat\.test\.ts$' . || true

printf '\nRelevant test file:\n'
if [ -f web/src/utils/tests/chat.test.ts ]; then
  nl -ba web/src/utils/tests/chat.test.ts | sed -n '1,140p'
fi

printf '\nSearch for sanitizeMarkdown definitions/usages:\n'
rg -n "sanitizeMarkdown|<think|<retrieving|think>|retrieving>" web/src -S || true

Repository: infiniflow/ragflow

Length of output: 354


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='web/src/utils/tests/chat.test.ts'
if [ -f "$file" ]; then
  echo "Relevant test file:"
  awk '{printf "%6d\t%s\n", NR, $0}' "$file" | sed -n '1,160p'
fi

echo
echo "Search for sanitizeMarkdown definitions/usages:"
rg -n "sanitizeMarkdown|<think|<retrieving|think>|retrieving>" web/src -S || true

Repository: infiniflow/ragflow

Length of output: 5037


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Chat utility around sanitizeMarkdown:"
awk '{printf "%6d\t%s\n", NR, $0}' web/src/utils/chat.ts | sed -n '1,140p'

echo
echo "Behavioral probe from source definitions:"
python3 - <<'PY'
import re
from pathlib import Path
src = Path('web/src/utils/chat.ts').read_text()
m = re.search(r'export const sanitizeMarkdown = \(content: string\) =>\s*\{(?P<body>.*?)}(?:\n|$);', src, re.S)
if m:
    print(m.group(0))
    body = m.group('body')
    print("\nContains think tag extraction:", 'extractthinkContent' in body)
    print("Contains retrieving tag extraction:", '<retrieving>' in body)
else:
    print("sanitizeMarkdown definition not found")
PY

Repository: infiniflow/ragflow

Length of output: 5598


Exercise the custom allow-list entries.

sanitizeMarkdown also allows think and retrieving; add preservation assertions for those tags instead of relying only on <details class="think"> and <summary>.

🤖 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 `@web/src/utils/tests/chat.test.ts` around lines 49 - 55, Add assertions in the
sanitizeMarkdown test for the custom think and retrieving allow-list entries.
Verify the sanitized output preserves the relevant think and retrieving tags,
rather than only checking the details class and summary elements.

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. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant