Skip to content

: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.

feat(ai-research): sign image fetch requests with web bot auth (#85231)

Robbie5c87d08fd070
diff --git a/docs/internal/web-bot-auth-key-directory.md b/docs/internal/web-bot-auth-key-directory.md
index a5429af271e5..11f7790ddb2e 100644
--- a/docs/internal/web-bot-auth-key-directory.md
+++ b/docs/internal/web-bot-auth-key-directory.md
@@ -7,7 +7,9 @@ The directory publishes the public keys for `PostHogSessionReplayBot` and signs
Set `WEB_BOT_AUTH_PRIVATE_KEYS` to a comma-separated list of unencrypted Ed25519 private keys in PKCS8 PEM format.
Encode PEM line breaks as literal `\n` sequences when the secret store requires a single-line value.
-During key rotation, include the old and new keys until consumers have accepted the new key.
+List the active outbound signing key first.
+During key rotation, add the new key after the active key so that the directory publishes both keys.
+Move the new key to the first position after consumers have accepted it, then remove the old key.
Leave the variable unset outside PostHog Cloud US.
The endpoint returns `404` when the variable is unset or the deployment is not in the US region.
@@ -15,3 +17,13 @@ The endpoint returns `404` when the variable is unset or the deployment is not i
When the variable is present, each production ASGI worker schedules validation on a daemon thread during lifespan startup.
An empty or invalid value does not stop startup.
PostHog Error Tracking receives a sanitized configuration error, and the endpoint returns `503` without exposing key material.
+
+## Outbound request signing
+
+The Node.js image fetch lane validates every configured key and signs each outbound request with the first key.
+It signs each redirect hop for the GET method, authority, full target URI, and `Signature-Agent` header.
+This prevents use of the signature for another method, path, or query.
+The signatures expire after one minute and include a unique 64-byte nonce.
+
+The request uses the structured-string `Signature-Agent` format in [Cloudflare's current verifier](https://developers.cloudflare.com/bots/reference/bot-verification/web-bot-auth/).
+It includes the parameters required by the [current Web Bot Auth protocol draft](https://datatracker.ietf.org/doc/draft-meunier-webbotauth-httpsig-protocol/).
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
index 1ba9635f0632..cfb97f27df3b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
@@ -1,6 +1,7 @@
import { ResolutionError, SecureRequestError, StreamedResponse, fetchStreamed } from '~/common/utils/request'
import { HttpImageFetcher, ImageFetchOptions, RedirectPolicy } from './image-fetcher'
+import { WebBotAuthRequestSigner } from './web-bot-auth'
jest.mock('~/common/utils/request', () => ({
...jest.requireActual('~/common/utils/request'),
@@ -37,9 +38,13 @@ function image(bytes: Buffer, contentType: string, extraHeaders: Record<string,
return respond(200, { 'content-type': contentType, ...extraHeaders }, { bytes, overLimit: false })
}
+const NOOP_SIGNER: WebBotAuthRequestSigner = { headersForGet: () => ({}) }
/** Everything public by default, so a test that cares about the policy says so. */
-const fetcher = (policy: Partial<RedirectPolicy> = {}): HttpImageFetcher =>
- new HttpImageFetcher({ maxUrlLength: 2048, isPublicHost: () => true, ...policy })
+const fetcher = (
+ policy: Partial<RedirectPolicy> = {},
+ webBotAuthSigner: WebBotAuthRequestSigner = NOOP_SIGNER
+): HttpImageFetcher =>
+ new HttpImageFetcher({ maxUrlLength: 2048, isPublicHost: () => true, ...policy }, webBotAuthSigner)
describe('HttpImageFetcher', () => {
beforeEach(() => {
@@ -129,6 +134,25 @@ describe('HttpImageFetcher', () => {
expect(fetchStreamedMock.mock.calls[1][0]).toBe('https://cdn.example.com/moved.png')
})
+ it('signs each redirect hop for its target URL', async () => {
+ fetchStreamedMock
+ .mockResolvedValueOnce(respond(302, { location: 'https://images.example.net/moved.png' }))
+ .mockResolvedValueOnce(image(PNG, 'image/png'))
+ const headersForGet = jest
+ .fn()
+ .mockReturnValueOnce({ signature: 'first-hop-signature' })
+ .mockReturnValueOnce({ signature: 'second-hop-signature' })
+
+ await fetcher({}, { headersForGet }).fetch('https://cdn.example.com/a.png', OPTIONS)
+
+ expect(headersForGet.mock.calls).toEqual([
+ ['https://cdn.example.com/a.png'],
+ ['https://images.example.net/moved.png'],
+ ])
+ expect(fetchStreamedMock.mock.calls[0][1].headers).toMatchObject({ signature: 'first-hop-signature' })
+ expect(fetchStreamedMock.mock.calls[1][1].headers).toMatchObject({ signature: 'second-hop-signature' })
+ })
+
it.each([
['the target is one this lane never follows', 'https://other.example/a.png', 'refuse' as const],
['it leaves HTTP for another scheme', 'javascript:alert(1)', 'allow' as const],
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
index 13a57b12335b..c6412fb293e2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
@@ -1,5 +1,7 @@
import { InvalidRequestError, ResolutionError, SecureRequestError, fetchStreamed } from '~/common/utils/request'
+import { WebBotAuthRequestSigner } from './web-bot-auth'
+
/**
* The raster set the anonymizer keeps on a collected ref, so a fetched image and an inline one reach
* the scrub lane as the same kind of thing.
@@ -88,15 +90,18 @@ const REQUEST_HEADERS: Record<string, string> = {
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
/**
- * This sends no credential of any kind: no cookie, no `Authorization`, and no `Referer`. This lane
- * must not reach an image behind a login, and a `Referer` would tell the origin which page of the
- * customer's site the image sat on.
+ * This sends no user credential: no cookie, no `Authorization`, and no `Referer`. This lane must not
+ * reach an image behind a login, and a `Referer` would tell the origin which page of the customer's
+ * site the image sat on. Web Bot Auth identifies PostHog as the operator of the request.
*
* Every refusal is an outcome rather than a throw. This runs inside a Kafka batch, one URL at a
* time, and a throw would abandon the URLs after it in the same batch.
*/
export class HttpImageFetcher implements ImageFetcher {
- constructor(private readonly policy: RedirectPolicy) {}
+ constructor(
+ private readonly policy: RedirectPolicy,
+ private readonly webBotAuthSigner: WebBotAuthRequestSigner
+ ) {}
public async fetch(url: string, options: ImageFetchOptions): Promise<ImageFetchResult> {
const deadlineMs = Date.now() + options.timeoutMs
@@ -149,7 +154,8 @@ export class HttpImageFetcher implements ImageFetcher {
}
private async hop(url: string, timeoutMs: number, maxBytes: number): Promise<HopResult> {
- const response = await fetchStreamed(url, { headers: REQUEST_HEADERS, timeoutMs })
+ const headers = { ...REQUEST_HEADERS, ...this.webBotAuthSigner.headersForGet(url) }
+ const response = await fetchStreamed(url, { headers, timeoutMs })
const status = response.status
if (REDIRECT_STATUSES.has(status)) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth.test.ts
new file mode 100644
index 000000000000..e9d212950ce2
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth.test.ts
@@ -0,0 +1,129 @@
+import { KeyObject, createHash, generateKeyPairSync, verify as verifySignature } from 'node:crypto'
+
+import { createWebBotAuthRequestSigner } from './web-bot-auth'
+
+const SIGNATURE_AGENT = '"https://us.posthog.com/.well-known/http-message-signatures-directory"'
+
+type TestKeyPair = {
+ privateKeyPem: string
+ publicKey: KeyObject
+}
+
+function generateEd25519KeyPair(): TestKeyPair {
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519')
+ return {
+ privateKeyPem: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
+ publicKey,
+ }
+}
+
+function keyId(publicKey: KeyObject): string {
+ const jwk = publicKey.export({ format: 'jwk' })
+ const canonicalJwk = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x })
+ return createHash('sha256').update(canonicalJwk).digest('base64url')
+}
+
+function expectSignedHeadersToVerify(
+ method: string,
+ url: string,
+ headers: Record<string, string>,
+ publicKey: KeyObject,
+ label: string,
+ expectedResult = true
+): void {
+ const signatureInput = headers['signature-input'].split(', ').find((member) => member.startsWith(`${label}=`))
+ const signature = headers.signature.split(', ').find((member) => member.startsWith(`${label}=`))
+ if (!signatureInput || !signature) {
+ throw new Error(`Missing ${label}`)
+ }
+
+ const parameters = signatureInput.slice(label.length + 1)
+ const parametersMatch = parameters.match(
+ /^\("@method" "@authority" "@target-uri" "signature-agent"\);created=(\d+);keyid="([^"]+)";alg="ed25519";expires=(\d+);nonce="([^"]+)";tag="web-bot-auth"$/
+ )
+ if (!parametersMatch) {
+ throw new Error(`Invalid ${label} parameters`)
+ }
+ const [, created, actualKeyId, expires, nonce] = parametersMatch
+ expect(actualKeyId).toBe(keyId(publicKey))
+ expect(Number(expires) - Number(created)).toBe(60)
+ expect(Buffer.from(nonce, 'base64url')).toHaveLength(64)
+
+ const targetUrl = new URL(url)
+ targetUrl.hash = ''
+ const signatureBase =
+ `"@method": ${method}\n` +
+ `"@authority": ${targetUrl.host}\n` +
+ `"@target-uri": ${targetUrl.toString()}\n` +
+ `"signature-agent": ${SIGNATURE_AGENT}\n` +
+ `"@signature-params": ${parameters}`
+ const signatureBytes = Buffer.from(signature.slice(`${label}=:`.length, -1), 'base64')
+ expect(verifySignature(null, Buffer.from(signatureBase), publicKey, signatureBytes)).toBe(expectedResult)
+}
+
+describe('Web Bot Auth request signing', () => {
+ beforeEach(() => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-08-19T08:00:00Z'))
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('creates a Cloudflare-compatible signature with current protocol parameters', () => {
+ const keyPair = generateEd25519KeyPair()
+ const signer = createWebBotAuthRequestSigner(keyPair.privateKeyPem)
+ const url = 'https://cdn.example.com/image.png?size=large'
+
+ const headers = signer.headersForGet(url)
+
+ expect(headers['signature-agent']).toBe(SIGNATURE_AGENT)
+ expectSignedHeadersToVerify('GET', url, headers, keyPair.publicKey, 'sig1')
+ })
+
+ it.each([
+ ['a different method', 'POST', 'https://cdn.example.com/image.png?size=large'],
+ ['a different path', 'GET', 'https://cdn.example.com/other.png?size=large'],
+ ['a different query', 'GET', 'https://cdn.example.com/image.png?size=small'],
+ ])('does not verify for %s', (_name, method, replayUrl) => {
+ const keyPair = generateEd25519KeyPair()
+ const signer = createWebBotAuthRequestSigner(keyPair.privateKeyPem)
+ const headers = signer.headersForGet('https://cdn.example.com/image.png?size=large')
+
+ expectSignedHeadersToVerify(method, replayUrl, headers, keyPair.publicKey, 'sig1', false)
+ })
+
+ it('signs with the first configured key during rotation', () => {
+ const firstKeyPair = generateEd25519KeyPair()
+ const secondKeyPair = generateEd25519KeyPair()
+ const signer = createWebBotAuthRequestSigner(
+ `${firstKeyPair.privateKeyPem},${secondKeyPair.privateKeyPem.replaceAll('\n', '\\n')}`
+ )
+ const url = 'https://cdn.example.com/image.png'
+
+ const headers = signer.headersForGet(url)
+
+ expectSignedHeadersToVerify('GET', url, headers, firstKeyPair.publicKey, 'sig1')
+ expect(headers['signature-input']).not.toContain(keyId(secondKeyPair.publicKey))
+ expect(headers.signature).not.toContain('sig2=')
+ })
+
+ it.each([
+ ['an empty value', '', 'must contain at least one'],
+ ['a malformed key', 'not a PEM', 'entry 1 could not be loaded'],
+ [
+ 'a malformed non-active key',
+ `${generateEd25519KeyPair().privateKeyPem},not a PEM`,
+ 'entry 2 could not be loaded',
+ ],
+ [
+ 'a non-Ed25519 key',
+ generateKeyPairSync('rsa', { modulusLength: 2048 })
+ .privateKey.export({ format: 'pem', type: 'pkcs8' })
+ .toString(),
+ 'entry 1 is not an Ed25519 private key',
+ ],
+ ])('rejects %s', (_name, privateKeyPems, expectedError) => {
+ expect(() => createWebBotAuthRequestSigner(privateKeyPems)).toThrow(expectedError)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth.ts
new file mode 100644
index 000000000000..b0c75b4128ed
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth.ts
@@ -0,0 +1,75 @@
+import { KeyObject, createHash, createPrivateKey, createPublicKey, randomBytes, sign } from 'node:crypto'
+
+const SIGNATURE_AGENT_URL = 'https://us.posthog.com/.well-known/http-message-signatures-directory'
+const SIGNATURE_AGENT_HEADER = JSON.stringify(SIGNATURE_AGENT_URL)
+const SIGNATURE_LIFETIME_SECONDS = 60
+const REQUEST_METHOD = 'GET'
+
+type SigningKey = {
+ privateKey: KeyObject
+ keyId: string
+}
+
+export interface WebBotAuthRequestSigner {
+ headersForGet(url: string): Record<string, string>
+}
+
+export function createWebBotAuthRequestSigner(commaSeparatedPrivateKeyPems: string): WebBotAuthRequestSigner {
+ const privateKeyPems = commaSeparatedPrivateKeyPems.split(',')
+ if (privateKeyPems.length === 1 && privateKeyPems[0].trim() === '') {
+ throw new Error('WEB_BOT_AUTH_PRIVATE_KEYS must contain at least one Ed25519 private key')
+ }
+
+ const signingKeys = privateKeyPems.map((privateKeyPem, index) => loadSigningKey(privateKeyPem, index + 1))
+ return new Ed25519WebBotAuthRequestSigner(signingKeys[0])
+}
+
+class Ed25519WebBotAuthRequestSigner implements WebBotAuthRequestSigner {
+ constructor(private readonly signingKey: SigningKey) {}
+
+ public headersForGet(url: string): Record<string, string> {
+ const targetUrl = new URL(url)
+ targetUrl.hash = ''
+ const authority = targetUrl.host
+ const targetUri = targetUrl.toString()
+ const created = Math.floor(Date.now() / 1000)
+ const expires = created + SIGNATURE_LIFETIME_SECONDS
+ const nonce = randomBytes(64).toString('base64url')
+ const parameters =
+ `("@method" "@authority" "@target-uri" "signature-agent");created=${created};keyid="${this.signingKey.keyId}";` +
+ `alg="ed25519";expires=${expires};nonce="${nonce}";tag="web-bot-auth"`
+ const signatureBase =
+ `"@method": ${REQUEST_METHOD}\n` +
+ `"@authority": ${authority}\n` +
+ `"@target-uri": ${targetUri}\n` +
+ `"signature-agent": ${SIGNATURE_AGENT_HEADER}\n` +
+ `"@signature-params": ${parameters}`
+
+ return {
+ // Cloudflare rejects the dictionary form from newer drafts, so use the compatible structured string.
+ 'signature-agent': SIGNATURE_AGENT_HEADER,
+ 'signature-input': `sig1=${parameters}`,
+ signature: `sig1=:${sign(null, Buffer.from(signatureBase), this.signingKey.privateKey).toString('base64')}:`,
+ }
+ }
+}
+
+function loadSigningKey(privateKeyPem: string, keyIndex: number): SigningKey {
+ let privateKey: KeyObject
+ try {
+ privateKey = createPrivateKey(privateKeyPem.trim().replaceAll('\\n', '\n'))
+ } catch {
+ throw new Error(`WEB_BOT_AUTH_PRIVATE_KEYS entry ${keyIndex} could not be loaded`)
+ }
+ if (privateKey.asymmetricKeyType !== 'ed25519') {
+ throw new Error(`WEB_BOT_AUTH_PRIVATE_KEYS entry ${keyIndex} is not an Ed25519 private key`)
+ }
+
+ const publicJwk = createPublicKey(privateKey).export({ format: 'jwk' })
+ if (publicJwk.kty !== 'OKP' || publicJwk.crv !== 'Ed25519' || !publicJwk.x) {
+ throw new Error(`WEB_BOT_AUTH_PRIVATE_KEYS entry ${keyIndex} has an invalid public key`)
+ }
+ const canonicalJwk = JSON.stringify({ crv: publicJwk.crv, kty: publicJwk.kty, x: publicJwk.x })
+ const keyId = createHash('sha256').update(canonicalJwk).digest('base64url')
+ return { privateKey, keyId }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index a7320ee51025..003a814e74d6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -69,6 +69,9 @@ export type MlMirrorConfig = {
*/
SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: boolean
+ // US-only, PEM, multiple keys allowed (comma-separated)
+ WEB_BOT_AUTH_PRIVATE_KEYS: string
+
/**
* While true the fetch lane sends no outbound request. It reads the topic, dedupes, writes the
* ledger and reports the metrics, which is the phase 0 measurement: how many requests the
@@ -242,6 +245,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: false,
SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: false,
SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: false,
+ WEB_BOT_AUTH_PRIVATE_KEYS: '',
SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: true,
SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',
SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
index 135b2829f5dc..43bccf84b4db 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -18,6 +18,7 @@ import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-
import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'
import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'
+import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth'
import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
@@ -72,6 +73,7 @@ export function buildFetchRunner(
config: IngestionSessionReplayMlMirrorServerConfig,
publisher: FrontierPublisher
): FetchRunner {
+ const webBotAuthSigner = createWebBotAuthRequestSigner(config.WEB_BOT_AUTH_PRIVATE_KEYS)
const budget = new HostBudget({
requestsPerSecond: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND,
burst: config.SESSION_RECORDING_ML_IMAGE_FETCH_BURST,
@@ -82,12 +84,15 @@ export function buildFetchRunner(
maxTrackedDomains: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS,
})
return new FetchRunner(
- new HttpImageFetcher({
- maxUrlLength: MAX_REDIRECT_URL_LENGTH,
- // The crate's rule, so a redirect target meets the check the collector already applied
- // to the first candidate rather than a second answer to the same question.
- isPublicHost: (host) => getAnonymizer().isPublicHost(host),
- }),
+ new HttpImageFetcher(
+ {
+ maxUrlLength: MAX_REDIRECT_URL_LENGTH,
+ // The crate's rule, so a redirect target meets the check the collector already applied
+ // to the first candidate rather than a second answer to the same question.
+ isPublicHost: (host) => getAnonymizer().isPublicHost(host),
+ },
+ webBotAuthSigner
+ ),
budget,
{
maxConcurrentPerDomain: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN,