Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
748eee24ba | ||
|
|
517e1adad3 | ||
|
|
a266c88b7f | ||
|
|
3d348772ad | ||
|
|
ccb5913620 | ||
|
|
bdcdff5e31 | ||
|
|
1a77739410 | ||
|
|
09c75f3b10 | ||
|
|
93b81fac96 | ||
|
|
a4809d8c52 | ||
|
|
b4c468b3e7 |
No files matched your search
@@ -0,0 +1,305 @@
|
||||
/**
|
||||
* KBN-101-02a — DatabaseModule REDs.
|
||||
*
|
||||
* This module has no spec today, and it is where the cross-field hazard lands:
|
||||
* `detectAndAssertTier` early-returns on `tier === 'local'` without inspecting
|
||||
* `storage.type`, and DatabaseModule then builds a storage adapter from
|
||||
* `config.storage` independently and migrates it in `onModuleInit`. So
|
||||
* `tier: local` + `storage.type: postgres` skips the probe and still reaches
|
||||
* real Postgres DDL.
|
||||
*
|
||||
* `@mosaicstack/db` and `@mosaicstack/storage` are mocked, so no real
|
||||
* PostgreSQL connection can be constructed here even if a guard is missing.
|
||||
* The mocks are also the instrument.
|
||||
*
|
||||
* The providers are exercised through the module's own metadata rather than a
|
||||
* full Nest bootstrap: the factories are the unit under test, and booting Nest
|
||||
* would itself be a side effect these cases must prove does not happen.
|
||||
*/
|
||||
|
||||
import 'reflect-metadata';
|
||||
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const createDbMock = vi.fn(() => ({ db: {}, close: vi.fn() }));
|
||||
const createPgliteDbMock = vi.fn((dataDir: string) => ({ db: { dataDir }, close: vi.fn() }));
|
||||
const runPgliteMigrationsMock = vi.fn(async () => {});
|
||||
const createStorageAdapterMock = vi.fn((_storage?: unknown) => ({
|
||||
name: 'mock',
|
||||
migrate: vi.fn(async () => {}),
|
||||
close: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock('@mosaicstack/db', () => ({
|
||||
createDb: createDbMock,
|
||||
createPgliteDb: createPgliteDbMock,
|
||||
runPgliteMigrations: runPgliteMigrationsMock,
|
||||
runMigrations: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock('@mosaicstack/storage', () => ({
|
||||
createStorageAdapter: createStorageAdapterMock,
|
||||
detectAndAssertTier: vi.fn(async () => {}),
|
||||
TierDetectionError: class TierDetectionError extends Error {},
|
||||
}));
|
||||
|
||||
// Keep the transitive `../env.js` import inert: it calls loadGatewayEnv() as a
|
||||
// top-level side effect today.
|
||||
vi.mock('dotenv', () => {
|
||||
const config = vi.fn(() => ({ parsed: {} }));
|
||||
return { config, default: { config } };
|
||||
});
|
||||
vi.mock('@mosaicstack/config', () => ({
|
||||
loadConfig: vi.fn(() => ({ tier: 'local', storage: { type: 'pglite' } })),
|
||||
// env.ts reads `detectFromEnv().tier` at import time, so this must be an
|
||||
// object — returning undefined turns every case in this file into a setup
|
||||
// error rather than a behavioral red.
|
||||
detectFromEnv: vi.fn(() => ({ tier: undefined })),
|
||||
}));
|
||||
|
||||
type AnyProvider = { provide?: unknown; useFactory?: (...args: unknown[]) => unknown };
|
||||
|
||||
let envSnapshot: NodeJS.ProcessEnv;
|
||||
|
||||
beforeEach(() => {
|
||||
envSnapshot = { ...process.env };
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/**
|
||||
* Disposable fixture roots are removed, not merely created.
|
||||
*
|
||||
* A spec that mkdtemps per case and never unlinks leaks one directory per run
|
||||
* forever; verification runs of this suite left 166 of them on the verifier's
|
||||
* host. A suite that litters the machine it runs on is not a suite that can
|
||||
* claim to prove disposability of anything.
|
||||
*/
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
async function trackTempRoot(path: string): Promise<string> {
|
||||
tempRoots.push(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
process.env = { ...envSnapshot };
|
||||
vi.resetModules();
|
||||
while (tempRoots.length > 0) {
|
||||
const root = tempRoots.pop();
|
||||
if (root !== undefined) {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function loadModuleUnderTest(): Promise<{
|
||||
factoryFor: (token: unknown) => (...args: unknown[]) => unknown;
|
||||
tokens: { DB_HANDLE: unknown; STORAGE_ADAPTER: unknown };
|
||||
}> {
|
||||
const mod = await import('./database.module.js');
|
||||
const providers = (Reflect.getMetadata('providers', mod.DatabaseModule) ?? []) as AnyProvider[];
|
||||
|
||||
return {
|
||||
tokens: { DB_HANDLE: mod.DB_HANDLE, STORAGE_ADAPTER: mod.STORAGE_ADAPTER },
|
||||
factoryFor: (token: unknown) => {
|
||||
const provider = providers.find((candidate) => candidate.provide === token);
|
||||
expect(provider?.useFactory, 'provider factory not found').toBeDefined();
|
||||
return provider!.useFactory!;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Establish a valid frozen local policy and return its state root. */
|
||||
async function establishLocalChannel(): Promise<string> {
|
||||
const tempRoot = await trackTempRoot(await mkdtemp(join(tmpdir(), 'kbn-02a-dbmod-')));
|
||||
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
|
||||
const homeBase = join(tempRoot, 'home');
|
||||
const stateRoot = join(tempRoot, 'session-state');
|
||||
await mkdir(anchor, { recursive: true });
|
||||
await mkdir(homeBase, { recursive: true });
|
||||
await mkdir(stateRoot, { recursive: true });
|
||||
|
||||
const { establishFrozenLocalPolicy } = await import('../local-start/local-start-policy.js');
|
||||
establishFrozenLocalPolicy({
|
||||
declaration: { tier: 'local', storageType: 'pglite', queueType: 'local', stateRoot },
|
||||
anchor,
|
||||
homeBase,
|
||||
env: {},
|
||||
});
|
||||
return stateRoot;
|
||||
}
|
||||
|
||||
describe('KBN-101-02a DatabaseModule — the cross-field hazard', () => {
|
||||
it('refuses tier local + storage postgres instead of constructing a Postgres adapter', async () => {
|
||||
vi.resetModules();
|
||||
await establishLocalChannel();
|
||||
const { factoryFor, tokens } = await loadModuleUnderTest();
|
||||
|
||||
const hazardConfig = {
|
||||
tier: 'local',
|
||||
storage: { type: 'postgres', url: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
|
||||
};
|
||||
|
||||
// detectAndAssertTier never sees this shape: it early-returns on tier alone.
|
||||
expect(() => factoryFor(tokens.STORAGE_ADAPTER)(hazardConfig)).toThrow();
|
||||
expect(createStorageAdapterMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses tier local + storage postgres in the DB handle factory as well', async () => {
|
||||
vi.resetModules();
|
||||
await establishLocalChannel();
|
||||
const { factoryFor, tokens } = await loadModuleUnderTest();
|
||||
|
||||
const hazardConfig = {
|
||||
tier: 'local',
|
||||
storage: { type: 'postgres', url: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
|
||||
};
|
||||
|
||||
expect(() => factoryFor(tokens.DB_HANDLE)(hazardConfig)).toThrow();
|
||||
expect(createDbMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never calls createDb while the local policy is established', async () => {
|
||||
vi.resetModules();
|
||||
await establishLocalChannel();
|
||||
const { factoryFor, tokens } = await loadModuleUnderTest();
|
||||
|
||||
const nonLocal = { tier: 'standalone', storage: { type: 'postgres', url: 'postgresql://x/y' } };
|
||||
|
||||
expect(() => factoryFor(tokens.DB_HANDLE)(nonLocal)).toThrow();
|
||||
expect(createDbMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('KBN-101-02a DatabaseModule — state lives under the declared root', () => {
|
||||
it('derives the PGlite data dir from the frozen policy, not from homedir()', async () => {
|
||||
vi.resetModules();
|
||||
const stateRoot = await establishLocalChannel();
|
||||
const { factoryFor, tokens } = await loadModuleUnderTest();
|
||||
|
||||
factoryFor(tokens.DB_HANDLE)({ tier: 'local', storage: { type: 'pglite' } });
|
||||
|
||||
expect(createPgliteDbMock).toHaveBeenCalledTimes(1);
|
||||
const dataDir = createPgliteDbMock.mock.calls[0]?.[0] as string;
|
||||
// A homedir()-derived path is neither declared, session-created, nor
|
||||
// disposable, and it is shared with the daemon install.
|
||||
expect(dataDir.startsWith(`${stateRoot}/`)).toBe(true);
|
||||
expect(dataDir).not.toContain('.config/mosaic/gateway/pglite');
|
||||
});
|
||||
|
||||
it('derives the storage adapter data dir from the frozen policy', async () => {
|
||||
vi.resetModules();
|
||||
const stateRoot = await establishLocalChannel();
|
||||
const { factoryFor, tokens } = await loadModuleUnderTest();
|
||||
|
||||
factoryFor(tokens.STORAGE_ADAPTER)({ tier: 'local', storage: { type: 'pglite' } });
|
||||
|
||||
expect(createStorageAdapterMock).toHaveBeenCalledTimes(1);
|
||||
const passed = JSON.stringify(createStorageAdapterMock.mock.calls[0]?.[0] ?? {});
|
||||
expect(passed).toContain(stateRoot);
|
||||
});
|
||||
|
||||
it('reads the frozen policy rather than the injected config in the local channel', async () => {
|
||||
vi.resetModules();
|
||||
const stateRoot = await establishLocalChannel();
|
||||
const { factoryFor, tokens } = await loadModuleUnderTest();
|
||||
|
||||
// A config object that disagrees with the frozen policy must not win: the
|
||||
// policy is the single read, and there is no fallback to an independent one.
|
||||
factoryFor(tokens.DB_HANDLE)({
|
||||
tier: 'local',
|
||||
storage: { type: 'pglite', dataDir: '/somewhere/else' },
|
||||
});
|
||||
|
||||
const dataDir = createPgliteDbMock.mock.calls[0]?.[0] as string;
|
||||
expect(dataDir.startsWith(`${stateRoot}/`)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The lifecycle, not just the factories.
|
||||
*
|
||||
* Provider factories construct handles; `onModuleInit()` is what actually runs
|
||||
* DDL — `runPgliteMigrations(handle)` and `storageAdapter.migrate()`. A guard
|
||||
* placed only in the factories leaves that path reachable whenever a handle is
|
||||
* obtained by any other route, and every case above would stay green. These
|
||||
* cases drive the lifecycle hook directly.
|
||||
*/
|
||||
describe('KBN-101-02a DatabaseModule — migrations are a lifecycle effect, not a factory effect', () => {
|
||||
interface Handle {
|
||||
db: unknown;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
async function instantiate(config: unknown): Promise<{
|
||||
instance: { onModuleInit: () => Promise<void> };
|
||||
adapterMigrate: ReturnType<typeof vi.fn>;
|
||||
}> {
|
||||
const mod = await import('./database.module.js');
|
||||
const adapterMigrate = vi.fn(async () => {});
|
||||
const handle: Handle = { db: {}, close: vi.fn() };
|
||||
const adapter = { name: 'mock', migrate: adapterMigrate, close: vi.fn(async () => {}) };
|
||||
const instance = new mod.DatabaseModule(
|
||||
handle as never,
|
||||
adapter as never,
|
||||
config as never,
|
||||
) as unknown as { onModuleInit: () => Promise<void> };
|
||||
return { instance, adapterMigrate };
|
||||
}
|
||||
|
||||
it('refuses to migrate a postgres storage shape while the local policy is established', async () => {
|
||||
vi.resetModules();
|
||||
await establishLocalChannel();
|
||||
const { instance, adapterMigrate } = await instantiate({
|
||||
tier: 'local',
|
||||
storage: { type: 'postgres', url: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
|
||||
});
|
||||
|
||||
await expect(instance.onModuleInit()).rejects.toThrow(/LOCAL_START_/);
|
||||
expect(adapterMigrate, 'storage migrate() ran on a refusing start').not.toHaveBeenCalled();
|
||||
expect(runPgliteMigrationsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses to migrate a non-local tier while the local policy is established', async () => {
|
||||
vi.resetModules();
|
||||
await establishLocalChannel();
|
||||
const { instance, adapterMigrate } = await instantiate({
|
||||
tier: 'standalone',
|
||||
storage: { type: 'pglite' },
|
||||
});
|
||||
|
||||
await expect(instance.onModuleInit()).rejects.toThrow(/LOCAL_START_/);
|
||||
expect(adapterMigrate).not.toHaveBeenCalled();
|
||||
expect(runPgliteMigrationsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Acceptance #6 — the positive anchor, and the only case in this file that is
|
||||
// not a refusal.
|
||||
//
|
||||
// A refusal-only matrix is fully satisfied by an onModuleInit() that always
|
||||
// throws. Dead production behavior and correct fail-closed behavior would be
|
||||
// indistinguishable, and the item would ship having made local start safe by
|
||||
// making it not work. The previous case here swallowed the error
|
||||
// (`.catch(() => undefined)`) and then asserted zero migration, so it was
|
||||
// satisfied by the same dead implementation it was supposed to exclude.
|
||||
//
|
||||
// This is the case that fails if the sterile local route stops working.
|
||||
it('completes the sterile local lifecycle: PGlite and adapter migrations both run, no Postgres seam', async () => {
|
||||
vi.resetModules();
|
||||
await establishLocalChannel();
|
||||
const { instance, adapterMigrate } = await instantiate({
|
||||
tier: 'local',
|
||||
storage: { type: 'pglite' },
|
||||
});
|
||||
|
||||
await expect(instance.onModuleInit()).resolves.toBeUndefined();
|
||||
expect(runPgliteMigrationsMock, 'the sterile local route never migrated').toHaveBeenCalled();
|
||||
expect(adapterMigrate, 'the local storage adapter was never migrated').toHaveBeenCalled();
|
||||
expect(
|
||||
createDbMock,
|
||||
'a Postgres handle was constructed on the sterile local route',
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* KBN-101-02a — env.ts REDs.
|
||||
*
|
||||
* `loadGatewayEnv()` runs today as an unconditional top-level module side
|
||||
* effect (`env.ts` last line), so merely importing this module loads dotenv
|
||||
* files and re-reads configuration. Inside the local channel that is a second,
|
||||
* independent read behind the frozen policy's back.
|
||||
*
|
||||
* Two signals are distinguished deliberately, because they fire under different
|
||||
* conditions and a case that asserts the wrong one cannot fail for its stated
|
||||
* reason:
|
||||
* - `dotenv.config()` fires ONLY when the dotenv file exists, so any case
|
||||
* about it plants a real fixture under a temp anchor;
|
||||
* - `loadConfig()` fires unconditionally, so it is the signal for the
|
||||
* import-time side effect at the real anchors.
|
||||
*
|
||||
* The final describe block is a legacy-channel regression guard and passes
|
||||
* before implementation. It is not claimed as a RED.
|
||||
*/
|
||||
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
|
||||
|
||||
const dotenvConfigMock = vi.fn((_options?: unknown) => ({ parsed: {} }));
|
||||
const loadConfigMock = vi.fn(() => ({
|
||||
tier: 'local',
|
||||
storage: { type: 'pglite' },
|
||||
queue: { type: 'local' },
|
||||
}));
|
||||
const detectFromEnvMock = vi.fn(() => ({ tier: undefined }));
|
||||
|
||||
vi.mock('dotenv', () => ({ config: dotenvConfigMock, default: { config: dotenvConfigMock } }));
|
||||
|
||||
vi.mock('@mosaicstack/config', () => ({
|
||||
loadConfig: loadConfigMock,
|
||||
detectFromEnv: detectFromEnvMock,
|
||||
}));
|
||||
|
||||
let envSnapshot: NodeJS.ProcessEnv;
|
||||
|
||||
beforeEach(() => {
|
||||
envSnapshot = { ...process.env };
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/** Temp roots created by makeBed, removed after every case. */
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
process.env = { ...envSnapshot };
|
||||
for (const root of tempRoots.splice(0)) {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
interface Bed {
|
||||
anchor: string;
|
||||
homeBase: string;
|
||||
stateRoot: string;
|
||||
}
|
||||
|
||||
async function makeBed(): Promise<Bed> {
|
||||
const tempRoot = await mkdtemp(join(tmpdir(), 'kbn-02a-env-'));
|
||||
tempRoots.push(tempRoot);
|
||||
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
|
||||
const homeBase = join(tempRoot, 'home');
|
||||
const stateRoot = join(tempRoot, 'session-state');
|
||||
await mkdir(anchor, { recursive: true });
|
||||
await mkdir(homeBase, { recursive: true });
|
||||
await mkdir(stateRoot, { recursive: true });
|
||||
return { anchor, homeBase, stateRoot };
|
||||
}
|
||||
|
||||
/** Plant a dotenv the loader would find, so `config()` can actually fire. */
|
||||
async function plantDotenv(bed: Bed): Promise<void> {
|
||||
await writeFile(
|
||||
join(bed.anchor, '..', '.env'),
|
||||
`MOSAIC_STORAGE_TIER=standalone\nDATABASE_URL=${FORBIDDEN_DSN}\n`,
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
|
||||
async function establishLocalChannel(bed: Bed): Promise<void> {
|
||||
const { establishFrozenLocalPolicy } = await import('./local-start/local-start-policy.js');
|
||||
establishFrozenLocalPolicy({
|
||||
declaration: {
|
||||
tier: 'local',
|
||||
storageType: 'pglite',
|
||||
queueType: 'local',
|
||||
stateRoot: bed.stateRoot,
|
||||
},
|
||||
anchor: bed.anchor,
|
||||
homeBase: bed.homeBase,
|
||||
env: {},
|
||||
});
|
||||
}
|
||||
|
||||
describe('KBN-101-02a env.ts — inert inside the local channel', () => {
|
||||
it('performs no configuration re-read on import when the frozen local policy is established', async () => {
|
||||
vi.resetModules();
|
||||
const bed = await makeBed();
|
||||
await establishLocalChannel(bed);
|
||||
|
||||
await import('./env.js');
|
||||
|
||||
// The frozen policy is the only read in the local channel. This one fires
|
||||
// unconditionally today, from the module's top-level side effect.
|
||||
expect(loadConfigMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('loads no dotenv file when called under the frozen local policy', async () => {
|
||||
vi.resetModules();
|
||||
const bed = await makeBed();
|
||||
await plantDotenv(bed);
|
||||
await establishLocalChannel(bed);
|
||||
|
||||
const mod = await import('./env.js');
|
||||
dotenvConfigMock.mockClear();
|
||||
loadConfigMock.mockClear();
|
||||
|
||||
mod.loadGatewayEnv(bed.anchor, bed.homeBase);
|
||||
|
||||
// The guard lives inside loadGatewayEnv, not at its call site: a caller
|
||||
// anywhere in the local channel must not be able to reintroduce the load.
|
||||
expect(dotenvConfigMock).not.toHaveBeenCalled();
|
||||
expect(loadConfigMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not repopulate the ambient environment from a planted dotenv under the local policy', async () => {
|
||||
vi.resetModules();
|
||||
const bed = await makeBed();
|
||||
await plantDotenv(bed);
|
||||
await establishLocalChannel(bed);
|
||||
|
||||
const mod = await import('./env.js');
|
||||
dotenvConfigMock.mockClear();
|
||||
|
||||
mod.loadGatewayEnv(bed.anchor, bed.homeBase);
|
||||
|
||||
// A dotenv load here would repopulate process.env from files the policy
|
||||
// already inspected and refused to be governed by.
|
||||
const loadedPaths = dotenvConfigMock.mock.calls.map((call) => JSON.stringify(call[0] ?? null));
|
||||
expect(loadedPaths).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('KBN-101-02a env.ts — legacy channel unchanged (regression guard, not a RED)', () => {
|
||||
it('still performs its configuration read on import when no local policy is established', async () => {
|
||||
vi.resetModules();
|
||||
|
||||
await import('./env.js');
|
||||
|
||||
expect(loadConfigMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still loads a planted dotenv when no local policy is established', async () => {
|
||||
vi.resetModules();
|
||||
const bed = await makeBed();
|
||||
await plantDotenv(bed);
|
||||
|
||||
const mod = await import('./env.js');
|
||||
dotenvConfigMock.mockClear();
|
||||
|
||||
mod.loadGatewayEnv(bed.anchor, bed.homeBase);
|
||||
|
||||
expect(dotenvConfigMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Local-development entrypoint — KBN-101-02a.
|
||||
*
|
||||
* THE channel discriminator. Being this entrypoint is what makes a start a
|
||||
* local-development start; it is never inferred from tier value or from
|
||||
* configuration provenance. Its sole contract is local + PGlite, in an
|
||||
* explicitly declared, session-created, disposable state root.
|
||||
*
|
||||
* Import order here is load-bearing. This module statically imports ONLY the
|
||||
* policy and inventory modules, establishes the frozen policy, and only then
|
||||
* dynamically imports `bootstrap()` from `main.js`. The modules that are able
|
||||
* to open a connection are not loaded until the policy has been established —
|
||||
* which is what makes "refused before connection" a structural property rather
|
||||
* than an assertion.
|
||||
*
|
||||
* RED PHASE SCAFFOLDING. This stub establishes nothing correctly and performs
|
||||
* no dynamic import, so the behavioral and structural specs fail. Do not read
|
||||
* this file as the implementation — there is none yet.
|
||||
*/
|
||||
|
||||
import { establishFrozenLocalPolicy } from './local-start/local-start-policy.js';
|
||||
|
||||
/** Explicit, session-scoped declarations for this invocation. Nothing defaults. */
|
||||
export const LOCAL_DEV_TIER_VAR = 'MOSAIC_LOCAL_DEV_TIER';
|
||||
export const LOCAL_DEV_STORAGE_VAR = 'MOSAIC_LOCAL_DEV_STORAGE';
|
||||
export const LOCAL_DEV_QUEUE_VAR = 'MOSAIC_LOCAL_DEV_QUEUE';
|
||||
export const LOCAL_DEV_STATE_ROOT_VAR = 'MOSAIC_LOCAL_DEV_STATE_ROOT';
|
||||
|
||||
export async function runLocalDev(): Promise<void> {
|
||||
// RED-phase stub: establishes via the permissive policy stub and stops. It
|
||||
// performs no dynamic import of bootstrap, so nothing starts. See header.
|
||||
establishFrozenLocalPolicy({
|
||||
declaration: {
|
||||
tier: process.env[LOCAL_DEV_TIER_VAR],
|
||||
storageType: process.env[LOCAL_DEV_STORAGE_VAR],
|
||||
queueType: process.env[LOCAL_DEV_QUEUE_VAR],
|
||||
stateRoot: process.env[LOCAL_DEV_STATE_ROOT_VAR],
|
||||
},
|
||||
anchor: import.meta.dirname,
|
||||
homeBase: '',
|
||||
env: process.env,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
/**
|
||||
* KBN-101-02a — local-start policy REDs.
|
||||
*
|
||||
* Covers mutation->guard rows 7 (exact local tier), 8 (exact PGlite + disposable
|
||||
* state root), and the freeze half of row 9 (one-shot freeze).
|
||||
*
|
||||
* The policy module holds one-shot module state, so every case re-imports it
|
||||
* through `vi.resetModules()` rather than sharing an established policy.
|
||||
*
|
||||
* Nothing here connects to anything. DSN strings are fixture text.
|
||||
*/
|
||||
|
||||
import type * as NodeFs from 'node:fs';
|
||||
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type * as PolicyNamespace from './local-start-policy.js';
|
||||
import type {
|
||||
EstablishInput,
|
||||
LocalStartDeclaration,
|
||||
LocalStartRefusalCode,
|
||||
} from './local-start-policy.js';
|
||||
import type { LocalStartSourceLabel } from './source-inventory.js';
|
||||
|
||||
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
|
||||
|
||||
type PolicyModule = typeof PolicyNamespace;
|
||||
|
||||
/** Fresh module state per case — the freeze is one-shot and has no reset API. */
|
||||
async function freshPolicy(): Promise<PolicyModule> {
|
||||
vi.resetModules();
|
||||
return import('./local-start-policy.js');
|
||||
}
|
||||
|
||||
/** Undo module substitutions so one case's mock cannot leak into the next. */
|
||||
const mockedFsCases: (() => void)[] = [];
|
||||
/** Temp roots created by makeBed, removed after every case. */
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (mockedFsCases.length > 0) {
|
||||
mockedFsCases.pop()?.();
|
||||
}
|
||||
for (const root of tempRoots.splice(0)) {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
interface Bed {
|
||||
tempRoot: string;
|
||||
anchor: string;
|
||||
homeBase: string;
|
||||
stateRoot: string;
|
||||
}
|
||||
|
||||
/** A clean layout: no source carries anything forbidden. */
|
||||
async function makeBed(): Promise<Bed> {
|
||||
const tempRoot = await mkdtemp(join(tmpdir(), 'kbn-02a-policy-'));
|
||||
tempRoots.push(tempRoot);
|
||||
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
|
||||
const homeBase = join(tempRoot, 'home');
|
||||
const stateRoot = join(tempRoot, 'session-state');
|
||||
await mkdir(anchor, { recursive: true });
|
||||
await mkdir(homeBase, { recursive: true });
|
||||
await mkdir(stateRoot, { recursive: true });
|
||||
return { tempRoot, anchor, homeBase, stateRoot };
|
||||
}
|
||||
|
||||
function validDeclaration(stateRoot: string): LocalStartDeclaration {
|
||||
return { tier: 'local', storageType: 'pglite', queueType: 'local', stateRoot };
|
||||
}
|
||||
|
||||
function establishInput(bed: Bed, overrides: Partial<EstablishInput> = {}): EstablishInput {
|
||||
return {
|
||||
declaration: validDeclaration(bed.stateRoot),
|
||||
anchor: bed.anchor,
|
||||
homeBase: bed.homeBase,
|
||||
env: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Assert the call refused, with the exact code, carrying no value. */
|
||||
async function expectRefusal(
|
||||
policy: PolicyModule,
|
||||
input: EstablishInput,
|
||||
code: LocalStartRefusalCode,
|
||||
): Promise<void> {
|
||||
let thrown: unknown;
|
||||
try {
|
||||
policy.establishFrozenLocalPolicy(input);
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
|
||||
expect(thrown, `expected a refusal with code ${code}, got none`).toBeInstanceOf(
|
||||
policy.LocalStartRefusal,
|
||||
);
|
||||
const refusal = thrown as InstanceType<PolicyModule['LocalStartRefusal']>;
|
||||
expect(refusal.code).toBe(code);
|
||||
// A refusal that echoed the offending value would move the secret into the
|
||||
// log, which is the failure this item exists to prevent.
|
||||
const serialized = `${refusal.message} ${JSON.stringify(refusal.sourceLabels)}`;
|
||||
expect(serialized).not.toContain(FORBIDDEN_DSN);
|
||||
expect(serialized).not.toContain('mosaic:mosaic');
|
||||
}
|
||||
|
||||
describe('KBN-101-02a establishFrozenLocalPolicy — row 7, exact local tier', () => {
|
||||
it('refuses when no tier is declared: absent is not local', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), tier: undefined },
|
||||
}),
|
||||
'LOCAL_START_TIER_NOT_EXPLICIT',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses an empty tier: empty is not local', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), tier: '' },
|
||||
}),
|
||||
'LOCAL_START_TIER_NOT_EXPLICIT',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a declared non-local tier inside the local channel', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), tier: 'standalone' },
|
||||
}),
|
||||
'LOCAL_START_NON_LOCAL_TIER',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a near-miss tier: matching is exact, not normalized', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), tier: ' Local ' },
|
||||
}),
|
||||
'LOCAL_START_NON_LOCAL_TIER',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a non-local tier found in a source even when the declaration is local', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeFile(join(bed.anchor, '..', '.env'), 'MOSAIC_STORAGE_TIER=federated\n', 'utf8');
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_NON_LOCAL_TIER');
|
||||
});
|
||||
|
||||
it('refuses a PostgreSQL DSN found in a source, naming the source label but not the value', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeFile(join(bed.anchor, '..', '.env'), `DATABASE_URL=${FORBIDDEN_DSN}\n`, 'utf8');
|
||||
const policy = await freshPolicy();
|
||||
|
||||
let thrown: unknown;
|
||||
try {
|
||||
policy.establishFrozenLocalPolicy(establishInput(bed));
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
|
||||
expect(thrown).toBeInstanceOf(policy.LocalStartRefusal);
|
||||
const refusal = thrown as InstanceType<PolicyModule['LocalStartRefusal']>;
|
||||
expect(refusal.code).toBe('LOCAL_START_POSTGRES_DSN_PRESENT');
|
||||
expect(refusal.sourceLabels).toContain('gateway-local-dotenv');
|
||||
expect(refusal.message).not.toContain(FORBIDDEN_DSN);
|
||||
});
|
||||
|
||||
it('refuses an inherited-environment DSN that precedence would have discarded', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, { env: { DATABASE_URL: FORBIDDEN_DSN } }),
|
||||
'LOCAL_START_POSTGRES_DSN_PRESENT',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses the default DSN constant, which is itself a PostgreSQL DSN', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
// No role classification is attempted: proving a DSN non-superuser requires
|
||||
// connecting, and connecting is the thing being prevented.
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
env: { DATABASE_URL: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
|
||||
}),
|
||||
'LOCAL_START_POSTGRES_DSN_PRESENT',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('KBN-101-02a establishFrozenLocalPolicy — row 8, PGlite and disposable state root', () => {
|
||||
it('refuses a non-pglite storage type', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), storageType: 'postgres' },
|
||||
}),
|
||||
'LOCAL_START_STORAGE_NOT_PGLITE',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a files storage type: only pglite is admitted, not merely "not postgres"', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), storageType: 'files' },
|
||||
}),
|
||||
'LOCAL_START_STORAGE_NOT_PGLITE',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses an undeclared storage type rather than defaulting it', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), storageType: undefined },
|
||||
}),
|
||||
'LOCAL_START_STORAGE_NOT_PGLITE',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a non-local queue', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), queueType: 'bullmq' },
|
||||
}),
|
||||
'LOCAL_START_QUEUE_NOT_LOCAL',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses an undeclared state root rather than falling back to HOME or CWD', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: undefined },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_MISSING',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses an empty state root', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: '' },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_MISSING',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a relative state root', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: './local-state' },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_NOT_ABSOLUTE',
|
||||
);
|
||||
});
|
||||
|
||||
// The traversal segment is concatenated, NOT built with join(). `join()`
|
||||
// normalizes `a/../a` to `a` before the policy is ever called, so a case built
|
||||
// that way asserts a refusal on a string identical to the valid one — it can
|
||||
// only be made green by also refusing the valid declaration. A red that cannot
|
||||
// go green for its stated reason is the same defect class as a green that
|
||||
// cannot go red.
|
||||
it('refuses a state root that is not its own canonical form', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
const noncanonical = `${bed.tempRoot}/session-state/../session-state`;
|
||||
expect(noncanonical).not.toBe(bed.stateRoot);
|
||||
expect(noncanonical).toContain('/../');
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: noncanonical },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_ESCAPES',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a state root that does not exist rather than creating it', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
const absent = join(bed.tempRoot, 'never-created');
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: absent },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_ABSENT',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a state root that exists but is a file', async () => {
|
||||
const bed = await makeBed();
|
||||
const notADir = join(bed.tempRoot, 'a-file');
|
||||
await writeFile(notADir, 'not a directory\n', 'utf8');
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: notADir },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_NOT_DIRECTORY',
|
||||
);
|
||||
});
|
||||
|
||||
// lstat, not stat: a stat on a symlinked root reports the TARGET, so every
|
||||
// later bar would describe a directory the operator never named.
|
||||
it('refuses a state root that is itself a symlink, even to a valid directory', async () => {
|
||||
const bed = await makeBed();
|
||||
const realRoot = join(bed.tempRoot, 'real-root');
|
||||
await mkdir(realRoot, { recursive: true, mode: 0o700 });
|
||||
const linkedRoot = join(bed.tempRoot, 'linked-root');
|
||||
await symlink(realRoot, linkedRoot, 'dir');
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: linkedRoot },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_IS_SYMLINK',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a state root readable by group or other', async () => {
|
||||
const bed = await makeBed();
|
||||
const shared = join(bed.tempRoot, 'shared-root');
|
||||
await mkdir(shared, { recursive: true });
|
||||
await chmod(shared, 0o755);
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(
|
||||
policy,
|
||||
establishInput(bed, {
|
||||
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: shared },
|
||||
}),
|
||||
'LOCAL_START_STATE_ROOT_NOT_PRIVATE',
|
||||
);
|
||||
});
|
||||
|
||||
// Ownership is the one bar that cannot be built on the filesystem without
|
||||
// privileges: an unprivileged process cannot chown, and a privileged one owns
|
||||
// everything it creates, so a filesystem-built case would pass trivially
|
||||
// wherever CI runs as root. That is a vacuous case, not a cheap one. The stat
|
||||
// result is therefore substituted directly. This couples the case to the
|
||||
// mechanism (the implementation must learn ownership from an lstat), which is
|
||||
// inherent to the bar rather than an accident of this test.
|
||||
it('refuses a state root owned by another user', async () => {
|
||||
const bed = await makeBed();
|
||||
const foreignUid = (process.getuid?.() ?? 0) + 1;
|
||||
vi.resetModules();
|
||||
vi.doMock('node:fs', async () => {
|
||||
const actual = await vi.importActual<typeof NodeFs>('node:fs');
|
||||
return {
|
||||
...actual,
|
||||
lstatSync: (target: string, ...rest: unknown[]) => {
|
||||
const stats = (
|
||||
actual.lstatSync as unknown as (...args: unknown[]) => Record<string, unknown>
|
||||
)(target, ...rest);
|
||||
if (target === bed.stateRoot) {
|
||||
return {
|
||||
...stats,
|
||||
uid: foreignUid,
|
||||
isDirectory: () => true,
|
||||
isSymbolicLink: () => false,
|
||||
};
|
||||
}
|
||||
return stats;
|
||||
},
|
||||
};
|
||||
});
|
||||
mockedFsCases.push(() => {
|
||||
vi.doUnmock('node:fs');
|
||||
});
|
||||
const policy = await import('./local-start-policy.js');
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_STATE_ROOT_NOT_OWNED');
|
||||
});
|
||||
|
||||
it('refuses when a derived child escapes the state root through a symlink', async () => {
|
||||
const bed = await makeBed();
|
||||
const escapeTarget = join(bed.tempRoot, 'outside');
|
||||
await mkdir(escapeTarget, { recursive: true });
|
||||
// The DB child is a symlink pointing out of the disposable root: state
|
||||
// written "under" the root would land outside it.
|
||||
await symlink(escapeTarget, join(bed.stateRoot, 'db'), 'dir');
|
||||
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_STATE_ROOT_ESCAPES');
|
||||
});
|
||||
|
||||
it('refuses the cross-field local+postgres shape that the tier probe does not catch', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeFile(
|
||||
join(bed.anchor, '..', 'mosaic.config.json'),
|
||||
JSON.stringify({ tier: 'local', storage: { type: 'postgres', url: FORBIDDEN_DSN } }),
|
||||
'utf8',
|
||||
);
|
||||
const policy = await freshPolicy();
|
||||
// detectAndAssertTier early-returns on tier === 'local' without inspecting
|
||||
// storage.type, so this shape reaches real Postgres DDL today.
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_CROSS_FIELD_MISMATCH');
|
||||
});
|
||||
});
|
||||
|
||||
describe('KBN-101-02a establishFrozenLocalPolicy — row 9, one-shot freeze', () => {
|
||||
it('returns a deep-frozen allowed-only policy', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
const frozen = policy.establishFrozenLocalPolicy(establishInput(bed));
|
||||
|
||||
expect(Object.isFrozen(frozen)).toBe(true);
|
||||
expect(Object.isFrozen(frozen.storage)).toBe(true);
|
||||
expect(Object.isFrozen(frozen.queue)).toBe(true);
|
||||
expect(frozen.tier).toBe('local');
|
||||
expect(frozen.storage.type).toBe('pglite');
|
||||
expect(frozen.queue.type).toBe('local');
|
||||
});
|
||||
|
||||
it('resolves every derived child beneath the declared state root', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
const frozen = policy.establishFrozenLocalPolicy(establishInput(bed));
|
||||
|
||||
expect(frozen.stateRoot).toBe(bed.stateRoot);
|
||||
expect(frozen.storage.dataDir.startsWith(`${bed.stateRoot}/`)).toBe(true);
|
||||
expect(frozen.queue.dataDir.startsWith(`${bed.stateRoot}/`)).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a second establish: the policy is one-shot and there is no reset API', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
policy.establishFrozenLocalPolicy(establishInput(bed));
|
||||
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_ALREADY_ESTABLISHED');
|
||||
expect(Object.keys(policy)).not.toContain('resetFrozenLocalPolicy');
|
||||
});
|
||||
|
||||
it('is unaffected by mutating the inputs after establish: the policy is a deep clone', async () => {
|
||||
const bed = await makeBed();
|
||||
const policy = await freshPolicy();
|
||||
const env: Record<string, string | undefined> = {};
|
||||
const frozen = policy.establishFrozenLocalPolicy(establishInput(bed, { env }));
|
||||
const dataDirBefore = frozen.storage.dataDir;
|
||||
|
||||
env['DATABASE_URL'] = FORBIDDEN_DSN;
|
||||
env['MOSAIC_STORAGE_TIER'] = 'standalone';
|
||||
|
||||
const observed = policy.getFrozenLocalPolicy();
|
||||
expect(observed?.storage.dataDir).toBe(dataDirBefore);
|
||||
expect(observed?.tier).toBe('local');
|
||||
expect(observed?.storage.type).toBe('pglite');
|
||||
});
|
||||
|
||||
it('refuses to serve a policy when the local channel was never established', async () => {
|
||||
const policy = await freshPolicy();
|
||||
expect(policy.getFrozenLocalPolicy()).toBeUndefined();
|
||||
expect(() => policy.requireFrozenLocalPolicy()).toThrow(policy.LocalStartRefusal);
|
||||
});
|
||||
|
||||
it('does not fall back to an independent config read when unestablished', async () => {
|
||||
const policy = await freshPolicy();
|
||||
// No `getFrozen() ?? loadConfig()` masking: the local and legacy channels
|
||||
// must not fall through to one another.
|
||||
let thrown: unknown;
|
||||
try {
|
||||
policy.requireFrozenLocalPolicy();
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
expect((thrown as { code?: string }).code).toBe('LOCAL_START_POLICY_NOT_ESTABLISHED');
|
||||
});
|
||||
});
|
||||
|
||||
/** Where each file source lives, relative to the bed's anchor and home base. */
|
||||
function sourcePath(
|
||||
bed: Bed,
|
||||
label: Exclude<LocalStartSourceLabel, 'process-environment'>,
|
||||
): string {
|
||||
const repo = join(bed.anchor, '..', '..', '..');
|
||||
const daemonDir = join(bed.homeBase, '.config', 'mosaic', 'gateway');
|
||||
const paths: Record<Exclude<LocalStartSourceLabel, 'process-environment'>, string> = {
|
||||
'daemon-dotenv': join(daemonDir, '.env'),
|
||||
'monorepo-root-dotenv': join(repo, '.env'),
|
||||
'gateway-local-dotenv': join(repo, 'apps', 'gateway', '.env'),
|
||||
'daemon-json': join(daemonDir, 'mosaic.config.json'),
|
||||
'app-json': join(repo, 'apps', 'gateway', 'mosaic.config.json'),
|
||||
'monorepo-root-json': join(repo, 'mosaic.config.json'),
|
||||
};
|
||||
return paths[label];
|
||||
}
|
||||
|
||||
const CLEAN_LOCAL_JSON = JSON.stringify({
|
||||
tier: 'local',
|
||||
storage: { type: 'pglite' },
|
||||
queue: { type: 'local' },
|
||||
memory: { type: 'none' },
|
||||
});
|
||||
|
||||
async function writeSource(bed: Bed, label: Parameters<typeof sourcePath>[1], body: string) {
|
||||
const path = sourcePath(bed, label);
|
||||
await mkdir(join(path, '..'), { recursive: true });
|
||||
await writeFile(path, body, 'utf8');
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* A source that cannot be read or parsed has UNKNOWN contents, and an unknown
|
||||
* source has not been shown to be free of a forbidden value. Skipping it — or
|
||||
* letting a clean higher-precedence source stand in for it — is precisely the
|
||||
* "a forbidden value refuses even when shadowed" rule failing in its other
|
||||
* direction: here the forbidden value is not absent, it is unreadable.
|
||||
*/
|
||||
describe('KBN-101-02a establishFrozenLocalPolicy — unreadable and malformed sources', () => {
|
||||
it('refuses malformed JSON in a LOSING source even when the winning source is clean', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
|
||||
await writeSource(bed, 'app-json', '{ "tier": "local", ');
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_SOURCE_MALFORMED');
|
||||
});
|
||||
|
||||
it('refuses malformed JSON in the daemon config specifically', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
|
||||
await writeSource(bed, 'daemon-json', 'not json at all');
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_SOURCE_MALFORMED');
|
||||
});
|
||||
|
||||
// A directory where a file is expected fails the read with EISDIR for every
|
||||
// uid. Mode 0o000 would not: a process running as root reads it anyway, so
|
||||
// that case would pass trivially in exactly the environments CI uses.
|
||||
it('refuses a source that cannot be read at all', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
|
||||
await mkdir(sourcePath(bed, 'gateway-local-dotenv'), { recursive: true });
|
||||
const policy = await freshPolicy();
|
||||
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_SOURCE_UNREADABLE');
|
||||
});
|
||||
|
||||
it('names the offending source label without quoting its contents', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeSource(bed, 'app-json', `{ "tier": "local", "note": "${FORBIDDEN_DSN}"`);
|
||||
const policy = await freshPolicy();
|
||||
let thrown: unknown;
|
||||
try {
|
||||
policy.establishFrozenLocalPolicy(establishInput(bed));
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
const refusal = thrown as InstanceType<PolicyModule['LocalStartRefusal']>;
|
||||
expect(refusal?.code).toBe('LOCAL_START_SOURCE_MALFORMED');
|
||||
expect(refusal.sourceLabels).toContain('app-json');
|
||||
expect(`${refusal.message} ${JSON.stringify(refusal.sourceLabels)}`).not.toContain(
|
||||
FORBIDDEN_DSN,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The freeze is a promise about the FUTURE, and a snapshot taken at establish
|
||||
* time proves nothing about it. These cases mutate the underlying sources after
|
||||
* establish and then read the policy back: a consumer that re-reads a file on
|
||||
* demand, or holds a live reference into one, fails here and passes every case
|
||||
* that only inspects the object returned at establish time.
|
||||
*/
|
||||
describe('KBN-101-02a establishFrozenLocalPolicy — the freeze survives source mutation', () => {
|
||||
it('retains the frozen policy after a source file is rewritten to carry a DSN', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
|
||||
const policy = await freshPolicy();
|
||||
const established = policy.establishFrozenLocalPolicy(establishInput(bed));
|
||||
|
||||
await writeSource(
|
||||
bed,
|
||||
'monorepo-root-json',
|
||||
JSON.stringify({
|
||||
tier: 'standalone',
|
||||
storage: { type: 'postgres', url: FORBIDDEN_DSN },
|
||||
queue: { type: 'bullmq' },
|
||||
memory: { type: 'none' },
|
||||
}),
|
||||
);
|
||||
|
||||
const after = policy.requireFrozenLocalPolicy();
|
||||
expect(after).toBe(established);
|
||||
expect(after.tier).toBe('local');
|
||||
expect(after.storage.type).toBe('pglite');
|
||||
expect(JSON.stringify(after)).not.toContain(FORBIDDEN_DSN);
|
||||
});
|
||||
|
||||
it('retains the frozen policy after the ambient environment gains a DSN', async () => {
|
||||
const bed = await makeBed();
|
||||
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
|
||||
const policy = await freshPolicy();
|
||||
const env: Record<string, string | undefined> = {};
|
||||
const established = policy.establishFrozenLocalPolicy(establishInput(bed, { env }));
|
||||
|
||||
env['DATABASE_URL'] = FORBIDDEN_DSN;
|
||||
|
||||
const after = policy.requireFrozenLocalPolicy();
|
||||
expect(after).toBe(established);
|
||||
expect(after.storage.type).toBe('pglite');
|
||||
expect(JSON.stringify(after)).not.toContain(FORBIDDEN_DSN);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Local-start policy — KBN-101-02a.
|
||||
*
|
||||
* The fail-closed refusal, and the single frozen policy the whole local channel
|
||||
* consumes. Refusal happens before any connection is opened and before any DDL
|
||||
* is executed; the modules that are able to connect are not loaded until this
|
||||
* has run.
|
||||
*
|
||||
* RED PHASE SCAFFOLDING. The signatures and codes below are the contract; the
|
||||
* bodies are deliberately permissive stubs that admit everything and freeze
|
||||
* nothing, so the behavioral specs fail on their assertions rather than on a
|
||||
* missing module. Do not read this file as the implementation — there is none
|
||||
* yet.
|
||||
*/
|
||||
|
||||
import type { LocalStartSourceLabel } from './source-inventory.js';
|
||||
|
||||
/** Stable refusal codes. Errors expose labels and codes only — never values. */
|
||||
export type LocalStartRefusalCode =
|
||||
| 'LOCAL_START_POSTGRES_DSN_PRESENT'
|
||||
| 'LOCAL_START_NON_LOCAL_TIER'
|
||||
| 'LOCAL_START_TIER_NOT_EXPLICIT'
|
||||
| 'LOCAL_START_STORAGE_NOT_PGLITE'
|
||||
| 'LOCAL_START_QUEUE_NOT_LOCAL'
|
||||
| 'LOCAL_START_STATE_ROOT_MISSING'
|
||||
| 'LOCAL_START_STATE_ROOT_NOT_ABSOLUTE'
|
||||
| 'LOCAL_START_STATE_ROOT_ESCAPES'
|
||||
| 'LOCAL_START_STATE_ROOT_ABSENT'
|
||||
| 'LOCAL_START_STATE_ROOT_NOT_DIRECTORY'
|
||||
| 'LOCAL_START_STATE_ROOT_IS_SYMLINK'
|
||||
| 'LOCAL_START_STATE_ROOT_NOT_PRIVATE'
|
||||
| 'LOCAL_START_STATE_ROOT_NOT_OWNED'
|
||||
| 'LOCAL_START_SOURCE_UNREADABLE'
|
||||
| 'LOCAL_START_SOURCE_MALFORMED'
|
||||
| 'LOCAL_START_CROSS_FIELD_MISMATCH'
|
||||
| 'LOCAL_START_ALREADY_ESTABLISHED'
|
||||
| 'LOCAL_START_POLICY_NOT_ESTABLISHED';
|
||||
|
||||
/**
|
||||
* A refusal. Carries the stable code and the source labels that produced it.
|
||||
*
|
||||
* It carries no value: no DSN, no dotenv line, no JSON body. A refusal that
|
||||
* echoed the offending value would move the secret into the log, which is the
|
||||
* failure this item exists to prevent.
|
||||
*/
|
||||
export class LocalStartRefusal extends Error {
|
||||
public readonly code: LocalStartRefusalCode;
|
||||
public readonly sourceLabels: readonly LocalStartSourceLabel[];
|
||||
|
||||
constructor(code: LocalStartRefusalCode, sourceLabels: readonly LocalStartSourceLabel[] = []) {
|
||||
super(`[local-start] refused: ${code}`);
|
||||
this.name = 'LocalStartRefusal';
|
||||
this.code = code;
|
||||
this.sourceLabels = sourceLabels;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The disposable state-root contract, stated so it is testable.
|
||||
*
|
||||
* "Disposable" is not a property of the path string; it is a property of the
|
||||
* directory the string names. A declared root is admitted only when ALL of the
|
||||
* following hold, each with its own refusal code so a removed guard turns
|
||||
* exactly one case red:
|
||||
*
|
||||
* 1. absolute (`LOCAL_START_STATE_ROOT_NOT_ABSOLUTE`);
|
||||
* 2. already its own canonical form, lexically (`LOCAL_START_STATE_ROOT_ESCAPES`);
|
||||
* 3. it exists (`LOCAL_START_STATE_ROOT_ABSENT`) — the local channel does not
|
||||
* create the root, because a channel that creates its own root cannot
|
||||
* distinguish "session-scoped" from "silently reused";
|
||||
* 4. it is a directory (`LOCAL_START_STATE_ROOT_NOT_DIRECTORY`);
|
||||
* 5. the root itself is not a symlink (`LOCAL_START_STATE_ROOT_IS_SYMLINK`) —
|
||||
* checked with lstat, since a stat on a symlinked root reports the target and
|
||||
* every subsequent check would describe a directory the operator did not name;
|
||||
* 6. it is owned by the current user (`LOCAL_START_STATE_ROOT_NOT_OWNED`);
|
||||
* 7. it is private — no group or other permission bits
|
||||
* (`LOCAL_START_STATE_ROOT_NOT_PRIVATE`);
|
||||
* 8. no derived child escapes it through a symlink (`LOCAL_START_STATE_ROOT_ESCAPES`).
|
||||
*
|
||||
* Only 1, 2 and 8 were covered by the first RED pass. A derived-child symlink
|
||||
* check alone admits a root that is missing, is a file, is a symlink into
|
||||
* someone else's directory, or is world-writable — none of which is disposable
|
||||
* in any sense that protects the operator's data.
|
||||
*/
|
||||
|
||||
/** Explicit declarations supplied for THIS invocation. Nothing is defaulted. */
|
||||
export interface LocalStartDeclaration {
|
||||
readonly tier?: string;
|
||||
readonly storageType?: string;
|
||||
readonly queueType?: string;
|
||||
readonly stateRoot?: string;
|
||||
}
|
||||
|
||||
export interface EstablishInput {
|
||||
readonly declaration: LocalStartDeclaration;
|
||||
readonly anchor: string;
|
||||
readonly homeBase: string;
|
||||
readonly env: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
/** The one resolved policy. Allowed-only, deep-cloned, deep-frozen. */
|
||||
export interface FrozenLocalPolicy {
|
||||
readonly tier: 'local';
|
||||
readonly storage: { readonly type: 'pglite'; readonly dataDir: string };
|
||||
readonly queue: { readonly type: 'local'; readonly dataDir: string };
|
||||
readonly stateRoot: string;
|
||||
}
|
||||
|
||||
let established: FrozenLocalPolicy | undefined;
|
||||
|
||||
/**
|
||||
* Establish the frozen local policy, once.
|
||||
*
|
||||
* Contract (not yet implemented):
|
||||
* - refuses unless tier/storage/queue/state-root are all explicitly declared;
|
||||
* - refuses any PostgreSQL DSN or non-local tier found in ANY source, shadowed
|
||||
* or not;
|
||||
* - refuses cross-field mismatches (local+postgres, local+files, non-local+pglite);
|
||||
* - refuses a source it cannot read or parse, EVEN when a clean source would win
|
||||
* precedence — an unknown source has not been shown to be safe;
|
||||
* - enforces the full disposable state-root contract above; never uses HOME/CWD
|
||||
* defaults;
|
||||
* - deep-clones and deep-freezes an allowed-only object;
|
||||
* - a second call refuses with LOCAL_START_ALREADY_ESTABLISHED; there is no reset.
|
||||
*/
|
||||
export function establishFrozenLocalPolicy(input: EstablishInput): FrozenLocalPolicy {
|
||||
// RED-phase stub: admits everything, validates nothing, freezes nothing, and
|
||||
// permits re-establish. See module header.
|
||||
const stateRoot = input.declaration.stateRoot ?? '';
|
||||
established = {
|
||||
tier: 'local',
|
||||
storage: { type: 'pglite', dataDir: `${stateRoot}/db` },
|
||||
queue: { type: 'local', dataDir: `${stateRoot}/queue` },
|
||||
stateRoot,
|
||||
};
|
||||
return established;
|
||||
}
|
||||
|
||||
/** The established policy, or undefined when the local channel is not active. */
|
||||
export function getFrozenLocalPolicy(): FrozenLocalPolicy | undefined {
|
||||
return established;
|
||||
}
|
||||
|
||||
/**
|
||||
* The established policy, refusing when the local channel is not active.
|
||||
*
|
||||
* Local-channel consumers use this rather than falling back to an independent
|
||||
* read: there is deliberately no `getFrozen() ?? loadConfig()` masking, because
|
||||
* a fallback would silently restore the split-config path this item removes.
|
||||
*/
|
||||
export function requireFrozenLocalPolicy(): FrozenLocalPolicy {
|
||||
if (established === undefined) {
|
||||
throw new LocalStartRefusal('LOCAL_START_POLICY_NOT_ESTABLISHED');
|
||||
}
|
||||
return established;
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
/**
|
||||
* KBN-101-02a — source inventory REDs.
|
||||
*
|
||||
* Covers mutation->guard rows 1-6: inherited env, shared dotenv, daemon JSON,
|
||||
* app JSON, root JSON, redirect.
|
||||
*
|
||||
* Every case here plants a forbidden value in exactly ONE source and leaves the
|
||||
* others clean, so a guard that is removed for that source alone turns exactly
|
||||
* one case red. Aggregate coverage would not distinguish them.
|
||||
*
|
||||
* These read fixture files under a temp root. Nothing here connects to anything.
|
||||
*/
|
||||
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
LOCAL_START_SOURCE_LABELS,
|
||||
inventoryLocalStartSources,
|
||||
type InventoriedSource,
|
||||
type LocalStartSourceLabel,
|
||||
} from './source-inventory.js';
|
||||
|
||||
/** A Postgres DSN used only as fixture text. Never connected to. */
|
||||
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
|
||||
|
||||
interface Layout {
|
||||
tempRoot: string;
|
||||
anchor: string;
|
||||
homeBase: string;
|
||||
gatewayHome: string;
|
||||
paths: Record<Exclude<LocalStartSourceLabel, 'process-environment'>, string>;
|
||||
}
|
||||
|
||||
const cleanups: (() => Promise<void>)[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
const fn = cleanups.pop();
|
||||
if (fn) {
|
||||
await fn();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function writeFixture(path: string, contents: string): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, contents, 'utf8');
|
||||
}
|
||||
|
||||
async function makeLayout(): Promise<Layout> {
|
||||
const tempRoot = await mkdtemp(join(tmpdir(), 'kbn-02a-inventory-'));
|
||||
// The stack above is drained in afterEach. It existed before this line did,
|
||||
// and nothing pushed to it — so every case in this file left its temp root
|
||||
// behind. Registering at the point of creation is the only placement that
|
||||
// cannot be forgotten by a case added later.
|
||||
cleanups.push(async () => {
|
||||
await rm(tempRoot, { recursive: true, force: true });
|
||||
});
|
||||
const repo = join(tempRoot, 'repo');
|
||||
const anchor = join(repo, 'apps', 'gateway', 'src');
|
||||
const homeBase = join(tempRoot, 'home');
|
||||
// Redirect target lives OUTSIDE the default home location on purpose: a
|
||||
// daemon-json hit here can only mean the redirect was followed.
|
||||
const gatewayHome = join(tempRoot, 'redirected-gateway-home');
|
||||
|
||||
return {
|
||||
tempRoot,
|
||||
anchor,
|
||||
homeBase,
|
||||
gatewayHome,
|
||||
paths: {
|
||||
'daemon-dotenv': join(homeBase, '.config', 'mosaic', 'gateway', '.env'),
|
||||
'monorepo-root-dotenv': join(repo, '.env'),
|
||||
'gateway-local-dotenv': join(repo, 'apps', 'gateway', '.env'),
|
||||
'daemon-json': join(gatewayHome, 'mosaic.config.json'),
|
||||
'app-json': join(repo, 'apps', 'gateway', 'mosaic.config.json'),
|
||||
'monorepo-root-json': join(repo, 'mosaic.config.json'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const CLEAN_LOCAL_JSON = JSON.stringify({
|
||||
tier: 'local',
|
||||
storage: { type: 'pglite' },
|
||||
queue: { type: 'local' },
|
||||
memory: { type: 'none' },
|
||||
});
|
||||
|
||||
function postgresJson(): string {
|
||||
return JSON.stringify({
|
||||
tier: 'standalone',
|
||||
storage: { type: 'postgres', url: FORBIDDEN_DSN },
|
||||
queue: { type: 'bullmq' },
|
||||
memory: { type: 'none' },
|
||||
});
|
||||
}
|
||||
|
||||
/** Plant a forbidden DSN in exactly one file source; all others written clean. */
|
||||
async function plantIn(
|
||||
layout: Layout,
|
||||
target: Exclude<LocalStartSourceLabel, 'process-environment'>,
|
||||
): Promise<void> {
|
||||
for (const [label, path] of Object.entries(layout.paths)) {
|
||||
const isTarget = label === target;
|
||||
const isJson = label.endsWith('json');
|
||||
if (isJson) {
|
||||
await writeFixture(path, isTarget ? postgresJson() : CLEAN_LOCAL_JSON);
|
||||
continue;
|
||||
}
|
||||
await writeFixture(
|
||||
path,
|
||||
isTarget ? `DATABASE_URL=${FORBIDDEN_DSN}\n` : 'MOSAIC_LOG_LEVEL=info\n',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function find(sources: InventoriedSource[], label: LocalStartSourceLabel): InventoriedSource {
|
||||
const found = sources.find((source) => source.label === label);
|
||||
expect(found, `no source reported for label "${label}"`).toBeDefined();
|
||||
return found as InventoriedSource;
|
||||
}
|
||||
|
||||
describe('KBN-101-02a inventoryLocalStartSources', () => {
|
||||
it('reports every source label, present or not, so no source can be silently skipped', async () => {
|
||||
const layout = await makeLayout();
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(sources.map((source) => source.label).sort()).toEqual(
|
||||
[...LOCAL_START_SOURCE_LABELS].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
// Row 1 — inherited env.
|
||||
it('row 1: detects a PostgreSQL DSN inherited from the ambient process environment', async () => {
|
||||
const layout = await makeLayout();
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { DATABASE_URL: FORBIDDEN_DSN },
|
||||
});
|
||||
|
||||
expect(find(sources, 'process-environment').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
it('row 1: detects a non-local tier inherited from the ambient process environment', async () => {
|
||||
const layout = await makeLayout();
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { MOSAIC_STORAGE_TIER: 'standalone' },
|
||||
});
|
||||
|
||||
// Classification, not quotation: 'standalone' is the planted VALUE, and the
|
||||
// inventory type cannot carry it. Demanding it here would be a red no
|
||||
// compliant implementation could turn green.
|
||||
expect(find(sources, 'process-environment').declaredTier).toBe('non-local');
|
||||
});
|
||||
|
||||
// Row 2 — shared dotenv, one case per file so they fail independently.
|
||||
it('row 2: detects a DSN in the anchored monorepo-root .env', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'monorepo-root-dotenv');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(find(sources, 'monorepo-root-dotenv').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
it('row 2: detects a DSN in the anchored gateway-local .env', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'gateway-local-dotenv');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(find(sources, 'gateway-local-dotenv').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
it('row 2: detects a DSN in the daemon .env at $HOME, which the redirect does not move', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'daemon-dotenv');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
// Redirect set and pointed elsewhere: the daemon DOTENV must still be
|
||||
// found at $HOME. Widening the redirect to cover dotenv would break this.
|
||||
env: { MOSAIC_GATEWAY_HOME: layout.gatewayHome },
|
||||
});
|
||||
|
||||
expect(find(sources, 'daemon-dotenv').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
// Rows 3-5 — the three JSON sources.
|
||||
it('row 3: detects postgres storage declared in the daemon mosaic.config.json', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'daemon-json');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { MOSAIC_GATEWAY_HOME: layout.gatewayHome },
|
||||
});
|
||||
|
||||
const daemonJson = find(sources, 'daemon-json');
|
||||
expect(daemonJson.carriesPostgresDsn).toBe(true);
|
||||
expect(daemonJson.declaredStorageType).toBe('non-pglite');
|
||||
});
|
||||
|
||||
it('row 4: detects postgres storage declared in the anchored app mosaic.config.json', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'app-json');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(find(sources, 'app-json').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
it('row 5: detects postgres storage declared in the anchored monorepo-root mosaic.config.json', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'monorepo-root-json');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(find(sources, 'monorepo-root-json').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
// Row 6 — redirect followed for daemon JSON only.
|
||||
it('row 6: follows MOSAIC_GATEWAY_HOME when locating the daemon JSON', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'daemon-json');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { MOSAIC_GATEWAY_HOME: layout.gatewayHome },
|
||||
});
|
||||
|
||||
const daemonJson = find(sources, 'daemon-json');
|
||||
expect(daemonJson.present).toBe(true);
|
||||
expect(daemonJson.path).toBe(layout.paths['daemon-json']);
|
||||
});
|
||||
|
||||
it('row 6: without the redirect, the daemon JSON resolves under $HOME and the redirected file is not read', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'daemon-json');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
const daemonJson = find(sources, 'daemon-json');
|
||||
expect(daemonJson.path).toBe(
|
||||
join(layout.homeBase, '.config', 'mosaic', 'gateway', 'mosaic.config.json'),
|
||||
);
|
||||
expect(daemonJson.carriesPostgresDsn).toBe(false);
|
||||
});
|
||||
|
||||
// Shadowing — the property that makes independent inspection necessary.
|
||||
it('reports a forbidden value in a LOSING source even when a winning source is clean', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'gateway-local-dotenv');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
// Ambient env would win precedence and is clean; the shadowed file value
|
||||
// must still be reported.
|
||||
env: { MOSAIC_STORAGE_TIER: 'local' },
|
||||
});
|
||||
|
||||
expect(find(sources, 'gateway-local-dotenv').carriesPostgresDsn).toBe(true);
|
||||
});
|
||||
|
||||
// Non-egress: classification only, never the value.
|
||||
it('retains no raw DSN text anywhere in the inventory result', async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantIn(layout, 'monorepo-root-dotenv');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { DATABASE_URL: FORBIDDEN_DSN },
|
||||
});
|
||||
|
||||
expect(JSON.stringify(sources)).not.toContain(FORBIDDEN_DSN);
|
||||
expect(JSON.stringify(sources)).not.toContain('mosaic:mosaic');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Tier and DSN are separate forbidden classes and must be separately detected.
|
||||
*
|
||||
* The DSN cases above would all still pass if the tier check were deleted
|
||||
* outright, because every DSN fixture also declares a non-local tier. These
|
||||
* cases plant a non-local tier and NO DSN, in exactly one source at a time, so
|
||||
* deleting the tier guard for one source turns exactly one case red and the DSN
|
||||
* cases stay green.
|
||||
*/
|
||||
const NON_LOCAL_TIER_JSON = JSON.stringify({
|
||||
tier: 'standalone',
|
||||
storage: { type: 'pglite' },
|
||||
queue: { type: 'local' },
|
||||
memory: { type: 'none' },
|
||||
});
|
||||
|
||||
async function plantNonLocalTierIn(
|
||||
layout: Layout,
|
||||
target: Exclude<LocalStartSourceLabel, 'process-environment'>,
|
||||
): Promise<void> {
|
||||
for (const [label, path] of Object.entries(layout.paths)) {
|
||||
const isTarget = label === target;
|
||||
if (label.endsWith('json')) {
|
||||
await writeFixture(path, isTarget ? NON_LOCAL_TIER_JSON : CLEAN_LOCAL_JSON);
|
||||
continue;
|
||||
}
|
||||
await writeFixture(
|
||||
path,
|
||||
isTarget ? 'MOSAIC_STORAGE_TIER=standalone\n' : 'MOSAIC_LOG_LEVEL=info\n',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
describe('KBN-101-02a inventoryLocalStartSources — non-local tier, per source, without any DSN', () => {
|
||||
const fileLabels: Exclude<LocalStartSourceLabel, 'process-environment'>[] = [
|
||||
'daemon-dotenv',
|
||||
'monorepo-root-dotenv',
|
||||
'gateway-local-dotenv',
|
||||
'daemon-json',
|
||||
'app-json',
|
||||
'monorepo-root-json',
|
||||
];
|
||||
|
||||
for (const label of fileLabels) {
|
||||
it(`classifies a non-local tier declared only in ${label}`, async () => {
|
||||
const layout = await makeLayout();
|
||||
await plantNonLocalTierIn(layout, label);
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(find(sources, label).declaredTier).toBe('non-local');
|
||||
expect(find(sources, label).carriesPostgresDsn).toBe(false);
|
||||
for (const other of fileLabels.filter((candidate) => candidate !== label)) {
|
||||
expect(find(sources, other).declaredTier).not.toBe('non-local');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('classifies a non-local tier inherited from the ambient process environment', async () => {
|
||||
const layout = await makeLayout();
|
||||
for (const [label, path] of Object.entries(layout.paths)) {
|
||||
await writeFixture(
|
||||
path,
|
||||
label.endsWith('json') ? CLEAN_LOCAL_JSON : 'MOSAIC_LOG_LEVEL=info\n',
|
||||
);
|
||||
}
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { MOSAIC_STORAGE_TIER: 'federated' },
|
||||
});
|
||||
|
||||
expect(find(sources, 'process-environment').declaredTier).toBe('non-local');
|
||||
expect(find(sources, 'process-environment').carriesPostgresDsn).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Classification, not quotation.
|
||||
*
|
||||
* `declaredTier: string` is value-free only by convention — it holds whatever
|
||||
* the file said. These cases plant a canary in the value position of every
|
||||
* source and assert it appears nowhere: not in the result, and not in anything
|
||||
* written to the console on the way there. The result is serialized whole rather
|
||||
* than field-by-field, so a field added later is covered without anyone
|
||||
* remembering to extend this case.
|
||||
*/
|
||||
describe('KBN-101-02a inventoryLocalStartSources — no source value is retained or logged', () => {
|
||||
const CANARY = 'kbn-101-02a-canary-2f7d1c';
|
||||
|
||||
it('retains no planted canary anywhere in the result', async () => {
|
||||
const layout = await makeLayout();
|
||||
for (const [label, path] of Object.entries(layout.paths)) {
|
||||
await writeFixture(
|
||||
path,
|
||||
label.endsWith('json')
|
||||
? JSON.stringify({
|
||||
tier: CANARY,
|
||||
storage: { type: CANARY, url: `postgresql://${CANARY}@localhost:5432/db` },
|
||||
queue: { type: CANARY },
|
||||
})
|
||||
: `MOSAIC_STORAGE_TIER=${CANARY}\nDATABASE_URL=postgresql://${CANARY}@localhost:5432/db\n`,
|
||||
);
|
||||
}
|
||||
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { MOSAIC_STORAGE_TIER: CANARY },
|
||||
});
|
||||
|
||||
expect(JSON.stringify(sources)).not.toContain(CANARY);
|
||||
});
|
||||
|
||||
it('writes no planted canary to the console while inspecting sources', async () => {
|
||||
const layout = await makeLayout();
|
||||
await writeFixture(
|
||||
layout.paths['monorepo-root-json'],
|
||||
JSON.stringify({ tier: CANARY, storage: { type: CANARY }, queue: { type: CANARY } }),
|
||||
);
|
||||
|
||||
const written: string[] = [];
|
||||
const methods = ['log', 'info', 'warn', 'error', 'debug', 'trace'] as const;
|
||||
const spies = methods.map((method) =>
|
||||
vi.spyOn(console, method).mockImplementation((...args: unknown[]): void => {
|
||||
written.push(args.map((arg) => String(arg)).join(' '));
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: { DATABASE_URL: `postgresql://${CANARY}@localhost:5432/db` },
|
||||
});
|
||||
} finally {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
}
|
||||
|
||||
expect(written.join('\n')).not.toContain(CANARY);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Readability is reported per source, and absence is its own classification.
|
||||
*
|
||||
* The refusal path in local-start-policy.ts consumes these rows, and it treats
|
||||
* "read, and clean" as the opposite of "contents unknown". If an absent source
|
||||
* has to be described as `readable`, those two collapse into one value and the
|
||||
* refusal loses the distinction it is built on. So all four states are asserted
|
||||
* directly here rather than inferred from a refusal downstream.
|
||||
*
|
||||
* The unreadable fixture is a DIRECTORY where a file is expected. `chmod 0o000`
|
||||
* would be the obvious choice and is worthless: root ignores the mode bits, so
|
||||
* the case would pass vacuously wherever CI runs as root. EISDIR holds for every
|
||||
* uid.
|
||||
*/
|
||||
describe('KBN-101-02a inventoryLocalStartSources — readability is classified per source', () => {
|
||||
it('classifies an absent source as absent, never as readable', async () => {
|
||||
const layout = await makeLayout();
|
||||
// Nothing planted: the anchored app JSON does not exist.
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
const appJson = find(sources, 'app-json');
|
||||
expect(appJson.present).toBe(false);
|
||||
expect(appJson.readability).toBe('absent');
|
||||
});
|
||||
|
||||
it('classifies a present, parseable source as readable', async () => {
|
||||
const layout = await makeLayout();
|
||||
await writeFixture(layout.paths['app-json'], CLEAN_LOCAL_JSON);
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
const appJson = find(sources, 'app-json');
|
||||
expect(appJson.present).toBe(true);
|
||||
expect(appJson.readability).toBe('readable');
|
||||
});
|
||||
|
||||
it('classifies a source that cannot be read as unreadable, not as absent', async () => {
|
||||
const layout = await makeLayout();
|
||||
// A directory at the file's path: open() fails with EISDIR for every uid.
|
||||
await mkdir(layout.paths['app-json'], { recursive: true });
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
const appJson = find(sources, 'app-json');
|
||||
expect(appJson.readability).toBe('unreadable');
|
||||
expect(appJson.readability, 'an unreadable source was reported as absent').not.toBe('absent');
|
||||
});
|
||||
|
||||
it('classifies a present but unparseable source as malformed, not as readable', async () => {
|
||||
const layout = await makeLayout();
|
||||
await writeFixture(layout.paths['app-json'], '{ "tier": "local", ');
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
const appJson = find(sources, 'app-json');
|
||||
expect(appJson.present).toBe(true);
|
||||
expect(appJson.readability).toBe('malformed');
|
||||
});
|
||||
|
||||
it('holds present === false exactly when readability === absent, across every source', async () => {
|
||||
const layout = await makeLayout();
|
||||
// A deliberately mixed bed: one readable, one malformed, one unreadable,
|
||||
// the rest absent. The invariant has to hold for all seven rows at once.
|
||||
await writeFixture(layout.paths['monorepo-root-json'], CLEAN_LOCAL_JSON);
|
||||
await writeFixture(layout.paths['app-json'], '{ not json');
|
||||
await mkdir(layout.paths['gateway-local-dotenv'], { recursive: true });
|
||||
|
||||
const sources = inventoryLocalStartSources({
|
||||
anchor: layout.anchor,
|
||||
homeBase: layout.homeBase,
|
||||
env: {},
|
||||
});
|
||||
|
||||
expect(sources.length).toBe(LOCAL_START_SOURCE_LABELS.length);
|
||||
for (const source of sources) {
|
||||
expect(
|
||||
source.readability === 'absent',
|
||||
`${source.label}: present=${String(source.present)} readability=${source.readability}`,
|
||||
).toBe(source.present === false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Local-start source inventory — KBN-101-02a.
|
||||
*
|
||||
* Enumerates and reads EVERY configuration source independently, BEFORE any
|
||||
* precedence is applied. A forbidden value refuses even when it is shadowed by
|
||||
* a higher-precedence source, so precedence must not be consulted here.
|
||||
*
|
||||
* RED PHASE SCAFFOLDING. The signatures below are the contract; the body is a
|
||||
* deliberately permissive stub that discovers nothing, so the behavioral specs
|
||||
* fail on their assertions rather than on a missing module. Do not read this
|
||||
* file as the implementation — there is none yet.
|
||||
*/
|
||||
|
||||
/** Every configuration source the local channel must inspect. */
|
||||
export type LocalStartSourceLabel =
|
||||
| 'process-environment'
|
||||
| 'daemon-dotenv'
|
||||
| 'monorepo-root-dotenv'
|
||||
| 'gateway-local-dotenv'
|
||||
| 'daemon-json'
|
||||
| 'app-json'
|
||||
| 'monorepo-root-json';
|
||||
|
||||
export const LOCAL_START_SOURCE_LABELS: readonly LocalStartSourceLabel[] = [
|
||||
'process-environment',
|
||||
'daemon-dotenv',
|
||||
'monorepo-root-dotenv',
|
||||
'gateway-local-dotenv',
|
||||
'daemon-json',
|
||||
'app-json',
|
||||
'monorepo-root-json',
|
||||
];
|
||||
|
||||
/**
|
||||
* Finite classifications, not values.
|
||||
*
|
||||
* These are unions rather than `string` on purpose. A `declaredTier?: string`
|
||||
* field is value-free only by convention: it will hold whatever the source said,
|
||||
* so a canary planted in a config file survives into the inventory and from
|
||||
* there into anything that logs it. A union of two members cannot carry a
|
||||
* canary — the type makes retention unrepresentable rather than discouraged.
|
||||
*/
|
||||
export type DeclaredTierClass = 'local' | 'non-local';
|
||||
export type DeclaredStorageClass = 'pglite' | 'non-pglite';
|
||||
|
||||
/**
|
||||
* Whether the source could be read and parsed at all.
|
||||
*
|
||||
* A source that cannot be read is not the same as a source that is absent. An
|
||||
* unreadable or malformed source is a source whose contents are UNKNOWN, and an
|
||||
* unknown source cannot be shown to be free of a forbidden value — so it refuses
|
||||
* rather than being skipped.
|
||||
*
|
||||
* `absent` is a member rather than an implication of `present: false`. Without
|
||||
* it the two fields can disagree — an absent source has to be reported as
|
||||
* `readable`, which is the one classification that means "read, and clean". A
|
||||
* reader that stats a path and finds nothing there would then be indistinguishable
|
||||
* from a reader that opened a file and found it safe, and the refusal path treats
|
||||
* those two as opposites. The invariant is exact and total:
|
||||
* `present === false` if and only if `readability === 'absent'`.
|
||||
*/
|
||||
export type SourceReadability = 'readable' | 'unreadable' | 'malformed' | 'absent';
|
||||
|
||||
/**
|
||||
* What one source was observed to carry.
|
||||
*
|
||||
* Deliberately value-free beyond classification: raw DSNs, dotenv contents and
|
||||
* JSON bodies are never retained here, because anything retained can later be
|
||||
* logged. Callers get labels and classifications, never secrets.
|
||||
*/
|
||||
export interface InventoriedSource {
|
||||
readonly label: LocalStartSourceLabel;
|
||||
/** Filesystem path inspected; absent for the ambient process environment. */
|
||||
readonly path?: string;
|
||||
readonly present: boolean;
|
||||
/** True when this source carries a PostgreSQL DSN in any recognized key. */
|
||||
readonly carriesPostgresDsn: boolean;
|
||||
/** Whether this source was readable and parseable. */
|
||||
readonly readability: SourceReadability;
|
||||
/** Classification of the tier this source declares, if it declares one. */
|
||||
readonly declaredTier?: DeclaredTierClass;
|
||||
/** Classification of the storage type this source declares, if it declares one. */
|
||||
readonly declaredStorageType?: DeclaredStorageClass;
|
||||
}
|
||||
|
||||
export interface InventoryInput {
|
||||
/** Module anchor used to resolve the anchored dotenv/JSON locations. */
|
||||
readonly anchor: string;
|
||||
/** Home base used to resolve the daemon dotenv location. */
|
||||
readonly homeBase: string;
|
||||
/** Ambient environment snapshot. */
|
||||
readonly env: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect every source independently and report what each one carries.
|
||||
*
|
||||
* Contract (not yet implemented):
|
||||
* - every label in LOCAL_START_SOURCE_LABELS appears in the result, present or not;
|
||||
* - MOSAIC_GATEWAY_HOME redirects `daemon-json` ONLY — `daemon-dotenv` stays at
|
||||
* `$HOME/.config/mosaic/gateway/.env` regardless of the redirect;
|
||||
* - a source that cannot be read or parsed is reported as such, never skipped
|
||||
* and never treated as clean;
|
||||
* - `present === false` if and only if `readability === 'absent'`; an absent
|
||||
* source is never reported as `readable`;
|
||||
* - no precedence is applied and no value is retained.
|
||||
*/
|
||||
export function inventoryLocalStartSources(_input: InventoryInput): InventoriedSource[] {
|
||||
// RED-phase stub: discovers nothing. See module header.
|
||||
return [];
|
||||
}
|
||||
@@ -3,9 +3,11 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import * as nodeOs from 'node:os';
|
||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import * as nodeUrl from 'node:url';
|
||||
import type * as NestCore from '@nestjs/core';
|
||||
import type * as MosaicConfigModule from '@mosaicstack/config';
|
||||
import type { MosaicConfig } from '@mosaicstack/config';
|
||||
import type * as MosaicStorage from '@mosaicstack/storage';
|
||||
import { describe, expect, it, vi, type MockInstance } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi, type MockInstance } from 'vitest';
|
||||
|
||||
// Each case uses vi.resetModules() and re-imports the full gateway graph for distinct ambient FS/env; CI needs headroom, while this still guards genuine hangs.
|
||||
const MODULE_IMPORT_TIMEOUT_MS = 120_000;
|
||||
@@ -162,3 +164,362 @@ describe('main bootstrap preflight config anchoring', (): void => {
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* KBN-101-02a — the real consumers, executed.
|
||||
*
|
||||
* The local-dev REDs mock `./main.js` wholesale, which proves the entrypoint
|
||||
* refuses before it calls bootstrap and proves nothing at all about what
|
||||
* bootstrap, AppModule and ConfigModule do when they DO run. Those three each
|
||||
* perform their own independent `loadConfig(resolveGatewayConfigPath())` —
|
||||
* `main.ts:28`, `app.module.ts:39`, `config.module.ts:12` — and the frozen
|
||||
* policy is worth nothing if the modules that actually start the process ignore
|
||||
* it. Every case below drives the real module.
|
||||
*
|
||||
* `@nestjs/core` is substituted so a case that wrongly proceeds cannot listen,
|
||||
* and `@mosaicstack/storage` so no tier probe can reach a real service. Those
|
||||
* substitutions are also the instrument: the assertions are that they were never
|
||||
* called.
|
||||
*
|
||||
* While red, this block also emits unhandled rejections ('process.exit
|
||||
* unexpectedly called with "1"'). They are not flake and must not be silenced:
|
||||
* they are the self-invocation at `main.ts:71` failing asynchronously after the
|
||||
* case that imported the module has already returned. An entrypoint that starts
|
||||
* nothing on import cannot produce them, so they disappear when the defect is
|
||||
* fixed. If they survive GREEN, the entrypoint is still self-invoking.
|
||||
*
|
||||
* NOTE — the case above this block ('main bootstrap preflight config anchoring')
|
||||
* asserts the CURRENT contract, in which importing `main.ts` self-invokes
|
||||
* `bootstrap()` and exits the process on failure:
|
||||
*
|
||||
* await import('./main.js');
|
||||
* await vi.waitFor(() => { expect(exitSpy).toHaveBeenCalled(); });
|
||||
*
|
||||
* That expectation is the direct opposite of the contract this item introduces,
|
||||
* so it cannot survive GREEN unchanged. It is deliberately left intact here: it
|
||||
* is the current behavior's regression guard, it must keep passing until the
|
||||
* behavior actually changes, and the GREEN author has to migrate it to drive the
|
||||
* exported `bootstrap()` explicitly rather than delete it. A red left where the
|
||||
* change has to happen is cheaper than a note in a document.
|
||||
*/
|
||||
describe('KBN-101-02a main.ts — importing the entrypoint starts nothing', () => {
|
||||
// The application double has to be complete enough for bootstrap to run all
|
||||
// the way through, not merely far enough to observe the config read. A thinner
|
||||
// double fails inside itself (`app.getHttpAdapter is not a function`), which
|
||||
// would leave these cases unable to go green for the reason they state even
|
||||
// after the defect is fixed. The HTTP instance is a permissive proxy so the
|
||||
// double does not have to track every route the controllers mount.
|
||||
const listenMock = vi.fn(async () => {});
|
||||
const nestCreateMock = vi.fn(async () => ({
|
||||
enableCors: vi.fn(),
|
||||
register: vi.fn(async () => {}),
|
||||
useGlobalPipes: vi.fn(),
|
||||
get: vi.fn(() => ({})),
|
||||
getHttpAdapter: vi.fn(() => ({
|
||||
getInstance: () => new Proxy({}, { get: () => vi.fn() }),
|
||||
})),
|
||||
listen: listenMock,
|
||||
}));
|
||||
const detectAndAssertTierMock = vi.fn(async () => {});
|
||||
const loadConfigMock = vi.fn(() => ({
|
||||
tier: 'local' as const,
|
||||
storage: { type: 'pglite' as const, dataDir: '.mosaic/storage-pglite' },
|
||||
queue: { type: 'local' as const, dataDir: '.mosaic/queue' },
|
||||
memory: { type: 'keyword' as const },
|
||||
}));
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
afterEach(async (): Promise<void> => {
|
||||
for (const root of tempRoots.splice(0)) {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Import `main.js` with the current self-invocation effect captured.
|
||||
*
|
||||
* `main.ts:71` invokes bootstrap on import; it rejects, and the tail calls
|
||||
* `process.exit(1)`. Vitest instruments `process.exit`, so that raised a
|
||||
* global error attributed to no case at all — which both falsified this
|
||||
* document's zero-non-assertion-failures claim and is exactly the shape
|
||||
* Vitest warns can produce false positives.
|
||||
*
|
||||
* Stubbing `process.exit` non-throwing for the duration and awaiting a settle
|
||||
* turn keeps the effect inside the case that provokes it. The behavioral
|
||||
* assertions stay red — importing an entrypoint must not do this — but the
|
||||
* error is now owned rather than loose. The spy is returned so callers can
|
||||
* assert against it.
|
||||
*/
|
||||
async function importMainCapturingExit(): Promise<{
|
||||
mod: Record<string, unknown>;
|
||||
exitSpy: MockInstance<typeof process.exit>;
|
||||
}> {
|
||||
const exitSpy = vi
|
||||
.spyOn(process, 'exit')
|
||||
.mockImplementation((() => undefined) as unknown as typeof process.exit);
|
||||
const mod = (await import('./main.js')) as Record<string, unknown>;
|
||||
// Two turns: one for the bootstrap rejection, one for its catch handler.
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
return { mod, exitSpy };
|
||||
}
|
||||
|
||||
async function establishLocalChannel(): Promise<string> {
|
||||
const tempRoot = await mkdtemp(join(nodeOs.tmpdir(), 'kbn-02a-main-'));
|
||||
tempRoots.push(tempRoot);
|
||||
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
|
||||
const homeBase = join(tempRoot, 'home');
|
||||
const stateRoot = join(tempRoot, 'session-state');
|
||||
await mkdir(anchor, { recursive: true });
|
||||
await mkdir(homeBase, { recursive: true });
|
||||
await mkdir(stateRoot, { recursive: true });
|
||||
|
||||
const { establishFrozenLocalPolicy } = await import('./local-start/local-start-policy.js');
|
||||
establishFrozenLocalPolicy({
|
||||
declaration: { tier: 'local', storageType: 'pglite', queueType: 'local', stateRoot },
|
||||
anchor,
|
||||
homeBase,
|
||||
env: {},
|
||||
});
|
||||
return stateRoot;
|
||||
}
|
||||
|
||||
function substituteStartupSurface(): void {
|
||||
vi.doMock('./tracing.js', () => ({}));
|
||||
// Partial, never wholesale. A wholesale substitution drops APP_GUARD and
|
||||
// every other export app.module.ts evaluates at import time, so the module
|
||||
// throws before reaching the behavior under test — the case would then be
|
||||
// red for a reason it does not state, and could never go green by fixing
|
||||
// the defect it names.
|
||||
vi.doMock('@nestjs/core', async () => {
|
||||
const actual = await vi.importActual<typeof NestCore>('@nestjs/core');
|
||||
return { ...actual, NestFactory: { ...actual.NestFactory, create: nestCreateMock } };
|
||||
});
|
||||
vi.doMock('@mosaicstack/storage', async () => {
|
||||
const actual = await vi.importActual<typeof MosaicStorage>('@mosaicstack/storage');
|
||||
return { ...actual, detectAndAssertTier: detectAndAssertTierMock };
|
||||
});
|
||||
}
|
||||
|
||||
function undoSubstitutions(): void {
|
||||
vi.doUnmock('@mosaicstack/storage');
|
||||
vi.doUnmock('@nestjs/core');
|
||||
vi.doUnmock('./tracing.js');
|
||||
vi.doUnmock('@mosaicstack/config');
|
||||
}
|
||||
|
||||
it(
|
||||
'does not bootstrap, probe, or exit merely by being imported',
|
||||
async (): Promise<void> => {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
let exitSpy: MockInstance<typeof process.exit> | undefined;
|
||||
try {
|
||||
delete process.env['BETTER_AUTH_SECRET'];
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
substituteStartupSurface();
|
||||
|
||||
({ exitSpy } = await importMainCapturingExit());
|
||||
|
||||
expect(exitSpy, 'importing main.ts exited the process').not.toHaveBeenCalled();
|
||||
expect(detectAndAssertTierMock, 'importing main.ts probed the tier').not.toHaveBeenCalled();
|
||||
expect(nestCreateMock, 'importing main.ts created the Nest app').not.toHaveBeenCalled();
|
||||
} finally {
|
||||
exitSpy?.mockRestore();
|
||||
undoSubstitutions();
|
||||
vi.resetModules();
|
||||
restoreProcessEnv(originalEnv);
|
||||
}
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'exports bootstrap so the local entrypoint can call it after establishing the policy',
|
||||
async (): Promise<void> => {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
try {
|
||||
vi.resetModules();
|
||||
substituteStartupSurface();
|
||||
const { mod, exitSpy } = await importMainCapturingExit();
|
||||
try {
|
||||
expect(typeof mod['bootstrap'], 'main.ts does not export bootstrap').toBe('function');
|
||||
} finally {
|
||||
exitSpy.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
undoSubstitutions();
|
||||
vi.resetModules();
|
||||
restoreProcessEnv(originalEnv);
|
||||
}
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'performs no independent config read or tier probe when the frozen policy is established',
|
||||
async (): Promise<void> => {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
try {
|
||||
process.env['BETTER_AUTH_SECRET'] = 'fixture-secret';
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
substituteStartupSurface();
|
||||
vi.doMock('@mosaicstack/config', async () => {
|
||||
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
|
||||
return { ...actual, loadConfig: loadConfigMock };
|
||||
});
|
||||
await establishLocalChannel();
|
||||
|
||||
const { mod, exitSpy } = await importMainCapturingExit();
|
||||
try {
|
||||
await (mod['bootstrap'] as (() => Promise<void>) | undefined)?.();
|
||||
|
||||
expect(
|
||||
loadConfigMock,
|
||||
'bootstrap re-read configuration independently',
|
||||
).not.toHaveBeenCalled();
|
||||
expect(detectAndAssertTierMock, 'bootstrap probed the tier').not.toHaveBeenCalled();
|
||||
} finally {
|
||||
exitSpy.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
undoSubstitutions();
|
||||
vi.resetModules();
|
||||
restoreProcessEnv(originalEnv);
|
||||
}
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'evaluates AppModule without an independent config read under the frozen policy',
|
||||
async (): Promise<void> => {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
try {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
substituteStartupSurface();
|
||||
vi.doMock('@mosaicstack/config', async () => {
|
||||
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
|
||||
return { ...actual, loadConfig: loadConfigMock };
|
||||
});
|
||||
await establishLocalChannel();
|
||||
|
||||
// app.module.ts decides federation at module-evaluation time, so the read
|
||||
// happens on import — before any provider is constructed.
|
||||
await import('./app.module.js');
|
||||
|
||||
expect(
|
||||
loadConfigMock,
|
||||
'AppModule re-read configuration independently',
|
||||
).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
undoSubstitutions();
|
||||
vi.resetModules();
|
||||
restoreProcessEnv(originalEnv);
|
||||
}
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'serves MOSAIC_CONFIG from the frozen policy rather than a fresh load',
|
||||
async (): Promise<void> => {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
try {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
substituteStartupSurface();
|
||||
vi.doMock('@mosaicstack/config', async () => {
|
||||
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
|
||||
return { ...actual, loadConfig: loadConfigMock };
|
||||
});
|
||||
const stateRoot = await establishLocalChannel();
|
||||
|
||||
const configModule = await import('./config/config.module.js');
|
||||
const providers = (Reflect.getMetadata('providers', configModule.ConfigModule) ?? []) as {
|
||||
provide?: unknown;
|
||||
useFactory?: () => unknown;
|
||||
}[];
|
||||
const provider = providers.find(
|
||||
(candidate) => candidate.provide === configModule.MOSAIC_CONFIG,
|
||||
);
|
||||
expect(provider?.useFactory, 'MOSAIC_CONFIG provider factory not found').toBeDefined();
|
||||
|
||||
const served = provider!.useFactory!() as {
|
||||
tier?: string;
|
||||
storage?: { type?: string; dataDir?: string };
|
||||
};
|
||||
|
||||
expect(
|
||||
loadConfigMock,
|
||||
'the MOSAIC_CONFIG factory called loadConfig',
|
||||
).not.toHaveBeenCalled();
|
||||
expect(served.tier).toBe('local');
|
||||
expect(served.storage?.type).toBe('pglite');
|
||||
expect(served.storage?.dataDir).toContain(stateRoot);
|
||||
} finally {
|
||||
undoSubstitutions();
|
||||
vi.resetModules();
|
||||
restoreProcessEnv(originalEnv);
|
||||
}
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
// The positive anchor for acceptance #6. Every other case in this file is a
|
||||
// refusal or an absence, and a refusal-only matrix is satisfied by production
|
||||
// code that does nothing at all: an exported `bootstrap()` with an empty body
|
||||
// passes all of them. This case is the one that fails against that, so "safe"
|
||||
// cannot come to mean "does not work". It is in-process and substituted at the
|
||||
// Nest seam — no port is bound, no database is reached, nothing is started for
|
||||
// real.
|
||||
it(
|
||||
'starts the application through the frozen policy: create and listen are reached with no independent read',
|
||||
async (): Promise<void> => {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
try {
|
||||
process.env['BETTER_AUTH_SECRET'] = 'fixture-secret';
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
substituteStartupSurface();
|
||||
vi.doMock('@mosaicstack/config', async () => {
|
||||
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
|
||||
return { ...actual, loadConfig: loadConfigMock };
|
||||
});
|
||||
await establishLocalChannel();
|
||||
|
||||
const { mod, exitSpy } = await importMainCapturingExit();
|
||||
try {
|
||||
const bootstrap = mod['bootstrap'] as (() => Promise<void>) | undefined;
|
||||
expect(typeof bootstrap, 'main.ts does not export bootstrap').toBe('function');
|
||||
await expect(
|
||||
bootstrap!(),
|
||||
'bootstrap rejected on the established local channel',
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(nestCreateMock, 'bootstrap never created the Nest application').toHaveBeenCalled();
|
||||
expect(listenMock, 'bootstrap never reached listen').toHaveBeenCalled();
|
||||
expect(
|
||||
loadConfigMock,
|
||||
'the started path re-read configuration independently',
|
||||
).not.toHaveBeenCalled();
|
||||
expect(
|
||||
detectAndAssertTierMock,
|
||||
'the started path probed the tier independently',
|
||||
).not.toHaveBeenCalled();
|
||||
expect(exitSpy, 'the started path exited the process').not.toHaveBeenCalled();
|
||||
} finally {
|
||||
exitSpy.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
undoSubstitutions();
|
||||
vi.resetModules();
|
||||
restoreProcessEnv(originalEnv);
|
||||
}
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user