/** Synthetic Docker HTTP only. No daemon, socket, network or container actions. */ import { test, mock } from "node:test" import assert from "node:assert/strict" import { EventEmitter } from "node:events" import { PassThrough } from "node:stream" import http from "node:http" import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto" import { performance } from "node:perf_hooks" import { lstat, mkdtemp, realpath, rm, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { basename, dirname, join } from "node:path" import { canonicalBandwidthNodeValue as canonical } from "./bandwidth-node-bootstrap.js" import type { BandwidthOperatorOriginalAuthoritySnapshot } from "./bandwidth-operator-writer-window.js" import { createBandwidthOperatorOriginalAuthorityReader } from "./bandwidth-operator-writer-window.js" import { bandwidthOperatorEnrollmentGrantSchema } from "./bandwidth-operator-enrollment.js" import { createDockerBandwidthOperatorStopAdapter, createDockerBandwidthOperatorWriterComposition, type DockerBandwidthOperatorWriterCompositionDependencies } from "./bandwidth-operator-docker-stop.js" const sha = (data: string | Buffer) => createHash("sha256").update(data).digest("hex") const installationId = "00000000-0000-4000-8000-000000000001" const { publicKey, privateKey } = generateKeyPairSync("ed25519") const ids = ["a".repeat(64), "b".repeat(64), "c".repeat(64)] function fixture(members = [ { service: "backend", role: "backend" }, { service: "updater", role: "updater" }, { service: "proxy", role: "unrelated" }, ]) { const ids = members.map((_member, index) => String.fromCharCode(97 + index).repeat(64)) const now = Date.now() const policy = { format: "mmapp-bandwidth-docker-only-quiescence-v1", installationId, daemonId: "owned-daemon", socketPath: "/var/run/docker.sock", automaticExecutorScope: "complete-docker-only-inventory", outsideAutomaticControllers: "none-operator-asserted", administratorBoundary: "trusted-no-manual-start-create-or-policy-change-during-window", socketAliases: ["/var/run/docker.sock", "/run/docker.sock"], containers: ids.map((containerId, index) => ({ containerId, imageId: "sha256:" + String(index + 1).repeat(64), project: "owned-project", service: members[index].service, role: members[index].role })), sourceArtifacts: [{ name: "owned-compose-fixture", sha256: sha("fixture compose source") }], } function signedConfig() { const bytes = canonical(policy) return { socketPath: policy.socketPath, daemonId: policy.daemonId, inventoryCanonicalJson: bytes, inventorySignatureBase64url: sign(null, Buffer.from(bytes), privateKey).toString("base64url"), inventoryPublicKeyPem: publicKey.export({ format: "pem", type: "spki" }).toString(), inventoryPublicKeySha256: sha(publicKey.export({ format: "der", type: "spki" })) } } const original = Object.freeze({ grant: Object.freeze({ executorInventorySha256: sha(canonical(policy)), installationId, executorsStoppedAt: now - 1000, issuedAt: now - 500, expiresAt: now + 4500 }), proof: "f".repeat(64), end: performance.now() + 4500 }) as unknown as BandwidthOperatorOriginalAuthoritySnapshot const inspect = new Map(ids.map((Id, index) => [Id, { Id, Image: policy.containers[index].imageId, Config: { Labels: { "com.docker.compose.project": "owned-project", "com.docker.compose.service": policy.containers[index].service }, Env: ["SECRET=never print this"] }, HostConfig: { RestartPolicy: { Name: "no", MaximumRetryCount: 0 }, Privileged: false, PidMode: "" }, State: { Running: false, Restarting: false, Paused: false, Dead: false, Pid: 0, Status: "exited", FinishedAt: new Date(now - 2000).toISOString() }, Mounts: members[index].role === "updater" ? [{ Type: "bind", Source: "/var/run/docker.sock", Destination: "/var/run/docker.sock", RW: true }] : [], }])) let calls = 0, destroyed = 0, swarm = "inactive", daemon = "owned-daemon" let listed = [...ids], before: ((path: string, count: number) => void) | undefined let payload: string | undefined, hang = false const requests: http.RequestOptions[] = [] const transport = mock.method(http, "request", ((options: http.RequestOptions, callback: (value: unknown) => void) => { calls++; const path = String(options.path); requests.push(options); before?.(path, calls) assert.equal(options.method, "GET"); assert.equal(options.socketPath, "/var/run/docker.sock"); assert.equal(options.agent, false) assert.equal(options.hostname, undefined); assert.equal(options.port, undefined) assert(/^\/v1\.45\/(info|containers\/json\?all=1&size=0|containers\/[a-f0-9]{64}\/json)$/.test(path)) const request = Object.assign(new EventEmitter(), { destroy() { destroyed++ }, end() { if (hang) return queueMicrotask(() => { const response = Object.assign(new PassThrough(), { statusCode: 200, headers: { "content-type": "application/json" }, complete: true }) callback(response) const value = path === "/v1.45/info" ? { ID: daemon, Swarm: { LocalNodeState: swarm } } : path.includes("?all=") ? listed.map(Id => ({ Id })) : inspect.get(path.split("/")[3]) response.end(payload ?? JSON.stringify(value)) }) } }) return request }) as typeof http.request) return { policy, original, inspect, signedConfig, requests, adapter: () => createDockerBandwidthOperatorStopAdapter(signedConfig()), scope: () => ({ deadlineAt: Date.now() + 4000 }), get calls() { return calls }, get destroyed() { return destroyed }, set before(value: typeof before) { before = value }, set swarm(value: string) { swarm = value }, set daemon(value: string) { daemon = value }, set listed(value: string[]) { listed = value }, set payload(value: string) { payload = value }, set hang(value: boolean) { hang = value }, close() { transport.mock.restore() }, } } async function refused(work: () => unknown) { await assert.rejects(async () => work(), (error: unknown) => { assert.equal((error as { code: string }).code, "BANDWIDTH_OPERATOR_WRITER_FENCE_REFUSED") assert(!String(error).includes("SECRET")); return true }) } test("inert constructor; immutable authenticated policy; GET-only opaque held reinspection", async () => { const f = fixture() try { const config = f.signedConfig(), adapter = createDockerBandwidthOperatorStopAdapter(config) assert.equal(f.calls, 0) config.socketPath = "/other.sock"; config.daemonId = "evil"; config.inventoryCanonicalJson = "{}" const held = await adapter.acquire(f.original, f.scope()) assert.equal(f.calls, 10); assert.deepEqual(Object.keys(held).sort(), ["assertCurrent", "close"]) await held.assertCurrent(f.original, f.scope()); assert.equal(f.calls, 20) held.close(); await refused(() => held.assertCurrent(f.original, f.scope())); assert.equal(f.calls, 20) } finally { f.close() } }) test("actual stand shape: frontend/backend/portal/postgres, no updater; unrelated services remain running", async () => { const f = fixture([{ service: "frontend", role: "unrelated" }, { service: "backend", role: "backend" }, { service: "portal", role: "unrelated" }, { service: "postgres", role: "unrelated" }]) try { for (const item of f.policy.containers) { const live = f.inspect.get(item.containerId)! if (item.role === "unrelated") { live.State.Running = true; live.State.Status = "running"; live.State.Pid = 123; live.HostConfig.RestartPolicy.Name = "unless-stopped" } } const held = await f.adapter().acquire(f.original, f.scope()) assert.equal(f.calls, 12); await held.assertCurrent(f.original, f.scope()); assert.equal(f.calls, 24); held.close() } finally { f.close() } }) test("genuine signed original grant distinguishes tmpfs from host binds and malformed mounts", async t => { const f = fixture(), directory = await mkdtemp(join(tmpdir(), "bw-tmpfs-grant-")) const trustKeyFile = join(directory,"operator.pub"), grantFile = join(directory,"operator.json"), now = Date.now() const root = { installationId, issuerKeySha256:"7".repeat(64), quiescenceProof:"8".repeat(64) } const grant = bandwidthOperatorEnrollmentGrantSchema.parse({ format:"mmapp-bandwidth-operator-enrollment-v1", ...root, grantId:randomUUID(), operatorId:"owned-mount-schema-unit", executorInventorySha256:sha(canonical(f.policy)), executorsStoppedAt:f.original.grant.executorsStoppedAt, issuedAt:now, expiresAt:now+120000, peerRef:{kind:"external",enrollmentId:randomUUID()}, sourceProof:"9".repeat(64), authorityGeneration:"owned-local", routingEndpointEpoch:randomUUID(), claims:[{kind:"system-id",value:"OWNED-TMPFS-SCHEMA"}] }) const payload = Buffer.from(canonical(grant)) await writeFile(trustKeyFile,publicKey.export({type:"spki",format:"pem"})) await writeFile(grantFile,JSON.stringify({format:"mmapp-bandwidth-operator-enrollment-envelope-v1",payload:payload.toString("base64url"),signature:sign(null,payload,privateKey).toString("base64url")})) const originals = createBandwidthOperatorOriginalAuthorityReader({...root,trustKeyFile,grantFile,trustKeySha256:sha(publicKey.export({type:"spki",format:"der"}))}) const unrelated = f.inspect.get(ids[2])! unrelated.State.Running=true;unrelated.State.Status="running";unrelated.State.Pid=321;unrelated.HostConfig.RestartPolicy.Name="unless-stopped" const setMounts = (mounts:unknown[]) => { (unrelated as {Mounts:unknown[]}).Mounts=mounts } const original = async () => originals.inspect(await originals.acquire(f.scope()),f.scope()) try { for (const [name,mount] of [ ["empty-source",{Type:"tmpfs",Source:"",Destination:"/var/lib/postgresql/data"}], ["omitted-source",{Type:"tmpfs",Destination:"/var/lib/postgresql/data"}], ["virtual-socket-name",{Type:"tmpfs",Source:"",Destination:"/var/run/docker.sock"}], ] as const) await t.test("recognized tmpfs "+name,async()=>{ setMounts([mount]);const held=await f.adapter().acquire(await original(),f.scope());held.close() }) for (const [name,mount] of [ ["empty-bind",{Type:"bind",Source:"",Destination:"/safe"}], ["empty-volume",{Type:"volume",Source:"",Destination:"/safe"}], ["host-root-bind",{Type:"bind",Source:"/",Destination:"/root"}], ["host-parent-bind",{Type:"bind",Source:"/run",Destination:"/host-run"}], ["unknown-type",{Type:"unknown",Source:"/safe",Destination:"/safe"}], ["missing-type",{Source:"/safe",Destination:"/safe"}], ["null-tmpfs-source",{Type:"tmpfs",Source:null,Destination:"/safe"}], ["nonempty-tmpfs-source",{Type:"tmpfs",Source:"/host",Destination:"/safe"}], ["relative-tmpfs-destination",{Type:"tmpfs",Destination:"relative"}], ["noncanonical-tmpfs-destination",{Type:"tmpfs",Destination:"/a/../safe"}], ["relative-bind-source",{Type:"bind",Source:"relative",Destination:"/safe"}], ] as const) await t.test("refuses "+name,async()=>{ setMounts([mount]);await refused(async()=>f.adapter().acquire(await original(),f.scope())) }) await t.test("all mounts validated after a dangerous bind on stopped protected executor",async()=>{ setMounts([]) ;(f.inspect.get(ids[0])! as {Mounts:unknown[]}).Mounts=[{Type:"bind",Source:"/run/docker.sock",Destination:"/socket"},{Type:"unknown",Source:"/safe",Destination:"/safe"}] await refused(async()=>f.adapter().acquire(await original(),f.scope())) }) } finally { originals.close();f.close() const actual=await realpath(directory), parent=await realpath(tmpdir()), info=await lstat(directory) assert(info.isDirectory()&&!info.isSymbolicLink());assert.equal(dirname(actual),parent);assert.match(basename(actual),/^bw-tmpfs-grant-[A-Za-z0-9]+$/) await rm(actual,{recursive:true,force:true}) } }) test("multiple backend replicas all require stopped state and disabled restart, with optional updater", async () => { for (const updater of [false, true]) { const members = [{ service: "backend", role: "backend" }, { service: "backend", role: "backend" }, ...(updater ? [{ service: "updater", role: "updater" }] : [])] const f = fixture(members) try { const held = await f.adapter().acquire(f.original, f.scope()); held.close() f.inspect.get(ids[1])!.State.Running = true await refused(() => f.adapter().acquire(f.original, f.scope())) f.inspect.get(ids[1])!.State.Running = false; f.inspect.get(ids[1])!.HostConfig.RestartPolicy.Name = "always" await refused(() => f.adapter().acquire(f.original, f.scope())) } finally { f.close() } } }) test("backend-only complete inventory is valid; no backend and empty inventory refuse before I/O", async () => { const f = fixture([{ service: "backend", role: "backend" }]) try { const held = await f.adapter().acquire(f.original, f.scope()); assert.equal(f.calls, 6); held.close() } finally { f.close() } for (const members of [[], [{ service: "frontend", role: "unrelated" }]]) { const g = fixture(members) try { assert.throws(() => g.adapter()); assert.equal(g.calls, 0) } finally { g.close() } } }) test("signature/policy/inventory binding refuses before any Docker request", async () => { const f = fixture() try { const config = f.signedConfig(); config.inventorySignatureBase64url = "a".repeat(86) assert.throws(() => createDockerBandwidthOperatorStopAdapter(config)) ;(f.policy as Record).outsideAutomaticControllers = "host-supervisor" assert.throws(() => f.adapter()); assert.equal(f.calls, 0) } finally { f.close() } const g = fixture() try { await refused(() => g.adapter().acquire({ ...g.original, grant: { ...g.original.grant, executorInventorySha256: "0".repeat(64) } }, g.scope())); assert.equal(g.calls, 0) } finally { g.close() } }) for (const change of ["running", "restart", "image", "labels", "late-exit", "socket-ro", "socket-parent", "privileged", "remote-docker", "unknown", "missing", "daemon", "swarm"] as const) { test(`live API refuses ${change}`, async () => { const f = fixture() try { const backend = f.inspect.get(ids[0])!, unrelated = f.inspect.get(ids[2])! if (change === "running") backend.State.Running = true if (change === "restart") f.inspect.get(ids[1])!.HostConfig.RestartPolicy.Name = "unless-stopped" if (change === "image") backend.Image = "sha256:" + "f".repeat(64) if (change === "labels") backend.Config.Labels["com.docker.compose.project"] = "other-project" if (change === "late-exit") backend.State.FinishedAt = new Date().toISOString() if (change === "socket-ro") unrelated.Mounts = [{ Type: "bind", Source: "/var/run/docker.sock", Destination: "/socket", RW: false }] if (change === "socket-parent") unrelated.Mounts = [{ Type: "bind", Source: "/run", Destination: "/host-run", RW: false }] if (change === "privileged") unrelated.HostConfig.Privileged = true if (change === "remote-docker") unrelated.Config.Env.push("DOCKER_HOST=tcp://controller:2375") if (change === "unknown") f.listed = [...ids, "d".repeat(64)] if (change === "missing") f.listed = ids.slice(0, 2) if (change === "daemon") f.daemon = "other-daemon" if (change === "swarm") f.swarm = "active" await refused(() => f.adapter().acquire(f.original, f.scope())) } finally { f.close() } }) } test("second inspect catches reactivation during scan; held failure terminal", async () => { const f = fixture() try { const held = await f.adapter().acquire(f.original, f.scope()) f.before = (_path, count) => { if (count === 16) f.inspect.get(ids[0])!.State.Restarting = true } await refused(() => held.assertCurrent(f.original, f.scope())) const count = f.calls; f.inspect.get(ids[0])!.State.Restarting = false await refused(() => held.assertCurrent(f.original, f.scope())); assert.equal(f.calls, count) } finally { f.close() } }) test("original cancellation and monotonic horizon cannot be replaced", async () => { const f = fixture() try { const controller = new AbortController(), original = Object.freeze({ ...f.original, signal: controller.signal }) const held = await f.adapter().acquire(original, f.scope()); controller.abort() await refused(() => held.assertCurrent(original, f.scope())); assert.equal(f.calls, 10) await refused(() => f.adapter().acquire({ ...f.original, end: performance.now() - 1 }, f.scope())); assert.equal(f.calls, 10) } finally { f.close() } }) test("trailing daemon/list checks refuse state replacement after inspections", async () => { for (const change of ["daemon", "inventory"] as const) { const f = fixture() try { f.before = (path, count) => { if (change === "daemon" && path === "/v1.45/info" && count === 10) f.daemon = "replacement" if (change === "inventory" && count === 9) f.listed = [...ids, "d".repeat(64)] } await refused(() => f.adapter().acquire(f.original, f.scope())) } finally { f.close() } } }) test("original replacement refuses and closing aborts an in-flight assert", async () => { const f = fixture() try { const held = await f.adapter().acquire(f.original, f.scope()) await refused(() => held.assertCurrent({ ...f.original }, f.scope())); assert.equal(f.calls, 10) const another = await f.adapter().acquire(f.original, f.scope()) f.hang = true const pending = another.assertCurrent(f.original, f.scope()) another.close(); await refused(() => pending); assert(f.destroyed > 0) } finally { f.close() } }) test("bounded malformed/oversize JSON and in-flight timeout/cancellation refuse", async () => { for (const payload of ["{", "x".repeat(2 * 1024 * 1024 + 1)]) { const f = fixture() try { f.payload = payload; await refused(() => f.adapter().acquire(f.original, f.scope())) } finally { f.close() } } const g = fixture() try { g.hang = true; await refused(() => g.adapter().acquire(g.original, { deadlineAt: Date.now() + 30 })); assert(g.destroyed > 0) const controller = new AbortController() const pending = g.adapter().acquire(g.original, { ...g.scope(), signal: controller.signal }); controller.abort() await refused(() => pending); assert(g.destroyed > 1) } finally { g.close() } }) for (const prepared of [false, true]) { test(`concrete Docker composition ${prepared ? "verifies live stop before source lease" : "refuses live stop failure before source lease"}`, async () => { const f = fixture(), directory = await mkdtemp(join(tmpdir(), "docker-operator-composition-")) let leases = 0, credentials = 0 let composition: ReturnType | undefined try { const trustKeyFile = join(directory, "operator.pub"), grantFile = join(directory, "grant.json") const config = { trustKeyFile, grantFile, trustKeySha256: sha(publicKey.export({ format: "der", type: "spki" })), installationId, issuerKeySha256: "a".repeat(64), quiescenceProof: "b".repeat(64) } const grant = { ...f.original.grant, format: "mmapp-bandwidth-operator-enrollment-v1", grantId: "00000000-0000-4000-8000-000000000002", operatorId: "owned-docker-composition-fixture", issuerKeySha256: config.issuerKeySha256, quiescenceProof: config.quiescenceProof, peerRef: { kind: "external", enrollmentId: "00000000-0000-4000-8000-000000000003" }, sourceProof: "d".repeat(64), authorityGeneration: "owned-fixture", routingEndpointEpoch: "00000000-0000-4000-8000-000000000004", claims: [{ kind: "system-id", value: "owned-synthetic-system" }] } const payload = Buffer.from(canonical(grant)) await writeFile(trustKeyFile, publicKey.export({ format: "pem", type: "spki" })) await writeFile(grantFile, JSON.stringify({ format: "mmapp-bandwidth-operator-enrollment-envelope-v1", payload: payload.toString("base64url"), signature: sign(null, payload, privateKey).toString("base64url") })) const refuseLease = async () => { leases++; assert(f.calls >= 20); throw Error("synthetic source boundary reached; no DB") } const nodeSource = { open: refuseLease, openWithOwnershipFence: refuseLease } as unknown as DockerBandwidthOperatorWriterCompositionDependencies["nodeSource"] if (!prepared) f.daemon = "wrong-live-daemon" composition = createDockerBandwidthOperatorWriterComposition({ config, nodeSource, observationSource: { async read() { credentials++; throw Error("must not resolve credentials") } }, docker: f.signedConfig() }) assert.equal(f.calls, 0); assert.equal(leases, 0) await refused(() => composition!.register(f.scope())) assert.equal(leases, prepared ? 1 : 0); assert.equal(credentials, 0) assert.equal(f.calls, prepared ? 20 : 1) composition.close() await refused(() => composition!.register(f.scope())) assert.equal(f.calls, prepared ? 20 : 1) } finally { composition?.close(); f.close(); await rm(directory, { recursive: true, force: true }) } }) }