forked from mtusi2026/mtusi2026lab4
feat: add attachment download and message attachment links
This commit is contained in:
@@ -1,13 +1,15 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { Readable } from 'stream';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
@@ -41,4 +43,37 @@ export class AttachmentsController {
|
||||
});
|
||||
return toAttachmentResponse(attachment);
|
||||
}
|
||||
|
||||
@Get('api/v1/attachments/:attachmentId')
|
||||
async metadata(
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
): Promise<AttachmentResponse> {
|
||||
return toAttachmentResponse(
|
||||
await this.attachments.getVisible(attachmentId, user.id),
|
||||
);
|
||||
}
|
||||
|
||||
@Get('api/v1/attachments/:attachmentId/content')
|
||||
async content(
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
@Query('variant') variant: unknown,
|
||||
@CurrentUser() user: User,
|
||||
@Res() reply: FastifyReply,
|
||||
): Promise<void> {
|
||||
const { attachment, content } = await this.attachments.openContent(
|
||||
attachmentId,
|
||||
user.id,
|
||||
variant,
|
||||
);
|
||||
await reply
|
||||
.header('content-type', attachment.contentType)
|
||||
.header('content-length', attachment.sizeBytes)
|
||||
.header('x-content-type-options', 'nosniff')
|
||||
.header(
|
||||
'content-disposition',
|
||||
`inline; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`,
|
||||
)
|
||||
.send(content);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Readable } from 'stream';
|
||||
import { assertChatMember } from '../chats/chat-access';
|
||||
import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
import { isDatabaseUnavailable, PrismaService } from '../db/prisma.service';
|
||||
import { S3Service } from '../storage/s3.service';
|
||||
import { assertValidImage, isSupportedContentType } from './image-validation';
|
||||
@@ -17,6 +18,7 @@ const TEMP_PREFIX = 'messenger-upload-';
|
||||
const STALE_TEMP_MS = 60 * 60 * 1000;
|
||||
const MAX_FILENAME_CODE_POINTS = 255;
|
||||
const FORBIDDEN_FILENAME = /[/\\\p{Cc}\p{Zl}\p{Zp}]/u;
|
||||
const KNOWN_VARIANTS = new Set(['thumbnail', 'crop', 'optimized']);
|
||||
|
||||
export interface UploadInput {
|
||||
chatId: string;
|
||||
@@ -65,6 +67,32 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
async getVisible(attachmentId: string, userId: string): Promise<Attachment> {
|
||||
if (!isUuid(attachmentId)) {
|
||||
throw new ApiError('invalid_request', 'attachmentId must be a valid UUID');
|
||||
}
|
||||
const row = await this.prisma.attachment.findFirst({
|
||||
where: {
|
||||
id: attachmentId,
|
||||
chat: { members: { some: { userId } } },
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
throw new ApiError('not_found', 'attachment not found');
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
async openContent(
|
||||
attachmentId: string,
|
||||
userId: string,
|
||||
variant: unknown,
|
||||
): Promise<{ attachment: Attachment; content: Readable }> {
|
||||
const attachment = await this.getVisible(attachmentId, userId);
|
||||
assertOriginalVariant(variant);
|
||||
return { attachment, content: await this.s3.getStream(attachment.objectKey) };
|
||||
}
|
||||
|
||||
private async store(
|
||||
input: UploadInput,
|
||||
filename: string,
|
||||
@@ -126,6 +154,16 @@ export class AttachmentsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
function assertOriginalVariant(raw: unknown): void {
|
||||
if (raw === undefined || raw === 'original') {
|
||||
return;
|
||||
}
|
||||
if (typeof raw === 'string' && KNOWN_VARIANTS.has(raw)) {
|
||||
throw new ApiError('not_found', 'attachment variant not found');
|
||||
}
|
||||
throw new ApiError('invalid_request', 'unknown attachment variant');
|
||||
}
|
||||
|
||||
function isDefiniteRejection(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
|
||||
@@ -18,4 +18,5 @@ export interface Message {
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachmentIds: string[];
|
||||
}
|
||||
|
||||
@@ -1,5 +1,32 @@
|
||||
import { ArrayMaxSize, IsArray, IsString, ValidateIf } from 'class-validator';
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
IsArray,
|
||||
IsString,
|
||||
Validate,
|
||||
ValidateIf,
|
||||
ValidatorConstraint,
|
||||
ValidatorConstraintInterface,
|
||||
} from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { validate as isUuid } from '../../common/uuid';
|
||||
|
||||
@ValidatorConstraint({ name: 'uniqueUuidList' })
|
||||
class UniqueUuidList implements ValidatorConstraintInterface {
|
||||
validate(value: unknown): boolean {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
!value.every((id) => typeof id === 'string' && isUuid(id))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const normalized = (value as string[]).map((id) => id.toLowerCase());
|
||||
return new Set(normalized).size === normalized.length;
|
||||
}
|
||||
|
||||
defaultMessage(): string {
|
||||
return 'attachment_ids must contain unique UUIDs';
|
||||
}
|
||||
}
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@@ -8,6 +35,7 @@ export class CreateMessageDto {
|
||||
|
||||
@ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined)
|
||||
@IsArray()
|
||||
@ArrayMaxSize(0, { message: 'attachment_ids must be empty: attachments are not supported' })
|
||||
attachment_ids?: unknown[];
|
||||
@ArrayMaxSize(10)
|
||||
@Validate(UniqueUuidList)
|
||||
attachment_ids?: string[];
|
||||
}
|
||||
|
||||
@@ -21,6 +21,6 @@ export function toMessageResponse(message: Message): MessageResponse {
|
||||
sender_id: message.senderId,
|
||||
text: message.text,
|
||||
created_at: message.createdAt,
|
||||
attachment_ids: [],
|
||||
attachment_ids: message.attachmentIds,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,7 +36,13 @@ export class MessagesController {
|
||||
@CurrentUser() user: User,
|
||||
): Promise<MessageResponse> {
|
||||
const key = parseIdempotencyKey(keyRaw);
|
||||
const message = await this.messages.create(chatId, user.id, dto.text, key);
|
||||
const message = await this.messages.create(
|
||||
chatId,
|
||||
user.id,
|
||||
dto.text,
|
||||
(dto.attachment_ids ?? []).map((id) => id.toLowerCase()),
|
||||
key,
|
||||
);
|
||||
return toMessageResponse(message);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,20 @@ interface MessageRow {
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: Date;
|
||||
attachmentIds: string[];
|
||||
}
|
||||
|
||||
const ATTACHMENT_LINKS = {
|
||||
attachments: {
|
||||
orderBy: { position: 'asc' },
|
||||
select: { attachmentId: true },
|
||||
},
|
||||
} satisfies Prisma.MessageInclude;
|
||||
|
||||
type MessageWithLinks = Prisma.MessageGetPayload<{
|
||||
include: typeof ATTACHMENT_LINKS;
|
||||
}>;
|
||||
|
||||
class KeyAlreadyUsed extends Error {}
|
||||
|
||||
@Injectable()
|
||||
@@ -30,18 +42,20 @@ export class MessagesService {
|
||||
chatId: string,
|
||||
callerId: string,
|
||||
text: string,
|
||||
attachmentIds: string[],
|
||||
key: string,
|
||||
): Promise<Message> {
|
||||
await this.assertMember(chatId, callerId);
|
||||
if (codePointLength(text.trim()) === 0) {
|
||||
if (codePointLength(text.trim()) === 0 && attachmentIds.length === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'text must not be empty or whitespace-only',
|
||||
'text must not be empty or whitespace-only without attachments',
|
||||
);
|
||||
}
|
||||
await this.assertAttachmentsInChat(chatId, attachmentIds);
|
||||
const scope = { userId: callerId, chatId, key };
|
||||
const requestHash = createHash('sha256')
|
||||
.update(JSON.stringify({ text }))
|
||||
.update(JSON.stringify({ text, attachment_ids: attachmentIds }))
|
||||
.digest('hex');
|
||||
try {
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
@@ -52,7 +66,18 @@ export class MessagesService {
|
||||
},
|
||||
});
|
||||
const row = await tx.message.create({
|
||||
data: { chatId, senderId: callerId, text },
|
||||
data: {
|
||||
chatId,
|
||||
senderId: callerId,
|
||||
text,
|
||||
attachments: {
|
||||
create: attachmentIds.map((attachmentId, position) => ({
|
||||
attachmentId,
|
||||
position,
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: ATTACHMENT_LINKS,
|
||||
});
|
||||
const { count } = await tx.idempotencyKey.createMany({
|
||||
data: [{ ...scope, requestHash, messageId: row.id }],
|
||||
@@ -61,7 +86,7 @@ export class MessagesService {
|
||||
if (count === 0) {
|
||||
throw new KeyAlreadyUsed();
|
||||
}
|
||||
return toMessage(row);
|
||||
return linkedMessage(row);
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof KeyAlreadyUsed)) {
|
||||
@@ -70,7 +95,7 @@ export class MessagesService {
|
||||
}
|
||||
const stored = await this.prisma.idempotencyKey.findUnique({
|
||||
where: { userId_chatId_key: scope },
|
||||
include: { message: true },
|
||||
include: { message: { include: ATTACHMENT_LINKS } },
|
||||
});
|
||||
if (!stored || stored.requestHash !== requestHash) {
|
||||
throw new ApiError(
|
||||
@@ -78,7 +103,7 @@ export class MessagesService {
|
||||
'Idempotency-Key was already used with a different request',
|
||||
);
|
||||
}
|
||||
return toMessage(stored.message);
|
||||
return linkedMessage(stored.message);
|
||||
}
|
||||
|
||||
async list(
|
||||
@@ -109,7 +134,12 @@ export class MessagesService {
|
||||
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
|
||||
}
|
||||
const rows = await this.prisma.$queryRaw<MessageRow[]>`
|
||||
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
|
||||
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt",
|
||||
ARRAY(
|
||||
SELECT attachment_id::text FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
) AS "attachmentIds"
|
||||
FROM messages
|
||||
WHERE chat_id = ${chatId}::uuid ${after}
|
||||
ORDER BY created_at, id
|
||||
@@ -128,6 +158,28 @@ export class MessagesService {
|
||||
private assertMember(chatId: string, callerId: string): Promise<void> {
|
||||
return assertChatMember(this.prisma, chatId, callerId);
|
||||
}
|
||||
|
||||
private async assertAttachmentsInChat(
|
||||
chatId: string,
|
||||
attachmentIds: string[],
|
||||
): Promise<void> {
|
||||
if (attachmentIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const found = await this.prisma.attachment.count({
|
||||
where: { id: { in: attachmentIds }, chatId },
|
||||
});
|
||||
if (found !== attachmentIds.length) {
|
||||
throw new ApiError('not_found', 'attachment not found');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function linkedMessage(row: MessageWithLinks): Message {
|
||||
return toMessage({
|
||||
...row,
|
||||
attachmentIds: row.attachments.map((link) => link.attachmentId),
|
||||
});
|
||||
}
|
||||
|
||||
function toMessage(row: MessageRow): Message {
|
||||
@@ -137,5 +189,6 @@ function toMessage(row: MessageRow): Message {
|
||||
senderId: row.senderId,
|
||||
text: row.text,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
attachmentIds: row.attachmentIds,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3';
|
||||
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import { createReadStream, readFileSync } from 'fs';
|
||||
import { Readable } from 'stream';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
|
||||
const CONNECT_TIMEOUT_MS = 1000;
|
||||
@@ -23,10 +25,11 @@ export interface StoredFile {
|
||||
export class S3Service implements OnModuleDestroy {
|
||||
private readonly logger = new Logger('S3Service');
|
||||
private readonly client: S3Client;
|
||||
private readonly streamClient: S3Client;
|
||||
private readonly bucket = process.env.S3_BUCKET ?? 'messenger-attachments';
|
||||
|
||||
constructor() {
|
||||
this.client = new S3Client({
|
||||
const config = {
|
||||
endpoint: process.env.S3_ENDPOINT ?? 'http://s3:9000',
|
||||
region: process.env.S3_REGION ?? 'us-east-1',
|
||||
forcePathStyle: true,
|
||||
@@ -35,11 +38,18 @@ export class S3Service implements OnModuleDestroy {
|
||||
accessKeyId: readSecret('S3_ACCESS_KEY_ID'),
|
||||
secretAccessKey: readSecret('S3_SECRET_ACCESS_KEY'),
|
||||
},
|
||||
};
|
||||
this.client = new S3Client({
|
||||
...config,
|
||||
requestHandler: {
|
||||
connectionTimeout: CONNECT_TIMEOUT_MS,
|
||||
requestTimeout: IDLE_TIMEOUT_MS,
|
||||
},
|
||||
});
|
||||
this.streamClient = new S3Client({
|
||||
...config,
|
||||
requestHandler: { connectionTimeout: CONNECT_TIMEOUT_MS },
|
||||
});
|
||||
}
|
||||
|
||||
async putFile(file: StoredFile): Promise<void> {
|
||||
@@ -58,6 +68,27 @@ export class S3Service implements OnModuleDestroy {
|
||||
);
|
||||
}
|
||||
|
||||
async getStream(key: string): Promise<Readable> {
|
||||
const deadline = new AbortController();
|
||||
const timer = setTimeout(() => deadline.abort(), IDLE_TIMEOUT_MS);
|
||||
try {
|
||||
const { Body } = await this.streamClient.send(
|
||||
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
|
||||
{ abortSignal: deadline.signal },
|
||||
);
|
||||
return Body as Readable;
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : 'unknown error';
|
||||
this.logger.error(`get ${key} failed: ${name}`);
|
||||
if (name === 'NoSuchKey') {
|
||||
throw new Error(`object ${key} is missing from storage`);
|
||||
}
|
||||
throw new ApiError('unavailable', 'object storage unavailable');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<void> {
|
||||
await this.guard(`delete ${key}`, () =>
|
||||
this.client.send(
|
||||
@@ -69,6 +100,7 @@ export class S3Service implements OnModuleDestroy {
|
||||
|
||||
onModuleDestroy(): void {
|
||||
this.client.destroy();
|
||||
this.streamClient.destroy();
|
||||
}
|
||||
|
||||
private async guard<T>(action: string, run: () => Promise<T>): Promise<T> {
|
||||
|
||||
@@ -405,7 +405,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('считает attachment_ids: [] равным отсутствию поля, непустой список отклоняет', async () => {
|
||||
it('считает attachment_ids: [] равным отсутствию поля, неизвестный ID — 404, неверный тип — 400', async () => {
|
||||
const alice = await createUser('aliceatt');
|
||||
const bob = await createUser('bobatt');
|
||||
const chat = await createChat(alice, bob);
|
||||
@@ -424,7 +424,13 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
.send({ attachment_ids: [], text: 'att' })
|
||||
.expect(201);
|
||||
expect(replay.body).toEqual(first.body);
|
||||
for (const attachment_ids of [[randomUUID()], null, 'x']) {
|
||||
await request(server)
|
||||
.post(path)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'x', attachment_ids: [randomUUID()] })
|
||||
.expect(404);
|
||||
for (const attachment_ids of [null, 'x']) {
|
||||
await request(server)
|
||||
.post(path)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { S3Service } from '../src/storage/s3.service';
|
||||
import { bearer, createTestApp, registerUser, TestUser } from './helpers';
|
||||
import { jpeg, SAMPLE_PNG } from './images';
|
||||
|
||||
describe('Скачивание и привязка вложений (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
let alice: TestUser;
|
||||
let bob: TestUser;
|
||||
let eve: TestUser;
|
||||
let chatId: string;
|
||||
let otherChatId: string;
|
||||
|
||||
const createChat = async (owner: TestUser, members: TestUser[]) => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(owner))
|
||||
.send({ title: 'Files', member_ids: members.map((m) => m.id) })
|
||||
.expect(201);
|
||||
return res.body.id as string;
|
||||
};
|
||||
|
||||
const upload = async (
|
||||
user = alice,
|
||||
chat = chatId,
|
||||
body: Buffer = SAMPLE_PNG,
|
||||
type = 'image/png',
|
||||
) => {
|
||||
const res = await request(server)
|
||||
.post(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent('фото 1.png')}`)
|
||||
.set('Authorization', bearer(user))
|
||||
.set('Content-Type', type)
|
||||
.send(body)
|
||||
.expect(201);
|
||||
return res.body;
|
||||
};
|
||||
|
||||
const get = (path: string, user: TestUser | null = bob) => {
|
||||
const req = request(server).get(path).buffer(true).parse(binaryParser);
|
||||
return user ? req.set('Authorization', bearer(user)) : req;
|
||||
};
|
||||
|
||||
const send = (
|
||||
body: unknown,
|
||||
{ user = alice, chat = chatId, key = randomUUID() }: { user?: TestUser; chat?: string; key?: string } = {},
|
||||
) =>
|
||||
request(server)
|
||||
.post(`/api/v1/chats/${chat}/messages`)
|
||||
.set('Authorization', bearer(user))
|
||||
.set('Idempotency-Key', key)
|
||||
.send(body as object);
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
alice = await registerUser(server, 'acc_alice');
|
||||
bob = await registerUser(server, 'acc_bob');
|
||||
eve = await registerUser(server, 'acc_eve');
|
||||
chatId = await createChat(alice, [alice, bob]);
|
||||
otherChatId = await createChat(eve, [eve]);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe('чтение', () => {
|
||||
it('участник получает метаданные и оригинал побайтно', async () => {
|
||||
const attachment = await upload();
|
||||
const meta = await request(server)
|
||||
.get(`/api/v1/attachments/${attachment.id}`)
|
||||
.set('Authorization', bearer(bob))
|
||||
.expect(200);
|
||||
expect(meta.body).toEqual(attachment);
|
||||
const res = await get(`/api/v1/attachments/${attachment.id}/content`).expect(200);
|
||||
expect(res.headers['content-type']).toBe('image/png');
|
||||
expect(res.headers['content-length']).toBe(String(SAMPLE_PNG.length));
|
||||
expect(res.headers['x-content-type-options']).toBe('nosniff');
|
||||
expect(res.headers['x-request-id']).toBeTruthy();
|
||||
expect(res.headers['x-instance-id']).toBeTruthy();
|
||||
expect(res.headers['location']).toBeUndefined();
|
||||
expect(createHash('sha256').update(res.body).digest('hex')).toBe(attachment.sha256);
|
||||
});
|
||||
|
||||
it('JPEG отдаётся с истинным Content-Type', async () => {
|
||||
const body = await jpeg();
|
||||
const attachment = await upload(alice, chatId, body, 'image/jpeg');
|
||||
const res = await get(`/api/v1/attachments/${attachment.id}/content`).expect(200);
|
||||
expect(res.headers['content-type']).toBe('image/jpeg');
|
||||
expect(Buffer.compare(res.body, body)).toBe(0);
|
||||
});
|
||||
|
||||
it('посторонний и неизвестный ID получают одинаковый 404', async () => {
|
||||
const attachment = await upload();
|
||||
for (const suffix of ['', '/content']) {
|
||||
const foreign = await get(`/api/v1/attachments/${attachment.id}${suffix}`, eve);
|
||||
const unknown = await get(`/api/v1/attachments/${randomUUID()}${suffix}`, eve);
|
||||
expect(foreign.status).toBe(404);
|
||||
expect(unknown.status).toBe(404);
|
||||
const parsed = JSON.parse(foreign.body.toString());
|
||||
expect(parsed.error.code).toBe('not_found');
|
||||
expect(parsed.error.message).toBe(JSON.parse(unknown.body.toString()).error.message);
|
||||
}
|
||||
});
|
||||
|
||||
it('без токена 401, неверный UUID 400', async () => {
|
||||
const attachment = await upload();
|
||||
for (const suffix of ['', '/content']) {
|
||||
await get(`/api/v1/attachments/${attachment.id}${suffix}`, null).expect(401);
|
||||
await get(`/api/v1/attachments/not-a-uuid${suffix}`).expect(400);
|
||||
}
|
||||
});
|
||||
|
||||
it('variant: original явно, отсутствующий 404, неизвестный и повторённый 400', async () => {
|
||||
const { id } = await upload();
|
||||
await get(`/api/v1/attachments/${id}/content?variant=original`).expect(200);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=thumbnail`).expect(404);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=nonsense`).expect(400);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=`).expect(400);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=original&variant=original`).expect(400);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=thumbnail`, eve).expect(404);
|
||||
});
|
||||
|
||||
it('нет доступа к S3 — метаданные 200, content 503 с заголовками', async () => {
|
||||
const attachment = await upload();
|
||||
const { app: down, server: downServer } = await createTestApp({
|
||||
S3_ENDPOINT: 'http://127.0.0.1:9',
|
||||
});
|
||||
try {
|
||||
await request(downServer)
|
||||
.get(`/api/v1/attachments/${attachment.id}`)
|
||||
.set('Authorization', bearer(bob))
|
||||
.expect(200);
|
||||
const res = await request(downServer)
|
||||
.get(`/api/v1/attachments/${attachment.id}/content`)
|
||||
.set('Authorization', bearer(bob))
|
||||
.expect(503);
|
||||
expect(res.body.error.code).toBe('unavailable');
|
||||
expect(res.headers['x-instance-id']).toBeTruthy();
|
||||
} finally {
|
||||
await down.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('объект пропал из S3 — 500 без внутренних деталей', async () => {
|
||||
const attachment = await upload();
|
||||
const row = await app.get(PrismaService).attachment.findUniqueOrThrow({
|
||||
where: { id: attachment.id },
|
||||
});
|
||||
await app.get(S3Service).delete(row.objectKey);
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/attachments/${attachment.id}/content`)
|
||||
.set('Authorization', bearer(bob))
|
||||
.expect(500);
|
||||
expect(res.body.error.code).toBe('internal_error');
|
||||
expect(JSON.stringify(res.body)).not.toContain(row.objectKey);
|
||||
});
|
||||
});
|
||||
|
||||
describe('attachment_ids в сообщениях', () => {
|
||||
it('text="" с вложением принимается, Message читается вторым участником', async () => {
|
||||
const attachment = await upload();
|
||||
const created = await send({ text: '', attachment_ids: [attachment.id] }).expect(201);
|
||||
expect(created.body.attachment_ids).toEqual([attachment.id]);
|
||||
const page = await request(server)
|
||||
.get(`/api/v1/chats/${chatId}/messages?limit=100`)
|
||||
.set('Authorization', bearer(bob))
|
||||
.expect(200);
|
||||
expect(page.body.items).toContainEqual(created.body);
|
||||
});
|
||||
|
||||
it('порядок [B, A] сохраняется в ответе, истории и повторе; перестановка с тем же ключом — 409', async () => {
|
||||
const a = await upload();
|
||||
const b = await upload();
|
||||
const key = randomUUID();
|
||||
const body = { text: 'order', attachment_ids: [b.id, a.id] };
|
||||
const created = await send(body, { key }).expect(201);
|
||||
expect(created.body.attachment_ids).toEqual([b.id, a.id]);
|
||||
const replay = await send(body, { key }).expect(201);
|
||||
expect(replay.body).toEqual(created.body);
|
||||
const page = await request(server)
|
||||
.get(`/api/v1/chats/${chatId}/messages?limit=100`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
expect(page.body.items.find((m: any) => m.id === created.body.id)).toEqual(created.body);
|
||||
const conflict = await send({ text: 'order', attachment_ids: [a.id, b.id] }, { key }).expect(409);
|
||||
expect(conflict.body.error.code).toBe('conflict');
|
||||
});
|
||||
|
||||
it('отсутствующий attachment_ids и [] равны при повторе, изменение списка — 409', async () => {
|
||||
const attachment = await upload();
|
||||
const key = randomUUID();
|
||||
const first = await send({ text: 'same' }, { key }).expect(201);
|
||||
expect(first.body.attachment_ids).toEqual([]);
|
||||
const replay = await send({ attachment_ids: [], text: 'same' }, { key }).expect(201);
|
||||
expect(replay.body).toEqual(first.body);
|
||||
await send({ text: 'same', attachment_ids: [attachment.id] }, { key }).expect(409);
|
||||
});
|
||||
|
||||
it('вложение другого чата и неизвестное — одинаковый 404, сообщение не создаётся', async () => {
|
||||
const foreign = await upload(eve, otherChatId);
|
||||
const key = randomUUID();
|
||||
const first = await send({ text: 'x', attachment_ids: [foreign.id] }, { key }).expect(404);
|
||||
const second = await send({ text: 'x', attachment_ids: [randomUUID()] }).expect(404);
|
||||
expect(first.body.error.code).toBe('not_found');
|
||||
expect(first.body.error.message).toBe(second.body.error.message);
|
||||
await send({ text: 'x' }, { key }).expect(201);
|
||||
});
|
||||
|
||||
it('смесь своего и чужого вложения — 404', async () => {
|
||||
const own = await upload();
|
||||
const foreign = await upload(eve, otherChatId);
|
||||
await send({ text: 'x', attachment_ids: [own.id, foreign.id] }).expect(404);
|
||||
});
|
||||
|
||||
it('посторонний не может отправить вложение в чужой чат', async () => {
|
||||
const attachment = await upload();
|
||||
await send({ text: 'x', attachment_ids: [attachment.id] }, { user: eve }).expect(404);
|
||||
});
|
||||
|
||||
it('любой участник может сослаться на вложение чата, вложение можно использовать повторно', async () => {
|
||||
const attachment = await upload();
|
||||
await send({ text: 'first', attachment_ids: [attachment.id] }).expect(201);
|
||||
const res = await send({ text: 'second', attachment_ids: [attachment.id] }, { user: bob }).expect(201);
|
||||
expect(res.body.sender_id).toBe(bob.id);
|
||||
expect(res.body.attachment_ids).toEqual([attachment.id]);
|
||||
});
|
||||
|
||||
it('ровно 10 вложений принимается, 11 — 400', async () => {
|
||||
const attachment = await upload();
|
||||
const links = await Promise.all(Array.from({ length: 9 }, () => upload()));
|
||||
const ten = [attachment.id, ...links.map((l) => l.id)];
|
||||
const created = await send({ text: 'ten', attachment_ids: ten }).expect(201);
|
||||
expect(created.body.attachment_ids).toEqual(ten);
|
||||
await send({ text: 'eleven', attachment_ids: [...ten, randomUUID()] }).expect(400);
|
||||
});
|
||||
|
||||
it('UUID в другом регистре — тот же ID и дубль', async () => {
|
||||
const attachment = await upload();
|
||||
const upper = attachment.id.toUpperCase();
|
||||
const created = await send({ text: 'case', attachment_ids: [upper] }).expect(201);
|
||||
expect(created.body.attachment_ids).toEqual([attachment.id]);
|
||||
await send({ text: 'dup', attachment_ids: [attachment.id, upper] }).expect(400);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['text отсутствует', (id: string) => ({ attachment_ids: [id] })],
|
||||
['text null', (id: string) => ({ text: null, attachment_ids: [id] })],
|
||||
['attachment_ids null', () => ({ text: 'x', attachment_ids: null })],
|
||||
['attachment_ids строка', (id: string) => ({ text: 'x', attachment_ids: id })],
|
||||
['элемент не UUID', () => ({ text: 'x', attachment_ids: ['nope'] })],
|
||||
['элемент число', () => ({ text: 'x', attachment_ids: [1] })],
|
||||
['дубликат', (id: string) => ({ text: 'x', attachment_ids: [id, id] })],
|
||||
['пустой текст без вложений', () => ({ text: '', attachment_ids: [] })],
|
||||
['пробельный текст без вложений', () => ({ text: ' ' })],
|
||||
])('%s — 400', async (_name, build) => {
|
||||
const attachment = await upload();
|
||||
await send(build(attachment.id)).expect(400);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function binaryParser(res: any, done: (error: Error | null, body: Buffer) => void): void {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
res.on('end', () => done(null, Buffer.concat(chunks)));
|
||||
}
|
||||
Reference in New Issue
Block a user