Files
support_backend/tests/integration/product-integrations-admin.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

152 lines
5.7 KiB
TypeScript

import { describe, it, expect, afterAll } from 'vitest';
import { buildApp } from '@/app';
import { prismaClient } from '@/infrastructure/database';
import { FastifyInstance } from 'fastify';
import { loginAs, authHeader } from '../helpers/auth';
import { issueIntegrationToken } from '@/modules/catalog/products';
/**
* Covers specs/002-saas-integration/quickstart.md Scenarios 5-7 (rotation zero-downtime,
* revocation is immediate, audit trail is retrievable) against a real Postgres/Redis. See
* specs/002-saas-integration/checklists/requirements.md implementation notes for the known
* DATABASE_URL wiring gap this test shares with tests/integration/product-integration-auth.test.ts.
*/
describe('Product Integration Admin Lifecycle', () => {
let app: FastifyInstance;
let token: string;
const externalProductId = `TEST_ADMIN_PROD_${Date.now()}`;
afterAll(async () => {
// A successful request now also creates a Ticket/Problem (specs/003-ticketing) — those
// must be cleaned up before the Product they reference, or the FK RESTRICT blocks it.
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();
});
it('Scenario 5+7: register, then rotate — both old and new credential work during the transition window, and the audit trail records every step', async () => {
app = await buildApp();
token = await loginAs(app, 'ADMIN');
const registerResponse = await app.inject({
method: 'POST',
url: `/admin/products/${externalProductId}/integration`,
headers: authHeader(token),
payload: {
name: 'Admin Test Product',
allowedScope: { tenantIds: ['tenant-1'] },
},
});
expect(registerResponse.statusCode).toBe(201);
const registered = registerResponse.json().data;
const originalSecret = registered.credentialSecret;
const integrationId = registered.integrationId;
const rotateResponse = await app.inject({
method: 'POST',
url: `/admin/integrations/${integrationId}/rotate`,
headers: authHeader(token),
});
expect(rotateResponse.statusCode).toBe(200);
const rotated = rotateResponse.json().data;
const newSecret = rotated.credentialSecret;
expect(newSecret).not.toBe(originalSecret);
const oldTokenRequest = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: {
authorization: `Bearer ${issueIntegrationToken(originalSecret, { externalProductId, tenantId: 'tenant-1', userId: 'user-1' })}`,
},
payload: {
productId: externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
source: 'test',
problem: 'old credential still valid during transition',
},
});
const newTokenRequest = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: {
authorization: `Bearer ${issueIntegrationToken(newSecret, { externalProductId, tenantId: 'tenant-1', userId: 'user-2' })}`,
},
payload: {
productId: externalProductId,
tenantId: 'tenant-1',
userId: 'user-2',
source: 'test',
problem: 'new credential valid',
},
});
expect(oldTokenRequest.statusCode).toBe(202);
expect(newTokenRequest.statusCode).toBe(202);
const auditResponse = await app.inject({
method: 'GET',
url: `/admin/integrations/${integrationId}/audit-trail`,
headers: authHeader(token),
});
expect(auditResponse.statusCode).toBe(200);
const actions = auditResponse.json().data.map((e: { action: string }) => e.action);
expect(actions).toContain('integration.registered');
expect(actions).toContain('integration.rotated');
expect(actions.filter((a: string) => a === 'integration.auth.success')).toHaveLength(2);
});
it('Scenario 6: revocation takes effect on the very next request', async () => {
const registerResponse = await app.inject({
method: 'POST',
url: `/admin/products/${externalProductId}-revoke/integration`,
headers: authHeader(token),
payload: {
name: 'Admin Test Product Revoke',
allowedScope: { tenantIds: ['tenant-1'] },
},
});
const { credentialSecret, integrationId } = registerResponse.json().data;
const revokeResponse = await app.inject({
method: 'POST',
url: `/admin/integrations/${integrationId}/revoke`,
headers: authHeader(token),
});
expect(revokeResponse.statusCode).toBe(200);
const requestAfterRevoke = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: {
authorization: `Bearer ${issueIntegrationToken(credentialSecret, { externalProductId: `${externalProductId}-revoke`, tenantId: 'tenant-1', userId: 'user-1' })}`,
},
payload: {
productId: `${externalProductId}-revoke`,
tenantId: 'tenant-1',
userId: 'user-1',
source: 'test',
problem: 'should be rejected',
},
});
expect(requestAfterRevoke.statusCode).toBe(401);
expect(requestAfterRevoke.json().error.code).toBe('INVALID_INTEGRATION_CREDENTIAL');
await prismaClient.productIntegration.deleteMany({
where: { product: { externalProductId: `${externalProductId}-revoke` } },
});
await prismaClient.product.deleteMany({
where: { externalProductId: `${externalProductId}-revoke` },
});
});
});