@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 394 lines 12.8 KB
Raw
1 import * as crypto from 'node:crypto';
2 import * as fs from 'node:fs';
3 import * as path from 'node:path';
4 import { describe, it, expect, vi, beforeEach } from 'vitest';
5 import { Triggers } from '../../src/models/Triggers';
6 import ComposioClient from '@composio/client';
7 import { WebhookVersions } from '../../src/types/triggers.types';
8
9 // Mock dependencies
10 vi.mock('../../src/utils/logger');
11 vi.mock('../../src/telemetry/Telemetry', () => ({
12 telemetry: {
13 instrument: vi.fn(),
14 },
15 }));
16 vi.mock('../../src/services/pusher/Pusher');
17
18 // Create mock client
19 const createMockClient = () => ({
20 baseURL: 'https://api.composio.dev',
21 apiKey: 'test-api-key',
22 triggerInstances: {
23 listActive: vi.fn(),
24 upsert: vi.fn(),
25 manage: {
26 delete: vi.fn(),
27 update: vi.fn(),
28 },
29 },
30 triggersTypes: {
31 list: vi.fn(),
32 retrieve: vi.fn(),
33 retrieveEnum: vi.fn(),
34 },
35 connectedAccounts: {
36 list: vi.fn(),
37 },
38 });
39
40 /**
41 * Fixture type definition
42 */
43 interface WebhookFixture {
44 description: string;
45 capturedAt: string;
46 headers: {
47 'webhook-id': string;
48 'webhook-timestamp': string;
49 'webhook-signature': string;
50 };
51 payload: string;
52 testSecret: string;
53 expectedResult: {
54 version: string;
55 triggerSlug: string;
56 userId?: string;
57 connectedAccountId?: string;
58 triggerId?: string;
59 };
60 }
61
62 /**
63 * Golden signature test case
64 */
65 interface GoldenSignatureTestCase {
66 name: string;
67 id: string;
68 timestamp: string;
69 payload: string;
70 secret: string;
71 expectedSignature: string;
72 }
73
74 interface GoldenSignatures {
75 description: string;
76 algorithm: string;
77 format: string;
78 testCases: GoldenSignatureTestCase[];
79 }
80
81 /**
82 * Load all webhook fixtures from the fixtures directory
83 */
84 function loadFixtures(): WebhookFixture[] {
85 const fixturesDir = path.join(__dirname, '../fixtures/webhook');
86 const fixtureFiles = fs
87 .readdirSync(fixturesDir)
88 .filter(f => f.startsWith('v') && f.endsWith('.json') && !f.includes('golden'));
89
90 return fixtureFiles.map(file => {
91 const content = fs.readFileSync(path.join(fixturesDir, file), 'utf-8');
92 return JSON.parse(content) as WebhookFixture;
93 });
94 }
95
96 /**
97 * Load golden signatures for contract testing
98 */
99 function loadGoldenSignatures(): GoldenSignatures {
100 const fixturesDir = path.join(__dirname, '../fixtures/webhook');
101 const content = fs.readFileSync(path.join(fixturesDir, 'golden-signatures.json'), 'utf-8');
102 return JSON.parse(content) as GoldenSignatures;
103 }
104
105 /**
106 * Compute signature using the documented algorithm
107 */
108 function computeSignature(id: string, timestamp: string, payload: string, secret: string): string {
109 const toSign = `${id}.${timestamp}.${payload}`;
110 const signature = crypto.createHmac('sha256', secret).update(toSign, 'utf8').digest('base64');
111 return `v1,${signature}`;
112 }
113
114 describe('Triggers.verifyWebhook - Integration Tests', () => {
115 let triggers: Triggers<unknown>;
116 let mockClient: ReturnType<typeof createMockClient>;
117 const fixtures = loadFixtures();
118 const goldenSignatures = loadGoldenSignatures();
119
120 beforeEach(() => {
121 vi.clearAllMocks();
122 mockClient = createMockClient();
123 triggers = new Triggers(mockClient as unknown as ComposioClient);
124 });
125
126 describe('fixture-based verification', () => {
127 it.each(fixtures)('verifies $description', async fixture => {
128 const result = await triggers.verifyWebhook({
129 payload: fixture.payload,
130 signature: fixture.headers['webhook-signature'],
131 id: fixture.headers['webhook-id'],
132 timestamp: fixture.headers['webhook-timestamp'],
133 secret: fixture.testSecret,
134 tolerance: 0, // Disable timestamp validation for fixtures
135 });
136
137 expect(result.version).toBe(fixture.expectedResult.version);
138 expect(result.payload.triggerSlug).toBe(fixture.expectedResult.triggerSlug);
139
140 if (fixture.expectedResult.userId) {
141 expect(result.payload.userId).toBe(fixture.expectedResult.userId);
142 }
143
144 if (fixture.expectedResult.connectedAccountId) {
145 expect(result.payload.metadata.connectedAccount.id).toBe(
146 fixture.expectedResult.connectedAccountId
147 );
148 }
149
150 if (fixture.expectedResult.triggerId) {
151 expect(result.payload.id).toBe(fixture.expectedResult.triggerId);
152 }
153 });
154
155 it('detects correct version for V3 payload', async () => {
156 const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
157 if (!v3Fixture) {
158 throw new Error('V3 fixture not found');
159 }
160
161 const result = await triggers.verifyWebhook({
162 payload: v3Fixture.payload,
163 signature: v3Fixture.headers['webhook-signature'],
164 id: v3Fixture.headers['webhook-id'],
165 timestamp: v3Fixture.headers['webhook-timestamp'],
166 secret: v3Fixture.testSecret,
167 tolerance: 0,
168 });
169
170 expect(result.version).toBe(WebhookVersions.V3);
171 expect(result.rawPayload).toHaveProperty('type', 'composio.trigger.message');
172 expect(result.rawPayload).toHaveProperty('metadata');
173 });
174
175 it('detects correct version for V2 payload', async () => {
176 const v2Fixture = fixtures.find(f => f.expectedResult.version === 'V2');
177 if (!v2Fixture) {
178 throw new Error('V2 fixture not found');
179 }
180
181 const result = await triggers.verifyWebhook({
182 payload: v2Fixture.payload,
183 signature: v2Fixture.headers['webhook-signature'],
184 id: v2Fixture.headers['webhook-id'],
185 timestamp: v2Fixture.headers['webhook-timestamp'],
186 secret: v2Fixture.testSecret,
187 tolerance: 0,
188 });
189
190 expect(result.version).toBe(WebhookVersions.V2);
191 expect(result.rawPayload).toHaveProperty('type');
192 expect(result.rawPayload).toHaveProperty('data');
193 });
194
195 it('detects correct version for V1 payload', async () => {
196 const v1Fixture = fixtures.find(f => f.expectedResult.version === 'V1');
197 if (!v1Fixture) {
198 throw new Error('V1 fixture not found');
199 }
200
201 const result = await triggers.verifyWebhook({
202 payload: v1Fixture.payload,
203 signature: v1Fixture.headers['webhook-signature'],
204 id: v1Fixture.headers['webhook-id'],
205 timestamp: v1Fixture.headers['webhook-timestamp'],
206 secret: v1Fixture.testSecret,
207 tolerance: 0,
208 });
209
210 expect(result.version).toBe(WebhookVersions.V1);
211 expect(result.rawPayload).toHaveProperty('trigger_name');
212 expect(result.rawPayload).toHaveProperty('connection_id');
213 });
214 });
215
216 describe('golden signature contract tests', () => {
217 it.each(goldenSignatures.testCases)(
218 'produces identical signature for: $name',
219 async testCase => {
220 const computed = computeSignature(
221 testCase.id,
222 testCase.timestamp,
223 testCase.payload,
224 testCase.secret
225 );
226 expect(computed).toBe(testCase.expectedSignature);
227 }
228 );
229
230 it('algorithm matches documented format', () => {
231 expect(goldenSignatures.algorithm).toBe('HMAC-SHA256');
232 expect(goldenSignatures.format).toBe('v1,base64(HMAC-SHA256(id.timestamp.payload, secret))');
233 });
234 });
235
236 describe('signature algorithm validation', () => {
237 it('computes signature using id.timestamp.payload format', async () => {
238 const fixture = fixtures[0];
239 const expectedSignature = computeSignature(
240 fixture.headers['webhook-id'],
241 fixture.headers['webhook-timestamp'],
242 fixture.payload,
243 fixture.testSecret
244 );
245
246 expect(expectedSignature).toBe(fixture.headers['webhook-signature']);
247 });
248
249 it('rejects signature computed with wrong format (payload only)', async () => {
250 const fixture = fixtures[0];
251 // Wrong format: just payload
252 const wrongSignature =
253 'v1,' +
254 crypto
255 .createHmac('sha256', fixture.testSecret)
256 .update(fixture.payload, 'utf8')
257 .digest('base64');
258
259 await expect(
260 triggers.verifyWebhook({
261 payload: fixture.payload,
262 signature: wrongSignature,
263 id: fixture.headers['webhook-id'],
264 timestamp: fixture.headers['webhook-timestamp'],
265 secret: fixture.testSecret,
266 tolerance: 0,
267 })
268 ).rejects.toThrow('The signature provided is invalid');
269 });
270
271 it('rejects signature computed with wrong format (timestamp.payload)', async () => {
272 const fixture = fixtures[0];
273 // Wrong format: timestamp.payload (missing id)
274 const toSign = `${fixture.headers['webhook-timestamp']}.${fixture.payload}`;
275 const wrongSignature =
276 'v1,' +
277 crypto.createHmac('sha256', fixture.testSecret).update(toSign, 'utf8').digest('base64');
278
279 await expect(
280 triggers.verifyWebhook({
281 payload: fixture.payload,
282 signature: wrongSignature,
283 id: fixture.headers['webhook-id'],
284 timestamp: fixture.headers['webhook-timestamp'],
285 secret: fixture.testSecret,
286 tolerance: 0,
287 })
288 ).rejects.toThrow('The signature provided is invalid');
289 });
290 });
291
292 describe('payload structure validation', () => {
293 it('preserves exact JSON structure from fixture', async () => {
294 const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
295 if (!v3Fixture) throw new Error('V3 fixture not found');
296
297 const result = await triggers.verifyWebhook({
298 payload: v3Fixture.payload,
299 signature: v3Fixture.headers['webhook-signature'],
300 id: v3Fixture.headers['webhook-id'],
301 timestamp: v3Fixture.headers['webhook-timestamp'],
302 secret: v3Fixture.testSecret,
303 tolerance: 0,
304 });
305
306 const parsedPayload = JSON.parse(v3Fixture.payload);
307 expect(result.rawPayload).toEqual(parsedPayload);
308 });
309
310 it('normalizes V3 payload to IncomingTriggerPayload format', async () => {
311 const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
312 if (!v3Fixture) throw new Error('V3 fixture not found');
313
314 const result = await triggers.verifyWebhook({
315 payload: v3Fixture.payload,
316 signature: v3Fixture.headers['webhook-signature'],
317 id: v3Fixture.headers['webhook-id'],
318 timestamp: v3Fixture.headers['webhook-timestamp'],
319 secret: v3Fixture.testSecret,
320 tolerance: 0,
321 });
322
323 // Verify normalized payload has expected structure
324 expect(result.payload).toHaveProperty('id');
325 expect(result.payload).toHaveProperty('uuid');
326 expect(result.payload).toHaveProperty('triggerSlug');
327 expect(result.payload).toHaveProperty('toolkitSlug');
328 expect(result.payload).toHaveProperty('userId');
329 expect(result.payload).toHaveProperty('payload');
330 expect(result.payload).toHaveProperty('metadata');
331 expect(result.payload.metadata).toHaveProperty('connectedAccount');
332 });
333 });
334
335 describe('whitespace sensitivity', () => {
336 it('fails verification if whitespace in payload changes', async () => {
337 const fixture = fixtures[0];
338 // Add extra whitespace to payload
339 const modifiedPayload = fixture.payload.replace('{', '{ ');
340
341 await expect(
342 triggers.verifyWebhook({
343 payload: modifiedPayload,
344 signature: fixture.headers['webhook-signature'],
345 id: fixture.headers['webhook-id'],
346 timestamp: fixture.headers['webhook-timestamp'],
347 secret: fixture.testSecret,
348 tolerance: 0,
349 })
350 ).rejects.toThrow();
351 });
352
353 it('fails verification if payload is re-serialized', async () => {
354 const fixture = fixtures[0];
355 // Parse and re-serialize - may change whitespace/key order
356 const reserialized = JSON.stringify(JSON.parse(fixture.payload));
357
358 // Only test if re-serialization actually changed the payload
359 if (reserialized !== fixture.payload) {
360 await expect(
361 triggers.verifyWebhook({
362 payload: reserialized,
363 signature: fixture.headers['webhook-signature'],
364 id: fixture.headers['webhook-id'],
365 timestamp: fixture.headers['webhook-timestamp'],
366 secret: fixture.testSecret,
367 tolerance: 0,
368 })
369 ).rejects.toThrow();
370 }
371 });
372 });
373
374 describe('cross-fixture consistency', () => {
375 it('all fixtures use the same test secret', () => {
376 const secrets = new Set(fixtures.map(f => f.testSecret));
377 expect(secrets.size).toBe(1);
378 expect(secrets.has('test-webhook-secret-for-fixtures')).toBe(true);
379 });
380
381 it('all fixtures have unique webhook IDs', () => {
382 const ids = fixtures.map(f => f.headers['webhook-id']);
383 const uniqueIds = new Set(ids);
384 expect(uniqueIds.size).toBe(fixtures.length);
385 });
386
387 it('fixtures cover all supported versions', () => {
388 const versions = new Set(fixtures.map(f => f.expectedResult.version));
389 expect(versions.has('V1')).toBe(true);
390 expect(versions.has('V2')).toBe(true);
391 expect(versions.has('V3')).toBe(true);
392 });
393 });
394 });