Repository navigation
Expand file tree
/
Copy pathWebhookTest.java
More file actions
537 lines (501 loc) · 23.3 KB
/
Copy pathWebhookTest.java
File metadata and controls
537 lines (501 loc) · 23.3 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
// Code generated by GetStream internal OpenAPI code generator. DO NOT EDIT.
package io.getstream;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class WebhookTest {
private static final String TEST_SECRET = "test-webhook-secret";
private static final String TEST_BODY = "{\"type\":\"test.event\"}";
private static String computeSignature(String body, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey =
new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKey);
byte[] hash = mac.doFinal(body.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
@Test
public void testVerifySignatureValid() throws Exception {
String signature = computeSignature(TEST_BODY, TEST_SECRET);
assertTrue(Webhook.verifySignature(TEST_BODY, signature, TEST_SECRET));
}
@Test
public void testVerifySignatureWrongSignature() {
assertFalse(Webhook.verifySignature(TEST_BODY, "invalidsignature", TEST_SECRET));
}
@Test
public void testVerifySignatureTamperedBody() throws Exception {
String signature = computeSignature(TEST_BODY, TEST_SECRET);
assertFalse(Webhook.verifySignature("{\"type\":\"tampered\"}", signature, TEST_SECRET));
}
@Test
public void testVerifySignatureWrongSecret() throws Exception {
String signature = computeSignature(TEST_BODY, TEST_SECRET);
assertFalse(Webhook.verifySignature(TEST_BODY, signature, "wrong-secret"));
}
@Test
public void testVerifySignatureEmptySignature() {
assertFalse(Webhook.verifySignature(TEST_BODY, "", TEST_SECRET));
}
@Test
public void testVerifySignatureEmptyOrNullSecretOrSignature() {
assertFalse(Webhook.verifySignature(TEST_BODY, "abc", ""));
assertFalse(Webhook.verifySignature(TEST_BODY, "abc", null));
assertFalse(Webhook.verifySignature(TEST_BODY, null, TEST_SECRET));
}
@Test
public void testGetEventTypeValid() {
assertEquals("message.new", Webhook.getEventType("{\"type\":\"message.new\"}"));
}
@Test
public void testGetEventTypeMissingField() {
assertNull(Webhook.getEventType("{\"foo\":\"bar\"}"));
}
@Test
public void testGetEventTypeInvalidJson() {
assertNull(Webhook.getEventType("not json"));
}
@Test
public void testGetEventTypeEmptyObject() {
assertNull(Webhook.getEventType("{}"));
}
@ParameterizedTest
@CsvSource({
"*, CustomEvent",
"appeal.accepted, AppealAcceptedEvent",
"appeal.created, AppealCreatedEvent",
"appeal.rejected, AppealRejectedEvent",
"call.accepted, CallAcceptedEvent",
"call.blocked_user, BlockedUserEvent",
"call.closed_caption, ClosedCaptionEvent",
"call.closed_captions_failed, CallClosedCaptionsFailedEvent",
"call.closed_captions_started, CallClosedCaptionsStartedEvent",
"call.closed_captions_stopped, CallClosedCaptionsStoppedEvent",
"call.created, CallCreatedEvent",
"call.deleted, CallDeletedEvent",
"call.dtmf, CallDTMFEvent",
"call.ended, CallEndedEvent",
"call.frame_recording_failed, CallFrameRecordingFailedEvent",
"call.frame_recording_ready, CallFrameRecordingFrameReadyEvent",
"call.frame_recording_started, CallFrameRecordingStartedEvent",
"call.frame_recording_stopped, CallFrameRecordingStoppedEvent",
"call.hls_broadcasting_failed, CallHLSBroadcastingFailedEvent",
"call.hls_broadcasting_started, CallHLSBroadcastingStartedEvent",
"call.hls_broadcasting_stopped, CallHLSBroadcastingStoppedEvent",
"call.kicked_user, KickedUserEvent",
"call.live_started, CallLiveStartedEvent",
"call.member_added, CallMemberAddedEvent",
"call.member_removed, CallMemberRemovedEvent",
"call.member_updated, CallMemberUpdatedEvent",
"call.member_updated_permission, CallMemberUpdatedPermissionEvent",
"call.missed, CallMissedEvent",
"call.moderation_blur, CallModerationBlurEvent",
"call.moderation_warning, CallModerationWarningEvent",
"call.notification, CallNotificationEvent",
"call.permission_request, PermissionRequestEvent",
"call.permissions_updated, UpdatedCallPermissionsEvent",
"call.reaction_new, CallReactionEvent",
"call.recording_failed, CallRecordingFailedEvent",
"call.recording_ready, CallRecordingReadyEvent",
"call.recording_started, CallRecordingStartedEvent",
"call.recording_stopped, CallRecordingStoppedEvent",
"call.rejected, CallRejectedEvent",
"call.ring, CallRingEvent",
"call.ring_settled, CallRingSettledEvent",
"call.rtmp_broadcast_failed, CallRtmpBroadcastFailedEvent",
"call.rtmp_broadcast_started, CallRtmpBroadcastStartedEvent",
"call.rtmp_broadcast_stopped, CallRtmpBroadcastStoppedEvent",
"call.session_ended, CallSessionEndedEvent",
"call.session_participant_count_updated, CallSessionParticipantCountsUpdatedEvent",
"call.session_participant_joined, CallSessionParticipantJoinedEvent",
"call.session_participant_left, CallSessionParticipantLeftEvent",
"call.session_started, CallSessionStartedEvent",
"call.stats_report_ready, CallStatsReportReadyEvent",
"call.transcription_failed, CallTranscriptionFailedEvent",
"call.transcription_ready, CallTranscriptionReadyEvent",
"call.transcription_started, CallTranscriptionStartedEvent",
"call.transcription_stopped, CallTranscriptionStoppedEvent",
"call.unblocked_user, UnblockedUserEvent",
"call.updated, CallUpdatedEvent",
"call.user_feedback_submitted, CallUserFeedbackSubmittedEvent",
"call.user_muted, CallUserMutedEvent",
"campaign.completed, CampaignCompletedEvent",
"campaign.started, CampaignStartedEvent",
"channel.created, ChannelCreatedEvent",
"channel.deleted, ChannelDeletedEvent",
"channel.forked, ChannelForkedEvent",
"channel.frozen, ChannelFrozenEvent",
"channel.hidden, ChannelHiddenEvent",
"channel.max_streak_changed, MaxStreakChangedEvent",
"channel.muted, ChannelMutedEvent",
"channel.rewound, ChannelRewoundEvent",
"channel.truncated, ChannelTruncatedEvent",
"channel.unfrozen, ChannelUnFrozenEvent",
"channel.unmuted, ChannelUnmutedEvent",
"channel.updated, ChannelUpdatedEvent",
"channel.visible, ChannelVisibleEvent",
"channel_batch_update.completed, ChannelBatchCompletedEvent",
"channel_batch_update.started, ChannelBatchStartedEvent",
"custom, CustomVideoEvent",
"export.bulk_image_moderation.error, AsyncExportErrorEvent",
"export.bulk_image_moderation.success, AsyncBulkImageModerationEvent",
"export.channels.error, AsyncExportErrorEvent",
"export.channels.success, AsyncExportChannelsEvent",
"export.label_results.error, AsyncExportErrorEvent",
"export.label_results.success, AsyncExportLabelResultsEvent",
"export.moderation_logs.error, AsyncExportErrorEvent",
"export.moderation_logs.success, AsyncExportModerationLogsEvent",
"export.review_queue.error, AsyncExportErrorEvent",
"export.review_queue.success, AsyncExportReviewQueueEvent",
"export.users.error, AsyncExportErrorEvent",
"export.users.success, AsyncExportUsersEvent",
"feeds.activity.added, ActivityAddedEvent",
"feeds.activity.deleted, ActivityDeletedEvent",
"feeds.activity.feedback, ActivityFeedbackEvent",
"feeds.activity.marked, ActivityMarkEvent",
"feeds.activity.pinned, ActivityPinnedEvent",
"feeds.activity.reaction.added, ActivityReactionAddedEvent",
"feeds.activity.reaction.deleted, ActivityReactionDeletedEvent",
"feeds.activity.reaction.updated, ActivityReactionUpdatedEvent",
"feeds.activity.removed_from_feed, ActivityRemovedFromFeedEvent",
"feeds.activity.restored, ActivityRestoredEvent",
"feeds.activity.unpinned, ActivityUnpinnedEvent",
"feeds.activity.updated, ActivityUpdatedEvent",
"feeds.bookmark.added, BookmarkAddedEvent",
"feeds.bookmark.deleted, BookmarkDeletedEvent",
"feeds.bookmark.updated, BookmarkUpdatedEvent",
"feeds.bookmark_folder.deleted, BookmarkFolderDeletedEvent",
"feeds.bookmark_folder.updated, BookmarkFolderUpdatedEvent",
"feeds.comment.added, CommentAddedEvent",
"feeds.comment.deleted, CommentDeletedEvent",
"feeds.comment.feedback, CommentFeedbackEvent",
"feeds.comment.reaction.added, CommentReactionAddedEvent",
"feeds.comment.reaction.deleted, CommentReactionDeletedEvent",
"feeds.comment.reaction.updated, CommentReactionUpdatedEvent",
"feeds.comment.restored, CommentRestoredEvent",
"feeds.comment.updated, CommentUpdatedEvent",
"feeds.export.error, AsyncExportErrorEvent",
"feeds.export.success, AsyncExportFeedsSuccessEvent",
"feeds.feed.created, FeedCreatedEvent",
"feeds.feed.deleted, FeedDeletedEvent",
"feeds.feed.updated, FeedUpdatedEvent",
"feeds.feed_group.changed, FeedGroupChangedEvent",
"feeds.feed_group.deleted, FeedGroupDeletedEvent",
"feeds.feed_group.restored, FeedGroupRestoredEvent",
"feeds.feed_member.added, FeedMemberAddedEvent",
"feeds.feed_member.removed, FeedMemberRemovedEvent",
"feeds.feed_member.updated, FeedMemberUpdatedEvent",
"feeds.follow.created, FollowCreatedEvent",
"feeds.follow.deleted, FollowDeletedEvent",
"feeds.follow.updated, FollowUpdatedEvent",
"feeds.notification_feed.updated, NotificationFeedUpdatedEvent",
"feeds.scheduled_activity.failed, ScheduledActivityFailedEvent",
"feeds.scheduled_activity.published, ScheduledActivityPublishedEvent",
"feeds.stories_feed.updated, StoriesFeedUpdatedEvent",
"flag.updated, FlagUpdatedEvent",
"import.error, AsyncImportErrorEvent",
"import.success, AsyncImportSuccessEvent",
"ingress.error, IngressErrorEvent",
"ingress.started, IngressStartedEvent",
"ingress.stopped, IngressStoppedEvent",
"ingress.stream_key.rejected, IngressStreamKeyRejectedEvent",
"member.added, MemberAddedEvent",
"member.removed, MemberRemovedEvent",
"member.updated, MemberUpdatedEvent",
"message.deleted, MessageDeletedEvent",
"message.flagged, MessageFlaggedEvent",
"message.new, MessageNewEvent",
"message.pending, PendingMessageEvent",
"message.read, MessageReadEvent",
"message.schema_violation, MessageSchemaViolationEvent",
"message.unblocked, MessageUnblockedEvent",
"message.undeleted, MessageUndeletedEvent",
"message.updated, MessageUpdatedEvent",
"moderation.analysis.failed, ModerationAnalysisFailedEvent",
"moderation.custom_action, ModerationCustomActionEvent",
"moderation.flagged, ModerationFlaggedEvent",
"moderation.image_analysis.complete, ModerationImageAnalysisCompleteEvent",
"moderation.mark_reviewed, ModerationMarkReviewedEvent",
"moderation.text_analysis.complete, ModerationTextAnalysisCompleteEvent",
"moderation_check.completed, ModerationCheckCompletedEvent",
"moderation_rule.triggered, ModerationRulesTriggeredEvent",
"notification.mark_unread, NotificationMarkUnreadEvent",
"notification.reminder_due, ReminderNotificationEvent",
"notification.thread_message_new, NotificationThreadMessageNewEvent",
"poll.closed, PollClosedEvent",
"poll.deleted, PollDeletedEvent",
"poll.updated, PollUpdatedEvent",
"poll.vote_casted, PollVoteCastedEvent",
"poll.vote_changed, PollVoteChangedEvent",
"poll.vote_removed, PollVoteRemovedEvent",
"reaction.deleted, ReactionDeletedEvent",
"reaction.new, ReactionNewEvent",
"reaction.schema_violation, ReactionSchemaViolationEvent",
"reaction.updated, ReactionUpdatedEvent",
"reminder.created, ReminderCreatedEvent",
"reminder.deleted, ReminderDeletedEvent",
"reminder.updated, ReminderUpdatedEvent",
"review_queue_item.new, ReviewQueueItemNewEvent",
"review_queue_item.updated, ReviewQueueItemUpdatedEvent",
"scheduled_message.failed, ScheduledMessageFailedEvent",
"scheduled_message.sent, ScheduledMessageSentEvent",
"thread.updated, ThreadUpdatedEvent",
"user.banned, UserBannedEvent",
"user.claimed, UserClaimedEvent",
"user.deactivated, UserDeactivatedEvent",
"user.deleted, UserDeletedEvent",
"user.flagged, UserFlaggedEvent",
"user.messages.deleted, UserMessagesDeletedEvent",
"user.muted, UserMutedEvent",
"user.reactivated, UserReactivatedEvent",
"user.unbanned, UserUnbannedEvent",
"user.unmuted, UserUnmutedEvent",
"user.unread_message_reminder, UserUnreadReminderEvent",
"user.updated, UserUpdatedEvent",
"user_group.created, UserGroupCreatedEvent",
"user_group.deleted, UserGroupDeletedEvent",
"user_group.member_added, UserGroupMemberAddedEvent",
"user_group.member_removed, UserGroupMemberRemovedEvent",
"user_group.updated, UserGroupUpdatedEvent",
})
public void testParseWebhookEvent(String eventType, String expectedClassName)
throws Webhook.InvalidWebhookError {
String payload = "{\"type\":\"" + eventType + "\"}";
Object event = Webhook.parseWebhookEvent(payload);
assertNotNull(event);
assertEquals(expectedClassName, event.getClass().getSimpleName());
}
@Test
public void testParseWebhookEventUnknownType() {
assertThrows(
Webhook.InvalidWebhookError.class,
() -> {
Webhook.parseWebhookEvent("{\"type\":\"unknown.event\"}");
});
}
@Test
public void testParseWebhookEventMissingType() {
assertThrows(
Webhook.InvalidWebhookError.class,
() -> {
Webhook.parseWebhookEvent("{\"foo\":\"bar\"}");
});
}
@Test
public void testParseWebhookEventInvalidJson() {
assertThrows(
Webhook.InvalidWebhookError.class,
() -> {
Webhook.parseWebhookEvent("not json");
});
}
// -----------------------------------------------------------------------
// Conformance fixture suite (CHA-2961). The fixture set is generated by
// chat/'s `build/openapi generate-webhook-fixtures` subcommand;
// the SDK's generate.sh copies it into src/test/resources/fixtures/webhooks/
// at codegen time.
// -----------------------------------------------------------------------
private static final String CANONICAL_TEST_SECRET = "test_secret_do_not_use_in_production";
private static final Path FIXTURE_ROOT =
Paths.get("src", "test", "resources", "fixtures", "webhooks");
@org.junit.jupiter.api.Test
void webhookConformanceFixturesPresent() {
org.junit.jupiter.api.Assertions.assertTrue(
java.nio.file.Files.isDirectory(FIXTURE_ROOT),
"Webhook conformance fixtures missing at " + FIXTURE_ROOT + ", run generate.sh");
}
@TestFactory
Collection<DynamicTest> webhookConformanceHappy() throws IOException {
if (!Files.isDirectory(FIXTURE_ROOT)) {
return Collections.emptyList();
}
List<DynamicTest> tests = new ArrayList<>();
try (Stream<Path> stream = Files.list(FIXTURE_ROOT)) {
List<Path> dirs = new ArrayList<>();
stream
.filter(Files::isDirectory)
.filter(p -> !p.getFileName().toString().equals("_invalid"))
.forEach(dirs::add);
Collections.sort(dirs);
for (Path dir : dirs) {
String name = dir.getFileName().toString();
tests.add(
DynamicTest.dynamicTest(
name,
() -> {
byte[] body = Files.readAllBytes(dir.resolve("body.json"));
byte[] bodyGz = Files.readAllBytes(dir.resolve("body.gz"));
String sqsCompressed = Files.readString(dir.resolve("sqs_body.txt")).trim();
String sqsRaw = Files.readString(dir.resolve("sqs_body_uncompressed.txt")).trim();
String sns = Files.readString(dir.resolve("sns_notification.txt")).trim();
String sig = Files.readString(dir.resolve("signature.txt")).trim();
assertTrue(Webhook.verifySignature(body, sig, CANONICAL_TEST_SECRET));
assertNotNull(Webhook.parseEvent(body));
assertNotNull(Webhook.verifyAndParseWebhook(body, sig, CANONICAL_TEST_SECRET));
assertNotNull(Webhook.verifyAndParseWebhook(bodyGz, sig, CANONICAL_TEST_SECRET));
assertNotNull(Webhook.parseSqs(sqsCompressed));
assertNotNull(Webhook.parseSqs(sqsRaw));
assertNotNull(Webhook.parseSns(sns));
assertNotNull(Webhook.verifyAndParseSns(sns, CANONICAL_TEST_SECRET));
}));
}
}
return tests;
}
@Test
void webhookConformanceTamperedBody() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("tampered_body");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.json"));
String sig = Files.readString(dir.resolve("signature.txt")).trim();
Webhook.InvalidWebhookError ex =
assertThrows(
Webhook.InvalidWebhookError.class,
() -> Webhook.verifyAndParseWebhook(body, sig, CANONICAL_TEST_SECRET));
assertTrue(
ex.getMessage().contains(Webhook.InvalidWebhookError.SIGNATURE_MISMATCH),
"expected '"
+ Webhook.InvalidWebhookError.SIGNATURE_MISMATCH
+ "' in message, got: "
+ ex.getMessage());
}
@Test
void webhookConformanceUnknownType() throws Exception {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("unknown_type");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.json"));
Object result = Webhook.parseEvent(body);
assertTrue(result instanceof Webhook.UnknownEvent);
assertEquals("totally.made.up", ((Webhook.UnknownEvent) result).getType());
}
@Test
void webhookConformanceMissingType() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("missing_type");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.json"));
Webhook.InvalidWebhookError ex =
assertThrows(Webhook.InvalidWebhookError.class, () -> Webhook.parseEvent(body));
assertTrue(
ex.getMessage().contains("missing 'type'"),
"expected \"missing 'type'\" in message, got: " + ex.getMessage());
}
@Test
void webhookConformanceMalformedJson() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("malformed_json");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.json"));
Webhook.InvalidWebhookError ex =
assertThrows(Webhook.InvalidWebhookError.class, () -> Webhook.parseEvent(body));
assertTrue(
ex.getMessage().contains("failed to parse webhook payload"),
"expected 'failed to parse webhook payload' in message, got: " + ex.getMessage());
}
@Test
void webhookConformanceEmptyBody() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("empty_body");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.json"));
Webhook.InvalidWebhookError ex =
assertThrows(Webhook.InvalidWebhookError.class, () -> Webhook.parseEvent(body));
assertTrue(
ex.getMessage().contains("must not be empty"),
"expected 'must not be empty' in message, got: " + ex.getMessage());
}
@Test
void webhookConformanceBadCompression() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("bad_compression");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.gz"));
String sig = Files.readString(dir.resolve("signature.txt")).trim();
Webhook.InvalidWebhookError ex =
assertThrows(
Webhook.InvalidWebhookError.class,
() -> Webhook.verifyAndParseWebhook(body, sig, CANONICAL_TEST_SECRET));
assertTrue(
ex.getMessage().contains(Webhook.InvalidWebhookError.GZIP_FAILED),
"expected '"
+ Webhook.InvalidWebhookError.GZIP_FAILED
+ "' in message, got: "
+ ex.getMessage());
}
@Test
void webhookConformanceOversizedCompression() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("oversized_compression");
if (!Files.exists(dir)) return;
byte[] body = Files.readAllBytes(dir.resolve("body.gz"));
String sig = Files.readString(dir.resolve("signature.txt")).trim();
Webhook.InvalidWebhookError ex =
assertThrows(
Webhook.InvalidWebhookError.class,
() -> Webhook.verifyAndParseWebhook(body, sig, CANONICAL_TEST_SECRET));
assertTrue(
ex.getMessage().contains("payload exceeds"),
"expected 'payload exceeds' in message, got: " + ex.getMessage());
}
@Test
void webhookConformanceBadBase64() throws IOException {
// Per CHA-3071 wire format: decodeSqsPayload falls back to raw bytes when
// base64 decoding fails (uncompressed wire format). For input that is
// neither valid base64 nor valid JSON nor gzip-prefixed, parseSqs still
// throws InvalidWebhookError, just down the chain at JSON parsing.
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("bad_base64");
if (!Files.exists(dir)) return;
String msg = Files.readString(dir.resolve("sqs_body.txt")).trim();
assertThrows(Webhook.InvalidWebhookError.class, () -> Webhook.parseSqs(msg));
}
@Test
void webhookConformanceBadSnsEnvelope() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("bad_sns_envelope");
if (!Files.exists(dir)) return;
// Fix #4: bad_sns_envelope (non-envelope JSON) is now treated as a
// pre-extracted Message string and flows through the SQS path,
// surfacing as a downstream parse failure rather than SNS-specific.
// Still InvalidWebhookError.
String notif = Files.readString(dir.resolve("sns_notification.txt")).trim();
assertThrows(Webhook.InvalidWebhookError.class, () -> Webhook.parseSns(notif));
}
@Test
void webhookConformanceVerifyAndParseSnsRejectsForgeries() throws IOException {
Path dir = FIXTURE_ROOT.resolve("_invalid").resolve("tampered_body");
if (!Files.exists(dir)) return;
String tampered = Files.readString(dir.resolve("sns_notification.txt")).trim();
String bareMessage = Files.readString(dir.resolve("sqs_body.txt")).trim();
String unsigned = "{\"Type\":\"Notification\",\"Message\":\"" + bareMessage + "\"}";
Webhook.InvalidWebhookError ex =
assertThrows(
Webhook.InvalidWebhookError.class,
() -> Webhook.verifyAndParseSns(tampered, CANONICAL_TEST_SECRET));
assertTrue(
ex.getMessage().contains(Webhook.InvalidWebhookError.SIGNATURE_MISMATCH), ex.getMessage());
ex =
assertThrows(
Webhook.InvalidWebhookError.class,
() -> Webhook.verifyAndParseSns(unsigned, CANONICAL_TEST_SECRET));
assertTrue(
ex.getMessage().contains(Webhook.InvalidWebhookError.SIGNATURE_MISMATCH), ex.getMessage());
ex =
assertThrows(
Webhook.InvalidWebhookError.class,
() -> Webhook.verifyAndParseSns(bareMessage, CANONICAL_TEST_SECRET));
assertTrue(ex.getMessage().contains("invalid SNS envelope"), ex.getMessage());
}
}