search

Home  >  Q&A  >  body text

Update js.erb template for select box options - handle XSS securely and display text correctly

I'm rendering a .js.erb file in a Rails application. In this file, I'm updating the options of a select box.

The most important thing is that I do it in an XSS safe way. Based on this Stack Overflow solution, referencing the OWASP DOM based XSS Prevention Cheat Sheet, I update the select box's options in the following way:

Try 1

// app/views/blogs/blogs_select_listing.js.erb

// 删除所有选项
$('#blog_select_box').children().remove();

// 遍历@blogs集合,将每个博客项目作为选项添加到选择框中
<% @blogs.each do |blog| %>
  var opt = document.createElement("option");
  opt.setAttribute("value", "<%= blog.id %>");
  opt.textContent = "<%= blog.name %>";
  $('#blog_select_box').append(opt);
<% end %>

Try 2

I know Rails has a html_safe method, so I tried using it: I updated "<%= blog.name %>"; to " <%= blog.name.html_safe %>";.

Try 3

This methodseemseffective. It updates the options and the display text works fine, while the options with the display text alert("gotcha"); just display as text and don't execute as code:

// app/views/blogs/blogs_select_listing.js.erb

// 删除所有选项
$('#blog_select_box').children().remove();

// 遍历@blogs集合,将每个博客项目作为选项添加到选择框中
$('#blog_select_box')
.html("<%= j options_from_collection_for_select(@blogs, :id, :name) %>");

It's unclear how I can update the selection options from the .js.erb template in a way that is both safe and displays the text correctly.

P粉674757114P粉674757114268 days ago636

reply all(1)I'll reply

  • P粉594941301

    P粉5949413012024-03-31 11:24:38

    Try to give my understanding:

    • Try 1

    While you can decode special characters , that's not the Rails way.

    • Try 2

    html_safe does not ensure that the string result is safe, but you explicitly specify that the string is safe so that the HTML tags in the string can be displayed in HTML form, so it does not solve the XSS problem .

    string = '<div>html with string</div>'
    <%= string.html_safe %> # 以HTML形式显示
    <%= string %> # 以字符串形式显示
    
    • Try 3

    According to this article, it is safe to use escape_javascript within single or double quotes.

    # 安全
    '<%= j string %>' # 或者
    "<%= j string %>"
    
    # 不安全
    <%= j string %>  # 或者
    `<%= j string %>`
    

    Therefore, attempt 3 is XSS safe and the Rails way, and is preferred.

    Your code can be simplified to:

    # html()方法会替换原始内容,所以你不需要先删除它
    $('#blog_select_box')
      .html("<%= j options_from_collection_for_select(@blogs, :id, :name) %>");
    

    reply
    0
  • Cancelreply