Writing a Markdown Pipeline in Go
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:
- Parse Markdown into an AST
- Render the AST to HTML
- 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,h1throughh6,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.
Comments 0
No comments yet. Be the first to share your thoughts.