Files
saqib mirandClaude Sonnet 5 40687f68fa feat(010-identity-auth): real staff login, session verification, and role gating
Replaces the no-op fastify.authenticate stub and the never-implemented
identity/auth login with real bcrypt password verification, JWT session
issuance/verification (reusing the existing JWT_SECRET), and a Redis-backed
revocation denylist for logout. Adds requireRole('ADMIN') to admin-only
configuration writes across 002-009 that previously relied on a decorator
that never actually checked anything. Adds self-identity (GET /auth/me,
re-validated against live account state) and admin-provisioned accounts
(POST /admin/users).

Making the auth check genuinely reject invalid/missing tokens exposed that
~18 pre-existing integration test files called already-gated routes with no
Authorization header (safe against the old no-op stub, broken against a real
one) — fixed via a shared tests/helpers/auth.ts (loginAs/authHeader) and a
file-by-file pass, plus two related SLA-run cleanup races exposed once admin
setup calls in those files' own beforeAll blocks started actually succeeding.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:45:37 +05:30

196 lines
7.4 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { buildApp } from '@/app';
import { prismaClient } from '@/infrastructure/database';
import { FastifyInstance } from 'fastify';
import { loginAs, authHeader } from '../helpers/auth';
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 agentToken: string;
let ticketId: string;
const externalProductId = `TEST_ATT_PROD_${Date.now()}`;
beforeAll(async () => {
app = await buildApp();
agentToken = await loginAs(app, 'AGENT');
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`,
headers: authHeader(agentToken),
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`,
headers: authHeader(agentToken),
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`,
headers: authHeader(agentToken),
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`,
headers: authHeader(agentToken),
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`,
headers: authHeader(agentToken),
});
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`,
headers: authHeader(agentToken),
});
// 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`,
headers: authHeader(agentToken),
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`,
headers: authHeader(agentToken),
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`,
headers: authHeader(agentToken),
});
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');
});
});