Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions field-test/hosted-startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,18 @@ compares the uploaded build ID with a different local ID, and checks the
service's verdict in both cases. Use a sandbox site reserved for this fixture
because each run uploads an app map. Rule delivery and a matching build do not
establish that this fixture has any generated rules to enforce.

## Build-scoped rule check against a local service

Use `PS_FASTIFY_LOCAL_SAAS=http://127.0.0.1:<port>/monitor/pulse` with the
same command above. Run once to upload the fixture's map. In the local service,
attach a synthetic request rule to that map's build for `POST /fixture`. Match
the literal `fixture-block` in `post.label` and configure the sandbox site for
blocking. Rerun the same fixture and tarball with `PS_FASTIFY_SCOPE_RULE` set to
the served rule ID. The matching build returns 403. The other build's lookup
omits the rule and returns 200.

Optionally set `PS_FASTIFY_FALLBACK_RULES_URL` to a second loopback endpoint that
delivers the sandbox site's unfiltered bundle. The same mismatched build must
then load the rule in detect-only mode and still return 200. Verify the two
recorded matches share a rule revision and only the first was enforced.
19 changes: 19 additions & 0 deletions scripts/fastify-startup-live.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ assert.equal(status.siteUuid, deployment.siteUuid);
assert.equal(status.buildId, deployment.buildId);
assert.equal(status.matched, expectMatch);
const { bundle } = JSON.parse(readFileSync('.patchstack/patchstack-rules.json', 'utf8'));
const scopedRule = process.env.PS_FASTIFY_SCOPE_RULE;
if (scopedRule) {
const outcome = process.env.PS_FASTIFY_SCOPE_EXPECT;
const served = bundle.firewall.find(rule => String(rule.id) === scopedRule);
const active = protection.rules.request.find(rule => String(rule.id) === scopedRule);
if (outcome === 'absent') {
assert.equal(served, undefined, 'The scoped lookup should omit the other build’s rule.');
assert.equal(active, undefined);
} else {
assert.ok(served && /^[a-f0-9]{64}$/.test(served.build_scope), 'SaaS did not serve the dedicated build-scoped rule.');
assert.equal(served.build_scope === deployment.buildId, outcome === 'block');
assert.ok(active, 'The guard did not load the dedicated rule.');
assert.equal(active.enforcement === 'dry-run', outcome === 'detect');
}
process.once('SIGTERM', async () => {
await protection.stop();
process.exit(0);
});
}
console.log('Fastify live pilot ' + JSON.stringify({
matched: status.matched, mapRules: status.mapRules, delivered: bundle.firewall.length,
scoped: status.rules.scoped, scopedBlocking: status.rules.scopedBlocking,
Expand Down
50 changes: 45 additions & 5 deletions scripts/framework-consumers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,25 @@ const [name, tarball] = process.argv.slice(2);
assert.ok(Object.hasOwn(fixtures, name) && tarball, `Usage: node scripts/framework-consumers.mjs <${Object.keys(fixtures).join('|')}> <tarball>`);
const fixture = fixtures[name];
const live = process.env.PS_FASTIFY_LIVE === '1';
const localSaas = process.env.PS_FASTIFY_LOCAL_SAAS;
const fallbackRulesUrl = process.env.PS_FASTIFY_FALLBACK_RULES_URL;
const scopedRule = process.env.PS_FASTIFY_SCOPE_RULE;
const siteUuid = process.env.PATCHSTACK_SITE_UUID;
const apiKey = process.env.PATCHSTACK_API_KEY;
if (live) {
assert.ok(fixture.preload && process.platform === 'linux', 'Live mode requires a Linux Fastify startup fixture.');
assert.ok(siteUuid && apiKey, 'Live mode needs a dedicated sandbox site and API key.');
}
for (const endpoint of [localSaas, fallbackRulesUrl].filter(value => value !== undefined)) {
assert.ok(live && /^http:\/\/127\.0\.0\.1:[0-9]+\/monitor\/pulse$/.test(endpoint),
'The local SaaS endpoint must be an explicit loopback HTTP service.');
}
if (scopedRule !== undefined) {
assert.ok(localSaas && scopedRule.trim(), 'Scoped enforcement checks require a local SaaS sandbox.');
}
if (fallbackRulesUrl !== undefined) {
assert.ok(scopedRule, 'The fallback rules service needs a dedicated sandbox rule.');
}
const cwd = mkdtempSync(join(tmpdir(), 'ps-framework-'));
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('PATCHSTACK_') && key !== 'NODE_OPTIONS' && !key.startsWith('PS_FASTIFY_')));
Object.assign(env, { ASTRO_TELEMETRY_DISABLED: '1', NUXT_TELEMETRY_DISABLED: '1', CI: '1', HOST: '127.0.0.1' });
Expand All @@ -215,10 +228,17 @@ async function check(protectedApp, liveBuild) {
await new Promise(done => listener.close(done));
const processEnv = { ...env, PORT: String(port), ORIGIN: `http://127.0.0.1:${port}` };
if (liveBuild) {
const rulesUrl = liveBuild.rulesUrl ?? localSaas;
Object.assign(processEnv, {
PS_FASTIFY_LIVE: '1', PS_FASTIFY_EXPECT_MATCH: liveBuild.matched ? '1' : '0',
PATCHSTACK_SITE_UUID: siteUuid, PATCHSTACK_API_KEY: apiKey,
PATCHSTACK_DEPLOYMENT_FILE: liveBuild.file, PATCHSTACK_ENVIRONMENT: 'sandbox', PATCHSTACK_MODE: 'dry-run',
PATCHSTACK_DEPLOYMENT_FILE: liveBuild.file, PATCHSTACK_ENVIRONMENT: 'sandbox',
PATCHSTACK_MODE: scopedRule ? 'block' : 'dry-run',
...(rulesUrl ? { PATCHSTACK_PULSE_RULES_URL: rulesUrl } : {}),
...(scopedRule ? {
PS_FASTIFY_SCOPE_RULE: scopedRule,
PS_FASTIFY_SCOPE_EXPECT: liveBuild.scopedOutcome,
} : {}),
});
}
const preload = liveBuild ? './host/live.mjs' : fixture.preload;
Expand All @@ -230,6 +250,7 @@ async function check(protectedApp, liveBuild) {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ label }),
signal: AbortSignal.timeout(3000),
});
let scopedCheckCompleted = false;
try {
let normal;
for (let attempt = 0; attempt < (liveBuild ? 350 : 200) && app.exitCode === null; attempt++) {
Expand Down Expand Up @@ -258,6 +279,15 @@ async function check(protectedApp, liveBuild) {
assert.equal(status.source.ok, true);
assert.equal(status.source.origin, 'api');
console.log(reported);
if (scopedRule) {
assert.equal(status.mode, 'block');
const response = await post('fixture-block');
assert.equal(response.status, liveBuild.scopedOutcome === 'block' ? 403 : 200);
const body = await response.json();
if (liveBuild.scopedOutcome !== 'block') assert.equal(body.label, 'fixture-block');
console.log(`Scoped rule (${liveBuild.scopedOutcome}): HTTP ${response.status}`);
scopedCheckCompleted = true;
}
return;
}
if (protectedApp) assert.doesNotMatch(result.sample, /fixture-private/);
Expand Down Expand Up @@ -291,9 +321,14 @@ async function check(protectedApp, liveBuild) {
} finally {
if (app.exitCode === null) {
const exited = once(app, 'exit');
const timer = setTimeout(() => app.kill('SIGKILL'), 3000);
const timer = setTimeout(() => app.kill('SIGKILL'), scopedRule ? 8000 : 3000);
app.kill('SIGTERM');
try { await exited; } finally { clearTimeout(timer); }
try {
const [code] = await exited;
if (scopedCheckCompleted) assert.equal(code, 0, 'The guard must drain detections before exiting.');
} finally {
clearTimeout(timer);
}
}
}
}
Expand Down Expand Up @@ -335,12 +370,17 @@ export const { errorCodes, LogController } = createGuardedApp;`);
const deployment = 'host/deployment.json';
run(process.execPath, [join(packageDir, 'dist/cli.js'), 'prepare-deploy', '--out', deployment], {
...env, PATCHSTACK_SITE_UUID: siteUuid, PATCHSTACK_API_KEY: apiKey, PATCHSTACK_ENVIRONMENT: 'sandbox',
...(localSaas ? { PATCHSTACK_ENDPOINT: localSaas + '/manifest' } : {}),
});
await check(true, { file: deployment, matched: true });
await check(true, { file: deployment, matched: true, scopedOutcome: 'block' });
const unmatched = JSON.parse(readFileSync(join(cwd, deployment), 'utf8'));
unmatched.buildId = (unmatched.buildId[0] === '0' ? '1' : '0') + unmatched.buildId.slice(1);
put('host/unmatched.json', JSON.stringify(unmatched));
await check(true, { file: 'host/unmatched.json', matched: false });
const mismatch = { file: 'host/unmatched.json', matched: false };
await check(true, { ...mismatch, scopedOutcome: 'absent' });
if (fallbackRulesUrl) {
await check(true, { ...mismatch, scopedOutcome: 'detect', rulesUrl: fallbackRulesUrl });
}
} else {
await check(true);
}
Expand Down
Loading