Class: Decidim::ContentSecurityPolicy

Inherits:
Object
  • Object
show all
Defined in:
lib/decidim/content_security_policy.rb

Overview

This class is responsible of generating the Content-Security-Policy header for the application. It takes into account the organization’s CSP settings and the additional settings defined in the initializer.

Constant Summary collapse

SUPPORTED_POLICIES =
%w(
  child-src
  connect-src
  default-src
  font-src
  frame-src
  img-src
  manifest-src
  media-src
  object-src
  prefetch-src
  script-src
  script-src-elem
  script-src-attr
  style-src-elem
  style-src-attr
  worker-src
  base-uri
  sandbox
  form-action
  frame-ancestors
  navigate-to
  report-uri
  report-to
  require-trusted-types-for
  trusted-types
  upgrade-insecure-requests
  style-src
).freeze

Instance Method Summary collapse

Constructor Details

#initialize(organization = nil, additional_policies = {}) ⇒ ContentSecurityPolicy

Returns a new instance of ContentSecurityPolicy.



38
39
40
41
42
# File 'lib/decidim/content_security_policy.rb', line 38

def initialize(organization = nil, additional_policies = {})
  @organization = organization
  @policy = default_policy
  @additional_policies = additional_policies.stringify_keys
end

Instance Method Details

#append_csp_directive(directive, value) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/decidim/content_security_policy.rb', line 53

def append_csp_directive(directive, value)
  return if value.blank?

  message = "Invalid Content Security Policy directive: #{directive}, supported directives: #{SUPPORTED_POLICIES.join(", ")}"
  raise message unless SUPPORTED_POLICIES.include?(directive)

  policy[directive] ||= []
  policy[directive] << value
end

#output_policyObject



44
45
46
47
48
49
50
51
# File 'lib/decidim/content_security_policy.rb', line 44

def output_policy
  add_system_csp_directives
  add_additional_policies
  organization_csp_directives
  append_development_directives

  format_policies
end