|
| 1 | +package com.siftscience.utils; |
| 2 | + |
| 3 | +import org.apache.commons.codec.digest.HmacAlgorithms; |
| 4 | +import org.apache.commons.codec.digest.HmacUtils; |
| 5 | +import org.junit.Assert; |
| 6 | +import org.junit.Test; |
| 7 | + |
| 8 | +import static com.siftscience.utils.WebhookValidator.isValidWebhook; |
| 9 | + |
| 10 | +public class WebhookValidatorTest { |
| 11 | + |
| 12 | + @Test |
| 13 | + public void testWebhookValidation_sha1() { |
| 14 | + |
| 15 | + final String secretKey = "1d708fe409f22591"; |
| 16 | + final String requestBody = "{\n" + |
| 17 | + " \"entity\": {\n" + |
| 18 | + " \"type\": \"user\",\n" + |
| 19 | + " \"id\": \"USER123\"\n" + |
| 20 | + " },\n" + |
| 21 | + " \"decision\": {\n" + |
| 22 | + " \"id\": \"block_user_payment_abuse\"\n" + |
| 23 | + " },\n" + |
| 24 | + " \"time\": 1461963439151\n" + |
| 25 | + "}"; |
| 26 | + final String signature = "sha1=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secretKey).hmacHex(requestBody); |
| 27 | + |
| 28 | + Assert.assertTrue(isValidWebhook(signature, requestBody, secretKey)); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void testWebhookValidation_sha256() { |
| 33 | + |
| 34 | + final String secretKey = "1d708fe409f22591"; |
| 35 | + final String requestBody = "{\n" + |
| 36 | + " \"entity\": {\n" + |
| 37 | + " \"type\": \"user\",\n" + |
| 38 | + " \"id\": \"USER123\"\n" + |
| 39 | + " },\n" + |
| 40 | + " \"decision\": {\n" + |
| 41 | + " \"id\": \"block_user_payment_abuse\"\n" + |
| 42 | + " },\n" + |
| 43 | + " \"time\": 1461963439151\n" + |
| 44 | + "}"; |
| 45 | + final String signature = "sha256=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secretKey.getBytes()).hmacHex(requestBody); |
| 46 | + |
| 47 | + Assert.assertTrue(isValidWebhook(signature, requestBody, secretKey)); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + public void testWebhookValidationForInvalidSecretKey() { |
| 52 | + |
| 53 | + final String secretKey = "1d708fe409f22591"; |
| 54 | + final String requestBody = "{\n" + |
| 55 | + " \"entity\": {\n" + |
| 56 | + " \"type\": \"user\",\n" + |
| 57 | + " \"id\": \"USER123\"\n" + |
| 58 | + " },\n" + |
| 59 | + " \"decision\": {\n" + |
| 60 | + " \"id\": \"block_user_payment_abuse\"\n" + |
| 61 | + " },\n" + |
| 62 | + " \"time\": 1461963439151\n" + |
| 63 | + "}"; |
| 64 | + final String signature = "sha1=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secretKey.getBytes()).hmacHex(requestBody); |
| 65 | + |
| 66 | + Assert.assertFalse(isValidWebhook(signature, requestBody, "invalid key")); |
| 67 | + } |
| 68 | +} |
0 commit comments