11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# File 'lib/increase/webhook/signature.rb', line 11
def self.verify?(payload:, signature_header:, secret:, scheme: DEFAULT_SCHEME, time_tolerance: DEFAULT_TIME_TOLERANCE)
sig_error = ->(msg) do
WebhookSignatureVerificationError.new(msg, signature_header: , payload: payload)
end
sig_values = .split(",").map { |pair| pair.split("=") }.to_h
t = sig_values["t"] sig = sig_values[scheme]
raise sig_error.call("No timestamp found in signature header") if t.nil?
raise sig_error.call("No signature found with scheme #{scheme} in signature header") if sig.nil?
expected_sig = compute_signature(timestamp: t, payload: payload, secret: secret)
matches = Util.secure_compare(expected_sig, sig)
raise sig_error.call("Signature mismatch") unless matches
if time_tolerance > 0
begin
timestamp = DateTime.parse(t)
now = DateTime.now
diff = (now - timestamp) * 24 * 60 * 60
if diff > time_tolerance || diff < 0
raise sig_error.call("Timestamp outside of the tolerance zone")
end
rescue Date::Error
raise sig_error.call("Invalid timestamp in signature header: #{t}")
end
end
true
end
|