Skip to content

Commit ec87670

Browse files
authored
Merge pull request #1288 from SharifIbrahimDev/fix/request-size-limit
fix: enforce 100kb payload limit on express.json and handle 413s
2 parents 06ba454 + cf94fac commit ec87670

3 files changed

Lines changed: 34 additions & 1 deletion

File tree

backend/src/__tests__/errorHandling.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,25 @@ describe('Centralized Error Handling', () => {
7575
});
7676
});
7777

78+
describe('Request Payload Size Limit', () => {
79+
it('should return 413 when payload exceeds the configured limit', async () => {
80+
// Create a payload larger than 100kb
81+
const largePayload = {
82+
data: 'x'.repeat(1024 * 150), // 150kb string
83+
};
84+
85+
const response = await request(app)
86+
.post('/api/simulate')
87+
.set('Authorization', authHeader)
88+
.send(largePayload);
89+
90+
expect(response.status).toBe(413);
91+
expect(response.body.success).toBe(false);
92+
expect(response.body.error.code).toBe('VALIDATION_ERROR');
93+
expect(response.body.error.message).toMatch(/payload too large/i);
94+
});
95+
});
96+
7897
/* ── Consistent JSON structure ────────────────────────────── */
7998

8099
describe('Response structure consistency', () => {

backend/src/app.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ const corsOptions: cors.CorsOptions = {
110110

111111
app.use(cors(corsOptions));
112112
app.use(compression());
113-
app.use(express.json());
113+
// Explicit request body size limit set to 100kb to mitigate payload-based DoS and unbounded audit log writes.
114+
app.use(express.json({ limit: '100kb' }));
114115
app.use(globalRateLimiter);
115116
app.use(requestIdMiddleware);
116117
app.use(requestLogger);

backend/src/middleware/errorHandler.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,19 @@ export const errorHandler = (
9494
return;
9595
}
9696

97+
// ── Payload Too Large (body-parser) ────────────────────────
98+
if ('type' in err && (err as { type?: string }).type === 'entity.too.large') {
99+
res.status(413).json({
100+
success: false,
101+
message: 'Request payload too large',
102+
error: {
103+
code: ErrorCode.VALIDATION_ERROR, // Or a dedicated code if defined
104+
message: 'Request payload too large',
105+
},
106+
});
107+
return;
108+
}
109+
97110
// ── Unexpected / Programming Errors ──────────────────────────
98111
logger.error('Unhandled error', {
99112
requestId: req.requestId,

0 commit comments

Comments
 (0)