Skip to content

AuthenticityToken does not work when configured via "set :protection" #2037

Closed

Description

@osbre

Somehow using set :protection, use: :authenticity_token results in CSRF protection not being applied (bug)

Working configuration

class MyApp < Sinatra::Base
  configure do
    enable :sessions
    set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
    use Rack::Protection
    use Rack::Protection::AuthenticityToken
  end
end

Currently non-working configuration

class MyApp < Sinatra::Base
  configure do
    enable :sessions
    set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
    set :protection, use: :authenticity_token
  end
end

Code to reproduce the issue

require "sinatra/base"
require "rack/protection"

class MyApp < Sinatra::Base
  configure do
    enable :sessions
    set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
    set :protection, use: :authenticity_token
    # use Rack::Protection
    # use Rack::Protection::AuthenticityToken
  end

  helpers do
    def csrf_tag
      "<input type='hidden' name='authenticity_token' value='#{session[:csrf]}' />"
    end
  end

  get "/login" do
    erb :login
  end

  post "/login" do
  end
end
<!-- views/login.erb -->
<form action="/login" method="post">
  <%= csrf_tag %>
  <label>
    Email:
    <input type="email" name="email" required>
  </label>
  <label for="password">
    Password:
    <input type="password" name="password" required>
  </label>
  <button type="submit">
    Login
  </button>
</form>

Activity

  1. dentarg commented on Aug 2, 2024

    @dentarg
    Member

    I think use should be an array

  2. osbre commented on Aug 4, 2024

    @osbre
    Author

    @dentarg same result when using it as an array:

    set :protection, use: [ :authenticity_token ]

    It just doesn't get applied

  3. dentarg commented on Aug 8, 2024

    @dentarg
    Member

    It works. Your session is dropped. I ran with this patch

    $ git diff
    diff --git a/rack-protection/lib/rack/protection/base.rb b/rack-protection/lib/rack/protection/base.rb
    index 499f0d04..0ae71376 100644
    --- a/rack-protection/lib/rack/protection/base.rb
    +++ b/rack-protection/lib/rack/protection/base.rb
    @@ -46,15 +46,22 @@ module Rack
           end
    
           def call(env)
    +        puts "Rack::Protection::Base self.class=#{self.class} accepts? env = #{accepts? env}"
             unless accepts? env
               instrument env
               result = react env
    +
    +          puts "  result=#{result.inspect}"
             end
    +
             result or app.call(env)
           end
    
           def react(env)
             result = send(options[:reaction], env)
    +        puts "    in react options=#{options.inspect}"
    +        puts "    in react result=#{result.inspect}"
    +        puts "    in react (Array === result) && (result.size == 3) = #{(Array === result) && (result.size == 3)}"
             result if (Array === result) && (result.size == 3)
           end
    
    @@ -93,12 +100,16 @@ module Rack
           end
    
           def drop_session(env)
    +        puts "    in drop_session -- session? env #{session? env}"
             return unless session? env
    
    +        puts "    in drop_session -- before session.clear"
             session(env).clear
    
             return if ["1", "true"].include?(ENV["RACK_PROTECTION_SILENCE_DROP_SESSION_WARNING"])
    
    +        puts "    in drop_session -- before 'warn session dropped by #{self.class}'"
    +
             warn env, "session dropped by #{self.class}"
           end

    That logs

    $ b e puma --log-requests --port 8080
    Puma starting in single mode...
    * Puma version: 6.4.2 (ruby 3.2.4-p170) ("The Eagle of Durango")
    *  Min threads: 0
    *  Max threads: 5
    *  Environment: development
    *          PID: 15141
    * Listening on http://0.0.0.0:8080
    Use Ctrl-C to stop
    Rack::Protection::Base self.class=Rack::Protection::AuthenticityToken accepts? env =
        in drop_session -- session? env true
        in drop_session -- before session.clear
        in drop_session -- before 'warn session dropped by Rack::Protection::AuthenticityToken'
        in react options={:reaction=>:drop_session, :logging=>true, :message=>"Forbidden", :encryptor=>Digest::SHA1, :session_key=>"rack.session", :status=>403, :allow_empty_referrer=>true, :report_key=>"protection.failed", :html_types=>["text/html", "application/xhtml", "text/xml", "application/xml"], :authenticity_param=>"authenticity_token", :key=>:csrf, :allow_if=>nil, :img_src=>"'self' data:", :font_src=>"'self'", :use=>:authenticity_token, :without_session=>false}
        in react result=true
        in react (Array === result) && (result.size == 3) = false
      result=nil
    Rack::Protection::Base self.class=Rack::Protection::HttpOrigin accepts? env = true
    Rack::Protection::Base self.class=Rack::Protection::IPSpoofing accepts? env = true
    Rack::Protection::Base self.class=Rack::Protection::RemoteToken accepts? env = true
    127.0.0.1 - - [08/Aug/2024:18:20:23 +0200] "POST /login HTTP/1.1" 200 - 0.0071
    ^C- Gracefully stopping, waiting for requests to finish
    === puma shutdown: 2024-08-08 18:22:16 +0200 ===
    - Goodbye!

    If you do set :protection, use: :authenticity_token, reaction: :deny, the response will be 403 Forbidden

  4. dentarg commented on Aug 8, 2024

    @dentarg
    Member

    You can also see it working if you do enable :logging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions