Files
support_backend/tests/integration/product-integrations-admin.test.ts
T
saqib mirandClaude Sonnet 5 3e2a5b97a3 feat: admin lifecycle endpoints for product integrations (US2)
Implements tasks T021-T025 from specs/002-saas-integration/tasks.md
(User Story 2, P2): an admin can register, rotate, revoke, and change
the status of a ProductIntegration, and retrieve its audit trail.

- ProductIntegrationsService: register (finds-or-creates the Product
  by external id), rotate (dual-credential transition window per
  research.md), revoke, updateStatus, getAuditTrail -- each writes
  its own AuditLog entry via a new shared
  integration-audit-log.repository.ts (extracted from the auth
  plugin, which now reuses it instead of writing to Prisma directly).
- Routes: POST /admin/products/:externalProductId/integration,
  POST/admin/integrations/:id/rotate|revoke, PATCH .../status,
  GET .../audit-trail -- gated by the existing fastify.authenticate
  (human/admin JWT) decorator.
- New integration test (product-integrations-admin.test.ts) covers
  Quickstart Scenarios 5-7 end-to-end against a real Postgres/Redis:
  register+rotate+audit-trail, and revoke-takes-effect-immediately.
  Verified passing against a live database.

Known, pre-existing limitation flagged (not fixed here, out of
scope): fastify.authenticate is currently a no-op stub with no real
JWT verification, so these admin endpoints aren't actually
access-controlled yet -- that depends on the unimplemented
identity/auth module. Documented in the contract and checklist notes
so it isn't mistaken for done.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 18:57:07 +05:30

136 lines
5.0 KiB
TypeScript

import { describe, it, expect, afterAll } from 'vitest';
import { buildApp } from '@/app';
import { prismaClient } from '@/infrastructure/database';
import { FastifyInstance } from 'fastify';
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;
const externalProductId = `TEST_ADMIN_PROD_${Date.now()}`;
afterAll(async () => {
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();
const registerResponse = await app.inject({
method: 'POST',
url: `/admin/products/${externalProductId}/integration`,
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`,
});
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`,
});
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`,
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`,
});
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` },
});
});
});