Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Storage Node8 * File : server/test/e2e.ts9 * Description : End-to-end test of the coordinator against scripted MSP/110 * devices: a real coordinator process, real files, real11 * crypto. usage: node server/test/e2e.ts12 * Module : server13 * Repository : https://git.spboucher.ai/maclustr-storage-ios14 * Project Website : https://storage.spboucher.ai15 * Created : 2026-12-0116 * Last Modified : 2026-12-0117 *18 * Author : Simon-Pierre Boucher19 * Position : Professor of Finance20 * Institution : Université du Québec en Outaouais (UQO)21 * Organization : SP Boucher22 * Website : https://spboucher.ai23 * Git : https://git.spboucher.ai24 *25 * Preferred Contact: admin@spboucher.ai26 * Technical Contact: dev@spboucher.ai27 * Security/Admin : admin@spboucher.ai28 *29 * Copyright (c) 202630 * Simon-Pierre Boucher31 * All rights reserved where applicable. This file is governed by the32 * applicable project license, copyright notices and relevant law.33 * Existing third-party rights and notices remain unaffected.34 *35 * License : None specified (no license file in this repository)36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445import { spawn, type ChildProcess } from "node:child_process";46import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto";47import { mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";48import { tmpdir } from "node:os";49import { join, dirname } from "node:path";50import { fileURLToPath } from "node:url";51import { TestDevice } from "./device.ts";5253const root = mkdtempSync(join(tmpdir(), "msc-e2e-"));54const port = 18870 + Math.floor(Math.random() * 500);55const base = `http://127.0.0.1:${port}`;56const env = { ...process.env, MSC_DATA_DIR: join(root, "data"), MSC_SECRET_DIR: join(root, "secret"), MSC_PORT: String(port), MSC_LAN_PORT: "0", MSC_BONJOUR: "0",57 MSC_FRAGMENT_MIB: "4", MSC_TICK_MS: "150", MSC_OFFLINE_AFTER_S: "3", MSC_VERIFY_INTERVAL_S: "100000", MSC_MOBILE_REPLICAS: "3", MSC_HOST: "127.0.0.1" };58const main = join(dirname(fileURLToPath(import.meta.url)), "..", "src", "main.ts");59let proc: ChildProcess;60const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));61async function start() {62 proc = spawn(process.execPath, [main], { env, stdio: ["ignore", "ignore", "inherit"] });63 for (let i = 0; i < 100; i++) { try { if ((await fetch(base + "/healthz")).ok) return; } catch { /* not yet */ } await sleep(50); }64 throw new Error("coordinator did not start");65}66async function stop() { proc.kill("SIGTERM"); await new Promise(r => proc.once("exit", r)); }6768let passed = 0;69function check(cond: unknown, label: string) { if (!cond) { console.error("FAIL " + label); throw new Error(label); } passed++; console.log("ok " + label); }70let token = "";71async function admin(method: string, route: string, body?: unknown | Buffer): Promise<{ status: number; body: any; raw?: Buffer }> {72 const isBuf = Buffer.isBuffer(body);73 const r = await fetch(base + "/admin/v1/" + route, { method, headers: { Authorization: "Bearer " + token, ...(isBuf ? {} : { "Content-Type": "application/json" }) }, body: body === undefined ? undefined : isBuf ? body : JSON.stringify(body) });74 const raw = Buffer.from(await r.arrayBuffer());75 let parsed: any = null; try { parsed = JSON.parse(raw.toString()); } catch { /* binary */ }76 return { status: r.status, body: parsed, raw };77}78async function until(fn: () => Promise<boolean>, label: string, ms = 8000) { const t = Date.now(); while (Date.now() - t < ms) { if (await fn()) return; await sleep(100); } throw new Error("timeout: " + label); }79const sha = (b: Buffer) => createHash("sha256").update(b).digest("hex");80async function pump(devs: TestDevice[], rounds = 12) { for (let i = 0; i < rounds; i++) { for (const d of devs) { await d.heartbeat(); await d.work(); } await sleep(170); } }8182try {83 await start();84 token = readFileSync(join(root, "secret", "admin.token"), "utf8").trim();8586 // --- pairing87 check((await fetch(base + "/admin/v1/overview")).status === 401, "admin API refuses a request without token");88 const c1 = (await admin("POST", "pairing", { label: "A" })).body;89 check(/^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(c1.code) && c1.qr_payload.startsWith("msp1://pair?"), "pairing code and QR payload issued");90 const A = new TestDevice(base, "node-A"), B = new TestDevice(base, "node-B"), X = new TestDevice(base, "intruder");91 check((await X.pair("AAAA-BBBB-CCCC")).status === 403, "unknown pairing code refused");92 check((await A.pair(c1.code.toLowerCase().replace(/-/g, " "))).status === 200 && A.id.length === 24, "device A pairs (code typed by hand, any case and spacing)");93 check((await X.pair(c1.code)).status === 403, "pairing code is single use");94 const c2 = (await admin("POST", "pairing", { label: "revoked" })).body;95 check((await admin("DELETE", "pairing/" + c2.id)).body.revoked === true && (await X.pair(c2.code)).status === 403, "revoked pairing code refused");96 check((await B.pair((await admin("POST", "pairing", { label: "B" })).body.code)).status === 200, "device B pairs");9798 // --- request authentication99 const stale = await A.post("heartbeat", {}, { ts: Math.floor(Date.now() / 1000) - 4000 });100 check(stale.status === 401 && stale.body.error === "clock_skew", "stale timestamp refused");101 const nonce = randomBytes(12).toString("base64url");102 check((await A.post("inventory", { fragments: [] }, { nonce })).status === 200 && (await A.post("inventory", { fragments: [] }, { nonce })).body.error === "replayed_request", "replayed request refused");103 const other = generateKeyPairSync("ec", { namedCurve: "prime256v1" }).privateKey;104 check((await A.post("heartbeat", {}, { key: other })).body.error === "bad_signature", "request signed by another key refused");105 check((await X.post("heartbeat", {}, { device: "0".repeat(24) })).body.error === "unknown_device", "unknown device refused");106107 // --- capacity and placement108 A.quota = 64 * 2 ** 20; B.quota = 64 * 2 ** 20;109 await A.heartbeat(); await B.heartbeat();110 let ov = (await admin("GET", "overview")).body;111 check(ov.totals.nodes === 2 && ov.totals.capacity_registered === 128 * 2 ** 20 && ov.totals.nodes_online === 2, "cluster sees both nodes and their allocated capacity");112 const payload = randomBytes(18 * 2 ** 20 + 12345);113 const obj = (await admin("PUT", "objects?name=dataset.bin&class=dataset", payload)).body;114 check(obj.fragments === 5 && obj.sha256 === sha(payload), "object ingested as 5 encrypted fragments, digest matches");115 await A.heartbeat(); await sleep(400);116 const first = await A.work({ splitDownload: true });117 check(first.filter(t => t.op === "store").length > 0, "device A receives store tasks; interrupted download resumes with a Range request");118 await pump([A, B]);119 ov = (await admin("GET", "overview")).body;120 check(A.fragments.size === 5 && B.fragments.size === 5 && ov.totals.fragments_on_mobile === 10, "each fragment is stored on both mobile nodes");121 check(ov.totals.integrity_checks >= 10 && ov.totals.integrity_rate === 1, "every stored fragment passed its possession proof");122 check(ov.nodes[0].capacity.used === A.used() && ov.totals.redundant_fragments === 5, "dashboard figures equal what the device really holds");123 const detail = (await admin("GET", "nodes/" + A.id)).body;124 check(detail.transfers.some((t: any) => t.resumed_from > 0 && t.ok === 1), "resumed transfer recorded");125 const stored = [...A.fragments.values()][0];126 check(!payload.includes(stored.subarray(0, 64)) && payload.subarray(0, 4 * 2 ** 20).length + 16 === stored.length, "fragments on the device are ciphertext (plaintext + 16-byte tag), not the data");127128 // --- read back, deduplication129 const back = await admin("GET", `objects/${obj.id}/content`);130 check(back.status === 200 && sha(back.raw!) === obj.sha256, "object read back from the stable store, digest matches");131 const dup = (await admin("PUT", "objects?name=copy.bin", payload)).body;132 check(dup.new_fragments === 0 && dup.deduplicated === 5, "identical content is deduplicated (no new fragment)");133 check((await admin("DELETE", "objects/" + dup.id)).body.fragments_released === 0, "deleting the duplicate releases nothing");134135 // --- restitution from a device, with an interrupted upload136 const frag0 = (await admin("GET", "objects/" + obj.id)).body.fragments[0].fragment_id;137 await admin("POST", `nodes/${A.id}/retrieve`, { fragments: [frag0] });138 const rt = await A.work({ splitUpload: true });139 check(rt.find(t => t.op === "retrieve")?.uploadStatus === 200, "device returns a fragment; interrupted upload resumes at the server offset; digest verified");140141 // --- loss of the stable copy: recovery from a mobile node142 const fpath = join(root, "data", "fragments", frag0.slice(0, 2), frag0.slice(2, 4), frag0);143 unlinkSync(fpath);144 const gone = await admin("GET", `objects/${obj.id}/content`);145 check(gone.status === 503 && gone.body.fragments[0] === frag0, "missing stable copy detected on read");146 await pump([A, B], 6);147 const healed = await admin("GET", `objects/${obj.id}/content`);148 check(healed.status === 200 && sha(healed.raw!) === obj.sha256, "stable copy rebuilt from a mobile node, object readable again");149 writeFileSync(fpath, Buffer.concat([randomBytes(16), readFileSync(fpath).subarray(16)]));150 await until(async () => { await pump([A, B], 2); return (await admin("GET", "events?limit=50")).body.events.some((e: any) => e.kind === "stable.fragment.corrupt"); }, "scrub detects corruption", 20000);151 await pump([A, B], 6);152 check(sha(readFileSync(fpath)) === frag0, "corrupt stable copy detected by the scrub and rebuilt from a mobile node");153154 // --- corruption on a device155 const victim = [...A.fragments.keys()][1];156 A.fragments.set(victim, Buffer.concat([randomBytes(8), A.fragments.get(victim)!.subarray(8)]));157 await admin("POST", `nodes/${A.id}/verify`);158 await pump([A, B], 8);159 const ev = (await admin("GET", "events?limit=100")).body.events;160 check(ev.some((e: any) => e.kind === "integrity.failed" && e.detail.fragment === victim), "corrupted fragment on a device fails its possession proof");161 check(sha(A.fragments.get(victim)!) === victim, "device discarded the corrupt fragment and received a clean copy again");162163 // --- coordinator restart164 await stop(); await start();165 ov = (await admin("GET", "overview")).body;166 check(ov.totals.nodes === 2 && ov.stable.objects === 1, "state survives a coordinator restart");167 await pump([A, B], 3);168 check((await A.inventory()).body.delete.length === 0 && (await A.inventory()).body.missing === 0, "inventory reconciles after restart: nothing to delete, nothing missing");169 A.fragments.set("f".repeat(64), Buffer.from("orphan"));170 check((await A.inventory()).body.delete[0] === "f".repeat(64), "orphan fragment on the device is reported for deletion");171 A.fragments.delete("f".repeat(64));172173 // --- a node disappears: no data loss174 await sleep(4600); await A.heartbeat();175 ov = (await admin("GET", "overview")).body;176 const nb = ov.nodes.find((n: any) => n.id === B.id);177 if (!(!nb.online && ov.totals.capacity_offline === B.quota && ov.totals.capacity_accessible === A.quota)) console.error(JSON.stringify([nb.online, nb.health, ov.totals, ov.nodes.map((n: any) => [n.name, n.online, n.capacity.allocated])]));178 check(!nb.online && nb.health === "offline" && ov.totals.capacity_offline === B.quota && ov.totals.capacity_accessible === A.quota, "silent node B is offline; its capacity is counted as offline, not accessible");179 const still = await admin("GET", `objects/${obj.id}/content`);180 check(still.status === 200 && sha(still.raw!) === obj.sha256, "object fully readable while node B is gone");181182 // --- quota respected, quota lowered183 const C = new TestDevice(base, "node-C");184 await C.pair((await admin("POST", "pairing", {})).body.code);185 C.quota = 9 * 2 ** 20;186 await pump([A, C], 8);187 check(C.fragments.size === 2 && C.used() <= C.quota, "node C never receives more than its quota (2 fragments of 4 MiB under 9 MiB)");188 C.quota = 5 * 2 ** 20;189 await pump([A, C], 6);190 check(C.fragments.size === 1, "lowering the quota releases fragments down to the new limit");191 C.accepting = false; C.quota = 64 * 2 ** 20;192 await pump([A, C], 5);193 check(C.fragments.size === 1, "a node that does not accept writes (policy, heat, low space) receives nothing new");194195 // --- graceful drain, then removal196 check((await A.post("drain", { mode: "graceful", remove: false })).body.status === "draining", "drain requested from the device");197 await pump([A], 10);198 const na = (await admin("GET", "nodes/" + A.id)).body.node;199 check(A.fragments.size === 0 && na.status === "drained" && na.fragments === 0, "drain: every fragment confirmed on the stable store, then deleted from the device");200 const afterDrain = await admin("GET", `objects/${obj.id}/content`);201 check(afterDrain.status === 200 && sha(afterDrain.raw!) === obj.sha256, "object intact after the drain");202 check((await A.post("drain", { rejoin: true })).body.status === "active", "drained node can rejoin");203204 // --- emergency release205 C.accepting = true; await pump([A, C], 8);206 check(C.fragments.size > 1, "node C holds fragments again");207 C.fragments.clear();208 check((await C.post("drain", { mode: "emergency", remove: true })).body.status === "removed", "emergency release: space freed at once, node removed");209 check((await C.heartbeat()).body.error === "device_removed", "removed node can no longer talk to the cluster");210 const afterEmergency = await admin("GET", `objects/${obj.id}/content`);211 check(afterEmergency.status === 200 && sha(afterEmergency.raw!) === obj.sha256, "object intact after the emergency release");212213 // --- key rotation214 const kp = generateKeyPairSync("ec", { namedCurve: "prime256v1" });215 const newPub = (kp.publicKey.export({ format: "der", type: "spki" }) as Buffer).subarray(26).toString("base64");216 const proof = sign("sha256", Buffer.from(`MSP1-REKEY\n${A.id}\n${newPub}`), kp.privateKey).toString("base64");217 const oldKey = A.key;218 check((await A.post("rekey", { new_public_key: newPub, new_key_signature: proof })).body.rotated === true, "device key rotated");219 check((await A.heartbeat()).status === 401, "old key no longer accepted");220 A.key = kp.privateKey; check((await A.heartbeat()).status === 200, "new key accepted");221 A.key = oldKey; A.key = kp.privateKey;222223 // --- revocation224 await pump([A], 6);225 check(A.fragments.size === 5, "node A holds the fragments again after rejoining");226 const tasks = (await admin("POST", `nodes/${A.id}/retrieve`, { count: 1 })).body.tasks;227 const w = await A.post("work", { max: 4, wait: 0 });228 const rt2 = w.body.tasks.find((t: any) => t.task === tasks[0].task);229 await admin("POST", `nodes/${A.id}/revoke`);230 check((await A.heartbeat()).body.error === "device_revoked", "revoked device refused");231 check((await fetch(A.url(rt2), { method: "PUT", body: A.fragments.get(rt2.fragment)! })).status === 403, "tickets of a revoked device are refused");232 const final = await admin("GET", `objects/${obj.id}/content`);233 check(final.status === 200 && sha(final.raw!) === obj.sha256, "object intact with every mobile node gone");234 ov = (await admin("GET", "overview")).body;235 check(ov.stable.fragments_only_on_mobile === 0, "no fragment ever existed only on a mobile node");236237 // --- object deletion reaches the devices238 const D = new TestDevice(base, "node-D");239 await D.pair((await admin("POST", "pairing", {})).body.code); D.quota = 64 * 2 ** 20;240 await pump([D], 8);241 check(D.fragments.size === 5, "node D replicates the object");242 await admin("DELETE", "objects/" + obj.id);243 await pump([D], 4);244 check(D.fragments.size === 0 && (await admin("GET", "overview")).body.stable.fragments === 0, "deleting the object removes its fragments from the stable store and from the devices");245246 console.log(`\n${passed} checks passed`);247} catch (e) {248 console.error("\n" + (e as Error).message);249 process.exitCode = 1;250} finally {251 try { await stop(); } catch { /* already stopped */ }252 rmSync(root, { recursive: true, force: true });253}254