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:
1 parent
ae1e3bef9b
commit
b102e55495
5 files changed
+340
-34
No files matched your search
@@ -15,20 +15,6 @@ From a security review, none of them urgent.
|
||||
of a tracker the user chose, but cheap: cap `event.data.length` before parsing, cap the log, drop
|
||||
failure reasons after acceptance or log one.
|
||||
|
||||
- The tracker relays anything: `isSdp` only checks for a string, so it passes any payload up to
|
||||
`MAX_FORWARDED` between two peers of a swarm, usable as a small message relay. The SDP is sealed,
|
||||
the tracker can't check it's SDP. Checking for base64 of a plausible length only shapes what it
|
||||
relays, any data can be base64. What limits the relay is a quota: bytes forwarded per IP over
|
||||
time, and a per-IP connection rate, not only `MAX_PER_IP` concurrent ones, so reconnecting doesn't
|
||||
reset it. Or decide this is accepted and say so in `tracker.mjs`.
|
||||
|
||||
- The tracker's plain HTTP path isn't counted: `MAX_CONNECTIONS` and `MAX_PER_IP` only apply to
|
||||
upgrades, a non-upgrade request gets a 404 with Node's default timeouts. Don't count on Caddy for
|
||||
it, its defaults may not cut slow clients short either. Setting `headersTimeout`,
|
||||
`requestTimeout`, `keepAliveTimeout` and `maxHeadersCount`, and closing the socket after the 404,
|
||||
costs little. Queues can reach `MAX_QUEUED` × `MAX_CONNECTIONS` = 32 MiB against `mem_limit: 96m`,
|
||||
maybe a global byte budget.
|
||||
|
||||
- Framing: no `frame-ancestors`, so another page can frame HellCon and overlay the security check's
|
||||
buttons. Gains little: a framed HellCon starts empty like any other, nothing is kept, so it has no
|
||||
file or offer the user didn't pick or paste inside it, and the address bar shows the framing site.
|
||||
|
||||
@@ -7,3 +7,8 @@ ORIGINS=https://hellcon.example.org
|
||||
|
||||
# The external network Caddy is on, "caddy" if unset.
|
||||
#CADDY_NETWORK=caddy
|
||||
|
||||
# Whose X-Forwarded-For the tracker believes, addresses or CIDRs separated by commas or spaces. Every
|
||||
# private range if unset, see compose.yaml. Narrow it to Caddy's address in CADDY_NETWORK, but keep it
|
||||
# covered: otherwise all clients count as Caddy's and share its limits, nearly all are refused.
|
||||
#PROXIES=172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 fd00::/8
|
||||
@@ -18,6 +18,12 @@ services:
|
||||
build: .
|
||||
environment:
|
||||
ORIGINS: ${ORIGINS:?set ORIGINS in .env to where HellCon is served from}
|
||||
# Whose X-Forwarded-For the tracker believes, addresses or CIDRs, see clientIp in tracker.mjs.
|
||||
# Caddy reaches it over the shared network, whose subnet is Docker's choice, so the default
|
||||
# trusts every private range: nothing public should reach the tracker besides Caddy. Set
|
||||
# PROXIES in .env to narrow it, e.g. to your Caddy's address in that network. If it doesn't
|
||||
# cover Caddy's address, all clients count as Caddy's and share its limits, nearly all are refused.
|
||||
PROXIES: ${PROXIES:-172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 fd00::/8}
|
||||
networks:
|
||||
caddy:
|
||||
aliases: [hellcon-tracker]
|
||||
|
||||
+164
-17
@@ -1,8 +1,10 @@
|
||||
// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
|
||||
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
|
||||
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
|
||||
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged.
|
||||
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged
|
||||
// but one warning about PROXIES, without any address.
|
||||
import { createServer } from 'node:http';
|
||||
import { BlockList, isIP } from 'node:net';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
// Read on import, 0 picks a free one, see server.address().
|
||||
@@ -24,12 +26,36 @@ const MAX_MESSAGE = 16 * 1024;
|
||||
const MAX_MESSAGES = 10;
|
||||
const RATE_WINDOW = 10_000;
|
||||
const MAX_FORWARDED = 64 * 1024;
|
||||
// A positive number from the environment, read on every use like ORIGINS, so the spec can lower it
|
||||
// to a testable moment. 0 or a typo would cut every connection short, the default stands then.
|
||||
const fromEnv = (name, fallback) => {
|
||||
const value = Number(process.env[name]);
|
||||
return value > 0 ? value : fallback;
|
||||
};
|
||||
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
|
||||
// a peer that reads never gets near it.
|
||||
const MAX_QUEUED = 32 * 1024;
|
||||
// The same for all peers together: MAX_QUEUED for each of MAX_CONNECTIONS would be 32 MiB against
|
||||
// mem_limit. A quarter of them can still fill theirs.
|
||||
const maxQueuedAll = () => fromEnv('MAX_QUEUED_ALL', 8 * 1024 * 1024);
|
||||
const MAX_AGE = 7 * 60_000;
|
||||
// A connection that announced nothing by then only holds a slot: 1024 of them would serve nobody
|
||||
// for MAX_AGE.
|
||||
const maxSilent = () => fromEnv('MAX_SILENT', 30_000);
|
||||
const MAX_CONNECTIONS = 1024;
|
||||
const MAX_PER_IP = 16;
|
||||
// Per address and window, across its connections: MAX_PER_IP is only at once, MAX_FORWARDED only one
|
||||
// connection, so a client that reconnects would otherwise get a fresh allowance for each. The window
|
||||
// is long enough for a search to walk the trackers and to reannounce, short enough to cap a relay.
|
||||
// Relaying through many addresses, e.g. the /64s of one /48, is accepted: other WebTorrent trackers
|
||||
// relay anything anyway, the caps only keep one address from using this one's bandwidth.
|
||||
const maxConnectsPerIp = () => fromEnv('MAX_CONNECTS_PER_IP', 120);
|
||||
const maxForwardedPerIp = () => fromEnv('MAX_FORWARDED_PER_IP', 1024 * 1024);
|
||||
const IP_WINDOW = 60_000;
|
||||
// A record without open connections lives until its window is over, a churning client could pile up
|
||||
// many: past a few thousand, the oldest closed ones go. An address dropping out only forgets its
|
||||
// rate, the concurrent limit still holds.
|
||||
const maxIps = () => fromEnv('MAX_IPS', 4 * MAX_CONNECTIONS);
|
||||
// A share has one sender, receivers keep one connection per tracker.
|
||||
const MAX_SWARM = 8;
|
||||
// Offers a sender got and may still answer, the oldest go first.
|
||||
@@ -37,19 +63,51 @@ const MAX_PENDING = 32;
|
||||
|
||||
// info_hash → peer_id → peer.
|
||||
const swarms = new Map();
|
||||
// address → { open, connects, forwarded, since }, see usage.
|
||||
const perIp = new Map();
|
||||
let connections = 0;
|
||||
// Peers that were sent something and may still have it queued, see fits.
|
||||
const queued = new Set();
|
||||
|
||||
// info_hash, peer_id and offer_id are 20 byte binary strings.
|
||||
const isId = (value) => typeof value === 'string' && value.length === 20;
|
||||
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
|
||||
|
||||
// Behind Caddy, the only way in. Caddy replaces any X-Forwarded-For a client sends, the last entry is
|
||||
// its own anyway. IPv6 counts by /64: a single host usually has a whole one, every address in it
|
||||
// would get MAX_PER_IP of its own. IPv4, also mapped to IPv6, counts as it is.
|
||||
// Whose X-Forwarded-For to believe, PROXIES' addresses or CIDRs. Read on every connection, like
|
||||
// ORIGINS. An entry that is none is left out, as is an empty prefix: it would be 0, all of IPv4.
|
||||
function proxies() {
|
||||
const list = new BlockList();
|
||||
for (const entry of (process.env.PROXIES ?? '').split(/[\s,]+/).filter(Boolean)) {
|
||||
const [base, prefix] = entry.split('/');
|
||||
const type = { 4: 'ipv4', 6: 'ipv6' }[isIP(base)];
|
||||
if (!type) continue;
|
||||
if (prefix === undefined) list.addAddress(base, type);
|
||||
else if (/^\d+$/.test(prefix) && prefix <= (type === 'ipv4' ? 32 : 128)) list.addSubnet(base, Number(prefix), type);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// Once: behind a proxy PROXIES doesn't cover, every client counts as the proxy and shares its limits.
|
||||
let warned = false;
|
||||
|
||||
// The client's address for the per-IP limits. A client that reaches the tracker directly names any
|
||||
// address it likes in X-Forwarded-For, so without a listed proxy only the socket's own counts. Behind
|
||||
// a listed proxy, like Caddy on the compose file's network, the last entry is the client's, whatever
|
||||
// the client put before it. IPv6 counts by /64: a single host usually has a whole one, every address
|
||||
// in it would get an allowance of its own. IPv4, also mapped to IPv6, counts as it is.
|
||||
function clientIp(req) {
|
||||
const ip = req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
|
||||
if (!ip?.includes(':') || ip.includes('.')) return ip;
|
||||
const peer = req.socket.remoteAddress;
|
||||
const header = req.headers['x-forwarded-for'];
|
||||
// BlockList matches IPv4 rules against IPv4-mapped addresses too.
|
||||
const trusted = isIP(peer) && proxies().check(peer, isIP(peer) === 4 ? 'ipv4' : 'ipv6');
|
||||
if (header && !trusted && !warned) {
|
||||
warned = true;
|
||||
console.warn('X-Forwarded-For from an address PROXIES does not cover, ignored. Behind a proxy, add it.');
|
||||
}
|
||||
const forwarded = trusted ? header?.split(',').at(-1).trim() : undefined;
|
||||
const ip = isIP(forwarded) ? forwarded : peer;
|
||||
if (!isIP(ip)) return 'unknown';
|
||||
if (ip.includes('.')) return ip.replace(/^::ffff:/i, '');
|
||||
const [head, tail] = ip.split('::');
|
||||
const groups = head ? head.split(':') : [];
|
||||
if (tail !== undefined) {
|
||||
@@ -62,16 +120,61 @@ function clientIp(req) {
|
||||
.join(':')}::/64`;
|
||||
}
|
||||
|
||||
// The address's record for the current window. Open connections stay counted across a reset, what it
|
||||
// used starts over. A record without open connections is dropped by the sweep once its window is over.
|
||||
function usage(ip) {
|
||||
const now = Date.now();
|
||||
let record = perIp.get(ip);
|
||||
if (!record) {
|
||||
// Room for the new one. At most MAX_CONNECTIONS records have an open connection, so with room to
|
||||
// spare above that there is always a closed one to drop.
|
||||
const limit = maxIps();
|
||||
for (const [old, other] of perIp) {
|
||||
if (perIp.size < limit) break;
|
||||
if (!other.open) perIp.delete(old);
|
||||
}
|
||||
record = { open: 0, connects: 0, forwarded: 0, since: now };
|
||||
perIp.set(ip, record);
|
||||
} else if (now - record.since >= IP_WINDOW) {
|
||||
record.connects = 0;
|
||||
record.forwarded = 0;
|
||||
record.since = now;
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
function refuse(socket, status) {
|
||||
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
|
||||
}
|
||||
|
||||
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
|
||||
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
|
||||
// wait for its close frame.
|
||||
// wait for its close frame. Past maxQueuedAll() for all of them, the largest queues go first: a peer
|
||||
// that reads has next to nothing queued, so one without a queue never goes for the others'.
|
||||
function fits(peer, bytes) {
|
||||
if (peer.ws.bufferedAmount + bytes <= MAX_QUEUED) return true;
|
||||
if (peer.ws.readyState !== peer.ws.OPEN) return false;
|
||||
if (peer.ws.bufferedAmount + bytes > MAX_QUEUED) return drop(peer);
|
||||
let total = bytes;
|
||||
for (const other of queued) {
|
||||
if (other.ws.bufferedAmount) total += other.ws.bufferedAmount;
|
||||
else queued.delete(other);
|
||||
}
|
||||
queued.add(peer);
|
||||
if (total > maxQueuedAll()) {
|
||||
for (const other of [...queued].sort((a, b) => b.ws.bufferedAmount - a.ws.bufferedAmount)) {
|
||||
if (total <= maxQueuedAll() || !other.ws.bufferedAmount) break;
|
||||
total -= other.ws.bufferedAmount;
|
||||
drop(other);
|
||||
}
|
||||
}
|
||||
return peer.ws.readyState === peer.ws.OPEN;
|
||||
}
|
||||
|
||||
// Its queue goes with the socket.
|
||||
function drop(peer) {
|
||||
peer.ws.terminate();
|
||||
queued.delete(peer);
|
||||
return false;
|
||||
}
|
||||
|
||||
function send(peer, message) {
|
||||
@@ -88,6 +191,9 @@ function reject(peer, reason) {
|
||||
function forward(from, to, message, sdp) {
|
||||
from.forwarded += sdp.length;
|
||||
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
|
||||
const used = usage(from.ip);
|
||||
used.forwarded += sdp.length;
|
||||
if (used.forwarded > maxForwardedPerIp()) return reject(from, 'too much signaling');
|
||||
send(to, message);
|
||||
}
|
||||
|
||||
@@ -101,6 +207,7 @@ function announce(peer, msg) {
|
||||
swarms.set(hash, swarm.set(id, peer));
|
||||
peer.id = id;
|
||||
peer.hash = hash;
|
||||
clearTimeout(peer.silent);
|
||||
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
|
||||
if (msg.event === 'stopped') return peer.ws.close();
|
||||
peer.seeder = msg.left === 0;
|
||||
@@ -145,8 +252,20 @@ function announce(peer, msg) {
|
||||
}
|
||||
}
|
||||
|
||||
function open(ws) {
|
||||
const peer = { ws, id: undefined, hash: undefined, seeder: false, pending: new Map(), forwarded: 0, messages: 0 };
|
||||
function open(ws, ip) {
|
||||
const peer = {
|
||||
ws,
|
||||
ip,
|
||||
id: undefined,
|
||||
hash: undefined,
|
||||
seeder: false,
|
||||
pending: new Map(),
|
||||
forwarded: 0,
|
||||
messages: 0,
|
||||
// Terminated, close would keep the slot for ws's 30 s more if the client ignores the close
|
||||
// frame. A peer that never announced has nothing to say goodbye to.
|
||||
silent: setTimeout(() => ws.terminate(), maxSilent()),
|
||||
};
|
||||
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
|
||||
const age = setTimeout(() => ws.close(), MAX_AGE);
|
||||
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
|
||||
@@ -167,6 +286,8 @@ function open(ws) {
|
||||
ws.on('close', () => {
|
||||
clearInterval(rate);
|
||||
clearTimeout(age);
|
||||
clearTimeout(peer.silent);
|
||||
queued.delete(peer);
|
||||
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
|
||||
peer.pending.clear();
|
||||
const swarm = swarms.get(peer.hash);
|
||||
@@ -181,7 +302,22 @@ function open(ws) {
|
||||
}
|
||||
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
|
||||
export const server = createServer((_, res) => res.writeHead(404).end());
|
||||
// Plain requests aren't counted below, only upgraded ones are, so Node's own limits keep them from
|
||||
// piling up, each one's kernel buffers against mem_limit. Node checks headersTimeout and
|
||||
// requestTimeout every connectionsCheckingInterval, 30 s unless set. headersTimeout starts only once
|
||||
// something arrived, the idle timeout on every connection covers one that sends nothing, cleared
|
||||
// for an accepted upgrade: HellCon's peers sit out their announce interval. The 404 closes the
|
||||
// socket, nothing of it stays for a keep-alive. maxConnections caps all sockets, plain ones
|
||||
// included: beyond it Node drops new ones without a response, the one place a client gets a bare
|
||||
// connection error instead of a 503.
|
||||
export const server = createServer({ connectionsCheckingInterval: 5_000 }, (_, res) =>
|
||||
res.writeHead(404, { Connection: 'close' }).end(),
|
||||
);
|
||||
server.on('connection', (socket) => socket.setTimeout(10_000, () => socket.destroy()));
|
||||
server.headersTimeout = 10_000;
|
||||
server.requestTimeout = 30_000;
|
||||
server.maxHeadersCount = 100;
|
||||
server.maxConnections = 2 * MAX_CONNECTIONS;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
|
||||
// client resetting a refused connection would end the process.
|
||||
@@ -189,16 +325,27 @@ server.on('upgrade', (req, socket, head) => {
|
||||
const ip = clientIp(req);
|
||||
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
|
||||
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
|
||||
if ((perIp.get(ip) ?? 0) >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
|
||||
const used = usage(ip);
|
||||
if (used.open >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
|
||||
// Closing a connection doesn't give the address its allowance back.
|
||||
if (used.connects >= maxConnectsPerIp()) return refuse(socket, '429 Too Many Requests');
|
||||
// Counted on the socket, so an upgrade that fails is released too.
|
||||
connections++;
|
||||
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
|
||||
used.open++;
|
||||
used.connects++;
|
||||
socket.once('close', () => {
|
||||
connections--;
|
||||
const left = perIp.get(ip) - 1;
|
||||
if (left) perIp.set(ip, left);
|
||||
else perIp.delete(ip);
|
||||
used.open--;
|
||||
});
|
||||
wss.handleUpgrade(req, socket, head, open);
|
||||
// A peer sits out its announce interval, the idle timeout is over for it.
|
||||
socket.setTimeout(0);
|
||||
wss.handleUpgrade(req, socket, head, (ws) => open(ws, ip));
|
||||
});
|
||||
// An address's window only matters while something of it is open or recent. Once its last connection
|
||||
// is gone and its window over, the record goes: nothing else would ever delete it.
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [ip, record] of perIp) if (!record.open && now - record.since >= IP_WINDOW) perIp.delete(ip);
|
||||
}, IP_WINDOW);
|
||||
sweep.unref();
|
||||
server.listen(PORT);
|
||||
+165
-3
@@ -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');
|
||||
|
||||
Reference in new issue
Block a user