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>
161 lines
5.7 KiB
TypeScript
161 lines
5.7 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 { loginAs, authHeader } from '../helpers/auth';
|
|
|
|
/**
|
|
* Covers specs/003-ticketing/quickstart.md Scenarios 1, 2, 3, 6 end-to-end against a real
|
|
* Postgres/Redis.
|
|
*/
|
|
describe('Ticket creation via the inbound trust boundary', () => {
|
|
let app: FastifyInstance;
|
|
let secret: string;
|
|
let agentToken: string;
|
|
const externalProductId = `TEST_TICKET_PROD_${Date.now()}`;
|
|
|
|
beforeAll(async () => {
|
|
app = await buildApp();
|
|
agentToken = await loginAs(app, 'AGENT');
|
|
|
|
const product = await prismaClient.product.create({
|
|
data: { externalProductId, name: 'Ticket Test Product', status: 'active' },
|
|
});
|
|
|
|
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,
|
|
},
|
|
});
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await prismaClient.ticketMessage.deleteMany({
|
|
where: { ticket: { product: { externalProductId } } },
|
|
});
|
|
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();
|
|
});
|
|
|
|
function send(payload: Record<string, unknown>, userId = 'user-1') {
|
|
const token = issueIntegrationToken(secret, {
|
|
externalProductId,
|
|
tenantId: 'tenant-1',
|
|
userId,
|
|
});
|
|
return app.inject({
|
|
method: 'POST',
|
|
url: '/v1/support/requests',
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
productId: externalProductId,
|
|
tenantId: 'tenant-1',
|
|
userId,
|
|
source: 'test',
|
|
...payload,
|
|
},
|
|
});
|
|
}
|
|
|
|
it('Scenario 1: creates a ticket and problem immediately', async () => {
|
|
const response = await send({ problem: 'PDF to HTML conversion failed' });
|
|
expect(response.statusCode).toBe(202);
|
|
const body = response.json().data;
|
|
expect(body.status).toBe('NEW');
|
|
expect(body.ticketId).toBeDefined();
|
|
expect(body.code).toMatch(/^[A-Z]+-\d{4}-\d{5}$/);
|
|
|
|
const ticket = await prismaClient.ticket.findUnique({ where: { id: body.ticketId } });
|
|
expect(ticket).not.toBeNull();
|
|
const problem = await prismaClient.problem.findUnique({ where: { id: body.problemId } });
|
|
expect(problem).not.toBeNull();
|
|
});
|
|
|
|
it('Scenario 2: a retried idempotency key returns the same ticket, never a second one', async () => {
|
|
const idempotencyKey = `idem-${Date.now()}`;
|
|
const first = await send({ problem: 'duplicate check', idempotencyKey });
|
|
const second = await send({ problem: 'duplicate check', idempotencyKey });
|
|
|
|
expect(first.statusCode).toBe(202);
|
|
expect(second.statusCode).toBe(202);
|
|
expect(first.json().data.ticketId).toBe(second.json().data.ticketId);
|
|
|
|
const count = await prismaClient.ticket.count({
|
|
where: { product: { externalProductId }, idempotencyKey },
|
|
});
|
|
expect(count).toBe(1);
|
|
});
|
|
|
|
it('Scenario 3: an explicit reference links to the existing Problem instead of creating a new one', async () => {
|
|
const first = await send({ problem: 'recurring problem' });
|
|
const firstBody = first.json().data;
|
|
|
|
const second = await send({
|
|
problem: 'recurring problem, again',
|
|
referenceIds: [firstBody.problemId],
|
|
});
|
|
const secondBody = second.json().data;
|
|
|
|
expect(secondBody.problemId).toBe(firstBody.problemId);
|
|
expect(secondBody.ticketId).not.toBe(firstBody.ticketId);
|
|
});
|
|
|
|
it('Scenario 6: a stale-version status update is rejected, not silently overwritten', async () => {
|
|
const created = await send({ problem: 'concurrency check' });
|
|
const { ticketId } = created.json().data;
|
|
const ticket = await prismaClient.ticket.findUniqueOrThrow({ where: { id: ticketId } });
|
|
|
|
const first = await app.inject({
|
|
method: 'PATCH',
|
|
url: `/tickets/${ticketId}/status`,
|
|
headers: authHeader(agentToken),
|
|
payload: { status: 'AI_ANALYZING', expectedVersion: ticket.version },
|
|
});
|
|
const second = await app.inject({
|
|
method: 'PATCH',
|
|
url: `/tickets/${ticketId}/status`,
|
|
headers: authHeader(agentToken),
|
|
payload: { status: 'HUMAN_ESCALATION', expectedVersion: ticket.version },
|
|
});
|
|
|
|
const results = [first.statusCode, second.statusCode].sort();
|
|
expect(results).toEqual([200, 409]);
|
|
|
|
const finalTicket = await prismaClient.ticket.findUniqueOrThrow({ where: { id: ticketId } });
|
|
expect(finalTicket.version).toBe(ticket.version + 1);
|
|
});
|
|
|
|
it('rejects an invalid status transition', async () => {
|
|
const created = await send({ problem: 'invalid transition check' });
|
|
const { ticketId } = created.json().data;
|
|
const ticket = await prismaClient.ticket.findUniqueOrThrow({ where: { id: ticketId } });
|
|
|
|
const response = await app.inject({
|
|
method: 'PATCH',
|
|
url: `/tickets/${ticketId}/status`,
|
|
headers: authHeader(agentToken),
|
|
payload: { status: 'RESOLVED', expectedVersion: ticket.version },
|
|
});
|
|
|
|
expect(response.statusCode).toBe(400);
|
|
expect(response.json().error.code).toBe('INVALID_TRANSITION');
|
|
});
|
|
});
|