create-tigra 3.3.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sendEmail (../email.ts) with Resend mocked: a hung Resend gives up after
|
|
3
|
+
* 10 s, and no log line ever carries a full recipient address.
|
|
4
|
+
*/
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
6
|
+
import { logger } from '@libs/logger.js';
|
|
7
|
+
|
|
8
|
+
const send = vi.hoisted(() => vi.fn());
|
|
9
|
+
vi.mock('resend', () => ({
|
|
10
|
+
Resend: class {
|
|
11
|
+
emails = { send };
|
|
12
|
+
},
|
|
13
|
+
}));
|
|
14
|
+
vi.mock('@config/env.js', () => ({ env: { RESEND_API_KEY: 're_test', RESEND_FROM_EMAIL: 'noreply@example.test' } }));
|
|
15
|
+
vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
16
|
+
|
|
17
|
+
const { sendEmail, maskEmail } = await import('../email.js');
|
|
18
|
+
const TO = 'anna.smith@example.test';
|
|
19
|
+
const mail = { to: TO, subject: 'Hi', html: '<p>Hi</p>' };
|
|
20
|
+
const logged = (): string => JSON.stringify([...vi.mocked(logger.info).mock.calls, ...vi.mocked(logger.error).mock.calls]);
|
|
21
|
+
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
vi.clearAllMocks();
|
|
24
|
+
});
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
vi.useRealTimers();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe('maskEmail', () => {
|
|
30
|
+
it.each([
|
|
31
|
+
['anna@example.com', 'an***@example.com'],
|
|
32
|
+
['a@example.com', 'a***@example.com'],
|
|
33
|
+
['not-an-address', '***'],
|
|
34
|
+
['@example.com', '***'],
|
|
35
|
+
['anna@', '***'],
|
|
36
|
+
])('%s → %s', (address, masked) => {
|
|
37
|
+
expect(maskEmail(address)).toBe(masked);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe('sendEmail', () => {
|
|
42
|
+
it('sends and logs the recipient masked', async () => {
|
|
43
|
+
send.mockResolvedValue({ data: { id: 'e1' }, error: null });
|
|
44
|
+
await sendEmail(mail);
|
|
45
|
+
expect(send).toHaveBeenCalledWith({ from: 'noreply@example.test', ...mail });
|
|
46
|
+
expect(logger.info).toHaveBeenCalledWith({ to: 'an***@example.test' }, '[EMAIL] Email sent successfully');
|
|
47
|
+
expect(logged()).not.toContain(TO);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('a Resend error is logged masked and thrown as a generic InternalError', async () => {
|
|
51
|
+
send.mockResolvedValue({ data: null, error: { message: 'invalid from address' } });
|
|
52
|
+
await expect(sendEmail(mail)).rejects.toMatchObject({ statusCode: 500, message: 'Failed to send email' });
|
|
53
|
+
expect(logged()).not.toContain(TO);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('gives up after 10 s when Resend hangs', async () => {
|
|
57
|
+
vi.useFakeTimers();
|
|
58
|
+
send.mockReturnValue(new Promise(() => undefined)); // never settles
|
|
59
|
+
const pending = sendEmail(mail);
|
|
60
|
+
const outcome = pending.then(() => 'sent', (error: Error) => error.message);
|
|
61
|
+
await vi.advanceTimersByTimeAsync(9_999);
|
|
62
|
+
expect(await Promise.race([outcome, Promise.resolve('still waiting')])).toBe('still waiting');
|
|
63
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
64
|
+
expect(await outcome).toBe('Email send timed out');
|
|
65
|
+
expect(logger.error).toHaveBeenCalledWith({ to: 'an***@example.test', timeoutMs: 10_000 }, '[EMAIL] Sending timed out');
|
|
66
|
+
expect(logged()).not.toContain(TO);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The global error handler (src/libs/error-handler.ts) on a small Fastify app
|
|
3
|
+
* wired like src/app.ts (fastify-type-provider-zod compilers). Proves the one
|
|
4
|
+
* shape for wrong input, 422 VALIDATION_FAILED + fields, from all three places
|
|
5
|
+
* input is checked (route schema, schema.parse() in a handler, parseInput), and
|
|
6
|
+
* that no submitted value is ever echoed back.
|
|
7
|
+
*/
|
|
8
|
+
import Fastify, { type FastifyInstance } from 'fastify';
|
|
9
|
+
import {
|
|
10
|
+
serializerCompiler,
|
|
11
|
+
validatorCompiler,
|
|
12
|
+
type ZodTypeProvider,
|
|
13
|
+
} from 'fastify-type-provider-zod';
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
16
|
+
import { registerErrorHandler } from '@libs/error-handler.js';
|
|
17
|
+
import { MAX_FIELD_ERRORS, parseInput } from '@libs/validation-errors.js';
|
|
18
|
+
import { TooManyRequestsError } from '@shared/errors/errors.js';
|
|
19
|
+
import { OutboundHttpError } from '@libs/http.js';
|
|
20
|
+
|
|
21
|
+
/** A distinctive value: it must never appear in any answer. */
|
|
22
|
+
const SECRET_VALUE = 'leak-canary-7Q2X';
|
|
23
|
+
|
|
24
|
+
const signupSchema = z.object({
|
|
25
|
+
email: z.email(),
|
|
26
|
+
age: z.number().int().min(18),
|
|
27
|
+
address: z.object({ city: z.string().min(2) }).optional(),
|
|
28
|
+
});
|
|
29
|
+
const passwordSchema = z.object({ password: z.string().min(8) });
|
|
30
|
+
const wideSchema = z.object(Object.fromEntries(Array.from({ length: 25 }, (_, i) => [`f${i}`, z.string()])));
|
|
31
|
+
|
|
32
|
+
let app: FastifyInstance;
|
|
33
|
+
|
|
34
|
+
beforeAll(async () => {
|
|
35
|
+
app = Fastify({ logger: false });
|
|
36
|
+
app.setValidatorCompiler(validatorCompiler);
|
|
37
|
+
app.setSerializerCompiler(serializerCompiler);
|
|
38
|
+
registerErrorHandler(app);
|
|
39
|
+
const typed = app.withTypeProvider<ZodTypeProvider>();
|
|
40
|
+
|
|
41
|
+
typed.post('/schema', { schema: { body: signupSchema } }, async () => ({ ok: true }));
|
|
42
|
+
typed.post('/wide', { schema: { body: wideSchema } }, async () => ({ ok: true }));
|
|
43
|
+
typed.get('/users/:id', { schema: { params: z.object({ id: z.uuid() }) } }, async () => ({ ok: true }));
|
|
44
|
+
typed.get('/list', { schema: { querystring: z.object({ page: z.coerce.number().int().min(1) }) } }, async () => ({ ok: true }));
|
|
45
|
+
app.post('/parse', async (request) => passwordSchema.parse(request.body));
|
|
46
|
+
app.post('/parse-input', async (request) => parseInput(passwordSchema, request.body));
|
|
47
|
+
app.get('/limited', async () => {
|
|
48
|
+
throw new TooManyRequestsError('Too many requests. Try again in 1 minute.', 'RATE_LIMIT_EXCEEDED', 42);
|
|
49
|
+
});
|
|
50
|
+
app.get('/outbound', async () => {
|
|
51
|
+
throw new OutboundHttpError('http', { status: 404, cause: new Error(`upstream said ${SECRET_VALUE}`) });
|
|
52
|
+
});
|
|
53
|
+
app.get('/boom', async () => {
|
|
54
|
+
throw new Error(`internal detail ${SECRET_VALUE}`);
|
|
55
|
+
});
|
|
56
|
+
await app.ready();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
afterAll(async () => {
|
|
60
|
+
await app.close();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
function expectNoLeak(raw: string): void {
|
|
64
|
+
expect(raw).not.toContain(SECRET_VALUE);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
describe('global error handler', () => {
|
|
68
|
+
it('route schema: 422 VALIDATION_FAILED with every wrong field (body), never the values', async () => {
|
|
69
|
+
const res = await app.inject({
|
|
70
|
+
method: 'POST',
|
|
71
|
+
url: '/schema',
|
|
72
|
+
payload: { email: SECRET_VALUE, age: 12, address: { city: 'x' } },
|
|
73
|
+
});
|
|
74
|
+
expect(res.statusCode).toBe(422);
|
|
75
|
+
const body = res.json();
|
|
76
|
+
expect(body.success).toBe(false);
|
|
77
|
+
expect(body.error.code).toBe('VALIDATION_FAILED');
|
|
78
|
+
expect(body.error.fields.map((f: { field: string }) => f.field).sort()).toEqual(['address.city', 'age', 'email']);
|
|
79
|
+
expect(body.error.message).toMatch(/^Please check these fields: /);
|
|
80
|
+
for (const f of body.error.fields) expect(typeof f.message).toBe('string');
|
|
81
|
+
expectNoLeak(res.body);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('route schema: a missing body names the request part', async () => {
|
|
85
|
+
const res = await app.inject({ method: 'POST', url: '/schema', headers: { 'content-type': 'application/json' }, payload: 'null' });
|
|
86
|
+
expect(res.statusCode).toBe(422);
|
|
87
|
+
expect(res.json().error.fields).toEqual([expect.objectContaining({ field: 'body' })]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('route schema: params and querystring use the same shape', async () => {
|
|
91
|
+
const params = await app.inject({ method: 'GET', url: `/users/${SECRET_VALUE}` });
|
|
92
|
+
expect(params.statusCode).toBe(422);
|
|
93
|
+
expect(params.json().error.fields[0].field).toBe('id');
|
|
94
|
+
expectNoLeak(params.body);
|
|
95
|
+
|
|
96
|
+
const query = await app.inject({ method: 'GET', url: '/list?page=0' });
|
|
97
|
+
expect(query.statusCode).toBe(422);
|
|
98
|
+
expect(query.json().error.fields[0].field).toBe('page');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('caps the field list', async () => {
|
|
102
|
+
const res = await app.inject({ method: 'POST', url: '/wide', payload: {} });
|
|
103
|
+
expect(res.statusCode).toBe(422);
|
|
104
|
+
expect(res.json().error.fields).toHaveLength(MAX_FIELD_ERRORS);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('schema.parse() inside a handler: same 422 shape', async () => {
|
|
108
|
+
const res = await app.inject({ method: 'POST', url: '/parse', payload: { password: 'short' } });
|
|
109
|
+
expect(res.statusCode).toBe(422);
|
|
110
|
+
expect(res.json().error).toMatchObject({
|
|
111
|
+
code: 'VALIDATION_FAILED',
|
|
112
|
+
message: 'Please check these fields: password',
|
|
113
|
+
fields: [expect.objectContaining({ field: 'password' })],
|
|
114
|
+
});
|
|
115
|
+
expect(res.body).not.toContain('"short"');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('parseInput(): same 422 shape', async () => {
|
|
119
|
+
const res = await app.inject({ method: 'POST', url: '/parse-input', payload: { password: 'short' } });
|
|
120
|
+
expect(res.statusCode).toBe(422);
|
|
121
|
+
expect(res.json().error).toMatchObject({ code: 'VALIDATION_FAILED', fields: [expect.objectContaining({ field: 'password' })] });
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('malformed JSON stays 400 BAD_REQUEST (unreadable request, not wrong input)', async () => {
|
|
125
|
+
const res = await app.inject({
|
|
126
|
+
method: 'POST',
|
|
127
|
+
url: '/schema',
|
|
128
|
+
headers: { 'content-type': 'application/json' },
|
|
129
|
+
payload: `{"email": "${SECRET_VALUE}"`,
|
|
130
|
+
});
|
|
131
|
+
expect(res.statusCode).toBe(400);
|
|
132
|
+
expect(res.json().error.code).toBe('BAD_REQUEST');
|
|
133
|
+
expect(res.json().error.fields).toBeUndefined();
|
|
134
|
+
expectNoLeak(res.body);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('AppError keeps its status, code and retryAfterSeconds, with no fields', async () => {
|
|
138
|
+
const res = await app.inject({ method: 'GET', url: '/limited' });
|
|
139
|
+
expect(res.statusCode).toBe(429);
|
|
140
|
+
expect(res.json().error).toEqual({
|
|
141
|
+
code: 'RATE_LIMIT_EXCEEDED',
|
|
142
|
+
message: 'Too many requests. Try again in 1 minute.',
|
|
143
|
+
retryAfterSeconds: 42,
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('an unexpected error is a generic 500 that reveals nothing', async () => {
|
|
148
|
+
const res = await app.inject({ method: 'GET', url: '/boom' });
|
|
149
|
+
expect(res.statusCode).toBe(500);
|
|
150
|
+
expect(res.json().error).toEqual({ code: 'INTERNAL_ERROR', message: 'Internal server error' });
|
|
151
|
+
expectNoLeak(res.body);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('an unhandled outbound failure is the same generic 500, without its status, kind or cause', async () => {
|
|
155
|
+
const res = await app.inject({ method: 'GET', url: '/outbound' });
|
|
156
|
+
expect(res.statusCode).toBe(500);
|
|
157
|
+
expect(res.json().error).toEqual({ code: 'INTERNAL_ERROR', message: 'Outbound HTTP request failed' });
|
|
158
|
+
expect(res.body).not.toContain('404');
|
|
159
|
+
expectNoLeak(res.body);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The real app while the database is unreachable: public /health answers 503
|
|
3
|
+
* with only { status: "unhealthy" }, /ready says not ready, /live (the Docker
|
|
4
|
+
* HEALTHCHECK) still answers, and repeated probes inside 5 s reuse one failed
|
|
5
|
+
* check. The database is "down" by pointing this file's app at a closed port
|
|
6
|
+
* before it loads, so no real service is touched.
|
|
7
|
+
*/
|
|
8
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
9
|
+
import type { FastifyInstance } from 'fastify';
|
|
10
|
+
import { buildTestApp, call } from '@/test/integration-helpers.js';
|
|
11
|
+
|
|
12
|
+
let app: FastifyInstance;
|
|
13
|
+
|
|
14
|
+
beforeAll(async () => {
|
|
15
|
+
process.env.DATABASE_URL = 'mysql://nobody:nothing@127.0.0.1:3399/closed_test'; // nothing listens there
|
|
16
|
+
app = await buildTestApp();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
afterAll(async () => {
|
|
20
|
+
await app?.close();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe('database down', () => {
|
|
24
|
+
it('/health → 503 { status: "unhealthy" } only; /ready → 503 ready false; /live → 200', async () => {
|
|
25
|
+
const health = await call(app, 'GET', '/health');
|
|
26
|
+
expect([health.status, health.body?.data]).toEqual([503, { status: 'unhealthy' }]);
|
|
27
|
+
const ready = await call(app, 'GET', '/ready');
|
|
28
|
+
expect([ready.status, ready.body?.data?.ready]).toEqual([503, false]);
|
|
29
|
+
expect((await call(app, 'GET', '/live')).status).toBe(200);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('a second probe inside 5 s reuses the failed check (no new query)', async () => {
|
|
33
|
+
const again = await call(app, 'GET', '/health');
|
|
34
|
+
expect(again.status).toBe(503);
|
|
35
|
+
expect(Number(again.res.headers['x-query-count'])).toBe(0);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The real app while Redis is unreachable: it keeps serving, public /health
|
|
3
|
+
* says "degraded" (nothing more), and the admin report names Redis. Redis is
|
|
4
|
+
* "down" by pointing this file's app at a closed port before it loads, so no
|
|
5
|
+
* real service is touched.
|
|
6
|
+
*/
|
|
7
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
8
|
+
import type { FastifyInstance } from 'fastify';
|
|
9
|
+
import { buildTestApp, call, makeAdmin, registerUser } from '@/test/integration-helpers.js';
|
|
10
|
+
|
|
11
|
+
let app: FastifyInstance;
|
|
12
|
+
|
|
13
|
+
beforeAll(async () => {
|
|
14
|
+
process.env.REDIS_URL = 'redis://127.0.0.1:6599/15'; // nothing listens there
|
|
15
|
+
app = await buildTestApp();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
afterAll(async () => {
|
|
19
|
+
await app?.close();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe('Redis down', () => {
|
|
23
|
+
it('public /health → 200 with only { status: "degraded" }', async () => {
|
|
24
|
+
const r = await call(app, 'GET', '/health');
|
|
25
|
+
expect(r.status).toBe(200);
|
|
26
|
+
expect(r.body?.data).toEqual({ status: 'degraded' });
|
|
27
|
+
expect(r.res.body).not.toMatch(/redis/i);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('the admin report says which check failed: redis down, overall degraded', async () => {
|
|
31
|
+
const u = await registerUser(app, 'redisdown-admin');
|
|
32
|
+
await makeAdmin(u.id);
|
|
33
|
+
const r = await call(app, 'GET', '/admin/health', { jar: u.jar });
|
|
34
|
+
expect(r.status).toBe(200);
|
|
35
|
+
expect([r.body?.data?.status, r.body?.data?.checks?.redis?.status, r.body?.data?.checks?.database?.status]).toEqual([
|
|
36
|
+
'degraded',
|
|
37
|
+
'down',
|
|
38
|
+
'up',
|
|
39
|
+
]);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('/ready stays 200: the database is what readiness needs', async () => {
|
|
43
|
+
expect((await call(app, 'GET', '/ready')).status).toBe(200);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The public probes (../health-routes.ts): /health answers only { status }
|
|
3
|
+
* (no checks, timings, memory, version) with 200/200/503, and /ready and /live
|
|
4
|
+
* keep their shapes. The checks themselves are mocked; monitoring.test.ts
|
|
5
|
+
* covers them.
|
|
6
|
+
*/
|
|
7
|
+
import Fastify, { type FastifyInstance } from 'fastify';
|
|
8
|
+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
9
|
+
import { performHealthCheck, checkReadiness } from '@libs/monitoring.js';
|
|
10
|
+
import { registerHealthRoutes } from '../health-routes.js';
|
|
11
|
+
|
|
12
|
+
vi.mock('@libs/monitoring.js', () => ({
|
|
13
|
+
performHealthCheck: vi.fn(),
|
|
14
|
+
checkReadiness: vi.fn(),
|
|
15
|
+
checkLiveness: vi.fn(() => true),
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
/** A full report, as the admin route would show it: none of this may reach the public body. */
|
|
19
|
+
function report(status: 'healthy' | 'degraded' | 'unhealthy'): Awaited<ReturnType<typeof performHealthCheck>> {
|
|
20
|
+
return {
|
|
21
|
+
status,
|
|
22
|
+
checks: {
|
|
23
|
+
database: { status: 'up', responseTime: 3 },
|
|
24
|
+
redis: { status: status === 'degraded' ? 'down' : 'up', message: 'Redis connection failed (non-fatal)', details: { maxRetries: 3 } },
|
|
25
|
+
memory: { status: 'up', details: { heapUsedMB: 50, heapLimitMB: 4096 } },
|
|
26
|
+
uptime: { status: 'up', details: { uptimeSeconds: 99 } },
|
|
27
|
+
},
|
|
28
|
+
timestamp: '2026-10-20T00:00:00.000Z',
|
|
29
|
+
checkedAt: '2026-10-20T00:00:00.000Z',
|
|
30
|
+
version: '1.2.3',
|
|
31
|
+
commit: 'abc1234def56',
|
|
32
|
+
environment: 'production',
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let app: FastifyInstance;
|
|
37
|
+
|
|
38
|
+
beforeAll(async () => {
|
|
39
|
+
app = Fastify({ logger: false });
|
|
40
|
+
registerHealthRoutes(app);
|
|
41
|
+
await app.ready();
|
|
42
|
+
});
|
|
43
|
+
afterAll(() => app.close());
|
|
44
|
+
beforeEach(() => vi.clearAllMocks());
|
|
45
|
+
|
|
46
|
+
describe('GET /api/v1/health (public)', () => {
|
|
47
|
+
it.each([
|
|
48
|
+
['healthy', 200, 'All systems operational'],
|
|
49
|
+
['degraded', 200, 'Some systems degraded'],
|
|
50
|
+
['unhealthy', 503, 'System unhealthy'],
|
|
51
|
+
] as const)('%s → %i with only the status', async (status, code, message) => {
|
|
52
|
+
vi.mocked(performHealthCheck).mockResolvedValue(report(status));
|
|
53
|
+
const res = await app.inject({ method: 'GET', url: '/api/v1/health' });
|
|
54
|
+
expect(res.statusCode).toBe(code);
|
|
55
|
+
expect(res.json()).toEqual({ success: true, message, data: { status } });
|
|
56
|
+
for (const leak of ['checks', 'responseTime', 'heap', 'uptime', 'version', '1.2.3', 'abc1234', 'Redis', 'environment']) {
|
|
57
|
+
expect(res.body).not.toContain(leak);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe('GET /api/v1/ready and /api/v1/live (unchanged)', () => {
|
|
63
|
+
it('/ready answers { ready, timestamp }, 503 when not ready', async () => {
|
|
64
|
+
vi.mocked(checkReadiness).mockResolvedValue(true);
|
|
65
|
+
const up = await app.inject({ method: 'GET', url: '/api/v1/ready' });
|
|
66
|
+
expect(up.statusCode).toBe(200);
|
|
67
|
+
expect(up.json()).toMatchObject({ success: true, message: 'Service is ready', data: { ready: true } });
|
|
68
|
+
expect(Object.keys(up.json().data)).toEqual(['ready', 'timestamp']);
|
|
69
|
+
|
|
70
|
+
vi.mocked(checkReadiness).mockResolvedValue(false);
|
|
71
|
+
const down = await app.inject({ method: 'GET', url: '/api/v1/ready' });
|
|
72
|
+
expect(down.statusCode).toBe(503);
|
|
73
|
+
expect(down.json()).toMatchObject({ message: 'Service not ready', data: { ready: false } });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('/live answers { alive, timestamp } without touching the checks', async () => {
|
|
77
|
+
const res = await app.inject({ method: 'GET', url: '/api/v1/live' });
|
|
78
|
+
expect(res.statusCode).toBe(200);
|
|
79
|
+
expect(Object.keys(res.json().data)).toEqual(['alive', 'timestamp']);
|
|
80
|
+
expect(performHealthCheck).not.toHaveBeenCalled();
|
|
81
|
+
expect(checkReadiness).not.toHaveBeenCalled();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Health probes and request logging in the real app with MySQL and Redis up
|
|
3
|
+
* (the layer 8 guarantees that run in-process).
|
|
4
|
+
* - Public /health answers only { status }; the full report is admin-only
|
|
5
|
+
* and judges memory against the heap limit.
|
|
6
|
+
* - The database check behind /health and /ready runs at most once per 5 s,
|
|
7
|
+
* however many probes arrive (X-Query-Count shows it).
|
|
8
|
+
* - Probes are never IP-blocked and never request-logged; other routes are.
|
|
9
|
+
* The outage answers (Redis down, database down) are in
|
|
10
|
+
* health-redis-down.integration.test.ts and health-db-down.integration.test.ts.
|
|
11
|
+
*/
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
16
|
+
import type { FastifyInstance } from 'fastify';
|
|
17
|
+
import { buildTestApp, call, registerAdmin, registerUser, type TestUser } from '@/test/integration-helpers.js';
|
|
18
|
+
|
|
19
|
+
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
|
|
20
|
+
|
|
21
|
+
let app: FastifyInstance;
|
|
22
|
+
let admin: TestUser;
|
|
23
|
+
|
|
24
|
+
beforeAll(async () => {
|
|
25
|
+
app = await buildTestApp();
|
|
26
|
+
admin = await registerAdmin(app, 'health-admin');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
afterAll(async () => {
|
|
30
|
+
await app?.close();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('public and admin health', () => {
|
|
34
|
+
it('GET /health → 200 with only { status: "healthy" }', async () => {
|
|
35
|
+
const r = await call(app, 'GET', '/health');
|
|
36
|
+
expect(r.status).toBe(200);
|
|
37
|
+
expect(r.body).toEqual({ success: true, message: 'All systems operational', data: { status: 'healthy' } });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('GET /admin/health → the full report: every check, memory against the heap limit, version, commit', async () => {
|
|
41
|
+
const r = await call(app, 'GET', '/admin/health', { jar: admin.jar });
|
|
42
|
+
expect(r.status).toBe(200);
|
|
43
|
+
const report = r.body?.data;
|
|
44
|
+
expect(Object.fromEntries(Object.entries(report.checks).map(([k, v]) => [k, (v as { status: string }).status]))).toEqual({
|
|
45
|
+
database: 'up',
|
|
46
|
+
redis: 'up',
|
|
47
|
+
memory: 'up',
|
|
48
|
+
uptime: 'up',
|
|
49
|
+
});
|
|
50
|
+
expect(report.checks.memory.details.heapLimitMB).toBeGreaterThan(100);
|
|
51
|
+
expect(report.checks.memory.message).toMatch(/of the heap limit/);
|
|
52
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(serverRoot, 'package.json'), 'utf8')) as { version: string };
|
|
53
|
+
expect(report.version).toBe(pkg.version);
|
|
54
|
+
expect(report.commit).toBeNull();
|
|
55
|
+
expect(Number.isNaN(Date.parse(report.checkedAt))).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('GET /admin/health: anonymous 401, USER 403', async () => {
|
|
59
|
+
const user = await registerUser(app, 'health-user');
|
|
60
|
+
expect((await call(app, 'GET', '/admin/health')).status).toBe(401);
|
|
61
|
+
expect((await call(app, 'GET', '/admin/health', { jar: user.jar })).status).toBe(403);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('/ready and /live keep their shapes', async () => {
|
|
65
|
+
const ready = await call(app, 'GET', '/ready');
|
|
66
|
+
const live = await call(app, 'GET', '/live');
|
|
67
|
+
expect([ready.status, Object.keys(ready.body?.data ?? {})]).toEqual([200, ['ready', 'timestamp']]);
|
|
68
|
+
expect([live.status, Object.keys(live.body?.data ?? {})]).toEqual([200, ['alive', 'timestamp']]);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe('the dependency check is shared', () => {
|
|
73
|
+
it('one database query per 5 s, however many probes arrive', async () => {
|
|
74
|
+
await new Promise((r) => setTimeout(r, 5_200)); // any earlier check has expired
|
|
75
|
+
const first = await call(app, 'GET', '/health');
|
|
76
|
+
const burst = await Promise.all([...Array(20)].map((_, i) => call(app, 'GET', i % 2 ? '/ready' : '/health')));
|
|
77
|
+
expect(Number(first.res.headers['x-query-count'])).toBe(1);
|
|
78
|
+
expect(burst.reduce((sum, r) => sum + Number(r.res.headers['x-query-count']), 0)).toBe(0);
|
|
79
|
+
}, 20_000);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('probes and the edges', () => {
|
|
83
|
+
it('a blocked address gets 403 elsewhere but 200 from every probe', async () => {
|
|
84
|
+
const ip = '198.51.100.77';
|
|
85
|
+
expect((await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip } })).status).toBe(201);
|
|
86
|
+
try {
|
|
87
|
+
const headers = { 'x-forwarded-for': ip };
|
|
88
|
+
const elsewhere = await call(app, 'GET', '/auth/me', { headers });
|
|
89
|
+
expect([elsewhere.status, elsewhere.code]).toEqual([403, 'IP_BLOCKED']);
|
|
90
|
+
for (const probe of ['/health', '/ready', '/live']) {
|
|
91
|
+
expect([probe, (await call(app, 'GET', probe, { headers })).status]).toEqual([probe, 200]);
|
|
92
|
+
}
|
|
93
|
+
} finally {
|
|
94
|
+
await call(app, 'DELETE', `/admin/blocked-ips/${ip}`, { jar: admin.jar });
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('probes are not request-logged; other routes are, without their query string', async () => {
|
|
99
|
+
const { logger } = await import('@/libs/logger.js');
|
|
100
|
+
const lines: string[] = [];
|
|
101
|
+
const spies = (['info', 'warn', 'error'] as const).map((level) =>
|
|
102
|
+
vi.spyOn(logger, level).mockImplementation(((...args: unknown[]) => {
|
|
103
|
+
lines.push(args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' '));
|
|
104
|
+
}) as never),
|
|
105
|
+
);
|
|
106
|
+
try {
|
|
107
|
+
await call(app, 'GET', '/health');
|
|
108
|
+
await call(app, 'GET', '/live');
|
|
109
|
+
await call(app, 'GET', '/auth/me?debug=secret-query');
|
|
110
|
+
} finally {
|
|
111
|
+
for (const spy of spies) spy.mockRestore();
|
|
112
|
+
}
|
|
113
|
+
expect(lines.some((l) => /\/api\/v1\/(health|live)\b/.test(l))).toBe(false);
|
|
114
|
+
const meLine = lines.find((l) => l.includes('/api/v1/auth/me'));
|
|
115
|
+
expect(meLine).toBeDefined();
|
|
116
|
+
expect(meLine).not.toContain('secret-query');
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -12,6 +12,7 @@ const captured = vi.hoisted(() => ({
|
|
|
12
12
|
responseFulfilled: null as null | ((r: AxiosResponse) => AxiosResponse),
|
|
13
13
|
responseRejected: null as null | ((e: unknown) => never),
|
|
14
14
|
mockIsAxiosError: vi.fn<(e: unknown) => boolean>(),
|
|
15
|
+
createConfig: null as unknown,
|
|
15
16
|
}));
|
|
16
17
|
|
|
17
18
|
// ---------------------------------------------------------------------------
|
|
@@ -19,7 +20,7 @@ const captured = vi.hoisted(() => ({
|
|
|
19
20
|
// ---------------------------------------------------------------------------
|
|
20
21
|
vi.mock('axios', () => ({
|
|
21
22
|
default: {
|
|
22
|
-
create: vi.fn(() => ({
|
|
23
|
+
create: vi.fn((config: unknown) => (captured.createConfig = config, {
|
|
23
24
|
interceptors: {
|
|
24
25
|
request: {
|
|
25
26
|
use: vi.fn(
|
|
@@ -60,7 +61,7 @@ vi.mock('@libs/logger.js', () => ({
|
|
|
60
61
|
}));
|
|
61
62
|
|
|
62
63
|
// Import AFTER mocks are registered
|
|
63
|
-
import { httpClient } from '../http.js';
|
|
64
|
+
import { httpClient, OutboundHttpError, MAX_BODY_BYTES, OUTBOUND_BLOCKED } from '../http.js';
|
|
64
65
|
import { logger } from '@libs/logger.js';
|
|
65
66
|
|
|
66
67
|
// ---------------------------------------------------------------------------
|
|
@@ -426,3 +427,74 @@ describe('httpClient', () => {
|
|
|
426
427
|
});
|
|
427
428
|
});
|
|
428
429
|
});
|
|
430
|
+
|
|
431
|
+
// ---------------------------------------------------------------------------
|
|
432
|
+
// Layer 7: redaction, size caps, and one typed error for every failure
|
|
433
|
+
// ---------------------------------------------------------------------------
|
|
434
|
+
describe('httpClient — secrets never logged, failures typed', () => {
|
|
435
|
+
beforeEach(() => {
|
|
436
|
+
vi.clearAllMocks();
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
it('logs URLs without query strings or credentials (API keys, user:password)', () => {
|
|
440
|
+
captured.requestFulfilled!(
|
|
441
|
+
makeConfig({ method: 'get', url: 'https://api.example.com/v1/geo?key=SECRET123', baseURL: 'https://user:pw@api.example.com' }),
|
|
442
|
+
);
|
|
443
|
+
captured.responseFulfilled!(makeResponse({ config: makeConfig({ method: 'get', url: '/v1?token=SECRET123' }) }));
|
|
444
|
+
captured.mockIsAxiosError.mockReturnValue(true);
|
|
445
|
+
expect(() =>
|
|
446
|
+
captured.responseRejected!({ isAxiosError: true, config: { method: 'get', url: 'https://user:pw@x.test/a?key=SECRET123' }, message: 'boom' }),
|
|
447
|
+
).toThrow();
|
|
448
|
+
const logged = JSON.stringify([...vi.mocked(logger.debug).mock.calls, ...vi.mocked(logger.error).mock.calls]);
|
|
449
|
+
expect(logged).not.toContain('SECRET123');
|
|
450
|
+
expect(logged).not.toContain('user:pw');
|
|
451
|
+
expect(logged).toContain('https://api.example.com/v1/geo');
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
it('caps request and response bodies at 10 MB', () => {
|
|
455
|
+
expect(captured.createConfig).toMatchObject({ maxContentLength: MAX_BODY_BYTES, maxBodyLength: MAX_BODY_BYTES });
|
|
456
|
+
expect(MAX_BODY_BYTES).toBe(10 * 1024 * 1024);
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
const reject = (error: object): OutboundHttpError => {
|
|
460
|
+
captured.mockIsAxiosError.mockReturnValue(true);
|
|
461
|
+
try {
|
|
462
|
+
captured.responseRejected!({ isAxiosError: true, message: 'x', ...error });
|
|
463
|
+
} catch (e) {
|
|
464
|
+
return e as OutboundHttpError;
|
|
465
|
+
}
|
|
466
|
+
throw new Error('expected a throw');
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
it.each([
|
|
470
|
+
['an upstream HTTP error, with its status', { response: { status: 404 } }, 'http', 404],
|
|
471
|
+
['a timeout', { code: 'ECONNABORTED', message: 'timeout of 30000ms exceeded' }, 'timeout', undefined],
|
|
472
|
+
['a body over the cap', { code: 'ERR_BAD_RESPONSE', message: 'maxContentLength size of 10485760 exceeded' }, 'too-large', undefined],
|
|
473
|
+
['a connection failure', { code: 'ECONNREFUSED', message: 'connect ECONNREFUSED' }, 'network', undefined],
|
|
474
|
+
['a request our guard refused (wrapped)', { code: 'ERR_FR_REDIRECTION_FAILURE', cause: { cause: { code: OUTBOUND_BLOCKED } } }, 'blocked', undefined],
|
|
475
|
+
])('turns %s into OutboundHttpError with that kind', (_label, error, kind, status) => {
|
|
476
|
+
const thrown = reject(error);
|
|
477
|
+
expect(thrown).toBeInstanceOf(OutboundHttpError);
|
|
478
|
+
expect(thrown).toBeInstanceOf(InternalError);
|
|
479
|
+
expect(thrown).toMatchObject({ kind, status, statusCode: 500, code: 'INTERNAL_ERROR', message: 'Outbound HTTP request failed' });
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
it('keeps the original error as a non-enumerable cause (never serialized with the error)', () => {
|
|
483
|
+
const thrown = reject({ response: { status: 500 } });
|
|
484
|
+
expect((thrown as { cause?: unknown }).cause).toBeDefined();
|
|
485
|
+
expect(Object.keys(thrown)).not.toContain('cause');
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
it("keeps a guard's OutboundHttpError when it passes through the request chain", () => {
|
|
489
|
+
const own = new OutboundHttpError('blocked');
|
|
490
|
+
expect(() => captured.requestRejected!(own)).toThrow(own);
|
|
491
|
+
expect(logger.error).not.toHaveBeenCalled();
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
it("passes our own guard's OutboundHttpError through unchanged", () => {
|
|
495
|
+
const own = new OutboundHttpError('blocked');
|
|
496
|
+
captured.mockIsAxiosError.mockReturnValue(false);
|
|
497
|
+
expect(() => captured.responseRejected!(own)).toThrow(own);
|
|
498
|
+
});
|
|
499
|
+
});
|
|
500
|
+
|