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.

fix(session-replay): url-scrub rr_src attributes in anonymizer (#68858)

Robbie7120e0f4ac69
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 1928b508943e..8f0003b96d3e 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,6 +9,7 @@ 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/anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
index fb294a772138..e1765f46aeba 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
@@ -6,6 +6,7 @@ import { ParsedMessageData } from './kafka/types'
describe('anonymize-step', () => {
const step = createAnonymizeStep({ scrubContext: { allow: defaultAllowLists() } })
+ const team = { teamId: 1, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true, firstPartyHosts: [] }
const parsedMessageWith = (eventsByWindowId: Record<string, any[]>): ParsedMessageData =>
({ eventsByWindowId }) as unknown as ParsedMessageData
@@ -16,7 +17,7 @@ describe('anonymize-step', () => {
win2: [{ type: 4, timestamp: 2, data: { href: 'https://example.com/user/abc/edit', width: 1, height: 1 } }],
})
- const result = await step({ parsedMessage })
+ const result = await step({ parsedMessage, team })
expect(result.type).toBe(PipelineResultType.OK)
expect((parsedMessage.eventsByWindowId.win1[0] as any).data.text).toBe('Hello **********')
@@ -49,7 +50,7 @@ describe('anonymize-step', () => {
],
})
- await step({ parsedMessage })
+ await step({ parsedMessage, team })
const src = (parsedMessage.eventsByWindowId.win1[0] as any).data.node.childNodes[0].attributes.src
// Blurred into a fresh PNG, not left as the placeholder or the original.
@@ -62,7 +63,7 @@ describe('anonymize-step', () => {
win1: [{ type: 3, timestamp: 1, data: { source: 1, positions: [] } }],
})
- const result = await step({ parsedMessage })
+ const result = await step({ parsedMessage, team })
expect(result.type).toBe(PipelineResultType.OK)
expect((parsedMessage.eventsByWindowId.win1[0] as any).data.source).toBe(1)
@@ -74,7 +75,7 @@ describe('anonymize-step', () => {
win1: [{ type: 2, timestamp: 1, cv: '2024-10', data: 'not-Ā-gzip' }],
})
- const result = await step({ parsedMessage })
+ const result = await step({ parsedMessage, team })
expect(result.type).toBe(PipelineResultType.DROP)
expect(result.type === PipelineResultType.DROP && result.reason).toBe('anonymize_failed')
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
index 62ad91f20434..90a5fcfb22b6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
@@ -4,9 +4,11 @@ import { ProcessingStep } from '~/ingestion/framework/steps'
import { anonymizeParsedMessage } from './anonymize/anonymize-event'
import { ScrubContext } from './anonymize/config'
import { ParsedMessageData } from './kafka/types'
+import { TeamForReplay } from './shared/teams/types'
export interface AnonymizeStepInput {
parsedMessage: ParsedMessageData
+ team: TeamForReplay
}
export interface AnonymizeStepConfig {
@@ -22,7 +24,11 @@ export function createAnonymizeStep<T extends AnonymizeStepInput>(config: Anonym
const { scrubContext } = config
return async function anonymizeStep(input) {
- const { failed } = await anonymizeParsedMessage(scrubContext, input.parsedMessage)
+ const teamContext: ScrubContext = {
+ ...scrubContext,
+ firstPartyHosts: input.team.firstPartyHosts,
+ }
+ const { failed } = await anonymizeParsedMessage(teamContext, input.parsedMessage)
if (failed) {
return drop('anonymize_failed')
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
index e56a79b2f3e1..d3f98ed7a9c9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
@@ -128,7 +128,7 @@ function routeEvent(ctx: ScrubContext, event: Record<string, unknown>): boolean
if (!isObject(data) || typeof data.href !== 'string') {
return false
}
- const r = scrubUrl(ctx, data.href, { scrubAuthority: true })
+ const r = scrubUrl(ctx, data.href, { collapseHost: true })
if (r.changed) {
data.href = r.value
return true
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
index d7dab2a24aef..1c95bc6eb4bb 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
@@ -10,7 +10,7 @@ export const INLINE_IMAGE_ATTR = 'rr_dataURL'
export const PLACEHOLDER_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>"
-export const MEDIA_SRC_ATTRS = ['src', 'srcset', 'href', 'xlink:href', 'poster']
+export const MEDIA_SRC_ATTRS = ['src', 'rr_src', 'srcset', 'href', 'xlink:href', 'poster']
export function isMediaTag(tag: string): boolean {
switch (tag.toLowerCase()) {
@@ -74,7 +74,7 @@ export function applyBlur(ctx: ScrubContext, attrs: Record<string, unknown>): vo
} else {
// Stash the scrubbed original under a namespaced attr (won't collide with app
// `data-original-*`), host-scrubbed too so the CDN host can't leak.
- const scrubbed = scrubUrl(ctx, existing, { scrubAuthority: true })
+ const scrubbed = scrubUrl(ctx, existing, { collapseHost: true })
attrs[key] = PLACEHOLDER_SRC
attrs[`data-anon-original-${key}`] = scrubbed.changed ? scrubbed.value : existing
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
index 12de1e7be1b4..233d99a05b45 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
@@ -20,6 +20,7 @@ export interface ScrubTiming {
/** Per-scrub context: the active allow lists plus tunables read by the scrubbers. */
export interface ScrubContext {
allow: AllowLists
+ firstPartyHosts?: string[]
/** Optional collector for deferred image-blur jobs (see {@link BlurJob}). */
blurJobs?: BlurJob[]
/** Optional per-Kafka-message memo shared across those jobs so identical images blur once (see {@link BlurCache}). */
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
index 0c3bd671c369..a1f73e75c546 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
@@ -54,6 +54,23 @@ describe('anonymize/cv', () => {
expect(outTexts[0].value).toBe('Hello **********')
})
+ it('round-trips a cv-compressed Mutation and media-scrubs an rr_src attribute sub-field', () => {
+ const leakUrl =
+ 'https://widget.example-vendor.co/v2/app/?widgetToken=eyJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ1c2VyX2Zha2UxMjMifQ.fakesignature&refreshToken=FakeRefreshTok3nValue000&user=%7B%22email%22%3A%22john.fakename%40example.com%22%7D'
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ cv: 'v2',
+ data: { source: 0, attributes: compress([{ id: 7, attributes: { rr_src: leakUrl } }]) },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ const outAttrs = decompress(event.data.attributes)[0].attributes
+ expect(outAttrs.rr_src).toMatch(/^data:image\/svg\+xml/)
+ for (const secret of ['fakesignature', 'FakeRefreshTok3nValue000', 'john.fakename']) {
+ expect(JSON.stringify(outAttrs)).not.toContain(secret)
+ }
+ })
+
it('scrubs a cv Mutation whose sub-fields are already decompressed arrays', () => {
// Some producers/exporters emit cv events with plain-array sub-fields.
// These must still be scrubbed (in place), not skipped as "absent".
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
index 995c78a05e82..83efc00c4923 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
@@ -224,6 +224,7 @@ function isUrlAttr(name: string): boolean {
switch (name) {
case 'href':
case 'src':
+ case 'rr_src':
case 'srcset':
case 'action':
case 'formaction':
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
index 68da7e45f535..9dbc71fabcd5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
@@ -9,7 +9,7 @@ import { AllowLists } from './allow-lists'
import { anonymizeEvent } from './anonymize-event'
import { ScrubContext } from './config'
import { scrubText } from './text'
-import { scrubUrl } from './url'
+import { URL_SCHEME_ALLOWLIST, scrubUrl } from './url'
// shared fixtures to guarantee identical behaviour between implementations
const FIXTURE_DIR = path.resolve(__dirname, '../../../../../../rust/replay-anonymizer-node/tests/fixtures')
@@ -25,7 +25,8 @@ interface TextCase {
expected: string
}
interface UrlCase extends TextCase {
- scrubAuthority?: boolean
+ collapseHost?: boolean
+ firstPartyHosts?: string[]
}
interface EventCase {
name: string
@@ -82,7 +83,8 @@ describe('anonymize shared fixtures', () => {
})
test.each(urlCases.map((c) => [c.name, c] as const))('url: %s', (_name, c) => {
- expect(scrubUrl(ctxOf(c.allow), c.input, { scrubAuthority: c.scrubAuthority }).value).toEqual(c.expected)
+ const ctx = { ...ctxOf(c.allow), firstPartyHosts: c.firstPartyHosts }
+ expect(scrubUrl(ctx, c.input, { collapseHost: c.collapseHost }).value).toEqual(c.expected)
})
test.each(eventCases.map((c) => [c.name, c] as const))('event: %s', (_name, c) => {
@@ -94,6 +96,11 @@ describe('anonymize shared fixtures', () => {
test.each(messageCases.map((c) => [c.name, c] as const))('message: %s', (_name, c) => {
expect(anonymizeMessageTs(c.allow, c.message)).toEqual(c.expected)
})
+
+ // The rust constant is checked against the same fixture, so the two lists cannot drift.
+ test('URL_SCHEME_ALLOWLIST matches the shared fixture', () => {
+ expect([...URL_SCHEME_ALLOWLIST].sort()).toEqual(load<string>('url-scheme-allowlist.json'))
+ })
})
const describeAddon = rustAddon ? describe : describe.skip
@@ -163,6 +170,36 @@ describe('anonymize 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.
@@ -199,6 +236,35 @@ describe('anonymize shared fixtures', () => {
expect(decoded.node.childNodes[0].textContent).toBe('keep ******')
})
+ it('media-scrubs an rr_src attribute inside a cv mutation sub-field', async () => {
+ const attrMutation = {
+ type: 3,
+ cv: '2024-10',
+ data: {
+ source: 0,
+ attributes: gzipLatin1(
+ JSON.stringify([
+ {
+ id: 7,
+ attributes: {
+ rr_src: 'https://widget.example-vendor.co/v2/app/?refreshToken=FakeRefreshTok3nValue000',
+ },
+ },
+ ])
+ ),
+ },
+ }
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [attrMutation]))
+ expect(result.failed).toBe(false)
+ const line = parseLines(result.lines!)[0] as [string, { data: { attributes: string } }]
+ 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]/'
+ )
+ })
+
it('scrubs a cv mutation sub-field and re-emits a decodable zstd payload', async () => {
rustAddon!.initAnonymizer({ text: ['keep'], url: [] })
const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [mutation]))
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
index 6c62f847928f..bf54e9f1f68b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
@@ -1,6 +1,6 @@
import { AllowLists } from './allow-lists'
import { defaultAllowLists } from './default-dict'
-import { scrubUrl } from './url'
+import { firstPartyHostPatterns, scrubUrl } from './url'
describe('anonymize/url', () => {
const allow = defaultAllowLists()
@@ -35,9 +35,9 @@ describe('anonymize/url', () => {
expect(scrub('https://example.com/api/v1/users')).toBe('https://example.com/api/v1/users')
})
- describe('scrubAuthority (Meta only)', () => {
+ describe('collapseHost (Meta only)', () => {
const ctx = { allow: new AllowLists([], ['us', 'api', 'v1', 'users', 'profile']) }
- const sa = (i: string): string => scrubUrl(ctx, i, { scrubAuthority: true }).value
+ const sa = (i: string): string => scrubUrl(ctx, i, { collapseHost: true }).value
it('keeps an allow-listed subdomain and rewrites the rest to example.com', () => {
expect(sa('https://us.website.com/api/v1/users/42/profile')).toBe(
@@ -98,4 +98,24 @@ describe('anonymize/url', () => {
const numCtx = { allow: new AllowLists([], ['users']) }
expect(scrubUrl(numCtx, 'https://example.com/users/2/x').value).toBe('https://example.com/users/$/[redacted]')
})
+
+ 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/anonymize/url.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
index 2c314765067e..09451f809e25 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
@@ -8,18 +8,26 @@
* counts as denied for survival, so `id=42` is dropped while `page=2` → `page=$`. When a param
* survives, each side renders independently: allow-listed → kept, number → `$$`, denied → `[key]`/`[value]`.
* - Fragment: kept only if it is an allow-listed alphanumeric token; numbers and everything else dropped.
- * - With `{ scrubAuthority: true }` it strips userinfo/port and
- * collapses the host to `example.com` (keeping a leading allow-listed subdomain label).
+ * - 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 `{ collapseHost: true }`, 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).
*/
+import { parse as parseHostname } from 'tldts'
+
import { ScrubContext } from './config'
import { ScrubResult } from './text'
export interface UrlScrubOptions {
- scrubAuthority?: boolean
+ collapseHost?: boolean
}
+export const URL_ALLOWLIST = ['about:blank', 'about:srcdoc']
+
const SIMPLE = /^[A-Za-z0-9]*$/ // 100% alphanumeric (empty allowed)
const NUMERIC = /^[0-9]+$/ // a bare number
+const HOST_PORT = /^(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]*)(:\d+)?$/ // host or [ipv6], optional port
const maskNumber = (n: string): string => '$'.repeat(n.length) // `$`, not `#` (the fragment separator)
@@ -35,6 +43,9 @@ function renderToken(ctx: ScrubContext, t: string): string | null {
}
export function scrubUrl(ctx: ScrubContext, input: string, opts?: UrlScrubOptions): ScrubResult {
+ if (URL_ALLOWLIST.includes(input)) {
+ return { value: input, changed: false }
+ }
const tailIdx = input.search(/[?#]/)
const base = tailIdx === -1 ? input : input.slice(0, tailIdx)
const tail = tailIdx === -1 ? '' : input.slice(tailIdx) // starts with ? or #
@@ -43,14 +54,24 @@ export function scrubUrl(ctx: ScrubContext, input: string, opts?: UrlScrubOption
const { scheme, authority, path } = splitUrl(base)
let out = scheme
if (authority) {
- if (opts?.scrubAuthority) {
- const scrubbed = scrubHost(ctx, authority)
- if (scrubbed !== authority) {
+ const at = authority.lastIndexOf('@')
+ if (at !== -1) {
+ changed = true
+ }
+ const hostPort = authority.slice(at + 1)
+ if (!HOST_PORT.test(hostPort)) {
+ // A structurally invalid "host" (e.g. an unencoded `?` in userinfo makes `user:pa`
+ // parse as the authority) must not pass through as if it were a hostname.
+ out += '[redacted]'
+ changed = true
+ } else if (opts?.collapseHost || isFirstPartyHost(ctx, hostPort)) {
+ const collapsed = collapsedHost(ctx, hostPort)
+ if (collapsed !== hostPort) {
changed = true
}
- out += scrubbed
+ out += collapsed
} else {
- out += authority
+ out += hostPort
}
}
@@ -131,29 +152,164 @@ function scrubTail(ctx: ScrubContext, tail: string): string {
return out
}
-// Strip userinfo + port and rewrite the host to example.com. Keep a leading *subdomain* label
+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
+}
+
+function isFirstPartyHost(ctx: ScrubContext, hostPort: string): boolean {
+ const patterns = ctx.firstPartyHosts
+ if (!patterns || patterns.length === 0) {
+ return false
+ }
+ const host = hostPort.replace(/:\d+$/, '').toLowerCase()
+ return patterns.some((pattern) => host === pattern || host.endsWith(`.${pattern}`))
+}
+
+// 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`.
-function scrubHost(ctx: ScrubContext, authority: string): string {
- const at = authority.lastIndexOf('@')
- let host = at !== -1 ? authority.slice(at + 1) : authority
- host = host.replace(/:\d+$/, '') // drop :port
+function collapsedHost(ctx: ScrubContext, hostPort: string): string {
+ const host = hostPort.replace(/:\d+$/, '')
const labels = host.split('.')
const first = labels[0] ?? ''
return labels.length > 2 && first && ctx.allow.urlContains(first) ? `${first}.example.com` : 'example.com'
}
+const SCHEME_NO_SLASHES = /^[A-Za-z][A-Za-z0-9+.-]*:/ // RFC 3986 scheme, e.g. `mailto:`, `tel:`
+
+export const URL_SCHEME_ALLOWLIST = new Set([
+ // Web platform
+ 'about',
+ 'blob',
+ 'data',
+ 'file',
+ 'ftp',
+ 'geo',
+ 'javascript',
+ 'magnet',
+ 'mailto',
+ 'sms',
+ 'tel',
+ 'urn',
+ 'ws',
+ 'wss',
+ // Microsoft
+ 'ms-access',
+ 'ms-excel',
+ 'ms-outlook',
+ 'ms-powerpoint',
+ 'ms-project',
+ 'ms-publisher',
+ 'ms-visio',
+ 'ms-word',
+ 'msteams',
+ 'onenote',
+ 'sip',
+ 'sips',
+ 'skype',
+ // Google
+ 'comgooglemaps',
+ 'googlechrome',
+ 'googlegmail',
+ 'googlemaps',
+ // Apple
+ 'facetime',
+ 'facetime-audio',
+ 'itms',
+ 'itms-apps',
+ 'maps',
+ 'music',
+ 'shortcuts',
+ // Chat and social
+ 'bluesky',
+ 'callto',
+ 'discord',
+ 'fb',
+ 'fb-messenger',
+ 'instagram',
+ 'irc',
+ 'line',
+ 'linkedin',
+ 'matrix',
+ 'reddit',
+ 'sgnl',
+ 'slack',
+ 'snapchat',
+ 'telegram',
+ 'tg',
+ 'tiktok',
+ 'twitter',
+ 'viber',
+ 'wechat',
+ 'weixin',
+ 'whatsapp',
+ 'xmpp',
+ // Media, payments, and tools
+ 'bitcoin',
+ 'bittorrent',
+ 'figma',
+ 'notion',
+ 'obsidian',
+ 'spotify',
+ 'steam',
+ 'vscode',
+ 'zoommtg',
+ 'zoomus',
+])
+
+const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/ // RFC 3986 scheme body
+
// Split into scheme prefix (incl. `://` or `//`), authority (`[userinfo@]host[:port]`), and path.
function splitUrl(s: string): { scheme: string; authority: string; path: string } {
let scheme = ''
let rest = s
const schemeEnd = s.indexOf('://')
- if (schemeEnd !== -1) {
+ if (schemeEnd !== -1 && VALID_SCHEME.test(s.slice(0, schemeEnd))) {
scheme = s.slice(0, schemeEnd + 3)
rest = s.slice(schemeEnd + 3)
} else if (s.startsWith('//')) {
scheme = '//'
rest = s.slice(2)
} else {
+ // Free text before a colon (or before an embedded `://`) must not pass through as a
+ // "scheme"; only allowlisted schemes survive, and only in the slashless form.
+ const m = SCHEME_NO_SLASHES.exec(s)
+ if (m && URL_SCHEME_ALLOWLIST.has(m[0].slice(0, -1).toLowerCase())) {
+ return { scheme: m[0], authority: '', path: s.slice(m[0].length) }
+ }
return { scheme: '', authority: '', path: s } // relative URL: all path
}
const pathOff = rest.indexOf('/')
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 311d0f0076f7..733adb0126d6 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
@@ -67,6 +67,7 @@ describe('ml-mirror-pipeline', () => {
teamId: 1,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn,
+ firstPartyHosts: [],
})
beforeEach(() => {
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 57068bdc2144..fe305eae8267 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,14 +14,21 @@ 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) =>
- mockAnonymizeKafkaPayload(payload, contentEncoding),
+ anonymizeKafkaPayload: (payload: Buffer, contentEncoding?: string | null, firstPartyHosts?: string[] | null) =>
+ mockAnonymizeKafkaPayload(payload, contentEncoding, firstPartyHosts),
}))
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',
@@ -68,7 +75,7 @@ describe('createParseAndAnonymizeMessageStep', () => {
it('assembles a pre-serialized ParsedMessageData from the addon output', async () => {
addonSuccess()
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result.type).toBe(PipelineResultType.OK)
const parsed = (result as any).value.parsedMessage
@@ -90,6 +97,7 @@ 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() },
})
@@ -101,15 +109,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 })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null)
+ await step({ message: kafkaMessage(zipped), headers, team })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null, team.firstPartyHosts)
mockAnonymizeKafkaPayload.mockClear()
addonSuccess()
const lz4Message = kafkaMessage(raw)
lz4Message.headers = [{ 'content-encoding': Buffer.from('lz4') }]
- await step({ message: lz4Message, headers })
- expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4')
+ await step({ message: lz4Message, headers, team })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4', team.firstPartyHosts)
})
test.each([
@@ -127,21 +135,21 @@ describe('createParseAndAnonymizeMessageStep', () => {
lines: null,
meta: null,
})
- const result = await step({ message: kafkaMessage(), headers })
+ const result = await step({ message: kafkaMessage(), headers, team })
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 })
+ const result = await step({ message: kafkaMessage(), headers, team })
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 })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'message_timestamp_diff_too_large' })
})
@@ -150,12 +158,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 })
+ const result = await step({ message: kafkaMessage(), headers, team })
expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason })
})
it('dlqs when the message value is empty', async () => {
- const result = await step({ message: kafkaMessage(null), headers })
+ const result = await step({ message: kafkaMessage(null), headers, team })
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 e1663a1a6b62..caac1100288e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
@@ -11,6 +11,7 @@ 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,10 +45,9 @@ 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>(): ProcessingStep<
- T,
- T & ParseMessageStepOutput
-> {
+export function createParseAndAnonymizeMessageStep<
+ T extends ParseMessageStepInput & { team: TeamForReplay },
+>(): ProcessingStep<T, T & ParseMessageStepOutput> {
return async function parseAndAnonymizeMessageStep(input) {
const { message, headers } = input
@@ -65,7 +65,11 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp
const t0 = performance.now()
let result
try {
- result = await getRustAnonymizer().anonymizeKafkaPayload(message.value, contentEncoding)
+ result = await getRustAnonymizer().anonymizeKafkaPayload(
+ message.value,
+ contentEncoding,
+ input.team.firstPartyHosts
+ )
} 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 400c8dbb2117..a9956a299c66 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
@@ -24,6 +24,7 @@ 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.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
index e167f731caf9..509d0e15275d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
@@ -109,6 +109,7 @@ 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 6b2dc8687a29..c5a57db51110 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
@@ -290,6 +290,7 @@ 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 fe6d232bc825..07ece787cfd0 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,6 +48,7 @@ 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 95c1bc53d7d9..739e108beb0a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
@@ -1,6 +1,7 @@
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/anonymize/url'
import { RetentionPeriod, isValidRetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'
import { Team, TeamId } from '~/types'
@@ -67,6 +68,7 @@ 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,
@@ -76,6 +78,7 @@ 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
@@ -91,6 +94,7 @@ 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 312149baf425..c0615c941b75 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
@@ -5,4 +5,6 @@ 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 d9a243e248b1..ae168b319229 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
@@ -13,6 +13,7 @@ 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 b9ae11c5a680..93c3f8d65b4b 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
@@ -192,6 +192,7 @@ 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 d066f9850b48..2d57f6100307 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
@@ -180,6 +180,7 @@ describe('session recording encryption integration', () => {
teamId,
consoleLogIngestionEnabled: false,
aiTrainingOptedIn: true,
+ firstPartyHosts: [],
},
message: {
distinct_id: 'distinct_id',
diff --git a/rust/replay-anonymizer-node/src/assets.rs b/rust/replay-anonymizer-node/src/assets.rs
index 9e6f696ed1ca..2470f7272f82 100644
--- a/rust/replay-anonymizer-node/src/assets.rs
+++ b/rust/replay-anonymizer-node/src/assets.rs
@@ -16,7 +16,7 @@ pub const INLINE_IMAGE_ATTR: &str = "rr_dataURL";
pub const PLACEHOLDER_SRC: &str = "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>";
-pub const MEDIA_SRC_ATTRS: &[&str] = &["src", "srcset", "href", "xlink:href", "poster"];
+pub const MEDIA_SRC_ATTRS: &[&str] = &["src", "rr_src", "srcset", "href", "xlink:href", "poster"];
pub fn is_media_tag(tag: &str) -> bool {
matches!(
@@ -68,7 +68,7 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {
} 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.allow, &existing, true).unwrap_or(existing);
+ let scrubbed = scrub_url_opts(ctx, &existing, true).unwrap_or(existing);
attrs.insert(
Cow::Borrowed(*key),
Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),
diff --git a/rust/replay-anonymizer-node/src/bytewalk.rs b/rust/replay-anonymizer-node/src/bytewalk.rs
index 0cfd00e6b418..80949bb3d973 100644
--- a/rust/replay-anonymizer-node/src/bytewalk.rs
+++ b/rust/replay-anonymizer-node/src/bytewalk.rs
@@ -840,7 +840,7 @@ impl<'c, 'a> Walker<'c, 'a> {
return w.scrub_string_value(vstart, out, |w, s| css::rewrite(w.ctx, s));
}
if is_url_attr(name) {
- return w.scrub_string_value(vstart, out, |w, s| scrub_url(w.ctx.allow, s));
+ return w.scrub_string_value(vstart, out, |w, s| scrub_url(w.ctx, s));
}
if is_user_text_attr(name) {
return w.scrub_string_value(vstart, out, |w, s| scrub_text(w.ctx.allow, s));
@@ -897,8 +897,8 @@ 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.allow, &existing, true)
- .unwrap_or_else(|| existing.into_owned());
+ let scrubbed =
+ scrub_url_opts(self.ctx, &existing, true).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-node/src/canvas.rs b/rust/replay-anonymizer-node/src/canvas.rs
index 492b4e3ebed1..42b3fe14be58 100644
--- a/rust/replay-anonymizer-node/src/canvas.rs
+++ b/rust/replay-anonymizer-node/src/canvas.rs
@@ -107,7 +107,7 @@ fn blur_canvas_arg(ctx: &Ctx<'_>, value: &mut Value<'_>) -> bool {
obj.insert(key("src"), string_value(b));
return true;
}
- return match scrub_url(ctx.allow, &src) {
+ return match scrub_url(ctx, &src) {
Some(v) => {
obj.insert(key("src"), string_value(v));
true
diff --git a/rust/replay-anonymizer-node/src/context.rs b/rust/replay-anonymizer-node/src/context.rs
index 6ca1a3297972..8bb7f06e0a34 100644
--- a/rust/replay-anonymizer-node/src/context.rs
+++ b/rust/replay-anonymizer-node/src/context.rs
@@ -20,6 +20,9 @@ const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;
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).
@@ -28,8 +31,13 @@ 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-node/src/dom.rs b/rust/replay-anonymizer-node/src/dom.rs
index 860b1cd25c5d..0c8d526a0a83 100644
--- a/rust/replay-anonymizer-node/src/dom.rs
+++ b/rust/replay-anonymizer-node/src/dom.rs
@@ -219,7 +219,7 @@ fn scrub_attrs(ctx: &Ctx<'_>, attrs: &mut Object<'_>, kind: TagKind) -> bool {
continue;
};
let result = if is_url_attr(name) {
- scrub_url(ctx.allow, current)
+ scrub_url(ctx, current)
} else if is_user_text_attr(name) {
scrub_text(ctx.allow, current)
} else if is_data_attr(name) {
@@ -283,6 +283,7 @@ pub(crate) fn is_url_attr(name: &str) -> bool {
name,
"href"
| "src"
+ | "rr_src"
| "srcset"
| "action"
| "formaction"
diff --git a/rust/replay-anonymizer-node/src/event.rs b/rust/replay-anonymizer-node/src/event.rs
index 3cff598c0d37..e447cb5db38b 100644
--- a/rust/replay-anonymizer-node/src/event.rs
+++ b/rust/replay-anonymizer-node/src/event.rs
@@ -139,7 +139,7 @@ pub fn route_data(
let Some(href) = data.get("href").and_then(as_str) else {
return Ok(false);
};
- match scrub_url_opts(ctx.allow, href, true) {
+ match scrub_url_opts(ctx, href, true) {
Some(v) => {
data.insert(key("href"), string_value(v));
Ok(true)
@@ -148,7 +148,7 @@ pub fn route_data(
}
}
Some(TYPE_CUSTOM) => match as_object_mut(data) {
- Some(data) => Ok(scrub_generic_field(ctx.allow, data, "payload")),
+ Some(data) => Ok(scrub_generic_field(ctx, data, "payload")),
None => Ok(false),
},
Some(TYPE_PLUGIN) => {
@@ -157,9 +157,9 @@ pub fn route_data(
};
let plugin = data.get("plugin").and_then(as_str).map(str::to_string);
Ok(match plugin.as_deref() {
- Some(NETWORK_PLUGIN) => scrub_network_plugin(ctx.allow, data, "payload"),
- Some(CONSOLE_PLUGIN) => scrub_console_plugin(ctx.allow, data, "payload"),
- _ => scrub_generic_field(ctx.allow, data, "payload"),
+ Some(NETWORK_PLUGIN) => scrub_network_plugin(ctx, data, "payload"),
+ Some(CONSOLE_PLUGIN) => scrub_console_plugin(ctx, data, "payload"),
+ _ => scrub_generic_field(ctx, data, "payload"),
})
}
// DomContentLoaded, Load, unknown types: pass-through.
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index 4897ca6dc9ed..fef3fa50e23e 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -75,7 +75,12 @@ export function initAnonymizer(allow: AllowListsInput): void {
*/
export function anonymizeKafkaPayload(
payload: Buffer,
- contentEncoding?: string | null
+ contentEncoding?: string | null,
+ firstPartyHosts?: string[] | null
): Promise<AnonymizeKafkaPayloadResult> {
- return native.anonymizeKafkaPayload(payload, contentEncoding ?? undefined)
+ return native.anonymizeKafkaPayload(
+ payload,
+ contentEncoding ?? undefined,
+ firstPartyHosts && firstPartyHosts.length > 0 ? JSON.stringify(firstPartyHosts) : undefined
+ )
}
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index b284e2e9ee88..bdbca8483770 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -119,6 +119,13 @@ 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)
@@ -130,12 +137,30 @@ 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,
Err(f) => return Ok(Err((f.kind.reason(), f.detail))),
};
- match snapshot::anonymize_kafka_payload(allow, &mut payload) {
+ match snapshot::anonymize_kafka_payload_opts(
+ allow,
+ &mut payload,
+ snapshot::AnonymizeOpts::default(),
+ first_party_hosts,
+ ) {
Ok(out) => {
let meta = serde_json::to_string(&out.meta)
.map_err(|e| format!("serialize meta: {e}"))?;
diff --git a/rust/replay-anonymizer-node/src/snapshot.rs b/rust/replay-anonymizer-node/src/snapshot.rs
index 58f6b9bac35a..0a5362306ac3 100644
--- a/rust/replay-anonymizer-node/src/snapshot.rs
+++ b/rust/replay-anonymizer-node/src/snapshot.rs
@@ -217,18 +217,19 @@ pub fn anonymize_kafka_payload(
allow: &AllowLists,
payload: &mut [u8],
) -> SResult<AnonymizedMessage> {
- anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default())
+ anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default(), Vec::new())
}
pub fn anonymize_kafka_payload_opts(
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);
+ return anonymize_kafka_payload_via_parse(allow, payload, opts, first_party_hosts);
};
let distinct_id = distinct_id.into_owned();
// Point of no return: the in-place unescape consumes the buffer, so failures past here are
@@ -246,9 +247,9 @@ pub fn anonymize_kafka_payload_opts(
"invalid utf-8 in data string",
));
}
- return anonymize_snapshot_data_opts(allow, &distinct_id, inner, opts);
+ return anonymize_snapshot_data_opts(allow, &distinct_id, inner, opts, first_party_hosts);
}
- anonymize_kafka_payload_via_parse(allow, payload, opts)
+ anonymize_kafka_payload_via_parse(allow, payload, opts, first_party_hosts)
}
/// Locate the `distinct_id` + `data` string spans by scanning the outer object. `None` means "let
@@ -323,6 +324,7 @@ 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()))?;
@@ -348,7 +350,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)
+ anonymize_snapshot_data_opts(allow, distinct_id, &mut data_bytes, opts, first_party_hosts)
}
/// Anonymize the inner `$snapshot_items` event JSON (the payload's `data` string). The buffer is
@@ -359,7 +361,13 @@ pub fn anonymize_snapshot_data(
distinct_id: &str,
inner: &mut [u8],
) -> SResult<AnonymizedMessage> {
- anonymize_snapshot_data_opts(allow, distinct_id, inner, AnonymizeOpts::default())
+ anonymize_snapshot_data_opts(
+ allow,
+ distinct_id,
+ inner,
+ AnonymizeOpts::default(),
+ Vec::new(),
+ )
}
pub fn anonymize_snapshot_data_opts(
@@ -367,11 +375,12 @@ pub fn anonymize_snapshot_data_opts(
distinct_id: &str,
inner: &mut [u8],
opts: AnonymizeOpts,
+ first_party_hosts: Vec<String>,
) -> SResult<AnonymizedMessage> {
// 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::new(allow);
+ let ctx = Ctx::with_first_party_hosts(allow, first_party_hosts);
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-node/src/url.rs b/rust/replay-anonymizer-node/src/url.rs
index 27ffaffb9520..b2c4b5d31f3b 100644
--- a/rust/replay-anonymizer-node/src/url.rs
+++ b/rust/replay-anonymizer-node/src/url.rs
@@ -5,16 +5,50 @@
//! - 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.
-//! - With `scrub_authority` it strips userinfo/port and collapses the host to `example.com`
-//! (keeping a leading allow-listed subdomain label).
+//! - 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 crate::allow_lists::AllowLists;
+use crate::context::Ctx;
-pub fn scrub_url(allow: &AllowLists, input: &str) -> Option<String> {
- scrub_url_opts(allow, input, false)
+// Mirrors `URL_ALLOWLIST` in `anonymize/url.ts`.
+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_opts(allow: &AllowLists, input: &str, scrub_authority: bool) -> Option<String> {
+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;
+ }
let tail_idx = input.find(['?', '#']);
let (base, tail) = match tail_idx {
Some(i) => (&input[..i], &input[i..]),
@@ -26,14 +60,26 @@ pub fn scrub_url_opts(allow: &AllowLists, input: &str, scrub_authority: bool) ->
let mut out = String::with_capacity(input.len());
out.push_str(scheme);
if !authority.is_empty() {
- if scrub_authority {
- let scrubbed = scrub_host(allow, authority);
- if scrubbed != authority {
+ let host_port = match authority.rfind('@') {
+ Some(at) => {
+ changed = true;
+ &authority[at + 1..]
+ }
+ None => authority,
+ };
+ if !is_valid_host_port(host_port) {
+ // A structurally invalid "host" (e.g. an unencoded `?` in userinfo makes `user:pa`
+ // 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(&scrubbed);
+ out.push_str(&collapsed);
} else {
- out.push_str(authority);
+ out.push_str(host_port);
}
}
@@ -129,13 +175,10 @@ fn scrub_tail(allow: &AllowLists, tail: &str) -> String {
out
}
-// Strip userinfo + port and rewrite the host to example.com. Keep a leading *subdomain* label
+// 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 scrub_host(allow: &AllowLists, authority: &str) -> String {
- let mut host = match authority.rfind('@') {
- Some(at) => &authority[at + 1..],
- None => authority,
- };
+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()) {
@@ -151,12 +194,123 @@ fn scrub_host(allow: &AllowLists, authority: &str) -> String {
}
}
+// Mirrors `URL_SCHEME_ALLOWLIST` in `anonymize/url.ts`.
+pub const URL_SCHEME_ALLOWLIST: &[&str] = &[
+ // Web platform
+ "about",
+ "blob",
+ "data",
+ "file",
+ "ftp",
+ "geo",
+ "javascript",
+ "magnet",
+ "mailto",
+ "sms",
+ "tel",
+ "urn",
+ "ws",
+ "wss", // Microsoft
+ "ms-access",
+ "ms-excel",
+ "ms-outlook",
+ "ms-powerpoint",
+ "ms-project",
+ "ms-publisher",
+ "ms-visio",
+ "ms-word",
+ "msteams",
+ "onenote",
+ "sip",
+ "sips",
+ "skype", // Google
+ "comgooglemaps",
+ "googlechrome",
+ "googlegmail",
+ "googlemaps", // Apple
+ "facetime",
+ "facetime-audio",
+ "itms",
+ "itms-apps",
+ "maps",
+ "music",
+ "shortcuts",
+ // Chat and social
+ "bluesky",
+ "callto",
+ "discord",
+ "fb",
+ "fb-messenger",
+ "instagram",
+ "irc",
+ "line",
+ "linkedin",
+ "matrix",
+ "reddit",
+ "sgnl",
+ "slack",
+ "snapchat",
+ "telegram",
+ "tg",
+ "tiktok",
+ "twitter",
+ "viber",
+ "wechat",
+ "weixin",
+ "whatsapp",
+ "xmpp",
+ // Media, payments, and tools
+ "bitcoin",
+ "bittorrent",
+ "figma",
+ "notion",
+ "obsidian",
+ "spotify",
+ "steam",
+ "vscode",
+ "zoommtg",
+ "zoomus",
+];
+
+fn scheme_without_slashes(s: &str) -> Option<usize> {
+ let colon = s.find(':')?;
+ let prefix = &s[..colon];
+ if URL_SCHEME_ALLOWLIST
+ .iter()
+ .any(|scheme| prefix.eq_ignore_ascii_case(scheme))
+ {
+ Some(colon + 1)
+ } else {
+ None
+ }
+}
+
+fn is_valid_scheme(prefix: &str) -> bool {
+ let bytes = prefix.as_bytes();
+ match bytes.split_first() {
+ Some((&first, rest)) => {
+ first.is_ascii_alphabetic()
+ && rest
+ .iter()
+ .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
+ }
+ None => false,
+ }
+}
+
// Split into scheme prefix (incl. `://` or `//`), authority (`[userinfo@]host[:port]`), and path.
fn split_url(s: &str) -> (&str, &str, &str) {
- let (scheme, rest) = if let Some(scheme_end) = s.find("://") {
+ let (scheme, rest) = if let Some(scheme_end) = s
+ .find("://")
+ .filter(|&scheme_end| is_valid_scheme(&s[..scheme_end]))
+ {
(&s[..scheme_end + 3], &s[scheme_end + 3..])
} else if let Some(rest) = s.strip_prefix("//") {
(&s[..2], rest)
+ } else if let Some(end) = scheme_without_slashes(s) {
+ // Free text before a colon (or before an embedded `://`) must not pass through as a
+ // "scheme"; only allowlisted schemes survive, and only in the slashless form.
+ return (&s[..end], "", &s[end..]);
} else {
return ("", "", s); // relative URL: all path
};
@@ -166,6 +320,36 @@ fn split_url(s: &str) -> (&str, &str, &str) {
}
}
+// Host or `[ipv6]`, with an optional `:digits` port. Mirrors `HOST_PORT` in `anonymize/url.ts`.
+fn is_valid_host_port(host_port: &str) -> bool {
+ let host = match host_port.split_once(':') {
+ None => host_port,
+ Some(_) if host_port.starts_with('[') => match host_port.rfind(']') {
+ Some(close) => {
+ let bracketed = &host_port[1..close];
+ let port = &host_port[close + 1..];
+ let port_ok = port.is_empty()
+ || (port.starts_with(':')
+ && port.len() > 1
+ && port[1..].bytes().all(|b| b.is_ascii_digit()));
+ return port_ok
+ && bracketed
+ .bytes()
+ .all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.');
+ }
+ None => return false,
+ },
+ Some((host, port)) => {
+ if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) {
+ return false;
+ }
+ host
+ }
+ };
+ host.bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
+}
+
fn is_safe_segment(seg: &str) -> bool {
matches!(seg, "" | "." | "..")
}
diff --git a/rust/replay-anonymizer-node/src/value.rs b/rust/replay-anonymizer-node/src/value.rs
index 5a7066584ca0..a816858e3cdf 100644
--- a/rust/replay-anonymizer-node/src/value.rs
+++ b/rust/replay-anonymizer-node/src/value.rs
@@ -3,7 +3,7 @@
use simd_json::borrowed::{Object, Value};
-use crate::allow_lists::AllowLists;
+use crate::context::Ctx;
use crate::json::{as_array_mut, as_object_mut, is_object, key, string_value};
use crate::text::scrub_text;
use crate::url::scrub_url;
@@ -12,18 +12,18 @@ fn looks_like_url(s: &str) -> bool {
s.starts_with("http://") || s.starts_with("https://")
}
-fn scrub_string_leaf(allow: &AllowLists, s: &str) -> Option<String> {
+fn scrub_string_leaf(ctx: &Ctx<'_>, s: &str) -> Option<String> {
if looks_like_url(s) {
- scrub_url(allow, s)
+ scrub_url(ctx, s)
} else {
- scrub_text(allow, s)
+ scrub_text(ctx.allow, s)
}
}
/// Scrub `slot`: a string leaf (with writeback), otherwise recurse into it.
-fn scrub_child(allow: &AllowLists, slot: &mut Value<'_>) -> bool {
+fn scrub_child(ctx: &Ctx<'_>, slot: &mut Value<'_>) -> bool {
if let Value::String(s) = slot {
- match scrub_string_leaf(allow, s) {
+ match scrub_string_leaf(ctx, s) {
Some(v) => {
*slot = string_value(v);
true
@@ -31,22 +31,22 @@ fn scrub_child(allow: &AllowLists, slot: &mut Value<'_>) -> bool {
None => false,
}
} else {
- scrub_value_in_place(allow, slot)
+ scrub_value_in_place(ctx, slot)
}
}
/// Recursively scrub string leaves inside an array/object, mutating in place.
-pub fn scrub_value_in_place(allow: &AllowLists, value: &mut Value<'_>) -> bool {
+pub fn scrub_value_in_place(ctx: &Ctx<'_>, value: &mut Value<'_>) -> bool {
let mut changed = false;
match value {
Value::Array(arr) => {
for item in arr.iter_mut() {
- changed |= scrub_child(allow, item);
+ changed |= scrub_child(ctx, item);
}
}
Value::Object(obj) => {
for (_, val) in obj.iter_mut() {
- changed |= scrub_child(allow, val);
+ changed |= scrub_child(ctx, val);
}
}
_ => {}
@@ -55,23 +55,22 @@ pub fn scrub_value_in_place(allow: &AllowLists, value: &mut Value<'_>) -> bool {
}
/// Generic scrub of `owner[key]`, handling both a string leaf and a container.
-pub fn scrub_generic_field(allow: &AllowLists, owner: &mut Object<'_>, field: &str) -> bool {
+pub fn scrub_generic_field(ctx: &Ctx<'_>, owner: &mut Object<'_>, field: &str) -> bool {
match owner.get_mut(field) {
- Some(slot) => scrub_child(allow, slot),
+ Some(slot) => scrub_child(ctx, slot),
None => false,
}
}
fn scrub_field_with(
- allow: &AllowLists,
obj: &mut Object<'_>,
field: &'static str,
- scrub: fn(&AllowLists, &str) -> Option<String>,
+ scrub: impl Fn(&str) -> Option<String>,
) -> bool {
let Some(cur) = obj.get(field).and_then(crate::json::as_str) else {
return false;
};
- match scrub(allow, cur) {
+ match scrub(cur) {
Some(v) => {
obj.insert(key(field), string_value(v));
true
@@ -82,9 +81,9 @@ fn scrub_field_with(
/// rrweb/network@1 payload: `{ requests: CapturedNetworkRequest[] }`. Per request: `name` is a
/// Resource Timing URL (URL-scrub); request/response bodies and every header value are free text.
-pub fn scrub_network_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &str) -> bool {
+pub fn scrub_network_plugin(ctx: &Ctx<'_>, owner: &mut Object<'_>, field: &str) -> bool {
if !owner.get(field).map(is_object).unwrap_or(false) {
- return scrub_generic_field(allow, owner, field);
+ return scrub_generic_field(ctx, owner, field);
}
let Some(payload) = owner.get_mut(field).and_then(as_object_mut) else {
return false;
@@ -97,15 +96,15 @@ pub fn scrub_network_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &
let Some(robj) = as_object_mut(req) else {
continue;
};
- changed |= scrub_field_with(allow, robj, "name", scrub_url);
+ changed |= scrub_field_with(robj, "name", |s| scrub_url(ctx, s));
for f in ["requestBody", "responseBody"] {
- changed |= scrub_field_with(allow, robj, f, scrub_text);
+ changed |= scrub_field_with(robj, f, |s| scrub_text(ctx.allow, s));
}
for f in ["requestHeaders", "responseHeaders"] {
if let Some(hdrs) = robj.get_mut(f).and_then(as_object_mut) {
for (_, v) in hdrs.iter_mut() {
if let Value::String(s) = v {
- if let Some(nv) = scrub_text(allow, s) {
+ if let Some(nv) = scrub_text(ctx.allow, s) {
*v = string_value(nv);
changed = true;
}
@@ -118,9 +117,9 @@ pub fn scrub_network_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &
}
/// rrweb/console@1 payload: `{ level, payload: string[], trace: string[] }`.
-pub fn scrub_console_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &str) -> bool {
+pub fn scrub_console_plugin(ctx: &Ctx<'_>, owner: &mut Object<'_>, field: &str) -> bool {
if !owner.get(field).map(is_object).unwrap_or(false) {
- return scrub_generic_field(allow, owner, field);
+ return scrub_generic_field(ctx, owner, field);
}
let Some(payload) = owner.get_mut(field).and_then(as_object_mut) else {
return false;
@@ -131,7 +130,7 @@ pub fn scrub_console_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &
for v in arr.iter_mut() {
// Console frames can hold URLs (stack traces); scrub URL-aware, not as plain text.
if let Value::String(s) = v {
- if let Some(nv) = scrub_string_leaf(allow, s) {
+ if let Some(nv) = scrub_string_leaf(ctx, s) {
*v = string_value(nv);
changed = true;
}
diff --git a/rust/replay-anonymizer-node/tests/fixtures/events.json b/rust/replay-anonymizer-node/tests/fixtures/events.json
index 8a7885a2fc4b..aa5be877c81a 100644
--- a/rust/replay-anonymizer-node/tests/fixtures/events.json
+++ b/rust/replay-anonymizer-node/tests/fixtures/events.json
@@ -479,5 +479,173 @@
"allow": { "text": [], "url": [] },
"event": { "type": 0, "data": { "href": "https://example.com/secret" } },
"expected": { "type": 0, "data": { "href": "https://example.com/secret" } }
+ },
+ {
+ "name": "iframe rr_src with tokens and user object is url-scrubbed identically to src",
+ "allow": { "text": [], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "id": 7,
+ "tagName": "iframe",
+ "attributes": {
+ "rr_src": "https://widget.example-vendor.co/v2/app/?key=abcd1234-fake-fake-fake-abcdef123456&route=%2Fannouncements&widgetToken=eyJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ1c2VyX2Zha2UxMjMifQ.fakesignature&refreshToken=FakeRefreshTok3nValue000&user=%7B%22name%22%3A%22John%20Fakename%22%2C%22email%22%3A%22john.fakename%40example.com%22%7D"
+ },
+ "childNodes": []
+ },
+ {
+ "type": 2,
+ "id": 8,
+ "tagName": "iframe",
+ "attributes": {
+ "src": "https://widget.example-vendor.co/v2/app/?key=abcd1234-fake-fake-fake-abcdef123456&route=%2Fannouncements&widgetToken=eyJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ1c2VyX2Zha2UxMjMifQ.fakesignature&refreshToken=FakeRefreshTok3nValue000&user=%7B%22name%22%3A%22John%20Fakename%22%2C%22email%22%3A%22john.fakename%40example.com%22%7D"
+ },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "id": 7,
+ "tagName": "iframe",
+ "attributes": { "rr_src": "https://widget.example-vendor.co/[redacted]/[redacted]/" },
+ "childNodes": []
+ },
+ {
+ "type": 2,
+ "id": 8,
+ "tagName": "iframe",
+ "attributes": { "src": "https://widget.example-vendor.co/[redacted]/[redacted]/" },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "mutation setting rr_src takes the media path like src",
+ "allow": { "text": [], "url": [] },
+ "event": {
+ "type": 3,
+ "data": {
+ "source": 0,
+ "texts": [],
+ "attributes": [
+ {
+ "id": 7,
+ "attributes": {
+ "rr_src": "https://widget.example-vendor.co/v2/app/?key=abcd1234-fake-fake-fake-abcdef123456&route=%2Fannouncements&widgetToken=eyJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ1c2VyX2Zha2UxMjMifQ.fakesignature&refreshToken=FakeRefreshTok3nValue000&user=%7B%22name%22%3A%22John%20Fakename%22%2C%22email%22%3A%22john.fakename%40example.com%22%7D"
+ }
+ }
+ ],
+ "adds": [],
+ "removes": []
+ }
+ },
+ "expected": {
+ "type": 3,
+ "data": {
+ "source": 0,
+ "texts": [],
+ "attributes": [
+ {
+ "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]/"
+ }
+ }
+ ],
+ "adds": [],
+ "removes": []
+ }
+ }
+ },
+ {
+ "name": "media element rr_src becomes placeholder with scrubbed original stashed",
+ "allow": { "text": [], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "img",
+ "attributes": { "rr_src": "https://cdn.example.com/u/john-fakename-avatar.png" },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "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]"
+ },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "benign rr_src values: about:blank passes through, other values follow src's fail-closed scrub",
+ "allow": { "text": [], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "iframe", "attributes": { "rr_src": "about:blank" }, "childNodes": [] },
+ { "type": 2, "tagName": "div", "attributes": { "rr_src": "data:text/html;base64,PGgxPmhpPC9oMT4=" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "iframe", "attributes": { "rr_src": "about:blank" }, "childNodes": [] },
+ { "type": 2, "tagName": "div", "attributes": { "rr_src": "data:[redacted]/[redacted]" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
}
]
diff --git a/rust/replay-anonymizer-node/tests/fixtures/url-scheme-allowlist.json b/rust/replay-anonymizer-node/tests/fixtures/url-scheme-allowlist.json
new file mode 100644
index 000000000000..6d46201bc757
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/fixtures/url-scheme-allowlist.json
@@ -0,0 +1,73 @@
+[
+ "about",
+ "bitcoin",
+ "bittorrent",
+ "blob",
+ "bluesky",
+ "callto",
+ "comgooglemaps",
+ "data",
+ "discord",
+ "facetime",
+ "facetime-audio",
+ "fb",
+ "fb-messenger",
+ "figma",
+ "file",
+ "ftp",
+ "geo",
+ "googlechrome",
+ "googlegmail",
+ "googlemaps",
+ "instagram",
+ "irc",
+ "itms",
+ "itms-apps",
+ "javascript",
+ "line",
+ "linkedin",
+ "magnet",
+ "mailto",
+ "maps",
+ "matrix",
+ "ms-access",
+ "ms-excel",
+ "ms-outlook",
+ "ms-powerpoint",
+ "ms-project",
+ "ms-publisher",
+ "ms-visio",
+ "ms-word",
+ "msteams",
+ "music",
+ "notion",
+ "obsidian",
+ "onenote",
+ "reddit",
+ "sgnl",
+ "shortcuts",
+ "sip",
+ "sips",
+ "skype",
+ "slack",
+ "sms",
+ "snapchat",
+ "spotify",
+ "steam",
+ "tel",
+ "telegram",
+ "tg",
+ "tiktok",
+ "twitter",
+ "urn",
+ "viber",
+ "vscode",
+ "wechat",
+ "weixin",
+ "whatsapp",
+ "ws",
+ "wss",
+ "xmpp",
+ "zoommtg",
+ "zoomus"
+]
diff --git a/rust/replay-anonymizer-node/tests/fixtures/url.json b/rust/replay-anonymizer-node/tests/fixtures/url.json
index 7c89795a27ee..08fc7a1df1db 100644
--- a/rust/replay-anonymizer-node/tests/fixtures/url.json
+++ b/rust/replay-anonymizer-node/tests/fixtures/url.json
@@ -1,79 +1,273 @@
[
{
"name": "keeps allow-listed path segments, masks numbers",
- "allow": { "text": [], "url": ["users", "profile"] },
+ "allow": {
+ "text": [],
+ "url": [
+ "users",
+ "profile"
+ ]
+ },
"input": "https://example.com/users/42/profile",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/users/$$/profile"
},
{
"name": "redacts non-allow-listed path segments",
- "allow": { "text": [], "url": [] },
+ "allow": {
+ "text": [],
+ "url": []
+ },
"input": "/foo/bar?x=1",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "/[redacted]/[redacted]"
},
{
"name": "query param survives on allow-listed key, number value masked",
- "allow": { "text": [], "url": ["page"] },
+ "allow": {
+ "text": [],
+ "url": [
+ "page"
+ ]
+ },
"input": "https://example.com/?page=2&secret=abc",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/?page=$"
},
{
"name": "allow-listed fragment kept",
- "allow": { "text": [], "url": ["section"] },
+ "allow": {
+ "text": [],
+ "url": [
+ "section"
+ ]
+ },
"input": "https://example.com/#section",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/#section"
},
{
- "name": "scrubAuthority strips userinfo/port and keeps allow-listed subdomain",
- "allow": { "text": [], "url": ["us", "path"] },
+ "name": "collapseHost drops the port and keeps an allow-listed subdomain",
+ "allow": {
+ "text": [],
+ "url": [
+ "us",
+ "path"
+ ]
+ },
"input": "https://user:[email protected]:8080/path",
- "scrubAuthority": true,
+ "collapseHost": true,
"expected": "https://us.example.com/path"
},
{
- "name": "scrubAuthority collapses a two-label host to example.com",
- "allow": { "text": [], "url": [] },
+ "name": "collapseHost collapses a two-label host to example.com",
+ "allow": {
+ "text": [],
+ "url": []
+ },
"input": "https://example.com/u/42",
- "scrubAuthority": true,
+ "collapseHost": true,
"expected": "https://example.com/[redacted]/$$"
},
{
"name": "query param with an allow-listed key and empty value survives",
- "allow": { "text": [], "url": ["ok"] },
+ "allow": {
+ "text": [],
+ "url": [
+ "ok"
+ ]
+ },
"input": "https://example.com/?ok=&x=1",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/?ok="
},
{
"name": "bare (valueless) query flag survives only when allow-listed",
- "allow": { "text": [], "url": ["ok"] },
+ "allow": {
+ "text": [],
+ "url": [
+ "ok"
+ ]
+ },
"input": "https://example.com/?ok&drop",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/?ok"
},
{
"name": "numeric fragment is dropped",
- "allow": { "text": [], "url": [] },
+ "allow": {
+ "text": [],
+ "url": []
+ },
"input": "https://example.com/#42",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/"
},
{
"name": "relative-path safe segments (. and ..) are preserved",
- "allow": { "text": [], "url": [] },
+ "allow": {
+ "text": [],
+ "url": []
+ },
"input": "/a/../b",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "/[redacted]/../[redacted]"
},
{
"name": "multiple surviving query params keep their order",
- "allow": { "text": [], "url": ["a", "b", "x", "y"] },
+ "allow": {
+ "text": [],
+ "url": [
+ "a",
+ "b",
+ "x",
+ "y"
+ ]
+ },
"input": "https://example.com/?a=x&b=y",
- "scrubAuthority": false,
+ "collapseHost": false,
"expected": "https://example.com/?a=x&b=y"
+ },
+ {
+ "name": "passthrough url literals survive even with authority scrubbing: about:blank",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "about:blank",
+ "collapseHost": true,
+ "expected": "about:blank"
+ },
+ {
+ "name": "passthrough url literals survive even with authority scrubbing: about:srcdoc",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "about:srcdoc",
+ "collapseHost": true,
+ "expected": "about:srcdoc"
+ },
+ {
+ "name": "userinfo is stripped even without authority scrubbing",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "https://user:[email protected]/settings",
+ "collapseHost": false,
+ "expected": "https://app.example.com/[redacted]"
+ },
+ {
+ "name": "scheme without slashes keeps the protocol and redacts the rest: tel",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "tel:+15551234567",
+ "collapseHost": false,
+ "expected": "tel:[redacted]"
+ },
+ {
+ "name": "scheme without slashes keeps the protocol and redacts the rest: mailto",
+ "allow": {
+ "text": [],
+ "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": {
+ "text": [],
+ "url": []
+ },
+ "input": "john.fakename:secret-chat",
+ "collapseHost": false,
+ "expected": "[redacted]"
+ },
+ {
+ "name": "app deep-link scheme survives with its value scrubbed",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "spotify:track:4uLU6hMCjMI75M1A2tKUQC",
+ "collapseHost": false,
+ "expected": "spotify:[redacted]"
+ },
+ {
+ "name": "unencoded ? in userinfo cannot smuggle credentials as a host",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "https://user:[email protected]/path",
+ "collapseHost": false,
+ "expected": "https://[redacted]"
+ },
+ {
+ "name": "free text before an embedded :// is not kept as a scheme",
+ "allow": {
+ "text": [],
+ "url": []
+ },
+ "input": "javascript:mail(\"[email protected]\",\"https://tracker.test/1\")",
+ "collapseHost": false,
+ "expected": "javascript:[redacted]//[redacted]/[redacted]"
}
]
diff --git a/rust/replay-anonymizer-node/tests/parity.rs b/rust/replay-anonymizer-node/tests/parity.rs
index 5785e4498b96..7b1496d97964 100644
--- a/rust/replay-anonymizer-node/tests/parity.rs
+++ b/rust/replay-anonymizer-node/tests/parity.rs
@@ -6,7 +6,8 @@ use std::time::Instant;
use replay_anonymizer_node::allow_lists::AllowLists;
use replay_anonymizer_node::{
- anonymize_event_str, anonymize_message, text::scrub_text, url::scrub_url_opts,
+ anonymize_event_str, anonymize_message, context::Ctx, text::scrub_text, url::scrub_url_opts,
+ url::URL_SCHEME_ALLOWLIST,
};
use serde_json::Value;
@@ -50,13 +51,34 @@ fn url_fixtures() {
let allow = allow_of(&case);
let input = case["input"].as_str().unwrap();
let expected = case["expected"].as_str().unwrap();
- let scrub_authority = case["scrubAuthority"].as_bool().unwrap_or(false);
+ 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(&allow, input, scrub_authority).unwrap_or_else(|| input.to_string());
+ scrub_url_opts(&ctx, input, collapse_host).unwrap_or_else(|| input.to_string());
assert_eq!(actual, expected, "url case: {}", case["name"]);
}
}
+#[test]
+fn url_scheme_allowlist_matches_fixture() {
+ // The TS constant is checked against the same fixture, so the two lists cannot drift.
+ let expected: Vec<String> = fixtures("url-scheme-allowlist.json")
+ .iter()
+ .map(|v| v.as_str().unwrap().to_string())
+ .collect();
+ let mut actual: Vec<String> = URL_SCHEME_ALLOWLIST.iter().map(|s| s.to_string()).collect();
+ actual.sort();
+ assert_eq!(actual, expected);
+}
+
#[test]
fn event_fixtures() {
for case in fixtures("events.json") {
diff --git a/rust/replay-anonymizer-node/tests/snapshot.rs b/rust/replay-anonymizer-node/tests/snapshot.rs
index f3e5d892e0f3..6811cc1b029c 100644
--- a/rust/replay-anonymizer-node/tests/snapshot.rs
+++ b/rust/replay-anonymizer-node/tests/snapshot.rs
@@ -365,35 +365,50 @@ 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();
- 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}"
- );
+ // 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)),
+ ),
}
- (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)),
- ),
}
}
}