Implements all 39 tasks from specs/003-ticketing/tasks.md across all
three user stories -- Phase 5 of the roadmap.
Schema (prisma/schema.prisma + migration):
- Ticket (code, status, version for optimistic concurrency,
idempotencyKey, customerId FK), Problem, TicketMessage,
TicketAttachment per docs/06, with Product/Category/
CustomerReference back-relations.
User Story 1 -- ticket/problem creation (P1, MVP):
- Explicit 12-state lifecycle adjacency table
(ticket-state-machine.ts), not "any transition allowed."
- Ticket code generation (<PRODUCT_CODE>-<YEAR>-<SEQUENCE>) scoped
by the actual code prefix, not productId -- see the collision bug
fixed below.
- Idempotency-key enforcement via atomic create-then-catch-conflict
(never a read-then-write race), completing the FR-012 placeholder
from 002-saas-integration.
- Explicit-reference-only recurring-problem linking (no fuzzy
matching -- that's a future AI-support concern).
- POST /v1/support/requests (002-saas-integration) now creates a
real ticket instead of echoing context back.
- PATCH /tickets/:id/status with expectedVersion-based optimistic
concurrency (409 on stale version, 400 on an invalid transition).
User Story 2 -- typed messages (P2):
- Message type -> visibleToCustomer mapping is a fixed constant map,
never caller-supplied; customer-scoped reads filter at the query
layer so an internal note is never fetched, not just hidden.
- POST/GET /tickets/:id/messages (customer-scoped) and
GET /agent/tickets/:id/messages (agent-scoped).
User Story 3 -- attachment pipeline (P3):
- Presigned-PUT upload (new getPresignedUploadUrl on the existing
storageService) -- file bytes never transit this API.
- A MalwareScanner interface with a fail-closed placeholder
(UnimplementedPlaceholderScanner) since no scanner exists in this
stack -- it always reports 'infected', never silently 'clean'.
- The existing attachments-queue job stub now actually calls the
scanner and updates scanStatus; registerAttachmentWorker() is
wired into bootstrapQueue() (previously defined but never called).
- Downloads are gated on scanStatus === 'clean' -- currently always
refused until a real scanner replaces the placeholder.
- MinIO added to docker-compose.{test,development}.yml for local/CI
S3-compatible storage, matching doc 04's explicit guidance.
Two real bugs found and fixed via integration testing against a
live Postgres/Redis/MinIO (not just typechecked):
- Ticket codes could collide across different products: the
sequence counter was scoped by internal productId, but the code
column's uniqueness is global, and deriveProductCode's 4-character
truncation means different products can share a prefix. Fixed by
counting against the actual code prefix instead.
- Three existing 002-saas-integration integration tests' cleanup
started failing an FK RESTRICT check once ticket creation was
wired in (deleting a Product before the Ticket/Problem that now
reference it). Fixed their afterAll ordering.
All 9 integration test files (24 tests, spanning this feature and
the pre-existing suite) verified passing against real Postgres,
Redis, and MinIO, including a genuine presigned-PUT/GET round trip.
Full quality gate (typecheck/lint/format/architecture/unit tests)
passes.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
183 lines
6.9 KiB
TypeScript
183 lines
6.9 KiB
TypeScript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
|
import { buildApp } from '@/app';
|
|
import { prismaClient } from '@/infrastructure/database';
|
|
import { FastifyInstance } from 'fastify';
|
|
import {
|
|
encryptCredential,
|
|
generateCredentialSecret,
|
|
issueIntegrationToken,
|
|
} from '@/modules/catalog/products';
|
|
import { malwareScanner } from '@/modules/ticketing/attachments';
|
|
|
|
/** Covers specs/003-ticketing/quickstart.md Scenario 5 against a real Postgres/Redis/MinIO. */
|
|
describe('Ticket attachments — upload, confirm, scan-gated download', () => {
|
|
let app: FastifyInstance;
|
|
let ticketId: string;
|
|
const externalProductId = `TEST_ATT_PROD_${Date.now()}`;
|
|
|
|
beforeAll(async () => {
|
|
app = await buildApp();
|
|
|
|
const product = await prismaClient.product.create({
|
|
data: { externalProductId, name: 'Attachments Test Product', status: 'active' },
|
|
});
|
|
const secret = generateCredentialSecret();
|
|
await prismaClient.productIntegration.create({
|
|
data: {
|
|
productId: product.id,
|
|
credentialRef: encryptCredential(secret),
|
|
authMechanism: 'signed_token',
|
|
allowedScope: { tenantIds: ['tenant-1'] },
|
|
status: 'active',
|
|
rateLimitPerMinute: 1000,
|
|
rateLimitPerUserPerMinute: 1000,
|
|
},
|
|
});
|
|
|
|
const token = issueIntegrationToken(secret, {
|
|
externalProductId,
|
|
tenantId: 'tenant-1',
|
|
userId: 'user-1',
|
|
});
|
|
const created = await app.inject({
|
|
method: 'POST',
|
|
url: '/v1/support/requests',
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
productId: externalProductId,
|
|
tenantId: 'tenant-1',
|
|
userId: 'user-1',
|
|
source: 'test',
|
|
problem: 'attachment pipeline check',
|
|
},
|
|
});
|
|
ticketId = created.json().data.ticketId;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await prismaClient.ticketAttachment.deleteMany({ where: { ticketId } });
|
|
await prismaClient.ticketMessage.deleteMany({ where: { ticketId } });
|
|
await prismaClient.ticket.deleteMany({ where: { product: { externalProductId } } });
|
|
await prismaClient.problem.deleteMany({ where: { product: { externalProductId } } });
|
|
await prismaClient.productIntegration.deleteMany({
|
|
where: { product: { externalProductId } },
|
|
});
|
|
await prismaClient.product.deleteMany({ where: { externalProductId } });
|
|
await app.close();
|
|
});
|
|
|
|
it('rejects an oversized upload before it ever reaches object storage', async () => {
|
|
const response = await app.inject({
|
|
method: 'POST',
|
|
url: `/tickets/${ticketId}/attachments/upload-url`,
|
|
payload: { fileName: 'huge.pdf', mimeType: 'application/pdf', sizeBytes: 999_999_999 },
|
|
});
|
|
expect(response.statusCode).toBe(400);
|
|
});
|
|
|
|
it('rejects a disallowed mime type', async () => {
|
|
const response = await app.inject({
|
|
method: 'POST',
|
|
url: `/tickets/${ticketId}/attachments/upload-url`,
|
|
payload: { fileName: 'evil.exe', mimeType: 'application/x-msdownload', sizeBytes: 100 },
|
|
});
|
|
expect(response.statusCode).toBe(400);
|
|
});
|
|
|
|
it('an uploaded attachment is refused for download while pending, and stays refused after the placeholder scanner marks it infected', async () => {
|
|
const uploadUrlResponse = await app.inject({
|
|
method: 'POST',
|
|
url: `/tickets/${ticketId}/attachments/upload-url`,
|
|
payload: { fileName: 'screenshot.png', mimeType: 'image/png', sizeBytes: 1024 },
|
|
});
|
|
expect(uploadUrlResponse.statusCode).toBe(200);
|
|
const { uploadUrl, storageKey } = uploadUrlResponse.json().data;
|
|
|
|
const putResponse = await fetch(uploadUrl, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'image/png' },
|
|
body: Buffer.from('fake-png-bytes'),
|
|
});
|
|
expect(putResponse.ok).toBe(true);
|
|
|
|
const confirmResponse = await app.inject({
|
|
method: 'POST',
|
|
url: `/tickets/${ticketId}/attachments/confirm`,
|
|
payload: { storageKey, fileName: 'screenshot.png', mimeType: 'image/png', sizeBytes: 1024 },
|
|
});
|
|
expect(confirmResponse.statusCode).toBe(201);
|
|
const attachmentId = confirmResponse.json().data.id;
|
|
expect(confirmResponse.json().data.scanStatus).toBe('pending');
|
|
|
|
const downloadWhilePending = await app.inject({
|
|
method: 'GET',
|
|
url: `/tickets/${ticketId}/attachments/${attachmentId}/download-url`,
|
|
});
|
|
expect(downloadWhilePending.statusCode).toBe(409);
|
|
|
|
// Run the scan job inline (no worker process in this test) — same call the queue worker
|
|
// makes, per src/jobs/attachments/index.ts.
|
|
const result = await malwareScanner.scan(storageKey);
|
|
await prismaClient.ticketAttachment.update({
|
|
where: { id: attachmentId },
|
|
data: { scanStatus: result },
|
|
});
|
|
|
|
const downloadAfterScan = await app.inject({
|
|
method: 'GET',
|
|
url: `/tickets/${ticketId}/attachments/${attachmentId}/download-url`,
|
|
});
|
|
// The placeholder scanner fails closed (always 'infected'), so this remains refused —
|
|
// proving the pipeline actually gates on a real scan result rather than defaulting open.
|
|
expect(downloadAfterScan.statusCode).toBe(409);
|
|
|
|
const attachment = await prismaClient.ticketAttachment.findUniqueOrThrow({
|
|
where: { id: attachmentId },
|
|
});
|
|
expect(attachment.scanStatus).toBe('infected');
|
|
});
|
|
|
|
it('a clean attachment produces a working, time-limited download URL', async () => {
|
|
const uploadUrlResponse = await app.inject({
|
|
method: 'POST',
|
|
url: `/tickets/${ticketId}/attachments/upload-url`,
|
|
payload: { fileName: 'clean.pdf', mimeType: 'application/pdf', sizeBytes: 2048 },
|
|
});
|
|
const { uploadUrl, storageKey } = uploadUrlResponse.json().data;
|
|
await fetch(uploadUrl, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/pdf' },
|
|
body: Buffer.from('fake-pdf-bytes'),
|
|
});
|
|
|
|
const confirmResponse = await app.inject({
|
|
method: 'POST',
|
|
url: `/tickets/${ticketId}/attachments/confirm`,
|
|
payload: { storageKey, fileName: 'clean.pdf', mimeType: 'application/pdf', sizeBytes: 2048 },
|
|
});
|
|
const attachmentId = confirmResponse.json().data.id;
|
|
|
|
// Simulate a real scanner reporting clean, bypassing the fail-closed placeholder directly
|
|
// at the repository layer — this test's job is to prove the DOWNLOAD gate respects
|
|
// scanStatus, not to re-test the placeholder scanner itself (covered by
|
|
// tests/unit/ticketing/malware-scanner.test.ts).
|
|
await prismaClient.ticketAttachment.update({
|
|
where: { id: attachmentId },
|
|
data: { scanStatus: 'clean' },
|
|
});
|
|
|
|
const downloadResponse = await app.inject({
|
|
method: 'GET',
|
|
url: `/tickets/${ticketId}/attachments/${attachmentId}/download-url`,
|
|
});
|
|
expect(downloadResponse.statusCode).toBe(200);
|
|
const { downloadUrl } = downloadResponse.json().data;
|
|
expect(downloadUrl).toContain(storageKey);
|
|
|
|
const fetched = await fetch(downloadUrl);
|
|
expect(fetched.ok).toBe(true);
|
|
const body = await fetched.text();
|
|
expect(body).toBe('fake-pdf-bytes');
|
|
});
|
|
});
|