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
26 changes: 23 additions & 3 deletions src/protect/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,11 @@ export async function createProtection(options = {}) {
const { capture: _evidence, ...forCallback } = detection ?? {};
notify(
userOnDetect,
{ ...forCallback, ...(detection?.rule ? { rule: ruleIdentity(detection.rule) } : {}) },
{
...forCallback,
...(typeof forCallback.message === 'string' ? { message: messageForMode(forCallback.message, forCallback.mode) } : {}),
...(detection?.rule ? { rule: ruleIdentity(detection.rule) } : {}),
},
'onDetect',
);
};
Expand Down Expand Up @@ -1909,7 +1913,16 @@ export async function createProtection(options = {}) {
fetchGuard() {
return async (request, ...hostArgs) => {
const { blocked } = await screenFetchRequest(request, hostArgs);
await deliverInRequest(blocked);
// A middleware that only screens (Next.js on Vercel) is frozen once the route answers, so a queued
// detect-only report would wait for a timer that never runs. Where the host offers `waitUntil`, the
// report is handed to it, as `fetch` does; otherwise it is delivered within the request.
const keep = detections && (blocked || detections.pending()) ? hostWaitUntil(request, hostArgs) : null;
if (keep) {
keep(detections.settle());
detectPendingSince = null;
} else {
await deliverInRequest(blocked);
}

return blocked;
};
Expand Down Expand Up @@ -3262,9 +3275,16 @@ function blockResponse(result, request) {
});
}

// A rule's message is written without knowing the mode it will run under, and the engine's default says
// "Blocked by". A match that did not block must not say it did.
function messageForMode(message, mode) {
return mode === 'block' ? message : message.replace(/^Blocked by /, 'Matched by ');
}

// Rules the site adds itself carry no category; they are named as what they are rather than as unknown.
function defaultOnDetect({ phase, mode, category, rule, message }) {
const tag = mode === 'block' ? 'BLOCK' : 'DETECT (dry-run)';
console.warn(`[patchstack] ${tag} phase=${phase ?? 'request'} category=${category ?? '?'} rule=${rule?.id ?? '?'} ${message ?? ''}`.trim());
console.warn(`[patchstack] ${tag} phase=${phase ?? 'request'} category=${category || 'custom'} rule=${rule?.id ?? '?'} ${message ?? ''}`.trim());
}

/**
Expand Down
49 changes: 49 additions & 0 deletions tests/protect/rules-reader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,52 @@ describe('delivering a block report on a host that passes no execution context a
await protection.stop();
});
});

// A Next.js middleware calls `fetchGuard` with the request alone, and on Vercel the function is frozen
// once the route answers: a detect-only report queued for a later flush would never be sent.
describe('a detect-only report from fetchGuard on a host with waitUntil', () => {
const key = Symbol.for('@vercel/request-context');
afterEach(() => {
delete (globalThis as Record<symbol, unknown>)[key];
});

it('is handed to the host and delivered, without waiting for a later request', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ps-reader-'));
dirs.push(cwd);
vi.stubEnv('PATCHSTACK_API_KEY', '');
vi.stubEnv('PATCHSTACK_PULSE_AUTH', '');
vi.stubEnv('PATCHSTACK_MODE', '');
const calls: string[] = [];
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
calls.push(String(url));
if (String(url).endsWith('/token')) return Response.json({ access_token: 'reader-token', expires_in: 3600 });
if (String(url).includes('/detections/')) return new Response('{}', { status: 202 });
return Response.json({ firewall: [{ id: 'live-rule', phase: 'request', action: 'block', rule_v2: [{ parameter: 'get.q', match: { type: 'contains', value: 'live-attack' } }] }], whitelists: [], whitelist_keys: {}, enforcement: 'dry-run' });
}));
const lines: string[] = [];
vi.spyOn(console, 'warn').mockImplementation((line: string) => { lines.push(line); });
const protection: any = await createProtection({
siteUuid: '550e8400-e29b-41d4-a716-446655440000',
pulseRulesUrl: 'https://x.test/monitor/pulse',
cwd,
cacheDir: join(cwd, '.patchstack'),
rules: { firewall: [], whitelists: [], whitelist_keys: {}, _patchstack: { rules_reader: READER } } as never,
reportDetections: true,
});
const kept: Promise<unknown>[] = [];
(globalThis as Record<symbol, unknown>)[key] = { get: () => ({ waitUntil: (work: Promise<unknown>) => { kept.push(work); } }) };

expect(await protection.fetchGuard()(new Request('https://app.test/search?q=live-attack'))).toBeNull();
expect(kept).toHaveLength(1);
await Promise.all(kept);
expect(calls.some((url) => url.includes('/detections/'))).toBe(true);

// The log line says what happened: a match that did not block, from a rule with no category.
const line = lines.find((l) => l.includes('rule=live-rule'));
expect(line).toContain('DETECT (dry-run)');
expect(line).toContain('category=custom');
expect(line).toContain('Matched by Patchstack WAF rule: live-rule');
expect(line).not.toContain('Blocked');
await protection.stop();
});
});