Files
support_backend/tests/integration/product-integration-auth.test.ts
T
saqib mirandClaude Sonnet 5 8d5731340d feat: implement SaaS product integration trust boundary (US1 MVP)
Implements tasks T001-T020 from specs/002-saas-integration/tasks.md
(Setup, Foundational, and User Story 1 - the P1 MVP: every inbound
request is authenticated and trusted before anything happens).
User Story 2 (admin onboarding/rotation/revocation) and User Story 3
(rate limiting) are not yet implemented (T021-T032 remain).

Schema (prisma/schema.prisma + initial migration):
- Replace the placeholder Product model (leftover starter-template
  scaffolding: code/description/ProductStatus enum) with the real
  docs/06-database-schema.md shape (externalProductId,
  supportEnabled, status).
- Add ProductIntegration (credential ref, rotation/revocation state,
  allowed scope, per-integration/per-user rate limits) and
  CustomerReference models.
- Align AuditLog to docs/06's shape (actor/actorType/entityType/
  entityId/reason/metadata) -- the placeholder shape had no fields
  to satisfy this feature's audit requirements.

Auth:
- HMAC-signed short-lived tokens (issue/verify) with jti-based replay
  defense via Redis and a bounded clock-skew tolerance.
- Credential secrets are AES-256-GCM encrypted at rest (new required
  INTEGRATION_CREDENTIAL_ENCRYPTION_KEY env var) since no secret
  manager exists in this stack yet -- see research.md "Credential
  storage".
- New product-integration-auth.plugin.ts Fastify plugin runs the
  validation order in contracts/inbound-request-contract.md and
  populates request.reqContext only on full success; every attempt
  (success or failure) is audit-logged without ever persisting the
  raw token/credential. Unregistered product and invalid credential
  return an identical response (FR-010).
- New POST /v1/support/requests endpoint exercises the boundary
  end-to-end (ticket creation itself is a future feature).

Also:
- Fix docker-compose.test.yml's container_name collisions --
  discovered while testing this change concurrently is now covered
  by an app-level regression test (separate commit).
- Fix test:unit to scope to tests/unit only (it was running the
  entire tests/** glob including integration tests) -- this feature's
  new integration test makes real Prisma/Redis calls, unlike the
  prior instantiation-only checks, so the existing glob-scoping gap
  became actually harmful.
- Update Jenkinsfile with the new required credential.

Verified: full quality gate (typecheck/lint/format/architecture/
unit tests) passes; all of User Story 1's quickstart scenarios
manually verified end-to-end against a live server + Postgres +
Redis; the new integration test suite verified against a live
database (not run as part of `npm test`, matches existing
test:integration convention).

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

172 lines
5.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';
/**
* Covers specs/002-saas-integration/quickstart.md Scenarios 1, 2, 4 end-to-end against a real
* Postgres/Redis (matching the vitest env DATABASE_URL/REDIS_* config — requires
* docker-compose.test.yml's postgres/redis services to be reachable at that address; see
* specs/002-saas-integration/checklists/requirements.md implementation notes for a known gap
* in how the current test DATABASE_URL is wired to those services).
*/
describe('Product Integration Auth (full preHandler)', () => {
let app: FastifyInstance;
let secret: string;
const externalProductId = `TEST_PROD_${Date.now()}`;
beforeAll(async () => {
app = await buildApp();
const product = await prismaClient.product.create({
data: { externalProductId, name: 'Integration 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',
},
});
});
afterAll(async () => {
await prismaClient.productIntegration.deleteMany({
where: { product: { externalProductId } },
});
await prismaClient.product.deleteMany({ where: { externalProductId } });
await app.close();
});
it('Scenario 1: accepts a valid, in-scope request', async () => {
const token = issueIntegrationToken(secret, {
externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
});
const response = 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: 'test problem',
},
});
expect(response.statusCode).toBe(202);
expect(response.json()).toMatchObject({ success: true });
});
it('Scenario 2: rejects an invalid credential and an unregistered product identically', async () => {
const badToken = issueIntegrationToken('wrong-secret', {
externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
});
const invalidCredentialResponse = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: { authorization: `Bearer ${badToken}` },
payload: {
productId: externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
source: 'test',
problem: 'x',
},
});
const unregisteredResponse = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: { authorization: `Bearer ${badToken}` },
payload: {
productId: 'NEVER_REGISTERED',
tenantId: 'tenant-1',
userId: 'user-1',
source: 'test',
problem: 'x',
},
});
expect(invalidCredentialResponse.statusCode).toBe(401);
expect(unregisteredResponse.statusCode).toBe(401);
// Same error shape for both — a caller cannot tell "wrong credential" apart from
// "unregistered product" (FR-010). Compare everything except the per-request requestId.
expect(invalidCredentialResponse.json().error).toEqual(unregisteredResponse.json().error);
expect(invalidCredentialResponse.json().error.code).toBe('INVALID_INTEGRATION_CREDENTIAL');
});
it('Scenario 4: rejects a request with an unrecognized field', async () => {
const token = issueIntegrationToken(secret, {
externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
});
const response = 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: 'x',
somethingUnexpected: true,
},
});
expect(response.statusCode).toBe(400);
expect(response.json().error.code).toBe('VALIDATION_ERROR');
});
it('replay of the same token is rejected on the second use', async () => {
const token = issueIntegrationToken(secret, {
externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
});
const payload = {
productId: externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
source: 'test',
problem: 'replay check',
};
const first = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: { authorization: `Bearer ${token}` },
payload,
});
const second = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: { authorization: `Bearer ${token}` },
payload,
});
expect(first.statusCode).toBe(202);
expect(second.statusCode).toBe(401);
expect(second.json().error.code).toBe('INVALID_INTEGRATION_CREDENTIAL');
});
});