Compare commits

...
Author SHA1 Message Date
mos 748eee24ba salvage: uncommitted work from /home/jwoltje/distrobox-homes/mosaic-dev/src/stack-p3-t5 (disk cleanup #824, 2026-11-06) 2026-11-06 09:54:57 -06:00
shaggyandClaude Opus 5 517e1adad3 test(kbn-101-02a): resolve tsx CLI directly, exact dev:local contract, honest timeout bound
Three reviewer blockers, all verified against source and by measurement before
acting on them.

C1 — the fixture's `tsx` was `apps/gateway/node_modules/.bin/tsx`, which is not
the TSX CLI but a pnpm-generated /bin/sh launcher that **exports NODE_PATH**
naming four repository module roots into the process it starts. A fixture whose
stated invariant is that the child receives no Node loader controls was shipping
a `tsx` that reinstated one. Resolving `tsx/dist/cli.mjs` directly deletes the
wrapper, the NODE_PATH injection, three coreutils symlinks and an off-PATH
package-layout symlink at once: PATH is now two names, `node` and `tsx`. Targets
are realpath-resolved and asserted to be executable files at module scope,
before the first child, and the symlinks derive from those checked values.
Observed child key set carries neither NODE_PATH nor NODE_OPTIONS.

C3 — the dev:local contract was a substring check followed by arbitrary shell
execution: the manifest case asserted the script *contained* src/local-dev.ts,
and the helper then handed the whole string to `sh -c`. "curl … | sh; tsx
src/local-dev.ts" satisfied it and ran. Now one module constant spelled once,
asserted with equality in the manifest case and re-asserted in the executing
helper against the value about to run. No metacharacter denylist — equality
already excludes them, and a denylist here would repeat the mistake the PATH
allowlist was built to correct.

C2 — the timeout bound is corrected rather than closed. `exec` removes the outer
shell, but the required route is itself multi-process: TSX spawns an esbuild
service child and a loader/eval child, and the latter is where route code runs.
Measured six out of six times under this exact spawn shape, that child survives
SIGKILL to its TSX parent, is reparented, and completes its work afterward —
while sandbox teardown removes directories it still holds. So exact equality
plus `exec` prohibits *injected* shell content and does not close the gap; the
launcher the contract *permits* is the one that leaks. The timeout control is
named and commented for the single-process property it actually measures and is
not offered as containment evidence.

Containment design is at architecture adjudication and is deliberately not
implemented here: every process in the TSX tree runs in the verifier's own
process group and session, so the obvious repair would signal the test runner.

RED unchanged: 83 failed | 17 passed -> 83 failed | 18 passed (101), the one
added case being the timeout control passing as a harness control. Prettier,
tsc and ESLint clean; zero /tmp/kbn-02a-* residue; casts unchanged at six.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ESFAnh2t9HmLwng8oW95St
2026-08-13 00:57:05 -05:00
shaggy a266c88b7f test(gateway): make the KBN-101-02a child PATH an allowlist and enumerate it
PATH was the last part of the child environment still built as a denylist:
the two workspace node_modules/.bin directories, dirname(process.execPath)
and the shell's directory. Measured on this host that is 4,093 distinct
executable names, and apps/gateway/node_modules/.bin carries real agent
runtimes this repo depends on directly — pi (@mariozechner/pi-coding-agent),
pi-ai, openai, anthropic-ai-sdk. The comment on that construction claimed it
prevented an unrelated same-name executable from answering, which is the
resolution it permitted.

PATH is now one fixture-owned directory in the per-run sandbox holding only
symlinks: node, tsx, and dirname/sed/uname (the pnpm tsx launcher is a
/bin/sh script that calls all three to locate its own entrypoint). The
launcher's relative ../tsx/dist/cli.mjs lookup is served by one directory
symlink inside the sandbox, off PATH. The shell is invoked absolutely and
needs no entry; env needs none because the shebang invokes it absolutely.

The fixture control now enumerates the directories on the child's observed
PATH and asserts the reachable executable names EQUAL the allowlist. The
seven harness-name assertions are kept and commented redundant-by-design: a
name enumeration finds pi and misses the other three actually present, which
is the empirical argument against the denylist shape. Symlink targets are
asserted to resolve to the exact expected binaries.

Measured: 4,093 -> 5 reachable names; `command -v pi` resolves the real
.bin/pi under the old construction and is not-found under the new one;
`tsx --version` still succeeds on the narrowed PATH.

Bounds recorded rather than overclaimed: this narrows command resolution,
not module resolution — the tsx launcher exports NODE_PATH naming four real
repository module roots, the last exposing 775 packages including the same
agent runtimes. And the shell-arm key-set measurement describes the
control's own arm, not the GREEN route.

RED unchanged: 83 failing / 17 passing (100 cases, 6 files), no Errors row,
zero /tmp/kbn-02a-* residue, dev:local still absent.
2026-08-13 00:17:39 -05:00
shaggy 3d348772ad test(gateway): bound the KBN-101-02a child-env guard's claim instead of escalating it
Three review rounds found the same defect in this guard: the value validated
and the value used came from two different reads. Each repair narrowed the
window and the next round reopened it -- a Proxy, then a getter replacing
Object.keys mid-enumeration. The single-entries-array form closes both, and a
fourth round showed it still is not a proof: the helper calls Object.fromEntries,
map and filter after the enumeration, and a getter can replace any of them.

That is not closable here. These cases share a closure with the guard, so an
author who can patch a global can patch the guard. The escalation is what was
wrong -- the previous round added a caller-supplied callback to the one spawn
site purely to make a mutation proof read better, and it had to be reverted.

So the claim is bounded rather than narrowed again:

- Freeze ALLOWED_CHILD_ENV, DECLARABLE_CASE_ENV_NAMES and SHELL_GENERATED_ENV.
  The name list was mutable; a case could push a forbidden name before
  declaring it. Verified: the push now throws and the spawn is still rejected.
- Say what the guard does. It rejects an ambient copy or a stray name passed
  as a declaration, which is the mistake a maintainer makes by accident. The
  comments claimed it closed the accessor gap; they no longer do.
- Correct the bootstrap() comment: main.ts constructs a logger before the
  secret check. The load-bearing claim -- the throw precedes any config read --
  is unchanged.

Document corrections, all found by review of claims written in earlier rounds:

- Withdraw "no second call to any replaceable global stands between the check
  and the use". False, and stated while correcting a different overclaim.
- Both exploits are rejected, but by different assertions. The ambient copy is
  named by the offending-keys message; the Proxy is stopped one assertion
  earlier by isProxy, whose message names no keys.
- The sandbox is created in spawnHermetic before the spawn call, not inside
  the spawn arguments. main.spec.ts:58 cleans up in a finally rather than by
  registration, outside the kbn-02a- prefix the residue count measures.
- The package.json RED does not execute the route yet: the script is absent, so
  the case stops on the missing manifest entry before any child is created.
- Three route cases, not two. Four XDG_*_HOME roots plus XDG_RUNTIME_DIR, not
  "five XDG home roots". Not every failure is behavioral -- the structural
  source guards are counted in the same 83.

RED unchanged: 83 failing / 17 passing (100 cases, 6 files), no Errors row,
zero /tmp/kbn-02a-* residue, fixture control green. Typecheck, lint, Prettier
clean.
2026-08-12 23:52:40 -05:00
shaggy ccb5913620 test(gateway): make the KBN-101-02a child-process fixture hermetic by allowlist
The dev:local route case built its child environment as a denylist — copy the
ambient process.env, delete three keys — leaving the real HOME, every XDG root,
MOSAIC_GATEWAY_HOME, service endpoints, auth/credential families, the Node
loader controls and an ambient PATH in place. A faulty GREEN could read real
host state before an assertion caught it, and a refusal could be produced by
the host's own configuration rather than by the route, so the case would pass
while proving nothing about the code under test. The hard timeout bounds how
long a leak runs; it does not prevent one.

The child now receives exactly eight variables built from scratch — a private
HOME under a per-run temporary sandbox, all five XDG roots and TMPDIR beneath
it, and a PATH built from the two workspace .bin directories and the directory
of the running Node binary — plus the per-case declarations. Nothing is
inherited.

Two cases hold that rather than assume it: a fixture control asserting the
constructed key set, that HOME is neither the real home nor an ancestor of it,
and that PATH is the three intended directories (green by construction, a
harness negative control, not coverage); and an executed case that plants a
complete valid local declaration and a forbidden DSN in the parent environment
and requires the undeclared refusal — a leaky fixture would fire the DSN
refusal instead.

RED only. 83 failing / 17 passing (100 cases, 6 files), Errors 0, zero
/tmp/kbn-02a-* residue. No GREEN, no push, no 17th fenced path.
2026-08-12 22:03:03 -05:00
shaggy bdcdff5e31 test(gateway): KBN-101-02a RED — positive anchors, owned exit, classified readability
Second AMEND from the verifier. Five blockers, all inside the 16-path fence; no
new path taken and no GREEN implemented.

1. The run carried an out-of-band `process.exit unexpectedly called with "1"`,
   raised by main.ts:71 self-invoking on import and rejecting after the importing
   case had returned. Vitest attributes that to no case and warns it can produce
   false positives; it also falsified the document's "zero non-assertion
   failures". The import is now wrapped so `process.exit` is stubbed
   non-throwing and the case awaits a settle turn — the behavioral red is
   unchanged, the error is owned, and the run reports `Errors 0`.

2. Two inventory cases demanded the raw values 'standalone' and 'postgres',
   which the value-free classification unions cannot represent, so no compliant
   implementation could have turned them green. They assert 'non-local' and
   'non-pglite'.

3. SourceReadability gained `absent`. Without it an absent source has to be
   reported `readable` — the one value meaning "read, and clean" — collapsing
   the distinction the refusal path is built on. The invariant
   `present === false` iff `readability === 'absent'` is now asserted per state
   and across all seven rows at once.

4. Acceptance #6 had no positive anchor: an empty `bootstrap()` and an
   always-refusing `onModuleInit()` satisfied every case, so "safe" could have
   meant "does not work". Two cases now fail against that — bootstrap must reach
   NestFactory.create and listen under the frozen policy with zero independent
   read, and the sterile local lifecycle must actually run both migrations with
   no Postgres handle. Both in-process and substituted at their seams; no port
   is bound and nothing connects.

5. Every mkdtemp site in the six files now registers teardown at the point of
   creation, including the child route's root created inside the spawn
   arguments. The matrix leaves zero /tmp/kbn-02a-* residue, measured.

Focused matrix: 82 failing / 16 passing (98 cases, 6 files), Errors 0.
Typecheck, lint, Prettier, diff --check clean.
2026-08-12 21:39:20 -05:00
shaggy 1a77739410 test(gateway): KBN-101-02a RED supplement — close the verifier's twelve findings
Author phase only; still no implementation. Kept as a distinct fifth commit so
the RED baseline, the contract restoration, the span audit and this supplement
remain separately reviewable.

The finding that mattered: every frozen-policy case mocked ./main.js wholesale,
so nothing executed main.ts, AppModule or the ConfigModule provider, and the
three independent reads at main.ts:28, app.module.ts:39 and config.module.ts:12
could all have survived a fully green matrix. Fence revision 15 -> 16 (granted
solely for apps/gateway/src/main.spec.ts) is used to import the real modules
with no ./main.js mock and assert no independent loadConfig, no tier probe and
no NestFactory.create. The existing anchoring case is left red-in-place rather
than deleted: its import-time-exit premise is the opposite of the new contract,
so it must be migrated by whoever implements GREEN.

Also closes: the executed dev:local child-process route, which requires a
LOCAL_START_* code AND the absence of the BETTER_AUTH_SECRET throw, since a
nonzero exit alone is satisfied by a crash; the real database onModuleInit
lifecycle, asserting migrations never run; the full disposable state-root
contract (absent, not-a-directory, symlink, non-private, foreign-owner), with
ownership substituted at lstat because a filesystem-built case passes trivially
wherever CI runs as root; unreadable and malformed sources, which refuse rather
than being skipped, built as EISDIR so they cannot be vacuous under any uid;
per-source non-local tier detection for all seven labels; canary retention and
console cases; post-freeze source-mutation cases; and a three-form static-import
guard.

Two defects of my own are fixed rather than papered over. The non-canonical
state-root case normalized to the valid path before the policy saw it, so it
demanded a refusal on input identical to the accepted one — a red that could
never go green for its stated reason. And the first substitution of @nestjs/core
was wholesale, which dropped APP_GUARD and killed app.module.ts at import, so
two cases failed for a reason they did not state.

Classification types are unions, not strings: a declaredTier?: string is
value-free only by convention, and a two-member union cannot carry a canary.

77 failing / 15 passing (92 cases, 6 files). Typecheck, lint and Prettier clean.
Zero non-assertion failures. Seven of the fifteen greens are vacuous against the
stub, up from three; that rise is recorded in the document so it cannot later be
read as coverage. The first RED report's implication that the GREEN targets were
covered behaviorally is corrected there too.

Refs: KBN-101-02a (Stack #1178)
2026-08-12 21:05:24 -05:00
shaggy 09c75f3b10 docs(kbn): downgrade the -05 Dockerfile finding to unresolved planned-vs-current
Scrappy's ruling, verified independently at
docs/scratchpads/771-kbn101-db-role-split.md:98, which records
apps/gateway/Dockerfile explicitly as 'a planned KBN-101-05 artifact'.
The row names something intended to exist, not a mis-naming of
docker/gateway.Dockerfile, so it is not the inverse defect I filed it as.

The correction sharpens the proposed control: a link check failing on any
absent ownership path would have flagged this row and been wrong. The
check needs a planned marker, and an unmarked absent path is the failure.

Negative existence evidence retained; classification corrected.
2026-08-12 20:23:38 -05:00
shaggy 93b81fac96 docs(kbn): file the -02a span audit of every held-until claim
Commissioned with -02a on the board ruling. Four findings: the -02
local-start hold is carried by eight files not five (AGENTS.md and
README.md among them, so -02a's completion surface is wider than its
record); a candidate defect of the same shape at -05, whose scope row
contains neither 'process-exec' nor 'LoadCredential' though three guides
condition deployment on that interface; a negative result confirming the
-00/-03/-05 activation hold spans correctly; and the structural hole that
makes all of them unverifiable, whose inverse form is the -05 rows naming
apps/gateway/Dockerfile, a path that does not exist.

Additive to section 10 only. No other item's rows altered; the Dockerfile
discrepancy is reported, not corrected — that row is -05's.
2026-08-12 20:04:46 -05:00
shaggy a4809d8c52 docs(kbn): restore KBN-101 family contract clobbered by the -02a manifest
b4c468b3 wrote the -02a path-ownership manifest OVER the frozen KBN-101
contract (#774, #902) rather than appending to it, deleting 272 lines
including the KBN-101-05 exclusive-ownership row, the K101-REQ-04
traceability row and the -03 runner/manifest contract.

Sections 1-9 are restored byte-identical to 216cd722. The -02a amendment
is re-added as additive section 10 with its headings demoted. No other
item's ownership rows are altered.

Self-reported to the verifier; the defect class is the same span/scope
failure -02a exists to close.
2026-08-12 20:00:32 -05:00
shaggy b4c468b3e7 test(gateway): KBN-101-02a RED — fail-closed local-start refusal
Author phase only. No implementation: the scaffolding is deliberately
permissive so every refusal assertion fails behaviorally rather than on a
missing module. A `not implemented` throw would have satisfied `.toThrow()`
and produced a green matrix that proved nothing.

Adds the path-ownership manifest and 60 behavioral cases across the nine
mutation->guard rows: inherited env, shared dotenv, daemon JSON, app JSON,
root JSON, MOSAIC_GATEWAY_HOME redirect, exact local tier, exact PGlite plus
disposable state root, and one-shot freeze with dynamic import.

50 red / 10 green. Zero non-assertion failures. The ten greens are itemized
in the manifest, including three that are vacuous until the implementation
exists.

Enforcement sits at the apps/gateway seam. Nothing in packages/db or
packages/config is touched: -02a proves the local entrypoint never reaches
those paths rather than modifying code owned by -01, -03 and -10.

Refs: KBN-101-02a (Stack #1178)
2026-08-12 19:54:24 -05:00
10 changed files with 5883 additions and 1 deletions

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();
});
});
+173
View File
@@ -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
+43
View File
@@ -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 [];
}
+362 -1
View File
@@ -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