Class: AlexaSkillsRuby::SignatureValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/alexa_skills_ruby/signature_validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(certificate_cache) ⇒ SignatureValidator

Returns a new instance of SignatureValidator.



4
5
6
7
# File 'lib/alexa_skills_ruby/signature_validator.rb', line 4

def initialize(certificate_cache)
  @certificate_cache = certificate_cache
  @extra_cas = []
end

Instance Method Details

#add_certificate_authorities(certs) ⇒ Object



30
31
32
# File 'lib/alexa_skills_ruby/signature_validator.rb', line 30

def add_certificate_authorities(certs)
  @extra_cas = certs
end

#validate(body, signature_cert_chain_url, signature) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/alexa_skills_ruby/signature_validator.rb', line 9

def validate(body, signature_cert_chain_url, signature)

  cert_uri = Addressable::URI.parse(signature_cert_chain_url).normalize

  raise SignatureValidationError, "Invalid signature URL: [#{cert_uri.to_s}]" unless valid_cert_uri?(cert_uri)

  pem_data = @certificate_cache.get(cert_uri.to_s) || fetch_data(cert_uri.to_s)
  validator = CertificateValidator.new(@extra_cas)
  cert = validator.get_signing_certificate(pem_data)

  raise SignatureValidationError, "Invalid certificate" unless cert

  @certificate_cache.set(cert_uri.to_s, pem_data)

  public_key = cert.public_key
  signature = Base64.decode64(signature)
  unless public_key.verify(OpenSSL::Digest::SHA1.new, signature, body)
    raise SignatureValidationError, "Signature is invalid"
  end
end