diff --git a/packages/sdk/src/cli/serve-webhook.ts b/packages/sdk/src/cli/serve-webhook.ts index 5d24c945e..3f156f765 100644 --- a/packages/sdk/src/cli/serve-webhook.ts +++ b/packages/sdk/src/cli/serve-webhook.ts @@ -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 { @@ -44,21 +48,45 @@ function reply(response: ServerResponse, status: number, body: object): void { } /** - * POST / accepts JSON; /providers/ 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_` (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; + /** Optional rate limit config; defaults to 20/s with 60 burst per key. */ + rateLimit?: RateLimitConfig; + /** Injectable env lookup for tests. */ + env?: NodeJS.ProcessEnv; +} + +/** POST / accepts JSON; /providers/ accepts typed event envelopes. */ export async function startWebhookServer( - dataDir: string, port: number, options: { admittedNames?: ReadonlySet } = {}, + dataDir: string, + port: number, + options: WebhookServerOptions = {}, ): Promise { 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) => { @@ -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 }); + return; + } let temporary: string | undefined; try { let bytes = 0; @@ -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; }); @@ -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; } diff --git a/packages/sdk/src/webhook-rate-limit.ts b/packages/sdk/src/webhook-rate-limit.ts new file mode 100644 index 000000000..fc9c4252d --- /dev/null +++ b/packages/sdk/src/webhook-rate-limit.ts @@ -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(); + + constructor( + 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'); + } + } + + 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; + 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}`; +} diff --git a/packages/sdk/src/webhook-signature.ts b/packages/sdk/src/webhook-signature.ts new file mode 100644 index 000000000..05296336e --- /dev/null +++ b/packages/sdk/src/webhook-signature.ts @@ -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_]`). 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'); + }, +}; + +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 = { + 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' }; +} diff --git a/packages/sdk/tests/webhook-hardening.test.ts b/packages/sdk/tests/webhook-hardening.test.ts new file mode 100644 index 000000000..56d5f91b3 --- /dev/null +++ b/packages/sdk/tests/webhook-hardening.test.ts @@ -0,0 +1,144 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { createHmac } from 'node:crypto'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { Server } from 'node:http'; +import { startWebhookServer } from '../src/cli/serve-webhook.js'; +import { TokenBucketLimiter, keyFor } from '../src/webhook-rate-limit.js'; +import { verifySignature, schemeFor } from '../src/webhook-signature.js'; + +const dirs: string[] = []; +const servers: Server[] = []; +afterEach(async () => { + for (const server of servers.splice(0)) await new Promise(done => { + server.close(() => done()); server.closeAllConnections(); + }); + await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))); +}); +async function temporary(): Promise { + const dir = await mkdtemp(join(tmpdir(), 'flows-webhook-hardening-')); + dirs.push(dir); return dir; +} +async function receiverWith(dir: string, env: NodeJS.ProcessEnv = {}, rateLimit = { ratePerSecond: 20, burst: 60 }): Promise { + const server = await startWebhookServer(dir, 0, { env, rateLimit }); + servers.push(server); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + return `http://127.0.0.1:${address.port}`; +} + +describe('webhook receiver hardening (#304)', () => { + it('refuses github signatures that do not match the configured secret', async () => { + const dir = await temporary(); + const base = await receiverWith(dir, { WEBHOOK_SECRET_GITHUB: 'topsecret' }); + const body = JSON.stringify({ type: 'pull_request', payload: { action: 'opened', number: 1 } }); + const wrong = 'sha256=' + createHmac('sha256', 'notmysecret').update(body).digest('hex'); + const response = await fetch(`${base}/providers/github`, { + method: 'POST', body, + headers: { 'content-type': 'application/json', 'x-hub-signature-256': wrong }, + }); + expect(response.status).toBe(401); + const parsed = await response.json() as { error: string; reason: string }; + expect(parsed).toMatchObject({ error: 'webhook_signature_invalid' }); + expect(['missing', 'mismatch', 'malformed']).toContain(parsed.reason); + }); + + it('accepts a correctly-signed github payload when the secret is configured', async () => { + const dir = await temporary(); + const secret = 'shared-secret'; + const base = await receiverWith(dir, { WEBHOOK_SECRET_GITHUB: secret }); + const body = JSON.stringify({ type: 'pull_request', payload: { action: 'opened', number: 2 } }); + const signature = 'sha256=' + createHmac('sha256', secret).update(body).digest('hex'); + const response = await fetch(`${base}/providers/github`, { + method: 'POST', body, + headers: { 'content-type': 'application/json', 'x-hub-signature-256': signature }, + }); + expect(response.status).toBe(202); + }); + + it('refuses when the signature header is missing but a secret is configured', async () => { + const dir = await temporary(); + const base = await receiverWith(dir, { WEBHOOK_SECRET_GITHUB: 'topsecret' }); + const body = JSON.stringify({ type: 'pull_request', payload: { action: 'opened', number: 3 } }); + const response = await fetch(`${base}/providers/github`, { + method: 'POST', body, headers: { 'content-type': 'application/json' }, + }); + expect(response.status).toBe(401); + const parsed = await response.json() as { error: string; reason: string }; + expect(parsed).toEqual({ error: 'webhook_signature_invalid', reason: 'missing' }); + }); + + it('runs unsigned when no secret is configured (loopback development mode)', async () => { + const dir = await temporary(); + const base = await receiverWith(dir, {}); + const body = JSON.stringify({ type: 'pull_request', payload: { action: 'opened', number: 4 } }); + const response = await fetch(`${base}/providers/github`, { + method: 'POST', body, headers: { 'content-type': 'application/json' }, + }); + expect(response.status).toBe(202); + }); + + it('rate-limits when burst is exhausted and returns Retry-After', async () => { + const dir = await temporary(); + const base = await receiverWith(dir, {}, { ratePerSecond: 0, burst: 2 }); + const body = JSON.stringify({ type: 'pull_request', payload: { action: 'opened', number: 5 } }); + const post = () => fetch(`${base}/providers/github`, { + method: 'POST', body, headers: { 'content-type': 'application/json' }, + }); + expect((await post()).status).toBe(202); + expect((await post()).status).toBe(202); + const limited = await post(); + expect(limited.status).toBe(429); + expect(limited.headers.get('retry-after')).toBeTruthy(); + expect(await limited.json()).toMatchObject({ error: 'webhook_rate_limited' }); + }); + + it('refuses provider payloads that do not match the declared shape', async () => { + const dir = await temporary(); + const base = await receiverWith(dir, {}); + const bad = JSON.stringify({ type: 'not_a_real_event', payload: {} }); + const response = await fetch(`${base}/providers/github`, { + method: 'POST', body: bad, headers: { 'content-type': 'application/json' }, + }); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ error: 'webhook_payload_invalid' }); + }); +}); + +describe('webhook-signature helpers', () => { + it('rejects a missing supplied header as `missing`', () => { + expect(verifySignature('github', Buffer.from('x'), undefined, 'secret')).toEqual({ ok: false, reason: 'missing' }); + expect(verifySignature('github', Buffer.from('x'), '', 'secret')).toEqual({ ok: false, reason: 'missing' }); + }); + it('rejects malformed headers as `malformed`', () => { + expect(verifySignature('github', Buffer.from('x'), 'sha256=zz', 'secret')).toMatchObject({ ok: false }); + }); + it('accepts a correctly-signed payload', () => { + const body = Buffer.from('hello'); + const scheme = schemeFor('github'); + const good = scheme.compute(body, 'secret'); + expect(verifySignature('github', body, good, 'secret')).toEqual({ ok: true }); + }); +}); + +describe('token-bucket rate limiter', () => { + it('allows up to burst then refuses; refills over time', () => { + let now = 1_000_000; + const limiter = new TokenBucketLimiter({ ratePerSecond: 1, burst: 3 }, () => now); + for (let i = 0; i < 3; i += 1) { + expect(limiter.consume('k').allowed).toBe(true); + } + expect(limiter.consume('k')).toEqual({ allowed: false, retryAfterMs: 1000 }); + now += 2000; + expect(limiter.consume('k').allowed).toBe(true); + expect(limiter.consume('k').allowed).toBe(true); + }); + + it('keys independently per (provider, name, source)', () => { + const limiter = new TokenBucketLimiter({ ratePerSecond: 0, burst: 1 }); + expect(limiter.consume(keyFor('github', 'pr', '10.0.0.1')).allowed).toBe(true); + expect(limiter.consume(keyFor('github', 'pr', '10.0.0.1')).allowed).toBe(false); + expect(limiter.consume(keyFor('github', 'pr', '10.0.0.2')).allowed).toBe(true); + }); +}); diff --git a/packages/sdk/tsconfig.tests.json b/packages/sdk/tsconfig.tests.json index c4f9bd44d..f0fa6bf29 100644 --- a/packages/sdk/tsconfig.tests.json +++ b/packages/sdk/tsconfig.tests.json @@ -35,7 +35,8 @@ "tests/build-gate.test.ts", "tests/scope-preflight.test.ts", "tests/worker-cli-cwd.test.ts", - "tests/agent-relay-transport.test.ts" + "tests/agent-relay-transport.test.ts", + "tests/webhook-hardening.test.ts" ], "exclude": ["node_modules", "dist"] }