Sha256: 244a53c0e005743129155fcd156d24c12310732d4ea2c993d803d4c6848eae16

Contents?: true

Size: 1.43 KB

Versions: 6

Compression:

Stored size: 1.43 KB

Contents

module SecureHeaders
  class STSBuildError < StandardError; end

  class StrictTransportSecurity < Header
    module Constants
      HSTS_HEADER_NAME = 'Strict-Transport-Security'
      HSTS_MAX_AGE = "631138519"
      DEFAULT_VALUE = "max-age=" + HSTS_MAX_AGE
      VALID_STS_HEADER = /\Amax-age=\d+(; includeSubdomains)?(; preload)?\z/i
      MESSAGE = "The config value supplied for the HSTS header was invalid."
      CONFIG_KEY = :hsts
    end
    include Constants

    def initialize(config = nil)
      @config = config
      validate_config unless @config.nil?
    end

    def name
      return HSTS_HEADER_NAME
    end

    def value
      case @config
      when String
        return @config
      when NilClass
        return DEFAULT_VALUE
      end

      max_age = @config.fetch(:max_age, HSTS_MAX_AGE)
      value = "max-age=" + max_age.to_s
      value += "; includeSubdomains" if @config[:include_subdomains]
      value += "; preload" if @config[:preload]

      value
    end

    private

    def validate_config
      if @config.is_a? Hash
        if !@config[:max_age]
          raise STSBuildError.new("No max-age was supplied.")
        elsif @config[:max_age].to_s !~ /\A\d+\z/
          raise STSBuildError.new("max-age must be a number. #{@config[:max_age]} was supplied.")
        end
      else
        @config = @config.to_s
        raise STSBuildError.new(MESSAGE) unless @config =~ VALID_STS_HEADER
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
secure_headers-2.4.4 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-2.4.3 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-2.4.2 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-2.4.1 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-2.4.0 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-2.3.0 lib/secure_headers/headers/strict_transport_security.rb