: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(cdp): log URL-validation blocks with team attribution (#73034)
Felipe Rosa de Almeidaed8219207c7f
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.tsindex b158d7ab5c2f..42a0a9b17e9d 100644--- a/nodejs/src/cdp/services/hog-executor.service.ts+++ b/nodejs/src/cdp/services/hog-executor.service.ts@@ -5,6 +5,7 @@ import { ExecResult, convertHogToJS } from '@posthog/hogvm'import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'import { instrumented } from '~/common/tracing/tracing-utils'+import { fetchAttribution } from '~/common/utils/fetch-attribution'import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'import { FetchOptions, FetchResponse, InvalidRequestError, SecureRequestError, fetch } from '~/common/utils/request'@@ -87,6 +88,40 @@ const cdpHttpRequestTimingRetried = new Histogram({buckets: [0, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000],})+// SecureRequestError (private/link-local IP), ResolutionError (DNS failed or every+// resolved IP was unsafe) and InvalidRequestError (bad scheme/URL) all mean the request+// was refused before or during connection — never a response from the destination.+// Matched by name, not instanceof: tests that mock ~/common/utils/request leave the+// error classes undefined, and instanceof against undefined throws.+export function isBlockedRequestError(error: unknown): boolean {+ const name = (error as { name?: string } | null)?.name+ return name === 'SecureRequestError' || name === 'ResolutionError' || name === 'InvalidRequestError'+}++// Emit ops-visible attribution for a blocked request. The low-level guard in+// common/utils/request.ts increments `node_request_unsafe` but has no team/function context,+// and the customer-facing `addLog` entries are team-scoped and not queryable from the ops+// side — this log carries the attribution needed to trace a block back to a destination.+function logBlockedRequest(+ error: Error,+ { url, templateId, teamId, hogFunctionId }: CdpFetchAttribution & { url: string; templateId: string }+): void {+ let hostname: string | undefined+ try {+ hostname = new URL(url).hostname+ } catch {+ // Malformed URL (InvalidRequestError) — hostname stays undefined+ }+ logger.warn('[cdpTrackedFetch] Request blocked by SSRF / URL-validation guard', {+ reason: error.name,+ message: error.message,+ hostname,+ teamId,+ hogFunctionId,+ templateId,+ })+}+// Stale keep-alive connections produce these errors when the server has closed its end before// we reuse the socket. A single in-process retry on a fresh connection may resolve them immediately.export function isConnectionLevelError(error: any): boolean {@@ -99,18 +134,39 @@ export function isConnectionLevelError(error: any): boolean {)}+// Attribution for a tracked fetch, so a blocked/refused request can be traced back to the+// owning hog function and team. Optional because a few callers (push notifications, hog+// transformations) hand `cdpTrackedFetch` to the Hog VM without an invocation in scope.+export type CdpFetchAttribution = {+ teamId?: number+ hogFunctionId?: string+}+export async function cdpTrackedFetch({url,fetchParams,templateId,+ teamId,+ hogFunctionId,}: {url: stringfetchParams: FetchOptionstemplateId: string-}): Promise<{ fetchError: Error | null; fetchResponse: FetchResponse | null; fetchDuration: number }> {+} & CdpFetchAttribution): Promise<{+ fetchError: Error | null+ fetchResponse: FetchResponse | null+ fetchDuration: number+}> {const start = performance.now()- let [fetchError, fetchResponse] = await tryCatch(async () => await fetch(url, fetchParams))+ // Attribution read by the URL-validation check logs in common/utils/request.ts, which+ // run inside undici's connect flow where no caller context is otherwise available.+ const doFetch = () =>+ fetchAttribution.run({ teamId, hogFunctionId, templateId }, () =>+ tryCatch(async () => await fetch(url, fetchParams))+ )++ let [fetchError, fetchResponse] = await doFetch()const fetchDuration = performance.now() - startcdpHttpRequestTiming.observe(fetchDuration)@@ -121,13 +177,20 @@ export async function cdpTrackedFetch({url,error: fetchError,})- ;[fetchError, fetchResponse] = await tryCatch(async () => await fetch(url, fetchParams))+ ;[fetchError, fetchResponse] = await doFetch()const retryDuration = performance.now() - startcdpHttpRequestTimingRetried.observe(retryDuration)cdpHttpRequests.inc({ status: fetchResponse?.status?.toString() ?? 'error', template_id: templateId })+ if (fetchError && isBlockedRequestError(fetchError)) {+ logBlockedRequest(fetchError, { url, templateId, teamId, hogFunctionId })+ }return { fetchError, fetchResponse, fetchDuration: retryDuration }}+ if (fetchError && isBlockedRequestError(fetchError)) {+ logBlockedRequest(fetchError, { url, templateId, teamId, hogFunctionId })+ }+return { fetchError, fetchResponse, fetchDuration }}@@ -897,6 +960,8 @@ export class HogExecutorService {url: params.url,fetchParams,templateId,+ teamId: invocation.teamId,+ hogFunctionId: invocation.hogFunction.id,})result.invocation.state.timings.push({diff --git a/nodejs/src/cdp/services/legacy-plugin-executor.service.ts b/nodejs/src/cdp/services/legacy-plugin-executor.service.tsindex 17d7cdc73563..2ddf61097e6c 100644--- a/nodejs/src/cdp/services/legacy-plugin-executor.service.ts+++ b/nodejs/src/cdp/services/legacy-plugin-executor.service.ts@@ -136,6 +136,8 @@ export class LegacyPluginExecutorService {url,fetchParams,templateId: invocation.hogFunction.template_id ?? '',+ teamId: invocation.teamId,+ hogFunctionId: invocation.hogFunction.id,})if (fetchError || !fetchResponse) {diff --git a/nodejs/src/cdp/services/native-destination-executor.service.ts b/nodejs/src/cdp/services/native-destination-executor.service.tsindex 9f859e7d2dc4..9ddf85e8d108 100644--- a/nodejs/src/cdp/services/native-destination-executor.service.ts+++ b/nodejs/src/cdp/services/native-destination-executor.service.ts@@ -161,6 +161,8 @@ export class NativeDestinationExecutorService {url,fetchParams: fetchOptions,templateId: invocation.hogFunction.template_id ?? '',+ teamId: invocation.teamId,+ hogFunctionId: invocation.hogFunction.id,})const fetchResponseText = (await fetchResponse?.text()) ?? 'unknown'diff --git a/nodejs/src/cdp/services/segment-destination-executor.service.ts b/nodejs/src/cdp/services/segment-destination-executor.service.tsindex 6f0bd7b9a379..88ebcb879f90 100644--- a/nodejs/src/cdp/services/segment-destination-executor.service.ts+++ b/nodejs/src/cdp/services/segment-destination-executor.service.ts@@ -251,6 +251,8 @@ export class SegmentDestinationExecutorService {url,fetchParams: fetchOptions,templateId: invocation.hogFunction.template_id ?? '',+ teamId: invocation.teamId,+ hogFunctionId: invocation.hogFunction.id,})const fetchResponseText = (await fetchResponse?.text()) ?? 'unknown'diff --git a/nodejs/src/common/utils/fetch-attribution.ts b/nodejs/src/common/utils/fetch-attribution.tsnew file mode 100644index 000000000000..e0c4b391efc1--- /dev/null+++ b/nodejs/src/common/utils/fetch-attribution.ts@@ -0,0 +1,7 @@+import { AsyncLocalStorage } from 'node:async_hooks'++// Caller attribution (e.g. teamId, hogFunctionId) for URL-validation check logs. The DNS+// check runs inside undici's connect flow, which has no caller context — callers that want+// attributed logs wrap their fetch in `fetchAttribution.run({...}, ...)`.+// Lives in its own module so tests that mock `./request` don't replace it with undefined.+export const fetchAttribution = new AsyncLocalStorage<Record<string, unknown>>()diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.tsindex f25ce5b5cec0..2689f327a9d8 100644--- a/nodejs/src/common/utils/request.ts+++ b/nodejs/src/common/utils/request.ts@@ -20,7 +20,9 @@ import { URL } from 'url'import { getExternalRequestConfig } from '~/common/config'import { isProdEnv } from './env-utils'+import { fetchAttribution } from './fetch-attribution'import { parseJSON } from './json-parse'+import { logger } from './logger'const requestConfig = getExternalRequestConfig()@@ -82,6 +84,17 @@ export class ResolutionError extends Error {}}+// Logged only when a check blocks the request. The check runs inside undici's connect flow+// where the thrown error can't carry caller context, so attribution comes from the ALS store;+// it reflects the request that opened the connection (keep-alive reuse skips the check).+function logBlockedUrlValidation(hostname: string, resolvedIps: string[]): void {+ logger.warn('[SSRF] Request blocked by URL validation check', {+ hostname,+ resolvedIps,+ ...fetchAttribution.getStore(),+ })+}+function validateUrl(url: string): URL {// Raise if the provided URL seems unsafe, otherwise do nothing.let parsedUrl: URL@@ -129,6 +142,7 @@ function validateHostnameIPLiteral(hostname: string, allowUnsafe: boolean): void} else {if (!isGlobalIPv6(parsed)) {unsafeRequestCounter.inc({ reason: 'internal_ip_literal' })+ logBlockedUrlValidation(hostname, [bare])throw new SecureRequestError('Hostname is not allowed')}return@@ -136,6 +150,7 @@ function validateHostnameIPLiteral(hostname: string, allowUnsafe: boolean): voidif (!isGlobalIPv4(ipv4)) {unsafeRequestCounter.inc({ reason: 'internal_ip_literal' })+ logBlockedUrlValidation(hostname, [bare])throw new SecureRequestError('Hostname is not allowed')}}@@ -178,6 +193,7 @@ async function staticLookupAsync(hostname: string): Promise<LookupAddress[]> {} catch {throw new ResolutionError('Invalid hostname')}+ const resolvedIps = addrinfo.map((a) => a.address)for (const addrInfo of addrinfo) {const parsed = ipaddr.parse(addrInfo.address)@@ -192,6 +208,7 @@ async function staticLookupAsync(hostname: string): Promise<LookupAddress[]> {const allowUnsafe = !isProdEnv()if (!allowUnsafe && !isGlobalIPv6(parsed)) {unsafeRequestCounter.inc({ reason: 'internal_hostname' })+ logBlockedUrlValidation(hostname, resolvedIps)throw new SecureRequestError('Hostname is not allowed')}validAddrinfo.push(addrInfo)@@ -204,12 +221,14 @@ async function staticLookupAsync(hostname: string): Promise<LookupAddress[]> {// Check if the IPv4 address is globalif (!allowUnsafe && !isGlobalIPv4(ipv4)) {unsafeRequestCounter.inc({ reason: 'internal_hostname' })+ logBlockedUrlValidation(hostname, resolvedIps)throw new SecureRequestError('Hostname is not allowed')}validAddrinfo.push(addrInfo)}if (validAddrinfo.length === 0) {unsafeRequestCounter.inc({ reason: 'unable_to_resolve' })+ logBlockedUrlValidation(hostname, resolvedIps)throw new ResolutionError(`Unable to resolve ${hostname}`)}