From ac863529724bc0f9ae897d4db6bf02debd7a1cad Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 12:30:57 +0200 Subject: [PATCH] Read every secret input from a credential file named by NAME_FILE The recipe declared Heimdall's secrets as plain environment, so its admit contract made the operator binding the only place their values could live, and the binding was printed into a transcript. The recipe now declares each secret only as its _FILE twin (GC_ACCESS_DATABASE_URL_FILE required, the rest optional). A binding binds those under [workload.secret_files] to root:root 0400 credential files, and Idunn's rule that a binding binds only declared names leaves a plaintext secret nowhere to go. GC_ACCESS_APP_SHARED_SECRET is deleted outright: nothing reads it. One reader, readSecretInput, serves every secret: it reads NAME_FILE and strips one trailing newline, refuses NAME and NAME_FILE set together, and its errors name the variable and path, never a value or file contents. Storage-backend selection keys off the resolved database URL. The published provider witness and the provider_not_configured body name the _FILE variables, and custody's errors name GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE. The plaintext fallback (NAME read while NAME_FILE is absent) is a named shim for the legacy EnvironmentFile unit only; secret-files Cut 5 deletes it. Idunn secret-files cut, Cut 1. Co-Authored-By: Claude Opus 5.5 --- deployment/idunn/recipe.toml | 23 +++-- src/config.ts | 58 ++++++++++-- src/custody.ts | 6 +- src/providers.ts | 12 +-- tests/config-secrets.test.ts | 174 +++++++++++++++++++++++++++++++++++ 5 files changed, 245 insertions(+), 28 deletions(-) create mode 100644 tests/config-secrets.test.ts diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index aa1e138..01722d1 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -131,17 +131,20 @@ arguments = [ ] transport = "http" route_required = true +# A secret input is declared only as its `*_FILE` name. The binding binds it +# under [workload.secret_files] to a root:root 0400 credential file, so the value +# never sits in the binding, the unit or a plan. Idunn refuses a binding that +# sets an undeclared name, so a plaintext secret has nowhere to go. optional_environment = [ "CULTMESH_URI_ODIN_RUDP", "GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_BIFROST_SHARED_SECRET", + "GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE", "GC_ACCESS_APP_GHOSTLIGHT_BACKEND_CALLBACK_URLS", "GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS", - "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET", + "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE", "GC_ACCESS_APPLY_SCHEMA_ON_STARTUP", - "GC_ACCESS_APP_SHARED_SECRET", "GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT", - "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET", + "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE", "GC_ACCESS_COMPLETION_TTL_SECONDS", "GC_ACCESS_IDUNN_HEALTH_CONTRACT", "GC_ACCESS_IDUNN_RUDP_HEALTH", @@ -150,27 +153,27 @@ optional_environment = [ "GC_ACCESS_PRIVATE_COMMAND_HOST", "GC_ACCESS_PRIVATE_COMMAND_PORT", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", - "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET", + "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", - "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET", + "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", - "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET", + "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", - "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET", + "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE", "GC_ACCESS_SESSION_TTL_SECONDS", "GC_ACCESS_SIGNING_KEY_ID", "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", "GC_ACCESS_STATE_TTL_SECONDS", "GC_ACCESS_STORAGE_BACKEND", - "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", + "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE", ] required_environment = [ "GAMECULT_IDUNN_RUNTIME_BUNDLE", "GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", "GC_ACCESS_BASE_URL", - "GC_ACCESS_DATABASE_URL", + "GC_ACCESS_DATABASE_URL_FILE", ] [service.health] diff --git a/src/config.ts b/src/config.ts index 58e5269..285c6b1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { appSlugs, providers, type AppSlug, type Provider } from "./contracts.js"; @@ -120,11 +121,47 @@ function readIdunnCandidateBind( return { host, port }; } +/** + * Read one secret input. Its value lives in a file named by `NAME_FILE`: under + * Idunn that is a systemd credential, so the value never enters a binding, a + * unit, a plan or the process environment. One trailing newline is stripped. + * + * LEGACY SHIM, deleted with the legacy EnvironmentFile unit (secret-files + * Cut 5): when `NAME_FILE` is absent, the plaintext `NAME` is read instead. + * Setting both is refused, so one input has one owner. Under Idunn the recipe + * declares only the `_FILE` names, so the plaintext form cannot be bound there. + * + * Errors name the variable and the path, never a value or a file's contents. + */ +export function readSecretInput(env: NodeJS.ProcessEnv, name: string): string | undefined { + const fileVariable = `${name}_FILE`; + const filePath = env[fileVariable]; + const plaintext = env[name]; + + if (filePath !== undefined && plaintext !== undefined) { + throw new Error(`${name} and ${fileVariable} are both set; set only ${fileVariable}.`); + } + + if (filePath === undefined) { + return plaintext; + } + + let contents: string; + try { + contents = readFileSync(filePath, "utf8"); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code ?? "read error"; + throw new Error(`${fileVariable} names ${filePath}, which could not be read (${code}).`); + } + + return contents.replace(/\r?\n$/, ""); +} + function readProviderConfig(env: NodeJS.ProcessEnv, provider: Provider): ProviderClientConfig { const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`; const config: ProviderClientConfig = {}; const clientId = env[`${prefix}_CLIENT_ID`]; - const clientSecret = env[`${prefix}_CLIENT_SECRET`]; + const clientSecret = readSecretInput(env, `${prefix}_CLIENT_SECRET`); if (clientId) { config.clientId = clientId; @@ -200,8 +237,9 @@ export function loadConfig( const issuer = trimTrailingSlash(env.GC_ACCESS_ISSUER ?? publicBaseUrl); const dataRoot = stateRootArgument ?? env.GC_ACCESS_DATA_ROOT ?? path.join(workspaceRoot, ".heimdall-data"); + const databaseUrl = readSecretInput(env, "GC_ACCESS_DATABASE_URL"); const storageBackend = - env.GC_ACCESS_STORAGE_BACKEND === "postgres" || env.GC_ACCESS_DATABASE_URL ? "postgres" : "memory"; + env.GC_ACCESS_STORAGE_BACKEND === "postgres" || databaseUrl ? "postgres" : "memory"; const providersConfig = Object.fromEntries( providers.map((provider) => [provider, readProviderConfig(env, provider)]) ) as Record; @@ -209,7 +247,7 @@ export function loadConfig( appSlugs .map((appSlug) => { const envKey = `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`; - return [appSlug, env[envKey]]; + return [appSlug, readSecretInput(env, envKey)]; }) .filter(([, value]) => Boolean(value)) ) as Partial>; @@ -285,20 +323,22 @@ export function loadConfig( config.signingKeyId = env.GC_ACCESS_SIGNING_KEY_ID; } - if (env.GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64) { - config.tokenEncryptionKeyBase64 = env.GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64; + const tokenEncryptionKeyBase64 = readSecretInput(env, "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64"); + if (tokenEncryptionKeyBase64) { + config.tokenEncryptionKeyBase64 = tokenEncryptionKeyBase64; } if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT) { config.bifrostPatronSupportEndpoint = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT; } - if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET) { - config.bifrostPatronSupportSecret = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET; + const bifrostPatronSupportSecret = readSecretInput(env, "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET"); + if (bifrostPatronSupportSecret) { + config.bifrostPatronSupportSecret = bifrostPatronSupportSecret; } - if (env.GC_ACCESS_DATABASE_URL) { - config.storage.databaseUrl = env.GC_ACCESS_DATABASE_URL; + if (databaseUrl) { + config.storage.databaseUrl = databaseUrl; } return config; diff --git a/src/custody.ts b/src/custody.ts index d2849c1..a70cbe1 100644 --- a/src/custody.ts +++ b/src/custody.ts @@ -14,13 +14,13 @@ export interface TokenCustody { function decodeConfiguredKey(base64Value: string): Buffer { const normalized = base64Value.trim(); if (!normalized) { - throw new Error("GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 is set but empty."); + throw new Error("GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE is set but empty."); } const key = Buffer.from(normalized, "base64"); if (key.byteLength !== TOKEN_KEY_BYTES) { throw new Error( - `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 must decode to exactly ${TOKEN_KEY_BYTES} bytes for AES-256-GCM.` + `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE must decode to exactly ${TOKEN_KEY_BYTES} bytes for AES-256-GCM.` ); } @@ -51,7 +51,7 @@ export function createTokenCustody(config: HeimdallConfig): TokenCustody { : (() => { if (config.storage.backend === "postgres") { throw new Error( - "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 is required when Heimdall uses persistent postgres storage." + "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE is required when Heimdall uses persistent postgres storage." ); } diff --git a/src/providers.ts b/src/providers.ts index e5c3775..506e084 100644 --- a/src/providers.ts +++ b/src/providers.ts @@ -21,7 +21,7 @@ export const providerCatalog: Record = { defaultScopes: ["identify", "guilds.members.read"], roles: ["identity", "entitlement"], clientIdEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE", }, patreon: { key: "patreon", @@ -30,7 +30,7 @@ export const providerCatalog: Record = { defaultScopes: ["identity", "identity[email]"], roles: ["identity", "entitlement"], clientIdEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE", }, github: { key: "github", @@ -39,7 +39,7 @@ export const providerCatalog: Record = { defaultScopes: ["read:user", "user:email"], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE", }, twitch: { key: "twitch", @@ -48,7 +48,7 @@ export const providerCatalog: Record = { defaultScopes: ["user:read:email"], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE", }, youtube: { key: "youtube", @@ -62,7 +62,7 @@ export const providerCatalog: Record = { ], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE", additionalAuthorizationParams: { access_type: "offline", include_granted_scopes: "true", @@ -80,7 +80,7 @@ export const providerCatalog: Record = { ], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE", }, }; diff --git a/tests/config-secrets.test.ts b/tests/config-secrets.test.ts new file mode 100644 index 0000000..fa2a56c --- /dev/null +++ b/tests/config-secrets.test.ts @@ -0,0 +1,174 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { loadConfig, readSecretInput } from "../src/config.js"; +import { appSlugs, providers } from "../src/contracts.js"; +import { providerCatalog, providerExpectedEnv } from "../src/providers.js"; + +// Secret inputs arrive as files named by `NAME_FILE` (systemd credentials under +// Idunn). These tests pin the reader's rules and that every secret Heimdall +// consumes goes through it. + +const tempDirs: string[] = []; + +function tempDir(): string { + const dir = mkdtempSync(join(tmpdir(), "heimdall-secret-input-")); + tempDirs.push(dir); + return dir; +} + +function secretFile(contents: string, name = "secret"): string { + const path = join(tempDir(), name); + writeFileSync(path, contents); + return path; +} + +function thrownMessage(action: () => unknown): string { + try { + action(); + } catch (error) { + return (error as Error).message; + } + throw new Error("expected the action to throw"); +} + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("readSecretInput", () => { + it("reads the value from the file named by NAME_FILE and strips exactly one trailing newline", () => { + const cases: Array<[string, string]> = [ + ["from-the-file\n", "from-the-file"], + ["from-the-file\r\n", "from-the-file"], + ["two-newlines\n\n", "two-newlines\n"], + [" inner spaces kept \n", " inner spaces kept "], + ["no-newline", "no-newline"], + ]; + + for (const [contents, expected] of cases) { + const env = { EXAMPLE_SECRET_FILE: secretFile(contents) }; + expect(readSecretInput(env, "EXAMPLE_SECRET")).toBe(expected); + } + }); + + it("returns undefined when neither form is set", () => { + expect(readSecretInput({}, "EXAMPLE_SECRET")).toBeUndefined(); + }); + + it("falls back to the plaintext name only while NAME_FILE is absent (legacy shim)", () => { + expect(readSecretInput({ EXAMPLE_SECRET: "legacy-plaintext" }, "EXAMPLE_SECRET")).toBe("legacy-plaintext"); + }); + + it("refuses both forms at once, and the refusal carries neither value", () => { + const fileCanary = "canary-file-7c1e0f"; + const plainCanary = "canary-plain-93ab2d"; + const env = { + EXAMPLE_SECRET: plainCanary, + EXAMPLE_SECRET_FILE: secretFile(fileCanary), + }; + + const message = thrownMessage(() => readSecretInput(env, "EXAMPLE_SECRET")); + expect(message).toContain("EXAMPLE_SECRET_FILE"); + expect(message).toMatch(/both set/); + expect(message).not.toContain(fileCanary); + expect(message).not.toContain(plainCanary); + expect(message).not.toContain("canary"); + }); + + it("refuses both forms even when the plaintext form is empty", () => { + const env = { EXAMPLE_SECRET: "", EXAMPLE_SECRET_FILE: secretFile("value") }; + expect(() => readSecretInput(env, "EXAMPLE_SECRET")).toThrow(/both set/); + }); + + it("names the variable and the path of a missing file", () => { + const missing = join(tempDir(), "absent-credential"); + const message = thrownMessage(() => readSecretInput({ EXAMPLE_SECRET_FILE: missing }, "EXAMPLE_SECRET")); + expect(message).toContain("EXAMPLE_SECRET_FILE"); + expect(message).toContain(missing); + expect(message).toContain("ENOENT"); + }); + + it("names the variable and the path of an unreadable file, and carries no byte of what sits beside it", () => { + const dir = tempDir(); + const canary = "canary-sibling-5d2f88"; + writeFileSync(join(dir, "sibling"), canary); + const notAFile = join(dir, "credential"); + mkdirSync(notAFile); + writeFileSync(join(notAFile, "inside"), canary); + + const message = thrownMessage(() => readSecretInput({ EXAMPLE_SECRET_FILE: notAFile }, "EXAMPLE_SECRET")); + expect(message).toContain("EXAMPLE_SECRET_FILE"); + expect(message).toContain(notAFile); + expect(message).not.toContain("canary"); + }); +}); + +describe("loadConfig secret inputs", () => { + it("configures every secret Heimdall consumes from its _FILE twin alone", () => { + const env: Record = {}; + const expected = new Map(); + function bind(name: string): string { + const value = `value-of-${name.toLowerCase()}`; + env[`${name}_FILE`] = secretFile(`${value}\n`, name); + expected.set(name, value); + return value; + } + + const databaseUrl = bind("GC_ACCESS_DATABASE_URL"); + const tokenKey = bind("GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64"); + const patronSecret = bind("GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET"); + const providerSecrets = Object.fromEntries( + providers.map((provider) => [provider, bind(`GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`)]) + ); + const appSecrets = Object.fromEntries( + appSlugs.map((slug) => [slug, bind(`GC_ACCESS_APP_${slug.toUpperCase()}_SHARED_SECRET`)]) + ); + + const config = loadConfig(env, []); + + expect(config.storage.databaseUrl).toBe(databaseUrl); + expect(config.tokenEncryptionKeyBase64).toBe(tokenKey); + expect(config.bifrostPatronSupportSecret).toBe(patronSecret); + for (const provider of providers) { + expect(config.providers[provider].clientSecret).toBe(providerSecrets[provider]); + } + expect(config.appSharedSecrets).toEqual(appSecrets); + }); + + it("selects postgres storage from a database URL given only as a file", () => { + const config = loadConfig( + { GC_ACCESS_DATABASE_URL_FILE: secretFile("postgres://heimdall@localhost/heimdall\n") }, + [] + ); + expect(config.storage.backend).toBe("postgres"); + }); + + it("refuses to start when the database URL file is absent", () => { + const missing = join(tempDir(), "database-url"); + const message = thrownMessage(() => loadConfig({ GC_ACCESS_DATABASE_URL_FILE: missing }, [])); + expect(message).toContain("GC_ACCESS_DATABASE_URL_FILE"); + expect(message).toContain(missing); + }); + + it("refuses a secret bound both ways at startup", () => { + const env = { + GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64: "plain", + GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("file"), + }; + expect(() => loadConfig(env, [])).toThrow(/GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE/); + }); + + it("publishes provider secret variable names that actually configure the secret", () => { + for (const provider of providers) { + const secretVariable = providerCatalog[provider].clientSecretEnv; + expect(providerExpectedEnv(provider)).toContain(secretVariable); + + const config = loadConfig({ [secretVariable]: secretFile(`${provider}-secret\n`) }, []); + expect(config.providers[provider].clientSecret).toBe(`${provider}-secret`); + } + }); +});