简体   繁体   中英

How to add/remove rack middleware while server is running?

In capybara specs I want to test absence of XSS vulnerability. We use selenium-webdriver with chromium to run browser specs, but chrome by default has XSS protection, which may be disabled by setting X-XSS-Protection header to 0 . I wrote a middleware to set this header, and it works if enabled in config/environments/test.rb . As this header is required only in this spec, I don't want to have it enabled for all specs.

I tried following:

describe 'without xss protection' do
  before :all do
    Rails.configuration.middleware.use Rack::DisableXssProtection
  end

  after :all do
    Rails.configuration.middleware.delete Rack::DisableXssProtection
  end

  it 'should not have xss', :needs_browser do
    visit new_order_path
    page.driver.execute_script <<-EOF
      $("<input/>", {
        id:    "new_input",
        name:  "bad_field",
        type:  "radio",
        value: "<script>alert('fail');</script>"
      }).appendTo("#some_form");
    EOF
    find('#new_input').click
    click_on 'submit'
  end
end

If I stop anywhere inside this spec, I can see it in Rails.configuration.middleware , but it is not called (header is not set and if I put raise in this middleware it is ignored).

So, how can I add/remove middleware while server is running?

EDIT: middleware is just the following:

module Rack
  class DisableXssProtection
    def initialize(app)
      @app = app 
    end 
    def call(env)
      status, headers, body = @app.call(env)
      headers['X-XSS-Protection'] = '0' 
      [status, headers, body]
    end 
  end 
end 

当您正在测试Rack::DisableXssProtection本身时,将它作为gem提取是有意义的,并使用虚拟Rails应用程序 Rack::DisableXssProtection测试它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM