lab4: исправления по ревью (парсеры image/text только на upload, rejected-статус прямой загрузки, диапазон 64 KiB, отчёт)

This commit is contained in:
2026-10-22 23:04:05 +03:00
parent f048a37df9
commit 830e5811fc
20 changed files with 933 additions and 805 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ export type AttachmentRow = {
filename: string;
content_type: 'image/png' | 'image/jpeg';
upload_mode: 'proxy' | 'direct';
status: 'pending' | 'ready' | 'deleting';
status: 'pending' | 'ready' | 'deleting' | 'rejected';
object_key: string;
size_bytes: string | number | null;
sha256: string | null;
+12 -2
View File
@@ -75,6 +75,15 @@ export class AttachmentsRepository {
);
}
async rejectPending(id: string): Promise<void> {
await this.database.query(
'attachments.reject_pending',
`UPDATE attachments SET status = 'rejected', updated_at = now()
WHERE id = $1 AND status = 'pending'`,
[id],
);
}
async findVisible(
id: string,
userId: string,
@@ -106,7 +115,8 @@ export class AttachmentsRepository {
const result = await this.database.query<{ count: string }>(
'attachments.count_pending_direct',
`SELECT count(*) AS count FROM attachments
WHERE owner_id = $1 AND status = 'pending' AND upload_mode = 'direct'`,
WHERE owner_id = $1 AND status IN ('pending', 'rejected')
AND upload_mode = 'direct' AND expires_at > now()`,
[ownerId],
);
return Number(result.rows[0].count);
@@ -134,7 +144,7 @@ export class AttachmentsRepository {
`UPDATE attachments SET status = 'deleting', updated_at = now()
WHERE id IN (
SELECT id FROM attachments
WHERE (status = 'pending'
WHERE (status IN ('pending', 'rejected')
AND expires_at < now() - make_interval(secs => $1::double precision))
OR (status = 'deleting' AND updated_at < now() - interval '1 minute')
ORDER BY expires_at NULLS FIRST
+66 -31
View File
@@ -13,15 +13,20 @@ import { ChatsService } from '../chats/chats.service.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { ObjectStorage } from '../storage/object-storage.js';
import type { User } from '../users/user.js';
import { toAttachment, type Attachment } from './attachment.js';
import {
toAttachment,
type Attachment,
type AttachmentRow,
} from './attachment.js';
import { AttachmentsRepository } from './attachments.repository.js';
import { AttachmentsService, imageRejection } from './attachments.service.js';
import { imageRejection } from './attachments.service.js';
import type { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
import { validateFilename } from './filename.js';
import {
IMAGE_HEADER_MAX_BYTES,
ImageInspector,
ImageRejectedError,
type ImageHeader,
} from './image/image-inspector.js';
export type DirectUpload = {
@@ -32,6 +37,7 @@ export type DirectUpload = {
expires_at: string;
};
const FIRST_RANGE_BYTES = 65_536;
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
@Injectable()
@@ -47,7 +53,6 @@ export class DirectUploadsService {
private readonly storage: ObjectStorage,
private readonly chats: ChatsService,
private readonly metrics: MetricsService,
private readonly attachments: AttachmentsService,
) {
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
@@ -141,47 +146,25 @@ export class DirectUploadsService {
if (head === null)
throw new ConflictException('Upload has not been received');
if (head.size !== size || head.checksumSha256 !== expectedChecksum) {
await this.attachments.compensate(row.id, row.object_key);
await this.reject(row);
throw new ConflictException(
'Uploaded object does not match the declaration',
);
}
// Only the header is read: the signed checksum already pins every byte.
const inspector = new ImageInspector(this.maxPixels);
const covered = size <= IMAGE_HEADER_MAX_BYTES;
const stream = await this.storage.getStream(
row.object_key,
`bytes=0-${Math.min(size, IMAGE_HEADER_MAX_BYTES) - 1}`,
);
if (stream === null)
throw new ConflictException('Upload has not been received');
let verified = 0;
let header: ImageHeader;
try {
for await (const chunk of stream as AsyncIterable<Buffer>) {
verified += chunk.length;
inspector.push(chunk);
if (!covered && inspector.header !== undefined) break;
}
if (covered) inspector.finish();
else if (inspector.header === undefined)
throw new ImageRejectedError(
'unsupported_media_type',
'Image header is missing',
);
header = await this.readHeader(row.object_key, size);
} catch (error) {
if (error instanceof ImageRejectedError) {
await this.attachments.compensate(row.id, row.object_key);
await this.reject(row);
throw imageRejection(error);
}
throw error;
} finally {
stream.destroy();
this.metrics.add('attachments.direct.verify_bytes', verified);
}
const header = inspector.header;
if (header === undefined || header.contentType !== row.content_type) {
await this.attachments.compensate(row.id, row.object_key);
if (header.contentType !== row.content_type) {
await this.reject(row);
throw new UnsupportedMediaTypeException(
'Image content does not match content_type',
);
@@ -196,4 +179,56 @@ export class DirectUploadsService {
this.metrics.increment('attachments.direct.completed');
return toAttachment(ready);
}
/**
* Reads a small first range and widens it only when the header is not in it,
* so the usual `complete` costs one short ranged GET. A range that covers the
* whole object is also checked for structural completeness.
*/
private async readHeader(key: string, size: number): Promise<ImageHeader> {
const ceiling = Math.min(size, IMAGE_HEADER_MAX_BYTES);
let range = Math.min(size, FIRST_RANGE_BYTES);
for (;;) {
const inspector = new ImageInspector(this.maxPixels);
const stream = await this.storage.getStream(
key,
`bytes=0-${range - 1}`,
);
if (stream === null)
throw new ConflictException('Upload has not been received');
let verified = 0;
try {
for await (const chunk of stream as AsyncIterable<Buffer>) {
verified += chunk.length;
inspector.push(chunk);
}
} finally {
stream.destroy();
this.metrics.add('attachments.direct.verify_bytes', verified);
}
if (range === size) return inspector.finish();
if (inspector.header !== undefined) return inspector.header;
if (range >= ceiling)
throw new ImageRejectedError(
'unsupported_media_type',
'Image header is missing',
);
range = ceiling;
}
}
/**
* A rejected claim keeps its row (status `rejected`, original expiry) while
* the signed URL may still be used: a later re-PUT would otherwise leave an
* object that no row refers to. The sweeper removes both after expiry + grace.
*/
private async reject(row: AttachmentRow): Promise<void> {
await this.repository.rejectPending(row.id);
try {
await this.storage.delete(row.object_key);
} catch {
// The sweeper deletes the object again after expiry.
}
this.metrics.increment('attachments.direct.rejected');
}
}
@@ -0,0 +1,8 @@
-- Rejected direct uploads keep their row until the signed URL can no longer be
-- used, so an object re-PUT after rejection is still found by the sweeper.
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
CHECK (status IN ('pending', 'ready', 'deleting', 'rejected'));
DROP INDEX attachments_owner_direct_pending_idx;
CREATE INDEX attachments_owner_direct_pending_idx ON attachments (owner_id)
WHERE status IN ('pending', 'rejected') AND upload_mode = 'direct';
+42 -9
View File
@@ -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(
+15
View File
@@ -325,6 +325,21 @@ describe('attachments (proxy upload)', () => {
expectError(await variant('bogus'), 400, 'invalid_request');
});
it('answers 4xx, not 500, for raw image or text bodies on JSON routes', async () => {
for (const [type, status, code] of [
['image/png', 415, 'unsupported_media_type'],
['image/jpeg', 415, 'unsupported_media_type'],
['text/plain', 400, 'invalid_request'],
] as const) {
const result = await http<ApiErrorBody>('/api/v1/users', {
method: 'POST',
headers: { 'content-type': type },
body: 'x',
});
expectError(result, status, code);
}
});
it('removes the pending row when the client drops the connection', async () => {
const data = noisePng(2 * 1024 * 1024);
const url = new URL(baseUrl);
+13
View File
@@ -228,6 +228,19 @@ describe('direct upload (presigned PUT)', () => {
404,
'not_found',
);
// The URL is still valid: a re-PUT must stay tracked so the sweeper
// removes the new object too.
expect((await put(ticket, jpeg)).status).toBe(200);
const row = await db.query<{ status: string }>(
'SELECT status FROM attachments WHERE id = $1',
[ticket.attachment_id],
);
expect(row.rows[0]?.status).toBe('rejected');
expectError(
await complete(alice.token, ticket.attachment_id),
404,
'not_found',
);
});
it('rejects a pixel bomb on complete', async () => {