From ae8b8cc5a48384d9f7e9aabd0cd39e45843a8b06 Mon Sep 17 00:00:00 2001 From: Mario Tarosso Date: Thu, 26 Nov 2026 09:01:47 +0000 Subject: [PATCH] Add PATCHSTACK_MODE=off to switch the guard off without a deploy Co-Authored-By: Claude Fable 5.2 --- AGENT-INSTALL.md | 10 +- README.md | 5 + src/cli.ts | 2 +- src/protect/protect.d.ts | 9 +- src/protect/runtime.js | 60 ++++++++++ .../switched-off-in-environment.test.ts | 108 ++++++++++++++++++ 6 files changed, 189 insertions(+), 5 deletions(-) create mode 100644 tests/protect/switched-off-in-environment.test.ts diff --git a/AGENT-INSTALL.md b/AGENT-INSTALL.md index 565f8e5..ec99fdd 100644 --- a/AGENT-INSTALL.md +++ b/AGENT-INSTALL.md @@ -772,8 +772,14 @@ would have stopped while it is still in dry-run. Two separate paths, with differ `protect --check` still accepts as the guard it wrote. Any other change to the file makes it a custom guard, which the check cannot vouch for. - **In automated tests**, the guard has no switch that removes it. Run the tests with - `PATCHSTACK_MODE=dry-run`, so it blocks nothing, and `PATCHSTACK_TELEMETRY=off`, so it reports nothing. + **In automated tests**, run the tests with `PATCHSTACK_MODE=dry-run`, so the guard blocks nothing, and + `PATCHSTACK_TELEMETRY=off`, so it reports nothing. + + **`PATCHSTACK_MODE=off` switches the guard off.** With it set, requests, responses and outbound calls + are not screened, no rules are fetched and nothing is reported; the app's log says so once at start. + It is read when the app starts, so it is set or cleared with a restart and no code change. It is for + the person running the app to use during an incident. Do not set it as part of an install, or to make + a test or a check pass: an app with it set is not protected. Keep `app.use(patchstackMiddleware)` unconditional: `protect --check` counts only a guard registered in the app's own scope, so registering it inside an `if` reads as unprotected. diff --git a/README.md b/README.md index 32b7091..b222835 100644 --- a/README.md +++ b/README.md @@ -548,6 +548,11 @@ refreshes rules while the app runs. It uses the existing cache and reporting. Set `PATCHSTACK_MODE=dry-run` to observe, or `PATCHSTACK_EGRESS=1` to enable outbound screening. Connect defaults to block mode for this integration. +`PATCHSTACK_MODE=off` switches the guard off for any integration: nothing is +screened, fetched or reported, and the app's log says so once at start. It is +read when the app starts, so setting or clearing it takes a restart and no code +change. An app with it set is not protected. + Import `protection` from the same entry point to inspect its `synchronization` and `coverage()` or to mount a request adapter. Preloading alone does not attach inbound request or response protection. Keep preview and production site diff --git a/src/cli.ts b/src/cli.ts index 847230d..018c7a3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -364,7 +364,7 @@ Environment: PATCHSTACK_ENDPOINT API endpoint (default: https://api.patchstack.com/monitor/pulse/manifest) PATCHSTACK_TIMEOUT_MS Request timeout in ms (default: 30000; a scan that needs longer saves what worked to .patchstackrc.json) PATCHSTACK_ENVIRONMENT Manifest label: production, sandbox or local. Unset, the build platform's own tier or branch name decides; a developer machine reports local. - PATCHSTACK_MODE (protect) Runtime guard mode: block (default) | dry-run + PATCHSTACK_MODE (protect) Runtime guard mode: block (default) | dry-run | off (screens nothing; applied on restart) PATCHSTACK_ROUTE_WAF (protect) Set to 1 to also screen every request at the route level (opt-in) Precedence, site UUID and settings: CLI flag > environment variable > .patchstackrc.json (committed). diff --git a/src/protect/protect.d.ts b/src/protect/protect.d.ts index e3e595a..1ff3219 100644 --- a/src/protect/protect.d.ts +++ b/src/protect/protect.d.ts @@ -19,7 +19,7 @@ export interface SynchronizationStatus { etag: string | null; lastCheckedAt: number | null; source: {ok: boolean; origin: "api" | "cache" | "bundled" | "empty"; reason?: string}; - mode: "block" | "dry-run"; + mode: "block" | "dry-run" | "off"; devSync: boolean; rules: {request: number; response: number; egress: number; delivered: number; local: number; scoped: number; scopedBlocking: number}; } @@ -27,7 +27,12 @@ export interface SynchronizationStatus { export interface Protection { /** Snapshot of the loaded guard and its last rule resolution, not proof of whole-app coverage. */ readonly synchronization: SynchronizationStatus; - mode: "block" | "dry-run"; + /** + * `off` only while `PATCHSTACK_MODE=off` is set in the environment: the guard screens nothing, reports + * nothing and reaches no network. It is read when the guard is created, so it takes a restart to set + * or clear, and it cannot be chosen on the platform or passed as an option. + */ + mode: "block" | "dry-run" | "off"; /** Active rules split by phase. */ rules: { request: unknown[]; response: unknown[]; egress: unknown[] }; /** (request, ...hostArgs) => Response (403 when blocked) | null (allow / dry-run). Request phase only. diff --git a/src/protect/runtime.js b/src/protect/runtime.js index b5b87f4..cd97685 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -139,6 +139,9 @@ const DETECTION_STALE_MS = 10_000; const BACKGROUND_CHECK_MS = 30_000; export async function createProtection(options = {}) { + // Read before anything else is: the switch exists for an incident, where the guard itself may be what + // has to stop, so nothing of it runs once the switch is set. + if (switchedOffInEnvironment()) return switchedOffProtection(options); // A copy of the runtime cache entry (`{ bundle, etag, … }`) passed as `rules` is read as the bundle it holds. if (options.rules && !Array.isArray(options.rules) && !Array.isArray(options.rules.firewall) && options.rules.bundle && Array.isArray(options.rules.bundle.firewall)) { @@ -2301,6 +2304,63 @@ function headersSentError(verb) { return Object.assign(new Error(`Cannot ${verb} headers after they are sent to the client`), { code: 'ERR_HTTP_HEADERS_SENT' }); } +/** Whether `PATCHSTACK_MODE=off` is set where this process runs. Read once per guard, when it is created. */ +function switchedOffInEnvironment() { + return typeof process !== 'undefined' && process.env?.PATCHSTACK_MODE === 'off'; +} + +const SWITCHED_OFF_SAID = Symbol.for('patchstack.connect.switched-off-said'); + +/** + * The guard an app gets while `PATCHSTACK_MODE=off`: every method is there, so the code that calls it + * runs unchanged, and none of them screens, reports or reaches the network. Requests go to the app as + * they came, responses leave as the app made them, and `fetch` and `node:http` are left as they were. + */ +function switchedOffProtection(options) { + const building = process.env?.NEXT_PHASE === 'phase-production-build'; + if (!building && !globalThis[SWITCHED_OFF_SAID]) { + // Once per process, however many copies of the guard a bundler makes. + globalThis[SWITCHED_OFF_SAID] = true; + console.warn( + '[patchstack] PATCHSTACK_MODE=off is set in this environment, so the guard is switched off: ' + + 'requests, responses and outbound calls are not screened, and nothing is reported. Remove PATCHSTACK_MODE to switch it back on.', + ); + } + + const source = { ok: false, origin: 'empty', reason: 'switched off by PATCHSTACK_MODE' }; + const passOn = (_req, _res, next) => next(); + + return { + mode: 'off', + rules: { request: [], response: [], egress: [] }, + coverage: () => ({ skipped: {} }), + screenResponse: async (response) => response, + screenNodeResponse() {}, + fetchGuard: () => async () => null, + fetch: (handler) => handler, + express: () => passOn, + node: () => passOn, + stop: () => Promise.resolve(), + stopRefresh: () => Promise.resolve(), + ruleSource: { ...source }, + synchronization: { + siteUuid: options.siteUuid ?? null, + buildId: null, + matched: false, + mapRules: 'unknown', + etag: null, + lastCheckedAt: null, + source: { ...source }, + mode: 'off', + devSync: false, + rules: { request: 0, response: 0, egress: 0, delivered: 0, local: 0, scoped: 0, scopedBlocking: 0 }, + }, + detectionReporting: 'disabled-by-config', + detectionHealth: undefined, + blockLogHealth: undefined, + }; +} + /** * Resolve runtime enforcement mode. * Precedence: PATCHSTACK_MODE env > Patchstack for JavaScript `enforcement` on the rules bundle > options.mode > dry-run. diff --git a/tests/protect/switched-off-in-environment.test.ts b/tests/protect/switched-off-in-environment.test.ts new file mode 100644 index 0000000..d7939ce --- /dev/null +++ b/tests/protect/switched-off-in-environment.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createProtection } from '../../src/protect/runtime.js'; + +// `PATCHSTACK_MODE=off` is the switch for an incident: with it set the guard screens nothing, reports +// nothing and reaches no network, and the code that calls it runs unchanged. + +const rules = { + firewall: [{ id: 'traversal', rule_v2: [{ parameter: 'get.f', mutations: ['urldecode'], match: { type: 'contains', value: '../' } }] }], + whitelists: [], + whitelist_keys: {}, + enforcement: 'block', +}; +const ATTACK = 'https://app.test/?f=../../etc/passwd'; +const SAID = Symbol.for('patchstack.connect.switched-off-said'); +const originalFetch = globalThis.fetch; + +let protection: any; + +afterEach(async () => { + await protection?.stop(); + protection = undefined; + delete process.env.PATCHSTACK_MODE; + delete (globalThis as any)[SAID]; + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); +}); + +describe('a guard switched off in the environment', () => { + it('lets through what the same guard blocks when switched on', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'log').mockImplementation(() => {}); + + protection = await createProtection({ mode: 'block', reportDetections: false, rules }); + expect((await protection.fetchGuard()(new Request(ATTACK)))?.status).toBe(403); + await protection.stop(); + + process.env.PATCHSTACK_MODE = 'off'; + protection = await createProtection({ mode: 'block', reportDetections: false, rules }); + + expect(protection.mode).toBe('off'); + expect(await protection.fetchGuard()(new Request(ATTACK))).toBeNull(); + }); + + it('hands handlers, responses and middleware back untouched', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + process.env.PATCHSTACK_MODE = 'off'; + protection = await createProtection({ mode: 'block', egress: true, rules }); + + const handler = async () => new Response('from the app'); + const response = new Response('body'); + const next = vi.fn(); + + expect(protection.fetch(handler)).toBe(handler); + expect(await protection.screenResponse(response, new Request(ATTACK))).toBe(response); + protection.express()({}, {}, next); + protection.node()({}, {}, next); + expect(next).toHaveBeenCalledTimes(2); + expect(protection.screenNodeResponse({}, new Request(ATTACK))).toBeUndefined(); + }); + + it('leaves fetch alone and reaches no network, even with a token and outbound screening asked for', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const calls: unknown[] = []; + const stub = (async (input: unknown) => { + calls.push(input); + return new Response('{}'); + }) as any; + globalThis.fetch = stub; + process.env.PATCHSTACK_MODE = 'off'; + + protection = await createProtection({ mode: 'block', egress: true, token: 'not-a-real-token', siteUuid: '11111111-2222-3333-4444-555555555555' }); + + expect(globalThis.fetch).toBe(stub); + expect(calls).toEqual([]); + expect(protection.detectionReporting).toBe('disabled-by-config'); + expect(protection.detectionHealth).toBeUndefined(); + expect(protection.ruleSource).toMatchObject({ ok: false, origin: 'empty' }); + expect(protection.synchronization).toMatchObject({ mode: 'off', matched: false }); + expect(protection.coverage()).toEqual({ skipped: {} }); + await expect(protection.stop()).resolves.toBeUndefined(); + await expect(protection.stopRefresh()).resolves.toBeUndefined(); + }); + + it('says so once in the log, however many guards are created', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + process.env.PATCHSTACK_MODE = 'off'; + + protection = await createProtection({ rules }); + await createProtection({ rules }); + + const lines = warn.mock.calls.map((call) => String(call[0])).filter((line) => line.includes('PATCHSTACK_MODE=off')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain('the guard is switched off'); + }); + + it('is not switched off by the option, or by any other value', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'log').mockImplementation(() => {}); + + protection = await createProtection({ mode: 'off' as never, reportDetections: false, rules }); + expect(protection.mode).not.toBe('off'); + await protection.stop(); + + process.env.PATCHSTACK_MODE = 'OFF'; + protection = await createProtection({ mode: 'block', reportDetections: false, rules }); + expect(protection.mode).toBe('block'); + }); +});