diff --git a/packages/cultnet-rs/examples/runtime_presence_vector.rs b/packages/cultnet-rs/examples/runtime_presence_vector.rs new file mode 100644 index 00000000..04571a8b --- /dev/null +++ b/packages/cultnet-rs/examples/runtime_presence_vector.rs @@ -0,0 +1,67 @@ +//! Emit canonical bytes for one fixed runtime-presence record. +//! +//! This is the reference the TypeScript fork is tested against. The two forks +//! agree only if `gamecult.runtime_presence_health.v2` means the same bytes in +//! both, and the only way to know that is to have one produce the vector and +//! the other reproduce it. A fixture written by hand for both sides would agree +//! with itself and prove nothing. + +use cultnet_rs::{GameCultRuntimeCapability, GameCultRuntimePresenceHealthRecord}; + +fn main() -> anyhow::Result<()> { + let record = GameCultRuntimePresenceHealthRecord { + schema_version: "gamecult.runtime_presence_health.v2".into(), + target: "heimdall".into(), + expected_projection_sha256: format!("sha256-{}", "a".repeat(64)), + plan_id: format!("sha256-{}", "b".repeat(64)), + incarnation_id: "service-incarnation-1".into(), + sealed_release_id: format!("sha256-{}", "c".repeat(64)), + activation_witness_sha256: format!("sha256-{}", "d".repeat(64)), + state_schema_generation: Some("v1".into()), + state_contract_sha256: Some(format!("sha256-{}", "e".repeat(64))), + runtime_id: "heimdall-yggdrasil".into(), + runtime_instance_id: format!("sha256-{}", "f".repeat(64)), + bound_endpoint: Some("http://127.0.0.1:14101".into()), + capabilities: vec![ + GameCultRuntimeCapability { + capability: "heimdall.access".into(), + schema: "heimdall.access.v1".into(), + compatibility: "v1".into(), + capacity: 2, + }, + GameCultRuntimeCapability { + capability: "zeta.runtime".into(), + schema: "zeta.runtime.v1".into(), + compatibility: "v1".into(), + capacity: 1, + }, + ], + health_contract: "heimdall.cultnet-rudp-provider-health".into(), + state: "warming".into(), + detail: "Heimdall candidate warming".into(), + write_lease_sha256: None, + signer_identity_id: "1".repeat(64), + publisher_sequence: 7, + observed_at_unix_millis: 1_757_000_000_000, + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + activation_signer_identity_id: "2".repeat(64), + activation_signature: Vec::new(), + }; + + // The proof payload: both signature fields empty. This is what both keys + // sign, so it is the vector that matters most. + let proof = record.canonical_proof_payload()?; + println!("proof {}", hex(&proof)); + + // And the complete record, with both proofs filled, to pin the signed shape. + let mut signed = record; + signed.signature = vec![0x11; 64]; + signed.activation_signature = vec![0x22; 64]; + println!("signed {}", hex(&rmp_serde::to_vec(&signed)?)); + Ok(()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} diff --git a/packages/cultnet-ts/src/index.ts b/packages/cultnet-ts/src/index.ts index db24d17b..140526c5 100644 --- a/packages/cultnet-ts/src/index.ts +++ b/packages/cultnet-ts/src/index.ts @@ -156,3 +156,21 @@ export { type SignedDaemonHealthPublisher, type SignedDaemonHealthPublisherOptions, } from "./signed-daemon-health"; + +export { + GAMECULT_RUNTIME_ACTIVATION_PROOF_SIGNING_PURPOSE, + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE, + GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME, + IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, + RUNTIME_PRESENCE_FIELD_COUNT, + RUNTIME_PRESENCE_SLOT, + encodeRuntimePresenceHealth, + runtimePresenceActivationSigningMessage, + runtimePresenceProofPayload, + runtimePresenceProviderSigningMessage, + validateRuntimePresence, + type GameCultRuntimeCapability, + type RuntimePresenceHealth, + type RuntimePresenceState, +} from "./runtime-presence-health"; diff --git a/packages/cultnet-ts/src/runtime-presence-health.ts b/packages/cultnet-ts/src/runtime-presence-health.ts new file mode 100644 index 00000000..8d70da8e --- /dev/null +++ b/packages/cultnet-ts/src/runtime-presence-health.ts @@ -0,0 +1,256 @@ +// Runtime presence health: the dual-proved statement one launched incarnation +// makes about itself. +// +// This is the TypeScript half of `gamecult.runtime_presence_health.v2`, the +// contract `cultnet-rs` defines in `runtime_authority_contracts.rs`. Odin admits +// a document as runtime presence only when it carries this schema id and its +// record key equals the signed target; anything else it files away as an +// ordinary document, and no topology correlation is ever produced for it. +// +// Two proofs cover one payload. The stable provider key says "this service made +// this statement"; the activation key Idunn hands the process at launch says +// "and it is the incarnation Idunn started". Neither establishes admission +// alone, which is why both signature fields are empty in the signed bytes: it +// avoids a circular signature while binding every authority-bearing field and +// both signer identities. +// +// The wire shape is a positional tuple indexed by the same field slots the Rust +// derive emits. Field N here is field N there; that correspondence is the whole +// contract, and the constants below name the slots so it stays checkable. + +import { encode } from "@msgpack/msgpack"; + +export const GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA = "gamecult.runtime_presence_health.v2"; + +/** Purpose for the stable provider-health signature over the proof payload. */ +export const GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE = + "gamecult.runtime_presence_health.v2"; + +/** Purpose for the activation-scoped proof over the same payload. */ +export const GAMECULT_RUNTIME_ACTIVATION_PROOF_SIGNING_PURPOSE = + "gamecult.runtime_presence.activation-proof.v1"; + +/** systemd file-descriptor name Idunn uses for the activation signing key. */ +export const IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME = "gamecult-idunn-runtime-activation-key"; + +/** systemd file-descriptor name Idunn uses for the provider-health identity. */ +export const GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME = "gamecult-runtime-presence-identity"; + +const PROVIDER_HEALTH_SIGNATURE_DOMAIN = Buffer.from( + "gamecult.provider-health.signature.v1\0", + "utf8", +); + +const RUNTIME_ACTIVATION_SIGNATURE_DOMAIN = Buffer.from( + "idunn.runtime-activation.signature.v1\0", + "utf8", +); + +/** + * Positional slots, mirroring the `#[cultcache(key = N)]` attributes on + * `GameCultRuntimePresenceHealthRecord`. The tuple is always this long: the + * Rust derive serialises `max_slot + 1` elements regardless of which are set. + */ +export const RUNTIME_PRESENCE_SLOT = { + schemaVersion: 0, + target: 1, + expectedProjectionSha256: 2, + planId: 3, + incarnationId: 4, + sealedReleaseId: 5, + activationWitnessSha256: 6, + stateSchemaGeneration: 7, + stateContractSha256: 8, + runtimeId: 9, + runtimeInstanceId: 10, + boundEndpoint: 11, + capabilities: 12, + healthContract: 13, + state: 14, + detail: 15, + writeLeaseSha256: 16, + signerIdentityId: 17, + publisherSequence: 18, + observedAtUnixMillis: 19, + signatureAlgorithm: 20, + signature: 21, + activationSignerIdentityId: 22, + activationSignature: 23, +} as const; + +export const RUNTIME_PRESENCE_FIELD_COUNT = 24; + +/** A capability claim. Nested as its own positional tuple, not a map. */ +export interface GameCultRuntimeCapability { + capability: string; + schema: string; + compatibility: string; + capacity: number; +} + +/** The states the contract admits. */ +export type RuntimePresenceState = "warming" | "active" | "degraded" | "failed"; + +export interface RuntimePresenceHealth { + target: string; + expectedProjectionSha256: string; + planId: string; + incarnationId: string; + sealedReleaseId: string; + activationWitnessSha256: string; + stateSchemaGeneration: string | null; + stateContractSha256: string | null; + runtimeId: string; + runtimeInstanceId: string; + boundEndpoint: string | null; + capabilities: GameCultRuntimeCapability[]; + healthContract: string; + state: RuntimePresenceState; + detail: string; + writeLeaseSha256: string | null; + signerIdentityId: string; + publisherSequence: number; + observedAtUnixMillis: number; + activationSignerIdentityId: string; +} + +function encodeCapability(capability: GameCultRuntimeCapability): unknown[] { + // Plain serde struct on the Rust side, and the record is encoded with + // rmp_serde's compact form, so a capability is a positional tuple too. + return [capability.capability, capability.schema, capability.compatibility, capability.capacity]; +} + +/** + * Capabilities are canonical only when strictly increasing by + * `(capability, schema, compatibility)`. Sorting here rather than trusting the + * caller keeps a correct statement from being rejected over field order. + */ +function canonicalCapabilities(capabilities: GameCultRuntimeCapability[]): unknown[][] { + const sorted = [...capabilities].sort((left, right) => { + const leftKey = [left.capability, left.schema, left.compatibility]; + const rightKey = [right.capability, right.schema, right.compatibility]; + for (let index = 0; index < leftKey.length; index += 1) { + if (leftKey[index]! < rightKey[index]!) return -1; + if (leftKey[index]! > rightKey[index]!) return 1; + } + return 0; + }); + return sorted.map(encodeCapability); +} + +function presenceTuple( + presence: RuntimePresenceHealth, + signature: Uint8Array, + activationSignature: Uint8Array, +): unknown[] { + const fields = new Array(RUNTIME_PRESENCE_FIELD_COUNT); + fields[RUNTIME_PRESENCE_SLOT.schemaVersion] = GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA; + fields[RUNTIME_PRESENCE_SLOT.target] = presence.target; + fields[RUNTIME_PRESENCE_SLOT.expectedProjectionSha256] = presence.expectedProjectionSha256; + fields[RUNTIME_PRESENCE_SLOT.planId] = presence.planId; + fields[RUNTIME_PRESENCE_SLOT.incarnationId] = presence.incarnationId; + fields[RUNTIME_PRESENCE_SLOT.sealedReleaseId] = presence.sealedReleaseId; + fields[RUNTIME_PRESENCE_SLOT.activationWitnessSha256] = presence.activationWitnessSha256; + fields[RUNTIME_PRESENCE_SLOT.stateSchemaGeneration] = presence.stateSchemaGeneration; + fields[RUNTIME_PRESENCE_SLOT.stateContractSha256] = presence.stateContractSha256; + fields[RUNTIME_PRESENCE_SLOT.runtimeId] = presence.runtimeId; + fields[RUNTIME_PRESENCE_SLOT.runtimeInstanceId] = presence.runtimeInstanceId; + fields[RUNTIME_PRESENCE_SLOT.boundEndpoint] = presence.boundEndpoint; + fields[RUNTIME_PRESENCE_SLOT.capabilities] = canonicalCapabilities(presence.capabilities); + fields[RUNTIME_PRESENCE_SLOT.healthContract] = presence.healthContract; + fields[RUNTIME_PRESENCE_SLOT.state] = presence.state; + fields[RUNTIME_PRESENCE_SLOT.detail] = presence.detail; + fields[RUNTIME_PRESENCE_SLOT.writeLeaseSha256] = presence.writeLeaseSha256; + fields[RUNTIME_PRESENCE_SLOT.signerIdentityId] = presence.signerIdentityId; + fields[RUNTIME_PRESENCE_SLOT.publisherSequence] = presence.publisherSequence; + fields[RUNTIME_PRESENCE_SLOT.observedAtUnixMillis] = presence.observedAtUnixMillis; + fields[RUNTIME_PRESENCE_SLOT.signatureAlgorithm] = "ed25519"; + fields[RUNTIME_PRESENCE_SLOT.signature] = signature; + fields[RUNTIME_PRESENCE_SLOT.activationSignerIdentityId] = presence.activationSignerIdentityId; + fields[RUNTIME_PRESENCE_SLOT.activationSignature] = activationSignature; + return fields; +} + +/** + * Reject statements the contract forbids, before they are signed. + * + * These are the same conditions `validate_shape` enforces on the Rust side. A + * statement that fails here would be refused after a round trip and a signature; + * failing early names the actual problem instead. + */ +export function validateRuntimePresence(presence: RuntimePresenceHealth): void { + if (presence.publisherSequence <= 0 || !Number.isSafeInteger(presence.publisherSequence)) { + throw new Error("runtime presence publisher sequence must be a positive integer"); + } + if (presence.observedAtUnixMillis <= 0 || !Number.isSafeInteger(presence.observedAtUnixMillis)) { + throw new Error("runtime presence observation time must be a positive integer"); + } + if (presence.detail.length > 512 || /\p{Cc}/u.test(presence.detail)) { + throw new Error("runtime presence detail is too long or carries control characters"); + } + if (presence.state === "warming" && presence.writeLeaseSha256 !== null) { + throw new Error("warming runtime presence cannot claim a process write lease"); + } + if (presence.stateSchemaGeneration === null && presence.writeLeaseSha256 !== null) { + throw new Error("stateless runtime presence cannot claim a process write lease"); + } + const generationPresent = presence.stateSchemaGeneration !== null; + const contractPresent = presence.stateContractSha256 !== null; + if (generationPresent !== contractPresent) { + throw new Error("runtime presence state lineage is partial"); + } +} + +/** + * The one payload both proofs cover: the complete record with both signature + * fields empty. + */ +export function runtimePresenceProofPayload(presence: RuntimePresenceHealth): Uint8Array { + validateRuntimePresence(presence); + return encode(presenceTuple(presence, new Uint8Array(), new Uint8Array())); +} + +/** The complete signed record, as put on the wire. */ +export function encodeRuntimePresenceHealth( + presence: RuntimePresenceHealth, + signature: Uint8Array, + activationSignature: Uint8Array, +): Uint8Array { + if (signature.length !== 64 || activationSignature.length !== 64) { + throw new Error("runtime presence proofs must both be 64-byte ed25519 signatures"); + } + validateRuntimePresence(presence); + return encode(presenceTuple(presence, signature, activationSignature)); +} + +function domainSeparated(domain: Buffer, purpose: string, payload: Uint8Array): Buffer { + const purposeBytes = Buffer.from(purpose, "utf8"); + const lengths = Buffer.alloc(16); + lengths.writeBigUInt64BE(BigInt(purposeBytes.length), 0); + lengths.writeBigUInt64BE(BigInt(payload.length), 8); + return Buffer.concat([ + domain, + lengths.subarray(0, 8), + purposeBytes, + lengths.subarray(8, 16), + Buffer.from(payload), + ]); +} + +/** Message the stable provider-health key signs. */ +export function runtimePresenceProviderSigningMessage(payload: Uint8Array): Buffer { + return domainSeparated( + PROVIDER_HEALTH_SIGNATURE_DOMAIN, + GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE, + payload, + ); +} + +/** Message the activation key Idunn passed at launch signs. */ +export function runtimePresenceActivationSigningMessage(payload: Uint8Array): Buffer { + return domainSeparated( + RUNTIME_ACTIVATION_SIGNATURE_DOMAIN, + GAMECULT_RUNTIME_ACTIVATION_PROOF_SIGNING_PURPOSE, + payload, + ); +} diff --git a/packages/cultnet-ts/test/fixtures/runtime-presence-vectors.json b/packages/cultnet-ts/test/fixtures/runtime-presence-vectors.json new file mode 100644 index 00000000..043689f4 --- /dev/null +++ b/packages/cultnet-ts/test/fixtures/runtime-presence-vectors.json @@ -0,0 +1,4 @@ +{ + "proof": "dc0018d92367616d6563756c742e72756e74696d655f70726573656e63655f6865616c74682e7632a86865696d64616c6cd9477368613235362d61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161d9477368613235362d62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262b5736572766963652d696e6361726e6174696f6e2d31d9477368613235362d63636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363d9477368613235362d64646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a27631d9477368613235362d65656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565b26865696d64616c6c2d79676764726173696cd9477368613235362d66666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666b6687474703a2f2f3132372e302e302e313a31343130319294af6865696d64616c6c2e616363657373b26865696d64616c6c2e6163636573732e7631a276310294ac7a6574612e72756e74696d65af7a6574612e72756e74696d652e7631a2763101d9256865696d64616c6c2e63756c746e65742d727564702d70726f76696465722d6865616c7468a77761726d696e67ba4865696d64616c6c2063616e646964617465207761726d696e67c0d9403131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313107cf00000199155c6200a765643235353139c400d94032323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232c400", + "signed": "dc0018d92367616d6563756c742e72756e74696d655f70726573656e63655f6865616c74682e7632a86865696d64616c6cd9477368613235362d61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161d9477368613235362d62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262b5736572766963652d696e6361726e6174696f6e2d31d9477368613235362d63636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363d9477368613235362d64646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a27631d9477368613235362d65656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565b26865696d64616c6c2d79676764726173696cd9477368613235362d66666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666b6687474703a2f2f3132372e302e302e313a31343130319294af6865696d64616c6c2e616363657373b26865696d64616c6c2e6163636573732e7631a276310294ac7a6574612e72756e74696d65af7a6574612e72756e74696d652e7631a2763101d9256865696d64616c6c2e63756c746e65742d727564702d70726f76696465722d6865616c7468a77761726d696e67ba4865696d64616c6c2063616e646964617465207761726d696e67c0d9403131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313107cf00000199155c6200a765643235353139c44011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111d94032323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232c44022222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222" +} diff --git a/packages/cultnet-ts/test/runtime-presence-health.test.ts b/packages/cultnet-ts/test/runtime-presence-health.test.ts new file mode 100644 index 00000000..fa21aeaa --- /dev/null +++ b/packages/cultnet-ts/test/runtime-presence-health.test.ts @@ -0,0 +1,123 @@ +// Cross-fork conformance for `gamecult.runtime_presence_health.v2`. +// +// The vectors below were produced by `cultnet-rs`, not written by hand: +// +// cargo run --example runtime_presence_vector -p cultnet-rs +// +// That matters. A fixture authored for both sides at once agrees with itself +// and proves nothing; the contract is only real if one fork emits the bytes and +// the other reproduces them. Regenerate these vectors from the Rust example if +// the record ever changes, and never by editing them to match this code. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { + RUNTIME_PRESENCE_FIELD_COUNT, + encodeRuntimePresenceHealth, + runtimePresenceProofPayload, + validateRuntimePresence, + type RuntimePresenceHealth, +} from "../src/runtime-presence-health"; + +// Read from the source tree, not a copy beside the compiled test: the vectors +// are generated output and must have exactly one home. +const VECTORS = JSON.parse( + readFileSync( + join(__dirname, "..", "..", "test", "fixtures", "runtime-presence-vectors.json"), + "utf8", + ), +) as { proof: string; signed: string }; + +/** The same statement the Rust example builds. */ +function referencePresence(): RuntimePresenceHealth { + return { + target: "heimdall", + expectedProjectionSha256: `sha256-${"a".repeat(64)}`, + planId: `sha256-${"b".repeat(64)}`, + incarnationId: "service-incarnation-1", + sealedReleaseId: `sha256-${"c".repeat(64)}`, + activationWitnessSha256: `sha256-${"d".repeat(64)}`, + stateSchemaGeneration: "v1", + stateContractSha256: `sha256-${"e".repeat(64)}`, + runtimeId: "heimdall-yggdrasil", + runtimeInstanceId: `sha256-${"f".repeat(64)}`, + boundEndpoint: "http://127.0.0.1:14101", + capabilities: [ + { + capability: "heimdall.access", + schema: "heimdall.access.v1", + compatibility: "v1", + capacity: 2, + }, + { capability: "zeta.runtime", schema: "zeta.runtime.v1", compatibility: "v1", capacity: 1 }, + ], + healthContract: "heimdall.cultnet-rudp-provider-health", + state: "warming", + detail: "Heimdall candidate warming", + writeLeaseSha256: null, + signerIdentityId: "1".repeat(64), + publisherSequence: 7, + observedAtUnixMillis: 1_757_000_000_000, + activationSignerIdentityId: "2".repeat(64), + }; +} + +function hex(bytes: Uint8Array): string { + return Buffer.from(bytes).toString("hex"); +} + +test("the proof payload is byte-identical to the one cultnet-rs signs", () => { + assert.equal(hex(runtimePresenceProofPayload(referencePresence())), VECTORS.proof); +}); + +test("the signed record carries both proofs in their own slots", () => { + const signed = encodeRuntimePresenceHealth( + referencePresence(), + new Uint8Array(64).fill(0x11), + new Uint8Array(64).fill(0x22), + ); + // Byte-identical to the fully signed record cultnet-rs emits, so the proofs + // land in their own slots rather than being appended. + assert.equal(hex(signed), VECTORS.signed); +}); + +test("capabilities are ordered canonically regardless of caller order", () => { + const presence = referencePresence(); + const reversed = { ...presence, capabilities: [...presence.capabilities].reverse() }; + assert.equal( + hex(runtimePresenceProofPayload(reversed)), + hex(runtimePresenceProofPayload(presence)), + ); +}); + +test("the tuple is always the full contract width", () => { + assert.equal(RUNTIME_PRESENCE_FIELD_COUNT, 24); +}); + +test("statements the contract forbids are refused before they are signed", () => { + const warmingWithLease = { + ...referencePresence(), + writeLeaseSha256: `sha256-${"0".repeat(64)}`, + }; + assert.throws(() => validateRuntimePresence(warmingWithLease), /cannot claim a process write/); + + const statelessWithLease = { + ...referencePresence(), + state: "active" as const, + stateSchemaGeneration: null, + stateContractSha256: null, + writeLeaseSha256: `sha256-${"0".repeat(64)}`, + }; + assert.throws(() => validateRuntimePresence(statelessWithLease), /stateless runtime presence/); + + assert.throws( + () => validateRuntimePresence({ ...referencePresence(), publisherSequence: 0 }), + /publisher sequence/, + ); + + const partialLineage = { ...referencePresence(), stateContractSha256: null }; + assert.throws(() => validateRuntimePresence(partialLineage), /state lineage is partial/); +});