From 8a404a6c7fe72ca12fa0bf7b5c88f515810e5dc8 Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 19 Nov 2026 15:39:01 +0000 Subject: [PATCH] Make firewall log lines match what the guard did Three fixes to the guard's detection reporting and its console line. A detect-only match on the `fetchGuard` path (the Next.js middleware, and the other templates that call it) was queued and left for a timer or a later request to send. On a host that freezes the function after the response, such as Vercel, neither runs, so the detection never reached the dashboard. `fetchGuard` now hands the queued report to the host's `waitUntil` when one is available, as `fetch` already does. Without one, delivery is unchanged. A match that did not block was logged as "Blocked by Patchstack WAF rule", because the engine's default message is written before the rule's mode is known. The message given to `onDetect`, and so the console line, now says "Matched by" when the mode is not block. Block responses are unchanged. Rules with no category, which is how the site's own rules arrive, were logged as `category=?`. They are now logged as `category=custom`. Amp-Thread-ID: https://ampcode.com/threads/T-2e659ca3-7bd0-4d70-b3d3-09638251060b Co-authored-by: Danilo Radovic --- src/protect/runtime.js | 26 ++++++++++++++-- tests/protect/rules-reader.test.ts | 49 ++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/src/protect/runtime.js b/src/protect/runtime.js index c6b4c5d..7cb8525 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -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', ); }; @@ -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; }; @@ -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()); } /** diff --git a/tests/protect/rules-reader.test.ts b/tests/protect/rules-reader.test.ts index ef3a38d..f93f434 100644 --- a/tests/protect/rules-reader.test.ts +++ b/tests/protect/rules-reader.test.ts @@ -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)[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[] = []; + (globalThis as Record)[key] = { get: () => ({ waitUntil: (work: Promise) => { 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(); + }); +});