teamcapybara / capybara

Acceptance test framework for web applications

Home Page:http://teamcapybara.github.io/capybara/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

undefined method `filter_map' for nil:NilClass in Capybara::Server::AnimationDisabler#directive_nonces

ndbroadbent opened this issue · comments

Note: This is for issues with Capybara. If you have a howto type question, please ask on the mailing list as requested in the README: http://groups.google.com/group/ruby-capybara

Meta

Capybara Version: 3.39.2

I use a gem called RSwag, and I'm seeing this crash when I run one of my own integration tests that loads the swagger UI page:

Failures:

  1) CSP Reports All reported CORS issues are fixed
     Got 1 failure and 1 other error:

     1.1) Failure/Error: 
            s[0], s[1..].filter_map do |value|
              /^'nonce-(?<nonce>.+)'/ =~ value
              nonce
            end[0]

          NoMethodError:
            undefined method `filter_map' for nil:NilClass
          # ./vendor/bundle/ruby/2.7.0/gems/capybara-3.38.0/lib/capybara/server/animation_disabler.rb:57:in `block in directive_nonces'
          # ./vendor/bundle/ruby/2.7.0/gems/capybara-3.38.0/lib/capybara/server/animation_disabler.rb:55:in `to_h'
          # ./vendor/bundle/ruby/2.7.0/gems/capybara-3.38.0/lib/capybara/server/animation_disabler.rb:55:in `directive_nonces'
          # ./vendor/bundle/ruby/2.7.0/gems/capybara-3.38.0/lib/capybara/server/animation_disabler.rb:29:in `call'
          # ./vendor/bundle/ruby/2.7.0/gems/capybara-3.38.0/lib/capybara/server/middleware.rb:60:in `call'

This is due to a CSP header that they set as a plain string with trailing spaces after the last semicolon: https://github.com/rswag/rswag/blob/master/rswag-ui/lib/rswag/ui/middleware.rb#L43-L51

I've fixed this with a monkey patch in my own codebase, where I added .map(&:strip) and .reject(&:empty?):

Capybara::Server::AnimationDisabler.class_eval do
    private

    def directive_nonces(headers)
      headers.fetch('Content-Security-Policy', '')
        .split(';')
        .map(&:strip)
        .reject(&:empty?)
        .map(&:split)
        .to_h do |s|
        [
          s[0],
          s[1..].filter_map do |value|
            /^'nonce-(?<nonce>.+)'/ =~ value
            nonce
          end[0],
        ]
      end
    end
end

Would you accept this as a PR, or is there a better way to fix this? Thanks!

I'd suggest fixing this in RSwag by not sending the trailing ; as defined in the content security policy header definition