Files
2026-10-22 23:55:28 +11:00

183 lines
6.0 KiB
JavaScript

const test = require('node:test');
const assert = require('node:assert/strict');
const http = require('node:http');
const express = require('express');
const rateLimit = require('express-rate-limit');
const { setup, teardown, cleanup } = require('../helpers');
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function createJar() {
return { cookies: [] };
}
function jarSet(jar, res) {
const cookies = res.headers['set-cookie'];
if (cookies && cookies.length) {
jar.cookies = cookies.map((c) => c.split(';')[0]);
}
}
function jarGet(jar) {
return jar.cookies.join('; ');
}
function fetchJson(base, path, options = {}) {
return new Promise((resolve, reject) => {
const url = new URL(path, base);
const opts = {
method: options.method || 'GET',
headers: {
'Content-Type': 'application/json',
...(options.cookie ? { Cookie: options.cookie } : {}),
},
};
const req = http.request(url, opts, (res) => {
let data = '';
res.on('data', (c) => { data += c; });
res.on('end', () => {
resolve({
status: res.statusCode,
headers: res.headers,
body: data ? JSON.parse(data) : null,
});
});
});
req.on('error', reject);
if (options.body) req.write(JSON.stringify(options.body));
req.end();
});
}
/* ------------------------------------------------------------------ */
/* Test: real login limiter is active (not a no-op) */
/* ------------------------------------------------------------------ */
test('rate limiter: login limiter is active and adds headers', async () => {
const baseUrl = await setup();
try {
// Send 9 bad logins — all should return 401 (max=10 in test env)
for (let i = 0; i < 9; i++) {
const res = await fetchJson(baseUrl, '/api/auth/login', {
method: 'POST',
body: { username: 'nonexistent', password: 'wrong' },
});
assert.equal(res.status, 401, `Login attempt ${i + 1} should return 401`);
assert.equal(res.body.ok, false);
assert.equal(res.body.error.code, 'INVALID_CREDENTIALS');
}
// Verify rate-limit headers are present (proves real limiter, not no-op stub)
const res = await fetchJson(baseUrl, '/api/auth/login', {
method: 'POST',
body: { username: 'nonexistent', password: 'wrong' },
});
assert.equal(res.status, 401);
assert.ok(
res.headers['x-ratelimit-limit'] || res.headers['x-ratelimit-remaining'] !== undefined,
'Response should include rate-limit headers from real limiter'
);
} finally {
await teardown();
cleanup();
}
});
/* ------------------------------------------------------------------ */
/* Test: real register limiter is active */
/* ------------------------------------------------------------------ */
test('rate limiter: register limiter is active and adds headers', async () => {
const baseUrl = await setup();
try {
const res = await fetchJson(baseUrl, '/api/auth/register', {
method: 'POST',
body: { username: 'ratelimituser', password: 'password123' },
});
assert.equal(res.status, 201);
assert.equal(res.body.ok, true);
assert.ok(
res.headers['x-ratelimit-limit'] || res.headers['x-ratelimit-remaining'] !== undefined,
'Register should include rate-limit headers'
);
} finally {
await teardown();
cleanup();
}
});
/* ------------------------------------------------------------------ */
/* Test: 429 response shape is correct JSON envelope */
/* ------------------------------------------------------------------ */
test('rate limiter: 429 returns correct error envelope', async () => {
// Create a minimal Express app with a low-limit rate limiter to verify
// the 429 response shape matches the standard error envelope.
const testApp = express();
testApp.use(express.json());
testApp.set('trust proxy', 1);
const limiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
message: { ok: false, error: { code: 'RATE_LIMITED', message: 'Too many login attempts. Try again later.' } },
});
testApp.post('/api/test-login', limiter, (_req, res) => {
res.json({ ok: true, data: { user: { id: 1, username: 'test' } } });
});
const server = await new Promise((resolve) => {
const s = testApp.listen(0, () => resolve(s));
});
const port = server.address().port;
const testUrl = `http://localhost:${port}`;
try {
// Send 10 requests (all succeed) + 1 (should be 429)
for (let i = 0; i < 10; i++) {
const res = await fetchJson(testUrl, '/api/test-login', {
method: 'POST',
body: { username: 'x', password: 'y' },
});
assert.equal(res.status, 200);
}
// 11th request → 429
const res = await fetchJson(testUrl, '/api/test-login', {
method: 'POST',
body: { username: 'x', password: 'y' },
});
assert.equal(res.status, 429);
assert.equal(res.body.ok, false);
assert.equal(res.body.error.code, 'RATE_LIMITED');
assert.equal(res.body.error.message, 'Too many login attempts. Try again later.');
} finally {
server.close();
}
});
/* ------------------------------------------------------------------ */
/* Test: global /api limiter covers auth routes */
/* ------------------------------------------------------------------ */
test('rate limiter: global /api limiter covers auth routes', async () => {
const baseUrl = await setup();
try {
const res = await fetchJson(baseUrl, '/api/auth/login', {
method: 'POST',
body: { username: 'ratetest2', password: 'wrongpass' },
});
assert.equal(res.status, 401);
assert.ok(
res.headers['x-ratelimit-limit'] || res.headers['x-ratelimit-remaining'] !== undefined,
'Global /api limiter should add rate-limit headers to auth responses'
);
} finally {
await teardown();
cleanup();
}
});