class SecureHeaders::PublicKeyPins

Constants

CONFIG_KEY
HASH_ALGORITHMS
HEADER_NAME
REPORT_ONLY

Public Class Methods

make_header(config) click to toggle source

Public: make an hpkp header name, value pair

Returns nil if not configured, returns header name and value if configured.

# File lib/secure_headers/headers/public_key_pins.rb, line 15
def make_header(config)
  return if config.nil?
  header = new(config)
  [header.name, header.value]
end
new(config) click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 36
def initialize(config)
  @max_age = config.fetch(:max_age, nil)
  @pins = config.fetch(:pins, nil)
  @report_uri = config.fetch(:report_uri, nil)
  @report_only = !!config.fetch(:report_only, nil)
  @include_subdomains = !!config.fetch(:include_subdomains, nil)
end
validate_config!(config) click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 21
def validate_config!(config)
  return if config.nil? || config == OPT_OUT
  raise PublicKeyPinsConfigError.new("config must be a hash.") unless config.is_a? Hash

  if !config[:max_age]
    raise PublicKeyPinsConfigError.new("max-age is a required directive.")
  elsif config[:max_age].to_s !~ /\A\d+\z/
    raise PublicKeyPinsConfigError.new("max-age must be a number.
                                      #{config[:max_age]} was supplied.")
  elsif config[:pins] && config[:pins].length < 2
    raise PublicKeyPinsConfigError.new("A minimum of 2 pins are required.")
  end
end

Public Instance Methods

max_age_directive() click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 70
def max_age_directive
  "max-age=#{@max_age}" if @max_age
end
name() click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 44
def name
  if @report_only
    REPORT_ONLY
  else
    HEADER_NAME
  end
end
pin_directives() click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 61
def pin_directives
  return nil if @pins.nil?
  @pins.collect do |pin|
    pin.map do |token, hash|
      "pin-#{token}=\"#{hash}\"" if HASH_ALGORITHMS.include?(token)
    end
  end.join("; ")
end
report_uri_directive() click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 74
def report_uri_directive
  "report-uri=\"#{@report_uri}\"" if @report_uri
end
subdomain_directive() click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 78
def subdomain_directive
  @include_subdomains ? "includeSubDomains" : nil
end
value() click to toggle source
# File lib/secure_headers/headers/public_key_pins.rb, line 52
def value
  [
    max_age_directive,
    pin_directives,
    report_uri_directive,
    subdomain_directive
  ].compact.join("; ").strip
end