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
7 changes: 7 additions & 0 deletions .changeset/violation-event-ids.md
Original file line number Diff line number Diff line change
@@ -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`.
6 changes: 6 additions & 0 deletions packages/fastify/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 39 additions & 0 deletions packages/fastify/src/violation-delivery.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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<void>((resolve) => server.close(() => resolve()));
}
});
18 changes: 17 additions & 1 deletion packages/hono/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>) => 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);
Expand All @@ -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.
Expand Down
35 changes: 35 additions & 0 deletions packages/hono/src/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const tasks: Promise<unknown>[] = [];
const ctx = { waitUntil: (task: Promise<unknown>) => { 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<void>((resolve) => server.close(() => resolve()));
}
});
});
2 changes: 2 additions & 0 deletions packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 13 additions & 3 deletions packages/webdecoy/src/fetch-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>) => void;
}

export interface FetchGuard {
/** Evaluate one request. */
check(request: Request, peer?: string): Promise<GuardOutcome>;
check(request: Request, peer?: string, lifecycle?: GuardLifecycle): Promise<GuardOutcome>;
/**
* 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.
Expand Down Expand Up @@ -156,7 +166,7 @@ export function createFetchGuard(options: FetchGuardOptions = {}): FetchGuard {
return shouldSkipPath(pathname, options.skipPaths);
},

async check(request: Request, peer?: string): Promise<GuardOutcome> {
async check(request: Request, peer?: string, lifecycle?: GuardLifecycle): Promise<GuardOutcome> {
const url = new URL(request.url);
const headers = headerRecord(request.headers);
if (!headers.host && !headers[':authority']) headers.host = url.host;
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/webdecoy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions packages/webdecoy/src/rules/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
105 changes: 102 additions & 3 deletions packages/webdecoy/src/violation-reporter.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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]);
Expand All @@ -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<void>((resolve) => closed.listen(0, '127.0.0.1', resolve));
const port = (closed.address() as AddressInfo).port;
await new Promise<void>((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([]);
});
});
Loading
Loading