Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,385 @@
|
||||
"use strict";
|
||||
|
||||
// Tests for the secret-free node bootstrap (utils/node-bootstrap.js).
|
||||
// Run: npm test (node --test tests/ utils/)
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const express = require("express");
|
||||
|
||||
const {
|
||||
ENROLL_ID_RE,
|
||||
buildNodeBootstrapScript,
|
||||
createBootstrapConfigHandler,
|
||||
createBootstrapScriptHandler,
|
||||
createNodeBootstrapRateLimiter,
|
||||
createNodeBootstrapStore,
|
||||
isEnrollId,
|
||||
} = require("./node-bootstrap");
|
||||
|
||||
const fixtureNode = (id) => ({ id, uuid: id, name: "test-node", token: "fixture-enrollment-token" });
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Store
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("shared enrollments survive worker changes and can only be redeemed once", async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-enrollment-test-"));
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const filePath = path.join(directory, "enrollments.json");
|
||||
let now = 100_000;
|
||||
const options = { filePath, ttlMs: 1_000, now: () => now };
|
||||
const issuer = createNodeBootstrapStore(options);
|
||||
const worker = createNodeBootstrapStore(options);
|
||||
const enrollment = await issuer.issue(fixtureNode("node-one"));
|
||||
assert.equal(fs.statSync(filePath).mode & 0o777, 0o600);
|
||||
assert.equal((await worker.consume(enrollment.scriptId)).configId, enrollment.configId);
|
||||
const consumed = await Promise.all([issuer.consume(enrollment.configId), worker.consume(enrollment.configId)]);
|
||||
assert.deepEqual(consumed.filter(Boolean).map(record => record.nodeId), ["node-one"]);
|
||||
const expiring = await issuer.issue(fixtureNode("node-two"));
|
||||
now += 1_000;
|
||||
assert.equal(await worker.consume(expiring.configId), null);
|
||||
});
|
||||
|
||||
test("store: issue mints a linked script/config pair of valid one-time IDs", () => {
|
||||
const store = createNodeBootstrapStore({ ttlMs: 60_000 });
|
||||
const enroll = store.issue(fixtureNode("node-uuid-1"));
|
||||
|
||||
assert.match(enroll.scriptId, ENROLL_ID_RE);
|
||||
assert.match(enroll.configId, ENROLL_ID_RE);
|
||||
assert.notEqual(enroll.scriptId, enroll.configId);
|
||||
assert.equal(store.size, 2);
|
||||
|
||||
const scriptRec = store.peek(enroll.scriptId);
|
||||
const configRec = store.peek(enroll.configId);
|
||||
assert.equal(scriptRec.kind, "script");
|
||||
assert.equal(scriptRec.nodeId, "node-uuid-1");
|
||||
assert.equal(scriptRec.configId, enroll.configId);
|
||||
assert.equal(configRec.kind, "config");
|
||||
assert.equal(configRec.nodeId, "node-uuid-1");
|
||||
});
|
||||
|
||||
test("store: consume is single-use — first caller wins, replay gets null", () => {
|
||||
const store = createNodeBootstrapStore({ ttlMs: 60_000 });
|
||||
const { scriptId, configId } = store.issue(fixtureNode("node-uuid-1"));
|
||||
|
||||
const first = store.consume(scriptId);
|
||||
assert.ok(first);
|
||||
assert.equal(first.kind, "script");
|
||||
|
||||
assert.equal(store.consume(scriptId), null);
|
||||
assert.equal(store.peek(scriptId), null);
|
||||
|
||||
const cfg = store.consume(configId);
|
||||
assert.ok(cfg);
|
||||
assert.equal(store.consume(configId), null);
|
||||
});
|
||||
|
||||
test("store: entries expire after the TTL", () => {
|
||||
let t = 1_000_000;
|
||||
const now = () => t;
|
||||
const store = createNodeBootstrapStore({ ttlMs: 10 * 60 * 1000, now });
|
||||
const { scriptId } = store.issue(fixtureNode("node-uuid-1"));
|
||||
|
||||
t += 10 * 60 * 1000 - 1;
|
||||
assert.ok(store.peek(scriptId));
|
||||
|
||||
t += 2;
|
||||
assert.equal(store.peek(scriptId), null, "expired entry must vanish");
|
||||
assert.equal(store.consume(scriptId), null);
|
||||
});
|
||||
|
||||
test("store: rejects malformed IDs without throwing", () => {
|
||||
const store = createNodeBootstrapStore({ ttlMs: 60_000 });
|
||||
store.issue(fixtureNode("node-uuid-1"));
|
||||
for (const bad of ["", "../../etc/passwd", "short", `${"a".repeat(44)}!`, null, undefined]) {
|
||||
assert.equal(store.peek(bad), null);
|
||||
assert.equal(store.consume(bad), null);
|
||||
}
|
||||
assert.equal(isEnrollId("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), true); // 43 chars
|
||||
assert.equal(isEnrollId("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), false); // 42 chars
|
||||
});
|
||||
|
||||
test("store: evicts oldest entries beyond the cap", () => {
|
||||
const store = createNodeBootstrapStore({ ttlMs: 60_000, maxEntries: 6 }); // 3 pairs
|
||||
const first = store.issue(fixtureNode("node-1"));
|
||||
store.issue(fixtureNode("node-2"));
|
||||
store.issue(fixtureNode("node-3"));
|
||||
assert.equal(store.size, 6);
|
||||
store.issue(fixtureNode("node-4")); // evicts the two oldest entries (node-1's pair)
|
||||
|
||||
assert.equal(store.peek(first.scriptId), null);
|
||||
assert.equal(store.peek(first.configId), null);
|
||||
assert.equal(store.size, 6);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rate limiter
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("rate limiter: allows up to max per window then blocks, and resets", () => {
|
||||
let t = 5_000_000;
|
||||
const limiter = createNodeBootstrapRateLimiter({ windowMs: 60_000, max: 3, now: () => t });
|
||||
|
||||
assert.equal(limiter.allow("1.2.3.4"), true);
|
||||
assert.equal(limiter.allow("1.2.3.4"), true);
|
||||
assert.equal(limiter.allow("1.2.3.4"), true);
|
||||
assert.equal(limiter.allow("1.2.3.4"), false);
|
||||
assert.equal(limiter.allow("1.2.3.4"), false);
|
||||
|
||||
// Different key is unaffected.
|
||||
assert.equal(limiter.allow("5.6.7.8"), true);
|
||||
|
||||
// Window rolls over.
|
||||
t += 61_000;
|
||||
assert.equal(limiter.allow("1.2.3.4"), true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Script builder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("script builder: embeds the single-use config URL, no other secret channel", () => {
|
||||
const configUrl = "https://panel.example.com/api/node-bootstrap/abc/config.yml";
|
||||
const script = buildNodeBootstrapScript({ configUrl });
|
||||
|
||||
assert.ok(script.includes(`CONFIG_URL='${configUrl}'`), "config URL must be embedded single-quoted");
|
||||
// Writes with restrictive perms and validates the payload before writing.
|
||||
assert.ok(script.includes("install -m 0640"));
|
||||
assert.ok(script.includes("grep -q '^uuid:'"));
|
||||
assert.ok(script.includes("grep -q '^token:'"));
|
||||
// Fetches with curl -f (fails on HTTP errors) and restarts the service.
|
||||
assert.ok(script.includes("curl -fsSL"));
|
||||
assert.ok(script.includes("systemctl restart adaemon"));
|
||||
// No echo of the downloaded config back to the terminal.
|
||||
assert.ok(!script.includes("cat \"$TMP_CONFIG\""));
|
||||
const echoLines = script.split("\n").filter((l) => /\becho\b/.test(l));
|
||||
assert.ok(
|
||||
echoLines.every((l) => !l.includes("TMP_CONFIG")),
|
||||
`no echo line may reference the config payload: ${JSON.stringify(echoLines)}`
|
||||
);
|
||||
});
|
||||
|
||||
test("script builder: refuses to build without a config URL", () => {
|
||||
assert.throws(() => buildNodeBootstrapScript({}), /configUrl/);
|
||||
assert.throws(() => buildNodeBootstrapScript({ configUrl: "" }), /configUrl/);
|
||||
});
|
||||
|
||||
test("linking with missing or inaccessible TLS files leaves the config and service untouched", { skip: process.platform !== "linux" }, (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-bootstrap-tls-"));
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const installed = path.join(directory, "config.yml");
|
||||
const certificate = path.join(directory, "cert.pem");
|
||||
const key = path.join(directory, "key.pem");
|
||||
const restartMarker = path.join(directory, "restarted");
|
||||
const config = ["uuid: fixture", "token: temporary-fixture-token", "api:", " ssl:",
|
||||
" enabled: true", ` cert: "${certificate}"`, ` key: "${key}"`, ""].join("\n");
|
||||
fs.writeFileSync(installed, "previous working config\n");
|
||||
for (const [command, body] of Object.entries({
|
||||
id: "printf '0\\n'",
|
||||
curl: 'while [ "$1" != "-o" ]; do shift; done\nprintf "%s" "$FIXTURE_CONFIG" > "$2"',
|
||||
install: 'for target do :; done\ncase "$target" in "$FIXTURE_DIR"|"$FIXTURE_DIR/config.yml") exec /usr/bin/install "$@";; *) exit 99;; esac',
|
||||
chown: ":",
|
||||
runuser: 'test "$1" = "-u" && test "$2" = "adaemon" && test "$3" = "--"\ntest "$FIXTURE_TLS_READABLE" = "yes"\nshift 3\nexec "$@"',
|
||||
systemctl: ': > "$FIXTURE_RESTART"',
|
||||
"rc-service": ': > "$FIXTURE_RESTART"',
|
||||
service: ': > "$FIXTURE_RESTART"',
|
||||
})) fs.writeFileSync(path.join(directory, command), `#!/bin/sh\nset -eu\n${body}\n`, { mode: 0o700 });
|
||||
const generated = buildNodeBootstrapScript({ configUrl: "https://panel.example.test/unused" });
|
||||
assert.ok(generated.includes("NODE_DIR=/var/lib/node"));
|
||||
const script = generated.replace("NODE_DIR=/var/lib/node", 'NODE_DIR="$FIXTURE_DIR"');
|
||||
const run = (readable = "yes") => spawnSync("/bin/sh", ["-s"], {
|
||||
input: script, encoding: "utf8", timeout: 3000,
|
||||
env: { PATH: `${directory}:/usr/bin:/bin`, FIXTURE_DIR: directory, FIXTURE_CONFIG: config, FIXTURE_RESTART: restartMarker, FIXTURE_TLS_READABLE: readable },
|
||||
});
|
||||
|
||||
const refused = run();
|
||||
assert.equal(refused.status, 1, refused.stderr);
|
||||
assert.match(refused.stderr, /TLS is enabled but the certificate or key is missing/);
|
||||
assert.equal(fs.readFileSync(installed, "utf8"), "previous working config\n");
|
||||
assert.equal(fs.existsSync(restartMarker), false);
|
||||
|
||||
fs.writeFileSync(certificate, "synthetic certificate");
|
||||
fs.writeFileSync(key, "synthetic key");
|
||||
const inaccessible = run("no");
|
||||
assert.equal(inaccessible.status, 1, inaccessible.stderr);
|
||||
assert.match(inaccessible.stderr, /unreadable by adaemon/);
|
||||
assert.equal(fs.readFileSync(installed, "utf8"), "previous working config\n");
|
||||
assert.equal(fs.existsSync(restartMarker), false);
|
||||
const deployed = run();
|
||||
assert.equal(deployed.status, 0, deployed.stderr);
|
||||
assert.equal(fs.readFileSync(installed, "utf8"), config);
|
||||
assert.equal(fs.existsSync(restartMarker), true);
|
||||
});
|
||||
|
||||
test("script builder: shell-quotes hostile URL content safely", () => {
|
||||
const hostile = "https://x/'$(rm -rf /)'";
|
||||
const script = buildNodeBootstrapScript({ configUrl: hostile });
|
||||
assert.ok(script.includes(`'https://x/'\\''$(rm -rf /)'\\'''`));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HTTP handlers (real express app, stubbed node lookup / config builder)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SENTINEL_TOKEN = "node-bearer-token-SENTINEL-9f8e7d6c";
|
||||
const SENTINEL_HMAC = "a".repeat(64);
|
||||
|
||||
function fixtureConfigYml() {
|
||||
return [
|
||||
"debug: false",
|
||||
"uuid: node-uuid-1",
|
||||
"token_id: tid-1",
|
||||
`token: ${SENTINEL_TOKEN}`,
|
||||
"auth:",
|
||||
` token: ${SENTINEL_TOKEN}`,
|
||||
"panel:",
|
||||
" url: https://panel.example.com",
|
||||
` hmac_secret: "${SENTINEL_HMAC}"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildTestServer({ limiterMax = 1000, findNode } = {}) {
|
||||
const store = createNodeBootstrapStore({ ttlMs: 60_000 });
|
||||
const nodeFixture = fixtureNode("node-uuid-1");
|
||||
const limiter = createNodeBootstrapRateLimiter({ windowMs: 60_000, max: limiterMax });
|
||||
|
||||
const app = express();
|
||||
app.get("/api/node-bootstrap/:id", createBootstrapScriptHandler({
|
||||
store,
|
||||
limiter,
|
||||
findNode: findNode || (async () => nodeFixture),
|
||||
buildPanelBaseUrl: () => "https://panel.example.com",
|
||||
}));
|
||||
app.get("/api/node-bootstrap/:id/config.yml", createBootstrapConfigHandler({
|
||||
store,
|
||||
limiter,
|
||||
findNode: findNode || (async () => nodeFixture),
|
||||
buildConfig: fixtureConfigYml,
|
||||
}));
|
||||
|
||||
const server = http.createServer(app);
|
||||
return new Promise((resolve) => {
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
resolve({
|
||||
store,
|
||||
base: `http://127.0.0.1:${server.address().port}`,
|
||||
close: () => new Promise((r) => server.close(r)),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("HTTP: full bootstrap flow — script once, config once, replays 410", async () => {
|
||||
const srv = await buildTestServer();
|
||||
try {
|
||||
const enroll = srv.store.issue(fixtureNode("node-uuid-1"));
|
||||
|
||||
// 1. Script download.
|
||||
const scriptRes = await fetch(`${srv.base}/api/node-bootstrap/${enroll.scriptId}`);
|
||||
assert.equal(scriptRes.status, 200);
|
||||
assert.match(scriptRes.headers.get("content-type") || "", /text\/x-shellscript/);
|
||||
assert.match(scriptRes.headers.get("cache-control") || "", /no-store/);
|
||||
const script = await scriptRes.text();
|
||||
assert.ok(script.includes(`/api/node-bootstrap/${enroll.configId}/config.yml`));
|
||||
// The script must NOT embed any credential material.
|
||||
assert.ok(!script.includes(SENTINEL_TOKEN));
|
||||
assert.ok(!script.includes(SENTINEL_HMAC));
|
||||
|
||||
// 2. Script replay -> gone.
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${enroll.scriptId}`)).status, 410);
|
||||
|
||||
// 3. Config download (exactly once) — this is the intended credential
|
||||
// delivery, over TLS in production (transport enforced upstream in
|
||||
// index.js isOpenNodeRoute, same rule as the config.yml endpoint).
|
||||
const cfgRes = await fetch(`${srv.base}/api/node-bootstrap/${enroll.configId}/config.yml`);
|
||||
assert.equal(cfgRes.status, 200);
|
||||
assert.match(cfgRes.headers.get("content-type") || "", /text\/yaml/);
|
||||
assert.match(cfgRes.headers.get("cache-control") || "", /no-store/);
|
||||
const yml = await cfgRes.text();
|
||||
assert.ok(yml.includes(`token: ${SENTINEL_TOKEN}`));
|
||||
assert.ok(yml.includes(`hmac_secret: "${SENTINEL_HMAC}"`));
|
||||
|
||||
// 4. Config replay -> gone.
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${enroll.configId}/config.yml`)).status, 410);
|
||||
} finally {
|
||||
await srv.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP: wrong-kind IDs are rejected and consumed (fail closed)", async () => {
|
||||
const srv = await buildTestServer();
|
||||
try {
|
||||
// configId used on the script endpoint -> 410, and the config enrollment
|
||||
// is burnt so it cannot be retried against the right endpoint.
|
||||
const a = srv.store.issue(fixtureNode("node-uuid-1"));
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${a.configId}`)).status, 410);
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${a.configId}/config.yml`)).status, 410);
|
||||
|
||||
// scriptId used on the config endpoint -> 410, script enrollment burnt.
|
||||
const b = srv.store.issue(fixtureNode("node-uuid-1"));
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${b.scriptId}/config.yml`)).status, 410);
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${b.scriptId}`)).status, 410);
|
||||
} finally {
|
||||
await srv.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP: script serve fails closed when the paired config link is dead", async () => {
|
||||
const srv = await buildTestServer();
|
||||
try {
|
||||
const enroll = srv.store.issue(fixtureNode("node-uuid-1"));
|
||||
// Burn the config link first (e.g. an early partial download).
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${enroll.configId}/config.yml`)).status, 200);
|
||||
// The script must now refuse rather than deliver a command that cannot work.
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${enroll.scriptId}`)).status, 410);
|
||||
} finally {
|
||||
await srv.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP: unknown node -> 410, enrollment consumed", async () => {
|
||||
const srv = await buildTestServer({ findNode: async () => null });
|
||||
try {
|
||||
const enroll = srv.store.issue(fixtureNode("node-uuid-1"));
|
||||
assert.equal((await fetch(`${srv.base}/api/node-bootstrap/${enroll.scriptId}`)).status, 410);
|
||||
assert.equal(srv.store.peek(enroll.scriptId), null, "consumed even when node lookup fails");
|
||||
} finally {
|
||||
await srv.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP: garbage IDs -> 410 (never 500)", async () => {
|
||||
const srv = await buildTestServer();
|
||||
try {
|
||||
for (const bad of ["x", "%2e%2e%2fetc%2fpasswd", "not-a-real-id-at-all-just-noise-12345"]) {
|
||||
const res = await fetch(`${srv.base}/api/node-bootstrap/${encodeURIComponent(bad)}`);
|
||||
assert.equal(res.status, 410);
|
||||
const resCfg = await fetch(`${srv.base}/api/node-bootstrap/${encodeURIComponent(bad)}/config.yml`);
|
||||
assert.equal(resCfg.status, 410);
|
||||
}
|
||||
} finally {
|
||||
await srv.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP: rate limiter trips and returns 429", async () => {
|
||||
const srv = await buildTestServer({ limiterMax: 5 });
|
||||
try {
|
||||
const codes = [];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const res = await fetch(`${srv.base}/api/node-bootstrap/unknown-id-${i}`);
|
||||
codes.push(res.status);
|
||||
}
|
||||
assert.ok(codes.includes(429), `expected a 429 among ${codes.join(",")}`);
|
||||
assert.ok(codes.every((c) => c === 410 || c === 429), `unexpected status among ${codes.join(",")}`);
|
||||
} finally {
|
||||
await srv.close();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user