Sha256: bd6689a6e84cc1d0337a752f413c9f7cf83a9b0578ff8355b0a2fb843b726299

Contents?: true

Size: 1.33 KB

Versions: 6

Compression:

Stored size: 1.33 KB

Contents

module SecureHeaders
  class STSBuildError < StandardError; end

  class StrictTransportSecurity
    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)?\z/i
      MESSAGE = "The config value supplied for the HSTS header was invalid."
    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
      value += "; includeSubdomains" if @config[:include_subdomains]

      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] !~ /\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-0.4.0 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-0.3.0 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-0.2.1 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-0.2.0 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-0.1.1 lib/secure_headers/headers/strict_transport_security.rb
secure_headers-0.1.0 lib/secure_headers/headers/strict_transport_security.rb