Skip to content
This repository has been archived by the owner on Sep 11, 2019. It is now read-only.

Commit

Permalink
Use bleach for HTML sanitization.
Browse files Browse the repository at this point in the history
  • Loading branch information
toolness committed Jun 20, 2018
1 parent dce5255 commit 642b995
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
22 changes: 22 additions & 0 deletions calc/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from typing import Any, List, Iterable
from django.contrib.auth.models import Permission
from django.utils.text import SafeText
from markdown import markdown
import bleach


def get_permissions_from_ns_codenames(ns_codenames):
Expand Down Expand Up @@ -60,3 +63,22 @@ def humanlist(items: Iterable[str], word: str='and') -> str:
if len(itemlist) < 2:
return ''.join(items)
return ', '.join(itemlist[:-1]) + f', {word} ' + itemlist[-1]


def markdown_to_sanitized_html(text: str) -> SafeText:
'''
Render the given untrusted Markdown to sanitized HTML.
Examples:
>>> markdown_to_sanitized_html('hello **there** *u*')
'<p>hello <strong>there</strong> <em>u</em></p>'
>>> markdown_to_sanitized_html('<script>meh</script>')
'&lt;script&gt;meh&lt;/script&gt;'
'''

return SafeText(bleach.clean(
markdown(text),
tags=['p', 'strong', 'em']
))
8 changes: 3 additions & 5 deletions contracts/models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import re

from datetime import datetime
from decimal import Decimal

from django.db import models, connection
from django.contrib.auth.models import User
from django.db.models.expressions import Value
from django.contrib.postgres.search import SearchVectorField, SearchVector
from django.utils.safestring import mark_safe
import markdown

from calc.utils import markdown_to_sanitized_html


EDUCATION_CHOICES = (
Expand Down Expand Up @@ -565,7 +563,7 @@ def full_name(self):

@property
def description_html(self):
return mark_safe(markdown.markdown(self.description)) # nosec
return markdown_to_sanitized_html(self.description)

def __str__(self):
return self.full_name
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ cg-django-uaa==1.3.0
semantic_version==2.6.0
coreapi==2.3.3
django-uswds-forms==1.0.0
bleach==2.1.3

0 comments on commit 642b995

Please sign in to comment.