简体   繁体   English

如何在服务器运行时添加/删除机架中间件?

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

In capybara specs I want to test absence of XSS vulnerability. 在水豚的规格中,我想测试缺少XSS漏洞。 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 . 我们使用带有铬的selenium-webdriver来运行浏览器规范,但默认情况下chrome具有XSS保护,可以通过将X-XSS-Protection标头设置为0来禁用它。 I wrote a middleware to set this header, and it works if enabled in config/environments/test.rb . 我编写了一个中间件来设置此标头,如果在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). 如果我停止在这个规范中的任何地方,我可以在Rails.configuration.middleware看到它,但它没有被调用(标头没有设置,如果我在这个中间件中raise它被忽略)。

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测试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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