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,146 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
import Fastify, { type FastifyError, type FastifyInstance, type LightMyRequestResponse } from 'fastify';
|
|
3
|
+
import type { Redis } from 'ioredis';
|
|
4
|
+
import { registerRateLimiting, registerNotFoundHandler } from '../rate-limiting.js';
|
|
5
|
+
import { TRUSTED_PROXY_RANGES } from '../client-ip.js';
|
|
6
|
+
import { recordRateLimitViolation } from '../ip-block.js';
|
|
7
|
+
import { isAppError } from '@shared/errors/AppError.js';
|
|
8
|
+
import { describeWait } from '@shared/errors/errors.js';
|
|
9
|
+
import { errorResponse } from '@shared/responses/successResponse.js';
|
|
10
|
+
import { DEFAULT_LIMIT } from '@config/rate-limit.config.js';
|
|
11
|
+
|
|
12
|
+
// Strikes are asserted, never stored: no Redis in unit tests.
|
|
13
|
+
vi.mock('../ip-block.js', () => ({ recordRateLimitViolation: vi.fn() }));
|
|
14
|
+
|
|
15
|
+
const VISITOR = '31.146.10.20';
|
|
16
|
+
const OTHER_VISITOR = '31.146.10.21';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A bare Fastify wired exactly like app.ts (same trustProxy, the same rate-limit module and
|
|
20
|
+
* an error handler that serializes AppErrors the same way), with the in-memory store.
|
|
21
|
+
*/
|
|
22
|
+
async function buildTestApp(redis?: Redis): Promise<FastifyInstance> {
|
|
23
|
+
const app = Fastify({ trustProxy: TRUSTED_PROXY_RANGES });
|
|
24
|
+
app.setErrorHandler((error: FastifyError, _request, reply) => {
|
|
25
|
+
if (isAppError(error)) {
|
|
26
|
+
return reply.status(error.statusCode).send(errorResponse(error.code, error.message, error.retryAfterSeconds));
|
|
27
|
+
}
|
|
28
|
+
return reply.status(500).send(errorResponse('INTERNAL_ERROR', error.message));
|
|
29
|
+
});
|
|
30
|
+
await registerRateLimiting(app, redis ? { redis } : {});
|
|
31
|
+
registerNotFoundHandler(app);
|
|
32
|
+
app.get('/api/v1/live', { config: { rateLimit: false } }, async () => ({ ok: true }));
|
|
33
|
+
app.get('/api/v1/plain-a', async () => ({ ok: true })); // no own limit → DEFAULT
|
|
34
|
+
app.get('/api/v1/plain-b', async () => ({ ok: true }));
|
|
35
|
+
app.get('/api/v1/own', { config: { rateLimit: { max: 2, timeWindow: 60_000 } } }, async () => ({ ok: true }));
|
|
36
|
+
app.post('/api/v1/auth/login', { config: { rateLimit: { max: 2, timeWindow: 60_000 } } }, async () => ({ ok: true }));
|
|
37
|
+
app.get('/uploads/*', async (_request, reply) => reply.callNotFound()); // stands in for @fastify/static
|
|
38
|
+
await app.ready();
|
|
39
|
+
return app;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function hit(
|
|
43
|
+
app: FastifyInstance,
|
|
44
|
+
url: string,
|
|
45
|
+
ip = VISITOR,
|
|
46
|
+
method: 'GET' | 'POST' = 'GET',
|
|
47
|
+
): Promise<LightMyRequestResponse> {
|
|
48
|
+
return app.inject({ method, url, remoteAddress: ip });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function hitTimes(app: FastifyInstance, url: string, times: number, ip = VISITOR): Promise<number[]> {
|
|
52
|
+
const statuses: number[] = [];
|
|
53
|
+
for (let i = 0; i < times; i++) statuses.push((await hit(app, url, ip)).statusCode);
|
|
54
|
+
return statuses;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
describe('rate limiting wiring (src/libs/rate-limiting.ts)', () => {
|
|
58
|
+
let app: FastifyInstance;
|
|
59
|
+
|
|
60
|
+
beforeEach(async () => {
|
|
61
|
+
vi.clearAllMocks();
|
|
62
|
+
app = await buildTestApp();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
afterEach(async () => {
|
|
66
|
+
await app.close();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('ships the default limit of 200 per minute', () => {
|
|
70
|
+
expect(DEFAULT_LIMIT).toEqual({ max: 200, timeWindow: 60_000 });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('gives a route without its own limit DEFAULT_LIMIT: request 201 → 429 with retryAfterSeconds', async () => {
|
|
74
|
+
const statuses = await hitTimes(app, '/api/v1/plain-a', 200);
|
|
75
|
+
expect(statuses.every((s) => s === 200)).toBe(true);
|
|
76
|
+
const over = await hit(app, '/api/v1/plain-a');
|
|
77
|
+
expect(over.statusCode).toBe(429);
|
|
78
|
+
const body = over.json();
|
|
79
|
+
expect(body.error.code).toBe('RATE_LIMIT_EXCEEDED');
|
|
80
|
+
expect(body.error.retryAfterSeconds).toBeGreaterThan(0);
|
|
81
|
+
expect(body.error.message).toBe(`Too many requests. Try again in ${describeWait(body.error.retryAfterSeconds)}.`);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('keeps a separate counter per route, and per visitor', async () => {
|
|
85
|
+
await hitTimes(app, '/api/v1/plain-a', 201);
|
|
86
|
+
expect((await hit(app, '/api/v1/plain-b')).statusCode).toBe(200); // another route
|
|
87
|
+
expect((await hit(app, '/api/v1/plain-a', OTHER_VISITOR)).statusCode).toBe(200); // another visitor
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("uses a route's own limit instead of the default", async () => {
|
|
91
|
+
expect(await hitTimes(app, '/api/v1/own', 3)).toEqual([200, 200, 429]);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('answers unknown URLs with the error envelope and limits them under DEFAULT_LIMIT', async () => {
|
|
95
|
+
const first = await hit(app, '/api/v1/nope');
|
|
96
|
+
expect(first.statusCode).toBe(404);
|
|
97
|
+
expect(first.json()).toEqual({ success: false, error: { code: 'NOT_FOUND', message: 'Route not found' } });
|
|
98
|
+
await hitTimes(app, '/api/v1/also-nope', 199); // all unknown URLs share one counter
|
|
99
|
+
const over = await hit(app, '/api/v1/third-nope');
|
|
100
|
+
expect(over.statusCode).toBe(429);
|
|
101
|
+
expect(over.json().error.code).toBe('RATE_LIMIT_EXCEEDED');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('never limits health probes, static /uploads/* or a missing upload', async () => {
|
|
105
|
+
expect((await hitTimes(app, '/api/v1/live', 500)).every((s) => s === 200)).toBe(true);
|
|
106
|
+
expect((await hitTimes(app, '/uploads/users/1/avatar/missing.webp', 500)).every((s) => s === 404)).toBe(true);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('records an auto-block strike for an over-limit request on a normal route', async () => {
|
|
110
|
+
await hitTimes(app, '/api/v1/own', 4);
|
|
111
|
+
expect(recordRateLimitViolation).toHaveBeenCalledTimes(2); // requests 3 and 4
|
|
112
|
+
expect(recordRateLimitViolation).toHaveBeenCalledWith(VISITOR);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('records no strike for over-limit requests on auth routes', async () => {
|
|
116
|
+
for (let i = 0; i < 4; i++) await hit(app, '/api/v1/auth/login', VISITOR, 'POST');
|
|
117
|
+
expect((await hit(app, '/api/v1/auth/login', VISITOR, 'POST')).statusCode).toBe(429);
|
|
118
|
+
expect(recordRateLimitViolation).not.toHaveBeenCalled();
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
describe('rate limiting when Redis is down', () => {
|
|
123
|
+
it('serves every request (fail open) instead of crashing', async () => {
|
|
124
|
+
// A store whose every call fails, as a lost Redis connection does.
|
|
125
|
+
const brokenRedis = {
|
|
126
|
+
rateLimit: (...args: unknown[]) => (args.at(-1) as (err: Error) => void)(new Error('Connection is closed')),
|
|
127
|
+
} as unknown as Redis;
|
|
128
|
+
const app = await buildTestApp(brokenRedis);
|
|
129
|
+
try {
|
|
130
|
+
expect((await hitTimes(app, '/api/v1/own', 10)).every((s) => s === 200)).toBe(true);
|
|
131
|
+
} finally {
|
|
132
|
+
await app.close();
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
describe('describeWait', () => {
|
|
138
|
+
it('words a wait for people, rounding minutes up', () => {
|
|
139
|
+
expect(describeWait(1)).toBe('1 second');
|
|
140
|
+
expect(describeWait(45)).toBe('45 seconds');
|
|
141
|
+
expect(describeWait(60)).toBe('1 minute');
|
|
142
|
+
expect(describeWait(61)).toBe('2 minutes');
|
|
143
|
+
expect(describeWait(900)).toBe('15 minutes');
|
|
144
|
+
expect(describeWait(0)).toBe('1 second');
|
|
145
|
+
});
|
|
146
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rate limits that guard the layer 3 and layer 8 promises, in the real
|
|
3
|
+
* app with limits switched ON (they are off in every other integration
|
|
4
|
+
* file): forgot-password emails one address at most 3 times an hour, and the
|
|
5
|
+
* health probes are never limited while an ordinary route is.
|
|
6
|
+
*
|
|
7
|
+
* Kept short on purpose: every 429 counts as a violation for the client's
|
|
8
|
+
* address, and enough of them would block it automatically. The file deletes
|
|
9
|
+
* its limiter keys at the end, and checks the address was never blocked.
|
|
10
|
+
*/
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
12
|
+
import type { FastifyInstance } from 'fastify';
|
|
13
|
+
import { buildTestApp, call, redis, startEmailStub, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
|
|
14
|
+
|
|
15
|
+
let app: FastifyInstance;
|
|
16
|
+
let mail: EmailStub;
|
|
17
|
+
|
|
18
|
+
beforeAll(async () => {
|
|
19
|
+
process.env.RATE_LIMIT_ENABLED = 'true';
|
|
20
|
+
process.env.RATE_LIMIT_OVERRIDES = 'DEFAULT=5/1m';
|
|
21
|
+
mail = await startEmailStub();
|
|
22
|
+
app = await buildTestApp();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
afterAll(async () => {
|
|
26
|
+
const r = await redis();
|
|
27
|
+
const keys = await r.keys('rl:*');
|
|
28
|
+
if (keys.length > 0) await r.del(...keys);
|
|
29
|
+
await app?.close();
|
|
30
|
+
await mail?.close();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('rate limits on', () => {
|
|
34
|
+
it('the 4th forgot-password email to one address within the hour → 429', async () => {
|
|
35
|
+
const email = uniqueEmail('cap');
|
|
36
|
+
const statuses: number[] = [];
|
|
37
|
+
for (let i = 0; i < 4; i++) statuses.push((await call(app, 'POST', '/auth/forgot-password', { payload: { email } })).status);
|
|
38
|
+
expect(statuses).toEqual([200, 200, 200, 429]);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('probes are never limited (40 calls → all 200), while an ordinary route is (DEFAULT 5/min → the 6th is 429)', async () => {
|
|
42
|
+
const probes = await Promise.all([...Array(40)].map((_, i) => call(app, 'GET', ['/live', '/health', '/ready'][i % 3])));
|
|
43
|
+
expect(probes.filter((p) => p.status !== 200)).toHaveLength(0);
|
|
44
|
+
const ordinary: number[] = [];
|
|
45
|
+
for (let i = 0; i < 6; i++) ordinary.push((await call(app, 'GET', '/no-such-route')).status);
|
|
46
|
+
expect(ordinary.slice(0, 5)).toEqual([404, 404, 404, 404, 404]);
|
|
47
|
+
expect(ordinary[5]).toBe(429);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('the test client was never automatically blocked', async () => {
|
|
51
|
+
expect(await (await redis()).zscore('auto_blocked_ips', '127.0.0.1')).toBeNull();
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { getRedis } from '@libs/redis.js';
|
|
3
|
+
import { assertRedisReady } from '../redis-required.js';
|
|
4
|
+
|
|
5
|
+
vi.mock('@libs/redis.js');
|
|
6
|
+
|
|
7
|
+
describe('assertRedisReady', () => {
|
|
8
|
+
it('passes while Redis is connected', () => {
|
|
9
|
+
vi.mocked(getRedis).mockReturnValue({ status: 'ready' } as never);
|
|
10
|
+
expect(() => assertRedisReady('Password reset')).not.toThrow();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it.each(['reconnecting', 'connecting', 'end', 'close', 'wait'])('answers 503 while Redis is %s', (status) => {
|
|
14
|
+
vi.mocked(getRedis).mockReturnValue({ status } as never);
|
|
15
|
+
expect(() => assertRedisReady('Password reset')).toThrow(
|
|
16
|
+
expect.objectContaining({
|
|
17
|
+
statusCode: 503,
|
|
18
|
+
code: 'SERVICE_UNAVAILABLE',
|
|
19
|
+
message: 'Password reset is temporarily unavailable. Please try again in a few minutes.',
|
|
20
|
+
}),
|
|
21
|
+
);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('answers 503 when the client cannot even be created', () => {
|
|
25
|
+
vi.mocked(getRedis).mockImplementation(() => {
|
|
26
|
+
throw new Error('bad REDIS_URL');
|
|
27
|
+
});
|
|
28
|
+
expect(() => assertRedisReady('Email verification')).toThrow(expect.objectContaining({ statusCode: 503 }));
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { afterEach, describe, it, expect, vi } from 'vitest';
|
|
3
|
+
import { redisRetryDelay, waitForRedisReady } from '../redis.js';
|
|
3
4
|
|
|
4
5
|
// The Redis client must never stop reconnecting: ioredis gives up for good
|
|
5
6
|
// when the retry strategy returns null, which used to leave a process without
|
|
@@ -21,3 +22,38 @@ describe('redisRetryDelay', () => {
|
|
|
21
22
|
expect(redisRetryDelay(10000)).toBe(5000);
|
|
22
23
|
});
|
|
23
24
|
});
|
|
25
|
+
|
|
26
|
+
// The production boot waits for Redis this way before refusing to start
|
|
27
|
+
// (server.ts): true as soon as the client is ready, false at the deadline.
|
|
28
|
+
describe('waitForRedisReady', () => {
|
|
29
|
+
/** A stand-in for the ioredis client: a status and the 'ready' event. */
|
|
30
|
+
const fakeClient = (status: string): EventEmitter & { status: string } => Object.assign(new EventEmitter(), { status });
|
|
31
|
+
|
|
32
|
+
afterEach(() => vi.useRealTimers());
|
|
33
|
+
|
|
34
|
+
it('true at once when the client is already ready', async () => {
|
|
35
|
+
await expect(waitForRedisReady(10_000, fakeClient('ready') as never)).resolves.toBe(true);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('true when the client becomes ready within the wait (here after 5 s)', async () => {
|
|
39
|
+
vi.useFakeTimers();
|
|
40
|
+
const client = fakeClient('reconnecting');
|
|
41
|
+
const waiting = waitForRedisReady(10_000, client as never);
|
|
42
|
+
vi.advanceTimersByTime(5_000);
|
|
43
|
+
client.status = 'ready';
|
|
44
|
+
client.emit('ready');
|
|
45
|
+
await expect(waiting).resolves.toBe(true);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('false exactly at the deadline when it never becomes ready, and stops listening', async () => {
|
|
49
|
+
vi.useFakeTimers();
|
|
50
|
+
const client = fakeClient('reconnecting');
|
|
51
|
+
let settled: boolean | undefined;
|
|
52
|
+
void waitForRedisReady(10_000, client as never).then((value) => (settled = value));
|
|
53
|
+
await vi.advanceTimersByTimeAsync(9_999);
|
|
54
|
+
expect(settled).toBeUndefined();
|
|
55
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
56
|
+
expect(settled).toBe(false);
|
|
57
|
+
expect(client.listenerCount('ready')).toBe(0);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { requestIdFrom } from '../request-id.js';
|
|
3
|
+
|
|
4
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
5
|
+
|
|
6
|
+
describe('requestIdFrom (inbound X-Request-Id)', () => {
|
|
7
|
+
it('keeps a short, plain id from a proxy', () => {
|
|
8
|
+
expect(requestIdFrom('trace-01.ABC_def')).toBe('trace-01.ABC_def');
|
|
9
|
+
const uuid = '3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90';
|
|
10
|
+
expect(requestIdFrom(uuid)).toBe(uuid);
|
|
11
|
+
expect(requestIdFrom('a'.repeat(128))).toBe('a'.repeat(128));
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('replaces anything else with a fresh UUID', () => {
|
|
15
|
+
for (const bad of ['a'.repeat(129), 'has space', 'semi;colon', '', '<script>']) {
|
|
16
|
+
const id = requestIdFrom(bad);
|
|
17
|
+
expect(id, JSON.stringify(bad)).toMatch(UUID);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('replaces a missing or repeated header', () => {
|
|
22
|
+
expect(requestIdFrom(undefined)).toMatch(UUID);
|
|
23
|
+
expect(requestIdFrom(['one', 'two'])).toMatch(UUID);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
3
|
+
import { logger } from '@libs/logger.js';
|
|
4
|
+
import {
|
|
5
|
+
formatRequestLine,
|
|
6
|
+
logRequestLine,
|
|
7
|
+
requestLogFields,
|
|
8
|
+
requestPath,
|
|
9
|
+
shouldAttachFields,
|
|
10
|
+
shouldColorize,
|
|
11
|
+
type RequestLineParts,
|
|
12
|
+
} from '../requestLogger.js';
|
|
13
|
+
|
|
14
|
+
vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
|
|
15
|
+
vi.mock('@libs/client-ip.js', () => ({ getClientIp: (): string => '203.0.113.7' }));
|
|
16
|
+
|
|
17
|
+
// ESC (0x1b) starts every ANSI colour code. Production JSON logs must never contain it.
|
|
18
|
+
const ESC = '\x1b';
|
|
19
|
+
|
|
20
|
+
const parts: RequestLineParts = {
|
|
21
|
+
method: 'GET',
|
|
22
|
+
url: '/api/v1/auth/me',
|
|
23
|
+
statusCode: 200,
|
|
24
|
+
statusMessage: 'OK',
|
|
25
|
+
durationMs: 12,
|
|
26
|
+
clientIp: '203.0.113.7',
|
|
27
|
+
requestId: 'req-1',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
describe('shouldColorize', () => {
|
|
31
|
+
it('colours only a real terminal outside production', () => {
|
|
32
|
+
expect(shouldColorize(true, 'development')).toBe(true);
|
|
33
|
+
expect(shouldColorize(true, 'test')).toBe(true);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('never colours production, even on a terminal', () => {
|
|
37
|
+
expect(shouldColorize(true, 'production')).toBe(false);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('never colours a pipe or file (no TTY), e.g. a container log', () => {
|
|
41
|
+
expect(shouldColorize(false, 'development')).toBe(false);
|
|
42
|
+
expect(shouldColorize(undefined, 'development')).toBe(false);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('formatRequestLine', () => {
|
|
47
|
+
it('writes a plain line without colours', () => {
|
|
48
|
+
const line = formatRequestLine(parts, { color: false });
|
|
49
|
+
expect(line).toBe('GET /api/v1/auth/me 200 OK (12ms) [ip=203.0.113.7 reqId=req-1]');
|
|
50
|
+
expect(line).not.toContain(ESC);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('stays plain for every status class and unknown methods', () => {
|
|
54
|
+
for (const statusCode of [200, 302, 404, 500]) {
|
|
55
|
+
for (const method of ['GET', 'POST', 'DELETE', 'PROPFIND']) {
|
|
56
|
+
expect(formatRequestLine({ ...parts, method, statusCode }, { color: false })).not.toContain(ESC);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('adds colours when asked, around the same text', () => {
|
|
62
|
+
const line = formatRequestLine(parts, { color: true });
|
|
63
|
+
expect(line).toContain(`${ESC}[34m`); // GET is blue
|
|
64
|
+
expect(line).toContain(`${ESC}[32m200 OK`); // 2xx is green
|
|
65
|
+
expect(line.replace(new RegExp(`${ESC}\\[\\d+m`, 'g'), '')).toBe(formatRequestLine(parts, { color: false }));
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('the query never reaches a request log', () => {
|
|
70
|
+
it('requestPath drops the query and the fragment, keeps route params', () => {
|
|
71
|
+
expect(requestPath('/api/v1/admin/users?search=jane@example.com&page=2')).toBe('/api/v1/admin/users');
|
|
72
|
+
expect(requestPath('/api/v1/admin/users/0b7c/status#x')).toBe('/api/v1/admin/users/0b7c/status');
|
|
73
|
+
expect(requestPath('/api/v1/auth/me')).toBe('/api/v1/auth/me');
|
|
74
|
+
expect(requestPath('/?')).toBe('/');
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('the text line prints the path without the query', () => {
|
|
78
|
+
const line = formatRequestLine({ ...parts, url: '/api/v1/admin/users?search=jane@example.com' }, { color: false });
|
|
79
|
+
expect(line).toBe('GET /api/v1/admin/users 200 OK (12ms) [ip=203.0.113.7 reqId=req-1]');
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('requestLogFields has exactly the six fields, with the path', () => {
|
|
83
|
+
expect(requestLogFields({ ...parts, url: '/api/v1/auth/me?token=abc' })).toEqual({
|
|
84
|
+
reqId: 'req-1',
|
|
85
|
+
method: 'GET',
|
|
86
|
+
path: '/api/v1/auth/me',
|
|
87
|
+
statusCode: 200,
|
|
88
|
+
durationMs: 12,
|
|
89
|
+
ip: '203.0.113.7',
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe('logRequestLine', () => {
|
|
95
|
+
const request = (url: string): FastifyRequest =>
|
|
96
|
+
({ method: 'GET', url, id: 'req-9', startTime: Date.now() - 5 }) as unknown as FastifyRequest;
|
|
97
|
+
const reply = (statusCode: number): FastifyReply =>
|
|
98
|
+
({ statusCode, raw: { statusMessage: 'Status' } }) as unknown as FastifyReply;
|
|
99
|
+
|
|
100
|
+
beforeEach(() => vi.clearAllMocks());
|
|
101
|
+
|
|
102
|
+
it('fields are attached only where logs are JSON (production)', () => {
|
|
103
|
+
expect(shouldAttachFields('production')).toBe(true);
|
|
104
|
+
expect(shouldAttachFields('development')).toBe(false);
|
|
105
|
+
expect(shouldAttachFields('test')).toBe(false);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it.each([
|
|
109
|
+
[200, 'info'],
|
|
110
|
+
[302, 'info'],
|
|
111
|
+
[404, 'warn'],
|
|
112
|
+
[503, 'error'],
|
|
113
|
+
] as const)('production: %i logs at %s with the fields and the line, no query anywhere', (status, level) => {
|
|
114
|
+
logRequestLine(request('/api/v1/admin/users?search=jane@example.com'), reply(status), { color: false, fields: true });
|
|
115
|
+
const call = vi.mocked(logger[level]).mock.calls[0] as unknown as [Record<string, unknown>, string];
|
|
116
|
+
expect(call[0]).toMatchObject({ reqId: 'req-9', method: 'GET', path: '/api/v1/admin/users', statusCode: status, ip: '203.0.113.7' });
|
|
117
|
+
expect(typeof call[0].durationMs).toBe('number');
|
|
118
|
+
expect(call[1]).toMatch(new RegExp(`^GET {4}/api/v1/admin/users ${status} Status `));
|
|
119
|
+
expect(JSON.stringify(call)).not.toMatch(/jane|search=|\?/);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('development: the one line only, no field object (pino-pretty would print each field)', () => {
|
|
123
|
+
logRequestLine(request('/api/v1/auth/me?x=1'), reply(200), { color: false, fields: false });
|
|
124
|
+
expect(vi.mocked(logger.info).mock.calls[0]).toEqual([expect.stringMatching(/^GET {4}\/api\/v1\/auth\/me 200 /)]);
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* safeHttpClient (../safe-http.ts) against a real local HTTP server. The test
|
|
3
|
+
* policy allows ONLY that server's address (127.0.0.1) on top of the production
|
|
4
|
+
* rules, so every other internal or special address stays forbidden, and a
|
|
5
|
+
* fake resolver decides what each test hostname "resolves" to.
|
|
6
|
+
*/
|
|
7
|
+
import http from 'node:http';
|
|
8
|
+
import type { AddressInfo } from 'node:net';
|
|
9
|
+
import type { LookupAddress } from 'node:dns';
|
|
10
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
11
|
+
import { createSafeHttpClient, safeHttpClient } from '../safe-http.js';
|
|
12
|
+
import { isForbiddenOutboundIp } from '../url-safety.js';
|
|
13
|
+
import { OutboundHttpError } from '../http.js';
|
|
14
|
+
|
|
15
|
+
vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
16
|
+
|
|
17
|
+
let port = 0;
|
|
18
|
+
const hits: string[] = [];
|
|
19
|
+
const server = http.createServer((req, res) => {
|
|
20
|
+
hits.push(req.url ?? '');
|
|
21
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
22
|
+
if (url.pathname === '/redirect') {
|
|
23
|
+
res.writeHead(302, { location: url.searchParams.get('to') ?? '/' });
|
|
24
|
+
return res.end();
|
|
25
|
+
}
|
|
26
|
+
if (url.pathname === '/loop') {
|
|
27
|
+
res.writeHead(302, { location: '/loop' });
|
|
28
|
+
return res.end();
|
|
29
|
+
}
|
|
30
|
+
if (url.pathname === '/big') {
|
|
31
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream' });
|
|
32
|
+
return res.end(Buffer.alloc(11 * 1024 * 1024, 1));
|
|
33
|
+
}
|
|
34
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
35
|
+
res.end(JSON.stringify({ ok: true }));
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/** Test DNS: public.test → the local server, internal.test → 10.0.0.5, mixed.test → both. */
|
|
39
|
+
const resolve = async (hostname: string): Promise<LookupAddress[]> => {
|
|
40
|
+
if (hostname === 'public.test') return [{ address: '127.0.0.1', family: 4 }];
|
|
41
|
+
if (hostname === 'internal.test') return [{ address: '10.0.0.5', family: 4 }];
|
|
42
|
+
if (hostname === 'mixed.test') return [{ address: '127.0.0.1', family: 4 }, { address: '169.254.169.254', family: 4 }];
|
|
43
|
+
return [];
|
|
44
|
+
};
|
|
45
|
+
const client = createSafeHttpClient({ resolve, isForbidden: (ip) => ip !== '127.0.0.1' && isForbiddenOutboundIp(ip) });
|
|
46
|
+
|
|
47
|
+
beforeAll(async () => {
|
|
48
|
+
await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
|
|
49
|
+
port = (server.address() as AddressInfo).port;
|
|
50
|
+
});
|
|
51
|
+
afterAll(() => {
|
|
52
|
+
server.close();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
async function failure(promise: Promise<unknown>): Promise<OutboundHttpError> {
|
|
56
|
+
try {
|
|
57
|
+
await promise;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
return error as OutboundHttpError;
|
|
60
|
+
}
|
|
61
|
+
throw new Error('expected the request to fail');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
describe('safeHttpClient', () => {
|
|
65
|
+
it('fetches a public target (a hostname whose every answer is allowed)', async () => {
|
|
66
|
+
const res = await client.get(`http://public.test:${port}/ok`);
|
|
67
|
+
expect(res.data).toEqual({ ok: true });
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it.each([
|
|
71
|
+
['a hostname resolving to a private address', 'http://internal.test/'],
|
|
72
|
+
['a hostname where ONE answer is internal', 'http://mixed.test:PORT/ok'],
|
|
73
|
+
['loopback as an IP literal (production policy)', 'http://127.0.0.1:PORT/ok'],
|
|
74
|
+
['IPv6 loopback literal', 'http://[::1]:PORT/ok'],
|
|
75
|
+
['127.0.0.1 written as hex IPv4-mapped', 'http://[::ffff:7f00:1]:PORT/ok'],
|
|
76
|
+
['the cloud metadata address', 'http://169.254.169.254/latest/meta-data/'],
|
|
77
|
+
['a non-http protocol', 'file:///etc/passwd'],
|
|
78
|
+
['a data: URL', 'data:text/plain,hello'],
|
|
79
|
+
])('refuses %s, before connecting', async (_label, raw) => {
|
|
80
|
+
const policyClient = raw.includes('127.0.0.1') || raw.includes('[::') ? safeHttpClient : client;
|
|
81
|
+
const before = hits.length;
|
|
82
|
+
const error = await failure(policyClient.get(raw.replace('PORT', String(port))));
|
|
83
|
+
expect(error).toBeInstanceOf(OutboundHttpError);
|
|
84
|
+
expect(error.kind).toBe('blocked');
|
|
85
|
+
expect(hits.length).toBe(before); // the server never saw the request
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('refuses a redirect to an internal IP literal (checked on every hop)', async () => {
|
|
89
|
+
const before = hits.length;
|
|
90
|
+
const error = await failure(client.get(`http://public.test:${port}/redirect?to=${encodeURIComponent('http://169.254.169.254/')}`));
|
|
91
|
+
expect(error.kind).toBe('blocked');
|
|
92
|
+
expect(hits.slice(before)).toEqual([`/redirect?to=${encodeURIComponent('http://169.254.169.254/')}`]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('refuses a redirect to a hostname that resolves internally', async () => {
|
|
96
|
+
const error = await failure(client.get(`http://public.test:${port}/redirect?to=${encodeURIComponent('http://internal.test/')}`));
|
|
97
|
+
expect(error.kind).toBe('blocked');
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('refuses a redirect to another protocol', async () => {
|
|
101
|
+
const error = await failure(client.get(`http://public.test:${port}/redirect?to=${encodeURIComponent('file:///etc/passwd')}`));
|
|
102
|
+
expect(error).toBeInstanceOf(OutboundHttpError);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('follows at most 3 redirects', async () => {
|
|
106
|
+
const before = hits.length;
|
|
107
|
+
const error = await failure(client.get(`http://public.test:${port}/loop`));
|
|
108
|
+
expect(error).toBeInstanceOf(OutboundHttpError);
|
|
109
|
+
expect(hits.length - before).toBe(4); // the first request + 3 redirects
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('stops a response over 10 MB (kind too-large)', async () => {
|
|
113
|
+
const error = await failure(client.get(`http://public.test:${port}/big`, { responseType: 'arraybuffer' }));
|
|
114
|
+
expect(error.kind).toBe('too-large');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('ignores an HTTP_PROXY from the environment (a proxy would fetch the target for us)', async () => {
|
|
118
|
+
const proxyHits: string[] = [];
|
|
119
|
+
const proxy = http.createServer((req, res) => {
|
|
120
|
+
proxyHits.push(req.url ?? '');
|
|
121
|
+
res.end('{}');
|
|
122
|
+
});
|
|
123
|
+
await new Promise<void>((done) => proxy.listen(0, '127.0.0.1', done));
|
|
124
|
+
const saved = process.env.HTTP_PROXY;
|
|
125
|
+
process.env.HTTP_PROXY = `http://127.0.0.1:${(proxy.address() as AddressInfo).port}`;
|
|
126
|
+
try {
|
|
127
|
+
const before = hits.length;
|
|
128
|
+
await client.get(`http://public.test:${port}/ok`);
|
|
129
|
+
expect(proxyHits).toEqual([]);
|
|
130
|
+
expect(hits.length).toBe(before + 1);
|
|
131
|
+
} finally {
|
|
132
|
+
if (saved === undefined) delete process.env.HTTP_PROXY;
|
|
133
|
+
else process.env.HTTP_PROXY = saved;
|
|
134
|
+
proxy.close();
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|