This product is not supported for your selected Datadog site. ().

Metadata

ID: ruby-security/no-html-safe

Language: Ruby

Severity: Warning

Category: Security

CWE: 79

Description

The html_safe method in Ruby on Rails marks a string as trusted and disables automatic HTML escaping. If any untrusted input is included, the output may contain raw HTML/JS and can lead to XSS. Thus, any use of html_safe on interpolated strings should be treated as unsafe unless every interpolated value is known to be safe.

This applies even if you are using h (also known as html_escape) because h does nothing if the string has already been marked html_safe.

Prefer letting Rails escape automatically:

<p><%= user_input %></p>

Or use tag helpers:

content_tag(:p, user_input)
tag.p(user_input)

When HTML is required, use sanitize:

content_tag(:p, sanitize(user_input))

Non-Compliant Code Examples

# Unsafe unless `username` is trusted or explicitly escaped
page_content = "<p>hello, #{username}</p>".html_safe

# Unsafe unless you can prove `user_input` is not already marked `html_safe` (because `h` will not escape it).
page_content = "<p>description: #{h(user_input)}</p>".html_safe

Compliant Code Examples

# For when HTML is required
content = content_tag(:p, sanitize(user_input))

# Tag helpers automatically perform escaping
content = content_tag(:p, "hello, #{username}")

# String literals are safe
content = "<p>hello</p>".html_safe
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security