From 151b02cf61ec61052ad8b4397d7abd1eea3e2168 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 17:32:14 +0000 Subject: [PATCH 1/2] fix(cli): one-shot secret commands seal with the crypto provider os serve uses The one-shot composition (os secret rewrap, os secret orphans, the data migrations' settings arm) built its own LocalCryptoProvider. It now chooses through serve's createHostCryptoProvider over the plugins the host config declares, boots a declared provider, and refuses naming it when it cannot be booted, registers none, or the config cannot be read. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kDtnUcfoZfMJqLNWd --- .changeset/31007-one-shot-crypto-provider.md | 24 ++ .../secret/orphans.driver-contract.test.ts | 4 +- packages/cli/src/commands/secret/orphans.ts | 4 +- .../secret/rewrap.driver-contract.test.ts | 89 +++++- .../src/commands/secret/rewrap.guards.test.ts | 33 ++- packages/cli/src/commands/secret/rewrap.ts | 104 +++++-- packages/cli/src/commands/serve.ts | 36 ++- .../cli/src/utils/data-migration-plugins.ts | 13 +- .../utils/one-shot-crypto-provider.test.ts | 280 ++++++++++++++++++ .../src/utils/one-shot-settings.pin.test.ts | 45 ++- packages/cli/src/utils/one-shot-settings.ts | 195 +++++++++++- 11 files changed, 751 insertions(+), 76 deletions(-) create mode 100644 .changeset/31007-one-shot-crypto-provider.md create mode 100644 packages/cli/src/utils/one-shot-crypto-provider.test.ts diff --git a/.changeset/31007-one-shot-crypto-provider.md b/.changeset/31007-one-shot-crypto-provider.md new file mode 100644 index 00000000000..c1991a50c6a --- /dev/null +++ b/.changeset/31007-one-shot-crypto-provider.md @@ -0,0 +1,24 @@ +--- +'@objectstack/cli': patch +--- + +fix(cli): one-shot secret commands seal and open with the crypto provider `os serve` uses + +Clause-②: no +Metadata-protocol: none + +`os secret rewrap`, `os secret orphans` and the data migrations that compose the settings service (`os migrate files-to-references`, `os storage orphans`, `os migrate recompute-home-amounts`) used to build their own `LocalCryptoProvider`. On a deployment whose plugin registers a KMS- or Vault-backed provider as the `crypto-provider` service, they could open nothing `os serve` sealed, and a re-wrap could have re-sealed under the local key. + +They now choose the provider with `os serve`'s own function. They read the host config's `plugins`, as `os serve` does without `--dev`: + +- One plugin declares `providesServices: ['crypto-provider']`: the run boots it and seals and opens with the provider it registers. +- Two plugins declare it: the run refuses before either initializes, and names both. +- No plugin declares it: nothing changes. The run uses the local provider over the key that already exists, and never mints one. + +The run fails closed and never falls back to the local key for a deployment that declares a provider. It refuses, names the provider, and writes nothing when: + +- the declared plugin cannot boot in the run; +- the declared plugin boots but registers no provider; +- the host config, or one of its `plugins` entries, cannot be loaded. + +`os secret rewrap` names the provider as the report's key source. diff --git a/packages/cli/src/commands/secret/orphans.driver-contract.test.ts b/packages/cli/src/commands/secret/orphans.driver-contract.test.ts index 97e09f4fbfb..52c0b53f309 100644 --- a/packages/cli/src/commands/secret/orphans.driver-contract.test.ts +++ b/packages/cli/src/commands/secret/orphans.driver-contract.test.ts @@ -60,7 +60,7 @@ import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import '@objectstack/service-settings'; import { bootSchemaStack, type SchemaStack } from '../../utils/schema-migrate.js'; import type { SecretReferenceEngineLike } from '../../utils/secret-reference-union.js'; -import { oneShotSettingsPlugin } from '../../utils/one-shot-settings.js'; +import { oneShotSettingsPlugins } from '../../utils/one-shot-settings.js'; import SecretOrphans from './orphans.js'; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -182,7 +182,7 @@ describe('os secret orphans — the concrete driver behind both reads (#14843)', databaseUrl: `file:${dbFile}`, // Byte-identical to `orphans.ts`'s own list — the boot has to be the // command's, or the driver this file names is not the one it holds. - extraPlugins: [new PlatformObjectsPlugin(), await oneShotSettingsPlugin()], + extraPlugins: [new PlatformObjectsPlugin(), ...await oneShotSettingsPlugins()], }); const engine = stack.kernel.getService('objectql') as SecretReferenceEngineLike | undefined; diff --git a/packages/cli/src/commands/secret/orphans.ts b/packages/cli/src/commands/secret/orphans.ts index 7580db853bd..2770eb43dcb 100644 --- a/packages/cli/src/commands/secret/orphans.ts +++ b/packages/cli/src/commands/secret/orphans.ts @@ -18,7 +18,7 @@ import { isExitSignal, } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; -import { oneShotSettingsPlugin } from '../../utils/one-shot-settings.js'; +import { oneShotSettingsPlugins } from '../../utils/one-shot-settings.js'; import { absentTableReads, secretUnionReadView } from '../../utils/absent-table-reads.js'; import { describeDriverSqliteFile } from '../../utils/connection-display.js'; import { JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; @@ -230,7 +230,7 @@ export default class SecretOrphans extends Command { // service's default provider: in a development posture with no key, // that default mints a key file in the key home, and this report // promises to write no row or table, and writes no key file either. - extraPlugins: [new PlatformObjectsPlugin(), await oneShotSettingsPlugin()], + extraPlugins: [new PlatformObjectsPlugin(), ...await oneShotSettingsPlugins()], // [#21391] The report boots READ-ONLY, the boot `os migrate plan` // takes: `deferSchemaDdl` holds schema DDL back on every SQL // datasource, and `readOnlyProbe` keeps a missing sqlite file from diff --git a/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts b/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts index 153389ab76b..5db4c8ef951 100644 --- a/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts +++ b/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts @@ -35,7 +35,7 @@ import { ciphertextDerivationStatus, LocalCryptoProvider } from '@objectstack/se import type { CryptoContext } from '@objectstack/spec/contracts'; import { bootSchemaStack, type SchemaStack } from '../../utils/schema-migrate.js'; import type { SecretReferenceEngineLike } from '../../utils/secret-reference-union.js'; -import { oneShotSettingsPlugin } from '../../utils/one-shot-settings.js'; +import { oneShotSettingsPlugins } from '../../utils/one-shot-settings.js'; import SecretRewrap from './rewrap.js'; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -106,7 +106,7 @@ describe('os secret rewrap — the concrete driver and the command, end to end ( // `rewrap.ts`'s own list: the one-shot settings composition, over the // key this file declares in `OS_SECRET_KEY` (the command resolves the // same key first and hands that instance in). - extraPlugins: [new PlatformObjectsPlugin(), await oneShotSettingsPlugin()], + extraPlugins: [new PlatformObjectsPlugin(), ...await oneShotSettingsPlugins()], }); const engine = stack.kernel.getService('objectql') as SecretReferenceEngineLike | undefined; if (!engine) throw new Error('no objectql engine on the booted stack — nothing to measure'); @@ -205,6 +205,58 @@ describe('os secret rewrap — the concrete driver and the command, end to end ( expect(await secretDriver.find('sys_secret', {})).toEqual(before); }, 180_000); + /** + * [#31007] A host config in the run's directory whose one plugin declares + * the crypto provider — `os serve`'s provider for this deployment. Removed + * again by the returned function. + */ + const declareProvider = (plugin: Record): (() => void) => { + (globalThis as Record).__os_rewrap_provider_plugin = plugin; + const file = join(dir, 'objectstack.config.mjs'); + writeFileSync(file, "export default { name: 'rewrap_dc', plugins: [globalThis.__os_rewrap_provider_plugin] };\n"); + return () => { + rmSync(file, { force: true }); + delete (globalThis as Record).__os_rewrap_provider_plugin; + }; + }; + + it('[#31007] a declared provider that boots re-wraps the rows, and the local key is never read', async () => { + const opened: string[] = []; + const inner = new LocalCryptoProvider({ key: KEY }); + const kms = { + encrypt: (plain: string, ctx: CryptoContext) => inner.encrypt(plain, ctx), + decrypt: (handle: Parameters[0], ctx: CryptoContext) => { opened.push(ctx.scope); return inner.decrypt(handle, ctx); }, + rotateKey: (handle: Parameters[0], ctx: CryptoContext) => inner.rotateKey(handle, ctx), + digest: (plain: string) => inner.digest(plain), + keyedDigest: (plain: string) => inner.keyedDigest(plain), + }; + const removeConfig = declareProvider({ + name: 'com.example.kms', + version: '1.0.0', + providesServices: ['crypto-provider'], + init: async (ctx: { registerService(name: string, service: unknown): void }) => { + ctx.registerService('crypto-provider', kms); + }, + }); + const savedKey = process.env.OS_SECRET_KEY; + // No local key at all: only the registered provider can open these rows. + delete process.env.OS_SECRET_KEY; + try { + const before = await secretDriver.find('sys_secret', {}); + const { payload, exitCode } = await runJson(['--declared-datasources', declaredFile]); + + expect(payload.error, JSON.stringify(payload).slice(0, 400)).toBeUndefined(); + expect(payload.report.byClass).toMatchObject({ rewrap: 2, refused_unreadable: 0 }); + expect(payload.report.keySource).toBe("crypto provider 'com.example.kms'"); + expect(exitCode).toBe(0); + expect(opened.length).toBeGreaterThan(0); + expect(await secretDriver.find('sys_secret', {})).toEqual(before); + } finally { + process.env.OS_SECRET_KEY = savedKey; + removeConfig(); + } + }, 180_000); + it('with no data key, the run refuses before opening a row, and NO provider in its boot mints one', async () => { // A development posture with no key anywhere: the posture in which a // default provider mints a key file. The settings service the boot @@ -277,4 +329,37 @@ describe('os secret rewrap — the concrete driver and the command, end to end ( expect(again.exitCode).toBe(0); expect(await secretDriver.find('sys_secret', {})).toEqual(tableBefore); }, 180_000); + // LAST on purpose: a boot that fails keeps this process's stdout reserved + // for the JSON payload (`bootSchemaStack`'s `jsonOutput`), as the one-shot + // process exits right after it, so no run may follow it in this file. + it('[#31007] a declared provider that cannot boot: --apply refuses naming it, and every stored value is byte-equal', async () => { + // A held version-1 row the earlier --apply has not re-wrapped, so a run + // that fell back to the local key — still present in `OS_SECRET_KEY` — + // would re-wrap it. + const engine = stack!.kernel.getService('objectql') as SecretReferenceEngineLike; + const settingDriver = engine.getDriverForObject('sys_setting') as unknown as DriverProbe; + const held = v1Row('sec_rewrap_dc_31007', 'smtp', 'username', 'dc-31007-plain'); + await secretDriver.create('sys_secret', { ...held }); + await settingDriver.create('sys_setting', { namespace: 'smtp', key: 'username', value_enc: held.id, organization_id: 'org_fixture' }); + + const removeConfig = declareProvider({ + name: 'com.example.kms-offline', + version: '1.0.0', + providesServices: ['crypto-provider'], + init: async () => { throw new Error('KMS endpoint unreachable'); }, + }); + try { + const before = await secretDriver.find('sys_secret', {}); + const { payload, exitCode } = await runJson(['--apply', '--yes', '--declared-datasources', declaredFile]); + + expect(payload.error, JSON.stringify(payload).slice(0, 400)).toBe('boot_failed'); + expect(payload.message).toContain("'com.example.kms-offline'"); + expect(payload.message).toContain('Nothing was opened or written'); + expect(payload.message).not.toContain(KEY.toString('hex')); + expect(exitCode).toBe(1); + expect(await secretDriver.find('sys_secret', {})).toEqual(before); + } finally { + removeConfig(); + } + }, 180_000); }); diff --git a/packages/cli/src/commands/secret/rewrap.guards.test.ts b/packages/cli/src/commands/secret/rewrap.guards.test.ts index 6061b32de60..fa94a26699b 100644 --- a/packages/cli/src/commands/secret/rewrap.guards.test.ts +++ b/packages/cli/src/commands/secret/rewrap.guards.test.ts @@ -137,16 +137,35 @@ function wireBoot( }, }; const absent = new Set(opts.absent ?? []); - vi.mocked(bootSchemaStack).mockResolvedValue({ - // The primary datasource's driver, as `SchemaStack.driver` carries it. - ...(opts.driverConfig ? { driver: { config: opts.driverConfig } } : {}), - kernel: { getService: (name: string) => (name === 'objectql' ? engine : undefined) }, - tableAbsent: (objectName: string) => absent.has(objectName), - shutdown: async () => {}, - } as never); + vi.mocked(bootSchemaStack).mockImplementation((async (bootOpts: { extraPlugins?: unknown[] }) => { + await driveHostCrypto(bootOpts.extraPlugins ?? []); + return { + // The primary datasource's driver, as `SchemaStack.driver` carries it. + ...(opts.driverConfig ? { driver: { config: opts.driverConfig } } : {}), + kernel: { getService: (name: string) => (name === 'objectql' ? engine : undefined) }, + tableAbsent: (objectName: string) => absent.has(objectName), + shutdown: async () => {}, + }; + }) as never); return harness; } +/** + * [#31007] What the replaced boot still does for the crypto: the host's + * crypto-provider seam (`createHostCryptoProvider`, `os serve`'s) is + * initialized and its `kernel:ready` hook fired, as a kernel would, with no + * plugin registering a provider — so the run's provider is the local one, + * chosen by the function `serve` chooses with. + */ +async function driveHostCrypto(plugins: readonly unknown[]): Promise { + const host = plugins.find((p) => (p as { name?: unknown }).name === 'com.objectstack.cli.host-crypto-provider') as + { init(ctx: unknown): Promise } | undefined; + if (!host) throw new Error('the run composed no host crypto-provider seam'); + const ready: Array<() => unknown> = []; + await host.init({ getServices: () => new Map(), hook: (_name: string, handler: () => unknown) => ready.push(handler) }); + for (const handler of ready) await handler(); +} + async function run(argv: string[]): Promise<{ payload: Record; exitCode: number }> { const chunks: string[] = []; const stdout = vi.spyOn(process.stdout, 'write').mockImplementation( diff --git a/packages/cli/src/commands/secret/rewrap.ts b/packages/cli/src/commands/secret/rewrap.ts index ca921558937..6e2297c05fb 100644 --- a/packages/cli/src/commands/secret/rewrap.ts +++ b/packages/cli/src/commands/secret/rewrap.ts @@ -16,7 +16,7 @@ import { isExitSignal, } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; -import { oneShotSettingsPlugin, resolveExistingDataKey } from '../../utils/one-shot-settings.js'; +import { oneShotCrypto, type OneShotCrypto } from '../../utils/one-shot-settings.js'; import { absentTableReads, secretUnionReadView } from '../../utils/absent-table-reads.js'; import { describeDriverSqliteFile } from '../../utils/connection-display.js'; import { JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; @@ -53,17 +53,27 @@ import { readDeclaredDatasources } from './orphans.js'; * * ## The key * - * Rows open only under the key that sealed them, so the provider is resolved - * from a key that ALREADY exists: `OS_SECRET_KEY`, `OS_DEV_CRYPTO_KEY`, or the - * persisted key file, the way every host resolves it. It is constructed in the - * strict posture and with the auto-key opt-in withheld, whatever `NODE_ENV` - * says, so this command never mints a key: a minted key can open nothing that - * is stored. It is resolved before the boot and handed to the settings - * service the boot composes, so no provider in this run mints a key. No key is - * a refusal, before any row is opened. The provider is `LocalCryptoProvider`, - * the one every in-tree host constructs, and both halves — the key and the - * settings service — come from `utils/one-shot-settings.ts`, the one - * composition every one-shot command shares. + * Rows open only under the provider that sealed them, so this run seals and + * opens with the one `os serve` seals with on this host, chosen by `serve`'s + * own function (`utils/one-shot-settings.ts`, `oneShotCrypto`, the one + * composition every one-shot command shares): + * + * - a plugin of the host config that declares the crypto provider is booted, + * and the provider it registers re-wraps the rows. ⛔ If it cannot boot, or + * registers none, the run refuses naming it and writes nothing: a re-seal + * under any other key would be a downgrade, and nothing it sealed opens + * under one anyway (#31007); + * - two declaring plugins, or a host config that cannot be read, are refused + * before the boot; + * - otherwise the local provider over a key that ALREADY exists: + * `OS_SECRET_KEY`, `OS_DEV_CRYPTO_KEY`, or the persisted key file, the way + * every host resolves it. It is constructed in the strict posture and with + * the auto-key opt-in withheld, whatever `NODE_ENV` says, so this command + * never mints a key: a minted key can open nothing that is stored. No key + * is a refusal, before any row is opened. + * + * The provider is composed before the boot and handed to the settings service + * the boot composes, so no provider in this run mints a key. */ export default class SecretRewrap extends Command { static override description = @@ -149,12 +159,23 @@ export default class SecretRewrap extends Command { const { ciphertextDerivationStatus } = await import('@objectstack/service-settings'); const { PlatformObjectsPlugin } = await import('@objectstack/platform-objects/plugin'); - // ── The provider, resolved BEFORE the boot, from a key that already exists ── - // The strict posture never mints a key, and the auto-key opt-in is - // withheld. A missing key is refused only once the plan has a row to open, - // so a run with nothing to open still reports. - const dataKey = await resolveExistingDataKey(); - const { provider, unavailable: keyUnavailable } = dataKey; + // ── The provider `os serve` seals with, composed BEFORE the boot ───────── + // A declared provider is booted with this run; otherwise the local one, in + // the strict posture that never mints a key, with the auto-key opt-in + // withheld. A missing local key is refused only once the plan has a row to + // open, so a run with nothing to open still reports. Two declaring plugins, + // or a host config that cannot be read, are refused here, before any boot. + let crypto: OneShotCrypto; + try { + crypto = await oneShotCrypto(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (json) { await emitJson({ error: 'crypto_provider_refused', message }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + const keyUnavailable = crypto.key?.unavailable ?? null; let stack; try { @@ -169,23 +190,41 @@ export default class SecretRewrap extends Command { // default would mint a key file, and the next run would then resolve a // key under which nothing stored opens. With no key, it is handed one // that refuses every call. Nothing in this one-shot boot reads a - // setting's value. + // setting's value. A declared provider's plugin boots here too. extraPlugins: [ new PlatformObjectsPlugin(), - await oneShotSettingsPlugin(dataKey), + ...crypto.plugins, ], // The dry run boots READ-ONLY, the boot `os migrate plan` takes. // `--apply` keeps the plain boot: it writes rows. ...(flags.apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }), }); } catch (error) { - const message = error instanceof Error ? error.message : String(error); + // [#31007] A boot that fails with a declared provider in it may be that + // provider failing: the refusal names it either way, and nothing was + // opened or written. + const cause = error instanceof Error ? error.message : String(error); + const message = crypto.declaredBy && !cause.includes(`'${crypto.declaredBy}'`) + ? `${cause} (This run boots the crypto provider plugin '${crypto.declaredBy}' the host config declares, ` + + 'and re-wraps nothing without it. Nothing was opened or written.)' + : cause; if (json) { await emitJson({ error: 'boot_failed', message }, 1, { compact: true }); return; } printError(message); this.exit(1); return; } + // [#31007] The provider the boot chose, confirmed as `serve` confirms it. + // A refusal is held until the plan has a row to open, like a missing key. + let provider: OneShotCrypto['provider'] | null = null; + let providerRefusal: string | null = null; + try { + crypto.provider.confirm(); + provider = crypto.provider; + } catch (error) { + providerRefusal = error instanceof Error ? error.message : String(error); + } + try { // [#23622] Either mode's connect may have switched a SQLite file's // journal mode (`SqlDriver.applySqliteJournalMode`, one rule for every @@ -290,8 +329,16 @@ export default class SecretRewrap extends Command { return; } - // ── A row to open needs a key that already existed before this run ─── - if (plan.attempts > 0 && !provider) { + // ── A row to open needs the deployment's provider ──────────────────── + if (plan.attempts > 0 && providerRefusal !== null) { + if (json) { await emitJson({ error: 'crypto_provider_refused', message: providerRefusal }, 1, { compact: true }); return; } + printError(providerRefusal); + this.exit(1); + return; + } + + // ── …or a local key that already existed before this run ───────────── + if (plan.attempts > 0 && (!provider || keyUnavailable !== null)) { const message = 'Refusing to re-wrap: no existing data key was found (OS_SECRET_KEY, OS_DEV_CRYPTO_KEY or the ' + 'persisted key file), and a key minted now could open nothing that is stored. Run this with ' @@ -324,7 +371,7 @@ export default class SecretRewrap extends Command { mode, plan, result, - keySource: plan.attempts > 0 ? provider?.keySource ?? null : null, + keySource: plan.attempts > 0 ? keySourceOf(crypto) : null, }); const exitCode = flags.apply && rewrapUnfinished(result) ? 1 : 0; @@ -352,6 +399,15 @@ export default class SecretRewrap extends Command { } } +/** + * What the report names as the key's source: the declaring plugin's provider, + * or the local key's channel. Never key material. + */ +function keySourceOf(crypto: OneShotCrypto): string | null { + if (crypto.declaredBy !== null) return `crypto provider '${crypto.declaredBy}'`; + return crypto.key?.provider?.keySource ?? null; +} + async function confirm(question: string): Promise { if (!process.stdin.isTTY) return false; // non-interactive → require --yes const rl = createInterface({ input: process.stdin, output: process.stdout }); diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 22534a487d4..c14e9c4b18c 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -6356,6 +6356,30 @@ export function createHostCryptoProvider(local: () => ICryptoProvider): { return { provider, plugin }; } +/** + * The plugins of a composition that declare, in `providesServices` + * (ADR-0116), that they register {@link CRYPTO_PROVIDER_SERVICE} — by name, in + * composition order. A plugin composed twice under one `name` boots once (the + * later one), and is listed once, as that later instance. + * + * The one reading of "who provides the crypto provider" that `os serve` + * ({@link refuseTwoCryptoProviderPlugins}) and the one-shot commands + * (`utils/one-shot-settings.ts`) both take. + */ +export function cryptoProviderPlugins(composed: Iterable): Array<{ name: string; plugin: object }> { + const byName = new Map(); + for (const candidate of composed) { + const name = (candidate as { name?: unknown } | null)?.name; + if (typeof name === 'string') byName.set(name, candidate as object); + } + return [...byName] + .filter(([, plugin]) => { + const provides = (plugin as { providesServices?: unknown }).providesServices; + return Array.isArray(provides) && provides.includes(CRYPTO_PROVIDER_SERVICE); + }) + .map(([name, plugin]) => ({ name, plugin })); +} + /** * Refuse a composition in which more than one plugin declares, in * `providesServices` (ADR-0116), that it registers {@link CRYPTO_PROVIDER_SERVICE}. @@ -6368,17 +6392,7 @@ export function createHostCryptoProvider(local: () => ICryptoProvider): { * twice under one `name` boots once (the later one), and is counted once. */ export function refuseTwoCryptoProviderPlugins(composed: Iterable): void { - const byName = new Map(); - for (const candidate of composed) { - const name = (candidate as { name?: unknown } | null)?.name; - if (typeof name === 'string') byName.set(name, candidate); - } - const declaring = [...byName] - .filter(([, plugin]) => { - const provides = (plugin as { providesServices?: unknown }).providesServices; - return Array.isArray(provides) && provides.includes(CRYPTO_PROVIDER_SERVICE); - }) - .map(([name]) => name); + const declaring = cryptoProviderPlugins(composed).map(({ name }) => name); if (declaring.length > 1) { throw new HostCryptoProviderRefusal( `Refusing to boot: ${declaring.length} plugins provide the crypto provider ('${CRYPTO_PROVIDER_SERVICE}'): ` diff --git a/packages/cli/src/utils/data-migration-plugins.ts b/packages/cli/src/utils/data-migration-plugins.ts index ab801636f46..429d18b28b3 100644 --- a/packages/cli/src/utils/data-migration-plugins.ts +++ b/packages/cli/src/utils/data-migration-plugins.ts @@ -1,7 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { resolveStorageCapabilityArg, resolveStorageLocalRootEnv } from '../commands/serve.js'; -import { oneShotSettingsPlugin } from './one-shot-settings.js'; +import { oneShotSettingsPlugins } from './one-shot-settings.js'; /** * The plugins a gated data migration boots with. @@ -88,12 +88,17 @@ export async function buildDataMigrationPlugins( // currency and timezone (`localization.currency` / `.timezone`) from the // settings service; without it every organization reads as having no home // currency. The one-shot composition, as the storage arm below takes it. - plugins.push(await oneShotSettingsPlugin()); + plugins.push(...await oneShotSettingsPlugins()); } if (opts.storage === true) { + // [#31007] Not optional any more where it refuses: a refusal of the crypto + // composition (a declared provider this run cannot read) is the run's + // answer, never a reason to boot on without the settings service. + const { HostCryptoProviderRefusal } = await import('../commands/serve.js'); try { - plugins.push(await oneShotSettingsPlugin()); - } catch { + plugins.push(...await oneShotSettingsPlugins()); + } catch (error) { + if (error instanceof HostCryptoProviderRefusal) throw error; // optional — without it, constructor/env-driven storage config still applies } const { StorageServicePlugin } = await import('@objectstack/service-storage'); diff --git a/packages/cli/src/utils/one-shot-crypto-provider.test.ts b/packages/cli/src/utils/one-shot-crypto-provider.test.ts new file mode 100644 index 00000000000..5ebfc54e532 --- /dev/null +++ b/packages/cli/src/utils/one-shot-crypto-provider.test.ts @@ -0,0 +1,280 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A one-shot command seals and opens secrets with the provider `os serve` + * seals with on the same host, chosen by `serve`'s own function. + * + * ## The gap + * + * `os serve` seals every `sys_secret` row with the crypto provider a plugin of + * its stack registers as the kernel service `crypto-provider` (a KMS/Vault + * one, for customer-managed keys), else its own `LocalCryptoProvider` + * (`createHostCryptoProvider`, `commands/serve.ts`). The one-shot composition + * (`utils/one-shot-settings.ts`: `os secret rewrap`, `os secret orphans`, the + * data migrations' settings arm) always built the local provider, so on such a + * deployment it could open nothing `serve` sealed, and a re-wrap would have + * re-sealed under the local key. + * + * ## What this file pins + * + * Each case writes a host config into a fresh directory, composes + * {@link oneShotCrypto} over it, and boots the composition's plugins in a REAL + * `ObjectKernel`, the way `serve`'s own pins boot its host plugin: + * + * 1. one plugin declares and registers the provider: the run seals and opens + * with it, and the local key is never resolved; + * 2. no plugin declares one: the local provider over the key that already + * exists, which opens what a provider built the original way sealed and + * the other way round; with no key, a provider that refuses every call; + * 3. two declaring plugins: refused before either initializes, both named; + * 4. fail closed: a declared provider that cannot boot, or boots and + * registers none, refuses the boot naming it, and a host config or entry + * that cannot be read refuses before any boot — ⛔ never the local key. + * + * The command-level refusal, with the stored rows read back byte-equal, is in + * `commands/secret/rewrap.driver-contract.test.ts`. + * + * ⛔ No key material reaches a refusal: every refusal is checked against the + * test keys' bytes. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { ObjectKernel } from '@objectstack/core'; +import { LocalCryptoProvider } from '@objectstack/service-settings'; +import type { CryptoContext, CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts'; +import { CRYPTO_PROVIDER_SERVICE } from '@objectstack/types'; + +import { HostCryptoProviderRefusal } from '../commands/serve.js'; +import { oneShotCrypto, type OneShotCrypto } from './one-shot-settings.js'; + +/** The local key, when a case gives the run one. */ +const LOCAL_KEY_HEX = '606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f'; +/** The key behind the registered ("KMS") provider. Never the local one. */ +const KMS_KEY = Buffer.from('404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f', 'hex'); +const CTX: CryptoContext = { scope: 'settings', namespace: 'crypto_ns', key: 'api_key' }; + +/** A refusal carries no byte of either key, in any spelling a log would print. */ +function expectNoKeyMaterial(text: string): void { + for (const spelling of [LOCAL_KEY_HEX, KMS_KEY.toString('hex'), KMS_KEY.toString('base64')]) { + expect(text).not.toContain(spelling); + } +} + +/** The provider a test plugin registers: AES-GCM under {@link KMS_KEY}, every seal recorded. */ +function kmsProvider() { + const inner = new LocalCryptoProvider({ key: KMS_KEY }); + const sealed: string[] = []; + const provider: ICryptoProvider = { + async encrypt(plain: string, ctx: CryptoContext): Promise { + sealed.push(ctx.scope); + return { ...(await inner.encrypt(plain, ctx)), kmsKeyId: 'test-kms' }; + }, + decrypt: (handle, ctx) => inner.decrypt(handle, ctx), + rotateKey: (handle, ctx) => inner.rotateKey(handle, ctx), + digest: (plain) => inner.digest(plain), + keyedDigest: (plain) => inner.keyedDigest(plain), + }; + return { provider, sealed }; +} + +/** What a case's host config hands its `plugins`, read by the config module at load. */ +type Fixture = { plugins: unknown[] }; +const FIXTURE_KEY = '__os_one_shot_crypto_fixture'; + +/** A plugin that registers `provider` as the crypto provider during init, recording that it ran. */ +function providerPlugin(name: string, provider: unknown, inits: string[] = []) { + return { + name, + version: '1.0.0', + providesServices: [CRYPTO_PROVIDER_SERVICE], + init: async (ctx: { registerService(name: string, service: unknown): void }) => { + inits.push(name); + if (provider !== undefined) ctx.registerService(CRYPTO_PROVIDER_SERVICE, provider); + }, + }; +} + +/** The one service a kernel refuses to start without. Nothing here reads data. */ +const DATA_STUB = { + name: 'com.example.one-shot-crypto.data-stub', + version: '1.0.0', + init: async (ctx: { registerService(name: string, service: unknown): void }) => { ctx.registerService('data', {}); }, +}; + +const dirs: string[] = []; +afterEach(() => { + delete (globalThis as Record)[FIXTURE_KEY]; + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +/** + * A project directory whose `objectstack.config.mjs` exports `plugins` — the + * case's {@link Fixture}, or `source` verbatim. `null` writes no config. + */ +function project(config: Fixture | string | null): string { + const dir = mkdtempSync(join(tmpdir(), 'os-one-shot-crypto-')); + dirs.push(dir); + if (config === null) return dir; + if (typeof config === 'string') { + writeFileSync(join(dir, 'objectstack.config.mjs'), config); + return dir; + } + (globalThis as Record)[FIXTURE_KEY] = config; + writeFileSync( + join(dir, 'objectstack.config.mjs'), + `export default { name: 'one_shot_crypto_fixture', plugins: globalThis.${FIXTURE_KEY}.plugins };\n`, + ); + return dir; +} + +/** The env a case runs in: an empty key home, plus what the case adds. */ +function envWith(extra: Record = {}): NodeJS.ProcessEnv { + const home = mkdtempSync(join(tmpdir(), 'os-one-shot-crypto-home-')); + dirs.push(home); + return { OS_HOME: home, ...extra }; +} + +/** + * Boot the composition in a real kernel. The settings service is left out: it + * needs a data engine, and it holds `crypto.provider`, which is what is read. + */ +async function boot(crypto: OneShotCrypto) { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + await kernel.use(DATA_STUB); + for (const plugin of crypto.plugins) { + if ((plugin as { opts?: { cryptoProvider?: unknown } }).opts?.cryptoProvider !== undefined) continue; + await kernel.use(plugin as never); + } + await kernel.bootstrap(); + return kernel; +} + +/** The settings service the composition hands the boot, and the provider it holds. */ +function settingsProviderOf(crypto: OneShotCrypto): unknown { + const settings = crypto.plugins.find( + (p) => (p as { opts?: { cryptoProvider?: unknown } }).opts?.cryptoProvider !== undefined, + ) as { opts: { cryptoProvider: unknown } }; + return settings.opts.cryptoProvider; +} + +describe('one declared and registered provider seals and opens every secret of the run', () => { + it('the run uses the registered provider, the settings service holds it, and the local key is never resolved', async () => { + const kms = kmsProvider(); + const dir = project({ plugins: [providerPlugin('com.example.kms', kms.provider)] }); + const crypto = await oneShotCrypto({ cwd: dir, env: envWith() }); + + expect(crypto.declaredBy).toBe('com.example.kms'); + expect(crypto.key).toBeNull(); + expect(settingsProviderOf(crypto)).toBe(crypto.provider); + + await boot(crypto); + expect(crypto.provider.source).toBe('registered'); + expect(crypto.provider.confirm()).toBe(kms.provider); + + const handle = await crypto.provider.encrypt('kms-sealed', CTX); + expect(handle.kmsKeyId).toBe('test-kms'); + expect(kms.sealed).toEqual(['settings']); + expect(await crypto.provider.decrypt(handle, CTX)).toBe('kms-sealed'); + // Sealed under the KMS key, not the local one. + await expect(new LocalCryptoProvider({ key: Buffer.from(LOCAL_KEY_HEX, 'hex') }).decrypt(handle, CTX)).rejects.toThrow(); + }, 60_000); +}); + +describe('with no declaration, the provider is the local one over the key that already exists', () => { + it('an existing key: what it seals opens under a LocalCryptoProvider built the original way, and the other way round', async () => { + for (const dir of [project(null), project({ plugins: [{ name: 'com.example.unrelated', version: '1.0.0', init: async () => {} }] })]) { + const crypto = await oneShotCrypto({ cwd: dir, env: envWith({ OS_SECRET_KEY: LOCAL_KEY_HEX }) }); + expect(crypto.declaredBy).toBeNull(); + expect(crypto.key?.provider?.keySource).toBe('env:OS_SECRET_KEY'); + + await boot(crypto); + expect(crypto.provider.source).toBe('local'); + const original = new LocalCryptoProvider({ key: Buffer.from(LOCAL_KEY_HEX, 'hex') }); + expect(await original.decrypt(await crypto.provider.encrypt('local-sealed', CTX), CTX)).toBe('local-sealed'); + expect(await crypto.provider.decrypt(await original.encrypt('original-sealed', CTX), CTX)).toBe('original-sealed'); + } + }, 60_000); + + it('no key: the chosen provider refuses every call, naming why, and nothing is minted', async () => { + const env = envWith({ NODE_ENV: 'production' }); + const crypto = await oneShotCrypto({ cwd: project(null), env }); + expect(crypto.key?.provider).toBeNull(); + + await boot(crypto); + expect(crypto.provider.source).toBe('local'); + await expect(crypto.provider.encrypt('x', CTX)).rejects.toThrow(crypto.key!.unavailable!); + }, 60_000); +}); + +describe('two declaring plugins are refused before either initializes', () => { + it('both are named, and neither init() ran', async () => { + const inits: string[] = []; + const dir = project({ + plugins: [ + providerPlugin('com.example.kms-a', kmsProvider().provider, inits), + providerPlugin('com.example.kms-b', kmsProvider().provider, inits), + ], + }); + const refusal = await oneShotCrypto({ cwd: dir, env: envWith({ OS_SECRET_KEY: LOCAL_KEY_HEX }) }) + .then(() => null, (error: unknown) => error); + + expect(refusal).toBeInstanceOf(HostCryptoProviderRefusal); + expect(String((refusal as Error).message)).toContain("'com.example.kms-a' and 'com.example.kms-b'"); + expect(inits).toEqual([]); + expectNoKeyMaterial(String((refusal as Error).message)); + }, 60_000); +}); + +describe('fail closed: a declared provider this run cannot boot is refused by name, never replaced by the local key', () => { + it('a declaring plugin whose init() throws refuses the boot, naming it', async () => { + const dir = project({ + plugins: [{ + ...providerPlugin('com.example.kms-offline', undefined), + init: async () => { throw new Error('KMS endpoint unreachable'); }, + }], + }); + // A usable local key is present: the refusal must not fall back to it. + const crypto = await oneShotCrypto({ cwd: dir, env: envWith({ OS_SECRET_KEY: LOCAL_KEY_HEX }) }); + expect(crypto.key).toBeNull(); + + const refusal = await boot(crypto).then(() => null, (error: unknown) => error); + const message = String((refusal as Error | null)?.message); + expect(message).toContain("'com.example.kms-offline'"); + expect(message).toContain('KMS endpoint unreachable'); + expectNoKeyMaterial(message); + expect(crypto.provider.source).toBeUndefined(); + }, 60_000); + + it('a declaring plugin that boots and registers no provider refuses at kernel:ready, naming it', async () => { + const dir = project({ plugins: [providerPlugin('com.example.kms-silent', undefined)] }); + const crypto = await oneShotCrypto({ cwd: dir, env: envWith({ OS_SECRET_KEY: LOCAL_KEY_HEX }) }); + + const refusal = await boot(crypto).then(() => null, (error: unknown) => error); + const message = String((refusal as Error | null)?.message); + expect(message).toContain("'com.example.kms-silent'"); + expect(message).toContain('registered none'); + expectNoKeyMaterial(message); + await expect(crypto.provider.encrypt('x', CTX)).rejects.toThrow("'com.example.kms-silent'"); + }, 60_000); + + it('a host config that does not load is refused, naming it, before any boot', async () => { + const dir = project("throw new Error('config exploded');\n"); + const refusal = await oneShotCrypto({ cwd: dir, env: envWith({ OS_SECRET_KEY: LOCAL_KEY_HEX }) }) + .then(() => null, (error: unknown) => error); + expect(refusal).toBeInstanceOf(HostCryptoProviderRefusal); + expect(String((refusal as Error).message)).toContain('objectstack.config.mjs'); + expect(String((refusal as Error).message)).toContain("crypto provider ('crypto-provider')"); + }, 60_000); + + it('a plugins entry that does not resolve is refused, naming the entry, before any boot', async () => { + const dir = project("export default { name: 'one_shot_crypto_fixture', plugins: ['@objectstack-fixture/absent-kms-plugin'] };\n"); + const refusal = await oneShotCrypto({ cwd: dir, env: envWith({ OS_SECRET_KEY: LOCAL_KEY_HEX }) }) + .then(() => null, (error: unknown) => error); + expect(refusal).toBeInstanceOf(HostCryptoProviderRefusal); + expect(String((refusal as Error).message)).toContain("plugins[0] ('@objectstack-fixture/absent-kms-plugin')"); + }, 60_000); +}); diff --git a/packages/cli/src/utils/one-shot-settings.pin.test.ts b/packages/cli/src/utils/one-shot-settings.pin.test.ts index dc1ecb92101..9315321c0bc 100644 --- a/packages/cli/src/utils/one-shot-settings.pin.test.ts +++ b/packages/cli/src/utils/one-shot-settings.pin.test.ts @@ -43,7 +43,7 @@ import { fileURLToPath } from 'node:url'; import { LocalCryptoProvider, settleKeyFileChannel } from '@objectstack/service-settings'; // The one code/prose separator, typed by the hand-written `.d.mts` beside it. import { maskComments } from '../../../../scripts/js-comment-mask.mjs'; -import { oneShotSettingsPlugin, refusingCryptoProvider, resolveExistingDataKey } from './one-shot-settings.js'; +import { oneShotCrypto, refusingCryptoProvider, resolveExistingDataKey, type OneShotCrypto } from './one-shot-settings.js'; /** …/packages/cli/src/utils */ const HERE = resolve(fileURLToPath(import.meta.url), '..'); @@ -136,6 +136,25 @@ function providerOf(plugin: unknown): { encrypt: (...a: unknown[]) => Promise (p as { opts?: { cryptoProvider?: unknown } }).opts?.cryptoProvider !== undefined); +} + +/** + * [#31007] What the composition's host provider chooses once its boot is up, + * with no plugin registering a provider: its plugin's `init()` and + * `kernel:ready` hook, driven as a kernel drives them. + */ +async function chosenBy(crypto: OneShotCrypto): Promise { + const host = crypto.plugins.find((p) => (p as { name?: unknown }).name === 'com.objectstack.cli.host-crypto-provider') as + { init(ctx: unknown): Promise }; + const ready: Array<() => unknown> = []; + await host.init({ getServices: () => new Map(), hook: (_name: string, handler: () => unknown) => ready.push(handler) }); + for (const handler of ready) await handler(); + return crypto.provider.resolve(); +} + describe('[#21471] the one-shot helper never mints a data key', () => { it('the control: the default provider mints a key file in this posture and this home', () => { const minted = new LocalCryptoProvider(); @@ -149,10 +168,12 @@ describe('[#21471] the one-shot helper never mints a data key', () => { expect(typeof key.unavailable).toBe('string'); expect(key.unavailable).not.toBe(''); - const plugin = await oneShotSettingsPlugin(); - const provider = providerOf(plugin); - expect(provider).toBeDefined(); - expect(provider).not.toBeInstanceOf(LocalCryptoProvider); + const crypto = await oneShotCrypto(); + const provider = providerOf(settingsOf(crypto)); + // [#31007] The service holds `os serve`'s one host provider, which chooses + // the refusing one: no plugin registered a provider, and no key exists. + expect(provider).toBe(crypto.provider); + expect(await chosenBy(crypto)).not.toBeInstanceOf(LocalCryptoProvider); // The refusal carries why there is no key, so an operator reading it is told. await expect(provider.encrypt('x', { scope: 'settings', namespace: 'n', key: 'k' })) .rejects.toThrow(key.unavailable!); @@ -161,22 +182,22 @@ describe('[#21471] the one-shot helper never mints a data key', () => { // Even with the auto-key opt-in present in the environment. process.env.OS_CRYPTO_AUTOKEY = '1'; expect((await resolveExistingDataKey()).provider).toBeNull(); - await oneShotSettingsPlugin(); + await chosenBy(await oneShotCrypto()); expect(readdirSync(home)).toEqual([]); - }); + }, 60_000); it('a key file that exists is read, never rewritten, and is the one the service is handed', async () => { const file = join(home, 'dev-crypto-key'); writeFileSync(file, Buffer.from(KEY_HEX, 'hex').toString('base64'), { mode: 0o600 }); const before = readFileSync(file, 'utf8'); - const key = await resolveExistingDataKey(); - expect(key.provider?.keySource).toBe('file'); - const plugin = await oneShotSettingsPlugin(key); - expect(providerOf(plugin)).toBe(key.provider); + const crypto = await oneShotCrypto(); + expect(crypto.key?.provider?.keySource).toBe('file'); + expect(providerOf(settingsOf(crypto))).toBe(crypto.provider); + expect(await chosenBy(crypto)).toBe(crypto.key?.provider); expect(readdirSync(home)).toEqual(['dev-crypto-key']); expect(readFileSync(file, 'utf8')).toBe(before); - }); + }, 60_000); it('an env key is used, and the key home is never touched', async () => { process.env.OS_SECRET_KEY = KEY_HEX; diff --git a/packages/cli/src/utils/one-shot-settings.ts b/packages/cli/src/utils/one-shot-settings.ts index ef75b52a8fe..17673a5a70c 100644 --- a/packages/cli/src/utils/one-shot-settings.ts +++ b/packages/cli/src/utils/one-shot-settings.ts @@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'; import path from 'node:path'; import type { ICryptoProvider } from '@objectstack/spec/contracts'; +import type { HostCryptoProvider } from '../commands/serve.js'; import { resolveStartHome } from './start-home.js'; /** @@ -35,9 +36,34 @@ import { resolveStartHome } from './start-home.js'; * then reads as the settings service reads any value it cannot open (`null`, * with a warning), which is what a minted key would have produced too. * - * `os secret rewrap` resolves the key FIRST and hands the same instance to the - * service and to its own re-wrap, so no provider in that run mints a key. - * Every other caller lets {@link oneShotSettingsPlugin} resolve it. + * `os secret rewrap` composes the crypto FIRST ({@link oneShotCrypto}) and + * hands the same provider to the service and to its own re-wrap, so no + * provider in that run mints a key. Every other caller lets + * {@link oneShotSettingsPlugins} compose it. + * + * ## Which provider: the one `os serve` seals with (#31007) + * + * `os serve` seals every `sys_secret` row with the provider a plugin of its + * stack registers as the kernel service `crypto-provider`, else its own local + * one (`createHostCryptoProvider`, `commands/serve.ts`). A one-shot run opens + * and re-seals those same rows, so it chooses through that SAME function, over + * the plugins that DECLARE the provider in the host config's `plugins` — + * read by `serve`'s own rules (`stackBootPlugins`, `materializeStackPlugin`, + * `Serve.importConfigPlugin`, `cryptoProviderPlugins`): + * + * - one declaring plugin: it is composed into this run's boot, its `init()` + * registers the provider, and the run seals and opens with it. If it does + * not boot, or boots and registers none, the run refuses, naming it — ⛔ it + * never falls back to the local key, under which nothing that deployment + * sealed opens and under which a re-seal would be a downgrade; + * - two: refused, both named (`refuseTwoCryptoProviderPlugins`, `serve`'s); + * - none: the local provider over the key that already exists, as above; + * - a host config that does not load, or a `plugins` entry that does not + * materialize: refused, because whether a provider is declared cannot be + * read, and guessing "none" is the fallback the line above forbids. + * + * Only `plugins` is read, never `devPlugins`: the list `os serve` boots + * without `--dev`, and `os start`. * * ⛔ Nothing else in `src/` names `SettingsServicePlugin` or * `LocalCryptoProvider`, except `commands/serve.ts`, the long-lived host: @@ -133,15 +159,160 @@ export function refusingCryptoProvider(reason: string): ICryptoProvider { } /** - * The settings service for a one-shot boot: no routes, and the provider over - * `key` (resolved here when the caller has none of its own), or one that - * refuses every call. ⛔ Never the service's default provider. + * What a one-shot boot composes for its secrets, and the provider it seals and + * opens them with. + */ +export interface OneShotCrypto { + /** + * Composed into the boot, in this order: the plugin that declares the crypto + * provider (when the host config has one), the host's crypto-provider seam + * (`createHostCryptoProvider`, `os serve`'s), and the settings service over + * that seam's provider. ⛔ Never the settings service's default provider. + */ + plugins: unknown[]; + /** + * The provider the boot chose, at `kernel:ready` — `os serve`'s one host + * provider. Read it once the boot is up: before that it refuses. + */ + provider: HostCryptoProvider; + /** The plugin that declares the crypto provider, or `null` when none does. */ + declaredBy: string | null; + /** The local key, resolved when no plugin declares a provider; else `null`. */ + key: ExistingDataKey | null; +} + +/** + * Compose the crypto for a one-shot boot: the provider `os serve` would seal + * with on this host, chosen by `serve`'s own function. Throws a + * `HostCryptoProviderRefusal` — before anything boots — when two plugins + * declare the provider, or when the host config or one of its `plugins` + * cannot be read. See the module header. */ -export async function oneShotSettingsPlugin(key?: ExistingDataKey): Promise { - const resolved = key ?? await resolveExistingDataKey(); +export async function oneShotCrypto( + opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {}, +): Promise { + const cwd = opts.cwd ?? process.cwd(); + const { createHostCryptoProvider, HostCryptoProviderRefusal } = await import('../commands/serve.js'); + const declared = await readDeclaredCryptoProvider(cwd); const { SettingsServicePlugin } = await import('@objectstack/service-settings'); - return new SettingsServicePlugin({ - registerRoutes: false, - cryptoProvider: resolved.provider ?? refusingCryptoProvider(resolved.unavailable ?? 'no data key'), - }); + const settingsOver = (provider: ICryptoProvider) => new SettingsServicePlugin({ registerRoutes: false, cryptoProvider: provider }); + + if (declared) { + // The local fallback of a deployment that declares its provider is a + // refusal: the declaring plugin booted and registered nothing. + const host = createHostCryptoProvider(() => { + throw new HostCryptoProviderRefusal( + `Refusing to seal or open a secret: the plugin '${declared.name}' declares the crypto provider ` + + `('crypto-provider') in the host config, and registered none in this run. Every secret this ` + + 'deployment holds is sealed by that provider, so this run uses no other key. Nothing was opened or written.', + ); + }); + return { + plugins: [refusingNamedOnFailure(declared.plugin, declared.name, HostCryptoProviderRefusal), host.plugin, settingsOver(host.provider)], + provider: host.provider, + declaredBy: declared.name, + key: null, + }; + } + + const key = await resolveExistingDataKey(opts); + const host = createHostCryptoProvider( + () => key.provider ?? refusingCryptoProvider(key.unavailable ?? 'no data key'), + ); + return { plugins: [host.plugin, settingsOver(host.provider)], provider: host.provider, declaredBy: null, key }; +} + +/** + * The settings service for a one-shot boot, with the crypto it seals and opens + * through: no routes, `os serve`'s provider choice ({@link oneShotCrypto}, + * composed here when the caller has none of its own). Spread into the boot's + * plugin list. ⛔ Never the service's default provider. + */ +export async function oneShotSettingsPlugins(crypto?: OneShotCrypto): Promise { + return (crypto ?? await oneShotCrypto()).plugins; +} + +/** + * The one plugin of the host config that declares the crypto provider, or + * `null` when none does. Two are refused, both named. Read by `serve`'s rules + * for the same list (module header); ⛔ never guessed: an unreadable config or + * entry is refused, not read as "none". + */ +async function readDeclaredCryptoProvider(cwd: string): Promise<{ name: string; plugin: object } | null> { + const { findHostConfig } = await import('./schema-migration-plugins.js'); + const configPath = findHostConfig(cwd); + if (!configPath) return null; + const { default: Serve, cryptoProviderPlugins, refuseTwoCryptoProviderPlugins, HostCryptoProviderRefusal } = + await import('../commands/serve.js'); + const refuse = (what: string, error: unknown): never => { + throw new HostCryptoProviderRefusal( + `Refusing to seal or open a secret: ${what} could not be read (${error instanceof Error ? error.message : String(error)}), ` + + `so this run cannot tell whether a plugin provides the crypto provider ('crypto-provider') that \`os serve\` ` + + 'seals with, and it uses no key it cannot confirm. Nothing was opened or written.', + ); + }; + const configName = path.basename(configPath); + let config: unknown; + try { + const { loadConfig } = await import('./config.js'); + ({ config } = await loadConfig(configPath)); + } catch (error) { + return refuse(configName, error); + } + const { stackBootPlugins } = await import('./stack-collections.js'); + const { materializeStackPlugin } = await import('@objectstack/core'); + const hostRoot = path.dirname(configPath); + const composed: unknown[] = []; + for (const [index, entry] of stackBootPlugins(config, false).entries()) { + if (entry === undefined || entry === null || entry === false) continue; + try { + composed.push(await materializeStackPlugin(entry, { + importSpecifier: async (specifier) => Serve.importConfigPlugin(specifier, hostRoot), + // A bundle is app metadata `serve` wraps into an AppPlugin, which + // provides no crypto: read as it is, never wrapped or booted here. + wrapBundle: async (bundle) => bundle, + })); + } catch (error) { + return refuse(`${configName} plugins[${index}]${typeof entry === 'string' ? ` ('${entry}')` : ''}`, error); + } + } + refuseTwoCryptoProviderPlugins(composed); + return cryptoProviderPlugins(composed)[0] ?? null; +} + +/** + * `plugin`, with an `init()` that refuses naming it when it throws: the + * one-shot run boots the deployment's crypto provider plugin, and a failure + * there must say whose provider could not boot. Every other member is + * forwarded, `constructor` unbound so a class-name presence test still reads + * the plugin's own class. + */ +function refusingNamedOnFailure( + plugin: T, + name: string, + Refusal: new (message: string) => Error, +): T { + return new Proxy(plugin, { + get(target, prop) { + const value = (target as Record)[prop]; + if (prop === 'init' && typeof value === 'function') { + return async (...args: unknown[]): Promise => { + try { + return await Reflect.apply(value as (...a: unknown[]) => unknown, target, args); + } catch (error) { + throw new Refusal( + `Refusing to seal or open a secret: the plugin '${name}', which declares the crypto provider ` + + `('crypto-provider') in the host config, could not boot in this run ` + + `(${error instanceof Error ? error.message : String(error)}). Every secret this deployment holds is ` + + 'sealed by that provider, so this run uses no other key. Nothing was opened or written.', + ); + } + }; + } + if (typeof value === 'function' && prop !== 'constructor') { + return (value as (...a: unknown[]) => unknown).bind(target); + } + return value; + }, + }) as T; } From e82bb064300493750b2a3fdce690542839101a7f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 18:10:49 +0000 Subject: [PATCH 2/2] test(cli): pay the one-shot crypto composition's first loads at module top Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kDtnUcfoZfMJqLNWd --- .../secret/orphans.driver-contract.test.ts | 10 ++++++++++ .../commands/secret/rewrap.driver-contract.test.ts | 10 ++++++++++ .../cli/src/commands/secret/rewrap.guards.test.ts | 10 ++++++++++ .../cli/src/utils/one-shot-crypto-provider.test.ts | 14 ++++++++++++++ .../cli/src/utils/one-shot-settings.pin.test.ts | 5 +++++ 5 files changed, 49 insertions(+) diff --git a/packages/cli/src/commands/secret/orphans.driver-contract.test.ts b/packages/cli/src/commands/secret/orphans.driver-contract.test.ts index 52c0b53f309..57e45b4aeeb 100644 --- a/packages/cli/src/commands/secret/orphans.driver-contract.test.ts +++ b/packages/cli/src/commands/secret/orphans.driver-contract.test.ts @@ -63,6 +63,16 @@ import type { SecretReferenceEngineLike } from '../../utils/secret-reference-uni import { oneShotSettingsPlugins } from '../../utils/one-shot-settings.js'; import SecretOrphans from './orphans.js'; +// [#31007] Pay the first load of what the one-shot crypto composition reaches through +// dynamic `import()`s (the host config reader and `serve.ts`) at MODULE LOAD, outside +// any clocked case. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; + const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); diff --git a/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts b/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts index 5db4c8ef951..5a563246d89 100644 --- a/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts +++ b/packages/cli/src/commands/secret/rewrap.driver-contract.test.ts @@ -38,6 +38,16 @@ import type { SecretReferenceEngineLike } from '../../utils/secret-reference-uni import { oneShotSettingsPlugins } from '../../utils/one-shot-settings.js'; import SecretRewrap from './rewrap.js'; +// [#31007] Pay the first load of what the one-shot crypto composition reaches through +// dynamic `import()`s (the host config reader and `serve.ts`) at MODULE LOAD, outside +// any clocked case. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; + const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); diff --git a/packages/cli/src/commands/secret/rewrap.guards.test.ts b/packages/cli/src/commands/secret/rewrap.guards.test.ts index fa94a26699b..bd5bf3bf08b 100644 --- a/packages/cli/src/commands/secret/rewrap.guards.test.ts +++ b/packages/cli/src/commands/secret/rewrap.guards.test.ts @@ -40,6 +40,16 @@ import SecretRewrap from './rewrap.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; import { JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; +// [#31007] Pay the first load of what the one-shot crypto composition reaches through +// dynamic `import()`s (the host config reader and `serve.ts`) at MODULE LOAD, outside +// any clocked case. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; + vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: vi.fn() })); // Constructed and handed to the (mocked) boot, never used. vi.mock('@objectstack/platform-objects/plugin', () => ({ PlatformObjectsPlugin: class {} })); diff --git a/packages/cli/src/utils/one-shot-crypto-provider.test.ts b/packages/cli/src/utils/one-shot-crypto-provider.test.ts index 5ebfc54e532..a17ef9f335a 100644 --- a/packages/cli/src/utils/one-shot-crypto-provider.test.ts +++ b/packages/cli/src/utils/one-shot-crypto-provider.test.ts @@ -51,6 +51,20 @@ import { CRYPTO_PROVIDER_SERVICE } from '@objectstack/types'; import { HostCryptoProviderRefusal } from '../commands/serve.js'; import { oneShotCrypto, type OneShotCrypto } from './one-shot-settings.js'; +// [#31007] Pay the first load of what the one-shot crypto composition reaches through +// dynamic `import()`s (the host config reader and `serve.ts`) at MODULE LOAD, outside +// any clocked case. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/objectql'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-datasource'; + /** The local key, when a case gives the run one. */ const LOCAL_KEY_HEX = '606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f'; /** The key behind the registered ("KMS") provider. Never the local one. */ diff --git a/packages/cli/src/utils/one-shot-settings.pin.test.ts b/packages/cli/src/utils/one-shot-settings.pin.test.ts index 9315321c0bc..d0437b10ef6 100644 --- a/packages/cli/src/utils/one-shot-settings.pin.test.ts +++ b/packages/cli/src/utils/one-shot-settings.pin.test.ts @@ -45,6 +45,11 @@ import { LocalCryptoProvider, settleKeyFileChannel } from '@objectstack/service- import { maskComments } from '../../../../scripts/js-comment-mask.mjs'; import { oneShotCrypto, refusingCryptoProvider, resolveExistingDataKey, type OneShotCrypto } from './one-shot-settings.js'; +// [#31007] Pay the first load of what the one-shot crypto composition reaches through +// dynamic `import()`s (the host config reader and `serve.ts`) at MODULE LOAD, outside +// any clocked case. +import '@objectstack/core'; + /** …/packages/cli/src/utils */ const HERE = resolve(fileURLToPath(import.meta.url), '..'); /** …/packages/cli/src — the whole CLI source tree, this package's own. */