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

208 Views Asked by At

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"
1

There are 1 best solutions below

0
matt On BEST ANSWER

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
  )