Files
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

139 lines
5.3 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';
import { loginAs, authHeader } from '../helpers/auth';
/**
* Covers specs/002-saas-integration/quickstart.md Scenario 8 (integration-level and per-user
* rate limiting) against a real Postgres/Redis.
*/
describe('Inbound rate limiting', () => {
let app: FastifyInstance;
let adminToken: string;
const externalProductId = `TEST_RATELIMIT_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('throttles an integration once it exceeds its per-minute limit, and independently throttles a single user within it', async () => {
app = await buildApp();
adminToken = await loginAs(app, 'ADMIN');
const registerResponse = await app.inject({
method: 'POST',
url: `/admin/products/${externalProductId}/integration`,
headers: authHeader(adminToken),
payload: {
name: 'Rate Limit Test Product',
allowedScope: { tenantIds: ['tenant-1'] },
rateLimitPerMinute: 5,
rateLimitPerUserPerMinute: 2,
},
});
expect(registerResponse.statusCode).toBe(201);
const { credentialSecret } = registerResponse.json().data;
const send = (userId: string) =>
app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: {
authorization: `Bearer ${issueIntegrationToken(credentialSecret, { externalProductId, tenantId: 'tenant-1', userId })}`,
},
payload: {
productId: externalProductId,
tenantId: 'tenant-1',
userId,
source: 'test',
problem: 'rate limit check',
},
});
// User A sends 2 requests (its own limit) — both succeed.
const a1 = await send('user-a');
const a2 = await send('user-a');
expect(a1.statusCode).toBe(202);
expect(a2.statusCode).toBe(202);
// User A's 3rd request exceeds its per-user limit (2/min) even though the integration
// limit (5/min) hasn't been hit yet.
const a3 = await send('user-a');
expect(a3.statusCode).toBe(429);
expect(a3.json().error.code).toBe('RATE_LIMIT_EXCEEDED');
// A different user under the same integration is unaffected by user-a's throttling.
const b1 = await send('user-b');
expect(b1.statusCode).toBe(202);
});
it('throttles at the integration level even when no single user has hit their own limit', async () => {
const registerResponse = await app.inject({
method: 'POST',
url: `/admin/products/${externalProductId}-int/integration`,
headers: authHeader(adminToken),
payload: {
name: 'Rate Limit Test Product (integration-level)',
allowedScope: { tenantIds: ['tenant-1'] },
rateLimitPerMinute: 5,
rateLimitPerUserPerMinute: 100,
},
});
const { credentialSecret } = registerResponse.json().data;
const productId = `${externalProductId}-int`;
const send = (userId: string) =>
app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: {
authorization: `Bearer ${issueIntegrationToken(credentialSecret, { externalProductId: productId, tenantId: 'tenant-1', userId })}`,
},
payload: {
productId,
tenantId: 'tenant-1',
userId,
source: 'test',
problem: 'integration-level rate limit check',
},
});
// 5 distinct users, one request each — all within the integration's 5/min cap.
for (const userId of ['u1', 'u2', 'u3', 'u4', 'u5']) {
const response = await send(userId);
expect(response.statusCode).toBe(202);
}
// A 6th distinct user's first-ever request still gets throttled, because the
// INTEGRATION's own limit (not this user's, who has never been throttled) is exhausted.
const sixth = await send('u6');
expect(sixth.statusCode).toBe(429);
expect(sixth.json().error.code).toBe('RATE_LIMIT_EXCEEDED');
await prismaClient.ticketMessage.deleteMany({
where: { ticket: { product: { externalProductId: productId } } },
});
await prismaClient.ticket.deleteMany({ where: { product: { externalProductId: productId } } });
await prismaClient.problem.deleteMany({
where: { product: { externalProductId: productId } },
});
await prismaClient.productIntegration.deleteMany({
where: { product: { externalProductId: productId } },
});
await prismaClient.product.deleteMany({ where: { externalProductId: productId } });
});
});