Nh3 and mark_safe usage in django markdown
I am using the nh3 library with my Django project to sanitize my HTML of my rendered markdown. I also have fenced code blocks and code block highlighting implemented. If I do not use mark_safe on my nh3 cleaned markdown, all my rich text markdown becomes html code. If I use mark_safe in my Post model after cleaning the markdown, it no longer appears as html code. This is what I have in my Post model's get_message_as_markdown function responsible for generating markdown:
from markdown import markdown
import nh3
def get_message_as_markdown(self):
clean_content = nh3.clean(self.message)
rendered_content = markdown(clean_content, extensions=['fenced_code', 'codehilite'])
return mark_safe(rendered_content)
Is this "safe" to do? Thanks in advance!
Using mark_safe
with sanitized HTML can be safe, provided that you are confident the sanitization is effective in stripping out harmful HTML and JavaScript. Since nh3
is specifically designed to sanitize HTML, your approach has a good foundation. Here are some specific considerations to ensure security in your setup:
Sanitization Scope:
nh3
effectively removes unsafe tags and attributes, but it’s important to make sure your settings are configured to prevent any injection risks. If you haven’t already, checknh3
's configuration to ensure it’s removing or escaping any tags, attributes, or protocols (likejavascript:
in URLs) that could introduce XSS vulnerabilities.Double-check Fenced Code Blocks and Highlighting: Since you’re enabling
fenced_code
andcodehilite
, which add classes and styling to<code>
and<pre>
elements, ensure thatnh3
is not stripping out necessary attributes required for code highlighting. You may need to allow certainclass
attributes if you are using CSS for syntax highlighting.Regularly Review
nh3
Updates: Libraries likenh3
are periodically updated for security improvements. Keep it up to date to ensure it has the latest security patches, especially if there are updates that address new sanitization issues or vulnerabilities.Testing: Before deploying, it’s a good idea to test this setup thoroughly, especially by trying to insert various types of potentially harmful content (e.g.,
<script>
tags, iframes, inline event handlers likeonclick
). This will help you verify thatnh3
is adequately sanitizing the content.