3

在 capybara 规范中,我想测试是否存在 XSS 漏洞。我们使用 selenium-webdriver 和 chromium 来运行浏览器规范,但 chrome 默认具有 XSS 保护,可以通过将X-XSS-Protectionheader 设置为0. 我编写了一个中间件来设置此标头,如果在config/environments/test.rb. 由于此标头仅在此规范中是必需的,因此我不想为所有规范启用它。

我试过以下:

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

如果我在此规范中的任何地方停下来,我可以在 中看到它Rails.configuration.middleware,但它不会被调用(未设置标头,如果我放入raise此中间件,它将被忽略)。

那么,如何在服务器运行时添加/删除中间件?

编辑:中间件如下:

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 
4

1 回答 1

0

当您在测试自己时,将其提取为 gem 并使用虚拟 Rails 应用程序单独Rack::DisableXssProtection测试它是有意义的。

于 2013-11-06T23:11:29.570 回答