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:

  1. 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, check nh3's configuration to ensure it’s removing or escaping any tags, attributes, or protocols (like javascript: in URLs) that could introduce XSS vulnerabilities.

  2. Double-check Fenced Code Blocks and Highlighting: Since you’re enabling fenced_code and codehilite, which add classes and styling to <code> and <pre> elements, ensure that nh3 is not stripping out necessary attributes required for code highlighting. You may need to allow certain class attributes if you are using CSS for syntax highlighting.

  3. Regularly Review nh3 Updates: Libraries like nh3 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.

  4. 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 like onclick). This will help you verify that nh3 is adequately sanitizing the content.

Back to Top