Search code examples
content-security-policyhanami

How to override Content-Security-Policy for a specific action


I can obviously change the Content-Security-Policy in views/application.rb. I can also add a different Content-Security-Policy for development mode.

How I can use a different Content-Security-Policy for a specific action/actions?


Solution

  • Content-Security-Policy is a HTTP header, so it's related to actions, not views.

    You can set a global value in apps/web/application.rb like this:

    security.content_security_policy '...'
    

    You can set a global value, per environment basis in apps/web/application.rb:

    configure :development do
      security.content_security_policy '...'
    end
    

    You can set a different value for a given action:

    module Web::Controllers::Home
      include Web::Action
    
      def call(params)
        headers.merge!('Content-Security-Policy' => '...')
      end
    end
    

    If you have many actions that need that same exception you can do:

    # apps/web/controllers/csp_rule.rb
    module Web::Controllers::CSPRule
      def self.included(action)
        action.class_eval do
          before :set_content_security_policy
        end
      end
    
      private
    
      def set_content_security_policy
        headers.merge!('Content-Security-Policy' => '...')
      end
    end
    

    And you can include it where needed.