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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,27 @@ if (!result.allowed) {
}
```

### Confirm an SSRF callback

For a route that intentionally performs a server-side fetch, mint a short-lived
canary and report its initiation immediately before the fetch:

```typescript
const canary = await wd.createSSRFCanary({
routeTemplate: '/api/fetch/:id',
test: true, // controlled validation; excluded from production threat metrics
});

await wd.reportSSRFInitiation(canary);
await applicationFetch(canary.callbackUrl);
```

Use the callback URL only as the controlled destination for the fetch you are
testing. WebDecoy never fetches a supplied URL. A confirmed finding requires
both the trusted initiation and the matching single-use callback within 15
minutes; either edge alone is not confirmed SSRF. Open the callback detection
in WebDecoy to see its **Correlated activity** evidence.

### Getting an API key

1. Sign up at [app.webdecoy.com](https://app.webdecoy.com)
Expand Down
17 changes: 17 additions & 0 deletions packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,23 @@ Behind a proxy, `req.socket.remoteAddress` is the proxy. Use `resolveClientIp()`

To get a key: sign up at [app.webdecoy.com](https://app.webdecoy.com), add your site, then create a key on the **API Keys** page. Keys start with `sk_live_` (production) or `sk_test_` (testing); any other prefix throws when the SDK is constructed. Keep the key on the server and out of committed files.

### Confirm an SSRF callback

```ts
const canary = await wd.createSSRFCanary({
routeTemplate: '/api/fetch/:id',
test: true,
});
await wd.reportSSRFInitiation(canary);
await applicationFetch(canary.callbackUrl);
```

The marker is property-scoped, single-use, and expires after 15 minutes. The
SDK reports only its marker ID and route template on the initiation edge.
WebDecoy never fetches a supplied URL; a finding is created only after the
matching callback arrives. Use `test: true` for controlled validation so it is
kept out of production threat metrics.

### Monitor first

`protect()` only returns a decision. It never writes a response, so nothing is blocked until your code acts on `decision.allowed`. The framework adapters and `createFetchGuard()` follow the same rule: they start in **monitor mode** (`mode: 'monitor'`), record the decision and serve every request. Set `mode: 'enforce'` only after you have reviewed what would have been blocked.
Expand Down
72 changes: 71 additions & 1 deletion packages/webdecoy/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@
*/

import type { AIReferralBatch } from './referrals/referral-counter';
import { SDKDetectionRequest, SDKDetectionResponse } from './types';
import {
SDKDetectionRequest,
SDKDetectionResponse,
SSRFCanary,
SSRFCanaryOptions,
SSRFInitiationReceipt,
} from './types';
import { reportableHeaders } from './report-headers';
import type { ViolationEvent, IPEnrichmentData } from './rules/types';

Expand Down Expand Up @@ -207,6 +213,70 @@ export class WebDecoyClient {
return response.data as SDKDetectionResponse;
}

async createSSRFCanary(options: SSRFCanaryOptions): Promise<SSRFCanary> {
const response = await this.request<{
marker_id: string;
callback_url: string;
route_template: string;
expires_at: string;
test: boolean;
} & ApiErrorBody>('POST', '/api/v1/sdk/ssrf/markers', {
property_id: options.propertyId,
route_template: options.routeTemplate,
test: options.test === true,
});
this.requireSuccess(response);
const data = response.data!;
if (!data.marker_id || !data.callback_url || !data.route_template || !data.expires_at) {
throw new Error('WebDecoy returned an invalid SSRF canary');
}
return {
markerId: data.marker_id,
callbackUrl: data.callback_url,
routeTemplate: data.route_template,
expiresAt: data.expires_at,
test: data.test === true,
};
}

async reportSSRFInitiation(
canary: Pick<SSRFCanary, 'markerId' | 'routeTemplate'>,
): Promise<SSRFInitiationReceipt> {
const response = await this.request<{
detection_id: string;
marker_id: string;
test: boolean;
} & ApiErrorBody>('POST', '/api/v1/sdk/ssrf/initiate', {
marker_id: canary.markerId,
route_template: canary.routeTemplate,
});
this.requireSuccess(response);
const data = response.data!;
if (!data.detection_id || !data.marker_id) {
throw new Error('WebDecoy returned an invalid SSRF initiation receipt');
}
return { detectionId: data.detection_id, markerId: data.marker_id, test: data.test === true };
}

private requireSuccess(response: ApiResponse<ApiErrorBody>): void {
if (response.status === 401) {
throw new Error('Invalid API key. Please check your Web Decoy configuration.');
}
if (response.status === 429) {
throw new Error('Rate limit exceeded. Please try again later.');
}
if (response.status >= 400) {
throw new Error(
response.data?.error ||
response.data?.message ||
`API request failed: HTTP ${response.status}`,
);
}
if (!response.data) {
throw new Error('WebDecoy returned an empty response');
}
}

/**
* Send violation events to the ingest service
*/
Expand Down
3 changes: 3 additions & 0 deletions packages/webdecoy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ export type {
SDKDetectionResponse,
ProtectResult,
ProtectOptions,
SSRFCanary,
SSRFCanaryOptions,
SSRFInitiationReceipt,
} from './types';

// The decision `protect()` returns. Exported as a value because the class
Expand Down
24 changes: 24 additions & 0 deletions packages/webdecoy/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ import {
ProtectOptions,
SDKDetectionRequest,
SDKDetectionResponse,
SSRFCanary,
SSRFCanaryOptions,
SSRFInitiationReceipt,
} from './types';

export class WebDecoy {
Expand Down Expand Up @@ -324,6 +327,27 @@ export class WebDecoy {
return this.getAgentVerifier().verify(request);
}

/** Mint a signed, single-use callback marker for an SSRF test or observation. */
async createSSRFCanary(options: SSRFCanaryOptions): Promise<SSRFCanary> {
if (!this.client) {
throw new Error('An apiKey is required to create an SSRF canary');
}
return this.client.createSSRFCanary(options);
}

/**
* Report the initiating server request immediately before the application's
* ordinary fetch. Only the marker ID and route template are sent.
*/
async reportSSRFInitiation(
canary: Pick<SSRFCanary, 'markerId' | 'routeTemplate'>,
): Promise<SSRFInitiationReceipt> {
if (!this.client) {
throw new Error('An apiKey is required to report an SSRF initiation');
}
return this.client.reportSSRFInitiation(canary);
}

/**
* Whether this SDK instance has filter rules that need async enrichment
*/
Expand Down
58 changes: 58 additions & 0 deletions packages/webdecoy/src/ssrf-canary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { WebDecoy } from './sdk';

describe('SSRF canary correlation', () => {
const realFetch = global.fetch;

afterEach(() => {
global.fetch = realFetch;
});

it('reports only the marker ID and route template on the initiation edge', async () => {
const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
global.fetch = jest.fn(async (url: unknown, init: RequestInit) => {
const body = JSON.parse(String(init.body)) as Record<string, unknown>;
calls.push({ url: String(url), body });
if (String(url).endsWith('/ssrf/markers')) {
return new Response(JSON.stringify({
marker_id: 'd65fd38c-4f45-4f32-91cf-1cdcd9c03fe6',
callback_url: 'https://ingest.example/api/v1/ssrf/callback/opaque-token',
route_template: '/api/fetch/:id',
expires_at: '2026-11-15T21:00:00Z',
test: true,
token: 'must-not-be-returned-by-the-sdk',
}), { status: 201 });
}
return new Response(JSON.stringify({
detection_id: 'c18348c8-9f6b-43e9-b993-86ca15db257f',
marker_id: body.marker_id,
test: true,
}), { status: 201 });
}) as jest.Mock;

const sdk = new WebDecoy({ apiKey: 'sk_test_ssrf', apiUrl: 'https://ingest.example' });
const canary = await sdk.createSSRFCanary({ routeTemplate: '/api/fetch/:id', test: true });
const receipt = await sdk.reportSSRFInitiation(canary);

expect(canary).toEqual({
markerId: 'd65fd38c-4f45-4f32-91cf-1cdcd9c03fe6',
callbackUrl: 'https://ingest.example/api/v1/ssrf/callback/opaque-token',
routeTemplate: '/api/fetch/:id',
expiresAt: '2026-11-15T21:00:00Z',
test: true,
});
expect(receipt.detectionId).toBe('c18348c8-9f6b-43e9-b993-86ca15db257f');
expect(calls[1]).toEqual({
url: 'https://ingest.example/api/v1/sdk/ssrf/initiate',
body: {
marker_id: 'd65fd38c-4f45-4f32-91cf-1cdcd9c03fe6',
route_template: '/api/fetch/:id',
},
});
expect(JSON.stringify(calls[1].body)).not.toContain('opaque-token');
});

it('requires a hosted API key', async () => {
const sdk = new WebDecoy();
await expect(sdk.createSSRFCanary({ routeTemplate: '/fetch' })).rejects.toThrow(/apiKey/);
});
});
25 changes: 25 additions & 0 deletions packages/webdecoy/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,31 @@ export interface WebDecoyConfig {
tracer?: Tracer;
}

/** Options for one short-lived, property-scoped SSRF canary. */
export interface SSRFCanaryOptions {
/** The application route that will perform the server-side fetch. */
routeTemplate: string;
/** Required only when an organization-wide API key is used. */
propertyId?: string;
/** Keep a controlled validation out of production threat metrics. */
test?: boolean;
}

/** A callback marker. Put callbackUrl in the controlled outbound request. */
export interface SSRFCanary {
markerId: string;
callbackUrl: string;
routeTemplate: string;
expiresAt: string;
test: boolean;
}

export interface SSRFInitiationReceipt {
detectionId: string;
markerId: string;
test: boolean;
}

/**
* TLS connection information from the request
*/
Expand Down
Loading