Steward cut 4: export declarative ENV_NAMES/SECRET_ENV_NAMES and trim recipe/entrypoint secret tests
This commit is contained in:
parent
b5c4e46e28
commit
509bf3a856
3 changed files with 164 additions and 422 deletions
|
|
@ -49,6 +49,53 @@ export interface HeimdallConfig {
|
|||
providers: Record<Provider, ProviderClientConfig>;
|
||||
}
|
||||
|
||||
/** Secret inputs read via `readSecretInput` (as `NAME_FILE` under Idunn, or legacy plaintext `NAME`). */
|
||||
export const SECRET_ENV_NAMES: readonly string[] = [
|
||||
"GC_ACCESS_DATABASE_URL",
|
||||
"GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64",
|
||||
"GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET",
|
||||
...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`),
|
||||
...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`),
|
||||
];
|
||||
|
||||
const NON_SECRET_ENV_NAMES: readonly string[] = [
|
||||
"HOST",
|
||||
"PORT",
|
||||
"GAMECULT_IDUNN_CANDIDATE_BIND",
|
||||
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
|
||||
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
||||
"GC_ACCESS_BASE_URL",
|
||||
"GC_ACCESS_ISSUER",
|
||||
"GC_ACCESS_DATA_ROOT",
|
||||
"GC_ACCESS_STORAGE_BACKEND",
|
||||
"GC_ACCESS_PRIVATE_COMMAND_HOST",
|
||||
"GC_ACCESS_PRIVATE_COMMAND_PORT",
|
||||
"GC_ACCESS_CULTCACHE_PATH",
|
||||
"GC_ACCESS_IDUNN_DAEMON",
|
||||
"GC_ACCESS_IDUNN_RUDP_HEALTH",
|
||||
"GC_ACCESS_IDUNN_HEALTH_CONTRACT",
|
||||
"GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH",
|
||||
"GC_ACCESS_SESSION_TTL_SECONDS",
|
||||
"GC_ACCESS_REFRESH_TTL_SECONDS",
|
||||
"GC_ACCESS_STATE_TTL_SECONDS",
|
||||
"GC_ACCESS_COMPLETION_TTL_SECONDS",
|
||||
"GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP",
|
||||
"GC_ACCESS_APPLY_SCHEMA_ON_STARTUP",
|
||||
"GC_ACCESS_ODIN_CULTMESH_URI",
|
||||
"GC_ACCESS_SIGNING_PRIVATE_KEY_PATH",
|
||||
"GC_ACCESS_SIGNING_KEY_ID",
|
||||
"GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT",
|
||||
...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_ID`),
|
||||
...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_BACKEND_CALLBACK_URLS`),
|
||||
...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_RUNTIME_IDS`),
|
||||
];
|
||||
|
||||
/** Canonical environment variable names read by `loadConfig` (using `*_FILE` for secrets). */
|
||||
export const ENV_NAMES: readonly string[] = [
|
||||
...NON_SECRET_ENV_NAMES,
|
||||
...SECRET_ENV_NAMES.map((name) => `${name}_FILE`),
|
||||
];
|
||||
|
||||
function trimTrailingSlash(value: string): string {
|
||||
return value.replace(/\/+$/, "");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,65 +1,35 @@
|
|||
import { spawn } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
|
||||
// A secret must never reach a terminal. Under Idunn, Heimdall's stderr goes to
|
||||
// the journal and the install script tails the journal to the operator's
|
||||
// terminal, so the layer that matters is the process's own output, not an
|
||||
// error's message. These cases run the real entrypoint with canary values in
|
||||
// the places a misbinding puts secrets, and fail on any byte of the canary
|
||||
// anywhere on stdout or stderr: in a message, an error cause, an error
|
||||
// property, or anything else Node chooses to print.
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("..", import.meta.url));
|
||||
const tsxCli = createRequire(import.meta.url).resolve("tsx/cli");
|
||||
const scratch = mkdtempSync(join(tmpdir(), "heimdall-entrypoint-"));
|
||||
chmodSync(scratch, 0o755);
|
||||
const CANARY = "CANARY";
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function file(name: string, contents: string): string {
|
||||
const path = join(scratch, name);
|
||||
writeFileSync(path, contents);
|
||||
return path;
|
||||
function secretFile(name: string, contents: string): string {
|
||||
const filePath = join(scratch, name);
|
||||
writeFileSync(filePath, contents);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
interface Run {
|
||||
code: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
output: string;
|
||||
function canaryTokenKey(): string {
|
||||
return `${CANARY}key`.padEnd(43, "A") + "=";
|
||||
}
|
||||
|
||||
interface Identity {
|
||||
uid: number;
|
||||
gid: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who can be denied a read. Root reads a mode-000 file, so a read failure is
|
||||
* only reachable as another user: the process itself when it is not root, or
|
||||
* else the checkout's owner, who can still load the entrypoint. A string is
|
||||
* the reason no such user exists here.
|
||||
*/
|
||||
function nonRootReader(): Identity | "self" | string {
|
||||
if (process.platform === "win32") return "file modes do not deny reads on Windows";
|
||||
if (process.getuid?.() !== 0) return "self";
|
||||
const owner = statSync(repoRoot);
|
||||
if (owner.uid === 0) return "running as root in a root-owned checkout, so no other user can load the entrypoint";
|
||||
return { uid: owner.uid, gid: owner.gid };
|
||||
}
|
||||
|
||||
/** Runs `tsx src/index.ts` with only the given environment, merging stdout and stderr. */
|
||||
function runEntrypoint(name: string, env: Record<string, string>, identity?: Identity): Promise<Run> {
|
||||
function runEntrypoint(name: string, env: Record<string, string>): Promise<{ code: number | null; signal: NodeJS.Signals | null; output: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [tsxCli, "src/index.ts"], {
|
||||
cwd: repoRoot,
|
||||
...identity,
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
HOME: scratch,
|
||||
|
|
@ -73,7 +43,6 @@ function runEntrypoint(name: string, env: Record<string, string>, identity?: Ide
|
|||
let output = "";
|
||||
child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
|
||||
child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
|
||||
// A case that fails to fail would start serving; stop it rather than hang.
|
||||
const timer = setTimeout(() => child.kill("SIGKILL"), 30_000);
|
||||
child.on("error", reject);
|
||||
child.on("close", (code, signal) => {
|
||||
|
|
@ -83,171 +52,81 @@ function runEntrypoint(name: string, env: Record<string, string>, identity?: Ide
|
|||
});
|
||||
}
|
||||
|
||||
/** A base64 value that decodes to exactly 32 bytes and still carries the canary. */
|
||||
function canaryTokenKey(tag: string): string {
|
||||
return `${CANARY}${tag}`.padEnd(43, "A") + "=";
|
||||
}
|
||||
|
||||
interface Case {
|
||||
name: string;
|
||||
env: () => Record<string, string>;
|
||||
/** Something the failure must say, so a case cannot pass by never reaching its path. */
|
||||
expect: RegExp;
|
||||
/** Run the entrypoint as a user a file mode can refuse. */
|
||||
nonRoot?: true;
|
||||
}
|
||||
|
||||
const cases: Case[] = [
|
||||
{
|
||||
name: "a URL bound into an absolute _FILE slot",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: `/postgres://heimdall:${CANARY}url@db/heimdall` }),
|
||||
expect: /GC_ACCESS_DATABASE_URL_FILE could not be read \(ENOENT\)/,
|
||||
},
|
||||
{
|
||||
name: "a _FILE path under a regular file",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: join(file("plain", "x"), `${CANARY}notdir`) }),
|
||||
expect: /GC_ACCESS_DATABASE_URL_FILE could not be read \(ENOTDIR\)/,
|
||||
},
|
||||
{
|
||||
name: "a secret bound into a relative _FILE slot",
|
||||
env: () => ({ GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: `${CANARY}relative-secret` }),
|
||||
expect: /GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE is not an absolute path/,
|
||||
},
|
||||
{
|
||||
name: "a secret bound both ways",
|
||||
env: () => ({
|
||||
GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET: `${CANARY}plain`,
|
||||
GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE: file("both", `${CANARY}file\n`),
|
||||
}),
|
||||
expect: /GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET and GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE are both set/,
|
||||
},
|
||||
{
|
||||
name: "a blank secret file",
|
||||
env: () => ({ GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE: join(scratch, "blank") }),
|
||||
expect: /GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE is empty/,
|
||||
},
|
||||
{
|
||||
name: "a token key that decodes short",
|
||||
env: () => ({ GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: file("short-key", `${CANARY}shortkey\n`) }),
|
||||
expect: /GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE must decode to exactly 32 bytes/,
|
||||
},
|
||||
{
|
||||
name: "a database URL with an unusable port",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-port", `postgres://heimdall:${CANARY}port@db:notaport/heimdall\n`) }),
|
||||
expect: /Postgres storage could not be prepared \(ERR_INVALID_URL\)/,
|
||||
},
|
||||
{
|
||||
name: "a database URL that does not parse",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-parse", `postgres://heimdall:${CANARY} parse@[bad/heimdall\n`) }),
|
||||
expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/,
|
||||
},
|
||||
{
|
||||
name: "a database URL with a broken percent escape",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-percent", `postgres://heimdall:${CANARY}%zz@127.0.0.1:1/heimdall\n`) }),
|
||||
expect: /Postgres storage could not be prepared \(ECONNREFUSED\)/,
|
||||
},
|
||||
{
|
||||
name: "a database that refuses the connection",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-refused", `postgres://heimdall:${CANARY}refused@127.0.0.1:1/heimdall\n`) }),
|
||||
expect: /Postgres storage could not be prepared \(ECONNREFUSED\)/,
|
||||
},
|
||||
{
|
||||
// A password holding an unescaped delimiter moves part of it into the
|
||||
// host, and the resolver's error names the host.
|
||||
name: "a database host that does not resolve",
|
||||
env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-host", `postgres://heimdall:pw@${CANARY}host.invalid/heimdall\n`) }),
|
||||
expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/,
|
||||
},
|
||||
{
|
||||
// A start that does not apply the schema still connects, so a misbound URL
|
||||
// fails at startup rather than in a request's error answer.
|
||||
name: "a database host that does not resolve, on a start that does not apply the schema",
|
||||
env: () => ({
|
||||
GC_ACCESS_APPLY_SCHEMA_ON_STARTUP: "0",
|
||||
GC_ACCESS_DATABASE_URL_FILE: file("db-host-noapply", `postgres://heimdall:pw@${CANARY}host.invalid/heimdall\n`),
|
||||
}),
|
||||
expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/,
|
||||
},
|
||||
{
|
||||
name: "private key text bound to the signing key path",
|
||||
env: () => ({
|
||||
GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: `-----BEGIN PRIVATE KEY-----\n${CANARY}pem\n-----END PRIVATE KEY-----\n`,
|
||||
}),
|
||||
expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH is not an absolute path/,
|
||||
},
|
||||
{
|
||||
name: "a signing key path that names no file",
|
||||
env: () => ({ GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: join(scratch, `${CANARY}missing-key`) }),
|
||||
expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH names no file \(ENOENT\)/,
|
||||
},
|
||||
{
|
||||
name: "a signing key file that is not a key",
|
||||
env: () => ({ GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: file("not-a-key", `${CANARY}notakey\n`) }),
|
||||
expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH does not hold a usable private key/,
|
||||
},
|
||||
{
|
||||
name: "a signing key file its reader may not read",
|
||||
env: () => {
|
||||
const key = file(`${CANARY}locked-key`, `${CANARY}pem\n`);
|
||||
chmodSync(key, 0o000);
|
||||
const dataRoot = join(scratch, "locked-key-data");
|
||||
mkdirSync(dataRoot, { recursive: true });
|
||||
chmodSync(dataRoot, 0o777);
|
||||
return { GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: key, GC_ACCESS_DATA_ROOT: dataRoot };
|
||||
},
|
||||
expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be read \(EACCES\)/,
|
||||
nonRoot: true,
|
||||
},
|
||||
{
|
||||
name: "a signing key path that is a directory",
|
||||
env: () => {
|
||||
const dir = join(scratch, "key-dir");
|
||||
mkdirSync(dir, { recursive: true });
|
||||
return { GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: dir };
|
||||
},
|
||||
expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be read \(EISDIR\)/,
|
||||
},
|
||||
{
|
||||
name: "a bootstrapped signing key whose directory cannot be created",
|
||||
env: () => ({
|
||||
GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: join(file("key-parent", "x"), `${CANARY}dir`, "key.pem"),
|
||||
GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP: "1",
|
||||
}),
|
||||
expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be created \(ENOTDIR\)/,
|
||||
},
|
||||
{
|
||||
// Every secret is configured and valid, and startup fails afterwards, in
|
||||
// the entrypoint's own catch: the one place that holds the whole config.
|
||||
name: "a listen failure with every secret configured",
|
||||
env: () => ({
|
||||
describe("entrypoint startup and secret redaction smoke checks", () => {
|
||||
it("startup failure redacts configured secrets from stdout and stderr", async () => {
|
||||
const run = await runEntrypoint("redact", {
|
||||
HOST: "203.0.113.1",
|
||||
GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: file("listen-key", `${canaryTokenKey("key")}\n`),
|
||||
GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE: file("listen-patron", `${CANARY}patron\n`),
|
||||
GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE: file("listen-github", `${CANARY}github\n`),
|
||||
GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: file("listen-bifrost", `${CANARY}bifrost\n`),
|
||||
}),
|
||||
expect: /Heimdall failed to start/,
|
||||
},
|
||||
];
|
||||
GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("token-key", `${canaryTokenKey()}\n`),
|
||||
GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("bifrost-secret", `${CANARY}bifrost\n`),
|
||||
GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE: secretFile("github-secret", `${CANARY}github\n`),
|
||||
});
|
||||
|
||||
describe("the entrypoint never prints a secret", () => {
|
||||
writeFileSync(join(scratch, "blank"), " \n");
|
||||
// mkdtemp makes the scratch directory private to its creator; a non-root
|
||||
// reader must still reach the files a case names inside it.
|
||||
chmodSync(scratch, 0o755);
|
||||
const reader = nonRootReader();
|
||||
expect(run.signal).toBeNull();
|
||||
expect(run.code).not.toBe(0);
|
||||
expect(run.output).toMatch(/Heimdall failed to start/);
|
||||
expect(run.output).not.toContain(CANARY);
|
||||
}, 45_000);
|
||||
|
||||
for (const testCase of cases) {
|
||||
const skipReason = testCase.nonRoot && typeof reader === "string" && reader !== "self" ? reader : undefined;
|
||||
const title = `refuses ${testCase.name} without printing the canary${skipReason ? ` (skipped: ${skipReason})` : ""}`;
|
||||
it.skipIf(skipReason !== undefined)(title, async () => {
|
||||
const identity = testCase.nonRoot && typeof reader === "object" ? reader : undefined;
|
||||
const run = await runEntrypoint(testCase.name.replace(/\W+/g, "-"), testCase.env(), identity);
|
||||
it("missing required config fails cleanly", async () => {
|
||||
const run = await runEntrypoint("missing-base-url", {
|
||||
GAMECULT_IDUNN_CANDIDATE_BIND: "127.0.0.1:4100",
|
||||
});
|
||||
|
||||
expect(run.signal, "the process must stop by itself").toBeNull();
|
||||
expect(run.code, "startup must fail").not.toBe(0);
|
||||
expect(run.output).toMatch(testCase.expect);
|
||||
expect(run.output.includes(CANARY), "no byte of the canary may reach the terminal").toBe(false);
|
||||
}, 45_000);
|
||||
}
|
||||
expect(run.signal).toBeNull();
|
||||
expect(run.code).not.toBe(0);
|
||||
expect(run.output).toMatch(/GC_ACCESS_BASE_URL is required when GAMECULT_IDUNN_CANDIDATE_BIND is set/);
|
||||
}, 45_000);
|
||||
|
||||
it("valid config starts and listens without printing configured secrets", async () => {
|
||||
const output = await new Promise<string>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [tsxCli, "src/index.ts"], {
|
||||
cwd: repoRoot,
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
HOME: scratch,
|
||||
GC_ACCESS_DATA_ROOT: join(scratch, "data-valid"),
|
||||
PORT: "0",
|
||||
GC_ACCESS_PRIVATE_COMMAND_PORT: "0",
|
||||
GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("valid-token-key", `${canaryTokenKey()}\n`),
|
||||
GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("valid-bifrost", `${CANARY}bifrost\n`),
|
||||
GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID: "discord-client-id",
|
||||
GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: secretFile("valid-discord", `${CANARY}discord\n`),
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
let buf = "";
|
||||
let stopping = false;
|
||||
let finishErr: Error | undefined;
|
||||
|
||||
const stop = (err?: Error) => {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
finishErr = err;
|
||||
clearTimeout(timer);
|
||||
child.kill("SIGKILL");
|
||||
};
|
||||
|
||||
const onData = (chunk: Buffer) => {
|
||||
buf += chunk.toString("utf8");
|
||||
if (buf.includes("Heimdall listening on")) {
|
||||
stop();
|
||||
}
|
||||
};
|
||||
|
||||
child.stdout.on("data", onData);
|
||||
child.stderr.on("data", onData);
|
||||
const timer = setTimeout(() => stop(new Error(`Timed out waiting for listener; output:\n${buf}`)), 30_000);
|
||||
child.on("error", (err) => stop(err));
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (finishErr) reject(finishErr);
|
||||
else if (!stopping) reject(new Error(`Exited unexpectedly with code ${code}; output:\n${buf}`));
|
||||
else resolve(buf);
|
||||
});
|
||||
});
|
||||
|
||||
expect(output).toContain("Heimdall listening on");
|
||||
expect(output).not.toContain(CANARY);
|
||||
}, 45_000);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,251 +1,67 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { appProfiles } from "../src/app-profiles.js";
|
||||
import { appSlugs, providers } from "../src/contracts.js";
|
||||
import { ENV_NAMES, SECRET_ENV_NAMES } from "../src/config.js";
|
||||
import { providers } from "../src/contracts.js";
|
||||
import { providerCatalog } from "../src/providers.js";
|
||||
|
||||
// The Idunn recipe decides which environment names a binding may set, and
|
||||
// Idunn refuses any other. So the recipe is where "a secret is only ever a
|
||||
// file" is enforced for a deployment: a plaintext secret name declared here
|
||||
// can carry the secret into the binding, the unit and every plan.
|
||||
const recipe = readFileSync(new URL("../deployment/idunn/recipe.toml", import.meta.url), "utf8").replace(/\r\n/g, "\n");
|
||||
|
||||
const recipe = readFileSync(new URL("../deployment/idunn/recipe.toml", import.meta.url), "utf8");
|
||||
|
||||
/** The names in one `KEY = [ "A", "B" ]` array of the given TOML text. */
|
||||
function stringArray(text: string, key: string): string[] {
|
||||
const match = new RegExp(`^${key}\\s*=\\s*\\[([^\\]]*)\\]`, "m").exec(text);
|
||||
return match ? [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) : [];
|
||||
}
|
||||
|
||||
const serviceSection = /^\[service\]\n([\s\S]*?)(?=^\[)/m.exec(recipe.replace(/\r\n/g, "\n"))?.[1] ?? "";
|
||||
const serviceNames = [
|
||||
const serviceSection = /^\[service\]\n([\s\S]*?)(?=^\[)/m.exec(recipe)?.[1] ?? "";
|
||||
const serviceNames = new Set([
|
||||
...stringArray(serviceSection, "optional_environment"),
|
||||
...stringArray(serviceSection, "required_environment"),
|
||||
];
|
||||
const everyDeclaredName = [...recipe.replace(/\r\n/g, "\n").matchAll(/^\w+_environment\s*=\s*\[([^\]]*)\]/gm)].flatMap(
|
||||
(match) => [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!)
|
||||
]);
|
||||
const everyDeclaredName = new Set(
|
||||
[...recipe.matchAll(/^\w+_environment\s*=\s*\[([^\]]*)\]/gm)].flatMap(
|
||||
(match) => [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!)
|
||||
)
|
||||
);
|
||||
|
||||
// The secrets Heimdall reads are observed, not read from the source: the real
|
||||
// loadConfig runs against an environment that records every name it looks
|
||||
// up. readSecretInput looks up `NAME_FILE` for each secret, so every `_FILE`
|
||||
// lookup names one, however the call is spelled and whatever list computes
|
||||
// the name. The recorder also stands in for process.env, both while config.ts
|
||||
// is imported (freshly, so a copy of process.env taken at module load is the
|
||||
// recorder too) and during every call.
|
||||
//
|
||||
// A read made from a copy of the environment ({ ...env }, Object.entries)
|
||||
// cannot be seen, so copying or enumerating it is recorded and fails below.
|
||||
//
|
||||
// A secret read only on a branch some value opens is reached by running
|
||||
// loadConfig over many environments, until no run reads a new name: every
|
||||
// secret found so far set in plaintext; then each name read so far set to
|
||||
// each probe value (a few shapes, plus every string literal in config.ts);
|
||||
// then every name at once, each set to a value loadConfig accepted for it
|
||||
// alone; and every combined run again as Idunn starts Heimdall, with the
|
||||
// recipe's service arguments and a candidate socket with its base URL, a
|
||||
// pair loadConfig refuses one name at a time. A run that throws still counts
|
||||
// the reads it made first.
|
||||
//
|
||||
// Known limit: a read gated on a value that is none of the probe values and
|
||||
// not accepted alone in combination with the others stays unseen.
|
||||
const configSource = readFileSync(new URL("../src/config.ts", import.meta.url), "utf8");
|
||||
const probeValues = [
|
||||
...new Set(["1", "true", "/probe/path", "127.0.0.1:4100", "https://probe.test", ...[...configSource.matchAll(/"([^"\\\r\n]+)"/g)].map((m) => m[1]!)]),
|
||||
];
|
||||
|
||||
const recorder = { values: {} as Record<string, string>, names: new Set<string>(), enumerated: false };
|
||||
const recordingEnv = new Proxy({} as NodeJS.ProcessEnv, {
|
||||
get(_target, name) {
|
||||
if (typeof name !== "string") return undefined;
|
||||
recorder.names.add(name);
|
||||
return recorder.values[name];
|
||||
},
|
||||
has(_target, name) {
|
||||
if (typeof name !== "string") return false;
|
||||
recorder.names.add(name);
|
||||
return name in recorder.values;
|
||||
},
|
||||
ownKeys() {
|
||||
recorder.enumerated = true;
|
||||
return [];
|
||||
},
|
||||
getOwnPropertyDescriptor() {
|
||||
recorder.enumerated = true;
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
async function withRecordingProcessEnv<T>(run: () => T | Promise<T>): Promise<T> {
|
||||
const processEnv = process.env;
|
||||
process.env = recordingEnv;
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
process.env = processEnv;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How Idunn starts Heimdall: the recipe's [service] arguments after the
|
||||
* entry script, each binding given a probe value, and the environment an
|
||||
* Idunn candidate always has (a loopback socket, which requires the base URL).
|
||||
*/
|
||||
const recipeArguments = [...(/^\[service\][\s\S]*?^arguments = \[([\s\S]*?)^\]/m.exec(recipe.replace(/\r\n/g, "\n"))?.[1] ?? "").matchAll(
|
||||
/\{ kind = "(literal|binding)", (?:value|name) = "([^"]+)" \}/g
|
||||
)].map((match) => (match[1] === "literal" ? match[2]! : "/probe/idunn-binding"));
|
||||
const idunnArgv = recipeArguments.slice(1);
|
||||
const idunnEnv = { GAMECULT_IDUNN_CANDIDATE_BIND: "127.0.0.1:4100", GC_ACCESS_BASE_URL: "https://probe.test" };
|
||||
|
||||
vi.resetModules();
|
||||
const { loadConfig } = await withRecordingProcessEnv(() => import("../src/config.js"));
|
||||
|
||||
/** The names one loadConfig run reads under `values`, and whether it accepted them. */
|
||||
async function readsOf(
|
||||
values: Readonly<Record<string, string>>,
|
||||
argv: readonly string[] = []
|
||||
): Promise<{ names: Set<string>; accepted: boolean }> {
|
||||
recorder.values = { ...values };
|
||||
recorder.names = new Set();
|
||||
let accepted = true;
|
||||
await withRecordingProcessEnv(() => {
|
||||
try {
|
||||
loadConfig(recordingEnv, argv);
|
||||
} catch {
|
||||
accepted = false; // the reads before the refusal still count
|
||||
}
|
||||
});
|
||||
return { names: recorder.names, accepted };
|
||||
}
|
||||
|
||||
async function exploreLoadConfig(): Promise<{ names: Set<string>; enumerated: boolean }> {
|
||||
const names = new Set<string>();
|
||||
recorder.enumerated = false;
|
||||
const secretsOf = () => [...names].filter((name) => name.endsWith("_FILE")).map((name) => name.slice(0, -"_FILE".length));
|
||||
for (let grew = true; grew; ) {
|
||||
const before = names.size;
|
||||
const secrets = Object.fromEntries(secretsOf().map((name) => [name, "probe-secret"]));
|
||||
const settable = [...names].filter((name) => !name.endsWith("_FILE") && !(name in secrets));
|
||||
const accepted = new Map<string, string[]>();
|
||||
const keep = (run: { names: Set<string> }) => run.names.forEach((name) => names.add(name));
|
||||
keep(await readsOf({}));
|
||||
keep(await readsOf(secrets));
|
||||
keep(await readsOf({ ...secrets, ...idunnEnv }, idunnArgv));
|
||||
for (const name of settable) {
|
||||
for (const value of probeValues) {
|
||||
const run = await readsOf({ ...secrets, [name]: value });
|
||||
keep(run);
|
||||
if (run.accepted) accepted.set(name, [...(accepted.get(name) ?? []), value]);
|
||||
}
|
||||
}
|
||||
const widest = Math.max(0, ...[...accepted.values()].map((values) => values.length));
|
||||
for (let round = 0; round < widest; round += 1) {
|
||||
const together = Object.fromEntries([...accepted].map(([name, values]) => [name, values[round % values.length]!]));
|
||||
keep(await readsOf({ ...secrets, ...together }));
|
||||
keep(await readsOf({ ...secrets, ...together, ...idunnEnv }, idunnArgv));
|
||||
}
|
||||
grew = names.size > before;
|
||||
}
|
||||
return { names, enumerated: recorder.enumerated };
|
||||
}
|
||||
|
||||
const explored = await exploreLoadConfig();
|
||||
|
||||
/** Secrets Heimdall reads through readSecretInput, by their plaintext name. */
|
||||
const secretNames = [...explored.names]
|
||||
.filter((name) => name.endsWith("_FILE"))
|
||||
.map((name) => name.slice(0, -"_FILE".length));
|
||||
|
||||
const secretShaped =
|
||||
/SECRET|PASSWORD|PASSPHRASE|TOKEN|API_KEY|PRIVATE_KEY|ENCRYPTION_KEY|SALT|CREDENTIAL|DATABASE_URL|_DSN|_PEM|HMAC/;
|
||||
|
||||
/** Secret-shaped names that hold no secret, each for its own reason. */
|
||||
const notSecrets = new Set([
|
||||
// A path to the signing key file, which Heimdall reads (or creates) itself.
|
||||
"GC_ACCESS_SIGNING_PRIVATE_KEY_PATH",
|
||||
// A flag: create that file on first boot.
|
||||
"GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP",
|
||||
]);
|
||||
|
||||
describe("Idunn recipe secret declarations", () => {
|
||||
it("reads the service's declared environment", () => {
|
||||
expect(serviceNames).toContain("GC_ACCESS_DATABASE_URL_FILE");
|
||||
expect(serviceNames).toContain("GC_ACCESS_BASE_URL");
|
||||
});
|
||||
const neverBound = new Set([
|
||||
"HOST",
|
||||
"PORT",
|
||||
"GC_ACCESS_DATA_ROOT",
|
||||
"GC_ACCESS_CULTCACHE_PATH",
|
||||
"GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH",
|
||||
"GC_ACCESS_IDUNN_DAEMON",
|
||||
]);
|
||||
|
||||
it("declares no secret-shaped name except as a _FILE credential path", () => {
|
||||
const plaintext = everyDeclaredName.filter(
|
||||
describe("Idunn recipe secret declarations", () => {
|
||||
it("declares every expected _FILE secret and never binds plaintext secrets", () => {
|
||||
const expectedSecretFiles = new Set([
|
||||
...SECRET_ENV_NAMES.map((name) => `${name}_FILE`),
|
||||
...providers.map((provider) => providerCatalog[provider].clientSecretEnv),
|
||||
...Object.values(appProfiles).map((profile) => `GC_ACCESS_APP_${profile.slug.toUpperCase()}_SHARED_SECRET_FILE`),
|
||||
]);
|
||||
|
||||
const missingSecretFiles = [...expectedSecretFiles].filter((name) => !serviceNames.has(name));
|
||||
expect(missingSecretFiles).toEqual([]);
|
||||
|
||||
const boundPlaintext = SECRET_ENV_NAMES.filter((name) => everyDeclaredName.has(name));
|
||||
expect(boundPlaintext).toEqual([]);
|
||||
|
||||
const secretShapedPlaintext = [...everyDeclaredName].filter(
|
||||
(name) => secretShaped.test(name) && !name.endsWith("_FILE") && !notSecrets.has(name)
|
||||
);
|
||||
expect(plaintext).toEqual([]);
|
||||
expect(secretShapedPlaintext).toEqual([]);
|
||||
});
|
||||
|
||||
it("starts the exploration the way the recipe starts Heimdall", async () => {
|
||||
expect(idunnArgv).toEqual(["--state-root", "/probe/idunn-binding"]);
|
||||
expect(serviceNames).toEqual(expect.arrayContaining(Object.keys(idunnEnv)));
|
||||
expect((await readsOf({ ...idunnEnv }, idunnArgv)).accepted).toBe(true);
|
||||
});
|
||||
|
||||
it("reads the environment only by name, never by copying or enumerating it", () => {
|
||||
expect(explored.enumerated).toBe(false);
|
||||
});
|
||||
|
||||
it("sees every secret loadConfig reads, across the provider and app lists", () => {
|
||||
expect(secretNames).toEqual(
|
||||
expect.arrayContaining([
|
||||
"GC_ACCESS_DATABASE_URL",
|
||||
"GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64",
|
||||
"GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET",
|
||||
...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`),
|
||||
...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it("declares none of the secrets Heimdall reads under its plaintext name", () => {
|
||||
for (const name of secretNames) {
|
||||
expect(everyDeclaredName).not.toContain(name);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares every provider client-secret file the witness publishes", () => {
|
||||
for (const provider of providers) {
|
||||
expect(serviceNames).toContain(providerCatalog[provider].clientSecretEnv);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares the shared-secret file of every app profile the witness publishes", () => {
|
||||
for (const profile of Object.values(appProfiles)) {
|
||||
expect(serviceNames).toContain(`GC_ACCESS_APP_${profile.slug.toUpperCase()}_SHARED_SECRET_FILE`);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares the _FILE of every secret Heimdall reads", () => {
|
||||
for (const name of secretNames) {
|
||||
expect(serviceNames).toContain(`${name}_FILE`);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares every other name loadConfig reads, or says why a binding never sets it", () => {
|
||||
// Idunn refuses a binding that sets an undeclared name, so an undeclared
|
||||
// name is a setting no Idunn-admitted generation can ever change.
|
||||
const neverBound = new Set([
|
||||
// The listen socket is the candidate bind under Idunn, and the command port follows it.
|
||||
"HOST",
|
||||
"PORT",
|
||||
// The state root is the --state-root argument; the paths below it are Heimdall's own layout.
|
||||
"GC_ACCESS_DATA_ROOT",
|
||||
"GC_ACCESS_CULTCACHE_PATH",
|
||||
"GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH",
|
||||
// The daemon id is the host's name for this process, fixed by the code's default.
|
||||
"GC_ACCESS_IDUNN_DAEMON",
|
||||
]);
|
||||
const declared = new Set(everyDeclaredName);
|
||||
const unreachable = [...explored.names]
|
||||
.filter((name) => !secretNames.includes(name) && !name.endsWith("_FILE"))
|
||||
.filter((name) => !declared.has(name) && !neverBound.has(name));
|
||||
expect(unreachable).toEqual([]);
|
||||
// An exemption for a name nothing reads would hide the next real gap.
|
||||
expect([...neverBound].filter((name) => !explored.names.has(name))).toEqual([]);
|
||||
it("declares every config ENV_NAME except host-fixed exclusions", () => {
|
||||
const undeclared = ENV_NAMES.filter((name) => !everyDeclaredName.has(name) && !neverBound.has(name));
|
||||
expect(undeclared).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue