Sanitize Markdown in Rails?
markdown, ruby-on-rails, sanitization, xss
Solution
I follow a couple principals:
- store what the user types
- sanitize on display
- only send data that is necessary
That leads me to the alternative architecture you suggest:
- store markdown in the database
- on render, markdown/sanitize, and send HTML to browser
- when (and if) the user chooses "Edit", request the raw markdown from the server via AJAX
- if I have a "preview" view during edit, I try to use the server to render this as well (although you may need to remove this step if it's too slow). During preview, though, sanitizing may not be that critical.
This has been my approach and it works out pretty cleanly.
Problem
Users can edit "articles" in my application. Each article is mastered in the DB and sent to the client as Markdown -- I convert it to HTML client side with Javascript. I'm doing this so that when the user wants to edit the article he can edit and POST the Markdown right back to the server (since it's already on the page). My question is how to sanitize the Markdown I send to the client -- can I just use Rails' `sanitize` helper? Also, any thoughts on this approach in general? Another strategy I thought of was rendering and sanitizing the HTML on the server, and pulling the Markdown to the client only if the user wants to edit the article.