lab4: исправления по ревью (парсеры image/text только на upload, rejected-статус прямой загрузки, диапазон 64 KiB, отчёт)
This commit is contained in:
+42
-9
@@ -1,7 +1,12 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import {
|
||||
PayloadTooLargeException,
|
||||
UnsupportedMediaTypeException,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import type { Readable } from 'node:stream';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
@@ -11,24 +16,52 @@ import { HealthService } from './health/health.service.js';
|
||||
import { MetricsService } from './metrics/metrics.service.js';
|
||||
import { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
|
||||
|
||||
const TEXT_BODY_LIMIT = 1_048_576;
|
||||
const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter({ logger: true }),
|
||||
);
|
||||
// Raw image bodies reach the controller as an unread stream: the upload is
|
||||
// bounded by our own checks, not by Fastify's bodyLimit.
|
||||
// bounded by our own checks, not by Fastify's bodyLimit. A stream may reach
|
||||
// only the upload route: on JSON routes it would hit the ValidationPipe and
|
||||
// overflow the stack there, so other routes keep the pre-upload behavior.
|
||||
const fastify = app.getHttpAdapter().getInstance();
|
||||
type ParserRequest = { method: string; routeOptions?: { url?: string } };
|
||||
type Done = (error: Error | null, body?: unknown) => void;
|
||||
const isUpload = (request: ParserRequest) =>
|
||||
request.method === 'POST' && request.routeOptions?.url === UPLOAD_ROUTE;
|
||||
fastify.addContentTypeParser(
|
||||
['image/png', 'image/jpeg'],
|
||||
(request: ParserRequest, payload: unknown, done: Done) =>
|
||||
isUpload(request)
|
||||
? done(null, payload)
|
||||
: done(new UnsupportedMediaTypeException()),
|
||||
);
|
||||
// Fastify's built-in text/plain parser buffers the body and fails binary
|
||||
// input with 400; the upload service answers 415 for it instead.
|
||||
// input with 400; on the upload route the service answers 415 instead.
|
||||
// Elsewhere text/plain keeps being buffered as a string (1 MiB cap).
|
||||
fastify.removeContentTypeParser('text/plain');
|
||||
fastify.addContentTypeParser(
|
||||
['image/png', 'image/jpeg', 'text/plain'],
|
||||
(
|
||||
_request: unknown,
|
||||
payload: unknown,
|
||||
done: (error: Error | null, body?: unknown) => void,
|
||||
) => done(null, payload),
|
||||
'text/plain',
|
||||
(request: ParserRequest, payload: Readable, done: Done) => {
|
||||
if (isUpload(request)) return done(null, payload);
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
payload.on('data', (chunk: Buffer) => {
|
||||
size += chunk.length;
|
||||
if (size > TEXT_BODY_LIMIT) {
|
||||
payload.destroy();
|
||||
done(new PayloadTooLargeException());
|
||||
} else chunks.push(chunk);
|
||||
});
|
||||
payload.on('end', () =>
|
||||
done(null, Buffer.concat(chunks).toString('utf8')),
|
||||
);
|
||||
payload.on('error', (error: Error) => done(error));
|
||||
},
|
||||
);
|
||||
app.useGlobalInterceptors(
|
||||
new RequestIdInterceptor(
|
||||
|
||||
Reference in New Issue
Block a user