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

+9
View File
@@ -0,0 +1,9 @@
.git
.gitea
.idea
.tools
**/node_modules
**/dist
runtime
sandbox
deploy
+28
View File
@@ -9,6 +9,17 @@ env:
REGISTRY: git.security-command.org/securitycommand
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: corepack pnpm install --frozen-lockfile
- run: corepack pnpm typecheck
- run: corepack pnpm test
sandbox:
runs-on: ubuntu-latest
steps:
@@ -24,3 +35,20 @@ jobs:
image="$REGISTRY/homepage-sandbox"
docker build -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" sandbox/
docker push --all-tags "$image"
spawner:
needs: check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Log in to the registry
run: >
echo "${{ secrets.REGISTRY_TOKEN }}"
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
- name: Build and push
run: |
image="$REGISTRY/homepage-spawner"
docker build -f apps/spawner/Dockerfile -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" .
docker push --all-tags "$image"
+3
View File
@@ -1,8 +1,11 @@
# ---> Strict
.*
!.git*
!.dockerignore
*.md
!README.md
/runtime/
node_modules/
dist/
+11
View File
@@ -0,0 +1,11 @@
# Build context is the repository root.
FROM node:24-alpine AS build
WORKDIR /src
COPY . .
RUN corepack pnpm install --frozen-lockfile \
&& corepack pnpm --filter @homepage/spawner build
FROM node:24-alpine
COPY --from=build /src/apps/spawner/dist/spawner.js /app/spawner.js
USER 10001:10100
CMD ["node", "/app/spawner.js"]
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@homepage/spawner",
"private": true,
"type": "module",
"scripts": {
"build": "esbuild src/main.ts --bundle --platform=node --target=node24 --format=esm --outfile=dist/spawner.js"
},
"dependencies": {
"@homepage/protocol": "workspace:*"
}
}
+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();
}
});
});
}
+16 -4
View File
@@ -73,15 +73,27 @@ pull_image() {
commit=$(as_owner git rev-parse HEAD)
sandbox_tag="${REGISTRY}/homepage-sandbox:${commit}"
spawner_tag="${REGISTRY}/homepage-spawner:${commit}"
pull_image sandbox_docker "$sandbox_tag"
sandbox_image=$(sandbox_docker image inspect --format '{{index .RepoDigests 0}}' "$sandbox_tag")
pull_image docker "$spawner_tag"
digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; }
install -d -m 0755 runtime
# The spawner runs as 10001 and shares group 10100 with the backend.
install -d -m 0755 runtime runtime/status
install -d -o 10001 -g 10100 -m 0750 runtime/spawner
cat > runtime/deploy.env <<EOF
SANDBOX_IMAGE=${sandbox_image}
SANDBOX_IMAGE=$(digest sandbox_docker "$sandbox_tag")
SPAWNER_IMAGE=$(digest docker "$spawner_tag")
SANDBOX_GROUP_ID=$(getent group sandbox-spawner | cut -d: -f3)
STATUS_DIR=${PWD}/runtime/status
EOF
set -a
source runtime/deploy.env
set +a
IMAGE=$sandbox_image deploy/host/verify-sandbox.sh
IMAGE=$SANDBOX_IMAGE deploy/host/verify-sandbox.sh
docker compose --project-directory "$PWD" -f deploy/compose.yml \
--env-file .env --env-file runtime/deploy.env up -d --remove-orphans
echo "deployed ${commit}"
+28
View File
@@ -0,0 +1,28 @@
name: security-command
services:
spawner:
image: ${SPAWNER_IMAGE:?run deploy.sh}
restart: unless-stopped
# 10100 is the group shared with the backend for the spawner socket.
user: "10001:10100"
group_add:
- "${SANDBOX_GROUP_ID:?run deploy.sh}"
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
network_mode: none
mem_limit: 128m
pids_limit: 64
environment:
SANDBOX_IMAGE: ${SANDBOX_IMAGE:?run deploy.sh}
CONTENT_DIR: ${CONTENT_DIR:?set CONTENT_DIR in .env}
STATUS_DIR: ${STATUS_DIR:?run deploy.sh}
volumes:
- /run/docker-sandbox/docker.sock:/run/docker-sandbox/docker.sock
- ./runtime/spawner:/run/spawner
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
+20
View File
@@ -0,0 +1,20 @@
{
"name": "security-command.org",
"private": true,
"type": "module",
"packageManager": "pnpm@12.11.2",
"engines": {
"node": ">=24"
},
"scripts": {
"typecheck": "tsc -p .",
"test": "vitest run",
"build": "pnpm -r build"
},
"devDependencies": {
"@types/node": "^26.6.5",
"esbuild": "^0.28.2",
"typescript": "^7.0.2",
"vitest": "~5.0.3"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"name": "@homepage/protocol",
"private": true,
"type": "module",
"exports": "./src/index.ts"
}
+78
View File
@@ -0,0 +1,78 @@
import { connect, type Socket } from 'node:net';
import { readLine } from './lines.ts';
import type { ManagedContainer, SpawnerRequest, SpawnerResponse } from './spawner.ts';
const MAX_RESPONSE_BYTES = 1024 * 1024;
export class SpawnerError extends Error {}
// noinspection ExceptionCaughtLocallyJS
export class SpawnerClient
{
readonly socketPath: string;
constructor(socketPath: string) { this.socketPath = socketPath; }
async spawn(sessionId: string, expiresAt: number): Promise<string> {
const response = await this.request({ op: 'spawn', sessionId, expiresAt });
return response.containerId!;
}
/**
* Returns a raw duplex stream to the container's terminal. The container
* is started by the first attach, and the stream starts paused, so no early
* output gets lost before the caller pipes or resumes it.
*/
async attach(containerId: string): Promise<Socket> {
const { socket } = await this.open({ op: 'attach', containerId });
return socket;
}
async resize(containerId: string, cols: number, rows: number): Promise<void> {
await this.request({ op: 'resize', containerId, cols, rows });
}
async kill(containerId: string): Promise<void> {
await this.request({ op: 'kill', containerId });
}
async list(): Promise<ManagedContainer[]> {
const response = await this.request({ op: 'list' });
return response.containers ?? [];
}
private async request(request: SpawnerRequest): Promise<SpawnerResponse & { ok: true }> {
const { socket, response } = await this.open(request);
socket.destroy();
return response;
}
private open(request: SpawnerRequest): Promise<{ socket: Socket; response: SpawnerResponse & { ok: true } }>
{
return new Promise((resolve, reject) =>
{
const socket = connect(this.socketPath);
socket.once('error', reject);
socket.once('connect', async () =>
{
socket.off('error', reject);
try
{
socket.write(`${JSON.stringify(request)}\n`);
const { line, rest } = await readLine(socket, MAX_RESPONSE_BYTES, 30_000);
const response = JSON.parse(line) as SpawnerResponse;
if (!response.ok) throw new SpawnerError(response.error);
if (rest.length > 0) socket.unshift(rest);
resolve({ socket, response });
}
catch (error)
{
socket.destroy();
reject(error);
}
});
});
}
}
+3
View File
@@ -0,0 +1,3 @@
export * from './spawner.ts';
export * from './lines.ts';
export * from './client.ts';
+54
View File
@@ -0,0 +1,54 @@
import type { Socket } from 'node:net';
export type Line = {
line: string;
/** Bytes received after the newline, which belong to the following stream. */
rest: Buffer;
};
export function readLine(socket: Socket, maxBytes: number, timeoutMs = 5000): Promise<Line> {
return new Promise((resolve, reject) =>
{
let buffered = Buffer.alloc(0);
const finish = (error: Error | null, result?: Line) =>
{
clearTimeout(timer);
socket.off('data', onData);
socket.off('end', onEnd);
socket.off('error', onError);
if (error) reject(error);
else resolve(result!);
};
const onData = (chunk: Buffer) =>
{
buffered = Buffer.concat([buffered, chunk]);
const newline = buffered.indexOf(0x0a);
if (newline === -1) {
if (buffered.length > maxBytes) finish(new Error('line too long'));
return;
}
if (newline > maxBytes) {
finish(new Error('line too long'));
return;
}
socket.pause();
finish(null, { line: buffered.subarray(0, newline).toString('utf8'), rest: buffered.subarray(newline + 1) });
};
const onEnd = () => finish(new Error('connection closed before a full line arrived'));
const onError = (error: Error) => finish(error);
const timer = setTimeout(() => finish(new Error('timed out waiting for a line')), timeoutMs);
socket.on('data', onData);
socket.once('end', onEnd);
socket.once('error', onError);
socket.resume();
});
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import { InvalidRequestError, MAX_SESSION_SECONDS, parseRequest } from './spawner.ts';
const now = 1_800_000_000;
const parse = (value: unknown) => parseRequest(JSON.stringify(value), now);
describe('parseRequest', () => {
it('accepts a valid spawn', () => {
expect(parse({ op: 'spawn', sessionId: 'abcdEFGH_-12', expiresAt: now + 1200 })).toEqual({
op: 'spawn',
sessionId: 'abcdEFGH_-12',
expiresAt: now + 1200,
});
});
it.each([
['short id', { op: 'spawn', sessionId: 'abc', expiresAt: now + 60 }],
['id with shell characters', { op: 'spawn', sessionId: 'abcdefgh;rm', expiresAt: now + 60 }],
['expiry in the past', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now }],
['expiry too far ahead', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + MAX_SESSION_SECONDS + 1 }],
['fractional expiry', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + 1.5 }],
['uppercase container id', { op: 'kill', containerId: 'ABCDEF123456' }],
['container id with path', { op: 'attach', containerId: '../../info' }],
['unknown op', { op: 'exec', containerId: 'abcdef123456' }],
['array', [{ op: 'list' }]],
['null', null],
])('rejects %s', (_name, value) => {
expect(() => parse(value)).toThrow(InvalidRequestError);
});
it('rejects malformed json', () => {
expect(() => parseRequest('{"op":', now)).toThrow(InvalidRequestError);
});
it('ignores inherited properties', () => {
expect(() => parseRequest('{"__proto__":{"op":"list"}}', now)).toThrow(InvalidRequestError);
});
it('clamps the terminal size', () => {
expect(parse({ op: 'resize', containerId: 'abcdef123456', cols: 9999, rows: 0 })).toEqual({
op: 'resize',
containerId: 'abcdef123456',
cols: 500,
rows: 1,
});
});
it('rejects a non integer terminal size', () => {
expect(() => parse({ op: 'resize', containerId: 'abcdef123456', cols: '80', rows: 24 })).toThrow(
InvalidRequestError,
);
});
});
+99
View File
@@ -0,0 +1,99 @@
export const SANDBOX_LABEL = 'org.security-command.sandbox';
export const SESSION_LABEL = 'org.security-command.session';
export const MAX_REQUEST_BYTES = 4096;
export const MAX_SESSION_SECONDS = 6 * 60 * 60;
export const MAX_TERMINAL_SIZE = 500;
export type SpawnerRequest =
| { op: 'spawn'; sessionId: string; expiresAt: number }
| { op: 'attach'; containerId: string }
| { op: 'resize'; containerId: string; cols: number; rows: number }
| { op: 'kill'; containerId: string }
| { op: 'list' };
export type ManagedContainer = {
containerId: string;
sessionId: string;
running: boolean;
};
export type SpawnerResponse =
| { ok: true; containerId?: string; containers?: ManagedContainer[] }
| { ok: false; error: string };
const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
const CONTAINER_ID = /^[0-9a-f]{12,64}$/;
export class InvalidRequestError extends Error {}
function invalid(message: string): never {
throw new InvalidRequestError(message);
}
function field(input: Record<string, unknown>, name: string): unknown {
return Object.hasOwn(input, name) ? input[name] : undefined;
}
function sessionId(value: unknown): string {
return typeof value === 'string' && SESSION_ID.test(value) ? value : invalid('invalid session id');
}
function containerId(value: unknown): string {
return typeof value === 'string' && CONTAINER_ID.test(value) ? value : invalid('invalid container id');
}
function terminalSize(value: unknown): number {
if (typeof value !== 'number' || !Number.isInteger(value)) invalid('invalid terminal size');
return Math.min(Math.max(value, 1), MAX_TERMINAL_SIZE);
}
/**
* Parses one request line. Everything the backend sends is treated as
* untrusted, because the backend faces the internet and may be compromised.
*/
export function parseRequest(line: string, nowSeconds = Math.floor(Date.now() / 1000)): SpawnerRequest
{
let input: unknown;
try { input = JSON.parse(line); }
catch { invalid('malformed json'); }
if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('request must be an object');
const request = input as Record<string, unknown>;
switch (field(request, 'op'))
{
case 'spawn': {
const expiresAt = field(request, 'expiresAt');
if (
typeof expiresAt !== 'number' ||
!Number.isInteger(expiresAt) ||
expiresAt <= nowSeconds ||
expiresAt > nowSeconds + MAX_SESSION_SECONDS
) { invalid('invalid expiry'); }
return { op: 'spawn', sessionId: sessionId(field(request, 'sessionId')), expiresAt };
}
case 'attach':
return { op: 'attach', containerId: containerId(field(request, 'containerId')) };
case 'resize':
return {
op: 'resize',
containerId: containerId(field(request, 'containerId')),
cols: terminalSize(field(request, 'cols')),
rows: terminalSize(field(request, 'rows')),
};
case 'kill':
return { op: 'kill', containerId: containerId(field(request, 'containerId')) };
case 'list':
return { op: 'list' };
default:
return invalid('unknown op');
}
}
+1296
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
packages:
- apps/*
- packages/*
allowBuilds:
esbuild: true
+4 -1
View File
@@ -13,9 +13,12 @@ RUN rm -f /etc/dpkg/dpkg.cfg.d/docker \
figlet cowsay fortune-mod fortunes-min sl curl wget \
&& rm -rf /var/lib/apt/lists/*
# The home directory stays empty, because Podman copies image content into
# tmpfs mounts and Docker does not. All shell configuration lives in /etc.
# Setuid binaries are useless under no-new-privileges, so they are stripped
# to keep the attack surface minimal even if that option is ever dropped.
RUN useradd --uid 1000 --create-home --shell /bin/bash guest \
RUN useradd --uid 1000 --no-create-home --home-dir /home/guest --shell /bin/bash guest \
&& mkdir /home/guest \
&& find / -xdev -perm /6000 -type f -exec chmod a-s {} +
COPY etc/ /etc/
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "es2024",
"module": "nodenext",
"moduleResolution": "nodenext",
"lib": ["es2024"],
"types": ["node"],
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["apps/*/src", "packages/*/src"]
}