Heimdall/src/provider-health-identity.ts
Meta Vens c044155855 Heimdall opens its Idunn presence authority once, before it listens
index.ts declared the presence sequence below the startup try, so the bundle's
hoisted var was undefined at the first publish; decodePrivateIdentity refused the
Rust owner's integer-array key fields; both descriptors were re-read every pulse and
returned nothing after the first. openPresenceAuthority now reads the bundle facts and
each descriptor once (whole, from offset 0, then closed), owns the one publisher
sequence, and signs through them; a launch-contract fault throws before anything
listens, so the process exits non-zero. decodePrivateIdentity takes the shape of its
source and names the failed check, never a value. openActivationSigner and the
per-pulse descriptor reads are deleted.

tests/idunn-boot.test.ts boots the bundle under the Idunn launch contract and checks
the signed warming frames and the fail-fast exits. The descriptor, sequence and
generation tests now use the Rust-written fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:48:08 +02:00

305 lines
12 KiB
TypeScript

import { decode, encode } from "@msgpack/msgpack";
import {
createHash,
createPrivateKey,
createPublicKey,
randomBytes,
sign,
type KeyObject,
} from "node:crypto";
import { closeSync, fstatSync, readSync } from "node:fs";
import { chmod, readFile } from "node:fs/promises";
import { SingleFileMessagePackBackingStore, type CultCacheEnvelope } from "@gamecult/cultcache-ts";
import { readPrivateStoreRecord } from "./idunn-store.js";
const PRIVATE_SCHEMA = "gamecult.provider_health_identity.private.v1";
const PRIVATE_KEY = "gamecult-provider-health-identity";
const ID_DOMAIN = Buffer.from("gamecult.provider-health.identity.v1\0");
const SIGNATURE_DOMAIN = Buffer.from("gamecult.provider-health.signature.v1\0");
const SIGNING_PURPOSE = Buffer.from("idunn.signed_daemon_health.v1");
const PROTECTOR_CONTEXT = "gamecult-provider-health-identity-v1";
const PKCS8_ED25519_SEED_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
export type PrivateIdentity = {
identityId: string;
publicKey: Uint8Array;
privateKey: KeyObject;
};
export async function openOrEnrollProviderHealthIdentity(path: string): Promise<PrivateIdentity> {
const store = new SingleFileMessagePackBackingStore(path);
const existing = await store.pullAll();
if (existing.length === 0) {
const seed = randomBytes(32);
const privateKey = privateKeyFromSeed(seed);
const publicKey = rawPublicKey(privateKey);
const identityId = deriveIdentityId(publicKey);
const machineId = await readMachineId();
const binding = protectorBinding(machineId);
const protectedSeed = xorSeed(seed, binding);
const createdAt = new Date().toISOString();
const payload = encode([
PRIVATE_SCHEMA,
identityId,
publicKey,
protectedSeed,
"linux_file_mode_machine_id_binding",
binding,
"v1",
"os_installation_file_bound_cloneable_baseline",
createdAt,
randomBytes(32),
]);
const envelope: CultCacheEnvelope = {
key: PRIVATE_KEY,
type: PRIVATE_SCHEMA,
schemaId: PRIVATE_SCHEMA,
storedAt: createdAt,
payload,
catalogEntry: {
schemaId: PRIVATE_SCHEMA,
schemaName: PRIVATE_SCHEMA,
schemaVersion: "1",
contentHash: createHash("sha256").update(PRIVATE_SCHEMA).digest("hex"),
canonicalSchemaJson: JSON.stringify({ title: PRIVATE_SCHEMA, type: "array" }),
},
};
await store.push(envelope);
await chmod(path, 0o600);
return { identityId, publicKey, privateKey };
}
if (existing.length !== 1) {
throw new Error("Provider-health identity store must contain exactly one record.");
}
return decodePrivateIdentity(existing[0]!.payload, await readMachineId(), "bin");
}
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.
*/
export function passedDescriptor(
descriptorName: string,
env: NodeJS.ProcessEnv
): number | undefined {
const names = env.LISTEN_FDNAMES;
if (!names) {
return undefined;
}
// LISTEN_PID cannot be compared to our own pid. Idunn launches candidates
// with PrivatePIDs=yes, and systemd sets LISTEN_PID to the pid it knows,
// which is in the *outer* namespace; inside, process.pid is the
// namespace-local one. The comparison could never hold, and because this
// function answers "undefined" rather than throwing, the caller quietly
// enrolled a self-signed identity instead -- exactly the failure the next
// doc comment warns about, and one that shows up only as health nobody
// admits. What identifies the descriptor is its name in LISTEN_FDNAMES.
const index = names.split(":").indexOf(descriptorName);
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,
machineId: () => Promise<string> = readMachineId
): Promise<PrivateIdentity> {
const descriptor = passedDescriptor(PRESENCE_IDENTITY_FD_NAME, env);
if (descriptor === undefined) {
if (env.GAMECULT_IDUNN_RUNTIME_BUNDLE) {
// Inside an Idunn generation a self-enrolled key is one Idunn does not
// trust, and its private store would land in a state root the next
// generation must share. The descriptor is the only identity there.
throw new Error(
`Idunn runtime bundle is set but the ${PRESENCE_IDENTITY_FD_NAME} descriptor was not passed; refusing to self-enroll`
);
}
return openOrEnrollProviderHealthIdentity(path);
}
const payload = readPrivateStoreRecord(
readPassedDescriptor(descriptor),
"Idunn runtime presence identity"
);
// The descriptor's writer is the Rust owner, whose key fields are integer arrays.
return decodePrivateIdentity(payload, await machineId(), "int-array");
}
/**
* Read a passed descriptor whole, from offset 0, and close it. A descriptor is
* a one-shot input: reading it again starts at the offset the last read left,
* which is the end, so the owner reads once at open and keeps what it decoded.
*/
export function readPassedDescriptor(descriptor: number): Buffer {
try {
const size = fstatSync(descriptor).size;
const bytes = Buffer.alloc(size);
let read = 0;
while (read < size) {
const count = readSync(descriptor, bytes, read, size - read, read);
if (count === 0) break;
read += count;
}
return bytes.subarray(0, read);
} finally {
closeSync(descriptor);
}
}
export function signProviderHealthPayload(identity: PrivateIdentity, payload: Uint8Array): Uint8Array {
const message = Buffer.concat([
SIGNATURE_DOMAIN,
u64be(SIGNING_PURPOSE.length),
SIGNING_PURPOSE,
u64be(payload.length),
payload,
]);
return sign(null, message, identity.privateKey);
}
/**
* Sign an already domain-separated message with this identity.
*
* The domain and purpose belong to the contract being signed, not to the key,
* so they are built by the caller from the shared CultNet helpers rather than
* assumed here.
*/
export function signWithIdentity(identity: PrivateIdentity, message: Buffer): Uint8Array {
return sign(null, message, identity.privateKey);
}
export function providerHealthPublicIdentity(identity: PrivateIdentity): {
identityId: string;
publicKeyHex: string;
} {
return { identityId: identity.identityId, publicKeyHex: Buffer.from(identity.publicKey).toString("hex") };
}
/**
* Which writer produced the record. The self-enrolling store this process
* writes keeps key fields as MessagePack bin; the Rust owner (cultnet-rs
* service_identity.rs) serialises a Vec<u8> without serde_bytes, so its key
* fields are arrays of integers. Each source is read in its own shape and the
* other is refused.
*/
type KeyShape = "bin" | "int-array";
function keyBytes(value: unknown, shape: KeyShape, field: string): Uint8Array {
const bytes =
shape === "bin"
? value instanceof Uint8Array
? value
: undefined
: Array.isArray(value) &&
value.every((byte) => typeof byte === "number" && Number.isInteger(byte) && byte >= 0 && byte <= 255)
? Uint8Array.from(value as number[])
: undefined;
if (bytes === undefined || bytes.length !== 32) {
throw new Error(
`Provider-health identity key shape check failed: ${field} is not a 32-byte ${shape === "bin" ? "binary" : "integer-array"} key field.`
);
}
return bytes;
}
function decodePrivateIdentity(payload: Uint8Array, machineId: string, shape: KeyShape): PrivateIdentity {
const value = decode(payload);
if (!Array.isArray(value) || value.length !== 10) {
throw new Error("Provider-health identity schema check failed: payload is not a 10-field record.");
}
const [schema, identityId, publicKeyField, protectedSeedField, protector, binding, version] = value;
if (schema !== PRIVATE_SCHEMA) {
throw new Error("Provider-health identity schema check failed: unexpected schema id.");
}
if (typeof identityId !== "string") {
throw new Error("Provider-health identity id check failed: id is not a string.");
}
const publicKey = keyBytes(publicKeyField, shape, "public key");
const protectedSeed = keyBytes(protectedSeedField, shape, "protected seed");
if (protector !== "linux_file_mode_machine_id_binding") {
throw new Error("Provider-health identity protector check failed: unexpected protector.");
}
if (binding !== protectorBinding(machineId)) {
throw new Error("Provider-health identity binding check failed: not bound to this host's machine id.");
}
if (version !== "v1") {
throw new Error("Provider-health identity version check failed: unexpected version.");
}
if (identityId !== deriveIdentityId(publicKey)) {
throw new Error("Provider-health identity id check failed: id does not derive from the public key.");
}
const seed = xorSeed(protectedSeed, binding);
const privateKey = privateKeyFromSeed(seed);
if (!rawPublicKey(privateKey).equals(Buffer.from(publicKey))) {
throw new Error("Provider-health private seed does not match its public key.");
}
return { identityId, publicKey, privateKey };
}
async function readMachineId(): Promise<string> {
for (const path of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
try {
const value = (await readFile(path, "utf8")).trim();
if (value) return value;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
}
throw new Error("Linux machine-id is unavailable.");
}
function protectorBinding(machineId: string): string {
return `${PROTECTOR_CONTEXT}:machine-id-sha256:${createHash("sha256").update(machineId).digest("hex")}`;
}
function xorSeed(seed: Uint8Array, binding: string): Buffer {
const mask = createHash("sha256")
.update(Buffer.from("gamecult-linux-service-seed-v1\0"))
.update(PROTECTOR_CONTEXT)
.update(binding)
.digest();
return Buffer.from(seed.map((byte, index) => byte ^ mask[index]!));
}
function deriveIdentityId(publicKey: Uint8Array): string {
return createHash("sha256").update(ID_DOMAIN).update(publicKey).digest("hex");
}
function privateKeyFromSeed(seed: Uint8Array): KeyObject {
return createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_SEED_PREFIX, seed]), format: "der", type: "pkcs8" });
}
function rawPublicKey(privateKey: KeyObject): Buffer {
const der = createPublicKey(privateKey).export({ format: "der", type: "spki" });
return Buffer.from(der.subarray(der.length - 32));
}
function u64be(value: number): Buffer {
const output = Buffer.alloc(8);
output.writeBigUInt64BE(BigInt(value));
return output;
}