Search code examples
ruby-on-railsinternationalizationlocalerails-i18n

Locale switch in Rails causing url params to be dropped


Until recently, I have been using params.merge to handle this, but having been alerted to an XSS vulnerability needed to find a better way to handle locale switching. Most pages are now completely fine, but certain urls will have params that I need to keep, for example:

movies/123456/seat?ticket_id=1670&locale=en&time_type=2

The locale switch is now handled like so from the navbar:

<li><%= link_to "English", locale: "en" %></li>

Unfortunately, switching the locale (EG; to Japanese) results in the following:

movies/123456/seat?locale=ja

Is there any way that I can retain the parameters (without using params.merge as before) or do I need to re-work large chunks of my application to resolve this?


Solution

  • You can create a method to whitelist and sanitize the params:

    module ParamsHelper
      def merge_and_santize_params(*whitelist)
         params.permit(*whitelist)
               .transform_values! { |v| sanitize v }
               .merge(locale: I18n.current_locale)
      end
    end
    

    <li><%= link_to "English", merge_and_santize_params(:time_type, :ticket_id) %></li>
    

    This uses ActionView::Helpers::SanitizeHelper which is better than nothing but may still be vulnerable to well crafted attacks.