skip to content

A Rails helper calls gsub on a sanitized member bio and the page now shows escaped tags; how do SafeBuffer's string methods, + and safe_concat explain it?

level: seniorimportance: should knowfreq 28%

answer

  1. the flag does not survive every method
  2. UNSAFE_STRING_METHODS return a plain String
  3. bang versions mark the buffer unsafe
  4. and << escape unsafe arguments
  5. SafeConcatError on an unsafe buffer

basics

~20 s

ActiveSupport::SafeBuffer's transforming methods such as gsub, sub and upcase return a plain String, so <%= %> escapes the sanitized markup again. Its +, << and % escape unsafe arguments, and safe_concat raises SafeConcatError on an unsafe buffer.

solid answer

~40 s

`ActiveSupport::SafeBuffer` keeps a list of transforming methods (`gsub`, `sub`, `upcase`, `downcase`, `strip`, `capitalize`, `tr`, `squeeze` and more) that cannot keep the safety promise, so the non-bang versions return `to_str.<method>`, a plain `String` with `html_safe?` false. Printed with `<%= %>`, the already-sanitized markup is escaped again. The bang versions modify in place and mark the buffer unsafe. Going the other way, `+`, `<<`/`concat` and `%` on a safe buffer escape any argument that is not html_safe, so appending user text to trusted markup is safe. `safe_concat` appends without escaping and raises `SafeBuffer::SafeConcatError` if the buffer itself is no longer safe. The fix is to transform the raw text first and sanitize last.

code

ruby · 12 lines
ruby
safe = "<b>Hi</b>".html_safe

safe.upcase.class             # => String (plain)
safe.upcase.html_safe?        # => false
safe.gsub("Hi", "Yo").html_safe? # => false

(safe + "<i>")                # => "<b>Hi</b>&lt;i&gt;"
(safe + "<i>").html_safe?     # => true
("plain " + safe).html_safe?  # => false

safe.upcase!                  # in place; buffer now unsafe
safe.safe_concat("<br>")      # raises ActiveSupport::SafeBuffer::SafeConcatError

go deeper

for a junior

Recall that changing a trusted string with methods like gsub or upcase gives back an untrusted one.

for a middle

Explain which SafeBuffer methods drop the flag, what +, << and % do with unsafe arguments, and when safe_concat raises.

for a senior

Diagnose double escaping from a stack of helpers and fix it by transforming before sanitizing, never by adding html_safe at the end.

for a principal

Push teams toward helper-built markup and one sanitising boundary so string surgery on trusted HTML stays rare and reviewable.

## The symptom A dating app lets members use bold and italic in their bios, rendered with `sanitize`. A new helper highlights a search term: ```ruby def highlighted_bio(member, term) sanitize(member.bio).gsub(term, "<mark>#{term}</mark>") end ``` After the change every bio shows literal `<b>` and `<mark>` text. Nothing was double-sanitized; the value simply stopped being html_safe. ## Why `gsub` loses the flag `ActiveSupport::SafeBuffer` subclasses `String` and records safety in an instance variable. It cannot know whether an arbitrary transformation keeps the markup trustworthy, so Active Support lists the risky methods and overrides them: - `UNSAFE_STRING_METHODS`: `capitalize`, `chomp`, `chop`, `delete`, `delete_prefix`, `delete_suffix`, `downcase`, `lstrip`, `next`, `reverse`, `rstrip`, `scrub`, `squeeze`, `strip`, `succ`, `swapcase`, `tr`, `tr_s`, `unicode_normalize`, `upcase`; - `UNSAFE_STRING_METHODS_WITH_BACKREF`: `gsub` and `sub`, with extra care so `$~` still works inside a block. For each, the non-bang form is defined as `to_str.<method>(...)`: it converts to a plain `String` first, so the result is an ordinary String with `html_safe?` false. The bang form (`gsub!`, `upcase!`) changes the buffer in place and sets the unsafe flag on it. Either way, when the value reaches `<%= %>` it is escaped. ## What concatenation does The rules for joining values are the mirror image, and they are what make SafeBuffer useful: | Expression | Result | |---|---| | `safe + "<i>"` | SafeBuffer; the `<i>` argument is escaped first | | `safe << user_text` (also `concat`) | appends `user_text` escaped, buffer stays safe | | `safe % [user_text]` | interpolates escaped arguments, result stays safe | | `"plain" + safe` | a plain String, because `String#+` on the receiver decides | | `safe.safe_concat("<i>")` | appends without escaping; raises `SafeConcatError` if `safe` is unsafe | | `unsafe_buffer << "<i>"` | appends as-is; the buffer is already untrusted and will be escaped on output | So the receiver matters: start from a safe buffer and every unsafe piece you add is escaped on the way in. ## Fixing the helper 1. **Transform first, trust last.** Run `gsub` on the original text, then sanitize the result; `mark` is already on the default allowlist. The sanitizer then removes anything a member smuggled in, including through a crafted search term. 2. **Or build with helpers.** Split the text and join the parts with `safe_join`, wrapping matches in `tag.mark`, so every user-supplied piece is escaped. 3. **Do not** call `html_safe` on the `gsub` result. It would make the symptom disappear while trusting `term`, which may come from the query string. ## Diagnosing it in a real app 1. Reproduce in `bin/rails console` with `ApplicationController.helpers`, calling the same helper chain on a sample bio. 2. Call `html_safe?` after each step; the first `false` is where trust was lost. 3. Look at the rendered entities: `&lt;b&gt;` means escaped once (lost trust), `&amp;lt;b&amp;gt;` means escaped twice (already-escaped text was escaped again). 4. Fix the order of operations, then add a helper test that asserts both `html_safe?` and the exact output. ## Related surprises - `safe_concat` exists for helpers that need to append trusted markup to a buffer they own. Calling it on a buffer that a bang method has already marked unsafe raises `ActiveSupport::SafeBuffer::SafeConcatError`, which is a useful alarm rather than a bug to silence. - `SafeBuffer#to_s` returns the buffer itself, so `to_s` does not drop the flag, while `to_str` returns a plain String copy. The general rule interviewers want to hear: **SafeBuffer escapes what you add to it and forgets its trust when you transform it.** Code that respects both halves never needs a late `html_safe`.

  • Why does Active Support treat `strip` as unsafe when it only removes whitespace?
    The list is deliberately conservative: SafeBuffer cannot prove that a given transformation preserves well-formed, trusted markup, so any method that rewrites content returns a plain String. The cost is an occasional re-escape, which is visible and harmless; the alternative risk is silently trusting rewritten markup.
  • How would you test a helper so this regression is caught?
    Write a helper test that asserts both `html_safe?` on the result and the exact output for a bio containing allowed tags and a crafted `<script>` term. The first assertion catches lost trust, the second catches an over-eager `html_safe` fix.

  • Every String method called on a SafeBuffer keeps the html_safe flag.
  • SafeBuffer#+ trusts its argument because the receiver is already safe.
  • safe_concat escapes its argument before appending it.
  • "plain" + a_safe_buffer returns a SafeBuffer.
  • Calling html_safe on the gsub result is the correct fix.