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(cdp): reject push registrations from blocked regions in the node service (#114038)

Daniel Marchuk59929c86dce8
diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts
index 9e74551b13a5..b43fc9ec5839 100644
--- a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts
@@ -20,11 +20,13 @@ describe('push subscriptions http', () => {
}[]
let answer: PushHandlerResult
let failure: Error | null
+ let regionBlocked: boolean
beforeEach(async () => {
seen = []
answer = { status: 200, body: { distinct_id: 'user-1' } }
failure = null
+ regionBlocked = false
const service = {
handle: (request: any) => {
seen.push({
@@ -38,7 +40,7 @@ describe('push subscriptions http', () => {
},
} as unknown as PushSubscriptionsService
- const handler = createPushSubscriptionsHandler(service)
+ const handler = createPushSubscriptionsHandler(service, () => regionBlocked)
server = createServer(
(req, res) =>
void handler(req, res).catch(() => {
@@ -74,6 +76,27 @@ describe('push subscriptions http', () => {
expect(seen[0].mirrored).toEqual(mirrored)
})
+ it.each([
+ ['POST', false],
+ ['OPTIONS', false],
+ ['DELETE', true],
+ ])(
+ 'answers %s from a blocked region with 403, and reaches the service only to unregister: %s',
+ async (method, reaches) => {
+ regionBlocked = true
+
+ const response = await internalFetch(`${base}/api/push_subscriptions/`, {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: method === 'OPTIONS' ? undefined : JSON.stringify({ api_key: 'phc_x' }),
+ })
+
+ expect(response.status).toEqual(403)
+ expect(await response.text()).toContain('not available in your region')
+ expect(seen.map((request) => request.method)).toEqual(reaches ? [method] : [])
+ }
+ )
+
it('delivers a DELETE body to the service', async () => {
// The reason this endpoint is not on the plugin server's express framework: that one drops
// the body on DELETE, and DELETE with a body is how every released SDK unregisters a device.
diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts
index 5abb1be3644b..ab6ae8df0650 100644
--- a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts
+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts
@@ -4,6 +4,7 @@ import { Counter, Histogram } from 'prom-client'
import { logger } from '~/common/utils/logger'
import { MAX_BODY_BYTES, PushSubscriptionsService } from './push-subscriptions.service'
+import { REGION_BLOCKED_MESSAGE, RegionBlockCheck } from './region-block'
/** Names match what Django exposes, so its dashboards and alerts survive a cutover. prometheus_client
* appends `_total` in the exposition format and prom-client does not, hence the explicit suffix. */
@@ -45,7 +46,10 @@ let discardedTeamsThisWindow = new Set<number>()
* device. Verified against ultimate-express 2.0.9 — content-length arrives, the stream never emits,
* and POST, PUT and PATCH are all unaffected, so it is specific to the verb this endpoint needs.
*/
-export function createPushSubscriptionsHandler(service: PushSubscriptionsService) {
+export function createPushSubscriptionsHandler(
+ service: PushSubscriptionsService,
+ isRegionBlocked: RegionBlockCheck = () => false
+) {
return async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
const rawUrl = req.url ?? '/'
const queryStart = rawUrl.indexOf('?')
@@ -63,6 +67,20 @@ export function createPushSubscriptionsHandler(service: PushSubscriptionsService
query = new URLSearchParams()
}
+ const regionBlocked = isRegionBlocked(req)
+ if (regionBlocked) {
+ rejectionCounter.inc({
+ code: 'region_blocked',
+ method: req.method === 'POST' || req.method === 'DELETE' ? req.method : 'other',
+ })
+ // A logout still removes the device, as it does in Django, so a person's pushes stop reaching
+ // a device that left. Anything else is rejected before the body is read.
+ if (req.method !== 'DELETE') {
+ res.writeHead(403, { 'Content-Type': 'text/html; charset=utf-8' }).end(REGION_BLOCKED_MESSAGE)
+ return
+ }
+ }
+
applyCors(req, res)
if (req.method === 'OPTIONS') {
@@ -134,6 +152,10 @@ export function createPushSubscriptionsHandler(service: PushSubscriptionsService
Number(process.hrtime.bigint() - startedAt) / 1e9
)
+ if (regionBlocked) {
+ res.writeHead(403, { 'Content-Type': 'text/html; charset=utf-8' }).end(REGION_BLOCKED_MESSAGE)
+ return
+ }
res.writeHead(result.status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(result.body))
}
diff --git a/nodejs/src/messaging/push-subscriptions/region-block.test.ts b/nodejs/src/messaging/push-subscriptions/region-block.test.ts
new file mode 100644
index 000000000000..dccd1d6555fe
--- /dev/null
+++ b/nodejs/src/messaging/push-subscriptions/region-block.test.ts
@@ -0,0 +1,59 @@
+import { createHmac } from 'crypto'
+import { IncomingMessage } from 'http'
+
+import { GeoIp } from '~/common/utils/geoip'
+
+import { createRegionBlockCheck } from './region-block'
+
+describe('createRegionBlockCheck', () => {
+ const countries: Record<string, string> = {
+ '5.255.255.1': 'RU',
+ '8.8.8.8': 'US',
+ '2a02:6b8::1': 'RU',
+ }
+ const geoip: GeoIp = {
+ city: (ip) => (countries[ip] ? ({ country: { isoCode: countries[ip] } } as any) : null),
+ }
+ const request = (forwardedFor: string | undefined, remoteAddress = '10.0.0.1'): IncomingMessage =>
+ ({
+ headers: forwardedFor === undefined ? {} : { 'x-forwarded-for': forwardedFor },
+ socket: { remoteAddress },
+ }) as any
+
+ it.each([
+ ['the client in X-Forwarded-For is in a blocked country', request('5.255.255.1, 10.0.0.2'), true],
+ ['only a proxy hop is in a blocked country', request('8.8.8.8, 5.255.255.1'), false],
+ ['the client sends a port with an IPv4 address', request('5.255.255.1:443'), true],
+ ['the client sends a bracketed IPv6 address with a port', request('[2a02:6b8::1]:443'), true],
+ ['the address is not an IP', request('not-an-ip'), true],
+ ['GeoIP cannot place the address', request('203.0.113.9'), false],
+ ['there is no X-Forwarded-For and the socket is in a blocked country', request(undefined, '5.255.255.1'), true],
+ ])('when %s, blocked is %s', (_name, req, expected) => {
+ expect(createRegionBlockCheck(['RU', 'BY'], geoip)(req)).toBe(expected)
+ })
+
+ const signed = (ip: string, key: string, ageSeconds = 0): IncomingMessage => {
+ const timestamp = String(Math.floor(Date.now() / 1000 - ageSeconds))
+ return {
+ headers: {
+ 'x-forwarded-for': '8.8.8.8',
+ 'x-posthog-client-ip': ip,
+ 'x-posthog-client-ip-timestamp': timestamp,
+ 'x-posthog-client-ip-signature': createHmac('sha256', key).update(`${ip}:${timestamp}`).digest('hex'),
+ },
+ socket: { remoteAddress: '10.0.0.1' },
+ } as any
+ }
+
+ it.each([
+ ['a valid signature uses the signed client IP', signed('5.255.255.1', 'key-b'), true],
+ ['a signature from an unknown key falls back to the edge IP', signed('5.255.255.1', 'other'), false],
+ ['an expired signature falls back to the edge IP', signed('5.255.255.1', 'key-a', 120), false],
+ ])('managed proxy: %s', (_name, req, expected) => {
+ expect(createRegionBlockCheck(['RU'], geoip, ['key-a', 'key-b'])(req)).toBe(expected)
+ })
+
+ it('blocks nothing when no regions are configured', () => {
+ expect(createRegionBlockCheck([], geoip)(request('5.255.255.1'))).toBe(false)
+ })
+})
diff --git a/nodejs/src/messaging/push-subscriptions/region-block.ts b/nodejs/src/messaging/push-subscriptions/region-block.ts
new file mode 100644
index 000000000000..6813e50fd329
--- /dev/null
+++ b/nodejs/src/messaging/push-subscriptions/region-block.ts
@@ -0,0 +1,124 @@
+import { createHmac, timingSafeEqual } from 'crypto'
+import { IncomingMessage } from 'http'
+import { isIP } from 'net'
+import { Counter } from 'prom-client'
+
+import { GeoIp } from '~/common/utils/geoip'
+
+export const REGION_BLOCKED_MESSAGE =
+ 'PostHog is not available in your region. If you think this is in error, please contact [email protected].'
+
+export type RegionBlockCheck = (req: IncomingMessage) => boolean
+
+const SIGNED_CLIENT_IP_MAX_AGE_SECONDS = 60
+const SIGNED_CLIENT_IP_MAX_CLOCK_SKEW_SECONDS = 5
+
+const signedClientIpCounter = new Counter({
+ name: 'push_subscription_managed_proxy_client_ip_total',
+ help: 'Verifications of the client IP the managed reverse proxy signs, by outcome.',
+ labelNames: ['outcome'],
+})
+
+function header(req: IncomingMessage, name: string): string | undefined {
+ const value = req.headers[name]
+ return Array.isArray(value) ? value[0] : value
+}
+
+/** Django's `verify_signed_client_ip`: the managed proxy sends hex(HMAC-SHA256(key, "<ip>:<unix seconds>")).
+ * Envoy sets X-Forwarded-For to the Cloudflare edge for that traffic, so only this signature recovers
+ * the real client. */
+export function signedClientIp(
+ req: IncomingMessage,
+ signingKeys: string[],
+ nowSeconds: number = Date.now() / 1000
+): string | undefined {
+ const ip = header(req, 'x-posthog-client-ip')
+ const timestamp = header(req, 'x-posthog-client-ip-timestamp')
+ const signature = header(req, 'x-posthog-client-ip-signature')
+ if (ip === undefined && timestamp === undefined && signature === undefined) {
+ return undefined
+ }
+ const outcome = verifySignature(ip, timestamp, signature, signingKeys, nowSeconds)
+ signedClientIpCounter.inc({ outcome })
+ return outcome === 'valid' ? ip : undefined
+}
+
+function verifySignature(
+ ip: string | undefined,
+ timestamp: string | undefined,
+ signature: string | undefined,
+ signingKeys: string[],
+ nowSeconds: number
+): string {
+ const keys = signingKeys.filter(Boolean)
+ if (keys.length === 0) {
+ return 'not_configured'
+ }
+ if (!ip || !timestamp || !signature || !/^\d{1,12}$/.test(timestamp) || !isIP(ip)) {
+ return 'invalid_input'
+ }
+ const age = nowSeconds - Number(timestamp)
+ if (age < -SIGNED_CLIENT_IP_MAX_CLOCK_SKEW_SECONDS || age > SIGNED_CLIENT_IP_MAX_AGE_SECONDS) {
+ return 'timestamp_out_of_window'
+ }
+ const provided = Buffer.from(signature.toLowerCase())
+ for (const key of keys) {
+ const expected = Buffer.from(createHmac('sha256', key).update(`${ip}:${timestamp}`).digest('hex'))
+ if (expected.length === provided.length && timingSafeEqual(expected, provided)) {
+ return 'valid'
+ }
+ }
+ return 'bad_signature'
+}
+
+/** Matches Django's `_normalize_ip`: strips a port, and returns undefined for anything that isn't an IP. */
+export function normalizeIp(raw: string): string | undefined {
+ let ip = raw.trim()
+ if (ip.startsWith('[')) {
+ const end = ip.indexOf(']')
+ if (end !== -1) {
+ ip = ip.slice(1, end)
+ }
+ } else if (ip.split(':').length === 2) {
+ ip = ip.split(':')[0]
+ }
+ return isIP(ip) ? ip : undefined
+}
+
+/** The managed proxy's signed client IP when it verifies, otherwise the left-most X-Forwarded-For
+ * entry, as Django reads it with TRUST_ALL_PROXIES. That entry is only trustworthy because the Cloud
+ * ingress overwrites the header. Behind a proxy that appends to it, the client controls the entry. */
+export function clientIp(req: IncomingMessage, signingKeys: string[] = []): string | undefined {
+ const signed = signedClientIp(req, signingKeys)
+ if (signed) {
+ return normalizeIp(signed)
+ }
+ const forwardedFor = req.headers['x-forwarded-for']
+ const forwarded = (Array.isArray(forwardedFor) ? forwardedFor.join(',') : (forwardedFor ?? ''))
+ .split(',')
+ .map((part) => part.trim())
+ .filter(Boolean)
+ const raw = forwarded[0] ?? req.socket.remoteAddress
+ return raw ? normalizeIp(raw) : undefined
+}
+
+/** Django's AllowIPMiddleware decision for BLOCKED_GEOIP_REGIONS. An address that cannot be read is
+ * blocked, and an address the GeoIP database cannot place is allowed. */
+export function createRegionBlockCheck(
+ blockedCountries: string[],
+ geoip: GeoIp | undefined,
+ signingKeys: string[] = []
+): RegionBlockCheck {
+ const blocked = new Set(blockedCountries.map((code) => code.trim().toUpperCase()).filter(Boolean))
+ if (blocked.size === 0) {
+ return () => false
+ }
+ return (req) => {
+ const ip = clientIp(req, signingKeys)
+ if (!ip) {
+ return true
+ }
+ const country = geoip?.city(ip)?.country?.isoCode
+ return country !== undefined && blocked.has(country)
+ }
+}
diff --git a/nodejs/src/servers/push-api-server.ts b/nodejs/src/servers/push-api-server.ts
index 06c67009a611..e51044d9770a 100644
--- a/nodejs/src/servers/push-api-server.ts
+++ b/nodejs/src/servers/push-api-server.ts
@@ -4,11 +4,13 @@ import { EncryptedFields } from '~/cdp/utils/encryption-utils'
import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
import { PostgresRouter, PostgresRouterConfig } from '~/common/utils/db/postgres'
import { isProdEnv, isTestEnv } from '~/common/utils/env-utils'
+import { GeoIPService } from '~/common/utils/geoip'
import { logger } from '~/common/utils/logger'
import { ProjectTokenLookup } from '~/messaging/push-subscriptions/project-token-lookup'
import { DryRunPushCaptureService, PushCaptureService } from '~/messaging/push-subscriptions/push-capture'
import { createPushSubscriptionsHandler } from '~/messaging/push-subscriptions/push-subscriptions-http'
import { PushSubscriptionsService } from '~/messaging/push-subscriptions/push-subscriptions.service'
+import { RegionBlockCheck, createRegionBlockCheck } from '~/messaging/push-subscriptions/region-block'
import { CommonConfig } from '../common/config'
import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService } from '../types'
@@ -24,6 +26,10 @@ export type PushApiConfig = {
/** Skips the person update for a mirrored copy and still answers as if it was stored. A request
* that reaches the service directly is still stored. */
PUSH_API_DRY_RUN: boolean
+ /** Comma-separated ISO country codes answered 403, the same list Django reads. */
+ BLOCKED_GEOIP_REGIONS: string
+ /** Comma-separated keys the managed reverse proxy signs the client IP with, the same as Django's. */
+ MANAGED_PROXY_SIGNING_KEYS: string
}
export function getDefaultPushApiConfig(): PushApiConfig {
@@ -32,13 +38,18 @@ export function getDefaultPushApiConfig(): PushApiConfig {
PUSH_API_HOST: '0.0.0.0',
SECRET_KEY: '',
PUSH_API_DRY_RUN: false,
+ BLOCKED_GEOIP_REGIONS: '',
+ MANAGED_PROXY_SIGNING_KEYS: '',
}
}
export type PushApiServerConfig = BaseServerConfig &
PostgresRouterConfig &
PushApiConfig &
- Pick<CommonConfig, 'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'ENCRYPTION_SALT_KEYS' | 'CAPTURE_INTERNAL_URL'>
+ Pick<
+ CommonConfig,
+ 'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'ENCRYPTION_SALT_KEYS' | 'CAPTURE_INTERNAL_URL' | 'MMDB_FILE_LOCATION'
+ >
/** Serves `/api/push_subscriptions/`, the endpoint every mobile SDK calls on app open.
*
@@ -104,8 +115,10 @@ export class PushApiServer implements NodeServer {
this.config.PUSH_API_DRY_RUN ? new DryRunPushCaptureService() : capture
)
+ const isRegionBlocked = await this.loadRegionBlockCheck()
+
if (!isTestEnv()) {
- this.pushServer = await this.listen(createPushSubscriptionsHandler(service))
+ this.pushServer = await this.listen(createPushSubscriptionsHandler(service, isRegionBlocked))
}
const pluginService: PluginServerService = {
@@ -124,6 +137,25 @@ export class PushApiServer implements NodeServer {
this.lifecycle.services.push(pluginService)
}
+ private async loadRegionBlockCheck(): Promise<RegionBlockCheck> {
+ const countries = this.config.BLOCKED_GEOIP_REGIONS.split(',').filter((code) => code.trim())
+ if (countries.length === 0) {
+ return createRegionBlockCheck([], undefined)
+ }
+ const geoip = await new GeoIPService(this.config.MMDB_FILE_LOCATION).get()
+ // An unreadable database places no address, which would let every blocked region through.
+ if (!geoip.city('8.8.8.8')) {
+ const message = 'push-api could not load the GeoIP database, so blocked regions are not enforced'
+ if (isProdEnv()) {
+ throw new Error(message)
+ }
+ logger.error(message, { location: this.config.MMDB_FILE_LOCATION })
+ }
+ logger.info('push-api blocks registrations from regions', { countries })
+ const signingKeys = this.config.MANAGED_PROXY_SIGNING_KEYS.split(',').map((key) => key.trim())
+ return createRegionBlockCheck(countries, geoip, signingKeys)
+ }
+
private listen(handler: (req: any, res: any) => Promise<void>): Promise<Server> {
// Node checks the header and request timeouts only this often, 30 seconds by default, which
// lets a slow client hold a socket well past them.