Jordan Reiter
Jordan Reiter

Reputation: 21022

Django template filter: HTML Sanitization AND Embedding YouTube, Vimeo, etc?

I have some user-entered content (currently entered in Markdown) and I want to allow users to embed YouTube, vimeo, etc. videos. So somehow I need to allow specific object, param and embed tags while still blocking others.

Currently I'm sanitizing the HTML using a whitelist. I realize I could customize the whitelist so it specifically allows objects that point to specific URLs, but writing this for all different kinds of online services seems like a maintenance nightmare.

Here's my logic. We have Markdown, which by it's nature is (mostly) safe. Aside from maliciously entered content in the Markdown, actual tags rendered by Markdown are guaranteed to be safe, so for example if I run the output through an oembed or video filter those generated tags are going to be safe. So if I could somehow know that those generated tags were safe and then only strip the other ones, that would solve the problem. I'm just not sure what the hook would be.

I'm wondering if there is already a straightforward way of doing this in Python or if I have to come up with some kind of clever hack.

Upvotes: 3

Views: 904

Answers (1)

sneeu
sneeu

Reputation: 2652

What you should do is check that the markdown is safe, have a look at bleach, then pass it through markdown:

bleached = bleach.clean(user_input, tags=bleach.ALLOWED_TAGS + ['object', 'param', 'embed'], strip=True)
output = markdown(bleached)

Additionally, django-janior looks like it might be useful.

Upvotes: 2

Related Questions