diff --git a/field-test/hosted-startup.md b/field-test/hosted-startup.md new file mode 100644 index 00000000..44332e5a --- /dev/null +++ b/field-test/hosted-startup.md @@ -0,0 +1,43 @@ +# Host-managed startup without app source changes + +The Fastify fixture starts the same entry file with and without a host-owned +Node loader hook. The hook uses `node:module.registerHooks()` to attach the +existing Fastify adapter when the app imports its installed Fastify factory. +It preserves the default and named exports. The fixture pins one copy of +Fastify 5.12.1 and uses a local synthetic rule bundle. + +Build and pack Connect, then run the fixtures against the resulting tarball. + +```sh +npm run build +tarball=$(npm pack --ignore-scripts --quiet) +npm run test:frameworks -- fastify-startup-esm "$tarball" +npm run test:frameworks -- fastify-startup-cjs "$tarball" +``` + +Both fixtures send HTTP requests to a real server. They check the source is +byte-for-byte identical, parsed JSON still reaches the app, a matching request +is blocked, scoped response rules redact values, and a stream's first chunk +reaches the client while the response is still open. The tests ran on Node +22.22, 24.21 and 26.8. The hook runs via an explicit `node --import` argument, +so the host can leave `NODE_OPTIONS` untouched. + +For a partner pilot, start with one app per process and add the hook through +the service manager or container command. Verify the framework and package +version, rule delivery for the deployment, and actual HTTP coverage before +enabling enforcement. Use the framework-native scaffold when the host can +participate in the build. That model also gives bundled and edge apps an +appropriate place to attach the guard. + +The experiment covers unbundled Fastify apps that load the tested factory by +package name. Bundled or alternate entry points, raw replies that bypass +Fastify's send hook, and shared tenant processes need separate integration. Stream +headers are screened and their bodies pass through. Live rule delivery and +build identity are verified separately by the hosted deployment fixture. + +A host-side proxy could apply request and response rules to traffic it +terminates. It would need separate integration for app-specific parsed fields, +dependency activity and outbound calls. A separate loader experiment could +observe which package versions really load, then evaluate version-specific +patches. Package replacement has its own compatibility and rollback +requirements and is outside this fixture. diff --git a/scripts/fastify-startup-preload.mjs b/scripts/fastify-startup-preload.mjs new file mode 100644 index 00000000..d4224a5a --- /dev/null +++ b/scripts/fastify-startup-preload.mjs @@ -0,0 +1,33 @@ +// Proof of concept for one host-managed Fastify app per Node process. +import { createRequire, registerHooks } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { patchstackFastify } from './fastify-guard.mjs'; + +const entry = process.argv[1]; +if (!entry) throw new Error('The Fastify startup fixture needs an application entry file.'); + +const requireFromEntry = createRequire(entry); +const factoryPath = requireFromEntry.resolve('fastify'); +if (requireFromEntry.cache[factoryPath]) throw new Error('The Fastify startup fixture must load before Fastify.'); +const { version } = requireFromEntry('fastify/package.json'); +if (version !== '5.12.1') throw new Error('The Fastify startup fixture needs Fastify 5.12.1.'); + +const fastify = requireFromEntry(factoryPath); +const factoryUrl = pathToFileURL(factoryPath).href; +const facadeUrl = new URL('./facade.mjs', import.meta.url).href; + +export function createGuardedApp(...options) { + return fastify(...options).register(patchstackFastify); +} +Object.assign(createGuardedApp, fastify); +createGuardedApp.fastify = createGuardedApp; +createGuardedApp.default = createGuardedApp; + +registerHooks({ + resolve(specifier, context, nextResolve) { + const resolved = nextResolve(specifier, context); + if (specifier !== 'fastify') return resolved; + if (resolved.url !== factoryUrl) throw new Error('The Fastify startup fixture only covers one installed copy.'); + return { url: facadeUrl, format: 'module', shortCircuit: true }; + }, +}); diff --git a/scripts/framework-consumers.mjs b/scripts/framework-consumers.mjs index 34909454..474182e8 100644 --- a/scripts/framework-consumers.mjs +++ b/scripts/framework-consumers.mjs @@ -1,10 +1,11 @@ import assert from 'node:assert/strict'; import { spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:net'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; const output = `({ label: body.label, sample: 'fixture-private' })`; const fetchRoute = `async ({ request }) => { @@ -146,8 +147,11 @@ function fastifyFixture(format) { return { dependencies: { fastify: '5.12.1' }, files: { [entry]: ` -${commonJs ? "const { fastify } = require('fastify');" : "import defaultFastify, { fastify } from 'fastify';"} -${commonJs ? "" : "if (defaultFastify !== fastify) throw new Error('Inconsistent Fastify exports');"} +${commonJs ? "const defaultFastify = require('fastify'); const { fastify, errorCodes, LogController } = defaultFastify;" : "import defaultFastify, { fastify, errorCodes, LogController } from 'fastify';"} +if (defaultFastify !== fastify || defaultFastify.errorCodes !== errorCodes || !errorCodes + || defaultFastify.LogController !== LogController || typeof LogController !== 'function') { + throw new Error('Inconsistent Fastify exports'); +} ${commonJs ? "const { Readable } = require('node:stream');" : "import { Readable } from 'node:stream';"} const app = fastify(); let finishStream; @@ -172,6 +176,14 @@ app.listen({ port: Number(process.env.PORT), host: '127.0.0.1' }); } fixtures.fastify = fastifyFixture('cjs'); +for (const format of ['esm', 'cjs']) { + fixtures['fastify-startup-' + format] = { + ...fastifyFixture(format), + rules: 'host/rules.json', + preload: './host/preload.mjs', + }; +} + // Run against an npm pack artifact on a Unix host. Framework packages are pinned per fixture. const [name, tarball] = process.argv.slice(2); assert.ok(Object.hasOwn(fixtures, name) && tarball, `Usage: node scripts/framework-consumers.mjs <${Object.keys(fixtures).join('|')}> `); @@ -193,7 +205,8 @@ async function check(protectedApp) { const port = listener.address().port; await new Promise(done => listener.close(done)); const processEnv = { ...env, PORT: String(port), ORIGIN: `http://127.0.0.1:${port}` }; - const app = spawn(process.execPath, fixture.start, { cwd, env: processEnv, stdio: ['ignore', 'pipe', 'pipe'] }); + const flags = protectedApp && fixture.preload ? ['--import', fixture.preload] : []; + const app = spawn(process.execPath, [...flags, ...fixture.start], { cwd, env: processEnv, stdio: ['ignore', 'pipe', 'pipe'] }); let log = ''; for (const stream of [app.stdout, app.stderr]) stream.on('data', part => { log += part; }); const post = label => fetch(processEnv.ORIGIN + '/fixture', { @@ -253,10 +266,20 @@ try { run('npm', ['install', '--no-audit', '--no-fund', '--ignore-scripts']); if (fixture.build) run(process.execPath, fixture.build); await check(false); - const cli = 'node_modules/@patchstack/connect/dist/cli.js'; - run(process.execPath, [cli, 'protect']); - run(process.execPath, [cli, 'protect', '--check']); - readFileSync(join(cwd, fixture.rules)); + const packageDir = 'node_modules/@patchstack/connect'; + if (fixture.preload) { + mkdirSync(join(cwd, 'host'), { recursive: true }); + copyFileSync(fileURLToPath(new URL('./fastify-startup-preload.mjs', import.meta.url)), join(cwd, fixture.preload)); + put('host/facade.mjs', `import { createGuardedApp } from './preload.mjs'; +export { createGuardedApp as fastify, createGuardedApp as default, createGuardedApp as 'module.exports' }; +export const { errorCodes, LogController } = createGuardedApp;`); + copyFileSync(join(cwd, packageDir, 'dist/protect/templates/fastify-plugin.js'), join(cwd, 'host/fastify-guard.mjs')); + } else { + const cli = join(packageDir, 'dist/cli.js'); + run(process.execPath, [cli, 'protect']); + run(process.execPath, [cli, 'protect', '--check']); + readFileSync(join(cwd, fixture.rules)); + } put(fixture.rules, JSON.stringify({ firewall: [ { id: 'fixture-request', rule_v2: [{ parameter: 'post.label', match: { type: 'equals', value: 'fixture-block' } }] }, { id: 'fixture-response', phase: 'response', action: 'redact', when: { path: '/fixture', method: 'POST' }, @@ -266,6 +289,9 @@ try { ], whitelists: [], whitelist_keys: {} })); if (fixture.build) run(process.execPath, fixture.build); await check(true); + if (fixture.preload) { + for (const [file, source] of Object.entries(fixture.files)) assert.equal(readFileSync(join(cwd, file), 'utf8'), source); + } console.log(`PASS ${name}: HTTP request screening, normal body parsing and response redaction${fixture.stream ? ' including stream headers' : ''}`); } finally { rmSync(cwd, { recursive: true, force: true });