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, processAttachment, 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(202); expect(await processAttachment(app, res.body.id)).toBe('ready'); const ready = await request(server) .get(`/api/v1/attachments/${res.body.id}`) .set('Authorization', bearer(user)) .expect(200); return ready.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.each([ ['nil', '00000000-0000-0000-0000-000000000000'], ['v7', '018f6f3a-7b1c-7def-8abc-0123456789ab'], ])('UUID %s корректного формата — 404, а не 400', async (_name, id) => { await get(`/api/v1/attachments/${id}`).expect(404); await get(`/api/v1/attachments/${id}/content`).expect(404); await get(`/api/v1/chats/${id}`, alice).expect(404); await send({ text: 'x', attachment_ids: [id] }).expect(404); await send({ text: 'x' }, { chat: id }).expect(404); await request(server) .post(`/api/v1/chats/${id}/attachments?filename=a.png`) .set('Authorization', bearer(alice)) .set('Content-Type', 'image/png') .send(SAMPLE_PNG) .expect(404); }); 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(200); await app.get(PrismaService).attachmentVariant.deleteMany({ where: { attachmentId: id, name: 'crop' }, }); await get(`/api/v1/attachments/${id}/content?variant=crop`).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))); }