Class: Pingram::WebhookVerification

Inherits:
Object
  • Object
show all
Defined in:
lib/pingram/webhooks.rb

Overview

Verifies HMAC signatures on webhook payloads. Call class methods on WebhookVerification.

Constant Summary collapse

DEFAULT_TOLERANCE_SECONDS =

Default timestamp tolerance in seconds (5 minutes)

300

Class Method Summary collapse

Class Method Details

.construct_event(payload:, message_id:, signature:, timestamp:, secret:, tolerance: DEFAULT_TOLERANCE_SECONDS) ⇒ Object

Verify webhook signature and return the parsed event.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/pingram/webhooks.rb', line 25

def construct_event(payload:, message_id:, signature:, timestamp:, secret:, tolerance: DEFAULT_TOLERANCE_SECONDS)
  begin
    timestamp_ms = Integer(timestamp)
  rescue ArgumentError, TypeError
    raise WebhookTimestampError, 'Invalid timestamp format'
  end

  now_ms = (Time.now.to_f * 1000).to_i
  age = (now_ms - timestamp_ms).abs / 1000.0
  if age > tolerance
    raise WebhookTimestampError, "Webhook timestamp is outside tolerance (#{age.to_i}s > #{tolerance}s)"
  end

  raw_signature = parse_signature(signature)
  expected_signature = compute_signature(payload, secret, timestamp, message_id)

  unless secure_compare(expected_signature, raw_signature)
    raise WebhookSignatureError, 'Invalid webhook signature'
  end

  begin
    data = JSON.parse(payload)
    WebhookEvent.build_from_hash(data)
  rescue JSON::ParserError => e
    raise WebhookSignatureError, "Invalid JSON payload: #{e.message}"
  end
end

.verify(payload:, message_id:, signature:, timestamp:, secret:, tolerance: DEFAULT_TOLERANCE_SECONDS) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/pingram/webhooks.rb', line 53

def verify(payload:, message_id:, signature:, timestamp:, secret:, tolerance: DEFAULT_TOLERANCE_SECONDS)
  construct_event(
    payload: payload,
    message_id: message_id,
    signature: signature,
    timestamp: timestamp,
    secret: secret,
    tolerance: tolerance
  )
end