Files
pulse/tests/ratelimit.test.js
T

31 lines
1.4 KiB
JavaScript
Raw Normal View History

'use strict';
process.env.TRUSTED_PROXIES = '192.0.2.10';
const { rateLimitKey } = require('../lib/ratelimit');
const PROXY = '192.0.2.10';
const req = (remoteAddress, headers = {}) => ({ headers, ip: remoteAddress, socket: { remoteAddress } });
const env = { GANDALF_API_KEY: 'g-key' };
beforeAll(() => jest.spyOn(console, 'warn').mockImplementation(() => {}));
afterAll(() => jest.restoreAllMocks());
test('each signed-in user behind the proxy gets their own bucket', () => {
expect(rateLimitKey(req(PROXY, { 'remote-user': 'alice' }), env)).toBe('user:alice');
expect(rateLimitKey(req(PROXY, { 'remote-user': 'bob' }), env)).toBe('user:bob');
});
test('identity headers from anywhere but the proxy are ignored (keyed by IP)', () => {
expect(rateLimitKey(req('198.51.100.7', { 'remote-user': 'alice' }), env)).toBe('ip:198.51.100.7');
});
test('Gandalf gets its own bucket only with the valid key', () => {
expect(rateLimitKey(req('10.10.10.61', { 'x-gandalf-api-key': 'g-key' }), env)).toBe('gandalf');
expect(rateLimitKey(req('10.10.10.61', { 'x-gandalf-api-key': 'wrong' }), env)).toBe('ip:10.10.10.61');
expect(rateLimitKey(req('10.10.10.61', { 'x-gandalf-api-key': 'g-key' }), {})).toBe('ip:10.10.10.61');
});
test('anything else is keyed by IP (IPv6 grouped by subnet)', () => {
expect(rateLimitKey(req('10.10.10.8'), env)).toBe('ip:10.10.10.8');
expect(rateLimitKey(req('2001:db8::1'), env)).toBe(rateLimitKey(req('2001:db8::2'), env));
});