4

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 
Alesya Huzik
  • 1,520
  • 14
  • 17

1 Answers1

0

As you're testing Rack::DisableXssProtection itself, it would make sense to extract it as a gem, and test it in isolation with a dummy Rails application.

Community
  • 1
  • 1
Leventix
  • 3,789
  • 1
  • 32
  • 41
  • I'm testing my app, not middleware. Middleware is actually dumb-simple and required only for one spec. I don't want it enabled in app at all, and there's nothing to test in it. – Alesya Huzik Nov 07 '13 at 08:06
  • Ok, so the middleware is only used for testing. Try switching on your middleware's functionality with a request header, like `X-DisableXSSProtection: 1` – Leventix Nov 07 '13 at 09:33
  • I can add class variable and set it before spec / unset after spec, to conditionally enable middleware functionality. But I don't want additional middleware to be _loaded_ for all specs. – Alesya Huzik Nov 08 '13 at 06:34