feat(planning): limit server calculations per client IP
Each client IP, read from CF-Connecting-IP or else the socket's remote address, may hold five admitted planning sockets. The server closes a sixth with code 4429 before any message, so that tab calculates locally; closing a socket frees its place. Incoming messages over 1 MB drop the socket without running a calculation. The README states that the limit holds only if the origin accepts traffic from Cloudflare alone, since anyone else can forge the header. Closes #324 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
63fc119297
commit
429b18ba64
4 files changed
+153
-8
No files matched your search
@@ -260,7 +260,7 @@ docker run --rm -p 4000:4000 vac-optimizer
|
||||
|
||||
The image builds the Angular application and the server bundle with Bun alone (no Node), then runs `dist/vac-optimizer/server/server.js` with Bun. The server bundle also includes `leave-planner.worker.js` next to `server.js`, which the server starts for each planning socket. The bundle has no runtime dependencies, so the production stage only copies `dist/` and installs nothing. Set `PORT` to override the default port `4000`; the health check requests `/`.
|
||||
|
||||
The server answers `GET` and `HEAD` only (other methods get 405), except at `/api/planning`: a WebSocket upgrade there opens a planning socket, and any other request there gets `426 Upgrade Required`. The client sends its build identifier in the `build` query parameter; the server closes a socket from a different build (or without one) with code 4409 before sending any message, so that tab calculates locally with its own engine. Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx Proxy Manager, enable WebSocket support for the host. The server serves files from `dist/vac-optimizer/browser` with `Cache-Control: public, max-age=31536000` (content-hashed assets), and returns `index.html` with `Cache-Control: no-cache` for `/index.html` and for every extension-less path, so direct navigation to client routes such as `/benchmark` works. A missing path with a file extension is a 404 rather than HTML, malformed or escaping paths are a 400, and unexpected failures are logged and answered with a plain 500.
|
||||
The server answers `GET` and `HEAD` only (other methods get 405), except at `/api/planning`: a WebSocket upgrade there opens a planning socket, and any other request there gets `426 Upgrade Required`. The client sends its build identifier in the `build` query parameter; the server closes a socket from a different build (or without one) with code 4409 before sending any message, so that tab calculates locally with its own engine. Each client IP may hold five planning sockets at once. The IP is the `CF-Connecting-IP` header, or the address of the connection when the header is absent. The server closes a sixth socket from the same IP with code 4429 before sending any message, so that tab calculates locally with its own engine; closing a socket frees its place. The server also closes a socket whose incoming message exceeds about 1 MB (WebSocket code 1009, or an abnormal close) without running a calculation. The per-IP limit holds only if the origin accepts traffic from Cloudflare alone: anyone who can reach the origin directly can forge `CF-Connecting-IP` and bypass it. Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx Proxy Manager, enable WebSocket support for the host. The server serves files from `dist/vac-optimizer/browser` with `Cache-Control: public, max-age=31536000` (content-hashed assets), and returns `index.html` with `Cache-Control: no-cache` for `/index.html` and for every extension-less path, so direct navigation to client routes such as `/benchmark` works. A missing path with a file extension is a 404 rather than HTML, malformed or escaping paths are a 400, and unexpected failures are logged and answered with a plain 500.
|
||||
|
||||
## Continuous integration
|
||||
|
||||
|
||||
@@ -9,7 +9,12 @@ import {
|
||||
type PlanningOutcome,
|
||||
type PlanningRequest,
|
||||
} from './app/services/leave-planner.service';
|
||||
import { createServer, PLANNING_BUILD_MISMATCH } from './server';
|
||||
import {
|
||||
createServer,
|
||||
PLANNING_BUILD_MISMATCH,
|
||||
PLANNING_CLIENT_LIMIT,
|
||||
PLANNING_JOBS_PER_CLIENT,
|
||||
} from './server';
|
||||
import { BunWebSocket, BunWorker } from './test-setup';
|
||||
import { vi } from './testing/vitest-compat';
|
||||
|
||||
@@ -184,6 +189,45 @@ describe('server-side planning equivalence', () => {
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('calculates locally when the server already holds five jobs for the client IP', async () => {
|
||||
// The test client and these sockets share one remote address.
|
||||
const url = new URL('/api/planning', server.url);
|
||||
url.protocol = 'ws:';
|
||||
url.searchParams.set('build', BUILD);
|
||||
const held = Array.from({ length: PLANNING_JOBS_PER_CLIENT }, () => new BunWebSocket(url));
|
||||
try {
|
||||
await Promise.all(
|
||||
held.map(
|
||||
(socket) => new Promise((resolve) => socket.addEventListener('open', resolve)),
|
||||
),
|
||||
);
|
||||
const refused = await runRemote(scenarioRequest('typed obligations'));
|
||||
const [socket] = sockets.slice(-1);
|
||||
expect(socket.closeCode).toBe(PLANNING_CLIENT_LIMIT);
|
||||
expect(socket.received).toEqual([]);
|
||||
expect(refused.createdWorkers.filter((worker) => !worker.local)).toEqual([]);
|
||||
expect(refused.createdWorkers.filter((worker) => worker.local)).toHaveLength(1);
|
||||
expect(held.every((candidate) => candidate.readyState === BunWebSocket.OPEN)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
const local = await runLocal(scenarioRequest('typed obligations'));
|
||||
expect(refused.outcome).toEqual(local.outcome);
|
||||
expect(refused.explanation).toEqual(local.explanation);
|
||||
} finally {
|
||||
// Wait for the close handshake so the next test finds the places free.
|
||||
await Promise.all(
|
||||
held.map(
|
||||
(socket) =>
|
||||
new Promise((resolve) => {
|
||||
socket.addEventListener('close', resolve);
|
||||
socket.close();
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('analyses a placement over its own socket like a local worker', async () => {
|
||||
const remote = await runRemote(scenarioRequest('typed obligations'));
|
||||
const placement = placementOf(remote.outcome);
|
||||
|
||||
+75
-3
@@ -4,7 +4,12 @@ import { connect } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { calculatePlanningAsyncInternal } from './app/services/leave-planner.core';
|
||||
import { createServer, PLANNING_BUILD_MISMATCH } from './server';
|
||||
import {
|
||||
createServer,
|
||||
PLANNING_BUILD_MISMATCH,
|
||||
PLANNING_CLIENT_LIMIT,
|
||||
PLANNING_JOBS_PER_CLIENT,
|
||||
} from './server';
|
||||
import { BunWebSocket, BunWorker } from './test-setup';
|
||||
import { vi } from './testing/vitest-compat';
|
||||
|
||||
@@ -21,12 +26,19 @@ const workers: CountingWorker[] = [];
|
||||
// Records each server worker so a test can tell whether its own was terminated.
|
||||
class CountingWorker extends BunWorker {
|
||||
terminated = false;
|
||||
readonly posted: unknown[] = [];
|
||||
|
||||
constructor(...args: ConstructorParameters<typeof Worker>) {
|
||||
super(...args);
|
||||
workers.push(this);
|
||||
}
|
||||
|
||||
override postMessage(message: unknown, ...rest: unknown[]) {
|
||||
this.posted.push(message);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(super.postMessage as any)(message, ...rest);
|
||||
}
|
||||
|
||||
override terminate() {
|
||||
this.terminated = true;
|
||||
return super.terminate();
|
||||
@@ -63,11 +75,16 @@ const PLAN = {
|
||||
type Message = { type: string; [key: string]: any };
|
||||
|
||||
// A planning client; `until` resolves with every message up to the first one of that type.
|
||||
function planningSocket(base: URL, build: string | null = 'test-build') {
|
||||
function planningSocket(
|
||||
base: URL,
|
||||
build: string | null = 'test-build',
|
||||
headers?: Record<string, string>,
|
||||
) {
|
||||
const url = new URL('/api/planning', base);
|
||||
url.protocol = 'ws:';
|
||||
if (build !== null) url.searchParams.set('build', build);
|
||||
const socket = new BunWebSocket(url);
|
||||
// Bun's WebSocket accepts request headers; the DOM typings omit them.
|
||||
const socket = new BunWebSocket(url, { headers } as unknown as string[]);
|
||||
const received: Message[] = [];
|
||||
const waiters: (() => void)[] = [];
|
||||
const closed = new Promise<{ code: number }>((resolve) =>
|
||||
@@ -364,6 +381,61 @@ describe('planning socket', () => {
|
||||
expect(workers).toHaveLength(before);
|
||||
});
|
||||
|
||||
describe('per-client limit', () => {
|
||||
const client = (ip: string) =>
|
||||
planningSocket(server.url, 'test-build', { 'CF-Connecting-IP': ip });
|
||||
const open = async (ip: string) => {
|
||||
const socket = client(ip);
|
||||
await socket.opened;
|
||||
return socket;
|
||||
};
|
||||
|
||||
it('refuses a sixth job from one IP, admits another IP, and frees a place on close', async () => {
|
||||
const before = workers.length;
|
||||
const held = [];
|
||||
for (let i = 0; i < PLANNING_JOBS_PER_CLIENT; i++) held.push(await open('203.0.113.7'));
|
||||
expect(workers).toHaveLength(before + PLANNING_JOBS_PER_CLIENT);
|
||||
|
||||
const refused = client('203.0.113.7');
|
||||
refused.socket.addEventListener('open', () =>
|
||||
refused.send({ type: 'plan', request: PLAN }),
|
||||
);
|
||||
expect((await refused.closed).code).toBe(PLANNING_CLIENT_LIMIT);
|
||||
expect(refused.received).toEqual([]);
|
||||
expect(workers).toHaveLength(before + PLANNING_JOBS_PER_CLIENT);
|
||||
|
||||
const other = await open('203.0.113.8');
|
||||
other.send({ type: 'plan', request: PLAN });
|
||||
expect((await other.until('result')).at(-1)?.['outcome']).toBeDefined();
|
||||
|
||||
held[0].socket.close();
|
||||
await held[0].closed;
|
||||
// The server frees the place when it sees the close, shortly after the client does.
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const freed = client('203.0.113.7');
|
||||
await freed.opened;
|
||||
held.push(freed);
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
for (const socket of [...held, other]) socket.socket.close();
|
||||
}, 20_000);
|
||||
|
||||
it('closes an oversized first message without running a calculation', async () => {
|
||||
const before = workers.length;
|
||||
const socket = await open('203.0.113.9');
|
||||
socket.socket.send(
|
||||
JSON.stringify({ type: 'plan', request: PLAN, padding: 'x'.repeat(1024 * 1024) }),
|
||||
);
|
||||
|
||||
// Bun drops the connection without a close frame, which the client reports as 1006.
|
||||
expect([1006, 1009]).toContain((await socket.closed).code);
|
||||
expect(socket.received).toEqual([]);
|
||||
expect(workers.slice(before).flatMap((worker) => worker.posted)).toEqual([]);
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
it('answers 426 to /api/planning without a WebSocket upgrade', async () => {
|
||||
const response = await fetch(new URL('/api/planning', server.url));
|
||||
|
||||
|
||||
+32
-3
@@ -4,6 +4,11 @@ import { planningBuild } from './app/services/planning-build';
|
||||
const IMMUTABLE = 'public, max-age=31536000';
|
||||
/** Close code for a planning socket whose client was built differently from this server. */
|
||||
export const PLANNING_BUILD_MISMATCH = 4409;
|
||||
/** Close code for a planning socket from a client IP that already holds its share of jobs. */
|
||||
export const PLANNING_CLIENT_LIMIT = 4429;
|
||||
export const PLANNING_JOBS_PER_CLIENT = 5;
|
||||
// Planning requests are a few kilobytes; Bun drops a socket whose incoming message is larger.
|
||||
const MAX_MESSAGE_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Fetch handler for a client-only Angular build in `root`: existing files are served as-is,
|
||||
@@ -55,7 +60,12 @@ export function createHandler(root: string) {
|
||||
}
|
||||
|
||||
type PlanningSocket = Bun.ServerWebSocket<PlanningSocketData>;
|
||||
type PlanningSocketData = { build: string | null; job?: PlanningJob };
|
||||
type PlanningSocketData = {
|
||||
build: string | null;
|
||||
client: string;
|
||||
admitted?: boolean;
|
||||
job?: PlanningJob;
|
||||
};
|
||||
|
||||
/**
|
||||
* One planning socket = one worker job. Client messages are buffered until the worker starts, so
|
||||
@@ -126,13 +136,20 @@ export function createServer({
|
||||
};
|
||||
if (!planning) return Bun.serve({ port, fetch: handler, error });
|
||||
|
||||
// Admitted sockets per client IP; entries are dropped at zero.
|
||||
const jobsByClient = new Map<string, number>();
|
||||
|
||||
return Bun.serve<PlanningSocketData>({
|
||||
port,
|
||||
fetch(request, server) {
|
||||
const url = new URL(request.url);
|
||||
if (url.pathname !== '/api/planning') return handler(request);
|
||||
if (server.upgrade(request, { data: { build: url.searchParams.get('build') } }))
|
||||
return undefined;
|
||||
// Behind Cloudflare the socket address is the proxy's; the header is trusted only if the
|
||||
// origin accepts Cloudflare traffic alone.
|
||||
const client =
|
||||
request.headers.get('CF-Connecting-IP') || server.requestIP(request)?.address || '';
|
||||
const build = url.searchParams.get('build');
|
||||
if (server.upgrade(request, { data: { build, client } })) return undefined;
|
||||
return new Response('Upgrade Required', { status: 426 });
|
||||
},
|
||||
websocket: {
|
||||
@@ -140,6 +157,11 @@ export function createServer({
|
||||
// A client from another build runs its own engine; refuse before any worker starts.
|
||||
if (ws.data.build !== planning.build)
|
||||
return ws.close(PLANNING_BUILD_MISMATCH, 'Build mismatch');
|
||||
const held = jobsByClient.get(ws.data.client) ?? 0;
|
||||
if (held >= PLANNING_JOBS_PER_CLIENT)
|
||||
return ws.close(PLANNING_CLIENT_LIMIT, 'Too many calculations');
|
||||
jobsByClient.set(ws.data.client, held + 1);
|
||||
ws.data.admitted = true;
|
||||
ws.data.job = new PlanningJob(ws, planning.worker);
|
||||
ws.data.job.start();
|
||||
},
|
||||
@@ -147,7 +169,14 @@ export function createServer({
|
||||
close(ws) {
|
||||
ws.data.job?.stop();
|
||||
ws.data.job = undefined;
|
||||
// Only an admitted socket holds a place, and it releases it once.
|
||||
if (!ws.data.admitted) return;
|
||||
ws.data.admitted = false;
|
||||
const held = (jobsByClient.get(ws.data.client) ?? 1) - 1;
|
||||
if (held > 0) jobsByClient.set(ws.data.client, held);
|
||||
else jobsByClient.delete(ws.data.client);
|
||||
},
|
||||
maxPayloadLength: MAX_MESSAGE_BYTES,
|
||||
},
|
||||
error,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user