API: trust proxy 1 skok + testy XFF (limity rateLimit liczone po IP klienta za nginxem)

This commit is contained in:
Tilumca
2026-10-14 04:46:55 +02:00
parent 78fa6adfea
commit 18f1432eac
2 changed files with 49 additions and 0 deletions

View File

@@ -30,6 +30,11 @@ import { createExerciseRoutes } from './routes/exercises.js';
export function createApp(deps: AppDeps): express.Express {
const app = express();
// Frontendy (nginx w kontenerach app/admin, vite dev proxy) wystawiaja API pod tym
// samym originem — dokladnie jeden skok proxy. Ufamy mu, zeby req.ip (kubełki
// rateLimit, logi) liczyl sie po adresie klienta z X-Forwarded-For, a nie po IP proxy.
app.set('trust proxy', 1);
app.use(helmet());
app.use(
cors({

View File

@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest';
import { buildApp, rand, PASSWORD } from '../helpers.js';
// Frontendy proxyja API przez nginx/vite (same-origin), Express ufa jednemu skokowi
// proxy (app.set('trust proxy', 1)). Bez tego kubełek authLimiter (50/15min) liczylby
// sie po IP kontenera nginx — wszyscy uzytkownicy dostaliby 429 zbiorowo.
describe('trust proxy — limity per adres klienta za nginxem', () => {
it('GET /health przechodzi z naglowkiem X-Forwarded-For', async () => {
const app = buildApp();
const res = await app.get('/health').set('X-Forwarded-For', '203.0.113.7');
expect(res.status).toBe(200);
expect(res.body.status).toBe('ok');
});
it('51 logowan z roznych X-Forwarded-For nie wyczerpuje authLimiter (brak 429)', async () => {
const app = buildApp();
const emails: string[] = [];
for (let i = 1; i <= 51; i++) emails.push(`xff-diff-${i}-${rand()}@test.local`);
for (let i = 0; i < 51; i++) {
const res = await app
.post('/api/v1/auth/login')
.set('X-Forwarded-For', `203.0.113.${(i % 254) + 1}`)
.send({ email: emails[i], password: PASSWORD });
expect(res.status, `zalodzenie ${i + 1} z IP 203.0.113.${(i % 254) + 1}`).not.toBe(429);
}
}, 120_000);
it('ten sam X-Forwarded-For po 50 probach dostaje 429 (kubelek per IP, nie per proxy)', async () => {
const app = buildApp();
const emails: string[] = [];
for (let i = 0; i < 51; i++) emails.push(`xff-same-${i}-${rand()}@test.local`);
let lastStatus = 0;
for (let i = 0; i < 51; i++) {
const res = await app
.post('/api/v1/auth/login')
.set('X-Forwarded-For', '198.51.100.7')
.send({ email: emails[i], password: PASSWORD });
lastStatus = res.status;
}
expect(lastStatus).toBe(429);
}, 120_000);
});