Module: Ibanity::Webhook::Signature

Defined in:
lib/ibanity/webhook.rb

Class Method Summary collapse

Class Method Details

.verify!(payload, signature_header, tolerance) ⇒ Object

Verifies the signature header for a given payload.

Raises an Ibanity::Error in the following cases:

  • the header does not match the expected format

  • the digest does not match the payload

  • the issued at or expiration timestamp is not within the tolerance

  • the audience or issuer does not match the application config

Returns true otherwise



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ibanity/webhook.rb', line 28

def self.verify!(payload, signature_header, tolerance)
  jwks_loader = ->(options) do
    raise Ibanity::Error.new("The key id from the header didn't match an available signing key", nil) if options[:kid_not_found]

    keys = Ibanity.webhook_keys.select { |key| key.use == "sig" }
                               .map { |key| JWT::JWK.new(key.to_h {|key, value| [key.to_s, value] }) }
    JWT::JWK::Set.new(keys)
  end

  options = {
    aud: Ibanity.client.application_id,
    algorithm: SIGNING_ALGORITHM,
    exp_leeway: tolerance,
    iss: Ibanity.client.base_uri,
    jwks: jwks_loader,
    verify_aud: true,
    verify_iss: true
  }
  jwts = JWT.decode(signature_header, nil, true, options)
  jwt = jwts.first

  validate_digest!(jwt, payload)
  validate_issued_at!(jwt, tolerance)

  true
rescue JWT::ExpiredSignature
  raise_invalid_signature_error!("exp")
rescue JWT::IncorrectAlgorithm
  raise Ibanity::Error.new("Incorrect algorithm for signature", nil)
rescue JWT::InvalidAudError
  raise_invalid_signature_error!("aud")
rescue JWT::InvalidIssuerError
  raise_invalid_signature_error!("iss")
rescue JWT::DecodeError
  raise Ibanity::Error.new("The signature verification failed", nil)
end