Files
Kelx/utils/node-token-integrity.js
T
2026-11-30 16:32:37 +00:00

232 lines
11 KiB
JavaScript

"use strict";
// Startup integrity gate for node bearer tokens (audit hardening).
//
//decryptNodeToken() passes legacy plaintext values through unchanged so the
// one-time encryption migration can read them — but that also means a row
// whose stored value can NOT pass AES-256-GCM auth-tag verification (a
// pre-migration plaintext value the migration missed, or corrupt ciphertext
// left behind by a SESSION_SECRET rotation) would linger silently forever.
// This gate runs once per startup, after the encryption migration, and leaves
// no such row unhandled:
//
// encrypted + ok → nothing to do.
// encrypted + rotate_required → legacy value that WAS plaintext at rest
// (flagged by the migration). Force-rotate:
// push a fresh credential to the daemon via
// /v1/token/rotate (authenticated WITH the
// legacy value, so this is a zero-downtime
// swap). If the daemon is unreachable or too
// old to self-rotate, the (now encrypted)
// value keeps working but the node stays
// flagged so the admin sees the badge.
// corrupt (auth-tag failure) → the panel can never recover this value.
// Invalidate it (token = NULL) and flag the
// node rotate_required; the daemon keeps its
// old token until the admin re-deploys
// config.yml / the setup command.
// plaintext → the migration should have converted this
// row. Re-encrypt in place and keep the
// rotate_required flag so the legacy value
// still gets rotated; it never lingers as
// plaintext.
// empty → nothing to invalidate, but the node is
// unusable for auth: flag rotate_required.
//
// Safety valve: if token encryption itself is unavailable (SESSION_SECRET
// missing/changed mid-flight), the whole gate aborts WITHOUT invalidating
// anything — bricking every node on a transient crypto misconfiguration would
// be worse than deferring the cleanup to the next healthy boot.
const crypto = require("crypto");
const nodeTokenCrypto = require("./node-token-crypto");
const { TOKEN_STATUS_OK, TOKEN_STATUS_ROTATE_REQUIRED } = nodeTokenCrypto;
async function verifyNodeTokenIntegrity({
db,
// Resolves the full node record (address, api_port, ssl_enabled, uuid,
// decrypted token, token_id) needed to reach the daemon for a rotation push.
getNodeByIdOrName,
// push = async (node, newToken) => boolean — installs newToken on the daemon
// (panel -> node /v1/token/rotate). Injected so this module stays
// transport-agnostic and unit-testable.
rotateNodeCredential,
// Optional per-node row lock: withNodeLock(nodeId, task) -> task(). index.js
// injects withKeyedLock(`node-ports:<id>`) so the credential swap below
// (fresh in-lock re-read -> daemon push -> persist) serializes with every
// other full-row node writer. The gate runs before the HTTP listeners open,
// but NOT all full-row writers are gated on listen: the pending-disk
// applier's interval timer is registered at module load and can fire
// mid-startup, and its full-row saveNode commits token/token_status from a
// snapshot taken inside the node lock. Without this lock a gate rotation
// that lands between the applier's in-lock re-read and its save is silently
// reverted — the panel holds the legacy credential while the daemon holds
// the rotated one, servable only through the daemon's 10-minute old-token
// grace (the same push/persist inversion the rotate-token endpoint's lock
// exists to prevent). Callers without a lock (the standalone verifier, whose
// db stub has no concurrent writers) run the swap directly.
withNodeLock,
logger = console,
} = {}) {
if (!db || typeof db.query !== "function") {
throw new Error("node-token-integrity: db dependency missing");
}
if (typeof rotateNodeCredential !== "function") {
throw new Error("node-token-integrity: rotateNodeCredential dependency missing");
}
// Crypto availability probe — fail closed to "do nothing destructive".
try {
nodeTokenCrypto.encryptNodeToken("startup-integrity-probe");
} catch (err) {
logger.warn(
"[security] Node token integrity check skipped — token encryption unavailable " +
`(${err && err.message ? err.message : err}). Plaintext/corrupt rows will be ` +
"re-examined on the next startup with working crypto."
);
return { skipped: true, rotated: 0, invalidated: 0, flagged: 0, normalized: 0 };
}
const rows = await db.query("SELECT id, name, token, token_status FROM nodes");
const summary = { skipped: false, rotated: 0, invalidated: 0, flagged: 0, normalized: 0 };
const pendingRotation = [];
for (const row of rows || []) {
const nodeId = String(row.id || "");
const nodeName = String(row.name || nodeId);
const stored = String(row.token || "");
const status = String(row.token_status || "");
const cls = nodeTokenCrypto.classifyStoredNodeToken(stored);
if (cls.state === "encrypted") {
if (status === TOKEN_STATUS_ROTATE_REQUIRED) {
// Legacy credential that was plaintext at rest before the encryption
// migration. Rotate it out now if the daemon will accept a replacement.
pendingRotation.push({ row, nodeName });
} else if (status !== TOKEN_STATUS_OK) {
// Missing/unknown status on a healthy token (e.g. column just added):
// normalize instead of flagging — there is no exposure to remediate.
await db.query("UPDATE nodes SET token_status = ? WHERE id = ?", [
TOKEN_STATUS_OK,
nodeId,
]);
summary.normalized += 1;
}
continue;
}
if (cls.state === "corrupt") {
await db.query("UPDATE nodes SET token = NULL, token_status = ? WHERE id = ?", [
TOKEN_STATUS_ROTATE_REQUIRED,
nodeId,
]);
summary.invalidated += 1;
summary.flagged += 1;
logger.error(
`[security] Node "${nodeName}" (${nodeId}): stored token FAILED AES-256-GCM ` +
"verification (SESSION_SECRET rotated since storage, or the row was tampered " +
"with). The unusable credential was invalidated; the node is flagged " +
"ROTATE REQUIRED — rotate the token (or re-deploy config.yml) to restore it."
);
continue;
}
if (cls.state === "plaintext") {
// The migration ran immediately before this gate, so a surviving
// plaintext row means the conversion failed for this row specifically.
// Never leave the plaintext value at rest: re-encrypt now and keep the
// rotate_required flag so the exposed value is still forced out.
await db.query("UPDATE nodes SET token = ?, token_status = ? WHERE id = ?", [
nodeTokenCrypto.encryptNodeToken(cls.plaintext),
TOKEN_STATUS_ROTATE_REQUIRED,
nodeId,
]);
// Flag accounting is left to the rotation outcome below: success clears
// the flag (rotated), failure leaves it set (flagged).
logger.warn(
`[security] Node "${nodeName}" (${nodeId}): token was still stored as PLAINTEXT ` +
"(encryption migration missed this row). It has been encrypted at rest and the " +
"node is flagged ROTATE REQUIRED — the legacy value must be rotated."
);
pendingRotation.push({ row, nodeName });
continue;
}
// empty
if (status !== TOKEN_STATUS_ROTATE_REQUIRED) {
await db.query("UPDATE nodes SET token_status = ? WHERE id = ?", [
TOKEN_STATUS_ROTATE_REQUIRED,
nodeId,
]);
summary.flagged += 1;
logger.warn(
`[security] Node "${nodeName}" (${nodeId}): no usable token stored — flagged ` +
"ROTATE REQUIRED. Rotate the token and re-deploy config.yml."
);
}
}
// Rotation pushes run in parallel and are individually time-bounded by the
// transport, so a fleet of offline nodes cannot stall startup linearly.
// Each swap runs under its node's row lock (when injected): rows have unique
// ids, so per-node locks never contend with each other.
const runUnderNodeRowLock = (nodeId, task) =>
typeof withNodeLock === "function" ? withNodeLock(nodeId, task) : task();
await Promise.all(pendingRotation.map(async ({ row, nodeName }) => {
const nodeId = String(row.id || "");
try {
await runUnderNodeRowLock(nodeId, async () => {
// Re-read under the node lock (same pattern as the rotate-token
// endpoint): this is the snapshot the push authenticates with and the
// persist applies onto, so no interleaved full-row writer can slip
// between the credential decision and its commit.
const node = getNodeByIdOrName ? await getNodeByIdOrName(nodeId) : null;
if (!node || !node.token) {
summary.flagged += 1;
return;
}
const newToken = "adpnt_" + crypto.randomBytes(24).toString("base64url");
const pushed = await rotateNodeCredential(node, newToken);
if (pushed) {
await db.query("UPDATE nodes SET token = ?, token_status = ? WHERE id = ?", [
nodeTokenCrypto.encryptNodeToken(newToken),
TOKEN_STATUS_OK,
nodeId,
]);
summary.rotated += 1;
logger.log(
`[security] Node "${nodeName}" (${nodeId}): legacy token (pre-migration plaintext ` +
"value) was force-rotated at startup; the new credential is active on the daemon."
);
} else {
summary.flagged += 1;
logger.warn(
`[security] Node "${nodeName}" (${nodeId}): automatic legacy-token rotation ` +
"failed (daemon offline or too old to accept /v1/token/rotate). The " +
"encrypted-at-rest legacy value keeps working, but the node stays flagged " +
"ROTATE REQUIRED — rotate the token from the admin UI."
);
}
});
} catch (err) {
summary.flagged += 1;
logger.warn(
`[security] Node "${nodeName}" (${nodeId}): automatic legacy-token rotation ` +
`failed: ${err && err.message ? err.message : err}. Node stays flagged ROTATE REQUIRED.`
);
}
}));
if (summary.rotated || summary.invalidated || summary.flagged || summary.normalized) {
logger.log(
`[security] Node token integrity check: ${summary.rotated} rotated, ` +
`${summary.invalidated} invalidated, ${summary.flagged} flagged rotate-required, ` +
`${summary.normalized} normalized.`
);
}
return summary;
}
module.exports = { verifyNodeTokenIntegrity };