skip to content

In a Rails view, how does sanitize decide which tags and attributes of a member bio survive, and how do strip_tags and strip_links differ?

level: middleimportance: should knowfreq 45%

answer

  1. allowlist, not blocklist
  2. tags: and attributes: replace the defaults
  3. javascript: hrefs removed
  4. HTML5 sanitizer since load_defaults 7.1
  5. strip_tags removes all, strip_links only a

basics

~10 s

Rails' sanitize keeps only tags and attributes on an allowlist, removes other elements but keeps their text, drops unsafe URL protocols and returns an html_safe string. strip_tags removes every tag; strip_links removes only links.

solid answer

~40 s

`sanitize` hands the HTML to the safe-list sanitizer of the configured vendor; with `load_defaults` 7.1 or later that is `Rails::HTML5::SafeListSanitizer` where Nokogiri's HTML5 parser is available. Its default allowlist covers formatting tags such as `b`, `em`, `strong`, `p`, `a`, `ul`, `li`, `img` and `blockquote`, and attributes such as `href`, `src`, `alt`, `title` and `class`; `style` and event handlers are not on it. Disallowed elements are removed with their text kept, and `href`/`src` values with protocols like `javascript:` are dropped. `tags:` and `attributes:` replace the default lists for one call, `scrubber:` takes precedence over both, and `config.action_view.sanitized_allowed_tags` changes the default. The result is html_safe. `strip_tags` removes every tag and returns escaped, html_safe text; `strip_links` removes only `a` tags, keeping their text, and returns a plain String that `<%= %>` escapes.

code

erb · 6 lines
erb
<%# app/views/profiles/show.html.erb %>
<div class="bio">
  <%= sanitize @member.bio, tags: %w[b i em strong p br a], attributes: %w[href] %>
</div>

<p class="preview"><%= strip_tags(@member.bio) %></p>

go deeper

for a junior

Know that sanitize keeps a small set of formatting tags and that strip_tags removes all tags.

for a middle

Explain the allowlist, that tags: and attributes: replace the defaults, the protocol check on href and src, and which vendor load_defaults selects.

for a senior

Choose the narrowest allowlist for each field, refuse style and event attributes, and re-sanitise stored HTML on output so tightened rules apply.

for a principal

Decide whether user rich text belongs in sanitize at all or in a structured editor with its own pipeline, and own the policy for changing the allowlist.

## The job `sanitize` does Escaping shows user markup as text. Sometimes the product wants a little of it rendered: a member may put **bold** or a link in a dating-profile bio. `sanitize` is Action View's helper for that case. It parses the HTML, keeps what is on an **allowlist**, removes the rest and returns an `html_safe` string, so `<%= sanitize @member.bio %>` needs no `raw`. ## Where the rules come from The helper delegates to a sanitizer from the **rails-html-sanitizer** gem (version 1.7 at this pin), chosen by `ActionView::Helpers::SanitizeHelper.sanitizer_vendor`: | Setting | Vendor | Parser | |---|---|---| | no `load_defaults` 7.1 (framework default) | `Rails::HTML4::Sanitizer` | HTML4 | | `load_defaults` 7.1 or later, including a new 8.1 app | `Rails::HTML::Sanitizer.best_supported_vendor`, which is `Rails::HTML5::Sanitizer` when Nokogiri supports HTML5 | HTML5 | The setting is `config.action_view.sanitizer_vendor`. On JRuby, where the HTML5 parser is unavailable, Rails falls back to HTML4. Parsing like a browser does matters because sanitizer bypasses usually exploit differences between the sanitizer's parse and the browser's. ## The default allowlist - **Tags** include `a`, `abbr`, `b`, `blockquote`, `br`, `code`, `del`, `div`, `em`, `h1`-`h6`, `hr`, `i`, `img`, `li`, `mark`, `ol`, `p`, `pre`, `span`, `strong`, `sub`, `sup`, `time` and `ul`. - **Attributes** are `abbr`, `alt`, `cite`, `class`, `datetime`, `height`, `href`, `lang`, `name`, `src`, `title`, `width` and `xml:lang`. - Not allowed by default: `script`, `iframe`, `form`, `style` elements, the `style` attribute and every `on*` event attribute. An element outside the list is removed but its child content is kept, so `<u>shy</u>` becomes `shy`. Elements in an SVG or MathML namespace are pruned entirely. URL attributes are also checked: an `href` using `javascript:` is removed even though `href` itself is allowed, including obfuscated spellings with character references. ## Narrowing or widening it 1. **Per call:** `sanitize(@member.bio, tags: %w[b i em strong a], attributes: %w[href])`. The lists **replace** the defaults for that call; pass only `tags:` and the default attributes still apply. 2. **Custom scrubber:** `sanitize(html, scrubber: BioScrubber.new)`, where the class subclasses `Rails::HTML::PermitScrubber`. A scrubber takes precedence over `tags:` and `attributes:`. 3. **App-wide:** `config.action_view.sanitized_allowed_tags = %w[...]` and `config.action_view.sanitized_allowed_attributes = %w[...]` in `config/application.rb` replace the vendor's defaults. The helper's own documentation warns that adding tags or attributes can introduce vulnerabilities; `style` and event attributes are the usual mistakes. Sanitizing also does not guarantee well-formed output, so it is not a substitute for validating structure you rely on. ## The two blunter helpers - **`strip_tags(html)`** uses the vendor's full sanitizer: every tag and comment is removed and special characters in the remaining text are escaped. `strip_tags("<b>Hi</b> & bye")` gives `Hi &amp; bye`, marked html_safe. Good for previews, notification text and meta descriptions. - **`strip_links(html)`** uses the link sanitizer: only `a` elements are removed and their text kept. Unlike the other two it does **not** mark its result html_safe, so `<%= strip_links(bio) %>` escapes whatever markup is left; it is a text-cleaning step, not a rendering one. ## Behaviour worth knowing - `sanitize(nil)` returns `nil`, so `<%= sanitize @member.bio %>` prints nothing for an empty profile instead of raising. - The sanitizer serialises the parsed tree, so output can differ from input even when nothing was removed, for example in quoting or in how unclosed tags are closed. - `sanitize_css` is the CSS part of the same machinery; it is used on `style` attributes when you allow them, and is rarely called directly. ## Choosing between them | Need | Helper | |---|---| | show user text exactly as typed | plain `<%= %>` (escaping) | | allow a few formatting tags | `sanitize` with a narrow `tags:` list | | plain-text excerpt of HTML | `strip_tags` | | render formatting, forbid links | `sanitize` with a `tags:` list that omits `a` | Where you store sanitised output, re-sanitise on render anyway: the allowlist may have tightened since the row was written.

  • A team adds `style` to `sanitized_allowed_attributes` so members can colour text. What is the risk?
    The `style` attribute is a large attack surface: CSS can overlay fake content, hide elements or load remote resources. The sanitizer scrubs CSS properties, but widening the allowlist means trusting that scrubbing. A safer design is a fixed set of classes on `class` or a separate colour field the app renders itself.
  • Why does `<%= strip_links(@member.bio) %>` show the bio's `<b>` tags as text?
    `strip_links` returns the link sanitizer's output as a plain String, not marked html_safe, unlike `sanitize` and `strip_tags`. `<%= %>` therefore escapes the remaining markup. To render formatting without links, use `sanitize` with a `tags:` list that leaves out `a`.
  • Why is sanitizing on input and storing the result not enough on its own?
    The stored HTML was cleaned with the allowlist and sanitizer version of that day. Rules tighten and bypasses get fixed, so sanitizing again at render time applies today's rules to old rows. Storing the original text and sanitizing on output keeps one boundary.

  • sanitize works by removing a list of known-bad tags such as script.
  • Passing tags: adds to the default allowlist for that call.
  • An allowed href attribute keeps whatever URL the user typed.
  • The output of sanitize must be wrapped in raw to render as markup.
  • strip_tags and strip_links both remove every tag from the text.

Assumes Rails 8.1 with load_defaults 8.1; the HTML5 sanitizer vendor became the default through load_defaults 7.1, and apps on older defaults still use Rails::HTML4::Sanitizer.