Security review: - Release verification cache keys on ctime as well as mtime, in nanoseconds. A same-size rewrite with mtime set back now re-hashes and reports proxy-install-invalid. Build review: - The setup page hides the account panels on any failed accounts read, not only proxy-down, and brings them back once the proxy answers. - The organizations table shows a dash, not a made-up 0, when a bus does not answer or sends no model list (orgCatalogue in proxy-admin.mjs). - A fence clear the bus did not answer keeps the confirmed restart for a retry. - A fence with no readable time names `mosaic proxy fence clear --proxy-restarted` on the page, in the refusal table and in the README. - CLI `init --generate-key` goes through the setup controller and writes the same init receipt as the page. - Status carries the last ten receipts, so the page shows them after a reload. An initialized proxy keeps the init form folded. - README: proxy-admin-busy is per process; the cross-process locks that serialize the writes are named.
141 lines
8.3 KiB
JavaScript
141 lines
8.3 KiB
JavaScript
// #1873 proxy setup controller shared by the Console page (webui proxy-admin.mjs) and
|
|
// `mosaic proxy status|unit|init-lock|fence clear --restart`. Host actions run here; init and
|
|
// the fence clear go to the bus, which decides them. Results and receipts carry labels, key IDs
|
|
// and process ids only: never a key, token, absolute path or upstream text.
|
|
import { homedir } from 'node:os';
|
|
import { fetchPinned } from './fetch.mjs';
|
|
import { PIN } from './common.mjs';
|
|
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, createUnitControl, FILE_LABELS } from './admin.mjs';
|
|
|
|
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
|
|
const failure = code => Object.assign(new Error(code), { code });
|
|
|
|
// `buses()` proves the init-lock condition "bus stopped" ({stopped, running:[label]}).
|
|
// `orgs()` lists the organizations this proxy serves: [{id, catalogue}]. `unit` and `fetch` are
|
|
// (and `pin`) seams for tests; the defaults run the real proxy-service.sh, systemctl and pinned fetch.
|
|
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], now = () => new Date(), env = process.env, pin = PIN }) {
|
|
const port = () => { try { return initState(configDir, dataRoot).settings?.port ?? null; } catch { return null; } };
|
|
const control = unit ?? createUnitControl({ instance, unitDir, port, env });
|
|
let job = { state: 'idle', step: null, receipt: null, error: null };
|
|
// The last confirmed restart this page made. One fence clear may use it.
|
|
let restarted = null;
|
|
let busy = null;
|
|
const receipt = record => appendReceipt(dataRoot, { time: now().toISOString(), ...record });
|
|
const fetchRecord = () => ({ op: 'fetch', version: pin.version, panelVersion: pin.panel.version, archiveSha256: pin.archive.sha256, panelSha256: pin.panel.sha256, binarySha256: pin.binary.sha256, verified: true });
|
|
async function exclusive(name, action) {
|
|
if (busy) throw failure('proxy-admin-busy');
|
|
busy = name;
|
|
try { return await action(); } finally { busy = null; }
|
|
}
|
|
async function unitStatus() {
|
|
try { return await control.status(); } catch (error) { return { unit: control.unit, installed: false, active: 'unknown', healthy: false, error: proxyCode(error, 'proxy-unit-failed') }; }
|
|
}
|
|
function nextSteps({ release, init, unitState, fence, lock }) {
|
|
if (!release.fetched || release.problem) return ['fetch'];
|
|
if (lock.present) return lock.clearable ? ['init-lock-clear'] : ['init-lock-wait'];
|
|
if (init.partial || init.problem) return ['init-repair'];
|
|
if (!init.initialized) return ['init'];
|
|
if (!unitState.installed) return ['unit-install'];
|
|
if (unitState.active !== 'active') return ['unit-start'];
|
|
if (!unitState.healthy) return ['unit-restart'];
|
|
if (fence) return restarted ? ['fence-clear'] : ['unit-restart'];
|
|
return ['accounts'];
|
|
}
|
|
return {
|
|
unit: control.unit,
|
|
async status() {
|
|
// The job is read before the release: a fetch that ends during the awaits below then reads
|
|
// "running" (and the page polls again), never "done" next to a release read before it ended.
|
|
const fetchJob = { ...job };
|
|
const release = releaseState(dataRoot, pin);
|
|
const init = initState(configDir, dataRoot);
|
|
const unitState = await unitStatus();
|
|
const fence = fenceState(dataRoot);
|
|
const lock = init.lock ? initLockStatus({ configDir, dataRoot, buses: await buses() }) : { present: false, clearable: false, blockers: [] };
|
|
let organizations = null;
|
|
try { organizations = await orgs(); } catch { organizations = null; }
|
|
return {
|
|
release: { version: release.version, panelVersion: release.panelVersion, fetched: release.fetched, verified: release.verified, problem: release.problem },
|
|
init: {
|
|
initialized: init.initialized, partial: init.partial, problem: init.problem, settings: init.settings,
|
|
files: Object.entries(init.files).map(([name, found]) => ({ label: FILE_LABELS[name], present: found })),
|
|
},
|
|
unit: unitState,
|
|
fence: fence ? { set: true, org: fence.org ?? null, op: fence.op ?? null, time: fence.time ?? null, invalid: fence.invalid === true } : { set: false },
|
|
initLock: lock,
|
|
fetch: fetchJob,
|
|
restart: restarted ? { confirmed: true, observedAt: restarted.observedAt, pid: restarted.after.pid } : null,
|
|
busy,
|
|
receipts: recentReceipts(dataRoot),
|
|
organizations,
|
|
// Ruling 8: the system config holds one proxy per instance; an organization's own proxy
|
|
// needs a config format that does not exist yet.
|
|
ownProxy: { available: false, state: 'not built', reason: 'This instance has one shared proxy. A separate proxy per organization is not built yet.' },
|
|
next: nextSteps({ release, init, unitState, fence, lock }),
|
|
};
|
|
},
|
|
// Runs in the background; the page polls status for its step and receipt.
|
|
fetchStart() {
|
|
if (job.state === 'running' || busy) throw failure('proxy-admin-busy');
|
|
job = { state: 'running', step: 'start', receipt: null, error: null };
|
|
busy = 'fetch';
|
|
Promise.resolve()
|
|
.then(() => fetch({ dataRoot, pin, progress: step => { job.step = step; } }))
|
|
.then(() => {
|
|
job = { state: 'done', step: 'done', error: null, receipt: receipt(fetchRecord()) };
|
|
})
|
|
.catch(error => { job = { state: 'failed', step: job.step, receipt: null, error: proxyCode(error, 'proxy-fetch-failed') }; })
|
|
.finally(() => { busy = null; });
|
|
return { state: 'running' };
|
|
},
|
|
// The CLI's fetch: the same pinned fetch and receipt, in the foreground. Returns the fetch
|
|
// result (for the CLI's existing output) and the receipt.
|
|
async fetchRun({ progress = () => {} } = {}) {
|
|
if (job.state === 'running') throw failure('proxy-admin-busy');
|
|
return exclusive('fetch', async () => {
|
|
const result = await fetch({ dataRoot, pin, progress });
|
|
return { result, receipt: receipt(fetchRecord()) };
|
|
});
|
|
},
|
|
async init(call, args) {
|
|
return exclusive('init', async () => {
|
|
const result = await call('proxy.init', args);
|
|
const settings = { port: result.port, rotateGraceMinutes: result.rotateGraceMinutes ?? null, firstOutputSeconds: result.firstOutputSeconds ?? null };
|
|
return { settings, receipt: receipt({ op: 'init', generated: args.generate === true, ...settings }) };
|
|
});
|
|
},
|
|
async render() {
|
|
const text = await control.render();
|
|
const home = homedir();
|
|
return { unit: control.unit, text: home && home !== '/' ? text.split(home).join('~') : text };
|
|
},
|
|
async unitAction(op) {
|
|
return exclusive(`unit-${op}`, async () => {
|
|
if (op === 'restart') {
|
|
const { state, evidence } = await control.restart();
|
|
restarted = evidence.confirmed ? evidence : null;
|
|
return { state, evidence, receipt: receipt({ op: 'unit.restart', unit: control.unit, confirmed: evidence.confirmed, before: { pid: evidence.before.pid }, after: { pid: evidence.after.pid, listening: evidence.after.listening }, observedAt: evidence.observedAt }) };
|
|
}
|
|
const state = await control[op]();
|
|
// Any other unit action ends the restart this page confirmed.
|
|
restarted = null;
|
|
return { state, receipt: receipt({ op: `unit.${op}`, unit: control.unit, active: state.active, pid: state.pid ?? null, healthy: state.healthy === true }) };
|
|
});
|
|
},
|
|
// Only after this page restarted the proxy and saw the new process. The bus re-proves it.
|
|
async fenceClear(call) {
|
|
return exclusive('fence-clear', async () => {
|
|
if (!restarted) throw failure('proxy-restart-required');
|
|
const evidence = restarted;
|
|
// Kept until the bus answers: a bus that is down or busy leaves the confirmed restart for a retry.
|
|
const result = await call('proxy.fence.clear', { evidence });
|
|
if (restarted === evidence) restarted = null;
|
|
return { cleared: result.cleared === true, receipt: receipt({ op: 'fence.clear', cleared: result.cleared === true, evidence: result.evidence ?? null }) };
|
|
});
|
|
},
|
|
async initLockClear() {
|
|
return exclusive('init-lock-clear', async () => ({ receipt: clearInitLock({ configDir, dataRoot, buses: await buses(), now }) }));
|
|
},
|
|
};
|
|
}
|