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(replay): stop scrubbing customer domains in replay anonymizer urls (#72562)

Robbiecb180e3c76b1
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
index 8f0003b96d3e..1928b508943e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
@@ -9,7 +9,6 @@ describe('ai-training-optin-filter-step', () => {
teamId: 1,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn,
- firstPartyHosts: [],
})
it('passes through a team that opted into AI training', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.test.ts
deleted file mode 100644
index cae48f08ede1..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { firstPartyHostPatterns } from './first-party-hosts'
-
-describe('firstPartyHostPatterns reduces recording domains to registrable domains', () => {
- test.each([
- ['subdomain and scheme dropped', ['https://www.example.com'], ['example.com']],
- ['deep subdomain dropped', ['https://app.eu.example.com'], ['example.com']],
- ['multi-part public suffix kept', ['https://www.example.co.uk'], ['example.co.uk']],
- ['wildcard entry reduces to its base', ['https://*.example.com'], ['example.com']],
- ['port and path dropped', ['https://app.example.com:5000/welcome'], ['example.com']],
- ['localhost kept whole', ['capacitor://localhost'], ['localhost']],
- ['ip kept whole', ['http://192.168.0.10:3000'], ['192.168.0.10']],
- ['bare wildcard ignored, casing normalized', ['*', 'https://App.Example.com'], ['example.com']],
- ['null and empty input give no patterns', null, []],
- ['private-suffix platform host keeps the tenant label', ['https://myapp.vercel.app'], ['myapp.vercel.app']],
- ['bare public suffix entries are dropped', ['https://*.com', 'https://co.uk'], []],
- ['non-string elements are skipped', [null as any, 'https://www.example.com'], ['example.com']],
- ['opaque-scheme host is lowercased', ['capacitor://LocalHost'], ['localhost']],
- ] as [string, string[] | null, string[]][])('%s', (_name, domains, expected) => {
- expect(firstPartyHostPatterns(domains)).toEqual(expected)
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.ts
deleted file mode 100644
index 36f17b597620..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { parse as parseHostname } from 'tldts'
-
-/**
- * Reduce a team's recording domains to registrable-domain patterns; the anonymizer collapses
- * matching hosts to `example.com`.
- */
-export function firstPartyHostPatterns(recordingDomains: string[] | null | undefined): string[] {
- const patterns: string[] = []
- for (const domain of recordingDomains ?? []) {
- // The DB column allows NULL elements; one bad entry must not poison the team refresh.
- if (typeof domain !== 'string') {
- continue
- }
- const trimmed = domain.trim()
- if (trimmed === '') {
- continue
- }
- let hostname: string
- try {
- hostname = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`).hostname
- } catch {
- continue
- }
- if (hostname.startsWith('*.')) {
- hostname = hostname.slice(2)
- }
- if (hostname === '' || hostname === '*') {
- continue
- }
- const parsed = parseHostname(hostname, { allowPrivateDomains: true })
- if (parsed.domain !== null) {
- patterns.push(parsed.domain.toLowerCase())
- continue
- }
- // No registrable domain: keep bare machine names (`localhost`, `intranet`) and IPs, but
- // drop listed public suffixes (`com`, `co.uk`, a bare `github.io`) — a suffix pattern
- // would match every host under it.
- if (parsed.isIp || !(parsed.isIcann || parsed.isPrivate)) {
- patterns.push(hostname.toLowerCase())
- }
- }
- return patterns
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
index ee3e9af9a00b..39ce9a456583 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
@@ -100,7 +100,6 @@ describe('ml-mirror-pipeline', () => {
teamId: 1,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn,
- firstPartyHosts: [],
})
beforeEach(() => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
index 6cf0fd2573e9..ed04b95ac25a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
@@ -110,36 +110,6 @@ describeAddon('native rust addon matches the shared fixtures', () => {
}
})
- it('collapses first-party hosts passed per call', async () => {
- const event = {
- type: 2,
- data: {
- node: {
- type: 0,
- childNodes: [
- {
- type: 2,
- tagName: 'a',
- attributes: { href: 'https://app.customer-site.test/settings' },
- childNodes: [],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- rustAddon!.initAnonymizer({ text: [], url: [] })
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [event]), undefined, [
- 'customer-site.test',
- ])
- expect(result.failed).toBe(false)
- const line = parseLines(result.lines!)[0] as [
- string,
- { data: { node: { childNodes: { attributes: Record<string, string> }[] } } },
- ]
- expect(line[1].data.node.childNodes[0].attributes.href).toBe('https://example.com/[redacted]')
- })
-
// fixtures are plain text, convert to gzip bytes for this test
describe('cv-compressed events through the production entry', () => {
// latin-1: each compressed byte is a U+00XX codepoint, matching the SDK wire format.
@@ -201,7 +171,7 @@ describeAddon('native rust addon matches the shared fixtures', () => {
const decoded = unzstdLatin1(line[1].data.attributes) as { attributes: Record<string, string> }[]
expect(decoded[0].attributes.rr_src).toMatch(/^data:image\/svg\+xml/)
expect(decoded[0].attributes['data-anon-original-rr_src']).toBe(
- 'https://example.com/[redacted]/[redacted]/'
+ 'https://widget.example-vendor.co/[redacted]/[redacted]/'
)
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
index 16e36b37a777..ed563051469f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
@@ -14,21 +14,14 @@ const compressWithGzip = promisify(gzip)
// assembly — not the scrub itself (that's covered by the Rust suite + shared fixtures).
const mockAnonymizeKafkaPayload = jest.fn()
jest.mock('@posthog/replay-anonymizer', () => ({
- anonymizeKafkaPayload: (payload: Buffer, contentEncoding?: string | null, firstPartyHosts?: string[] | null) =>
- mockAnonymizeKafkaPayload(payload, contentEncoding, firstPartyHosts),
+ anonymizeKafkaPayload: (payload: Buffer, contentEncoding?: string | null) =>
+ mockAnonymizeKafkaPayload(payload, contentEncoding),
}))
describe('createParseAndAnonymizeMessageStep', () => {
const step = createParseAndAnonymizeMessageStep()
const now = Date.now()
- const team = {
- teamId: 1,
- consoleLogIngestionEnabled: true,
- aiTrainingOptedIn: true,
- firstPartyHosts: ['customer-site.test'],
- }
-
const headers: SessionReplayHeaders = {
token: 'token-1',
distinct_id: 'user-1',
@@ -75,7 +68,7 @@ describe('createParseAndAnonymizeMessageStep', () => {
it('assembles a pre-serialized ParsedMessageData from the addon output', async () => {
addonSuccess()
- const result = await step({ message: kafkaMessage(), headers, team })
+ const result = await step({ message: kafkaMessage(), headers })
expect(result.type).toBe(PipelineResultType.OK)
const parsed = (result as any).value.parsedMessage
@@ -97,7 +90,6 @@ describe('createParseAndAnonymizeMessageStep', () => {
const upper = '019539D9-6B23-7E26-B0E3-3C8D3E2AD068'
addonSuccess({ sessionId: upper })
const result = await step({
- team,
message: kafkaMessage(),
headers: { ...headers, session_id: upper.toLowerCase() },
})
@@ -109,15 +101,15 @@ describe('createParseAndAnonymizeMessageStep', () => {
addonSuccess()
const raw = Buffer.from(JSON.stringify({ distinct_id: 'user-1', data: '{}' }))
const zipped = await compressWithGzip(raw)
- await step({ message: kafkaMessage(zipped), headers, team })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null, team.firstPartyHosts)
+ await step({ message: kafkaMessage(zipped), headers })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null)
mockAnonymizeKafkaPayload.mockClear()
addonSuccess()
const lz4Message = kafkaMessage(raw)
lz4Message.headers = [{ 'content-encoding': Buffer.from('lz4') }]
- await step({ message: lz4Message, headers, team })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4', team.firstPartyHosts)
+ await step({ message: lz4Message, headers })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4')
})
test.each([
@@ -135,21 +127,21 @@ describe('createParseAndAnonymizeMessageStep', () => {
lines: null,
meta: null,
})
- const result = await step({ message: kafkaMessage(), headers, team })
+ const result = await step({ message: kafkaMessage(), headers })
expect(result.type).toBe(expectedType)
expect((result as any).reason).toBe(reason)
})
it('fails closed when the addon promise rejects', async () => {
mockAnonymizeKafkaPayload.mockRejectedValue(new Error('native panic'))
- const result = await step({ message: kafkaMessage(), headers, team })
+ const result = await step({ message: kafkaMessage(), headers })
expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'anonymize_failed' })
})
it('drops messages whose timestamps are too far from now', async () => {
const monthAgo = now - 30 * 24 * 60 * 60 * 1000
addonSuccess({ startTs: monthAgo, endTs: monthAgo + 1000 })
- const result = await step({ message: kafkaMessage(), headers, team })
+ const result = await step({ message: kafkaMessage(), headers })
expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'message_timestamp_diff_too_large' })
})
@@ -158,12 +150,12 @@ describe('createParseAndAnonymizeMessageStep', () => {
['distinct_id', { distinctId: 'other-user' }, 'distinct_id_header_body_mismatch'],
])('dlqs on a %s header/body mismatch', async (_field, metaOverrides, reason) => {
addonSuccess(metaOverrides)
- const result = await step({ message: kafkaMessage(), headers, team })
+ const result = await step({ message: kafkaMessage(), headers })
expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason })
})
it('dlqs when the message value is empty', async () => {
- const result = await step({ message: kafkaMessage(null), headers, team })
+ const result = await step({ message: kafkaMessage(null), headers })
expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason: 'message_value_or_timestamp_is_empty' })
expect(mockAnonymizeKafkaPayload).not.toHaveBeenCalled()
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
index e4d361f8bef3..fee021fe1414 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
@@ -11,7 +11,6 @@ import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/typ
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
import { ParseMessageStepInput, ParseMessageStepOutput, getContentEncoding, isGzipped } from './parse-message-step'
-import { TeamForReplay } from './shared/teams/types'
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
@@ -44,9 +43,10 @@ const DLQ_REASONS = new Set([
* unencrypted ML bucket. Failure classification matches the TS parse step so DLQ/drop behavior and
* ingestion warnings are unchanged.
*/
-export function createParseAndAnonymizeMessageStep<
- T extends ParseMessageStepInput & { team: TeamForReplay },
->(): ProcessingStep<T, T & ParseMessageStepOutput> {
+export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput>(): ProcessingStep<
+ T,
+ T & ParseMessageStepOutput
+> {
return async function parseAndAnonymizeMessageStep(input) {
const { message, headers } = input
@@ -64,11 +64,7 @@ export function createParseAndAnonymizeMessageStep<
const t0 = performance.now()
let result
try {
- result = await getRustAnonymizer().anonymizeKafkaPayload(
- message.value,
- contentEncoding,
- input.team.firstPartyHosts
- )
+ result = await getRustAnonymizer().anonymizeKafkaPayload(message.value, contentEncoding)
} catch (error) {
// A rejected promise (native panic, addon load failure) must fail closed.
logger.warn('🙈', 'anonymize_event_failed', { error: String(error) })
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts
index 98b4e2706fd4..bf63adec7ae7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts
@@ -23,7 +23,6 @@ describe('createRecordSessionEventStep', () => {
teamId: 1,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
}
const createParsedMessage = (overrides: Partial<ParsedMessageData> = {}): ParsedMessageData => ({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts
index b5870db289c8..0d0d2c25f68c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-rate-limiter.test.ts
@@ -161,7 +161,6 @@ describe('session-replay-pipeline rate limiter failure modes', () => {
teamId: TEAM_ID,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
}
const now = DateTime.fromMillis(1_700_000_000_000)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
index b6d82e97a5f2..780d44c0ac46 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
@@ -122,7 +122,6 @@ describe('session-replay-pipeline', () => {
teamId: 1,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
}
const now = DateTime.now()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
index 958854b7e72c..af0a6958ab2b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
@@ -276,7 +276,6 @@ describe('SessionBatchRecorder', () => {
teamId,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
},
message: {
distinct_id: distinctId,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts
index 07ece787cfd0..fe6d232bc825 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts
@@ -48,7 +48,6 @@ describe('SessionConsoleLogRecorder', () => {
teamId,
consoleLogIngestionEnabled,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
},
message: {
distinct_id: distinctId,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
index 45a70f1d909a..95c1bc53d7d9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
@@ -1,7 +1,6 @@
import { BackgroundRefresher } from '~/common/utils/background-refresher'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
import { logger } from '~/common/utils/logger'
-import { firstPartyHostPatterns } from '~/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts'
import { RetentionPeriod, isValidRetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'
import { Team, TeamId } from '~/types'
@@ -68,7 +67,6 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
capture_console_log_opt_in: boolean
session_recording_retention_period: string
is_ai_training_opted_in: boolean
- recording_domains: string[] | null
} & Pick<Team, 'id' | 'api_token'>
>(
PostgresUse.COMMON_READ,
@@ -78,7 +76,6 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
t.api_token,
t.capture_console_log_opt_in,
t.session_recording_retention_period,
- t.recording_domains,
COALESCE(o.is_ai_training_opted_in, false) AS is_ai_training_opted_in
FROM posthog_team t
LEFT JOIN posthog_organization o ON o.id = t.organization_id
@@ -94,7 +91,6 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
teamId: row.id,
consoleLogIngestionEnabled: row.capture_console_log_opt_in,
aiTrainingOptedIn: row.is_ai_training_opted_in,
- firstPartyHosts: firstPartyHostPatterns(row.recording_domains),
}
return acc
},
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
index c0615c941b75..312149baf425 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
@@ -5,6 +5,4 @@ export interface TeamForReplay {
consoleLogIngestionEnabled: boolean
/** Whether the team's organization opted into using its data for AI training. */
aiTrainingOptedIn: boolean
- /** Registrable domains derived from the team's recording domains; the anonymizer collapses these hosts (and their subdomains) as first-party. */
- firstPartyHosts: string[]
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
index ae168b319229..d9a243e248b1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
@@ -13,7 +13,6 @@ describe('createTeamFilterStep', () => {
teamId: 1,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
}
it('should enrich message with team context when team is valid', async () => {
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts
index 369d4b60ee82..578400d2c573 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts
@@ -174,7 +174,6 @@ describe('session recording integration', () => {
teamId,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
},
message: {
distinct_id: 'distinct_id',
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
index 74add40add69..a9df07536eb7 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
@@ -185,7 +185,6 @@ describe('session recording encryption integration', () => {
teamId,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
- firstPartyHosts: [],
},
message: {
distinct_id: 'distinct_id',
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index da48dc00bcf9..046a4f0785b7 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8020,7 +8020,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.2.0"
+version = "0.3.0"
dependencies = [
"ahash 0.8.12",
"anyhow",
@@ -8033,6 +8033,7 @@ dependencies = [
"serde",
"serde_json",
"simd-json",
+ "url",
"zstd",
]
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index fef3fa50e23e..4897ca6dc9ed 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -75,12 +75,7 @@ export function initAnonymizer(allow: AllowListsInput): void {
*/
export function anonymizeKafkaPayload(
payload: Buffer,
- contentEncoding?: string | null,
- firstPartyHosts?: string[] | null
+ contentEncoding?: string | null
): Promise<AnonymizeKafkaPayloadResult> {
- return native.anonymizeKafkaPayload(
- payload,
- contentEncoding ?? undefined,
- firstPartyHosts && firstPartyHosts.length > 0 ? JSON.stringify(firstPartyHosts) : undefined
- )
+ return native.anonymizeKafkaPayload(payload, contentEncoding ?? undefined)
}
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index b32ea2c35b95..6540634486c1 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -56,13 +56,6 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
.argument_opt(1)
.and_then(|v| v.downcast::<JsString, _>(&mut cx).ok())
.map(|s| s.value(&mut cx));
- // A present-but-non-string argument must fail loudly (the caller drops the message), not
- // silently disable first-party collapsing; only absent/undefined/null mean "no hosts".
- let first_party_hosts_json: Option<String> = match cx.argument_opt(2) {
- Some(v) if v.is_a::<JsUndefined, _>(&mut cx) || v.is_a::<JsNull, _>(&mut cx) => None,
- Some(v) => Some(v.downcast_or_throw::<JsString, _>(&mut cx)?.value(&mut cx)),
- None => None,
- };
let promise = cx
.task(move || -> TaskOutcome {
// Contain any panic on untrusted input so it fails closed (the caller drops the message)
@@ -74,19 +67,6 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
let allow = guard.as_ref().ok_or_else(|| {
"anonymizer not initialized (call initAnonymizer first)".to_string()
})?;
- // A malformed host list fails closed (message dropped), never silently unscrubbed.
- let first_party_hosts: Vec<String> = match &first_party_hosts_json {
- Some(json) => {
- let hosts: Vec<String> = serde_json::from_str(json)
- .map_err(|e| format!("invalid first-party hosts json: {e}"))?;
- hosts
- .iter()
- .map(|h| h.trim().to_ascii_lowercase())
- .filter(|h| !h.is_empty())
- .collect()
- }
- None => Vec::new(),
- };
let mut payload =
match snapshot::decompress_payload(raw, content_encoding.as_deref()) {
Ok(p) => p,
@@ -96,7 +76,6 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
allow,
&mut payload,
snapshot::AnonymizeOpts::default(),
- first_party_hosts,
) {
Ok(out) => {
let meta = serde_json::to_string(&out.meta)
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 749f1d688f64..6f4a61ded819 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.2.0"
+version = "0.3.0"
edition = "2021"
description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"
license = "MIT"
@@ -27,6 +27,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
serde = { workspace = true }
serde_json = { workspace = true }
simd-json = { version = "0.15", features = ["serde_impl"] }
+url = { workspace = true }
zstd = { workspace = true }
[dev-dependencies]
diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rs
index 0ca4d1b7a56a..5071cf10fbfd 100644
--- a/rust/replay-anonymizer/src/assets.rs
+++ b/rust/replay-anonymizer/src/assets.rs
@@ -9,7 +9,7 @@ use simd_json::borrowed::{Object, Value};
use crate::blur::{blank_image_data_uri, is_image_data_uri};
use crate::context::Ctx;
use crate::json::{as_str, string_value};
-use crate::url::scrub_url_opts;
+use crate::url::scrub_url;
// rrweb inlines rendered pixels (a `toDataURL()` snapshot) into this attribute.
pub const INLINE_IMAGE_ATTR: &str = "rr_dataURL";
@@ -66,9 +66,8 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {
.unwrap_or_else(|| PLACEHOLDER_SRC.to_string());
attrs.insert(Cow::Borrowed(*key), string_value(blurred));
} else {
- // Host-scrubbed too so a CDN host can't leak; stashed under a namespaced attr that won't
- // collide with an app `data-original-*`.
- let scrubbed = scrub_url_opts(ctx, &existing, true).unwrap_or(existing);
+ // Stashed under a namespaced attr that won't collide with an app `data-original-*`.
+ let scrubbed = scrub_url(ctx, &existing).unwrap_or(existing);
attrs.insert(
Cow::Borrowed(*key),
Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),
diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rs
index 7ac47df89c44..1464312306d3 100644
--- a/rust/replay-anonymizer/src/bytewalk.rs
+++ b/rust/replay-anonymizer/src/bytewalk.rs
@@ -24,7 +24,7 @@ use crate::dom::{
use crate::event::{SOURCE_INPUT, SOURCE_MUTATION, TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL};
use crate::scan::{self, Span};
use crate::text::{redact_emails, scrub_text};
-use crate::url::{scrub_url, scrub_url_opts};
+use crate::url::scrub_url;
// rrweb NodeType (mirrors dom.rs).
const NODE_DOCUMENT: u8 = 0;
@@ -901,8 +901,7 @@ impl<'c, 'a> Walker<'c, 'a> {
.unwrap_or_else(|| PLACEHOLDER_SRC.to_string());
scan::write_json_string(&blurred, out);
} else {
- let scrubbed =
- scrub_url_opts(self.ctx, &existing, true).unwrap_or_else(|| existing.into_owned());
+ let scrubbed = scrub_url(self.ctx, &existing).unwrap_or_else(|| existing.into_owned());
scan::write_json_string(PLACEHOLDER_SRC, out);
stashes.push((format!("data-anon-original-{name}"), scrubbed));
}
diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rs
index e25db1f134d5..c7221cdfa16e 100644
--- a/rust/replay-anonymizer/src/context.rs
+++ b/rust/replay-anonymizer/src/context.rs
@@ -18,24 +18,9 @@ use crate::blur::{blur_image_data_uri, pixelate_raw_rgba};
/// fields can't decompress gigabytes serially. Real messages total under 10 MB.
const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;
-/// Scrub context: the allow lists, the first-party host patterns, the cv decompression budget,
-/// and the blur memo.
-///
-/// # Production configuration
-///
-/// Ingestion builds one `Ctx` per Kafka message via [`Ctx::with_first_party_hosts`], passing the
-/// registrable domains derived from the team's recording domains (computed TS-side by
-/// `firstPartyHostPatterns` in `ml-mirror/first-party-hosts.ts`: hostname extracted, `*.`
-/// wildcards stripped, reduced to the registrable domain, lowercased). The URL scrub collapses
-/// matching hosts and their subdomains to `example.com`. [`Ctx::new`] — no first-party hosts —
-/// matches production only for teams with no recording domains configured; an offline consumer
-/// that wants production-equivalent URL scrubbing for a team must pass the same registrable
-/// domains.
+/// Scrub context: the allow lists, the cv decompression budget, and the blur memo.
pub struct Ctx<'a> {
pub allow: &'a AllowLists,
- /// Registrable-domain patterns (computed TS-side from the team's recording domains);
- /// matching hosts and their subdomains collapse to example.com in the URL scrub.
- pub first_party_hosts: Vec<String>,
pub cv_budget: Cell<usize>,
// key: the original data URI (data-image blur), or `raw:{w}x{h}:{base64}` (raw RGBA pixelate).
// value: the blurred result, or `None` when blurring failed (caller falls back to a blank pixel).
@@ -44,13 +29,8 @@ pub struct Ctx<'a> {
impl<'a> Ctx<'a> {
pub fn new(allow: &'a AllowLists) -> Self {
- Self::with_first_party_hosts(allow, Vec::new())
- }
-
- pub fn with_first_party_hosts(allow: &'a AllowLists, first_party_hosts: Vec<String>) -> Self {
Self {
allow,
- first_party_hosts,
cv_budget: Cell::new(CV_MESSAGE_DECOMPRESSION_BUDGET),
blur_cache: RefCell::new(HashMap::new()),
}
diff --git a/rust/replay-anonymizer/src/event.rs b/rust/replay-anonymizer/src/event.rs
index e1bbf30f3402..7e927e1d1694 100644
--- a/rust/replay-anonymizer/src/event.rs
+++ b/rust/replay-anonymizer/src/event.rs
@@ -17,7 +17,7 @@ use crate::json::{
reject_if_too_deep, string_value,
};
use crate::text::scrub_text;
-use crate::url::scrub_url_opts;
+use crate::url::scrub_url;
use crate::value::{scrub_console_plugin, scrub_generic_field, scrub_network_plugin};
// RRWebEventType
@@ -224,14 +224,14 @@ pub fn route_data(
}
}
Some(TYPE_META) => {
- // Meta `href` is the page URL — strip the authority and rewrite the host to example.com.
+ // Meta `href` is the page URL — scrub path/query/fragment, keep the host.
let Some(data) = as_object_mut(data) else {
return Ok(false);
};
let Some(href) = data.get("href").and_then(as_str) else {
return Ok(false);
};
- match scrub_url_opts(ctx, href, true) {
+ match scrub_url(ctx, href) {
Some(v) => {
data.insert(key("href"), string_value(v));
Ok(true)
diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rs
index efbd3e921880..09ef3109bc0f 100644
--- a/rust/replay-anonymizer/src/snapshot.rs
+++ b/rust/replay-anonymizer/src/snapshot.rs
@@ -215,28 +215,26 @@ pub fn anonymize_kafka_payload(
allow: &AllowLists,
payload: &mut [u8],
) -> SResult<AnonymizedMessage> {
- anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default(), Vec::new())
+ anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default())
}
pub fn anonymize_kafka_payload_opts(
allow: &AllowLists,
payload: &mut [u8],
opts: AnonymizeOpts,
- first_party_hosts: Vec<String>,
) -> SResult<AnonymizedMessage> {
- contain_panics(|| anonymize_kafka_payload_opts_impl(allow, payload, opts, first_party_hosts))
+ contain_panics(|| anonymize_kafka_payload_opts_impl(allow, payload, opts))
}
fn anonymize_kafka_payload_opts_impl(
allow: &AllowLists,
payload: &mut [u8],
opts: AnonymizeOpts,
- first_party_hosts: Vec<String>,
) -> SResult<AnonymizedMessage> {
if let Some((distinct_id_span, data_span)) = scan_outer_envelope(payload) {
// Resolve distinct_id to an owned string first — the unescape below rewrites the buffer.
let Ok(distinct_id) = scan::unescape(payload, distinct_id_span) else {
- return anonymize_kafka_payload_via_parse(allow, payload, opts, first_party_hosts);
+ return anonymize_kafka_payload_via_parse(allow, payload, opts);
};
let distinct_id = distinct_id.into_owned();
// Point of no return: the in-place unescape consumes the buffer, so failures past here are
@@ -254,9 +252,9 @@ fn anonymize_kafka_payload_opts_impl(
"invalid utf-8 in data string",
));
}
- return anonymize_snapshot_data_opts(allow, &distinct_id, inner, opts, first_party_hosts);
+ return anonymize_snapshot_data_opts(allow, &distinct_id, inner, opts);
}
- anonymize_kafka_payload_via_parse(allow, payload, opts, first_party_hosts)
+ anonymize_kafka_payload_via_parse(allow, payload, opts)
}
/// Locate the `distinct_id` + `data` string spans by scanning the outer object. `None` means "let
@@ -331,7 +329,6 @@ fn anonymize_kafka_payload_via_parse(
allow: &AllowLists,
payload: &mut [u8],
opts: AnonymizeOpts,
- first_party_hosts: Vec<String>,
) -> SResult<AnonymizedMessage> {
reject_if_too_deep(payload, "kafka payload")
.map_err(|e| Failure::new(FailKind::InvalidJson, e.to_string()))?;
@@ -357,7 +354,7 @@ fn anonymize_kafka_payload_via_parse(
};
// Rare path (the scanner bailed): one owned copy buys the in-place processing a mutable buffer.
let mut data_bytes = data.as_bytes().to_vec();
- anonymize_snapshot_data_opts(allow, distinct_id, &mut data_bytes, opts, first_party_hosts)
+ anonymize_snapshot_data_opts(allow, distinct_id, &mut data_bytes, opts)
}
/// Anonymize the inner `$snapshot_items` event JSON (the payload's `data` string). The buffer is
@@ -368,13 +365,7 @@ pub fn anonymize_snapshot_data(
distinct_id: &str,
inner: &mut [u8],
) -> SResult<AnonymizedMessage> {
- anonymize_snapshot_data_opts(
- allow,
- distinct_id,
- inner,
- AnonymizeOpts::default(),
- Vec::new(),
- )
+ anonymize_snapshot_data_opts(allow, distinct_id, inner, AnonymizeOpts::default())
}
pub fn anonymize_snapshot_data_opts(
@@ -382,13 +373,12 @@ pub fn anonymize_snapshot_data_opts(
distinct_id: &str,
inner: &mut [u8],
opts: AnonymizeOpts,
- first_party_hosts: Vec<String>,
) -> SResult<AnonymizedMessage> {
contain_panics(|| {
// No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines
// past its limit, and every recursive parse below is preceded by a span-local
// reject_if_too_deep — so the common all-walked path never pays a depth scan at all.
- let ctx = Ctx::with_first_party_hosts(allow, first_party_hosts);
+ let ctx = Ctx::new(allow);
match stream_message(&ctx, distinct_id, inner, opts)? {
Some(msg) => Ok(msg),
// Escaped/duplicate envelope keys: only a real parse resolves them, and nothing was
diff --git a/rust/replay-anonymizer/src/url.rs b/rust/replay-anonymizer/src/url.rs
index 620362de8c6a..5c5c09321e0c 100644
--- a/rust/replay-anonymizer/src/url.rs
+++ b/rust/replay-anonymizer/src/url.rs
@@ -1,49 +1,26 @@
//! URL scrub. `None` means "unchanged".
//!
+//! Hostnames identify the customer (the business running PostHog), not an individual user, so
+//! they pass through intact; the parts of a URL that can identify a user or a machine are
+//! scrubbed:
+//!
//! - Numbers (a bare run of digits) are masked to `$` per digit (length-preserving; `$` rather than
//! `#` so it doesn't clash with the fragment separator).
+//! - Host: an IP-address host -> `[ip_address]`; a port -> `:[port]`; domain names are kept.
//! - Path: keep allow-listed segments; a number -> `$$`; anything else -> `[redacted]`.
//! - Query: a param survives only if its key or value is an allow-listed alphanumeric token.
//! - Fragment: kept only if it is an allow-listed alphanumeric token.
//! - Userinfo (`user:pass@`) is always stripped from the authority.
//! - A scheme without slashes (`mailto:`, `tel:`) is kept; the rest is scrubbed as a path.
-//! - With `collapse_host`, or when the host matches the context's first-party host patterns
-//! (the team's recording domains), it additionally drops the port and collapses the host to
-//! `example.com` (keeping a leading allow-listed subdomain label).
+
+use url::Host;
use crate::allow_lists::AllowLists;
use crate::context::Ctx;
pub const URL_ALLOWLIST: &[&str] = &["about:blank", "about:srcdoc"];
-fn strip_port(host: &mut String) {
- if let Some(ci) = host.rfind(':') {
- let after = &host[ci + 1..];
- if !after.is_empty() && after.bytes().all(|b| b.is_ascii_digit()) {
- host.truncate(ci);
- }
- }
-}
-
-fn is_first_party_host(ctx: &Ctx<'_>, host_port: &str) -> bool {
- if ctx.first_party_hosts.is_empty() {
- return false;
- }
- let mut host = host_port.to_ascii_lowercase();
- strip_port(&mut host);
- ctx.first_party_hosts.iter().any(|pattern| {
- host == *pattern
- || (host.len() > pattern.len()
- && host.ends_with(pattern.as_str())
- && host.as_bytes()[host.len() - pattern.len() - 1] == b'.')
- })
-}
-
pub fn scrub_url(ctx: &Ctx<'_>, input: &str) -> Option<String> {
- scrub_url_opts(ctx, input, false)
-}
-
-pub fn scrub_url_opts(ctx: &Ctx<'_>, input: &str, collapse_host: bool) -> Option<String> {
let allow = ctx.allow;
if URL_ALLOWLIST.contains(&input) {
return None;
@@ -71,14 +48,8 @@ pub fn scrub_url_opts(ctx: &Ctx<'_>, input: &str, collapse_host: bool) -> Option
// parse as the authority) must not pass through as if it were a hostname.
out.push_str("[redacted]");
changed = true;
- } else if collapse_host || is_first_party_host(ctx, host_port) {
- let collapsed = collapsed_host(allow, host_port);
- if collapsed != host_port {
- changed = true;
- }
- out.push_str(&collapsed);
} else {
- out.push_str(host_port);
+ changed |= push_host_port(host_port, &mut out);
}
}
@@ -174,25 +145,6 @@ fn scrub_tail(allow: &AllowLists, tail: &str) -> String {
out
}
-// Drop the port and rewrite the host to example.com. Keep a leading *subdomain* label
-// (only when there is one, i.e. >=3 labels) if it's url-allow-listed: `us.test.com` -> `us.example.com`.
-fn collapsed_host(allow: &AllowLists, host_port: &str) -> String {
- let mut host = host_port;
- if let Some(ci) = host.rfind(':') {
- let after = &host[ci + 1..];
- if !after.is_empty() && after.bytes().all(|b| b.is_ascii_digit()) {
- host = &host[..ci];
- }
- }
- let labels: Vec<&str> = host.split('.').collect();
- let first = labels.first().copied().unwrap_or("");
- if labels.len() > 2 && !first.is_empty() && allow.url_contains(first) {
- format!("{first}.example.com")
- } else {
- "example.com".to_string()
- }
-}
-
// Pinned by `tests/fixtures/url-scheme-allowlist.json` (see `tests/parity.rs`).
pub const URL_SCHEME_ALLOWLIST: &[&str] = &[
// Web platform
@@ -319,6 +271,43 @@ fn split_url(s: &str) -> (&str, &str, &str) {
}
}
+// A domain name passes through, but an IP address identifies a machine (possibly an end user's)
+// and a port is infrastructure detail, so both are masked. Returns whether anything was masked.
+// `host_port` has already passed `is_valid_host_port`, so a colon outside brackets can only
+// introduce a port.
+fn push_host_port(host_port: &str, out: &mut String) -> bool {
+ let (host, port) = match host_port.split_once(']') {
+ Some((bracketed, rest)) => (&host_port[..bracketed.len() + 1], rest.strip_prefix(':')),
+ None => match host_port.split_once(':') {
+ Some((host, port)) => (host, Some(port)),
+ None => (host_port, None),
+ },
+ };
+ let mut changed = false;
+ if is_ip_host(host) {
+ out.push_str("[ip_address]");
+ changed = true;
+ } else {
+ out.push_str(host);
+ }
+ if port.is_some() {
+ out.push_str(":[port]");
+ changed = true;
+ }
+ changed
+}
+
+// The WHATWG host parser (what browsers use) decides what is an IP: bracketed IPv6, plus every
+// IPv4 encoding browsers resolve (`192.168.0.1`, hex `0xc0a80101`, octal `0300.0250.0.1`, decimal
+// `3232235777`). Unparseable hosts mask too, incidentally — a browser can't have produced a
+// replay from one, so the case doesn't matter.
+fn is_ip_host(host: &str) -> bool {
+ if host.is_empty() {
+ return false;
+ }
+ !matches!(Host::parse(host), Ok(Host::Domain(_)))
+}
+
// Host or `[ipv6]`, with an optional `:digits` port.
fn is_valid_host_port(host_port: &str) -> bool {
let host = match host_port.split_once(':') {
diff --git a/rust/replay-anonymizer/tests/fixtures/events.json b/rust/replay-anonymizer/tests/fixtures/events.json
index aa5be877c81a..ed88105c2c72 100644
--- a/rust/replay-anonymizer/tests/fixtures/events.json
+++ b/rust/replay-anonymizer/tests/fixtures/events.json
@@ -82,10 +82,10 @@
"expected": { "type": 3, "data": { "source": 5, "id": 1, "text": "hello ******", "isChecked": false } }
},
{
- "name": "meta href strips authority and redacts the path",
+ "name": "meta href strips userinfo, keeps the host, and redacts the path",
"allow": { "text": [], "url": [] },
"event": { "type": 4, "data": { "href": "https://[email protected]/u/42", "width": 100, "height": 200 } },
- "expected": { "type": 4, "data": { "href": "https://example.com/[redacted]/$$", "width": 100, "height": 200 } }
+ "expected": { "type": 4, "data": { "href": "https://app.example.com/[redacted]/$$", "width": 100, "height": 200 } }
},
{
"name": "custom event payload string is scrubbed and email redacted",
@@ -173,7 +173,7 @@
"tagName": "img",
"attributes": {
"src": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/></svg>",
- "data-anon-original-src": "https://example.com/[redacted]",
+ "data-anon-original-src": "https://cdn.example.com/[redacted]",
"alt": "******* *****"
},
"childNodes": []
@@ -568,7 +568,7 @@
"id": 7,
"attributes": {
"rr_src": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/></svg>",
- "data-anon-original-rr_src": "https://example.com/[redacted]/[redacted]/"
+ "data-anon-original-rr_src": "https://widget.example-vendor.co/[redacted]/[redacted]/"
}
}
],
@@ -608,7 +608,7 @@
"tagName": "img",
"attributes": {
"rr_src": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/></svg>",
- "data-anon-original-rr_src": "https://example.com/[redacted]/[redacted]"
+ "data-anon-original-rr_src": "https://cdn.example.com/[redacted]/[redacted]"
},
"childNodes": []
}
diff --git a/rust/replay-anonymizer/tests/fixtures/messages.json b/rust/replay-anonymizer/tests/fixtures/messages.json
index fb0de84cce75..bb1625dfad07 100644
--- a/rust/replay-anonymizer/tests/fixtures/messages.json
+++ b/rust/replay-anonymizer/tests/fixtures/messages.json
@@ -20,7 +20,7 @@
},
"expected": {
"window-a": [
- { "type": 4, "data": { "href": "https://example.com/[redacted]/$$", "width": 100, "height": 200 } },
+ { "type": 4, "data": { "href": "https://app.example.com/[redacted]/$$", "width": 100, "height": 200 } },
{ "type": 3, "data": { "source": 5, "id": 1, "text": "hello ******", "isChecked": false } },
{ "type": 1, "data": {} }
],
diff --git a/rust/replay-anonymizer/tests/fixtures/url.json b/rust/replay-anonymizer/tests/fixtures/url.json
index 08fc7a1df1db..9c974552ee95 100644
--- a/rust/replay-anonymizer/tests/fixtures/url.json
+++ b/rust/replay-anonymizer/tests/fixtures/url.json
@@ -9,7 +9,6 @@
]
},
"input": "https://example.com/users/42/profile",
- "collapseHost": false,
"expected": "https://example.com/users/$$/profile"
},
{
@@ -19,7 +18,6 @@
"url": []
},
"input": "/foo/bar?x=1",
- "collapseHost": false,
"expected": "/[redacted]/[redacted]"
},
{
@@ -31,7 +29,6 @@
]
},
"input": "https://example.com/?page=2&secret=abc",
- "collapseHost": false,
"expected": "https://example.com/?page=$"
},
{
@@ -43,11 +40,10 @@
]
},
"input": "https://example.com/#section",
- "collapseHost": false,
"expected": "https://example.com/#section"
},
{
- "name": "collapseHost drops the port and keeps an allow-listed subdomain",
+ "name": "userinfo is stripped and the port masked; the host passes through",
"allow": {
"text": [],
"url": [
@@ -56,18 +52,43 @@
]
},
"input": "https://user:[email protected]:8080/path",
- "collapseHost": true,
- "expected": "https://us.example.com/path"
+ "expected": "https://us.example.org:[port]/path"
},
{
- "name": "collapseHost collapses a two-label host to example.com",
+ "name": "ipv4 host is masked",
"allow": {
"text": [],
"url": []
},
- "input": "https://example.com/u/42",
- "collapseHost": true,
- "expected": "https://example.com/[redacted]/$$"
+ "input": "http://192.168.0.1/admin",
+ "expected": "http://[ip_address]/[redacted]"
+ },
+ {
+ "name": "bracketed ipv6 host and port are masked",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "https://[2001:db8::1]:8443/status",
+ "expected": "https://[ip_address]:[port]/[redacted]"
+ },
+ {
+ "name": "hex-encoded ipv4 host is masked",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "http://0xc0a80101/admin",
+ "expected": "http://[ip_address]/[redacted]"
+ },
+ {
+ "name": "octal-encoded ipv4 host and port are masked",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "http://0300.0250.0.1:8080/admin",
+ "expected": "http://[ip_address]:[port]/[redacted]"
},
{
"name": "query param with an allow-listed key and empty value survives",
@@ -78,7 +99,6 @@
]
},
"input": "https://example.com/?ok=&x=1",
- "collapseHost": false,
"expected": "https://example.com/?ok="
},
{
@@ -90,7 +110,6 @@
]
},
"input": "https://example.com/?ok&drop",
- "collapseHost": false,
"expected": "https://example.com/?ok"
},
{
@@ -100,7 +119,6 @@
"url": []
},
"input": "https://example.com/#42",
- "collapseHost": false,
"expected": "https://example.com/"
},
{
@@ -110,7 +128,6 @@
"url": []
},
"input": "/a/../b",
- "collapseHost": false,
"expected": "/[redacted]/../[redacted]"
},
{
@@ -125,37 +142,33 @@
]
},
"input": "https://example.com/?a=x&b=y",
- "collapseHost": false,
"expected": "https://example.com/?a=x&b=y"
},
{
- "name": "passthrough url literals survive even with authority scrubbing: about:blank",
+ "name": "passthrough url literals survive: about:blank",
"allow": {
"text": [],
"url": []
},
"input": "about:blank",
- "collapseHost": true,
"expected": "about:blank"
},
{
- "name": "passthrough url literals survive even with authority scrubbing: about:srcdoc",
+ "name": "passthrough url literals survive: about:srcdoc",
"allow": {
"text": [],
"url": []
},
"input": "about:srcdoc",
- "collapseHost": true,
"expected": "about:srcdoc"
},
{
- "name": "userinfo is stripped even without authority scrubbing",
+ "name": "userinfo is stripped from the authority",
"allow": {
"text": [],
"url": []
},
"input": "https://user:[email protected]/settings",
- "collapseHost": false,
"expected": "https://app.example.com/[redacted]"
},
{
@@ -165,7 +178,6 @@
"url": []
},
"input": "tel:+15551234567",
- "collapseHost": false,
"expected": "tel:[redacted]"
},
{
@@ -175,61 +187,8 @@
"url": []
},
"input": "mailto:[email protected]?subject=hello%20there",
- "collapseHost": true,
"expected": "mailto:[redacted]"
},
- {
- "name": "first-party base domain collapses subdomain and port",
- "allow": {
- "text": [],
- "url": []
- },
- "firstPartyHosts": [
- "customer-site.test"
- ],
- "input": "https://app.customer-site.test:5000/settings/billing",
- "collapseHost": false,
- "expected": "https://example.com/[redacted]/[redacted]"
- },
- {
- "name": "first-party base domain collapses the apex host itself",
- "allow": {
- "text": [],
- "url": []
- },
- "firstPartyHosts": [
- "customer-site.test"
- ],
- "input": "https://customer-site.test/pricing",
- "collapseHost": false,
- "expected": "https://example.com/[redacted]"
- },
- {
- "name": "third-party host keeps its hostname despite first-party patterns",
- "allow": {
- "text": [],
- "url": []
- },
- "firstPartyHosts": [
- "customer-site.test"
- ],
- "input": "https://js.payment-vendor.test/v3",
- "collapseHost": false,
- "expected": "https://js.payment-vendor.test/[redacted]"
- },
- {
- "name": "lookalike suffix host is not treated as first-party",
- "allow": {
- "text": [],
- "url": []
- },
- "firstPartyHosts": [
- "customer-site.test"
- ],
- "input": "https://evil-customer-site.test/x",
- "collapseHost": false,
- "expected": "https://evil-customer-site.test/[redacted]"
- },
{
"name": "unknown token before a colon is not treated as a scheme",
"allow": {
@@ -237,7 +196,6 @@
"url": []
},
"input": "john.fakename:secret-chat",
- "collapseHost": false,
"expected": "[redacted]"
},
{
@@ -247,7 +205,6 @@
"url": []
},
"input": "spotify:track:4uLU6hMCjMI75M1A2tKUQC",
- "collapseHost": false,
"expected": "spotify:[redacted]"
},
{
@@ -257,7 +214,6 @@
"url": []
},
"input": "https://user:[email protected]/path",
- "collapseHost": false,
"expected": "https://[redacted]"
},
{
@@ -267,7 +223,6 @@
"url": []
},
"input": "javascript:mail(\"[email protected]\",\"https://tracker.test/1\")",
- "collapseHost": false,
"expected": "javascript:[redacted]//[redacted]/[redacted]"
}
]
diff --git a/rust/replay-anonymizer/tests/parity.rs b/rust/replay-anonymizer/tests/parity.rs
index e225df41a49e..c47a91931d2f 100644
--- a/rust/replay-anonymizer/tests/parity.rs
+++ b/rust/replay-anonymizer/tests/parity.rs
@@ -6,7 +6,7 @@ use std::time::Instant;
use posthog_replay_anonymizer::allow_lists::AllowLists;
use posthog_replay_anonymizer::{
- anonymize_event_str, anonymize_message, context::Ctx, text::scrub_text, url::scrub_url_opts,
+ anonymize_event_str, anonymize_message, context::Ctx, text::scrub_text, url::scrub_url,
url::URL_SCHEME_ALLOWLIST,
};
use serde_json::Value;
@@ -51,18 +51,8 @@ fn url_fixtures() {
let allow = allow_of(&case);
let input = case["input"].as_str().unwrap();
let expected = case["expected"].as_str().unwrap();
- let collapse_host = case["collapseHost"].as_bool().unwrap_or(false);
- let first_party_hosts: Vec<String> = case["firstPartyHosts"]
- .as_array()
- .map(|a| {
- a.iter()
- .filter_map(|v| v.as_str().map(String::from))
- .collect()
- })
- .unwrap_or_default();
- let ctx = Ctx::with_first_party_hosts(&allow, first_party_hosts);
- let actual =
- scrub_url_opts(&ctx, input, collapse_host).unwrap_or_else(|| input.to_string());
+ let ctx = Ctx::new(&allow);
+ let actual = scrub_url(&ctx, input).unwrap_or_else(|| input.to_string());
assert_eq!(actual, expected, "url case: {}", case["name"]);
}
}
diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rs
index 3b6eb296260c..996fdef99276 100644
--- a/rust/replay-anonymizer/tests/snapshot.rs
+++ b/rust/replay-anonymizer/tests/snapshot.rs
@@ -56,7 +56,7 @@ const TS0: f64 = 1_700_000_000_000.0;
fn end_to_end_contract() {
let allow = AllowLists::new(["hello"], Vec::<String>::new());
let inner = snapshot_message(json!([
- // Meta: href scrubbed (authority collapsed), no flags.
+ // Meta: href path scrubbed (host kept), no flags.
{ "type": 4, "timestamp": TS0, "data": { "href": "https://foo.corp.com/path", "width": 1, "height": 1 } },
// Input: text scrubbed; keypress + active.
{ "type": 3, "timestamp": TS0 + 1000.0, "data": { "source": 5, "id": 1, "text": "hello secret", "isChecked": false } },
@@ -78,7 +78,7 @@ fn end_to_end_contract() {
}
assert_eq!(
lines[0][1]["data"]["href"],
- "https://example.com/[redacted]"
+ "https://foo.corp.com/[redacted]"
);
assert_eq!(lines[1][1]["data"]["text"], "hello ******");
assert_eq!(
@@ -116,7 +116,7 @@ fn end_to_end_contract() {
);
assert_eq!(
meta.events[0].href.as_deref(),
- Some("https://example.com/[redacted]"),
+ Some("https://foo.corp.com/[redacted]"),
"href meta must be the post-scrub value"
);
assert_eq!(meta.events[1].href, None);
@@ -365,50 +365,35 @@ impl Rng {
fn assert_stream_matches_tree(allow: &AllowLists, inner_json: &str, label: &str) {
let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner_json})).unwrap();
- // Hosts that appear across the fixture corpus, so first-party collapsing is differentially
- // pinned alongside the no-hosts configuration.
- let host_configs: &[&[&str]] = &[&[], &["example.com", "example-vendor.co"]];
- for hosts in host_configs {
- let hosts: Vec<String> = hosts.iter().map(|h| h.to_string()).collect();
- let ctx = Ctx::with_first_party_hosts(allow, hosts.clone());
- let tree = anonymize_via_tree(&ctx, "d", inner_json.as_bytes());
-
- // Both scrub engines are pinned: the parse-free byte walk (with its per-event fallbacks)
- // and the simd path.
- for byte_walk in [true, false] {
- let fp = !hosts.is_empty();
- let mut bytes = payload.as_bytes().to_vec();
- let stream = anonymize_kafka_payload_opts(
- allow,
- &mut bytes,
- AnonymizeOpts { byte_walk },
- hosts.clone(),
- );
- match (&stream, &tree) {
- (Ok(s), Ok(t)) => {
- let s_lines = parse_lines(&s.lines);
- let t_lines = parse_lines(&t.lines);
- assert_eq!(
- s_lines, t_lines,
- "lines diverged (walk={byte_walk} fp={fp}): {label}"
- );
- assert_eq!(
- s.meta, t.meta,
- "meta diverged (walk={byte_walk} fp={fp}): {label}"
- );
- }
- (Err(s), Err(t)) => {
- assert_eq!(
- s.kind, t.kind,
- "failure kind diverged (walk={byte_walk} fp={fp}): {label}"
- );
- }
- (s, t) => panic!(
- "outcome diverged (walk={byte_walk} fp={fp}) for {label}: stream={:?} tree={:?}",
- s.as_ref().map(|m| parse_lines(&m.lines)),
- t.as_ref().map(|m| parse_lines(&m.lines)),
- ),
+ let ctx = Ctx::new(allow);
+ let tree = anonymize_via_tree(&ctx, "d", inner_json.as_bytes());
+
+ // Both scrub engines are pinned: the parse-free byte walk (with its per-event fallbacks)
+ // and the simd path.
+ for byte_walk in [true, false] {
+ let mut bytes = payload.as_bytes().to_vec();
+ let stream = anonymize_kafka_payload_opts(allow, &mut bytes, AnonymizeOpts { byte_walk });
+ match (&stream, &tree) {
+ (Ok(s), Ok(t)) => {
+ let s_lines = parse_lines(&s.lines);
+ let t_lines = parse_lines(&t.lines);
+ assert_eq!(
+ s_lines, t_lines,
+ "lines diverged (walk={byte_walk}): {label}"
+ );
+ assert_eq!(s.meta, t.meta, "meta diverged (walk={byte_walk}): {label}");
+ }
+ (Err(s), Err(t)) => {
+ assert_eq!(
+ s.kind, t.kind,
+ "failure kind diverged (walk={byte_walk}): {label}"
+ );
}
+ (s, t) => panic!(
+ "outcome diverged (walk={byte_walk}) for {label}: stream={:?} tree={:?}",
+ s.as_ref().map(|m| parse_lines(&m.lines)),
+ t.as_ref().map(|m| parse_lines(&m.lines)),
+ ),
}
}
}