File: referrer_policy.rb

package info (click to toggle)
ruby-secure-headers 7.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 556 kB
  • sloc: ruby: 4,196; makefile: 5
file content (42 lines) | stat: -rw-r--r-- 1,296 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# frozen_string_literal: true
module SecureHeaders
  class ReferrerPolicyConfigError < StandardError; end
  class ReferrerPolicy
    HEADER_NAME = "referrer-policy".freeze
    DEFAULT_VALUE = "origin-when-cross-origin"
    VALID_POLICIES = %w(
      no-referrer
      no-referrer-when-downgrade
      same-origin
      strict-origin
      strict-origin-when-cross-origin
      origin
      origin-when-cross-origin
      unsafe-url
    )

    # Public: generate an Referrer Policy header.
    #
    # Returns a default header if no configuration is provided, or a
    # header name and value based on the config.
    def self.make_header(config = nil, user_agent = nil)
      return if config == OPT_OUT
      config ||= DEFAULT_VALUE
      [HEADER_NAME, Array(config).join(", ")]
    end

    def self.validate_config!(config)
      case config
      when nil, OPT_OUT
        # valid
      when String, Array
        config = Array(config)
        unless config.all? { |t| t.is_a?(String) && VALID_POLICIES.include?(t.downcase) }
          raise ReferrerPolicyConfigError.new("Value can only be one or more of #{VALID_POLICIES.join(", ")}")
        end
      else
        raise TypeError.new("Must be a string or array of strings. Found #{config.class}: #{config}")
      end
    end
  end
end