Rendering Markdown to HTML is a solved problem. What is not solved is rendering it safely.

The pipeline

A safe Markdown renderer has three stages:

  1. Parse Markdown into an AST
  2. Render the AST to HTML
  3. Sanitize the HTML against an allowlist

Skip stage three and you have built an XSS vector.

p := parser.NewWithExtensions(parser.CommonExtensions)
renderer := html.NewRenderer(html.RendererOptions{
    Flags: html.CommonFlags | html.SkipHTML,
})
out := markdown.ToHTML(src, p, renderer)
clean := policy.Sanitize(out) // the important line

Allowlists, not blocklists

A blocklist asks “is this dangerous?” A blocklist always misses something.

An allowlist asks “is this allowed?” — and the answer for anything unrecognised is no.

The rules are simple:

  • Permit formatting tags: p, h1 through h6, ul, ol, li, code, pre, blockquote, table
  • Permit attributes you actually use: href, src, alt, id
  • Permit URL schemes you actually need: http, https, mailto

Everything else gets stripped.

Escape by default

Raw HTML embedded in Markdown is the most common source of injection. Skip it during rendering and let the sanitizer be the last line of defence.

Two independent layers means one mistake is not enough to cause a breach.