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
86 changes: 72 additions & 14 deletions packages/sdk/src/cli/serve-webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ import { join, resolve } from 'node:path';
import { TextDecoder } from 'node:util';
import type { CliIo } from '../cli.js';
import { providerInboxEvent } from '../trigger-executor.js';
import { verifySignature, schemeFor } from '../webhook-signature.js';
import { TokenBucketLimiter, keyFor, type RateLimitConfig } from '../webhook-rate-limit.js';

const MAX_BODY_BYTES = 1024 * 1024;
const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;

const DEFAULT_RATE_LIMIT: RateLimitConfig = { ratePerSecond: 20, burst: 60 };

export function parseWebhookArgs(args: readonly string[]): {
command: 'serve-webhook'; dataDir: string; port: number; admitted?: readonly string[];
} | undefined {
Expand Down Expand Up @@ -44,21 +48,45 @@ function reply(response: ServerResponse, status: number, body: object): void {
}

/**
* POST /<name> accepts JSON; /providers/<provider> accepts typed event envelopes.
* Look up the shared secret for a provider from the process environment.
*
* When `admittedNames` is set, unknown names (or providers) refuse with
* `webhook_flow_unknown`. This closes the "any-name" ingress opened by slice E
* (#333) so the receiver only accepts inbox writes for triggers whose flows
* have been explicitly loaded — the loaded-flow admission half of #303.
* (Durable handler execution against the journal is deferred; per #303 that
* half depends on kernel authored-handler registration + resume protocol.)
* `WEBHOOK_SECRET_<PROVIDER_UPPER>` (e.g. `WEBHOOK_SECRET_GITHUB`) is the
* canonical env var. When unset, the receiver runs unsigned — this is
* documented in #301 as the local-development posture.
*/
export function providerSecret(provider: string | undefined, env: NodeJS.ProcessEnv = process.env): string | undefined {
if (!provider) return env.WEBHOOK_SECRET_DEFAULT;
const upper = provider.toUpperCase().replace(/[^A-Z0-9]/g, '_');
return env[`WEBHOOK_SECRET_${upper}`];
}

export interface WebhookServerOptions {
/**
* When set, unknown names refuse with `webhook_flow_unknown`. Closes the
* "any-name" ingress opened by slice E (#333) so the receiver only accepts
* inbox writes for triggers whose flows have been explicitly loaded — the
* loaded-flow admission half of #303. Durable handler execution against
* the journal is deferred; per #303 that half depends on kernel authored-
* handler registration + resume protocol.
*/
admittedNames?: ReadonlySet<string>;
/** Optional rate limit config; defaults to 20/s with 60 burst per key. */
rateLimit?: RateLimitConfig;
/** Injectable env lookup for tests. */
env?: NodeJS.ProcessEnv;
}

/** POST /<name> accepts JSON; /providers/<provider> accepts typed event envelopes. */
export async function startWebhookServer(
dataDir: string, port: number, options: { admittedNames?: ReadonlySet<string> } = {},
dataDir: string,
port: number,
options: WebhookServerOptions = {},
): Promise<Server> {
const inbox = join(resolve(dataDir), 'inbox');
await directory(inbox);
const admitted = options.admittedNames;
const env = options.env ?? process.env;
const limiter = new TokenBucketLimiter(options.rateLimit ?? DEFAULT_RATE_LIMIT);
// TODO https://github.com/AgentWorkforce/flows/issues/301: provider signatures,
// public ingress and Cloud mount provisioning belong to the deployment slice.
const server = createServer(async (request, response) => {
Expand All @@ -75,15 +103,29 @@ export async function startWebhookServer(
reply(response, 404, { error: 'invalid_webhook_name' });
return;
}
// Loaded-flow admission (#303) runs FIRST: refuse unknown names before
// spending any body-read or rate-limit budget. A rogue POST can't
// accumulate events in an inbox the daemon will never drain, and can't
// steal from the honest ratelimit token bucket.
if (admitted !== undefined && !admitted.has(name)) {
// Loaded-flow admission (#303): the receiver refuses any name whose
// trigger wasn't advertised at boot, so a rogue POST can't accumulate
// events in an inbox the daemon will never drain. The check runs before
// any body read so an unadmitted caller can't waste MAX_BODY_BYTES.
request.resume();
reply(response, 404, { error: 'webhook_flow_unknown', name });
return;
}
// #304 rate limiting — key by provider+name+source so an abusive caller
// cannot starve every route. Loopback callers share 127.0.0.1 as the
// source key by design (single-process, single-tenant).
const sourceAddress = request.socket.remoteAddress ?? '127.0.0.1';
const provider = providerRoute ? name : undefined;
const rateKey = keyFor(provider, name, sourceAddress);
const decision = limiter.consume(rateKey);
if (!decision.allowed) {
request.resume();
const retryAfterSeconds = Math.max(1, Math.ceil(decision.retryAfterMs / 1000));
response.setHeader('retry-after', String(retryAfterSeconds));
reply(response, 429, { error: 'webhook_rate_limited', retryAfterMs: decision.retryAfterMs });
Comment on lines +124 to +126

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When ratePerSecond is zero, this emits Retry-After: Infinity and retryAfterMs: null, neither of which is valid retry metadata. Omit the retry header and field for a non-refilling bucket, or define a finite retry policy.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/sdk/src/cli/serve-webhook.ts, line 93:

<comment>When `ratePerSecond` is zero, this emits `Retry-After: Infinity` and `retryAfterMs: null`, neither of which is valid retry metadata. Omit the retry header and field for a non-refilling bucket, or define a finite retry policy.</comment>

<file context>
@@ -53,6 +81,20 @@ export async function startWebhookServer(dataDir: string, port: number): Promise
+    const decision = limiter.consume(rateKey);
+    if (!decision.allowed) {
+      request.resume();
+      const retryAfterSeconds = Math.max(1, Math.ceil(decision.retryAfterMs / 1000));
+      response.setHeader('retry-after', String(retryAfterSeconds));
+      reply(response, 429, { error: 'webhook_rate_limited', retryAfterMs: decision.retryAfterMs });
</file context>
Suggested change
const retryAfterSeconds = Math.max(1, Math.ceil(decision.retryAfterMs / 1000));
response.setHeader('retry-after', String(retryAfterSeconds));
reply(response, 429, { error: 'webhook_rate_limited', retryAfterMs: decision.retryAfterMs });
const retryAfterSeconds = Number.isFinite(decision.retryAfterMs)
? Math.max(1, Math.ceil(decision.retryAfterMs / 1000))
: undefined;
if (retryAfterSeconds !== undefined) response.setHeader('retry-after', String(retryAfterSeconds));
reply(response, 429, { error: 'webhook_rate_limited',
...(retryAfterSeconds === undefined ? {} : { retryAfterMs: decision.retryAfterMs }) });

return;
}
let temporary: string | undefined;
try {
let bytes = 0;
Expand All @@ -97,9 +139,23 @@ export async function startWebhookServer(
}
chunks.push(buffer);
}
const rawBody = Buffer.concat(chunks);
// #304 signature verification — only enforced when a secret is
// configured for this provider/name. Absent secret = development mode.
const secret = providerSecret(provider, env);
if (secret) {
const scheme = schemeFor(provider);
const headerValue = request.headers[scheme.header];
const suppliedHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue;
const verdict = verifySignature(provider, rawBody, suppliedHeader, secret);
if (!verdict.ok) {
reply(response, 401, { error: 'webhook_signature_invalid', reason: verdict.reason });
return;
}
}
let payload: unknown;
try {
payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)), (_key, value: unknown) => {
payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(rawBody), (_key, value: unknown) => {
if (typeof value === 'number' && !Number.isFinite(value)) throw new Error('non-finite JSON number');
return value;
});
Expand All @@ -111,7 +167,9 @@ export async function startWebhookServer(
try {
payload = providerInboxEvent(name, payload);
} catch (error) {
reply(response, 400, { error: 'invalid_provider_event',
// #304 payload-shape rejection: providers declare a closed event
// vocabulary; anything else is `webhook_payload_invalid`.
reply(response, 400, { error: 'webhook_payload_invalid',
message: error instanceof Error ? error.message : 'invalid provider event' });
return;
}
Expand Down
69 changes: 69 additions & 0 deletions packages/sdk/src/webhook-rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* In-process token-bucket rate limiter for the local webhook receiver (#304).
*
* Slice E's receiver binds loopback and is documented as development-only, so
* a single-process in-memory bucket is sufficient. Cluster deployments must
* layer a shared store in a follow-up slice; the taxonomy stays the same
* (`webhook_rate_limited`) so client behavior does not change.
*/
export interface RateLimitConfig {
/** Tokens replenished per second. */
readonly ratePerSecond: number;
/** Maximum burst capacity. */
readonly burst: number;
}

export interface RateLimitDecision {
readonly allowed: boolean;
readonly retryAfterMs: number;
}

interface Bucket {
tokens: number;
refilledAtMs: number;
}

export class TokenBucketLimiter {
private readonly buckets = new Map<string, Bucket>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Every unique route/source key remains in buckets forever. Because the receiver admits arbitrary route names before validation, a local client can grow this map without bound; add idle eviction or a bounded key policy.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/sdk/src/webhook-rate-limit.ts, line 27:

<comment>Every unique route/source key remains in `buckets` forever. Because the receiver admits arbitrary route names before validation, a local client can grow this map without bound; add idle eviction or a bounded key policy.</comment>

<file context>
@@ -0,0 +1,69 @@
+}
+
+export class TokenBucketLimiter {
+  private readonly buckets = new Map<string, Bucket>();
+
+  constructor(
</file context>


constructor(
private readonly config: RateLimitConfig,
private readonly clock: () => number = Date.now,
) {
if (config.burst <= 0 || config.ratePerSecond < 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When a caller supplies NaN or Infinity in RateLimitConfig, the constructor accepts it and the bucket can reject every request with a non-finite retry value. Require finite rate and burst values before creating the limiter.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/sdk/src/webhook-rate-limit.ts, line 33:

<comment>When a caller supplies `NaN` or `Infinity` in `RateLimitConfig`, the constructor accepts it and the bucket can reject every request with a non-finite retry value. Require finite rate and burst values before creating the limiter.</comment>

<file context>
@@ -0,0 +1,69 @@
+    private readonly config: RateLimitConfig,
+    private readonly clock: () => number = Date.now,
+  ) {
+    if (config.burst <= 0 || config.ratePerSecond < 0) {
+      throw new Error('rate limiter: burst > 0 and ratePerSecond >= 0 required');
+    }
</file context>

throw new Error('rate limiter: burst > 0 and ratePerSecond >= 0 required');
}
}

consume(key: string, cost = 1): RateLimitDecision {
const now = this.clock();
const bucket = this.buckets.get(key) ?? { tokens: this.config.burst, refilledAtMs: now };
const elapsedSeconds = Math.max(0, (now - bucket.refilledAtMs) / 1000);
bucket.tokens = Math.min(this.config.burst, bucket.tokens + elapsedSeconds * this.config.ratePerSecond);
bucket.refilledAtMs = now;
if (bucket.tokens >= cost) {
bucket.tokens -= cost;
this.buckets.set(key, bucket);
return { allowed: true, retryAfterMs: 0 };
}
this.buckets.set(key, bucket);
const missingTokens = cost - bucket.tokens;
const retryAfterMs = this.config.ratePerSecond > 0
? Math.ceil((missingTokens / this.config.ratePerSecond) * 1000)
: Number.POSITIVE_INFINITY;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Zero rate emits invalid Retry-After

Low Severity

When ratePerSecond is 0, consume returns retryAfterMs of Infinity. The receiver then sends retry-after: Infinity, which is not a valid delay-seconds value, and JSON.stringify turns retryAfterMs into null. The HTTP rate-limit test uses this configuration, so clients lose a usable retry hint.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4fe4f6e. Configure here.

return { allowed: false, retryAfterMs };
}

/** Test/inspection helper — production code should only call {@link consume}. */
size(): number {
return this.buckets.size;
}
}

export function keyFor(
provider: string | undefined,
name: string,
sourceAddress: string,
): string {
return `${provider ?? 'raw'}:${name}:${sourceAddress}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When a generic /raw request and a /providers/raw request share a source, keyFor gives them the same bucket. Encode the tuple without using a sentinel string that can also be a provider name.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/sdk/src/webhook-rate-limit.ts, line 68:

<comment>When a generic `/raw` request and a `/providers/raw` request share a source, `keyFor` gives them the same bucket. Encode the tuple without using a sentinel string that can also be a provider name.</comment>

<file context>
@@ -0,0 +1,69 @@
+  name: string,
+  sourceAddress: string,
+): string {
+  return `${provider ?? 'raw'}:${name}:${sourceAddress}`;
+}
</file context>
Suggested change
return `${provider ?? 'raw'}:${name}:${sourceAddress}`;
return JSON.stringify([provider ?? null, name, sourceAddress]);

}
74 changes: 74 additions & 0 deletions packages/sdk/src/webhook-signature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { createHmac, timingSafeEqual } from 'node:crypto';

/**
* Per-provider HMAC signature schemes for webhook payload authentication (#304).
*
* The receiver only invokes verification when a secret is configured for the
* provider (via `env[WEBHOOK_SECRET_<PROVIDER>]`). When no secret is set the
* receiver runs unsigned, matching the initial loopback-only development mode
* documented in #301. Callers deploying to public ingress MUST set the secret.
*/
export type SignatureScheme = {
header: string;
compute(rawBody: Buffer, secret: string): string;
};

const HEX = /^[0-9a-f]+$/i;

const github: SignatureScheme = {
header: 'x-hub-signature-256',
compute(rawBody, secret) {
return 'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex');
},
};

const slack: SignatureScheme = {
header: 'x-slack-signature',
compute(rawBody, secret) {
// Slack's v0 scheme is HMAC(SHA256, secret) over `v0:{ts}:{body}`; a
// deployment that wants Slack signature verification must set the secret
// to include the timestamp prefix or use provider-specific integration.
return 'v0=' + createHmac('sha256', secret).update(rawBody).digest('hex');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When WEBHOOK_SECRET_SLACK is configured, valid Slack signatures are rejected because slack.compute omits Slack’s per-request timestamp. Read X-Slack-Request-Timestamp and verify v0:{timestamp}:{rawBody} (including replay-age validation), or remove Slack from SIGNATURE_SCHEMES until that integration exists.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/sdk/src/webhook-signature.ts, line 31:

<comment>When `WEBHOOK_SECRET_SLACK` is configured, valid Slack signatures are rejected because `slack.compute` omits Slack’s per-request timestamp. Read `X-Slack-Request-Timestamp` and verify `v0:{timestamp}:{rawBody}` (including replay-age validation), or remove Slack from `SIGNATURE_SCHEMES` until that integration exists.</comment>

<file context>
@@ -0,0 +1,74 @@
+    // Slack's v0 scheme is HMAC(SHA256, secret) over `v0:{ts}:{body}`; a
+    // deployment that wants Slack signature verification must set the secret
+    // to include the timestamp prefix or use provider-specific integration.
+    return 'v0=' + createHmac('sha256', secret).update(rawBody).digest('hex');
+  },
+};
</file context>

},
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slack signature scheme is incorrect

Medium Severity

The slack scheme is registered in SIGNATURE_SCHEMES, so WEBHOOK_SECRET_SLACK selects it, but compute HMACs only the raw body and never reads x-slack-request-timestamp. Slack signs v0:{timestamp}:{body}, so enabling that secret rejects real Slack deliveries. Putting the timestamp into the static secret cannot work because the timestamp changes per request.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4fe4f6e. Configure here.


const generic: SignatureScheme = {
header: 'x-flows-signature-256',
compute(rawBody, secret) {
return 'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex');
},
};

export const SIGNATURE_SCHEMES: Record<string, SignatureScheme> = {
github,
slack,
};

export function schemeFor(provider: string | undefined): SignatureScheme {
if (provider && Object.hasOwn(SIGNATURE_SCHEMES, provider)) {
return SIGNATURE_SCHEMES[provider]!;
}
return generic;
}

/** Constant-time verification of a hex-encoded signature against the expected. */
export function verifySignature(
provider: string | undefined,
rawBody: Buffer,
headerValue: string | undefined,
secret: string,
): { ok: true } | { ok: false; reason: 'missing' | 'malformed' | 'mismatch' } {
const scheme = schemeFor(provider);
const supplied = headerValue?.trim();
if (!supplied) return { ok: false, reason: 'missing' };
const expected = scheme.compute(rawBody, secret);
if (supplied.length !== expected.length) return { ok: false, reason: 'malformed' };
const [suppliedHex, expectedHex] = [supplied.replace(/^[^=]+=/, ''), expected.replace(/^[^=]+=/, '')];
if (!HEX.test(suppliedHex) || suppliedHex.length !== expectedHex.length) {
return { ok: false, reason: 'malformed' };
}
const suppliedBytes = Buffer.from(suppliedHex, 'hex');
const expectedBytes = Buffer.from(expectedHex, 'hex');
if (suppliedBytes.length !== expectedBytes.length) return { ok: false, reason: 'malformed' };
return timingSafeEqual(suppliedBytes, expectedBytes) ? { ok: true } : { ok: false, reason: 'mismatch' };
}
Loading
Loading