Django Markdown Rendering XSS Fix – nh3 Sanitization
Goal
Make the render_markdown template filter in the creolecorner Django app safe to apply to user-supplied text, while keeping fenced code blocks and Pygments syntax highlighting working.
Setup
render_markdown (apps/common/templatetags/markdown_filters.py) converted Markdown and returned it through mark_safe() with no sanitization:
@register.filter
@stringfilter
def render_markdown(value):
md = markdown.Markdown(extensions=["fenced_code", "codehilite"])
return mark_safe(md.convert(value))
Any <script>, onerror= handler or javascript: link in the input reached the page as executable code (see Rendering Untrusted Markdown with mark_safe Causes XSS). The realistic target was a Contact message rendered for staff in the CRM, which would let a script read customer PII and tokens with a staff session.
Steps and findings
1. Added nh3
Added nh3 to pyproject.toml (and uv.lock). It wraps the Rust sanitizer ammonia, which parses HTML with html5ever and keeps only allowlisted tags, attributes and URL schemes. bleach was not an option: it has been deprecated since January 2023.
2. Sanitized before mark_safe()
ALLOWED_ATTRIBUTES = deepcopy(nh3.ALLOWED_ATTRIBUTES)
for _tag in ("div", "pre", "code", "span"):
ALLOWED_ATTRIBUTES.setdefault(_tag, set()).add("class")
# Only keep class names emitted by codehilite/Pygments (e.g. "codehilite", "k", "nf", "s2"),
# so user-supplied raw HTML can't reuse site CSS (e.g. Tailwind) to build overlays.
_ALLOWED_CLASS = re.compile(r"^(codehilite|[a-z]{1,3}\d?)$")
def _attribute_filter(tag, attr, value):
if attr == "class":
kept = " ".join(c for c in value.split() if _ALLOWED_CLASS.match(c))
return kept or None
return value
@register.filter
@stringfilter
def render_markdown(value):
md = markdown.Markdown(extensions=["fenced_code", "codehilite"])
html = md.convert(value)
sanitized_html = nh3.clean(
html, attributes=ALLOWED_ATTRIBUTES, attribute_filter=_attribute_filter
)
return mark_safe(sanitized_html)
md.convert()produces HTML, including Pygments markup for fenced code.nh3.clean()keeps safe formatting tags, removes<script>/<style>with their content, drops other unknown tags but keeps their text, removeson*andstyleattributes, removeshref/srcattributes with schemes likejavascript:ordata:, and addsrel="noopener noreferrer"to links. Details: Sanitizing Markdown Output with an HTML Allowlist.classis allowed ondiv,pre,codeandspanfor highlighting, but_attribute_filterkeeps only names matchingcodehiliteor short Pygments token names, so<div class="fixed inset-0 z-50 bg-white">loses its classes (see Scriptless UI Redressing via Allowed class Attributes).- Only then is the result passed to
mark_safe().
Controls verified
RenderMarkdownFilterTests in apps/common/tests.py:
test_renders_safe_markdown_and_code_blocks: headings, bold,https://links and a fenced Python block render as aSafeStringwithcodehiliteclasses.test_strips_script_tags_and_event_handlers:<script>alert("xss")</script>,<img src="x" onerror="alert(1)">and[Click me](javascript:alert(1))lose the script, theonerrorattribute and thejavascript:href.test_strips_non_highlighting_classes:<div class="fixed inset-0 z-50 bg-white">keeps its text but loses every class.test_keeps_pygments_token_classes: a fenced Python block still carriesclass="codehilite"and token classes likeclass="k".
Remaining limitations
<img>with anyhttps:source is still allowed, so a message can embed a tracking pixel that reveals when, and from which IP, staff open it.- A relative
srcmakes the staff browser send a same-origin GET with its cookies; harmless as long as no endpoint changes state on GET. - Without Pygments installed,
codehiliteemitsclass="language-…", which the filter strips (no security impact).
Dropping img from the allowed tags, or proxying images, closes the first two.
References
- nh3 documentation -
clean(), default allowlists,attribute_filterandallowed_classes(last checked 2026-10-24). - mozilla/bleach #698: Bleach is deprecated - Deprecation announcement of 2023-01-23 (last checked 2026-10-24).
- Python-Markdown Change Log - 3.0 entry recommending an HTML sanitizer for untrusted content.
- Python-Markdown: CodeHilite - HTML and classes emitted for fenced code.
- Django Documentation:
mark_safe- Why the filter's return value bypasses escaping. - Rendering Untrusted Markdown with mark_safe Causes XSS - The vulnerability.
- Sanitizing Markdown Output with an HTML Allowlist - The general fix.
- Scriptless UI Redressing via Allowed class Attributes - Why
classneeded its own allowlist. - Web Application and Django Security MOC - Hub for Django and web application security notes.