Repository navigation
Expand file tree
/
Copy pathWebhookVerifier.java
More file actions
82 lines (76 loc) · 2.95 KB
/
Copy pathWebhookVerifier.java
File metadata and controls
82 lines (76 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/** Verifies Standard Webhooks signatures with the JDK only. */
public final class WebhookVerifier {
public static final class VerificationException extends Exception {
public VerificationException(String message) {
super(message);
}
}
private WebhookVerifier() {}
/**
* Returns normally when the delivery is authentic, otherwise throws VerificationException.
*
* @param secret signing secret, "whsec_<base64 key>"
* @param headers request headers (names matched case-insensitively)
* @param rawBody the exact bytes received, never a re-serialized object
* @param nowSeconds reference time as Unix seconds (use System.currentTimeMillis() / 1000)
*/
public static void verify(
String secret,
Map<String, String> headers,
byte[] rawBody,
long nowSeconds,
long toleranceSeconds)
throws VerificationException {
Map<String, String> lower = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
lower.putAll(headers);
String id = lower.get("webhook-id");
String timestamp = lower.get("webhook-timestamp");
String signatureHeader = lower.get("webhook-signature");
if (isEmpty(id) || isEmpty(timestamp) || isEmpty(signatureHeader)) {
throw new VerificationException(
"Missing webhook-id, webhook-timestamp or webhook-signature header");
}
if (!timestamp.matches("\\d{1,18}")) {
throw new VerificationException("Invalid webhook-timestamp");
}
if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > toleranceSeconds) {
throw new VerificationException("Timestamp outside the tolerance window");
}
byte[] expected;
try {
byte[] key = Base64.getDecoder().decode(secret.replaceFirst("^whsec_", ""));
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
expected = mac.doFinal(rawBody);
} catch (Exception e) {
throw new VerificationException("Cannot compute signature: " + e.getMessage());
}
// The header holds space-separated "v1,<base64>" entries. Any match is enough.
for (String entry : signatureHeader.split(" ")) {
String[] parts = entry.split(",", 2);
if (parts.length != 2 || !parts[0].equals("v1")) {
continue;
}
try {
byte[] candidate = Base64.getDecoder().decode(parts[1]);
if (MessageDigest.isEqual(candidate, expected)) {
return;
}
} catch (IllegalArgumentException ignored) {
// Not base64: try the next entry.
}
}
throw new VerificationException("No matching signature");
}
private static boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
}