Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/main/java/com/gr4vy/sdk/Webhooks.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.gr4vy.sdk;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;

Expand Down Expand Up @@ -69,7 +70,11 @@ public static void verifyWebhook(String payload,
throw new IllegalArgumentException("Invalid secret");
}

if(!signatures.contains(expectedSignature)) {
// Compare in constant time, so the check doesn't leak how much of one matched.
byte[] expected = expectedSignature.getBytes(StandardCharsets.UTF_8);
boolean matched = signatures.stream()
.anyMatch(signature -> MessageDigest.isEqual(expected, signature.getBytes(StandardCharsets.UTF_8)));
if(!matched) {
throw new IllegalArgumentException("No matching signature found");
}
}
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/com/gr4vy/sdk/WebhooksTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,23 @@ void testVerifyWebhookMissingTimestampHeader() {

assertEquals(thrown.getMessage(), "Missing header values");
}

@Test
void testVerifyWebhookAcceptsAValidSignatureInAnyPosition() {
String header = "other,78aca0c78005107a654a957b8566fa6e0e5e06aea92d7da72a6da9e5a690d013";

assertDoesNotThrow(() -> Webhooks.verifyWebhook(payload, secret, header, 0, timestampHeader));
}

@Test
void testVerifyWebhookRejectsANearlyMatchingSignature() {
String header = "78aca0c78005107a654a957b8566fa6e0e5e06aea92d7da72a6da9e5a690d014";

IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> Webhooks.verifyWebhook(payload, secret, header, 0, timestampHeader)
);

assertEquals(thrown.getMessage(), "No matching signature found");
}
}
Loading