Search code examples
rubymarkdownredcarpet

Ruby, How to prevent Redcarpet to render HTML code in the output?


I am using Redcarpet to render in a webpage data introduced by the User.

I see that it is very easy for the User to introduce malicious HTML code.

I am trying different Redcarpet initializer options to prevent any possible malicious code to be renderered in the output but nothing is working:

Trying filter_html:

markdown =
  Redcarpet::Markdown.new(
    Redcarpet::Render::HTML,
    filter_html: true
  )

markdown.render("<style>style</style> <script>alert()</script>")

# => "<p><style>style</style> <script>alert()</script></p>\n"

Trying scape_html:

markdown =
  Redcarpet::Markdown.new(
    Redcarpet::Render::HTML,
    escape_html: true
  )

markdown.render("<style>style</style> <script>alert()</script>")

# => "<p><style>style</style> <script>alert()</script></p>\n"

Solution

  • These are options for the renderer, not the parser, so you need to pass them to the renderer, and then pass the configured renderer to the parser, e.g.:

    markdown =
      Redcarpet::Markdown.new(
        Redcarpet::Render::HTML.new(escape_html: true),
        # other parser options here, e.g.
        autolink: true
      )