:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(agent-platform): hmac_sha256 scheme for shared_secret webhook auth (#72055)
Tom Piccirello29b6994572ff
diff --git a/products/agent_platform/services/agent-ingress/AGENTS.md b/products/agent_platform/services/agent-ingress/AGENTS.mdindex 9b06bb105cec..4a1240164a4e 100644--- a/products/agent_platform/services/agent-ingress/AGENTS.md+++ b/products/agent_platform/services/agent-ingress/AGENTS.md@@ -72,6 +72,14 @@ for the wider dev flow before non-trivial changes.| PostHog backend → ingress server-to-server | `posthog_internal` | The platform itself || Genuinely public surface (docs embed, marketing) | `public` | Anonymous — opt-in via `acknowledge_public_exposure` |+ `shared_secret` accepts two possession proofs, picked by `scheme`:+ omitted/`plain` compares the header value to the secret verbatim+ (incident.io, Grafana — anything that can echo a configured header);+ `scheme: 'hmac_sha256'` expects hex `HMAC-SHA256(raw body, secret)`+ in the header (`signature_prefix` default `sha256=`) for signers that+ never transmit the secret itself — GitHub's `X-Hub-Signature-256` and+ most webhook providers. Same single-principal trust model either way.+**`shared_secret` is single-principal by design.** Holders of theagent's secret share a session space; `x-external-key` is a routingtag, not a credential, and `principalsMatch` discriminates only ondiff --git a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.tsindex 5cc95b793d81..553602c499ac 100644--- a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts+++ b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts@@ -6,6 +6,7 @@*/import type { Request } from 'express'+import { createHmac } from 'node:crypto'import { describe, expect, it } from 'vitest'import { AgentApplication, AgentRevision, AuthModeSchema } from '@posthog/agent-shared'@@ -83,6 +84,14 @@ const secretResolver = { resolve: async (key: string): Promise<string | null> =>const req = (headers: Record<string, string>): Request => ({ headers }) as unknown as Request+/** Request carrying the raw body the express json verify hook captures — the+ * hmac scheme hashes `rawBodyBytes` (the exact bytes signed). Accepts a Buffer+ * so tests can exercise non-UTF-8 payloads. */+const signedReq = (headers: Record<string, string>, rawBody: string | Buffer): Request => {+ const bytes = typeof rawBody === 'string' ? Buffer.from(rawBody) : rawBody+ return { headers, rawBody: bytes.toString('utf-8'), rawBodyBytes: bytes } as unknown as Request+}+const allVerifiers = (): ReturnType<typeof buildDefaultVerifiers> =>buildDefaultVerifiers({introspector,@@ -171,6 +180,96 @@ describe('buildDefaultVerifiers', () => {expect(await v.verify(req({}), mode, APP, REV)).toMatchObject({ ok: false, status: 0 })})+ it('shared_secret hmac_sha256: verifies a GitHub-style signature over the raw body', async () => {+ const v = sharedSecretVerifier(secretResolver)+ const mode = {+ type: 'shared_secret' as const,+ header: 'X-Hub-Signature-256',+ secret_ref: 'WH',+ scheme: 'hmac_sha256' as const,+ }+ const body = '{"action":"review_requested","installation":{"id":42}}'+ const sig = `sha256=${createHmac('sha256', 's3cret').update(body).digest('hex')}`++ const good = await v.verify(signedReq({ 'x-hub-signature-256': sig }, body), mode, APP, REV)+ expect(good).toMatchObject({ ok: true })+ if (good.ok) {+ expect(good.principal).toEqual({ kind: 'shared_secret', team_id: 7 })+ }++ // A signature over different bytes (or with the wrong secret) is a 401 —+ // the raw secret value in the header must NOT pass in this scheme.+ expect(+ await v.verify(signedReq({ 'x-hub-signature-256': sig }, '{"tampered":true}'), mode, APP, REV)+ ).toMatchObject({ ok: false, status: 401 })+ expect(await v.verify(signedReq({ 'x-hub-signature-256': 's3cret' }, body), mode, APP, REV)).toMatchObject({+ ok: false,+ status: 401,+ })+ // No header → skip so the next mode can try; unresolvable secret → fail closed.+ expect(await v.verify(signedReq({}, body), mode, APP, REV)).toMatchObject({ ok: false, status: 0 })+ expect(+ await v.verify(+ signedReq({ 'x-hub-signature-256': sig }, body),+ { ...mode, secret_ref: 'MISSING' },+ APP,+ REV+ )+ ).toMatchObject({ ok: false, status: 500 })+ })++ it('shared_secret hmac_sha256: honors a custom signature_prefix', async () => {+ const v = sharedSecretVerifier(secretResolver)+ const mode = {+ type: 'shared_secret' as const,+ header: 'X-Sig',+ secret_ref: 'WH',+ scheme: 'hmac_sha256' as const,+ signature_prefix: '',+ }+ const body = '{"ping":true}'+ const bare = createHmac('sha256', 's3cret').update(body).digest('hex')+ expect(await v.verify(signedReq({ 'x-sig': bare }, body), mode, APP, REV)).toMatchObject({ ok: true })+ // The GitHub-style default prefix is not accepted once overridden.+ expect(await v.verify(signedReq({ 'x-sig': `sha256=${bare}` }, body), mode, APP, REV)).toMatchObject({+ ok: false,+ status: 401,+ })+ })++ it('shared_secret hmac_sha256: fails loudly (500) when the raw body was never captured', async () => {+ // A route that reached the verifier without the express raw-body hook+ // must not hash '' and 401 every valid signature — that reads as a+ // customer credential problem instead of the server misconfig it is.+ const v = sharedSecretVerifier(secretResolver)+ const mode = {+ type: 'shared_secret' as const,+ header: 'X-Hub-Signature-256',+ secret_ref: 'WH',+ scheme: 'hmac_sha256' as const,+ }+ const noCapture = { headers: { 'x-hub-signature-256': 'sha256=deadbeef' } } as unknown as Request+ expect(await v.verify(noCapture, mode, APP, REV)).toMatchObject({ ok: false, status: 500 })+ })++ it('shared_secret hmac_sha256: hashes the raw bytes, not a UTF-8 re-decode', async () => {+ // A payload with a non-UTF-8 byte (0xff) round-trips losslessly only if+ // we hash the bytes; hashing buf.toString('utf-8') would replace it with+ // U+FFFD and never match the sender's signature.+ const v = sharedSecretVerifier(secretResolver)+ const mode = {+ type: 'shared_secret' as const,+ header: 'X-Hub-Signature-256',+ secret_ref: 'WH',+ scheme: 'hmac_sha256' as const,+ }+ const rawBytes = Buffer.from([0x7b, 0x22, 0x78, 0x22, 0x3a, 0xff, 0x7d]) // {"x":<0xff>}+ const sig = `sha256=${createHmac('sha256', 's3cret').update(rawBytes).digest('hex')}`+ expect(await v.verify(signedReq({ 'x-hub-signature-256': sig }, rawBytes), mode, APP, REV)).toMatchObject({+ ok: true,+ })+ })+it('shared_secret: yields a single team-scoped principal (no per-caller discriminator)', async () => {// One secret == one trust principal. Any holder of the agent's secret// is the same principal; per-caller isolation belongs to `jwt`.diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.tsindex 9c1f131bb5e2..073a56c2615a 100644--- a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts+++ b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts@@ -314,7 +314,26 @@ export function sharedSecretVerifier(resolver: SecretResolver): AuthVerifier {if (!expected) {return { ok: false, status: 500, reason: 'shared_secret_not_set' }}- if (!secretsMatch(provided, expected)) {+ if (mode.scheme === 'hmac_sha256') {+ // The header carries a signature over the raw body, not the+ // secret — signers like GitHub never transmit the secret itself.+ const prefix = mode.signature_prefix ?? 'sha256='+ if (!provided.startsWith(prefix)) {+ return { ok: false, status: 401, reason: 'malformed_signature' }+ }+ // Hash the exact bytes the sender signed. A missing capture is a+ // server misconfiguration (a route reached here without the+ // raw-body hook), not a bad credential — fail loudly rather than+ // hashing '' and rejecting every legitimate delivery as a 401.+ const rawBody = (req as Request & { rawBodyBytes?: Buffer }).rawBodyBytes+ if (rawBody === undefined) {+ return { ok: false, status: 500, reason: 'raw_body_unavailable' }+ }+ const digest = createHmac('sha256', expected).update(rawBody).digest('hex')+ if (!secretsMatch(provided.slice(prefix.length).toLowerCase(), digest)) {+ return { ok: false, status: 401, reason: 'invalid_signature' }+ }+ } else if (!secretsMatch(provided, expected)) {return { ok: false, status: 401, reason: 'invalid_secret' }}const principal: SessionPrincipal = { kind: 'shared_secret', team_id: application.team_id }diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.tsindex 644daca35bc0..3ecb02545ab3 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts@@ -269,7 +269,13 @@ export function buildApp(opts: BuildAppOpts): Express {app.use(express.json({verify: (req: Request, _res, buf) => {- ;(req as Request & { rawBody?: string }).rawBody = buf.toString('utf-8')+ const r = req as Request & { rawBody?: string; rawBodyBytes?: Buffer }+ // Keep both: `rawBody` (string) for consumers that hash text+ // (Slack), and `rawBodyBytes` for signature schemes that must+ // hash the exact bytes the sender signed (a UTF-8 re-decode is+ // lossy for non-UTF-8 payloads).+ r.rawBody = buf.toString('utf-8')+ r.rawBodyBytes = buf},}))@@ -280,7 +286,13 @@ export function buildApp(opts: BuildAppOpts): Express {express.urlencoded({extended: false,verify: (req: Request, _res, buf) => {- ;(req as Request & { rawBody?: string }).rawBody = buf.toString('utf-8')+ const r = req as Request & { rawBody?: string; rawBodyBytes?: Buffer }+ // Keep both: `rawBody` (string) for consumers that hash text+ // (Slack), and `rawBodyBytes` for signature schemes that must+ // hash the exact bytes the sender signed (a UTF-8 re-decode is+ // lossy for non-UTF-8 payloads).+ r.rawBody = buf.toString('utf-8')+ r.rawBodyBytes = buf},}))diff --git a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts b/products/agent_platform/services/agent-ingress/src/triggers/webhook.tsindex cb3705e4e44e..d1121af0c10b 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts@@ -11,7 +11,7 @@ import { Request } from 'express'import { createHash } from 'node:crypto'import type { z } from 'zod'-import { TRIGGER_ROUTES } from '@posthog/agent-shared'+import { type Trigger, TRIGGER_ROUTES } from '@posthog/agent-shared'import { principalDisplay } from '../enqueue/acl'import { enqueueOrResume } from '../enqueue/enqueue'@@ -28,7 +28,8 @@ async function webhookHandler(ctx: AuthedRouteCtx<z.infer<typeof WebhookBodyScheconst body = ctx.parsedconst externalKeyHeader = req.headers['x-external-key']const externalKey = typeof externalKeyHeader === 'string' ? externalKeyHeader : null- const idempotencyKey = extractProviderIdempotencyKey(req, body)+ const trigger = resolved.revision.spec.triggers.find((t) => t.type === 'webhook')+ const idempotencyKey = extractIdempotencyKey(req, body, trigger)const sessionPrincipal = ctx.principalconst outcome = await enqueueOrResume({ queue: deps.queue },@@ -97,6 +98,31 @@ function extractProviderIdempotencyKey(req: Request, parsedBody: unknown): strinreturn undefined}+/**+ * Prefer the verified HMAC signature as the dedup key when the trigger uses an+ * `hmac_sha256` auth mode. The signature is an unforgeable function of the body+ * (the mount guard already verified it before this handler ran), so a replay+ * that resends the same signed body under a fresh `X-GitHub-Delivery` — which+ * is NOT part of the signed content — still collapses to one session, closing+ * the signature-covers-body-only replay window. Falls back to the+ * provider-header key for unsigned deliveries (Stripe id, GitHub delivery, …),+ * whose header+body-digest form defends the separate pre-emption spoof.+ */+function extractIdempotencyKey(req: Request, parsedBody: unknown, trigger: Trigger | undefined): string | undefined {+ if (trigger?.type === 'webhook') {+ for (const mode of trigger.auth.modes) {+ if (mode.type === 'shared_secret' && mode.scheme === 'hmac_sha256') {+ const v = req.headers[mode.header.toLowerCase()]+ const sig = typeof v === 'string' ? v : Array.isArray(v) ? v[0] : undefined+ if (sig && sig.length > 0) {+ return `webhook:sig:${sig}`+ }+ }+ }+ }+ return extractProviderIdempotencyKey(req, parsedBody)+}+/** The published `bodySchema` is intentionally loose — webhook accepts any* JSON object, and the agent's `agent.md` defines what the *content* of that* object should look like. We do reject null / non-object bodies at the edgediff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex 74ac49efa311..eb6aeb270ff1 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -94,6 +94,18 @@ export const AuthModeSchema = z.discriminatedUnion('type', [type: z.literal('shared_secret'),header: z.string().min(1),secret_ref: z.string().min(1),+ /** How the header proves possession of the secret:+ * - omitted / `plain`: the header carries the secret verbatim.+ * - `hmac_sha256`: the header carries hex `HMAC-SHA256(raw request+ * body, secret)` — for signers that never send the secret itself+ * (GitHub's `X-Hub-Signature-256`, and most webhook providers).+ * Same trust model either way: possession of the one secret == the+ * one principal. */+ scheme: z.enum(['plain', 'hmac_sha256']).optional(),+ /** `hmac_sha256` only: prefix expected before the hex digest in the+ * header value. Defaults to GitHub's `sha256=`; set `''` for signers+ * that send the bare digest. */+ signature_prefix: z.string().optional(),}),/** PostHog-internal server-to-server token (for Django ↔ ingress). */z.object({ type: z.literal('posthog_internal') }),diff --git a/products/agent_platform/services/agent-tests/src/cases/auth.test.ts b/products/agent_platform/services/agent-tests/src/cases/auth.test.tsindex 5e14147d619e..aad050d310d4 100644--- a/products/agent_platform/services/agent-tests/src/cases/auth.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/auth.test.ts@@ -4,9 +4,12 @@* Old equivalent: isolated/auth.test.ts (all 9 cases).*/+import { createHmac } from 'node:crypto'import request from 'supertest'-import { buildCluster, closeSharedPool, Cluster, fakeAuthProvider } from '../harness'+import { sharedSecretVerifier } from '@posthog/agent-ingress'++import { buildCluster, closeSharedPool, Cluster, fakeAuthProvider, fauxText } from '../harness'const KNOWN_PAT = 'phx_abc123def456'const KNOWN_INTERNAL_SECRET = 'internal-secret-xyz'@@ -140,4 +143,112 @@ describe('trigger auth: real e2e', () => {expect(res.status).toBe(401)})})++ describe('shared_secret scheme hmac_sha256 (real verifier)', () => {+ // Runs the REAL sharedSecretVerifier through the real /webhook route so+ // the express `rawBody` capture is on the hook: the signature is over+ // the exact request bytes, which no unit test can prove end to end.+ it('webhook: GitHub-style signature over the raw body → 200; tampered body → 401', async () => {+ const hc = await buildCluster({+ authProvider: {+ verifiers: [+ sharedSecretVerifier({+ resolve: async (ref: string) => (ref === 'GITHUB_WEBHOOK_SECRET' ? 'wh-secret-1' : null),+ }),+ ],+ },+ })+ try {+ hc.setScript([fauxText('ack')])+ await hc.deployAgent({+ slug: 'wh-hmac',+ spec: {+ auth: {+ modes: [+ {+ type: 'shared_secret',+ header: 'X-Hub-Signature-256',+ secret_ref: 'GITHUB_WEBHOOK_SECRET',+ scheme: 'hmac_sha256',+ },+ ],+ },+ },+ })+ const body = { action: 'review_requested', installation: { id: 42 } }+ const sig = `sha256=${createHmac('sha256', 'wh-secret-1').update(JSON.stringify(body)).digest('hex')}`+ const ok = await request(hc.ingress)+ .post('/agents/wh-hmac/webhook')+ .set('X-Hub-Signature-256', sig)+ .send(body)+ expect(ok.status).toBe(200)+ // Same signature over different bytes — and the raw secret in+ // the header — must both fail.+ const tampered = await request(hc.ingress)+ .post('/agents/wh-hmac/webhook')+ .set('X-Hub-Signature-256', sig)+ .send({ ...body, tampered: true })+ expect(tampered.status).toBe(401)+ const rawSecret = await request(hc.ingress)+ .post('/agents/wh-hmac/webhook')+ .set('X-Hub-Signature-256', 'wh-secret-1')+ .send(body)+ expect(rawSecret.status).toBe(401)+ } finally {+ await hc.teardown()+ }+ })++ it('collapses a replay of the same signed body under a fresh delivery id', async () => {+ // GitHub signs only the body (no timestamp), so a captured signed+ // request could be resent with a new X-GitHub-Delivery to dodge the+ // delivery-id dedup. Keying idempotency on the signature (bound to+ // the body) makes the replay collapse to the original session.+ const hc = await buildCluster({+ authProvider: {+ verifiers: [+ sharedSecretVerifier({+ resolve: async (ref: string) => (ref === 'GITHUB_WEBHOOK_SECRET' ? 'wh-secret-1' : null),+ }),+ ],+ },+ })+ try {+ hc.setScript([fauxText('ack'), fauxText('ack')])+ await hc.deployAgent({+ slug: 'wh-replay',+ spec: {+ auth: {+ modes: [+ {+ type: 'shared_secret',+ header: 'X-Hub-Signature-256',+ secret_ref: 'GITHUB_WEBHOOK_SECRET',+ scheme: 'hmac_sha256',+ },+ ],+ },+ },+ })+ const body = { action: 'review_requested', installation: { id: 42 } }+ const sig = `sha256=${createHmac('sha256', 'wh-secret-1').update(JSON.stringify(body)).digest('hex')}`+ const first = await request(hc.ingress)+ .post('/agents/wh-replay/webhook')+ .set('X-Hub-Signature-256', sig)+ .set('X-GitHub-Delivery', 'delivery-1')+ .send(body)+ const replay = await request(hc.ingress)+ .post('/agents/wh-replay/webhook')+ .set('X-Hub-Signature-256', sig)+ .set('X-GitHub-Delivery', 'delivery-2')+ .send(body)+ expect(first.status).toBe(200)+ expect(replay.status).toBe(200)+ // Same signed body → same session despite the different delivery id.+ expect(replay.body.session_id).toBe(first.body.session_id)+ } finally {+ await hc.teardown()+ }+ })+ })})