forked from Streampay-Org/StreamPay-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.test.ts
More file actions
647 lines (505 loc) · 23.4 KB
/
Copy pathmiddleware.test.ts
File metadata and controls
647 lines (505 loc) · 23.4 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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/** @jest-environment node */
describe('CORS middleware', () => {
let middleware: any;
beforeEach(async () => {
jest.resetModules();
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'production';
(process.env as any).ALLOWED_ORIGINS = 'https://allowed.example.com';
const imported = await import('./middleware');
middleware = imported.middleware;
});
afterEach(() => {
delete (process.env as any).STELLAR_NETWORK;
delete (process.env as any).JWT_SECRET;
delete (process.env as any).NODE_ENV;
delete (process.env as any).ALLOWED_ORIGINS;
});
it('adds CORS headers for allowed origins on normal requests', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { origin: 'https://allowed.example.com' },
});
const response = await middleware(request as any);
expect(response.headers.get('access-control-allow-origin')).toBe('https://allowed.example.com');
expect(response.headers.get('vary')).toBe('Origin');
});
it('rejects disallowed origin with 403 and error envelope', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { origin: 'https://evil.example.com' },
});
const response = await middleware(request as any);
expect(response.status).toBe(403);
const body = await response.json();
expect(body).toMatchObject({
error: {
code: 'CORS_ORIGIN_DISALLOWED',
message: "Origin 'https://evil.example.com' is not allowed.",
request_id: expect.any(String),
},
});
expect(response.headers.get('x-request-fingerprint')).toMatch(/^[a-f0-9]{64}$/);
});
it('returns a preflight response with explicit headers for allowed origins', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'OPTIONS',
headers: {
origin: 'https://allowed.example.com',
'access-control-request-method': 'POST',
},
});
const response = await middleware(request as any);
expect(response.status).toBe(204);
expect(response.headers.get('access-control-allow-origin')).toBe('https://allowed.example.com');
expect(response.headers.get('access-control-allow-methods')).toContain('GET');
expect(response.headers.get('access-control-allow-headers')).toContain('authorization');
expect(response.headers.get('access-control-max-age')).toBe('600');
});
it('rejects disallowed origin OPTIONS with 403 and error envelope', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'OPTIONS',
headers: {
origin: 'https://evil.example.com',
'access-control-request-method': 'POST',
},
});
const response = await middleware(request as any);
expect(response.status).toBe(403);
const body = await response.json();
expect(body).toMatchObject({
error: {
code: 'CORS_ORIGIN_DISALLOWED',
request_id: expect.any(String),
},
});
});
it('passes through requests without an origin header', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
});
const response = await middleware(request as any);
expect(response.status).not.toBe(403);
expect(response.headers.get('access-control-allow-origin')).toBeNull();
});
it('passes through OPTIONS requests without an origin header', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'OPTIONS',
});
const response = await middleware(request as any);
expect(response.status).toBe(204);
expect(response.headers.get('access-control-allow-origin')).toBeNull();
});
it('rejects malformed origin header with 403', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { origin: 'not a valid url with spaces' },
});
const response = await middleware(request as any);
expect(response.status).toBe(403);
const body = await response.json();
expect(body.error.code).toBe('CORS_ORIGIN_DISALLOWED');
});
it('includes x-request-id in rejection error envelope when present', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: {
origin: 'https://evil.example.com',
'x-request-id': 'req_cors_test_123',
},
});
const response = await middleware(request as any);
const body = await response.json();
expect(body.error.request_id).toBe('req_cors_test_123');
});
});
// =============================================================================
// CORS wildcard allowlist (non-production)
// =============================================================================
describe('CORS wildcard allowlist (non-production)', () => {
let middleware: any;
beforeEach(async () => {
jest.resetModules();
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'development';
(process.env as any).ALLOWED_ORIGINS = '*';
const imported = await import('./middleware');
middleware = imported.middleware;
});
afterEach(() => {
delete (process.env as any).STELLAR_NETWORK;
delete (process.env as any).JWT_SECRET;
delete (process.env as any).NODE_ENV;
delete (process.env as any).ALLOWED_ORIGINS;
});
it('allows any origin when wildcard is configured in non-production', async () => {
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { origin: 'https://any-origin.example.com' },
});
const response = await middleware(request as any);
expect(response.headers.get('access-control-allow-origin')).toBe('https://any-origin.example.com');
expect(response.headers.get('vary')).toBe('Origin');
});
});
// =============================================================================
// Request body size cap
// =============================================================================
describe('canary middleware', () => {
let middleware: any;
beforeEach(async () => {
jest.resetModules();
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'production';
(process.env as any).ALLOWED_ORIGINS = 'https://allowed.example.com';
delete (process.env as any).CANARY_PERCENTAGE;
const imported = await import('./middleware');
middleware = imported.middleware;
});
afterEach(() => {
delete (process.env as any).STELLAR_NETWORK;
delete (process.env as any).JWT_SECRET;
delete (process.env as any).NODE_ENV;
delete (process.env as any).ALLOWED_ORIGINS;
delete (process.env as any).CANARY_PERCENTAGE;
});
it('does not emit X-Canary when percentage is 0', async () => {
(process.env as any).CANARY_PERCENTAGE = '0';
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { 'x-tenant-id': 'tenant-123' },
});
const response = await middleware(request as any);
expect(response.headers.get('x-canary')).toBeNull();
});
it('emits X-Canary for requests when percentage is 100', async () => {
(process.env as any).CANARY_PERCENTAGE = '100';
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { 'x-tenant-id': 'tenant-123' },
});
const response = await middleware(request as any);
expect(response.headers.get('x-canary')).toBe('true');
});
it('uses a deterministic hash derived from the tenant id', async () => {
(process.env as any).CANARY_PERCENTAGE = '50';
const requestA = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { 'x-tenant-id': 'tenant-123' },
});
const requestB = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: { 'x-tenant-id': 'tenant-123' },
});
const responseA = await middleware(requestA as any);
const responseB = await middleware(requestB as any);
expect(responseA.headers.get('x-canary')).toBe(responseB.headers.get('x-canary'));
});
});
describe('request size cap middleware', () => {
/** The default cap enforced by the middleware (256 KB). */
const DEFAULT_CAP = 256 * 1024; // 262 144 bytes
let middleware: any;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Build a synthetic NextRequest-compatible object aimed at a v2 streams path.
* We construct the URL with `localhost` as the host because NextURL (used by
* the Edge runtime) requires an absolute URL.
*/
function makeRequest(
path: string,
method: string,
contentLength: number | null,
extra: Record<string, string> = {},
): Request {
const headers: Record<string, string> = { ...extra };
if (contentLength !== null) {
headers['content-length'] = String(contentLength);
}
return new Request(`http://localhost${path}`, { method, headers });
}
// ---------------------------------------------------------------------------
// Setup / teardown
// ---------------------------------------------------------------------------
beforeEach(async () => {
jest.resetModules();
delete (process.env as any).MAX_STREAM_BODY_BYTES;
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'production';
(process.env as any).ALLOWED_ORIGINS = 'https://allowed.example.com';
const imported = await import('./middleware');
middleware = imported.middleware;
});
afterEach(() => {
delete (process.env as any).STELLAR_NETWORK;
delete (process.env as any).JWT_SECRET;
delete (process.env as any).NODE_ENV;
delete (process.env as any).ALLOWED_ORIGINS;
delete (process.env as any).MAX_STREAM_BODY_BYTES;
});
// ---------------------------------------------------------------------------
// Core enforcement
// ---------------------------------------------------------------------------
it('returns 413 when Content-Length exceeds the default 256 KB cap on POST /api/v2/streams', async () => {
const request = makeRequest('/api/v2/streams', 'POST', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('returns 413 when Content-Length exceeds the cap on PUT /api/v2/streams/{id}', async () => {
const request = makeRequest('/api/v2/streams/stream-abc-123', 'PUT', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('returns 413 when Content-Length exceeds the cap on PATCH /api/v2/streams/{id}/pause', async () => {
const request = makeRequest('/api/v2/streams/stream-abc-123/pause', 'PATCH', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('passes through when Content-Length is exactly at the 256 KB cap', async () => {
const request = makeRequest('/api/v2/streams', 'POST', DEFAULT_CAP);
const response = await middleware(request as any);
// Should NOT be a 413 — at-limit is allowed.
expect(response.status).not.toBe(413);
});
it('passes through when Content-Length is below the cap', async () => {
const request = makeRequest('/api/v2/streams', 'POST', 1024); // 1 KB
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
});
// ---------------------------------------------------------------------------
// Missing / malformed Content-Length
// ---------------------------------------------------------------------------
it('passes through when Content-Length header is absent (let downstream enforce streaming limits)', async () => {
const request = makeRequest('/api/v2/streams', 'POST', null);
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
});
// ---------------------------------------------------------------------------
// Path scoping
// ---------------------------------------------------------------------------
it('applies the default size cap to paths outside /api/v2/streams', async () => {
// /api/v1/streams is subject to the default 256 KB cap.
const request = makeRequest('/api/v1/streams', 'POST', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('applies the default size cap to other v2 routes (e.g. /api/v2/other)', async () => {
const request = makeRequest('/api/v2/other', 'POST', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
// ---------------------------------------------------------------------------
// Method scoping
// ---------------------------------------------------------------------------
it('does not apply the size cap to GET requests on /api/v2/streams', async () => {
// GET requests must never be blocked by the body size cap.
const request = makeRequest('/api/v2/streams', 'GET', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
});
it('does not apply the size cap to DELETE requests on /api/v2/streams/{id}', async () => {
const request = makeRequest('/api/v2/streams/stream-abc-123', 'DELETE', DEFAULT_CAP + 1);
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
});
// ---------------------------------------------------------------------------
// Error envelope shape
// ---------------------------------------------------------------------------
it('returns the canonical error envelope with code REQUEST_TOO_LARGE on 413', async () => {
const overLimit = DEFAULT_CAP + 512;
const request = makeRequest('/api/v2/streams', 'POST', overLimit);
const response = await middleware(request as any);
expect(response.status).toBe(413);
const body = await response.json();
expect(body).toMatchObject({
error: {
code: 'REQUEST_TOO_LARGE',
message: expect.stringContaining(String(overLimit)),
request_id: expect.any(String),
},
});
});
it('forwards x-request-id from the incoming request into the 413 error envelope', async () => {
const requestId = 'req_test_forwarded_id';
const request = makeRequest('/api/v2/streams', 'POST', DEFAULT_CAP + 1, {
'x-request-id': requestId,
});
const response = await middleware(request as any);
expect(response.status).toBe(413);
const body = await response.json();
expect(body.error.request_id).toBe(requestId);
});
// ---------------------------------------------------------------------------
// Configurable cap
// ---------------------------------------------------------------------------
it('honours MAX_STREAM_BODY_BYTES env override', async () => {
// Re-import with a custom cap of 1024 bytes so the test is self-contained
// and does not depend on build-time module caching.
jest.resetModules();
(process.env as any).MAX_STREAM_BODY_BYTES = '1024';
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'production';
(process.env as any).ALLOWED_ORIGINS = 'https://allowed.example.com';
const { middleware: mw } = await import('./middleware');
// 1025 bytes — just above the custom 1 KB cap.
const over = makeRequest('/api/v2/streams', 'POST', 1025);
const overResponse = await mw(over as any);
expect(overResponse.status).toBe(413);
// 1024 bytes — exactly at the custom cap.
const at = makeRequest('/api/v2/streams', 'POST', 1024);
const atResponse = await mw(at as any);
expect(atResponse.status).not.toBe(413);
});
// ---------------------------------------------------------------------------
// Webhook routes with 1 MB limit
// ---------------------------------------------------------------------------
it('returns 413 when webhook Content-Length exceeds 1 MB on POST /api/webhooks', async () => {
const WEBHOOK_CAP = 1024 * 1024; // 1 MB
const request = makeRequest('/api/webhooks', 'POST', WEBHOOK_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('returns 413 when webhook Content-Length exceeds 1 MB on /api/webhooks/rotate', async () => {
const WEBHOOK_CAP = 1024 * 1024; // 1 MB
const request = makeRequest('/api/webhooks/rotate', 'POST', WEBHOOK_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('returns 413 when webhook Content-Length exceeds 1 MB on /api/webhooks/deliveries', async () => {
const WEBHOOK_CAP = 1024 * 1024; // 1 MB
const request = makeRequest('/api/webhooks/deliveries', 'POST', WEBHOOK_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('passes through when webhook Content-Length is exactly at the 1 MB cap', async () => {
const WEBHOOK_CAP = 1024 * 1024; // 1 MB
const request = makeRequest('/api/webhooks', 'POST', WEBHOOK_CAP);
const response = await middleware(request as any);
// Should NOT be a 413 — at-limit is allowed.
expect(response.status).not.toBe(413);
});
it('passes through when webhook Content-Length is below the 1 MB cap', async () => {
const request = makeRequest('/api/webhooks', 'POST', 512 * 1024); // 512 KB
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
});
it('passes through when webhook Content-Length is at 768 KB (well below 1 MB)', async () => {
const request = makeRequest('/api/webhooks/rotate', 'POST', 768 * 1024);
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
});
it('enforces 1 MB limit for nested webhook paths like /api/webhooks/dlq', async () => {
const WEBHOOK_CAP = 1024 * 1024; // 1 MB
const request = makeRequest('/api/webhooks/dlq', 'POST', WEBHOOK_CAP + 1);
const response = await middleware(request as any);
expect(response.status).toBe(413);
});
it('includes webhook limit in error message', async () => {
const WEBHOOK_CAP = 1024 * 1024; // 1 MB
const overLimit = WEBHOOK_CAP + 10000;
const request = makeRequest('/api/webhooks', 'POST', overLimit);
const response = await middleware(request as any);
expect(response.status).toBe(413);
const body = await response.json();
expect(body.error.message).toContain('1048576-byte limit'); // 1 MB in bytes
expect(body.error.message).toContain(String(overLimit));
});
it('honours MAX_WEBHOOK_BODY_BYTES env override', async () => {
// Re-import with a custom webhook cap of 2 MB
jest.resetModules();
(process.env as any).MAX_WEBHOOK_BODY_BYTES = String(2 * 1024 * 1024); // 2 MB
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'production';
(process.env as any).ALLOWED_ORIGINS = 'https://allowed.example.com';
const { middleware: mw } = await import('./middleware');
// 1.5 MB — within the custom 2 MB webhook cap, but exceeds default 1 MB
const within = makeRequest('/api/webhooks', 'POST', 1.5 * 1024 * 1024);
const withinResponse = await mw(within as any);
expect(withinResponse.status).not.toBe(413);
// 2.5 MB — exceeds the custom 2 MB webhook cap
const over = makeRequest('/api/webhooks', 'POST', 2.5 * 1024 * 1024);
const overResponse = await mw(over as any);
expect(overResponse.status).toBe(413);
});
it('does not apply webhook limit to non-webhook routes', async () => {
// A 512 KB body should be rejected on /api/v2/streams (under 256 KB default)
// but not be related to webhook limits
const request = makeRequest('/api/v2/streams', 'POST', 512 * 1024);
const response = await middleware(request as any);
expect(response.status).toBe(413);
const body = await response.json();
expect(body.error.message).toContain('262144-byte limit'); // 256 KB default
});
it('does not apply webhook limit to paths similar to webhooks but not exact', async () => {
// /api/webhook (singular) should not get 1 MB limit
// Falls through to default 256 KB limit
const request = makeRequest('/api/webhook', 'POST', 512 * 1024);
const response = await middleware(request as any);
// Should be 413 because /api/webhook exceeds the default 256 KB limit
expect(response.status).toBe(413);
});
});
// =============================================================================
// Request fingerprinting
// =============================================================================
describe('request fingerprint middleware', () => {
let middleware: any;
beforeEach(async () => {
jest.resetModules();
(process.env as any).STELLAR_NETWORK = 'testnet';
(process.env as any).JWT_SECRET = 'test-secret-at-least-32-characters-long';
(process.env as any).NODE_ENV = 'production';
(process.env as any).ALLOWED_ORIGINS = 'https://allowed.example.com';
const { resetAuditLogStore } = await import('@/app/lib/audit-log');
resetAuditLogStore();
await import('@/lib/fingerprint-audit');
const imported = await import('./middleware');
middleware = imported.middleware;
});
afterEach(() => {
delete (process.env as any).STELLAR_NETWORK;
delete (process.env as any).JWT_SECRET;
delete (process.env as any).NODE_ENV;
delete (process.env as any).ALLOWED_ORIGINS;
});
it('captures a stable fingerprint in the audit log for API requests', async () => {
const { auditLogStore } = await import('@/app/lib/audit-log');
const { REQUEST_FINGERPRINT_AUDIT_ACTION } = await import('@/lib/fingerprint');
const request = new Request('https://api.example.com/api/health', {
method: 'GET',
headers: {
'accept-encoding': 'gzip',
'accept-language': 'en-US',
'user-agent': 'StreamPay-Test/1.0',
'x-forwarded-for': '203.0.113.10',
'x-request-id': 'req_fingerprint_middleware_1',
},
});
const response = await middleware(request as any);
expect(response.status).not.toBe(413);
const entries = auditLogStore.list({ action: REQUEST_FINGERPRINT_AUDIT_ACTION });
expect(entries).toHaveLength(1);
expect(entries[0]?.metadata?.requestFingerprint).toMatch(/^[a-f0-9]{64}$/);
expect(entries[0]?.requestId).toBe('req_fingerprint_middleware_1');
});
it('includes the fingerprint on 413 responses for oversized bodies', async () => {
const request = new Request('http://localhost/api/v2/streams', {
method: 'POST',
headers: {
'content-length': String(256 * 1024 + 1),
'user-agent': 'StreamPay-Test/1.0',
},
});
const response = await middleware(request as any);
expect(response.status).toBe(413);
expect(response.headers.get('x-request-fingerprint')).toMatch(/^[a-f0-9]{64}$/);
});
});