In a Rails view, which code patterns bypass ERB's automatic escaping and let a car listing's user-written text run as script?
answer
- <%= escapes, <%== does not
- html_safe on an interpolated string
- raw() around user data
- link_to with a javascript: URL
- render inline: and render html:
basics
~10 sEscaping is bypassed by <%== %>, raw, .html_safe on strings that contain user data, render inline: or html: with user input, and link_to with a user-supplied URL, whose javascript: scheme survives escaping.
solid answer
~40 sERB's `<%= %>` escapes any string not marked safe, so the risk is code that marks or emits user text as safe. The common bypasses are `<%== %>` and `raw(...)`, `"<b>#{listing.title}</b>".html_safe`, where the whole string, user part included, becomes trusted, a helper returning an interpolated string with `html_safe`, and `render inline:` or `render html:` fed with request data. A different class is `link_to "Dealer site", listing.website_url`: the attribute is escaped, but a `javascript:` URL still runs when clicked, so the scheme must be validated. Fixes keep data out of trusted strings: let ERB escape, build markup with `tag`, `content_tag` or `safe_join`, sanitize genuine rich text, and allow only `http`/`https` URLs. Brakeman reports all of these as **Cross-Site Scripting**, for example "Unsafe parameter value in link_to href".
go deeper
Know that <%= escapes by default, and that raw, <%== and html_safe on user data switch that off.
Explain why html_safe after interpolation is the classic bug, why link_to needs scheme validation, and which helpers build markup safely.
Review helpers and presenters for hidden html_safe calls, decide where rich text is sanitized, and triage Brakeman's XSS warnings by input source.
Set rules that keep trust decisions few and visible: a short list of approved rich-text paths, and html_safe only on constants.
## Where Rails' protection comes from In a Rails template, `<%= value %>` escapes `<`, `>`, `&`, `"` and `'` unless the value is an `ActiveSupport::SafeBuffer`, a string already marked safe. Helpers such as `link_to`, `tag` and `content_tag` escape their text and attributes the same way. So Rails views are safe by default, and **cross-site scripting** in a Rails app nearly always means some code told Rails that user data was safe, or put it somewhere escaping does not help. ## The patterns that bypass escaping | Pattern | Why it is dangerous | |---|---| | `<%== listing.description %>` | outputs without escaping | | `<%= raw listing.description %>` | same, as a helper call | | `"<b>#{listing.title}</b>".html_safe` | marks the interpolated user text as trusted | | a helper returning `"...#{x}...".html_safe` | the same bug, hidden in `app/helpers` | | `render inline: params[:template]` | renders request data as an ERB template | | `render html: listing.notes.html_safe` | sends user data as trusted HTML | | `link_to "Website", listing.website_url` | escaping keeps the attribute intact, but `javascript:` URLs still execute | The `html_safe` case trips up experienced developers. `html_safe` does not clean anything; it is a promise that the string contains no attacker-controlled markup. Interpolating first and promising afterwards breaks the promise. ## A worked example In the dealership app, a listing card helper looks harmless: ```ruby def listing_badge(listing) "<span class=\"badge\">#{listing.title}</span>".html_safe end ``` A seller titles a car `<img src=x onerror=alert(document.cookie)>`. Every visitor to the search results runs that handler. The fix lets Rails escape the title: ```ruby def listing_badge(listing) tag.span(listing.title, class: "badge") end ``` ## The link_to case Escaping protects HTML structure, not URL meaning. `link_to "Dealer site", listing.website_url` produces a well-formed `href`, and if the stored URL is `javascript:fetch('/admin')`, clicking it runs the script. The defence is validating the scheme when the URL is saved, and again before rendering: 1. Parse it with `URI`. 2. Accept only `http` and `https`. 3. Fall back to plain text for anything else. ## Fixes, in order of preference - Do nothing: `<%= listing.description %>` is already safe as plain text. - Build markup with `tag.*`, `content_tag` and `safe_join`, which escape their parts. - For genuine rich text, sanitize with an allowlist instead of trusting it. - Never feed request data to `render inline:`; templates belong in files. - Keep `html_safe` and `raw` for constant strings you wrote, and review every other use. A strict content security policy limits the damage of a slip, but does not replace escaping. ## Reviewing a codebase for it The bypasses are few and searchable, which makes a review tractable: 1. Search for `html_safe`, `raw(`, `<%==` and `render inline:` and read every hit, starting with helpers and presenters. 2. For each, ask whether any part of the string came from a user, including stored model attributes and translations with interpolated values. 3. List every `link_to`, `button_to` and `href` that takes a model attribute or param as the URL, and confirm the scheme is validated. 4. Check JSON embedded in `<script>` tags, where HTML escaping rules differ from the page body. ## How Brakeman reports it Brakeman's cross-site scripting checks produce warnings of type **Cross-Site Scripting**: - unescaped `params`, cookies or model attributes in templates, through `raw`, `html_safe` or `<%==`; - "Unsafe parameter value in `link_to` href" when request input or a model attribute becomes a link target; - "Unescaped parameter value rendered inline" for `render inline:` with request data. Confidence is higher for direct request input than for model attributes, because stored data might have been cleaned on the way in.
- Why is "<b>#{listing.title}</b>".html_safe unsafe when "<b>".html_safe + listing.title is not?`html_safe` marks the whole receiver as trusted. Interpolating first puts the user's title inside the string that gets the mark, so its markup is trusted too. Concatenating onto a `SafeBuffer` escapes the unsafe right-hand string as it is appended, so the title stays text.
- A listing's website field is escaped by link_to. Why can it still run script?Escaping keeps the value from breaking out of the `href` attribute, but a `javascript:` URL is valid inside it, and the browser executes it on click. Validate the scheme: accept only `http` and `https` when saving, and render anything else as plain text.
- html_safe escapes the string so it is safe to output
- <%== is just a shorter form of <%=
- link_to escapes the href, so any stored URL is safe
- Model attributes are trusted because validations ran on save
- A strict CSP makes html_safe on user data acceptable