Files
support_backend/tests/integration/ticket-messages.test.ts
T
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

125 lines
4.3 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 { MESSAGE_TYPES } from '@/modules/ticketing/messages/mapper/message-visibility';
import { loginAs, authHeader } from '../helpers/auth';
/** Covers specs/003-ticketing/quickstart.md Scenario 4 against a real Postgres. */
describe('Ticket messages — type-scoped visibility', () => {
let app: FastifyInstance;
let ticketId: string;
let authToken: string;
const externalProductId = `TEST_MSG_PROD_${Date.now()}`;
beforeAll(async () => {
app = await buildApp();
authToken = await loginAs(app, 'AGENT');
const product = await prismaClient.product.create({
data: { externalProductId, name: 'Messages 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: 'message visibility check',
},
});
ticketId = created.json().data.ticketId;
for (const type of MESSAGE_TYPES) {
const response = await app.inject({
method: 'POST',
url: `/tickets/${ticketId}/messages`,
headers: authHeader(authToken),
payload: { type, body: `Message of type ${type}` },
});
expect(response.statusCode).toBe(201);
}
});
afterAll(async () => {
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('a customer-scoped read excludes internal-only types entirely', async () => {
const response = await app.inject({
method: 'GET',
url: `/tickets/${ticketId}/messages`,
headers: authHeader(authToken),
});
expect(response.statusCode).toBe(200);
const types = response.json().data.map((m: { type: string }) => m.type);
expect(types).toContain('CUSTOMER_MESSAGE');
expect(types).toContain('AI_MESSAGE');
expect(types).toContain('AGENT_MESSAGE');
expect(types).toContain('SYSTEM_EVENT');
expect(types).not.toContain('INTERNAL_NOTE');
expect(types).not.toContain('INVESTIGATION_NOTE');
expect(types).not.toContain('SOLUTION_NOTE');
});
it('an agent-scoped read includes every message type, including internal notes', async () => {
const response = await app.inject({
method: 'GET',
url: `/agent/tickets/${ticketId}/messages`,
headers: authHeader(authToken),
});
expect(response.statusCode).toBe(200);
const types = response.json().data.map((m: { type: string }) => m.type);
for (const type of MESSAGE_TYPES) {
expect(types).toContain(type);
}
// +1 for the SYSTEM_EVENT ticket-creation message written by TicketsService itself.
expect(types.length).toBe(MESSAGE_TYPES.length + 1);
});
it('rejects a message with an undefined type', async () => {
const response = await app.inject({
method: 'POST',
url: `/tickets/${ticketId}/messages`,
headers: authHeader(authToken),
payload: { type: 'NOT_A_REAL_TYPE', body: 'x' },
});
expect(response.statusCode).toBe(400);
});
});