Introduce spawner app with sandboxing support and client protocol implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-12 23:49:05 +02:00
1 parent 571f43457d
commit 7b1df2607e
26 files changed
+2438 -5

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
import { randomBytes } from 'node:crypto';
import { SpawnerClient } from '@homepage/protocol';
const usage = 'usage: cli.ts <spawner socket> run | list | kill <container id>';
const [socketPath, command, argument] = process.argv.slice(2);
if (!socketPath || !command) {
console.error(usage);
process.exit(2);
}
const client = new SpawnerClient(socketPath);
async function run(): Promise<void>
{
const sessionId = randomBytes(12).toString('base64url');
const containerId = await client.spawn(sessionId, Math.floor(Date.now() / 1000) + 20 * 60);
const stream = await client.attach(containerId);
const resize = () => client.resize(containerId, process.stdout.columns, process.stdout.rows).catch(() => {});
await resize();
process.stdout.on('resize', resize);
if (process.stdin.isTTY) process.stdin.setRawMode(true);
process.stdin.pipe(stream, { end: false });
stream.pipe(process.stdout);
stream.on('close', async () =>
{
if (process.stdin.isTTY) process.stdin.setRawMode(false);
await client.kill(containerId).catch(() => {});
process.exit(0);
});
}
switch (command)
{
case 'run':
await run();
break;
case 'list':
console.log(JSON.stringify(await client.list(), null, 2));
break;
case 'kill':
if (!argument) {
console.error(usage);
process.exit(2);
}
await client.kill(argument);
break;
default:
console.error(usage);
process.exit(2);
}
+40
View File
@@ -0,0 +1,40 @@
import { isAbsolute } from 'node:path';
export type SpawnerConfig = {
dockerSocket: string;
listenSocket: string;
image: string;
/** Host paths, resolved by the sandbox daemon and never opened by the spawner. */
contentDir: string;
statusDir: string;
maxSandboxes: number;
/** Only for local development with Podman, where gVisor is unavailable. */
allowNonGvisor: boolean;
};
function required(env: NodeJS.ProcessEnv, name: string): string {
const value = env[name];
if (!value) throw new Error(`${name} is not set`);
return value;
}
function absolute(env: NodeJS.ProcessEnv, name: string): string {
const value = required(env, name);
if (!isAbsolute(value)) throw new Error(`${name} must be an absolute path`);
return value;
}
export function loadConfig(env: NodeJS.ProcessEnv): SpawnerConfig {
const maxSandboxes = Number(env.MAX_SANDBOXES ?? 16);
if (!Number.isInteger(maxSandboxes) || maxSandboxes < 1) throw new Error('MAX_SANDBOXES must be a positive integer');
return {
dockerSocket: env.DOCKER_SOCKET ?? '/run/docker-sandbox/docker.sock',
listenSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
image: required(env, 'SANDBOX_IMAGE'),
contentDir: absolute(env, 'CONTENT_DIR'),
statusDir: absolute(env, 'STATUS_DIR'),
allowNonGvisor: env.SPAWNER_ALLOW_NON_GVISOR === '1',
maxSandboxes,
};
}
+103
View File
@@ -0,0 +1,103 @@
import { request } from 'node:http';
import type { Socket } from 'node:net';
export class DockerError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
/**
* Minimal client for the few Docker Engine API calls the spawner needs.
* Works with Docker and with Podman's Docker compatible API.
*/
export class DockerClient
{
readonly socketPath: string;
constructor(socketPath: string) {
this.socketPath = socketPath;
}
call<T>(method: string, path: string, body?: unknown): Promise<T>
{
return new Promise((resolve, reject) =>
{
const payload = body === undefined ? undefined : JSON.stringify(body);
const req = request(
{
socketPath: this.socketPath,
method,
path,
headers: payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {},
},
(res) =>
{
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () =>
{
const text = Buffer.concat(chunks).toString('utf8');
const status = res.statusCode ?? 0;
if (status >= 400)
{
reject(new DockerError(status, errorMessage(text) ?? `docker responded with ${status}`));
return;
}
try { resolve((text ? JSON.parse(text) : undefined) as T); }
catch { resolve(undefined as T); }
});
res.on('error', reject);
},
);
req.on('error', reject);
req.end(payload);
});
}
/** Upgrades the connection to a raw stream, as used by attach. */
hijack(path: string): Promise<Socket>
{
return new Promise((resolve, reject) =>
{
const req = request({
socketPath: this.socketPath,
method: 'POST',
path,
headers: { Connection: 'Upgrade', Upgrade: 'tcp' },
});
req.on('upgrade', (_res, socket, head) =>
{
if (head.length > 0) socket.unshift(head);
resolve(socket);
});
req.on('response', (res) =>
{
res.resume();
reject(new DockerError(res.statusCode ?? 0, `attach failed with ${res.statusCode}`));
});
req.on('error', reject);
req.end();
});
}
}
function errorMessage(text: string): string | undefined
{
try
{
const parsed = JSON.parse(text) as { message?: unknown };
return typeof parsed.message === 'string' ? parsed.message : undefined;
}
catch { return text || undefined; }
}
+33
View File
@@ -0,0 +1,33 @@
import { chmodSync, rmSync } from 'node:fs';
import { loadConfig } from './config.ts';
import { SandboxManager } from './sandbox.ts';
import { createSpawnerServer } from './server.ts';
const log = (message: string) => console.log(`[spawner] ${message}`);
const config = loadConfig(process.env);
const manager = new SandboxManager(config);
await manager.assertRuntime();
const reaped = await manager.reapOrphans();
if (reaped > 0) log(`removed ${reaped} orphaned sandbox(es)`);
// The socket must never be reachable by anyone outside the shared group,
// not even for the moment between creating it and changing its mode.
process.umask(0o117);
rmSync(config.listenSocket, { force: true });
const server = createSpawnerServer(manager, log);
server.listen(config.listenSocket, () =>
{
chmodSync(config.listenSocket, 0o660);
log(`listening on ${config.listenSocket}`);
});
for (const signal of ['SIGTERM', 'SIGINT'] as const)
{
process.once(signal, () => {
server.close();
process.exit(0);
});
}
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest';
import type { SpawnerConfig } from './config.ts';
import { containerSpec } from './sandbox.ts';
const config: SpawnerConfig = {
dockerSocket: '/docker.sock',
listenSocket: '/spawner.sock',
image: 'registry/homepage-sandbox@sha256:abc',
contentDir: '/srv/content',
statusDir: '/srv/status',
maxSandboxes: 16,
allowNonGvisor: false,
};
describe('containerSpec', () => {
const spec = containerSpec(config, 'session123', 1_800_000_000);
const host = spec.HostConfig;
it('isolates the sandbox', () => {
expect(host.Privileged).toBe(false);
expect(host.ReadonlyRootfs).toBe(true);
expect(host.NetworkMode).toBe('none');
expect(spec.NetworkDisabled).toBe(true);
expect(host.CapDrop).toEqual(['ALL']);
expect(host.SecurityOpt).toContain('no-new-privileges');
expect(spec.User).toBe('guest');
});
it('limits resources', () => {
expect(host.Memory).toBe(80 * 1024 * 1024);
expect(host.MemorySwap).toBe(host.Memory);
expect(host.NanoCpus).toBe(500_000_000);
expect(host.PidsLimit).toBe(50);
expect(host.LogConfig.Type).toBe('none');
});
it('mounts host paths read only', () => {
expect(host.Binds).toEqual(['/srv/content:/srv/www:ro', '/srv/status:/var/status:ro']);
expect(Object.values(host.Tmpfs).every((options) => options.includes('noexec'))).toBe(true);
});
it('passes only the session id and expiry into the container', () => {
expect(spec.Env).toEqual(['SESSION_ID=session123', 'SESSION_EXPIRES_AT=1800000000', 'TERM=xterm-256color']);
});
});
+170
View File
@@ -0,0 +1,170 @@
import type { Socket } from 'node:net';
import { SANDBOX_LABEL, SESSION_LABEL, type ManagedContainer } from '@homepage/protocol';
import type { SpawnerConfig } from './config.ts';
import { DockerClient, DockerError } from './docker.ts';
const MiB = 1024 * 1024;
/**
* The complete container configuration of a sandbox session. Only the
* validated session id and expiry come from outside. Keep in sync with
* deploy/host/sandbox-flags.sh.
*/
export function containerSpec(config: SpawnerConfig, sessionId: string, expiresAt: number)
{
return {
Image: config.image,
User: 'guest',
Hostname: 'sandbox',
Env: [`SESSION_ID=${sessionId}`, `SESSION_EXPIRES_AT=${expiresAt}`, 'TERM=xterm-256color'],
Tty: true,
OpenStdin: true,
StdinOnce: false,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
NetworkDisabled: true,
Labels: { [SANDBOX_LABEL]: '1', [SESSION_LABEL]: sessionId },
HostConfig: {
Privileged: false,
ReadonlyRootfs: true,
NetworkMode: 'none',
CapDrop: ['ALL'],
SecurityOpt: ['no-new-privileges'],
IpcMode: 'private',
Memory: 80 * MiB,
MemorySwap: 80 * MiB,
NanoCpus: 500_000_000,
PidsLimit: 50,
Ulimits: [{ Name: 'nofile', Soft: 256, Hard: 256 }],
Tmpfs: {
'/home/guest': 'size=8m,mode=1777,noexec,nosuid',
'/tmp': 'size=8m,noexec,nosuid',
},
Binds: [`${config.contentDir}:/srv/www:ro`, `${config.statusDir}:/var/status:ro`],
LogConfig: { Type: 'none', Config: {} },
AutoRemove: true,
},
};
}
type ContainerSummary = {
Id: string;
State: string;
Labels?: Record<string, string>;
};
type ContainerDetails = {
Id: string;
State: { Status: string };
Config: { Labels?: Record<string, string> };
};
export class SandboxManager {
readonly config: SpawnerConfig;
readonly docker: DockerClient;
constructor(config: SpawnerConfig, docker = new DockerClient(config.dockerSocket)) {
this.config = config;
this.docker = docker;
}
async assertRuntime(): Promise<void>
{
const info = await this.docker.call<{ DefaultRuntime?: string }>('GET', '/info');
if (info.DefaultRuntime !== 'runsc' && !this.config.allowNonGvisor) {
throw new Error(`the sandbox daemon runs "${info.DefaultRuntime}" instead of gVisor (runsc)`);
}
}
async spawn(sessionId: string, expiresAt: number): Promise<string>
{
const existing = await this.list();
if (existing.length >= this.config.maxSandboxes) throw new Error('sandbox limit reached');
const created = await this.docker.call<{ Id: string }>(
'POST',
`/containers/create?name=sandbox-${sessionId}`,
containerSpec(this.config, sessionId, expiresAt),
);
return created.Id;
}
/** Attaches before starting, so the motd and first prompt are not lost. */
async attach(containerId: string): Promise<Socket>
{
const container = await this.managed(containerId);
const stream = await this.docker.hijack(
`/containers/${container.Id}/attach?stream=1&stdin=1&stdout=1&stderr=1`,
);
if (container.State.Status === 'created')
{
try { await this.docker.call('POST', `/containers/${container.Id}/start`); }
catch (error)
{
stream.destroy();
throw error;
}
}
return stream;
}
async resize(containerId: string, cols: number, rows: number): Promise<void> {
const container = await this.managed(containerId);
await this.docker.call('POST', `/containers/${container.Id}/resize?h=${rows}&w=${cols}`);
}
async kill(containerId: string): Promise<void>
{
let container: ContainerDetails;
try { container = await this.managed(containerId); }
catch (error)
{
if (error instanceof DockerError && error.status === 404) return;
throw error;
}
await this.remove(container.Id);
}
async list(): Promise<ManagedContainer[]>
{
const filters = encodeURIComponent(JSON.stringify({ label: [`${SANDBOX_LABEL}=1`] }));
const containers = await this.docker.call<ContainerSummary[]>('GET', `/containers/json?all=1&filters=${filters}`);
return containers
.filter((container) => container.Labels?.[SANDBOX_LABEL] === '1')
.map((container) => ({
containerId: container.Id,
sessionId: container.Labels?.[SESSION_LABEL] ?? '',
running: container.State === 'running',
}));
}
/** Removes sandboxes left over from a previous run, because nobody can reach them anymore. */
async reapOrphans(): Promise<number> {
const containers = await this.list();
await Promise.all(containers.map((container) => this.remove(container.containerId)));
return containers.length;
}
private async managed(containerId: string): Promise<ContainerDetails> {
const container = await this.docker.call<ContainerDetails>('GET', `/containers/${containerId}/json`);
if (container.Config.Labels?.[SANDBOX_LABEL] !== '1') throw new Error('not a sandbox container');
return container;
}
private async remove(containerId: string): Promise<void>
{
try { await this.docker.call('DELETE', `/containers/${containerId}?force=1`); }
catch (error)
{
// A container with AutoRemove may already be gone or in removal.
if (error instanceof DockerError && (error.status === 404 || error.status === 409)) return;
throw error;
}
}
}
+158
View File
@@ -0,0 +1,158 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { createServer, type IncomingMessage, type Server as HttpServer } from 'node:http';
import type { Server, Socket } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SANDBOX_LABEL, SpawnerClient, SpawnerError } from '@homepage/protocol';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { SpawnerConfig } from './config.ts';
import { SandboxManager } from './sandbox.ts';
import { createSpawnerServer } from './server.ts';
const MANAGED = 'aaaaaaaaaaaa';
const FOREIGN = 'bbbbbbbbbbbb';
type Call = { method: string; path: string; body?: unknown };
/** Pretends to be the Docker Engine API. Attached streams echo input in upper case. */
function fakeDocker(socketPath: string, calls: Call[]): Promise<HttpServer> {
const containers = new Map<string, { labels: Record<string, string>; status: string }>([
[MANAGED, { labels: { [SANDBOX_LABEL]: '1' }, status: 'created' }],
[FOREIGN, { labels: {}, status: 'running' }],
]);
const server = createServer(async (req: IncomingMessage, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const text = Buffer.concat(chunks).toString();
const url = new URL(req.url!, 'http://docker');
calls.push({ method: req.method!, path: url.pathname, body: text ? JSON.parse(text) : undefined });
const send = (status: number, body?: unknown) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(body === undefined ? '' : JSON.stringify(body));
};
const id = url.pathname.split('/')[2] ?? '';
const container = containers.get(id);
if (url.pathname === '/info') return send(200, { DefaultRuntime: 'runsc' });
if (url.pathname === '/containers/json') {
return send(
200,
[...containers].map(([Id, c]) => ({ Id, State: c.status, Labels: c.labels })),
);
}
if (url.pathname === '/containers/create') {
const created = String(containers.size).padStart(12, 'c');
containers.set(created, { labels: { [SANDBOX_LABEL]: '1' }, status: 'created' });
return send(201, { Id: created });
}
if (!container) return send(404, { message: 'no such container' });
if (url.pathname.endsWith('/json')) {
return send(200, { Id: id, State: { Status: container.status }, Config: { Labels: container.labels } });
}
if (url.pathname.endsWith('/start')) {
container.status = 'running';
return send(204);
}
if (url.pathname.endsWith('/resize')) return send(200);
if (req.method === 'DELETE') {
containers.delete(id);
return send(204);
}
send(404, { message: 'unexpected call' });
});
server.on('upgrade', (req: IncomingMessage, socket: Socket) => {
calls.push({ method: req.method!, path: new URL(req.url!, 'http://docker').pathname });
socket.write('HTTP/1.1 101 UPGRADED\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n');
socket.on('data', (data) => socket.write(data.toString().toUpperCase()));
});
return new Promise((resolve) => server.listen(socketPath, () => resolve(server)));
}
function read(socket: Socket): Promise<string> {
return new Promise((resolve) => {
socket.once('data', (data) => resolve(data.toString()));
socket.resume();
});
}
describe('spawner server', () => {
let dir: string;
let docker: HttpServer;
let spawner: Server;
let client: SpawnerClient;
let calls: Call[];
let config: SpawnerConfig;
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), 'spawner-test-'));
calls = [];
docker = await fakeDocker(join(dir, 'docker.sock'), calls);
config = {
dockerSocket: join(dir, 'docker.sock'),
listenSocket: join(dir, 'spawner.sock'),
image: 'sandbox@sha256:abc',
contentDir: '/srv/content',
statusDir: '/srv/status',
maxSandboxes: 2,
allowNonGvisor: false,
};
spawner = createSpawnerServer(new SandboxManager(config), () => {});
await new Promise<void>((resolve) => spawner.listen(config.listenSocket, resolve));
client = new SpawnerClient(config.listenSocket);
});
afterEach(() => {
spawner.close();
docker.close();
rmSync(dir, { recursive: true, force: true });
});
it('creates a sandbox with the hardcoded spec', async () => {
const containerId = await client.spawn('session123', Math.floor(Date.now() / 1000) + 600);
expect(containerId).toBe('ccccccccccc2');
const create = calls.find((call) => call.path === '/containers/create');
expect(create?.body).toMatchObject({ Image: 'sandbox@sha256:abc', HostConfig: { NetworkMode: 'none' } });
});
it('refuses to spawn beyond the sandbox limit', async () => {
const expiresAt = Math.floor(Date.now() / 1000) + 600;
await client.spawn('session123', expiresAt);
await expect(client.spawn('session456', expiresAt)).rejects.toThrow('sandbox limit reached');
});
it('attaches before starting and bridges the stream', async () => {
const stream = await client.attach(MANAGED);
const paths = calls.map((call) => call.path);
expect(paths.indexOf(`/containers/${MANAGED}/attach`)).toBeLessThan(paths.indexOf(`/containers/${MANAGED}/start`));
stream.write('hello');
expect(await read(stream)).toBe('HELLO');
stream.destroy();
});
it('refuses containers it does not manage', async () => {
await expect(client.attach(FOREIGN)).rejects.toThrow('not a sandbox container');
await expect(client.kill(FOREIGN)).rejects.toThrow('not a sandbox container');
expect(calls.some((call) => call.method === 'DELETE')).toBe(false);
});
it('kills managed containers and tolerates missing ones', async () => {
await client.kill(MANAGED);
await client.kill('dddddddddddd');
expect(calls.filter((call) => call.method === 'DELETE').map((call) => call.path)).toEqual([
`/containers/${MANAGED}`,
]);
});
it('lists only managed containers', async () => {
expect(await client.list()).toEqual([{ containerId: MANAGED, sessionId: '', running: false }]);
});
it('answers invalid requests with an error', async () => {
await expect(client.resize('../../info', 80, 24)).rejects.toThrow(SpawnerError);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { createServer, type Server, type Socket } from 'node:net';
import {
InvalidRequestError,
MAX_REQUEST_BYTES,
parseRequest,
readLine,
type SpawnerResponse,
} from '@homepage/protocol';
import type { SandboxManager } from './sandbox.ts';
export type Logger = (message: string) => void;
function respond(connection: Socket, response: SpawnerResponse): void {
connection.write(`${JSON.stringify(response)}\n`);
}
function bridge(connection: Socket, upstream: Socket, rest: Buffer): void
{
const close = () => {
connection.destroy();
upstream.destroy();
};
connection.on('close', close);
upstream.on('close', close);
connection.on('error', close);
upstream.on('error', close);
if (rest.length > 0) upstream.write(rest);
connection.pipe(upstream);
upstream.pipe(connection);
}
async function handle(connection: Socket, manager: SandboxManager, log: Logger): Promise<void>
{
const { line, rest } = await readLine(connection, MAX_REQUEST_BYTES);
const request = parseRequest(line);
switch (request.op)
{
case 'spawn': {
const containerId = await manager.spawn(request.sessionId, request.expiresAt);
log(`spawned ${containerId.slice(0, 12)} for session ${request.sessionId}`);
respond(connection, { ok: true, containerId });
break;
}
case 'attach': {
const upstream = await manager.attach(request.containerId);
respond(connection, { ok: true });
bridge(connection, upstream, rest);
return;
}
case 'resize':
await manager.resize(request.containerId, request.cols, request.rows);
respond(connection, { ok: true });
break;
case 'kill':
await manager.kill(request.containerId);
log(`killed ${request.containerId.slice(0, 12)}`);
respond(connection, { ok: true });
break;
case 'list':
respond(connection, { ok: true, containers: await manager.list() });
break;
}
connection.end();
}
export function createSpawnerServer(manager: SandboxManager, log: Logger): Server
{
return createServer((connection) =>
{
connection.on('error', () => connection.destroy());
handle(connection, manager, log).catch((error: unknown) =>
{
const message = error instanceof Error ? error.message : 'internal error';
if (!(error instanceof InvalidRequestError)) log(`request failed: ${message}`);
if (!connection.destroyed) {
respond(connection, { ok: false, error: message });
connection.end();
}
});
});
}