module AlexaRequestVerifier::CertificateStore

A module used to download, cache and serve certificates from our requests. @since 0.1

Constants

CERTIFICATE_CACHE_TIME

Public Class Methods

delete(uri) click to toggle source

Given a certificate uri, remove the certificate from our store.

@param [String] uri the uri of our certificate @return [nil|Hash] returns nil if the certificate was not in the store,

or a Hash representing the deleted certificate
# File lib/alexa_request_verifier/certificate_store.rb, line 33
def delete(uri)
  store

  @store.delete(uri)
end
fetch(uri) click to toggle source

Given a certificate uri, either download the certificate, or load it from our certificate store.

@param [String] uri the uri of our certificate @return [OpenSSL::X509::Certificate] our certificate file

# File lib/alexa_request_verifier/certificate_store.rb, line 13
def fetch(uri)
  store

  if cache_valid?(@store[uri])
    certificate = @store[uri][:certificate]
  else
    certificate_data = download_certificate(uri)
    certificate = OpenSSL::X509::Certificate.new(certificate_data)

    @store[uri] = { timestamp: Time.now, certificate: certificate }
  end

  certificate
end
store() click to toggle source

Returns a copy of our certificate store

@return [Hash] returns our certificate store

# File lib/alexa_request_verifier/certificate_store.rb, line 42
def store
  @store ||= {}
end

Private Class Methods

cache_valid?(certificate_entry) click to toggle source

Given a certificate entry from our store, tell us if the cache is still valid

@param [Hash] certificate_entry the entry we are checking @return [Boolean] is the certificate cache valid?

# File lib/alexa_request_verifier/certificate_store.rb, line 52
def cache_valid?(certificate_entry)
  return false if certificate_entry.nil?

  (Time.now <= (certificate_entry[:timestamp] + CERTIFICATE_CACHE_TIME))
end
download_certificate(uri) click to toggle source

Given a certificate uri, download it and return the certificate data

@param [String] uri the uri of our certificate @return [String] certificate data

# File lib/alexa_request_verifier/certificate_store.rb, line 62
def download_certificate(uri)
  certificate_uri = URI.parse(uri)

  certificate_data = nil

  Net::HTTP.start(certificate_uri.host, certificate_uri.port, use_ssl: true) do |http|
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER

    response = http.request(Net::HTTP::Get.new(certificate_uri))

    raise AlexaRequestVerifier::InvalidCertificateError, "Unable to download certificate from #{certificate_uri} - Got #{response.code} status code" unless response.is_a? Net::HTTPOK

    certificate_data = response.body
  end

  certificate_data
end