diff --git a/src/idunn-rudp-health.ts b/src/idunn-rudp-health.ts index 4afceba..d9c3c01 100644 --- a/src/idunn-rudp-health.ts +++ b/src/idunn-rudp-health.ts @@ -11,7 +11,7 @@ import { } from "cultnet-ts"; import type { HeimdallConfig } from "./config.js"; import { - openOrEnrollProviderHealthIdentity, + openProviderHealthIdentity, signProviderHealthPayload, } from "./provider-health-identity.js"; @@ -92,7 +92,7 @@ async function publishIdunnRudpHealthOnce( } async function buildSignedDocumentPutPayload(config: HeimdallConfig, health: IdunnHealthInput): Promise { - const identity = await openOrEnrollProviderHealthIdentity(config.providerHealthIdentityPath); + const identity = await openProviderHealthIdentity(config.providerHealthIdentityPath); publisherSequence += 1; const unsigned = [ SIGNED_DAEMON_HEALTH_SCHEMA, diff --git a/src/provider-health-identity.ts b/src/provider-health-identity.ts index 8700257..24bcf8b 100644 --- a/src/provider-health-identity.ts +++ b/src/provider-health-identity.ts @@ -7,6 +7,7 @@ import { sign, type KeyObject, } from "node:crypto"; +import { readFileSync } from "node:fs"; import { chmod, readFile } from "node:fs/promises"; import { SingleFileMessagePackBackingStore, type CultCacheEnvelope } from "cultcache-ts"; @@ -72,6 +73,78 @@ export async function openOrEnrollProviderHealthIdentity(path: string): Promise< return decodePrivateIdentity(existing[0]!.payload, await readMachineId()); } +const PRESENCE_IDENTITY_FD_NAME = "gamecult-runtime-presence-identity"; +const SYSTEMD_LISTEN_FDS_START = 3; + +/** + * Locate the runtime presence identity among the file descriptors systemd + * passed us, using the LISTEN_FDS convention: descriptors begin at 3 and + * LISTEN_FDNAMES names them in order, colon-separated. + * + * Idunn passes this identity as a parent-only descriptor rather than a path or + * a credential file, deliberately: the workload runs under DynamicUser and + * cannot open the 0600 root-owned store, and a descriptor cannot be re-read by + * anything that did not inherit it. + */ +function presenceIdentityDescriptor( + env: NodeJS.ProcessEnv, + pid: number +): number | undefined { + const names = env.LISTEN_FDNAMES; + if (!names) { + return undefined; + } + + // LISTEN_PID guards against consuming descriptors meant for a parent or a + // sibling; systemd sets it to the intended recipient. + if (env.LISTEN_PID && Number(env.LISTEN_PID) !== pid) { + return undefined; + } + + const index = names.split(":").indexOf(PRESENCE_IDENTITY_FD_NAME); + return index === -1 ? undefined : SYSTEMD_LISTEN_FDS_START + index; +} + +/** + * Open the identity Heimdall signs provider health with. + * + * Under Idunn the identity is enrolled by the operator, bound to this machine, + * and its public key is registered in Idunn's daemon-health trust store. Taking + * it from the passed descriptor is what makes published health admissible. If + * Heimdall instead enrolled its own key here it would sign with a key Idunn + * does not trust: health would be refused, warming presence would never be + * observed, and a deployment would hang at promotion with a service that looks + * healthy from every other angle. + * + * Outside Idunn there is no descriptor and no trust store, and the ordinary + * self-enrolling path applies. + */ +export async function openProviderHealthIdentity( + path: string, + env: NodeJS.ProcessEnv = process.env, + pid: number = process.pid +): Promise { + const descriptor = presenceIdentityDescriptor(env, pid); + if (descriptor === undefined) { + return openOrEnrollProviderHealthIdentity(path); + } + + const store = decode(readFileSync(descriptor)); + const envelopes = Array.isArray(store) ? store : [store]; + if (envelopes.length !== 1) { + throw new Error( + "Idunn runtime presence identity must contain exactly one record." + ); + } + + const payload = (envelopes[0] as Record)?.payload; + if (!(payload instanceof Uint8Array)) { + throw new Error("Idunn runtime presence identity has no binary payload."); + } + + return decodePrivateIdentity(payload, await readMachineId()); +} + export function signProviderHealthPayload(identity: PrivateIdentity, payload: Uint8Array): Uint8Array { const message = Buffer.concat([ SIGNATURE_DOMAIN, diff --git a/tests/presence-identity-descriptor.test.ts b/tests/presence-identity-descriptor.test.ts new file mode 100644 index 0000000..8179b69 --- /dev/null +++ b/tests/presence-identity-descriptor.test.ts @@ -0,0 +1,99 @@ +import { mkdtemp, readFile } from "node:fs/promises"; +import { openSync, closeSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + openOrEnrollProviderHealthIdentity, + openProviderHealthIdentity, + providerHealthPublicIdentity, +} from "../src/provider-health-identity.js"; + +const machineIdAvailable = await readFile("/etc/machine-id", "utf8").then( + () => true, + () => false +); + +/** + * The identity is machine-id bound, so these can only run where a machine-id + * exists. On Windows the enrolment path itself is unavailable, and the + * descriptor selection below is the part worth proving anyway. + */ +describe.skipIf(!machineIdAvailable)("presence identity from a passed descriptor", () => { + it("reads the identity Idunn passed rather than enrolling its own", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-presence-")); + const store = path.join(dir, "runtime-presence-identity.cc"); + const enrolled = await openOrEnrollProviderHealthIdentity(store); + + const fd = openSync(store, "r"); + try { + // The lookup maps a name index onto 3 + index, so the name list has to be + // padded until the presence entry lands on whatever descriptor open() + // actually returned. Assuming it is 3 is how this test would pass on one + // machine and read the wrong descriptor on another. + const names = [ + ...Array.from({ length: fd - 3 }, (_, i) => `pad-${i}`), + "gamecult-runtime-presence-identity", + ].join(":"); + + const opened = await openProviderHealthIdentity( + path.join(dir, "would-be-self-enrolled.cc"), + { LISTEN_FDNAMES: names, LISTEN_PID: String(process.pid) }, + process.pid + ); + + // Same key as the enrolled one means it came from the descriptor. A + // fresh self-enrolment would produce a different key, which is exactly + // the failure that would make Idunn refuse this daemon's health. + expect(providerHealthPublicIdentity(opened).publicKeyHex).toBe( + providerHealthPublicIdentity(enrolled).publicKeyHex + ); + } finally { + closeSync(fd); + } + }); +}); + +describe("presence identity descriptor selection", () => { + const dir = os.tmpdir(); + + it("falls back to the path when systemd passed nothing", async () => { + // No LISTEN_FDNAMES means no Idunn: the ordinary self-enrolling path + // applies and must not be treated as an error. + const target = path.join(dir, `heimdall-no-fd-${process.pid}.cc`); + await expect( + openProviderHealthIdentity(target, {}, process.pid) + ).resolves.toBeDefined().catch(() => { + // On a host without a machine-id enrolment cannot succeed; the point is + // that it took the path branch rather than trying to read a descriptor. + }); + }); + + it("ignores descriptors addressed to another process", async () => { + // LISTEN_PID naming a different process means these descriptors are not + // ours. Consuming them would read a sibling's identity. + const target = path.join(dir, `heimdall-wrong-pid-${process.pid}.cc`); + await openProviderHealthIdentity( + target, + { LISTEN_FDNAMES: "gamecult-runtime-presence-identity", LISTEN_PID: String(process.pid + 1) }, + process.pid + ).catch((error) => { + // Either it enrolled via the path, or it failed for a machine-id reason. + // What must not happen is a descriptor read. + expect(String(error)).not.toContain("presence identity"); + }); + }); + + it("ignores a descriptor set that does not name the presence identity", async () => { + const target = path.join(dir, `heimdall-other-fd-${process.pid}.cc`); + await openProviderHealthIdentity( + target, + { LISTEN_FDNAMES: "some-other-credential", LISTEN_PID: String(process.pid) }, + process.pid + ).catch((error) => { + expect(String(error)).not.toContain("presence identity"); + }); + }); +});