diff --git a/.changeset/violation-event-ids.md b/.changeset/violation-event-ids.md new file mode 100644 index 0000000..e3d71f7 --- /dev/null +++ b/.changeset/violation-event-ids.md @@ -0,0 +1,7 @@ +--- +'@webdecoy/node': minor +'@webdecoy/fastify': patch +'@webdecoy/hono': patch +--- + +Give every reported rule violation a unique `eventId` so ingest stores it once even when a batch is delivered twice. Deliver buffered violations before a process exits: the reporter now holds the process open for at most one flush interval when events are waiting, `fastify.close()` sends what the plugin still holds, and the Hono middleware passes `executionCtx.waitUntil` to the reporter on Workers. `FetchGuard.check()` accepts an optional lifecycle with `waitUntil`. diff --git a/packages/fastify/src/plugin.ts b/packages/fastify/src/plugin.ts index f5ba03b..e1c8226 100644 --- a/packages/fastify/src/plugin.ts +++ b/packages/fastify/src/plugin.ts @@ -231,6 +231,12 @@ async function webdecoyPluginImpl( enabled: options.honeytoken, }); + // fastify.close() is the app's shutdown: send what the reporter still holds + // and stop its timers, so the last violations are delivered or counted. + fastify.addHook('onClose', async () => { + await sdk.destroy(); + }); + // Add decorator for webdecoy property fastify.decorateRequest('webdecoy', null); // The edge validator's verdict, typed, so a handler can branch on diff --git a/packages/fastify/src/violation-delivery.test.ts b/packages/fastify/src/violation-delivery.test.ts new file mode 100644 index 0000000..fafe6f6 --- /dev/null +++ b/packages/fastify/src/violation-delivery.test.ts @@ -0,0 +1,39 @@ +import Fastify from 'fastify'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tripwire } from '@webdecoy/node'; +import { webdecoyPlugin } from './plugin'; + +// fastify.close() is how an app shuts down. The plugin's SDK is private, so +// the plugin itself has to send what its reporter still holds at that point. +test('fastify.close() delivers the violations the plugin still holds', async () => { + const received: { path?: string; eventId?: string }[] = []; + const server = createServer(async (request, response) => { + let body = ''; + for await (const chunk of request) body += chunk; + if (request.url === '/api/v1/sdk/violations/batch') received.push(...JSON.parse(body).events); + response.writeHead(201).end('{}'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + + try { + const app = Fastify(); + await app.register(webdecoyPlugin, { + apiKey: 'sk_test_fastify_delivery', apiUrl, countAIReferrals: false, honeytoken: false, + mode: 'enforce', rules: [tripwire({ includeDefaults: false, paths: ['/trap'] })], + }); + app.get('/*', async () => 'ok'); + + const res = await app.inject({ method: 'GET', url: '/trap' }); + expect(res.statusCode).toBe(403); + // Buffered, not yet sent: the reporter batches on an interval. + expect(received).toEqual([]); + + await app.close(); + expect(received).toEqual([expect.objectContaining({ path: '/trap', eventId: expect.any(String) })]); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/packages/hono/src/index.ts b/packages/hono/src/index.ts index 1d57d63..6f84f36 100644 --- a/packages/hono/src/index.ts +++ b/packages/hono/src/index.ts @@ -49,6 +49,22 @@ declare module 'hono' { } } +/** + * The runtime's waitUntil (Workers and other runtimes with an execution + * context), so violation delivery outlives the response. Hono throws when the + * runtime has no execution context, as on Node or Bun, where the reporter's + * own timer delivers instead. + */ +function executionWaitUntil(c: Context): ((delivery: Promise) => void) | undefined { + try { + const ctx = c.executionCtx; + if (typeof ctx?.waitUntil !== 'function') return undefined; + return (delivery) => ctx.waitUntil(delivery); + } catch { + return undefined; + } +} + export function webdecoy(options: WebDecoyHonoOptions = {}): MiddlewareHandler { const { onBlocked, ...guardOptions } = options; const guard = createFetchGuard(guardOptions); @@ -63,7 +79,7 @@ export function webdecoy(options: WebDecoyHonoOptions = {}): MiddlewareHandler { // there is no portable accessor across Hono's runtimes — so the guard's // trusted-hops default over X-Forwarded-For is what resolves the client, // and `trustProxy: 'cloudflare'` is the stronger choice behind Cloudflare. - const { decision, response } = await guard.check(c.req.raw); + const { decision, response } = await guard.check(c.req.raw, undefined, { waitUntil: executionWaitUntil(c) }); c.set(WEBDECOY_CONTEXT_KEY, decision); // The same value under the name the Node adapters use, so documentation and // application code do not have to branch on which framework they are in. diff --git a/packages/hono/src/middleware.test.ts b/packages/hono/src/middleware.test.ts index 3ca497d..e2503c7 100644 --- a/packages/hono/src/middleware.test.ts +++ b/packages/hono/src/middleware.test.ts @@ -1,3 +1,5 @@ +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; import { Hono } from 'hono'; import { tripwire, rateLimit } from '@webdecoy/node'; import { webdecoy } from './index'; @@ -162,3 +164,36 @@ describe('honeytoken injection through Hono', () => { expect(global.fetch).toHaveBeenCalledTimes(attempts); }); }); + +describe('violation delivery on Workers', () => { + // Workers can freeze the isolate once the response is returned, so the + // report has to be handed to the execution context, not left to a timer. + it('hands the report to executionCtx.waitUntil', async () => { + const received: { path?: string; eventId?: string }[] = []; + const server = createServer(async (request, response) => { + let body = ''; + for await (const chunk of request) body += chunk; + if (request.url === '/api/v1/sdk/violations/batch') received.push(...JSON.parse(body).events); + response.writeHead(201).end('{}'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + const tasks: Promise[] = []; + const ctx = { waitUntil: (task: Promise) => { tasks.push(task); }, passThroughOnException() {}, props: {} }; + + try { + const app = appWith({ + apiKey: 'sk_test_hono_delivery', apiUrl, countAIReferrals: false, honeytoken: false, + rules: [tripwire({ includeDefaults: false, paths: ['/trap'] })], + }); + const res = await app.fetch(new Request('https://worker.example/trap'), {}, ctx); + expect(res.status).toBe(403); + expect(tasks).toHaveLength(1); + await Promise.all(tasks); + expect(received).toEqual([expect.objectContaining({ path: '/trap', eventId: expect.any(String) })]); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); +}); diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index 22f361b..5ab26e1 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -200,6 +200,8 @@ Local rules decide the request before the SDK reports their events. With an API For a long-lived SDK instance, call `getViolationDeliveryStats()` for counts of events acknowledged by ingest, failed batches, discarded events, and events waiting for an attempt. Call `await sdk.destroy()` during graceful shutdown to finish an in-flight send and attempt the remaining queue. Reporting has a fixed in-memory buffer. When the client pauses after a failure, unattempted events stay buffered. An attempted batch with an uncertain acknowledgment is discarded to avoid replaying its server-side effects. +Each event carries a unique `eventId`. Ingest stores an event once per id, so a batch that reaches it twice, for example through a proxy retry, adds no second violation and no second detection, and the repeat is still acknowledged. If the process exits without `destroy()`, the reporter keeps it open for at most one flush interval plus the request timeout to attempt the events it holds. It never keeps the process open while the client is paused after a failure. The Fastify plugin sends its remaining events when `fastify.close()` runs, and the Hono middleware hands each send to `executionCtx.waitUntil` on runtimes that provide one, such as Cloudflare Workers. + ## Fetch runtimes (Bun, Deno, Workers, Astro, SvelteKit, Remix) `createFetchGuard()` wraps the SDK for any runtime that hands you a WHATWG `Request`. It is the same implementation `@webdecoy/hono` uses. diff --git a/packages/webdecoy/src/fetch-guard.ts b/packages/webdecoy/src/fetch-guard.ts index 1167fa1..ddcfd66 100644 --- a/packages/webdecoy/src/fetch-guard.ts +++ b/packages/webdecoy/src/fetch-guard.ts @@ -69,9 +69,19 @@ export interface GuardOutcome { response?: Response; } +/** The host runtime's request lifecycle, where it has one. */ +export interface GuardLifecycle { + /** + * Keeps violation delivery alive after the response, as Workers' + * `ctx.waitUntil`. Without it a runtime that freezes after responding can + * drop the report. + */ + waitUntil?: (delivery: Promise) => void; +} + export interface FetchGuard { /** Evaluate one request. */ - check(request: Request, peer?: string): Promise; + check(request: Request, peer?: string, lifecycle?: GuardLifecycle): Promise; /** * Rewrite an HTML response to carry the honeytoken link. Returns the response * unchanged when there is no token yet, or the body is not injectable HTML. @@ -156,7 +166,7 @@ export function createFetchGuard(options: FetchGuardOptions = {}): FetchGuard { return shouldSkipPath(pathname, options.skipPaths); }, - async check(request: Request, peer?: string): Promise { + async check(request: Request, peer?: string, lifecycle?: GuardLifecycle): Promise { const url = new URL(request.url); const headers = headerRecord(request.headers); if (!headers.host && !headers[':authority']) headers.host = url.host; @@ -175,7 +185,7 @@ export function createFetchGuard(options: FetchGuardOptions = {}): FetchGuard { threshold: options.threshold, skipLocalAnalysis: options.skipLocalAnalysis, metadata: options.metadata, - violationReporting: { mode }, + violationReporting: { mode, waitUntil: lifecycle?.waitUntil }, }); // Monitor mode records the verdict and serves the request anyway. The diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index ec2184a..1f553b9 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -143,7 +143,7 @@ export { shouldSkipPath, ruleBlockResponse, armSiteHoneytoken, deriveAndArm } fr export type { BlockResponse, HoneytokenArmingOptions } from './adapter-core'; export { createFetchGuard } from './fetch-guard'; -export type { FetchGuard, FetchGuardOptions, GuardOutcome } from './fetch-guard'; +export type { FetchGuard, FetchGuardOptions, GuardLifecycle, GuardOutcome } from './fetch-guard'; export { createNodeHttpGuard } from './node-http-guard'; export type { diff --git a/packages/webdecoy/src/rules/types.ts b/packages/webdecoy/src/rules/types.ts index 04661d1..3195670 100644 --- a/packages/webdecoy/src/rules/types.ts +++ b/packages/webdecoy/src/rules/types.ts @@ -225,6 +225,12 @@ export interface ViolationEvent { dryRun: boolean; /** When the violation occurred (ISO 8601) */ timestamp: string; + /** + * Unique id for this event (a UUID), assigned by the reporter when absent. + * Ingest stores an event once per id, so a batch that reaches it twice adds + * no second violation and no second tripwire detection. + */ + eventId?: string; } /** diff --git a/packages/webdecoy/src/violation-reporter.test.ts b/packages/webdecoy/src/violation-reporter.test.ts index b9aa00e..2dc2c74 100644 --- a/packages/webdecoy/src/violation-reporter.test.ts +++ b/packages/webdecoy/src/violation-reporter.test.ts @@ -1,5 +1,11 @@ +import { spawn } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { buildSync } from 'esbuild'; import { WebDecoyClient } from './client'; import { WebDecoy } from './sdk'; import { tripwire } from './rules'; @@ -73,7 +79,7 @@ test('counts a refused batch once and keeps unattempted events for a later flush const reporter = new ViolationReporter(client); const events: ViolationEvent[] = Array.from({ length: 105 }, (_, index) => ({ rule: 'rateLimit', action: 'THROTTLE', ip: '192.0.2.5', path: `/fixture/${index}`, - dryRun: false, timestamp: new Date().toISOString(), + dryRun: false, timestamp: new Date().toISOString(), eventId: randomUUID(), })); try { @@ -119,9 +125,9 @@ test('a flush scheduled during an active send acknowledges the newly queued even .mockResolvedValue(true); const first: ViolationEvent = { rule: 'rateLimit', action: 'THROTTLE', ip: '192.0.2.5', path: '/first', - dryRun: false, timestamp: new Date().toISOString(), + dryRun: false, timestamp: new Date().toISOString(), eventId: randomUUID(), }; - const second = { ...first, path: '/second' }; + const second = { ...first, path: '/second', eventId: randomUUID() }; try { reporter.report([first]); @@ -141,3 +147,96 @@ test('a flush scheduled during an active send acknowledges the newly queued even await reporter.destroy(); } }); + +test('gives every event its own id and keeps an id the caller set', async () => { + const client = new WebDecoyClient({ + apiUrl, apiKey: 'sk_test_delivery_fixture', debug: false, timeout: 1_000, tlsRejectUnauthorized: true, + }); + const reporter = new ViolationReporter(client); + const event: ViolationEvent = { + rule: 'tripwire', action: 'DENY', ip: '192.0.2.5', path: '/trap', + dryRun: false, timestamp: new Date().toISOString(), + }; + const preset = randomUUID(); + + try { + reporter.report([event, { ...event }, { ...event, eventId: preset }]); + await reporter.flush(); + } finally { + await reporter.destroy(); + } + + const ids = batches.flat().map((sent) => sent.eventId); + expect(ids).toHaveLength(3); + expect(ids[0]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(new Set(ids).size).toBe(3); + expect(ids[2]).toBe(preset); + // The caller's object is not modified. + expect(event.eventId).toBeUndefined(); +}); + +describe('a process that exits without destroy()', () => { + // The reporter as an installed package ships it, run in its own process so + // the exit is a real one: nothing but the reporter holds the event loop. + let dir: string; + let bundle: string; + + beforeAll(() => { + dir = mkdtempSync(path.join(tmpdir(), 'wd-reporter-exit-')); + bundle = path.join(dir, 'reporter.cjs'); + buildSync({ + stdin: { + contents: "export { ViolationReporter } from './violation-reporter'; export { WebDecoyClient } from './client';", + resolveDir: __dirname, + loader: 'ts', + }, + bundle: true, platform: 'node', format: 'cjs', outfile: bundle, logLevel: 'silent', + }); + }); + + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + function runChild(target: string): Promise<{ code: number | null; ms: number; output: string }> { + const script = path.join(dir, 'child.cjs'); + writeFileSync(script, ` + const { ViolationReporter, WebDecoyClient } = require(${JSON.stringify(bundle)}); + const client = new WebDecoyClient({ + apiUrl: process.argv[2], apiKey: 'sk_test_exit', debug: false, timeout: 1000, tlsRejectUnauthorized: true, + }); + const reporter = new ViolationReporter(client, { flushInterval: 200 }); + reporter.report([{ rule: 'tripwire', action: 'DENY', ip: '192.0.2.5', path: '/exit-trap', + dryRun: false, timestamp: new Date().toISOString() }]); + // A server that has been closed: the handler returns and nothing else runs. + `); + const started = Date.now(); + return new Promise((resolve) => { + const child = spawn(process.execPath, [script, target], { stdio: ['ignore', 'pipe', 'pipe'] }); + let output = ''; + child.stdout.on('data', (chunk) => { output += chunk; }); + child.stderr.on('data', (chunk) => { output += chunk; }); + const kill = setTimeout(() => child.kill('SIGKILL'), 10_000); + child.on('exit', (code) => { + clearTimeout(kill); + resolve({ code, ms: Date.now() - started, output }); + }); + }); + } + + test('delivers the events it still holds before exiting', async () => { + const result = await runChild(apiUrl); + expect(result).toMatchObject({ code: 0 }); + expect(batches).toEqual([[expect.objectContaining({ path: '/exit-trap', eventId: expect.any(String) })]]); + }); + + test('still exits when ingest cannot be reached', async () => { + const closed = createServer(); + await new Promise((resolve) => closed.listen(0, '127.0.0.1', resolve)); + const port = (closed.address() as AddressInfo).port; + await new Promise((resolve) => closed.close(() => resolve())); + + const result = await runChild(`http://127.0.0.1:${port}`); + expect(result.code).toBe(0); + expect(result.ms).toBeLessThan(5_000); + expect(batches).toEqual([]); + }); +}); diff --git a/packages/webdecoy/src/violation-reporter.ts b/packages/webdecoy/src/violation-reporter.ts index 309c070..5e9b1ea 100644 --- a/packages/webdecoy/src/violation-reporter.ts +++ b/packages/webdecoy/src/violation-reporter.ts @@ -37,6 +37,8 @@ export class ViolationReporter { private client: WebDecoyClient; private buffer: ViolationEvent[] = []; private flushTimer: ReturnType; + private deliveryTimer: ReturnType | undefined; + private flushInterval: number; private maxBufferSize: number; private debug: boolean; private flushPromise: Promise | undefined; @@ -51,6 +53,7 @@ export class ViolationReporter { this.debug = config.debug ?? false; const flushInterval = config.flushInterval ?? 5000; + this.flushInterval = flushInterval; // flush() catches everything internally and never rejects, so `void` is the // whole handling. Said out loud because a timer whose callback rejects // keeps firing and every tick adds another unhandled rejection. @@ -64,7 +67,11 @@ export class ViolationReporter { * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize. */ report(violations: ViolationEvent[]): void { - this.buffer.push(...violations); + // A per-event id lets ingest store each event once, however many times + // the batch carrying it arrives. + for (const violation of violations) { + this.buffer.push(violation.eventId ? violation : { ...violation, eventId: crypto.randomUUID() }); + } if (this.buffer.length > MAX_BUFFERED_VIOLATIONS) { const overflow = this.buffer.length - MAX_BUFFERED_VIOLATIONS; this.buffer.splice(0, overflow); @@ -74,9 +81,35 @@ export class ViolationReporter { if (this.buffer.length >= this.maxBufferSize) { // Fire-and-forget flush this.flush().catch(() => {}); + } else { + this.scheduleDelivery(); } } + /** + * Give buffered events one delivery attempt before the process can exit. + * + * The interval above is unref'd so an idle reporter never holds a process + * open. On its own that meant a server shut down gracefully (Express after + * server.close(), Fastify after close(), Hono on Node) exited with its last + * events unsent and uncounted. This one-shot timer is left ref'd, so a + * natural exit waits at most one flush interval plus the request timeout. + * It is not re-armed while the client is paused, so an outage cannot keep + * the process alive. + */ + private cancelDelivery(): void { + clearTimeout(this.deliveryTimer); + this.deliveryTimer = undefined; + } + + private scheduleDelivery(): void { + if (this.deliveryTimer) return; + this.deliveryTimer = setTimeout(() => { + this.deliveryTimer = undefined; + void this.flush(); + }, this.flushInterval); + } + /** Flush the buffer, coalescing requests that arrive during an active send. */ flush(): Promise { if (this.queuedFlush) return this.queuedFlush; @@ -93,7 +126,11 @@ export class ViolationReporter { const size = this.buffer.length; this.flushPromise = Promise.resolve() .then(() => this.flushBatches(size)) - .finally(() => { this.flushPromise = undefined; }); + .finally(() => { + this.flushPromise = undefined; + // Nothing left to deliver: stop holding the process open. + if (this.buffer.length === 0) this.cancelDelivery(); + }); return this.flushPromise; } @@ -129,6 +166,7 @@ export class ViolationReporter { /** Stop the timer and give remaining events one final flush. */ async destroy(): Promise { clearInterval(this.flushTimer); + this.cancelDelivery(); if (this.flushPromise) await this.flushPromise; await this.flush(); this.droppedEvents += this.buffer.length;