Sha256: bd8e5b34fff62409fb3d0c3f05ef01b48ab691124337eefd65501d5b47e4c14c

Contents?: true

Size: 1.93 KB

Versions: 1

Compression:

Stored size: 1.93 KB

Contents

class ContentSecurityPolicy

  # @attr_reader [Boolean] use in report only mode
  attr_reader :report_only

  # @attr_reader [Hash] directives hash
  attr_reader :directives

  #
  # Initializes Content Security Policy middleware.
  #
  # @param [Hash] opts Options hash
  # @option [Boolean] :report_only Set to true if use in report-only mode
  # @option [Hash] :directives Directives
  #
  # @example
  #   use ContentSecurityPolicy, :directives => { 'default-src' => "'self'" }
  #   use ContentSecurityPolicy, :directives => { 'default-src' => "'self'", :report_only => true }
  #
  def initialize(app, options = {})
    @app = app
    @report_only = options[:report_only] || ContentSecurityPolicy.report_only
    @directives = options[:directives] || ContentSecurityPolicy.directives

    @directives or raise NoDirectivesError, 'No directives were passed.'

    # make sure directives with policy-uri don't contain any other directives
    if @directives['policy-uri'] && @directives.keys.length > 1
      raise IncorrectDirectivesError, 'You passed both policy-uri and other directives.'
    # make sure default-src is present
    elsif !@directives['policy-uri'] && !@directives['default-src']
      raise IncorrectDirectivesError, 'You have to set default-src directive.'
    end
  end

  #
  # @api private
  #
  def call(env)
    dup._call(env)
  end

  #
  # @api private
  #
  def _call(env)
    status, headers, response = @app.call(env)

    # flatten directives
    directives = @directives.sort.map { |dir| "#{dir[0]} #{dir[1]}" }.join('; ')

    # prepare response headers names
    if @report_only
      resp_headers = %w(X-Content-Security-Policy-Report-Only X-WebKit-CSP-Report-Only)
    else
      resp_headers = %w(X-Content-Security-Policy X-WebKit-CSP)
    end

    # append response header
    resp_headers.each do |resp_header|
      headers[resp_header] = directives
    end

    [status, headers, response]
  end

end # ContentSecurityPolicy

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
content-security-policy-0.1.1 lib/content-security-policy/middleware.rb