Files
Kelx/tests/agent-worker-feature-config.test.js
T
2026-11-30 16:32:37 +00:00

134 lines
6.9 KiB
JavaScript

"use strict";
const assert = require("node:assert/strict");
const { spawnSync } = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const test = require("node:test");
const {
AGENT_ENABLED_KEY,
PANEL_ENV_PATH,
readAgentFeatureConfig,
reportAgentFeatureConfig,
} = require("../AgentWorker/feature-config");
test("the Agent switch reads the authoritative panel .env as data", (context) => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-agent-config-"));
const envPath = path.join(directory, ".env");
const previous = process.env[AGENT_ENABLED_KEY];
context.after(() => {
fs.rmSync(directory, { recursive: true, force: true });
if (previous === undefined) delete process.env[AGENT_ENABLED_KEY];
else process.env[AGENT_ENABLED_KEY] = previous;
});
process.env[AGENT_ENABLED_KEY] = "ON";
assert.equal(PANEL_ENV_PATH, path.resolve(__dirname, "..", ".env"));
assert.deepEqual(readAgentFeatureConfig(envPath), { enabled: false, reason: "missing" });
assert.deepEqual(readAgentFeatureConfig(directory), { enabled: false, reason: "unreadable" });
const cases = [
["OTHER_SETTING=ON", { enabled: false, reason: "missing" }],
[`${AGENT_ENABLED_KEY}=OFF`, { enabled: false, reason: "disabled" }],
[`${AGENT_ENABLED_KEY}=NOT-ASKED`, { enabled: false, reason: "not-asked" }],
[`${AGENT_ENABLED_KEY}="ON" # opt in`, { enabled: true, reason: "enabled" }],
[`${AGENT_ENABLED_KEY}=on`, { enabled: false, reason: "invalid" }],
[`${AGENT_ENABLED_KEY}=`, { enabled: false, reason: "invalid" }],
[`${AGENT_ENABLED_KEY}=$(printf ON)`, { enabled: false, reason: "invalid" }],
];
for (const [contents, expectation] of cases) {
fs.writeFileSync(envPath, `${contents}\n`);
assert.deepEqual(readAgentFeatureConfig(envPath), expectation);
}
});
test("startup notices describe only the feature setting, not file contents", () => {
const notices = [];
const logger = { info: (message) => notices.push(message), warn: (message) => notices.push(message) };
for (const reason of ["missing", "invalid", "unreadable", "enabled", "disabled", "not-asked"]) {
reportAgentFeatureConfig({ reason, value: "private value" }, logger);
}
assert.equal(notices.length, 3);
assert.ok(notices.every((message) => message.includes("OFF") && !message.includes("private value")));
});
test("a panel process still reconciles after prolonged contention for the startup lock", async () => {
const runtime = fs.readFileSync(require.resolve("../AgentWorker/panel-runtime"), "utf8");
const tick = runtime.slice(runtime.indexOf(" async function tick()"), runtime.indexOf(" function start()"));
let locked = true;
let starts = 0;
const state = { enabled: true, generation: "2" };
const run = require("node:vm").runInNewContext(`
let inFlight = false, stopped = false, attempts = 0, reconciled, stateConfirmedAt = 0;
const STARTUP_ATTEMPTS = 24, RPC_VERSION = 1, enabledAtStartup = true;
const call = async () => ({ ...state, ready: true, version: RPC_VERSION });
${tick}
({ tick, ready: () => reconciled === state && stateConfirmedAt > 0 });`, {
state, mutex: { tryAcquire: () => locked ? null : () => {} }, readAgentFeatureConfig: () => state,
bindDiagnosticSocket: async () => {}, pruneCredentialProposals: async () => {}, db: { pool: {} },
ensureAgentQueueSchema: async () => {}, reconcileAgentQueueState: async () => state,
startMatchingWorker: async () => { starts += 1; }, logger: { warn: assert.fail },
});
for (let interval = 0; interval < 30; interval += 1) await run.tick();
assert.equal(starts, 0);
locked = false;
await run.tick();
assert.equal(starts, 1);
assert.equal(run.ready(), true);
});
test("the systemd start condition allows only ON from the installed panel's .env", (context) => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-agent-condition-"));
context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
const workerDir = path.join(directory, "AgentWorker");
const dependencies = path.join(directory, "node_modules");
fs.mkdirSync(workerDir);
fs.mkdirSync(dependencies);
const condition = path.join(workerDir, "feature-config.js");
fs.copyFileSync(require.resolve("../AgentWorker/feature-config"), condition);
fs.symlinkSync(path.dirname(require.resolve("dotenv/package.json")), path.join(dependencies, "dotenv"), "dir");
for (const [contents, expected] of [[null, 1], ["OFF", 1], ["NOT-ASKED", 1], ["invalid", 1], ['"ON" # opt in', 0]]) {
if (contents !== null) fs.writeFileSync(path.join(directory, ".env"), `${AGENT_ENABLED_KEY}=${contents}\n`);
const result = spawnSync(process.execPath, [condition], {
cwd: os.tmpdir(), env: { ...process.env, [AGENT_ENABLED_KEY]: "ON" }, encoding: "utf8", timeout: 5000,
});
assert.ifError(result.error);
assert.equal(result.status, expected, contents);
assert.equal(result.stderr, "");
}
});
test("Initialize Panel provisions the Agent unit without enabling it or asking for a setting", () => {
const installer = fs.readFileSync(path.join(__dirname, "..", "initialize.sh"), "utf8");
const body = (name) => {
const match = installer.match(new RegExp(`^${name}\\(\\) \\{\\n`, "m"));
assert.ok(match, `Missing installer function: ${name}`);
const rest = installer.slice(match.index + match[0].length);
const next = rest.search(/^[a-z_]+\(\) \{/m);
assert.notEqual(next, -1, `Missing function after ${name}`);
return rest.slice(0, next);
};
const option = body("initialize_panel");
assert.match(option, /^ADPANEL_AGENT_ENABLED=NOT-ASKED$/m);
assert.match(option, /^ADPANEL_AGENT_ENABLED=NOT-ASKED$[\s\S]*?^ if ! setup_adpanel_service; then$/m);
assert.doesNotMatch(option, /\bread\b[^\n]*(?:ADPanel Agent|ADPANEL_AGENT_ENABLED)/i);
assert.match(body("setup_adpanel_service"), /systemd\)[\s\S]*?setup_adpanel_systemd_service/);
const systemd = body("setup_adpanel_systemd_service");
assert.match(systemd, /if provision_adpanel_agent_worker; then[\s\S]*?systemctl daemon-reload[\s\S]*?systemctl start/);
assert.doesNotMatch(systemd, /^(?:BindsTo|Requires|Upholds|Wants)=.*adpanel-agent/m);
const unit = body("provision_adpanel_agent_worker");
assert.match(unit, /^After=network\.target adpanel\.service$/m);
assert.match(unit, /^BindsTo=adpanel\.service$/m);
assert.match(unit, /^PartOf=adpanel\.service$/m);
assert.match(unit, /^User=adpanel$/m);
assert.doesNotMatch(unit, /^Exec(?:Condition|Start)=.*\/AgentWorker\//m, "neither systemd phase may load unverified Agent code");
assert.match(unit, /^ExecStart=.*\/scripts\/panel-update-recovery\.cjs --agent$/m);
assert.match(unit, /^StartLimitIntervalSec=0$/m, "a temporary database outage must not permanently stop Agent");
assert.match(unit, /^Restart=on-failure$/m);
assert.match(unit, /^RestartSec=15$/m, "unlimited recovery attempts must be paced");
assert.doesNotMatch(unit, /^\[Install\]$|\bsystemctl\s+(?:enable|start)\b/m);
});