github-mcp-server icon indicating copy to clipboard operation
github-mcp-server copied to clipboard

fix(sanitize): preserve angle brackets inside code blocks and inline code

Open blackwell-systems opened this issue 7 months ago • 1 comments

Description

bluemonday.StrictPolicy() treats angle brackets inside markdown code blocks and inline code spans as HTML tags and strips them. This causes content like mut_raw_ptr<int> in issue/PR bodies to become mut_raw_ptr when read through MCP endpoints.

Before

let ptr: mut_raw_ptr<int> = raw_new int;

Agent sees: let ptr: mut_raw_ptr = raw_new int;

After

Agent sees: let ptr: mut_raw_ptr<int> = raw_new int;

Root cause

FilterHTMLTags calls bluemonday.Sanitize() on the entire markdown body without distinguishing code from prose. Bluemonday treats <int>, <T>, <String>, etc. as unrecognized HTML tags and removes them.

Fix

Before HTML sanitization, replace < and > inside fenced code blocks (```) and inline code spans (`) with null-byte sentinels that bluemonday will not interpret as HTML. After sanitization, restore the sentinels to angle brackets.

This preserves XSS protection for angle brackets in prose (e.g. <script> is still stripped) while keeping angle brackets inside code intact.

Testing

Added 6 test cases covering:

  • Fenced code blocks with angle brackets (the reported bug)
  • Inline code with generic types (Vec<String>)
  • Angle brackets outside code still sanitized (XSS protection preserved)
  • Multiple inline code spans
  • Fenced code with language info string

Fixes #2202

blackwell-systems avatar Apr 30 '26 02:04 blackwell-systems

@SamMorrowDrums Thanks for the goldmark suggestion and prototype! You're right that it's cleaner and more maintainable.

I've refactored to use goldmark's CommonMark parser. Changes:

  1. Replaced hand-rolled scanner with goldmark AST walker (~150 lines → ~40 lines)
  2. Added indented code block coverage (4-space blocks now protected)
  3. Added package documentation with threat model
  4. Documented ordering invariant (FilterInvisibleCharacters before protectCodeAngleBrackets)
  5. Updated sentinel documentation explaining collision prevention

All existing tests pass plus a new test for indented code blocks. Ran script/lint locally (0 issues) and go test -race ./....

Happy to address the inline suggestions if there's anything else needed. Thanks again for the detailed review.

blackwell-systems avatar Jun 01 '26 00:06 blackwell-systems