Search code examples
ruby-on-railshttp-redirectbrakeman

How to prevent Brakeman 'unprotected redirect' warning when redirect to external domain is desired?


A model in a Rails app has a url column, where users can enter the address of external sites.

The urls are displayed on a page. When clicked, in addition to routing to that url, I need to perform some actions in the app. So I defined a controller action as follows

#objects_controller.rb

def click
  @object = Object.find params[:id]
  # do some stuff
  respond_to do |format|
    format.html { redirect_to @object.url }
  end
end

and in the view

<%= 'click me', click_object_path @object %>

Brakeman is (as expected) throwing a warning

High - Redirect - Possible unprotected redirect

Normally the solution to this would be to add only_path: true to the redirect and only allow redirects within the current app. But in this case the desired behaviour is to navigate to an external site.

My questions

  1. Are there any steps I should be taking to ensure malicious code cannot be entered and activated from the Object.url column (or in other words, is my click controller action the best way to archive the desired in-app actions plus navigation)?
  2. If this is the correct approach, is there a way to quieten Brakeman so that this particular issue is no longer reported?

Solution

  • For anyone else having a similar issue, I added some checks to my controller to verify that @object.url is indeed a properly formatted url.

    def click
      @object = Object.find params[:id]
      if @object.url =~ URI::regexp
        obj_url = URI.parse(@object.url)
      else
        obj_url = nil
      end
      # do some stuff
      respond_to do |format|
        format.html { redirect_to obj_url }
      end
    end
    

    And Brakeman reports 1 fixed warning. Result!