Limit the tracker per address and harden its plain HTTP path

Per address and minute: connects and forwarded signaling, so reconnecting
doesn't reset a client's allowance. X-Forwarded-For only counts from PROXIES,
checked with net.BlockList, with one warning when an uncovered peer sends it.
Plain requests get timeouts and a closing 404, silent connections go after
30 s and all queues together share a budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-29 20:27:50 +01:00
1 parent ae1e3bef9b
commit b102e55495
5 files changed
+340 -34

No files matched your search

+165 -3
View File
@@ -7,6 +7,7 @@ import { expect, test } from '@playwright/test';
import { WebSocket as ServerSocket } from 'ws';
const ORIGIN = 'https://hellcon.test';
let server;
let url;
// Every connection a test opened, closed after it.
let clients = [];
@@ -18,11 +19,23 @@ let tests = 0;
test.beforeAll(async () => {
process.env.PORT = '0';
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`;
const { server } = await import('./tracker.mjs');
// The tracker believes this test's X-Forwarded-For like Caddy's.
process.env.PROXIES = '127.0.0.1';
// Reconnecting tests pass the per-address limits on purpose, the ones about them lower them.
process.env.MAX_CONNECTS_PER_IP = '100000';
process.env.MAX_FORWARDED_PER_IP = String(64 * 1024 * 1024);
({ server } = await import('./tracker.mjs'));
if (!server.listening) await once(server, 'listening');
url = `ws://127.0.0.1:${server.address().port}`;
});
// e2e.spec.ts may run next in this worker, with the tracker as it is deployed.
test.afterAll(() => {
delete process.env.PROXIES;
delete process.env.MAX_CONNECTS_PER_IP;
delete process.env.MAX_FORWARDED_PER_IP;
});
test.beforeEach(() => {
ip = `198.51.100.${++tests}`;
});
@@ -33,14 +46,29 @@ test.afterEach(async () => {
clients = [];
});
// fn with the environment variables in vars, undefined for unset, as they were again after it.
async function withEnv(vars, fn) {
const set = (name, value) => {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
};
const was = Object.keys(vars).map((name) => [name, process.env[name]]);
for (const [name, value] of Object.entries(vars)) set(name, value);
try {
return await fn();
} finally {
for (const [name, value] of was) set(name, value);
}
}
const id = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(20)));
const sdp = (type, text = type) => ({ type, sdp: text });
// A connection like HellCon's, without one if the tracker refused it. Its messages queue up in
// messages, closed resolves with the close code.
function open({ origin = ORIGIN } = {}) {
function open({ origin = ORIGIN, xff = ip } = {}) {
return new Promise((resolve) => {
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': ip } });
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': xff } });
const client = { ws, messages: [], closed: once(ws, 'close').then(([event]) => event.code) };
ws.addEventListener('message', ({ data }) => client.messages.push(JSON.parse(data)));
ws.addEventListener('open', () => {
@@ -278,6 +306,51 @@ test('limits the signaling forwarded per connection', async () => {
);
});
test('limits the signaling from one address across connections', () =>
withEnv({ MAX_FORWARDED_PER_IP: '20' }, async () => {
const { hash, receiver } = await swarm();
const fields = { action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1 };
// Five bytes each, four fit, the fifth is past the limit though the connection's own is far off.
const offer = { offer_id: id(), offer: sdp('offer') };
for (let i = 0; i < 4; i++) await announce(receiver, { ...fields, offers: [offer] });
await rejected(receiver, { ...fields, offers: [offer] }, 'too much signaling');
// A new connection from the same address doesn't get a fresh allowance.
const again = await open();
const second = { action: 'announce', info_hash: hash, peer_id: id(), left: 1 };
await announce(again, second);
await rejected(again, { ...second, offers: [offer] }, 'too much signaling');
}));
test('limits connections from one address over time, not only at once', () =>
withEnv({ MAX_CONNECTS_PER_IP: '3' }, async () => {
for (let i = 0; i < 3; i++) expect(await open()).toBeTruthy();
// Below MAX_PER_IP, and closing them doesn't reset the rate.
const opened = clients.splice(0);
for (const client of opened) client.ws.close();
await Promise.all(opened.map((client) => client.closed));
expect(await open()).toBeUndefined();
}));
test('forgets the oldest address once too many records pile up', () =>
withEnv({ MAX_IPS: '2', MAX_CONNECTS_PER_IP: '1' }, async () => {
const close = async (address) => {
ip = address;
const client = await open();
client.ws.close();
await client.closed;
// The tracker only evicts closed records, let it see the close first.
await new Promise((resolve) => setTimeout(resolve, 50));
};
await close('192.0.2.1');
await close('192.0.2.2');
// The third record pushes the first out, which may connect again; the second stays limited.
await close('192.0.2.3');
ip = '192.0.2.2';
expect(await open()).toBeUndefined();
ip = '192.0.2.1';
expect(await open()).toBeTruthy();
}));
test('drops a peer that stops reading', async () => {
const hash = id();
const slowId = id();
@@ -310,6 +383,42 @@ test('drops a peer that stops reading', async () => {
expect(await closed).toBe(1006);
});
test('drops the largest queues once all of them together pass MAX_QUEUED_ALL', async () => {
// The tracker's side of the slow sender's connection: what its socket holds is queued, the kernel's
// buffers are full by then.
let queue;
const track = (_, socket) => (queue = socket);
server.on('upgrade', track);
const hash = id();
const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
const closed = once(slow, 'close').then(([code]) => code);
await once(slow, 'open');
server.off('upgrade', track);
slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: id(), left: 0, numwant: 0 }));
await once(slow, 'message');
slow._socket.pause();
// Budget lowered first: once the kernel's buffers are full, the next offer leaves a queue, and
// the reply to the receiver right after it is past the budget. Checked later, the kernel could
// have taken the queue in by then. The slow sender's queue goes, the receiver's reply arrives.
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
await withEnv({ MAX_QUEUED_ALL: '1' }, async () => {
for (let i = 0; i < 1000 && !queue.destroyed; i++) {
const receiver = await open();
const fields = { info_hash: hash, peer_id: id(), left: 1 };
for (let j = 0; j < 4 && !queue.destroyed; j++) {
await announce(receiver, { ...fields, offers: [big()] });
// Gone with its first queue, not once it grew to MAX_QUEUED.
expect(queue.destroyed || !queue.writableLength).toBe(true);
}
receiver.ws.close();
await receiver.closed;
}
});
expect(queue.destroyed).toBe(true);
slow._socket.resume();
expect(await closed).toBe(1006);
});
test('limits a swarm to 8 peers', async () => {
const hash = id();
for (let i = 0; i < 8; i++) await announce(await open(), { info_hash: hash, peer_id: id(), left: 1 });
@@ -334,6 +443,59 @@ test('counts IPv6 by /64, however it is written', async () => {
expect(await open()).toBeTruthy();
});
test('ignores X-Forwarded-For without a trusted proxy', () =>
// Without PROXIES the socket's address counts, a client can't hand-pick a fresh one per
// connection. All these come from 127.0.0.1.
withEnv({ PROXIES: undefined }, async () => {
for (let i = 0; i < 16; i++) expect(await open({ xff: `203.0.113.${i + 1}` })).toBeTruthy();
expect(await open({ xff: '203.0.113.250' })).toBeUndefined();
// With the peer trusted again, the forwarded address counts once more. One that is no address
// counts as the peer's, full by now.
process.env.PROXIES = '127.0.0.1';
for (const xff of ['203.0.113.250:1234', '2001:db8::1::1']) expect(await open({ xff })).toBeUndefined();
expect(await open({ xff: '203.0.113.250' })).toBeTruthy();
// Also as a CIDR, however the proxy's address is written. An IPv4 prefix counts in IPv4's 32
// bits, an empty one is no range at all.
for (const proxies of ['10.0.0.0/8', '10.0.0.0/']) {
process.env.PROXIES = proxies;
expect(await open({ xff: '203.0.113.251' })).toBeUndefined();
}
for (const [i, proxies] of ['127.0.0.0/8', '::ffff:127.0.0.0/120'].entries()) {
process.env.PROXIES = proxies;
expect(await open({ xff: `203.0.113.${251 + i}` })).toBeTruthy();
}
}));
// MAX_SILENT lowered only here: the tests holding 16 silent connections would lose the first ones
// on a busy machine.
test('closes a connection that announces nothing', () =>
// One that only holds a slot goes. Terminated, without a close frame it could ignore.
withEnv({ MAX_SILENT: '500' }, async () => {
const client = await open();
expect(await client.closed).toBe(1006);
}));
test('keeps a connection that announced', () =>
// Also past MAX_SILENT, announcing is the first thing a peer does.
withEnv({ MAX_SILENT: '500' }, async () => {
const client = await open();
const fields = { info_hash: id(), peer_id: id(), left: 0 };
await announce(client, fields);
await new Promise((resolve) => setTimeout(resolve, 750));
await announce(client, fields);
}));
test('answers plain HTTP with a 404 and closes the socket', async () => {
const socket = connectTcp(new URL(url).port, '127.0.0.1');
await once(socket, 'connect');
socket.write('GET / HTTP/1.1\r\nHost: x\r\n\r\n');
const [data] = await once(socket, 'data');
expect(String(data)).toContain('404');
// Connection: close, so unlimited sequential 404s on one connection are over.
expect(String(data).toLowerCase()).toContain('connection: close');
await once(socket, 'close');
});
test('survives clients resetting refused connections', async () => {
for (let i = 0; i < 100; i++) {
const socket = connectTcp(new URL(url).port, '127.0.0.1');