lab4: прямая загрузка, скрипты экспериментов и проверок

This commit is contained in:
2026-10-22 22:39:25 +03:00
parent 7de3012b46
commit 39a6df8c09
12 changed files with 1574 additions and 2 deletions
@@ -1,4 +1,5 @@
import {
Body,
Controller,
Get,
Headers,
@@ -20,6 +21,8 @@ import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import type { AppConfig } from '../config/app-config.schema.js';
import type { User } from '../users/user.js';
import { AttachmentsService } from './attachments.service.js';
import { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
import { DirectUploadsService } from './direct-uploads.service.js';
import { contentDisposition } from './filename.js';
@Controller('api/v1')
@@ -29,6 +32,7 @@ export class AttachmentsController {
constructor(
private readonly attachments: AttachmentsService,
private readonly directUploads: DirectUploadsService,
config: ConfigService<AppConfig>,
) {
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
@@ -58,6 +62,25 @@ export class AttachmentsController {
);
}
@Post('chats/:chatId/attachments/direct-uploads')
@HttpCode(201)
initDirectUpload(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@CurrentUser() user: User,
@Body() body: CreateDirectUploadDto,
) {
return this.directUploads.init(chatId, user, body);
}
@Post('attachments/:attachmentId/complete')
@HttpCode(200)
completeDirectUpload(
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
@CurrentUser() user: User,
) {
return this.directUploads.complete(attachmentId, user);
}
@Get('attachments/:attachmentId')
metadata(
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
+7 -1
View File
@@ -8,6 +8,7 @@ import { StorageModule } from '../storage/storage.module.js';
import { AttachmentSweeper } from './attachment-sweeper.service.js';
import { AttachmentsController } from './attachments.controller.js';
import { AttachmentsRepository } from './attachments.repository.js';
import { DirectUploadsService } from './direct-uploads.service.js';
import { AttachmentsService } from './attachments.service.js';
@Module({
@@ -20,7 +21,12 @@ import { AttachmentsService } from './attachments.service.js';
StorageModule,
],
controllers: [AttachmentsController],
providers: [AttachmentsRepository, AttachmentsService, AttachmentSweeper],
providers: [
AttachmentsRepository,
AttachmentsService,
DirectUploadsService,
AttachmentSweeper,
],
exports: [AttachmentsRepository],
})
export class AttachmentsModule {}
+1 -1
View File
@@ -279,7 +279,7 @@ export class AttachmentsService {
return error;
}
private async compensate(id: string, key: string): Promise<void> {
async compensate(id: string, key: string): Promise<void> {
try {
await this.storage.delete(key);
await this.repository.deletePending(id);
@@ -0,0 +1,199 @@
import {
ConflictException,
HttpException,
Injectable,
NotFoundException,
PayloadTooLargeException,
UnsupportedMediaTypeException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomUUID } from 'node:crypto';
import type { AppConfig } from '../config/app-config.schema.js';
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 { AttachmentsRepository } from './attachments.repository.js';
import { AttachmentsService, 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,
} from './image/image-inspector.js';
export type DirectUpload = {
attachment_id: string;
method: 'PUT';
url: string;
headers: Record<string, string>;
expires_at: string;
};
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
@Injectable()
export class DirectUploadsService {
private readonly maxUploadBytes: number;
private readonly maxPixels: number;
private readonly ttlSeconds: number;
private readonly maxPending: number;
constructor(
config: ConfigService<AppConfig>,
private readonly repository: AttachmentsRepository,
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');
this.ttlSeconds = config.getOrThrow('DIRECT_UPLOAD_URL_TTL_SECONDS');
this.maxPending = config.getOrThrow(
'DIRECT_UPLOAD_MAX_PENDING_PER_USER',
);
}
async init(
chatId: string,
user: User,
dto: CreateDirectUploadDto,
): Promise<DirectUpload> {
const filename = validateFilename(dto.filename);
if (!MEDIA_TYPES.has(dto.content_type))
throw new UnsupportedMediaTypeException(
'content_type must be image/png or image/jpeg',
);
if (dto.size_bytes > this.maxUploadBytes)
throw new PayloadTooLargeException('Image is too large');
await this.chats.getForUser(chatId, user);
if (
(await this.repository.countPendingDirect(user.id)) >=
this.maxPending
)
throw new HttpException(
{
message: 'Too many unfinished direct uploads',
retryAfter: this.ttlSeconds,
},
429,
);
const id = randomUUID();
const key = this.storage.objectKey(id);
await this.repository.insertPending({
id,
chatId,
ownerId: user.id,
filename,
contentType: dto.content_type,
uploadMode: 'direct',
objectKey: key,
sizeBytes: dto.size_bytes,
sha256: dto.sha256,
ttlMs: this.ttlSeconds * 1000,
});
const checksum = Buffer.from(dto.sha256, 'hex').toString('base64');
let url: string;
try {
url = await this.storage.presignPut(key, {
contentType: dto.content_type,
contentLength: dto.size_bytes,
checksumSha256Base64: checksum,
expiresInSeconds: this.ttlSeconds,
});
} catch (error) {
await this.repository.deletePending(id);
throw error;
}
this.metrics.increment('attachments.direct.initiated');
return {
attachment_id: id,
method: 'PUT',
url,
headers: {
'Content-Type': dto.content_type,
'x-amz-checksum-sha256': checksum,
},
expires_at: new Date(
Date.now() + this.ttlSeconds * 1000,
).toISOString(),
};
}
async complete(attachmentId: string, user: User): Promise<Attachment> {
const row = await this.repository.findForComplete(
attachmentId,
user.id,
);
if (!row) throw new NotFoundException();
if (row.status === 'ready') return toAttachment(row);
const size = Number(row.size_bytes);
const expectedChecksum = Buffer.from(
row.sha256 as string,
'hex',
).toString('base64');
const head = await this.storage.head(row.object_key);
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);
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;
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',
);
} catch (error) {
if (error instanceof ImageRejectedError) {
await this.attachments.compensate(row.id, row.object_key);
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);
throw new UnsupportedMediaTypeException(
'Image content does not match content_type',
);
}
const ready = await this.repository.markReady(row.id, {
sizeBytes: size,
sha256: row.sha256 as string,
width: header.width,
height: header.height,
});
if (!ready) throw new ConflictException('Upload is no longer pending');
this.metrics.increment('attachments.direct.completed');
return toAttachment(ready);
}
}
@@ -0,0 +1,16 @@
import { IsInt, IsString, Matches, Min } from 'class-validator';
export class CreateDirectUploadDto {
@IsString()
filename!: string;
@IsString()
content_type!: string;
@IsInt()
@Min(1)
size_bytes!: number;
@Matches(/^[a-f0-9]{64}$/u)
sha256!: string;
}
+288
View File
@@ -0,0 +1,288 @@
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { Pool } from 'pg';
import type { Attachment } from '../src/attachments/attachment.js';
import type { DirectUpload } from '../src/attachments/direct-uploads.service.js';
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
import {
Actor,
actor,
bearer,
createChat,
database,
download,
expectError,
http,
json,
postMessage,
} from './support/e2e.js';
import { pixelBombPng } from './support/png.js';
const png = readFileSync(
new URL('../../tests/fixtures/sample.png', import.meta.url),
);
const jpeg = readFileSync(new URL('./fixtures/sample.jpg', import.meta.url));
const MAX = 10_485_760;
const shortTtl = process.env.E2E_DIRECT_TTL_SHORT === '1';
let db: Pool;
let alice: Actor;
let bob: Actor;
let eve: Actor;
let chatId: string;
const sha256 = (data: Uint8Array) =>
createHash('sha256').update(data).digest('hex');
function init(token: string, chat: string, body: Record<string, unknown>) {
return http<DirectUpload & ApiErrorBody>(
`/api/v1/chats/${chat}/attachments/direct-uploads`,
json(body, bearer(token)),
);
}
function declaration(data: Buffer, contentType = 'image/png') {
return {
filename: 'direct.png',
content_type: contentType,
size_bytes: data.length,
sha256: sha256(data),
};
}
async function initOk(data: Buffer, contentType = 'image/png') {
const result = await init(
alice.token,
chatId,
declaration(data, contentType),
);
expect(result.response.status).toBe(201);
return result.body;
}
// The PUT goes straight to the public S3 endpoint, not through the API.
async function put(ticket: DirectUpload, data: Buffer): Promise<Response> {
return fetch(ticket.url, {
method: ticket.method,
headers: ticket.headers,
body: data as unknown as BodyInit,
});
}
function complete(token: string, id: string) {
return http<Attachment & ApiErrorBody>(
`/api/v1/attachments/${id}/complete`,
{
method: 'POST',
headers: bearer(token),
},
);
}
describe('direct upload (presigned PUT)', () => {
beforeAll(async () => {
db = database();
alice = await actor();
bob = await actor();
eve = await actor();
chatId = (await createChat(alice, [bob])).id;
});
afterAll(async () => {
await db.end();
});
it('uploads around the API and exposes the attachment after complete', async () => {
const ticket = await initOk(png);
expect(ticket.method).toBe('PUT');
expect(ticket.headers['x-amz-checksum-sha256']).toBe(
Buffer.from(sha256(png), 'hex').toString('base64'),
);
expect(Date.parse(ticket.expires_at)).toBeGreaterThan(Date.now());
expect(new URL(ticket.url).pathname).toBe(
`/messenger-attachments/attachments/${ticket.attachment_id}/original`,
);
const hidden = await http<ApiErrorBody>(
`/api/v1/attachments/${ticket.attachment_id}`,
{ headers: bearer(bob.token) },
);
expectError(hidden, 404, 'not_found');
expectError(
await postMessage(alice.token, chatId, {
text: '',
attachment_ids: [ticket.attachment_id],
}),
404,
'not_found',
);
expectError(
await complete(alice.token, ticket.attachment_id),
409,
'conflict',
);
expect((await put(ticket, png)).status).toBe(200);
expectError(
await complete(bob.token, ticket.attachment_id),
404,
'not_found',
);
expectError(
await complete(eve.token, ticket.attachment_id),
404,
'not_found',
);
const done = await complete(alice.token, ticket.attachment_id);
expect(done.response.status).toBe(200);
expect(done.body).toMatchObject({
id: ticket.attachment_id,
owner_id: alice.user.id,
content_type: 'image/png',
size_bytes: png.length,
sha256: sha256(png),
status: 'ready',
});
const again = await complete(alice.token, ticket.attachment_id);
expect(again.response.status).toBe(200);
expect(again.body).toEqual(done.body);
const content = await download(bob.token, ticket.attachment_id);
expect(content.response.status).toBe(200);
expect(content.bytes.equals(png)).toBe(true);
const sent = await postMessage(alice.token, chatId, {
text: '',
attachment_ids: [ticket.attachment_id],
});
expect(sent.response.status).toBe(201);
expect(sent.body.attachment_ids).toEqual([ticket.attachment_id]);
});
it('rejects invalid declarations', async () => {
const base = declaration(png);
expectError(await init(eve.token, chatId, base), 404, 'not_found');
expectError(
await init(alice.token, chatId, { ...base, size_bytes: MAX + 1 }),
413,
'payload_too_large',
);
expectError(
await init(alice.token, chatId, {
...base,
content_type: 'image/gif',
}),
415,
'unsupported_media_type',
);
for (const bad of [
{ ...base, extra: true },
{ ...base, sha256: 'ABC' },
{ ...base, size_bytes: 0 },
{ ...base, filename: 'a/b.png' },
])
expectError(
await init(alice.token, chatId, bad),
400,
'invalid_request',
);
});
it('lets the storage refuse bytes that differ from the declaration', async () => {
const ticket = await initOk(png);
const tampered = Buffer.from(png);
tampered[1000] ^= 1;
const refused = await put(ticket, tampered);
expect(refused.status).toBe(400);
expect(await refused.text()).toContain('XAmzContentChecksumMismatch');
// No object was created, so the upload can still be finished.
expectError(
await complete(alice.token, ticket.attachment_id),
409,
'conflict',
);
expect((await put(ticket, png)).status).toBe(200);
expect(
(await complete(alice.token, ticket.attachment_id)).response.status,
).toBe(200);
const longer = await initOk(png);
const wrongLength = await put(
longer,
Buffer.concat([png, Buffer.from('x')]),
);
expect(wrongLength.status).toBe(403);
});
it('rejects a declared PNG that is really a JPEG, then forgets the claim', async () => {
const ticket = await initOk(jpeg, 'image/png');
expect((await put(ticket, jpeg)).status).toBe(200);
expectError(
await complete(alice.token, ticket.attachment_id),
415,
'unsupported_media_type',
);
expectError(
await complete(alice.token, ticket.attachment_id),
404,
'not_found',
);
});
it('rejects a pixel bomb on complete', async () => {
const bomb = pixelBombPng();
const ticket = await initOk(bomb);
expect((await put(ticket, bomb)).status).toBe(200);
expectError(
await complete(alice.token, ticket.attachment_id),
413,
'payload_too_large',
);
expectError(
await complete(alice.token, ticket.attachment_id),
404,
'not_found',
);
});
it('limits unfinished direct uploads per user', async () => {
const spammer = await actor();
const chat = (await createChat(spammer, [])).id;
for (let index = 0; index < 10; index += 1) {
const ok = await init(spammer.token, chat, declaration(png));
expect(ok.response.status).toBe(201);
}
const limited = await init(spammer.token, chat, declaration(png));
expectError(limited, 429, 'rate_limited');
expect(
Number(limited.response.headers.get('retry-after')),
).toBeGreaterThan(0);
});
it.runIf(shortTtl)(
'refuses an expired URL and removes the claim',
async () => {
const ticket = await initOk(png);
const expiresAt = Date.parse(ticket.expires_at);
await sleep(Math.max(0, expiresAt - Date.now()) + 2000);
expect((await put(ticket, png)).status).toBe(403);
const deadline = Date.now() + 15_000;
for (;;) {
const rows = await db.query(
'SELECT 1 FROM attachments WHERE id = $1',
[ticket.attachment_id],
);
if (rows.rowCount === 0) break;
expect(Date.now()).toBeLessThan(deadline);
await sleep(250);
}
expectError(
await complete(alice.token, ticket.attachment_id),
404,
'not_found',
);
},
60_000,
);
});