:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-research): collect remote image URLs in the ml mirror (#80859)
Robbieb34ba218f101
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.tsindex 62e8618ac308..70570b1cc103 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts@@ -11,6 +11,11 @@ export type MlAnonymizeRoute = 'stream' | 'tree' | ''export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed'+/** Stages of the URL lane. Deliberately the same vocabulary as {@link MlImageLaneStage}, so the two+ * lanes read the same way on a dashboard even though only `collected` exists until the fetch lane+ * ships. */+export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed'+export class SessionRecordingIngesterMetrics {private static readonly sessionsHandled = new Gauge({name: 'recording_blob_ingestion_v2_session_manager_count',@@ -83,6 +88,30 @@ export class SessionRecordingIngesterMetrics {labelNames: ['outcome'],})+ private static readonly mlUrlsCollected = new Counter({+ name: 'recording_blob_ingestion_v2_ml_urls_collected',+ help: 'Remote image URLs through the fetch lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed)',+ labelNames: ['outcome'],+ })++ private static readonly mlUrlsDeclined = new Counter({+ name: 'recording_blob_ingestion_v2_ml_urls_declined',+ help: 'Remote image URLs the anonymizer refused to collect, by reason. A decline is invisible in the collected count, so without this the lane looks like traffic carries fewer images than it does',+ labelNames: ['reason'],+ })++ private static readonly mlUrlDomainsPerMessage = new Histogram({+ name: 'recording_blob_ingestion_v2_ml_url_domains_per_message',+ help: 'Distinct registrable domains among the URLs collected from one message, observed for every message including those with none. The fetch topic is keyed by that domain, so this is how many Kafka messages one replay message becomes, and how concentrated a page is on one operator',+ buckets: [0, 1, 2, 3, 5, 8, 13, 21, 34, 55],+ })++ private static readonly mlUrlsPerMessage = new Histogram({+ name: 'recording_blob_ingestion_v2_ml_urls_per_message',+ help: 'URLs collected from one message that carried at least one. The counter alone gives a mean; sizing the fetch lane needs the tail',+ buckets: [1, 2, 5, 10, 25, 50, 100, 256],+ })+private static readonly mlImageBytesProduced = new Counter({name: 'recording_blob_ingestion_v2_ml_image_bytes_produced',help: 'Bytes of collected images delivered to the scrub topic (acked)',@@ -142,6 +171,24 @@ export class SessionRecordingIngesterMetrics {this.mlImagesCollected.labels(outcome).inc(count)}+ public static incrementMlUrlsCollected(outcome: MlUrlLaneStage, count: number): void {+ this.mlUrlsCollected.labels(outcome).inc(count)+ }++ public static incrementMlUrlsDeclined(reason: string, count: number): void {+ if (count > 0) {+ this.mlUrlsDeclined.inc({ reason }, count)+ }+ }++ public static observeMlUrlDomainsPerMessage(domains: number): void {+ this.mlUrlDomainsPerMessage.observe(domains)+ }++ public static observeMlUrlsPerMessage(urls: number): void {+ this.mlUrlsPerMessage.observe(urls)+ }+public static incrementMlImageBytesProduced(bytes: number): void {this.mlImageBytesProduced.inc(bytes)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.tsindex cdd80b2348ee..70c2ffff96fb 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts@@ -8,7 +8,16 @@import { createHmac } from 'node:crypto'const PREFIX = 'image'-const REF_RE = /^image:([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/+/**+ * The prefix of a ref whose hash names a URL rather than the bytes behind it.+ *+ * A content ref promises the hash names the bytes, which is what lets a reader treat one as+ * content-addressed. The bytes at a URL can change, so a URL ref cannot make that promise. One+ * prefix for both would leave a reader unable to tell which it holds, and the failure would be a+ * silent mis-join rather than an error.+ */+const URL_PREFIX = 'imageurl'+const REF_RE = /^(image|imageurl):([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/export function hashImageBytes(contentKey: string | Buffer, bytes: Buffer): string {return createHmac('sha256', contentKey).update(bytes).digest('base64url').slice(0, 22)@@ -18,11 +27,16 @@ export function imageRef(pseudoTeam: string, hash: string): string {return `${PREFIX}:${pseudoTeam}:${hash}`}+export function urlRef(pseudoTeam: string, hash: string): string {+ return `${URL_PREFIX}:${pseudoTeam}:${hash}`+}+export function isImageRef(s: string): boolean {return REF_RE.test(s)}-export function parseImageRef(s: string): { pseudoTeam: string; hash: string } | null {+/** Parses either kind of ref. `source` says which promise the hash carries. */+export function parseImageRef(s: string): { pseudoTeam: string; hash: string; source: 'bytes' | 'url' } | null {const m = REF_RE.exec(s)- return m ? { pseudoTeam: m[1], hash: m[2] } : null+ return m ? { pseudoTeam: m[2], hash: m[3], source: m[1] === PREFIX ? 'bytes' : 'url' } : null}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex ba2bd7cca697..34893e3454e9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -336,7 +336,11 @@ export class ImageBatcher {// The ref's hash is a producer-side per-team HMAC; this consumer doesn't hold the key and// trusts the producer (the topic's only writer) that the key names these bytes.const parsed = ref ? parseImageRef(ref) : null- if (!ref || !parsed || !m.value) {+ // A URL ref names a URL, not these bytes. The shard store indexes by (pseudoTeam, hash)+ // with the prefix dropped, so accepting one here would file URL-sourced bytes in the+ // same slot as content-addressed ones. That is the silent mis-join the prefix exists+ // to prevent, so it counts as an invalid key rather than being stored.+ if (!ref || !parsed || parsed.source !== 'bytes' || !m.value) {ImageScrubConsumerMetrics.incInvalidKey()continue}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 4b83c853a2a8..3412a06c95c4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -43,6 +43,18 @@ export type MlMirrorConfig = {* both the scrub consumer lane AND ref-aware downstream readers must be live first.*/SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: boolean++ /**+ * Collect the URLs of remote images as well, so the fetch lane can download them later.+ *+ * Enabling changes the mirrored JSONL shape a second time: a remote image's `src` carries an+ * `imageurl:<pseudoTeam>:<hash>` ref instead of the grey placeholder. The prefix differs from+ * the image lane's `image:` on purpose, because this hash names the URL rather than the bytes+ * behind it. Nothing fetches those URLs yet, so every such ref is dangling, and a dangling ref+ * renders as the same placeholder it replaced. What this buys is the measurement of how many+ * URLs and how many distinct hosts real traffic carries.+ */+ SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: booleanSESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: stringSESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: stringSESSION_RECORDING_ML_IMAGE_SCRUB_SIDECAR_URL: string@@ -110,6 +122,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_REDIS_HOST: '',SESSION_RECORDING_ML_REDIS_PORT: 6379,SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: false,+ SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: false,SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: 'session-replay-ml-image-scrub',SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: 'scrubbed-images',// 127.0.0.1, not localhost: the sidecar binds IPv4 loopback, and localhost can resolve to ::1 first.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex 4007b0c94100..e2e00d6ccd74 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -34,15 +34,29 @@ export interface MlMirrorPipelineOptions {/** Enables the image-collection lane: inlined images become refs, originals go to the scrub topic. */export interface MlMirrorImageScrubProducer {outputs: IngestionOutputs<MlImageScrubOutput>+ producedRefCacheMax: number+}++/**+ * Which collection lanes the anonymizer runs, and the key they derive their per-team ref prefix+ * from.+ *+ * Separate from {@link MlMirrorImageScrubProducer} because collecting and producing are separate+ * decisions. The URL lane collects and measures before any topic exists. A requirement to turn the+ * scrub producer on first would make that measurement impossible to take on its own.+ */+export interface MlMirrorCollection {/** The ML pseudonym HMAC key (also used by the block-metadata sink), for the per-team ref prefix. */pseudonymSecret: string | Buffer- producedRefCacheMax: number+ collectImages: boolean+ collectUrls: boolean}export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfig,mlOptions: MlMirrorPipelineOptions,- imageScrub?: MlMirrorImageScrubProducer+ imageScrub?: MlMirrorImageScrubProducer,+ collection?: MlMirrorCollection): SessionReplayPipeline {const {outputs,@@ -141,9 +155,9 @@ export function createMlMirrorReplayPipeline(const parsed = b.pipe(topHogWrapper(createParseAndAnonymizeMessageStep(- imageScrub && {- pseudonymSecret: imageScrub.pseudonymSecret,- }+ collection?.collectImages || collection?.collectUrls+ ? collection+ : undefined),[timer('parse_time_ms_by_session_id', (input) => ({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.tsindex 2aa12cf6fc5a..24f6f8a26204 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts@@ -15,5 +15,12 @@ export function pseudonymize(secret: string | Buffer, namespace: string, value:export const PSEUDONYM_TEAM = 'team'/** Namespace for the per-team image content-HMAC key (see ml-mirror-image-scrub/content-ref.ts). */export const PSEUDONYM_IMAGE_CONTENT_KEY = 'image-content-key'+/**+ * Namespace for the per-team URL-HMAC key, which hashes a remote image's URL rather than its bytes.+ *+ * Separate from the content key on purpose. Both produce a ref of the same shape, and each hashes+ * a different thing. A separate key keeps the two kinds of ref independent for one team.+ */+export const PSEUDONYM_IMAGE_URL_KEY = 'image-url-key'export const PSEUDONYM_SESSION = 'session'export const PSEUDONYM_DISTINCT_ID = 'distinct_id'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.tsindex b0215d98b739..cbebf953965d 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@@ -288,7 +288,13 @@ describeAddon('native image collection', () => {expect(Buffer.from(bytes)).toEqual(png)// The Rust-emitted hash must be the keyed HMAC of the returned bytes.expect(hashImageBytes(CONTENT_KEY, Buffer.from(bytes))).toBe(entry.hash)- expect(parseImageRef(expectedRef)).toEqual({ pseudoTeam: PSEUDO_TEAM, hash: entry.hash })+ // `source` is what tells a reader whether the hash names the bytes or only the URL they+ // came from. An inlined image is content-addressed, so it must read as `bytes`.+ expect(parseImageRef(expectedRef)).toEqual({+ pseudoTeam: PSEUDO_TEAM,+ hash: entry.hash,+ source: 'bytes',+ })})it('collects nothing without the collection keys and blurs inline instead', async () => {@@ -300,13 +306,26 @@ describeAddon('native image collection', () => {expect(result.lines!.toString()).not.toContain('image:')})- it('rejects when pseudoTeam and contentKey are not passed together', async () => {+ it('rejects a per-team key with no pseudonym to attribute it to', async () => {+ // Each lane's ref embeds the pseudonym, so a key without one would mint refs that nothing+ // can attribute to a team. That fails loudly rather than collecting under a blank prefix.rustAddon!.initAnonymizer({ text: [], url: [] })- await expect(- rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, PSEUDO_TEAM, undefined)- ).rejects.toThrow('must be passed together')await expect(rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, CONTENT_KEY)- ).rejects.toThrow('must be passed together')+ ).rejects.toThrow('require pseudoTeam')+ await expect(+ rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, undefined, CONTENT_KEY)+ ).rejects.toThrow('require pseudoTeam')+ })++ it('runs either collection lane without the other', async () => {+ // The URL lane measures before any fetch topic exists, so it must not need the image lane.+ rustAddon!.initAnonymizer({ text: [], url: [] })+ const imagesOnly = await rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, PSEUDO_TEAM, CONTENT_KEY)+ expect(imagesOnly.failed).toBe(false)+ // A pseudonym with neither key collects nothing and is not an error.+ const neither = await rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, PSEUDO_TEAM, undefined)+ expect(neither.failed).toBe(false)+ expect(neither.lines!.toString()).not.toContain('image:')})})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.tsindex 1c91b8868dca..c1ef8e9a0ccc 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@@ -5,7 +5,12 @@ import { gzip } from 'zlib'import { PipelineResultType } from '~/ingestion/framework/results'import { imageRef } from './ml-mirror-image-scrub/content-ref'-import { PSEUDONYM_IMAGE_CONTENT_KEY, PSEUDONYM_TEAM, pseudonymize } from './ml-mirror/pseudonymize'+import {+ PSEUDONYM_IMAGE_CONTENT_KEY,+ PSEUDONYM_IMAGE_URL_KEY,+ PSEUDONYM_TEAM,+ pseudonymize,+} from './ml-mirror/pseudonymize'import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'import { SessionReplayHeaders } from './pipeline-types'@@ -20,8 +25,9 @@ jest.mock('@posthog/replay-anonymizer', () => ({payload: Buffer,contentEncoding?: string | null,pseudoTeam?: string | null,- contentKey?: string | null- ) => mockAnonymizeKafkaPayload(payload, contentEncoding, pseudoTeam, contentKey),+ contentKey?: string | null,+ urlKey?: string | null+ ) => mockAnonymizeKafkaPayload(payload, contentEncoding, pseudoTeam, contentKey, urlKey),}))describe('createParseAndAnonymizeMessageStep', () => {@@ -116,14 +122,14 @@ describe('createParseAndAnonymizeMessageStep', () => {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, undefined, undefined)+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null, undefined, undefined, undefined)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', undefined, undefined)+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4', undefined, undefined, undefined)})test.each([@@ -177,7 +183,11 @@ describe('createParseAndAnonymizeMessageStep', () => {describe('createParseAndAnonymizeMessageStep with image collection', () => {const secret = 'test-pseudonym-secret'- const step = createParseAndAnonymizeMessageStep({ pseudonymSecret: secret })+ const step = createParseAndAnonymizeMessageStep({+ pseudonymSecret: secret,+ collectImages: true,+ collectUrls: false,+ })const pseudoTeam = pseudonymize(secret, PSEUDONYM_TEAM, '1')const contentKey = pseudonymize(secret, PSEUDONYM_IMAGE_CONTENT_KEY, '1')const now = Date.now()@@ -281,3 +291,95 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {expect((result as any).value.collectedImages).toBeUndefined()})})++describe('createParseAndAnonymizeMessageStep with url collection', () => {+ const secret = 'test-pseudonym-secret'+ const pseudoTeam = pseudonymize(secret, PSEUDONYM_TEAM, '1')+ const urlKey = pseudonymize(secret, PSEUDONYM_IMAGE_URL_KEY, '1')+ const now = Date.now()+ const team = { teamId: 1, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true }+ const headers: SessionReplayHeaders = {+ token: 'token',+ distinct_id: 'distinct-id',+ session_id: 'session-id',+ } as SessionReplayHeaders++ const kafkaMessage = (): any => ({+ value: Buffer.from('payload'),+ timestamp: now,+ partition: 0,+ topic: 't',+ offset: 1,+ size: 7,+ })++ const meta = (urls?: unknown[]): string =>+ JSON.stringify({+ distinctId: 'distinct-id',+ sessionId: 'session-id',+ windowId: 'w',+ snapshotSource: null,+ snapshotLibrary: null,+ startTs: now,+ endTs: now,+ consoleLogCount: 0,+ consoleWarnCount: 0,+ consoleErrorCount: 0,+ events: [],+ ...(urls ? { urls } : {}),+ })++ beforeEach(() => mockAnonymizeKafkaPayload.mockReset())++ it('runs without the image lane, and forwards only the url key', async () => {+ // The URL lane measures before any topic exists. Requiring the image lane to be on first+ // would make that measurement impossible to take on its own.+ mockAnonymizeKafkaPayload.mockResolvedValue({+ failed: false,+ lines: Buffer.from(''),+ meta: meta([{ hash: 'h'.repeat(22), url: 'https://cdn.example.com/a.png', host: 'cdn.example.com' }]),+ images: null,+ })+ const step = createParseAndAnonymizeMessageStep({+ pseudonymSecret: secret,+ collectImages: false,+ collectUrls: true,+ })++ const result: any = await step({ message: kafkaMessage(), headers, team } as any)++ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(expect.anything(), null, pseudoTeam, undefined, urlKey)+ expect(result.value.collectedUrls).toEqual([+ {+ ref: `imageurl:${pseudoTeam}:${'h'.repeat(22)}`,+ url: 'https://cdn.example.com/a.png',+ host: 'cdn.example.com',+ },+ ])+ expect(result.value.collectedImages).toBeUndefined()+ })++ it('passes no keys at all when both lanes are off', async () => {+ mockAnonymizeKafkaPayload.mockResolvedValue({+ failed: false,+ lines: Buffer.from(''),+ meta: meta(),+ images: null,+ })+ const step = createParseAndAnonymizeMessageStep({+ pseudonymSecret: secret,+ collectImages: false,+ collectUrls: false,+ })++ await step({ message: kafkaMessage(), headers, team } as any)++ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(+ expect.anything(),+ null,+ pseudoTeam,+ undefined,+ undefined+ )+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.tsindex a514a9b1823f..d64d71707213 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts@@ -12,8 +12,13 @@ import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/typimport { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'-import { hashImageBytes, imageRef, isImageRef } from './ml-mirror-image-scrub/content-ref'-import { PSEUDONYM_IMAGE_CONTENT_KEY, PSEUDONYM_TEAM, pseudonymize } from './ml-mirror/pseudonymize'+import { hashImageBytes, imageRef, isImageRef, urlRef } from './ml-mirror-image-scrub/content-ref'+import {+ PSEUDONYM_IMAGE_CONTENT_KEY,+ PSEUDONYM_IMAGE_URL_KEY,+ PSEUDONYM_TEAM,+ pseudonymize,+} from './ml-mirror/pseudonymize'import { ParseMessageStepInput, ParseMessageStepOutput, getContentEncoding, isGzipped } from './parse-message-step'const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7@@ -44,13 +49,41 @@ export interface CollectedImage {bytes: Buffer}+/**+ * A remote image URL the addon collected for the fetch lane.+ *+ * `url` is the original, unscrubbed URL. It carries whatever the page put in its path and query.+ * It is therefore as sensitive as the raw replay payload. It must not reach a log line, a metric+ * label, or any destination outside the fetch topic.+ */+export interface CollectedUrl {+ /** `imageurl:<pseudoTeam>:<hash>` — the ref the mirrored line carries for this URL. */+ ref: string+ url: string+ /** The host the request goes to. robots.txt and the connection limit are scoped to this. */+ host: string+ /** The registrable domain of `host` — the fetch topic's Kafka key, so every URL of one operator+ * lands on one partition. */+ domain: string+}+export interface ParseAndAnonymizeStepOutput extends ParseMessageStepOutput {collectedImages?: CollectedImage[]+ collectedUrls?: CollectedUrl[]}export interface ImageCollectionConfig {/** The ML pseudonym HMAC key; only its per-team derivatives (never the key) cross the FFI. */pseudonymSecret: string | Buffer+ /** Replace inlined images with refs and return their bytes for the scrub topic. */+ collectImages: boolean+ /**+ * Replace a remote image's `src` with a ref and return its URL for the fetch lane.+ *+ * Independent of `collectImages`. The two lanes have separate destinations and separate+ * rollouts, so tying them together would make the URL measurement wait on the scrub lane.+ */+ collectUrls: boolean}/**@@ -71,7 +104,8 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp// carries no unkeyed content digest; it never crosses the FFI as the raw secret.interface TeamImageKeys {pseudoTeam: string- contentKey: string+ contentKey?: string+ urlKey?: string}const teamKeysCache = new Map<number, TeamImageKeys>()const teamKeysFor = (teamId: number): TeamImageKeys | undefined => {@@ -94,7 +128,13 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpSessionRecordingIngesterMetrics.incrementMlImagePseudoTeamInvalid()return undefined}- keys = { pseudoTeam, contentKey }+ keys = {+ pseudoTeam,+ contentKey: imageCollection.collectImages ? contentKey : undefined,+ urlKey: imageCollection.collectUrls+ ? pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, String(teamId))+ : undefined,+ }teamKeysCache.set(teamId, keys)}return keys@@ -123,7 +163,8 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpmessage.value,contentEncoding,teamKeys?.pseudoTeam,- teamKeys?.contentKey+ teamKeys?.contentKey,+ teamKeys?.urlKey)} catch (error) {// A rejected promise (native panic, addon load failure) must fail closed.@@ -229,8 +270,11 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpsnapshot_library: meta.snapshotLibrary,}- const collectedImages = teamKeys ? unpackCollectedImages(teamKeys.pseudoTeam, meta, result.images) : undefined- return ok({ ...input, parsedMessage, collectedImages })+ const collectedImages = teamKeys?.contentKey+ ? unpackCollectedImages(teamKeys.pseudoTeam, meta, result.images)+ : undefined+ const collectedUrls = teamKeys?.urlKey ? unpackCollectedUrls(teamKeys.pseudoTeam, meta) : undefined+ return ok({ ...input, parsedMessage, collectedImages, collectedUrls })}}@@ -261,3 +305,34 @@ function unpackCollectedImages(SessionRecordingIngesterMetrics.incrementMlImagesCollected('collected', images.length)return images.length > 0 ? images : undefined}++/**+ * Turn the addon's `meta.urls` into produce-ready records.+ *+ * The domain count is observed for a message with no URL too. A count taken only from messages+ * that carry one describes an image-heavy page, and this number exists to size a topic that+ * carries all the traffic.+ */+function unpackCollectedUrls(pseudoTeam: string, meta: AnonymizeMeta): CollectedUrl[] | undefined {+ const urls: CollectedUrl[] = []+ const domains = new Set<string>()+ for (const entry of meta.urls ?? []) {+ urls.push({+ ref: urlRef(pseudoTeam, entry.hash),+ url: entry.url,+ host: entry.host,+ domain: entry.domain,+ })+ domains.add(entry.domain)+ }+ for (const decline of meta.urlDeclines ?? []) {+ SessionRecordingIngesterMetrics.incrementMlUrlsDeclined(decline.reason, decline.count)+ }+ SessionRecordingIngesterMetrics.observeMlUrlDomainsPerMessage(domains.size)+ if (urls.length === 0) {+ return undefined+ }+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('collected', urls.length)+ SessionRecordingIngesterMetrics.observeMlUrlsPerMessage(urls.length)+ return urls+}diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex 34c1cdf927bd..dc74fb27c3fe 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -117,8 +117,7 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)- // The restriction pool is deliberately not overridden: the event restriction list is- // configuration another system writes, so every lane has to read the same copy of it.+ // Another system writes the event restriction list, so every lane reads one copy of it.const pools = buildSessionReplayRedisPools(this.config, resolveMlMirrorRedisConnection(this.config))this.redisPool = pools.redisPoolthis.restrictionRedisPool = pools.restrictionRedisPool@@ -171,10 +170,17 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED? {outputs,- pseudonymSecret,producedRefCacheMax: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX,}- : undefined+ : undefined,+ {+ pseudonymSecret,+ // Producing the images is what makes collecting them useful, so the image+ // lane follows its producer flag. The URL lane has no producer yet and+ // measures on its own, so it follows only its own flag.+ collectImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED,+ collectUrls: this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED,+ }),// Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let// the cleartext mirror mark a session seen without the main lane's KMS key, so the main lanediff --git a/rust/Cargo.lock b/rust/Cargo.lockindex a511f3c15b4f..290bfa4bc046 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8971,7 +8971,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.1"+version = "0.4.2"dependencies = ["ahash 0.8.12","anyhow",@@ -8983,6 +8983,7 @@ dependencies = ["libdeflater","lz4","memchr",+ "public-suffix","serde","serde_json","sha2 0.10.9",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 5c0e8ecd4609..b749d4b3304a 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -27,6 +27,21 @@ export interface AnonymizeImageEntry {len: number}+/** One collected remote image URL, ready for the fetch lane. */+export interface AnonymizeUrlEntry {+ /** First 22 base64url chars of `HMAC-SHA256(urlKey, dedupUrl)`, where the dedup URL is the+ * canonical URL minus its volatile parameters. The ref in the mirrored line ends with this. */+ hash: string+ /** The canonical URL with every parameter intact — what the fetcher requests. A signed URL only+ * works in this form, which is why it is not the value the hash was taken over. */+ url: string+ /** The host the request goes to. robots.txt and the connection limit are scoped to this. */+ host: string+ /** The registrable domain of `host`. The fetch topic keys on this, so every URL of one operator+ * lands on one partition and one pod holds its rate budget without a distributed lock. */+ domain: string+}+/** Envelope + per-event metadata parsed from {@link AnonymizeKafkaPayloadResult.meta}. */export interface AnonymizeMeta {distinctId: string@@ -46,6 +61,10 @@ export interface AnonymizeMeta {events: AnonymizeEventMeta[]/** Collected original images (hash-sorted); present only when the collection lane was enabled and images were collected. */images?: AnonymizeImageEntry[]+ /** Collected remote image URLs (hash-sorted); present only when the URL lane was enabled and URLs were collected. */+ urls?: AnonymizeUrlEntry[]+ /** Counts by reason for the URLs the collector refused. Absent when it refused none. */+ urlDeclines?: { reason: string; count: number }[]}/**@@ -116,19 +135,28 @@ export function initAnonymizer(allow: AllowListsInput): void {* the raw team id or master secret) enable the image-collection lane: inlined images are replaced* with `image:<pseudoTeam>:<hash>` refs (hash = keyed HMAC of the bytes) instead of the inline* blur, and the original bytes come back in `images`/`meta.images` for the caller to produce to- * the scrub topic. Passing one without the other throws.+ * the scrub topic.+ *+ * `urlKey` enables the URL-collection lane alongside it: a remote image's `src` is replaced with a+ * ref of the same shape, and its original URL comes back in `meta.urls` for the caller to hand to+ * the fetch lane.+ *+ * The two lanes are independent: either, both, or neither. Both need `pseudoTeam`, because the ref+ * embeds it, so a `contentKey` or a `urlKey` without one throws.*/export async function anonymizeKafkaPayload(payload: Buffer,contentEncoding?: string | null,pseudoTeam?: string | null,- contentKey?: string | null+ contentKey?: string | null,+ urlKey?: string | null): Promise<AnonymizeKafkaPayloadResult> {const result = await native.anonymizeKafkaPayload(payload,contentEncoding ?? undefined,pseudoTeam ?? undefined,- contentKey ?? undefined+ contentKey ?? undefined,+ urlKey ?? undefined)// Timings are best-effort telemetry: a malformed timings blob must never fail the message.let timings: AnonymizeTimings | null = nulldiff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 8b067e748869..91d3f0a7f64c 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -12,7 +12,7 @@ use std::sync::RwLock;use neon::prelude::*;use neon::types::buffer::TypedArray;use posthog_replay_anonymizer::{- snapshot, AllowLists, FailKind, ImageCollection, ImagePolicy, PhaseTimings,+ snapshot, AllowLists, FailKind, ImageCollection, ImagePolicy, PhaseTimings, UrlCollection,};use serde::Deserialize;@@ -99,13 +99,27 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {};let pseudo_team = opt_string_arg(&mut cx, 2)?;let content_key = opt_string_arg(&mut cx, 3)?;- let image_collection = match (pseudo_team, content_key) {+ // The URL lane is enabled independently of the image lane, but it needs the same pseudonym, so+ // a urlKey without a pseudoTeam is a mis-keyed ref rather than a partial opt-in.+ let url_key = opt_string_arg(&mut cx, 4)?;+ // Each lane needs the pseudonym, because its ref embeds it, and its own per-team key. A key+ // without the pseudonym would mint refs nothing can attribute, so it fails loudly instead.+ if pseudo_team.is_none() && (content_key.is_some() || url_key.is_some()) {+ return cx.throw_error("contentKey and urlKey each require pseudoTeam");+ }+ let image_collection = match (pseudo_team.clone(), content_key) {(Some(pseudo_team), Some(content_key)) => Some(ImageCollection {pseudo_team,content_key,}),- (None, None) => None,- _ => return cx.throw_error("pseudoTeam and contentKey must be passed together"),+ _ => None,+ };+ let url_collection = match (pseudo_team, url_key) {+ (Some(pseudo_team), Some(url_key)) => Some(UrlCollection {+ pseudo_team,+ url_key,+ }),+ _ => None,};// Created on the JS thread so every offset shares one monotonic origin: the task-start mark// becomes the threadpool queue wait, and no wall clock is involved.@@ -131,7 +145,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {};timings.decompress_finished();timings.scrub_started();- let scrubbed = snapshot::anonymize_kafka_payload_timed(+ let scrubbed = snapshot::anonymize_kafka_payload_collecting(allow,&mut payload,snapshot::AnonymizeOpts {@@ -140,6 +154,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {},Some(&timings),image_collection,+ url_collection,);timings.scrub_finished();match scrubbed {diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 401f5e78fe37..6d1fabd64ff0 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.4.1"+version = "0.4.2"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"@@ -30,6 +30,7 @@ serde = { workspace = true }serde_json = { workspace = true }sha2 = { workspace = true }simd-json = { version = "0.15", features = ["serde_impl"] }+public-suffix = { workspace = true }url = { workspace = true }zstd = { workspace = true }diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rsindex b8dd6984bb2c..7b8d9ce1793e 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -31,6 +31,48 @@ pub fn is_media_src_attr(name: &str) -> bool {MEDIA_SRC_ATTRS.contains(&name)}+/// True for a tag whose `src` names an image.+///+/// `TagKind::Media` is too broad to decide this. It also covers `video`, `audio`, `track` and+/// `source`. Their `src` is a movie, a sound file, or a WebVTT subtitle document.+///+/// `source` is excluded because its meaning depends on its parent, and the walk does not carry+/// one.+pub(crate) fn tag_src_is_image(tag: &str) -> bool {+ matches!(+ tag.to_ascii_lowercase().as_str(),+ "img" | "image" | "picture"+ )+}++/// Whether the fetch lane may collect the URL in this attribute.+///+/// A subset of [`MEDIA_SRC_ATTRS`], because the rest do not name one fetchable image.+///+/// `src` and `rr_src` need the tag as well as the name.+///+/// Without the tag check, the lane collects the `src` of a `<video>`, an `<audio>` or a `<track>`.+/// The mutation path is worse: rrweb sends attributes with no tag, so any `src` passes, including+/// one from an `<iframe>` or a `<script>`.+///+/// The fetch lane is sized to download images. Video, subtitle text and third-party JavaScript are+/// a different workload and a different data-classification question. `tag_src_is_image` is false+/// on the tagless mutation path, so that path declines rather than guesses.+///+/// `poster` needs no tag check. It exists only on a video element and it always names a still+/// image.+///+/// `srcset` holds several candidates with descriptors, so it needs a parse and a choice of which+/// candidate to fetch. `href` and `xlink:href` on a media tag are as often a link or an SVG+/// fragment reference as an image. Both can be added later without changing anything else here.+pub(crate) fn is_fetchable_src_attr(name: &str, tag_src_is_image: bool) -> bool {+ match name {+ "poster" => true,+ "src" | "rr_src" => tag_src_is_image,+ _ => false,+ }+}+/// True if an attribute map contains any media-source attribute.pub fn has_media_src_attr(attrs: &Object<'_>) -> bool {MEDIA_SRC_ATTRS.iter().any(|name| attrs.contains_key(*name))@@ -53,7 +95,7 @@ pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str)/// Replace a media element's source attrs with the blurred image (data URIs) or placeholder (remote/// URLs, whose scrubbed original is stashed under a namespaced attr). Returns whether it changed any/// attribute — a media tag with no source attrs (e.g. a bare `<img>`) is left untouched.-pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {+pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>, tag_src_is_image: bool) -> bool {let mut acted = false;for key in MEDIA_SRC_ATTRS {let Some(existing) = attrs.get(*key).and_then(as_str).map(str::to_string) else {@@ -72,12 +114,22 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {let blurred = ctx.scrub_image(&existing, ImageFallback::Placeholder);attrs.insert(Cow::Borrowed(*key), string_value(blurred));} else {+ // A ref here means the fetch lane downloads this URL and scrubs it out of band. The+ // attribute can therefore carry a join key instead of the placeholder. Until those bytes+ // land the ref is dangling, which readers already render as the placeholder, so the+ // worst case matches the behaviour this replaces.+ let collected = is_fetchable_src_attr(key, tag_src_is_image)+ .then(|| ctx.collect_url(&existing))+ .flatten();// 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)),- );+ match collected {+ Some(url_ref) => attrs.insert(Cow::Borrowed(*key), string_value(url_ref)),+ None => attrs.insert(+ Cow::Borrowed(*key),+ Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),+ ),+ };attrs.insert(Cow::Owned(format!("data-anon-original-{key}")),string_value(scrubbed),diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex 851b87699120..9f743abbd0ef 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -13,7 +13,9 @@//! scrubber), any object with more keys than the dup check covers, or any structural surprise makes//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.-use crate::assets::{is_media_src_attr, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC};+use crate::assets::{+ is_fetchable_src_attr, is_media_src_attr, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC,+};use crate::blur::is_image_data_uri;use crate::collect::is_image_ref_strict;use crate::context::Ctx;@@ -708,12 +710,14 @@ impl<'c, 'a> Walker<'c, 'a> {scan::parse_number(bytes, v).and_then(|n| (n.fract() == 0.0 && (0.0..=255.0).contains(&n)).then_some(n as u8))});- let kind = match tag_m {+ let tag = match tag_m {Some((_, v)) if scan::is_string(bytes, v) => {- classify_tag(&scan::unescape(bytes, v).ok()?)+ scan::unescape(bytes, v).ok()?.into_owned()}- _ => classify_tag(""),+ _ => String::new(),};+ let kind = classify_tag(&tag);+ let tag_src_is_image = crate::assets::tag_src_is_image(&tag);let node_changed = self.changed != changed_before;match ty {@@ -734,7 +738,7 @@ impl<'c, 'a> Walker<'c, 'a> {// Attributes with the real tag kind (media blur vs plain scrubs).if let Some((key, v)) = attrs_m {emit_deferred_key(bytes, key, &mut emitted, out);- self.walk_attrs(v.0, kind, out)?;+ self.walk_attrs(v.0, kind, tag_src_is_image, out)?;}for (key, v) in [ty_m, tag_m, is_style_m, text_m].into_iter().flatten() {emit_deferred_key(bytes, key, &mut emitted, out);@@ -824,7 +828,13 @@ impl<'c, 'a> Walker<'c, 'a> {/// An element's `attributes` object (mirrors `dom::scrub_attrs`, including the media blur)./// Stash attrs (`data-anon-original-*`) are appended before the closing brace; the tree path/// inserts them into the map instead, which is the same object semantically.- fn walk_attrs(&mut self, start: usize, kind: TagKind, out: &mut Vec<u8>) -> Option<usize> {+ fn walk_attrs(+ &mut self,+ start: usize,+ kind: TagKind,+ tag_src_is_image: bool,+ out: &mut Vec<u8>,+ ) -> Option<usize> {if self.bytes.get(start) != Some(&b'{') {return self.copy_value(start, out);}@@ -834,7 +844,7 @@ impl<'c, 'a> Walker<'c, 'a> {self.walk_object(start, out, &mut |w, key, vstart, out| {let name = std::str::from_utf8(&w.bytes[key.0..key.1]).ok()?;if kind == TagKind::Media && is_media_src_attr(name) {- return w.blur_media_src(name, vstart, out, stashes);+ return w.blur_media_src(name, vstart, tag_src_is_image, out, stashes);}if name == INLINE_IMAGE_ATTR {return w.scrub_string_value(vstart, out, |w, s| {@@ -883,11 +893,13 @@ impl<'c, 'a> Walker<'c, 'a> {}/// One media source attribute (mirrors `assets::apply_blur` for a single key): data images are- /// blurred; remote URLs become the placeholder with the host-scrubbed original stashed.+ /// blurred; a remote URL becomes a fetch-lane ref when collection is on, and the placeholder+ /// otherwise. Either way the host-scrubbed original is stashed alongside.fn blur_media_src(&mut self,name: &str,vstart: usize,+ tag_src_is_image: bool,out: &mut Vec<u8>,stashes: &mut Vec<(String, String)>,) -> Option<usize> {@@ -907,8 +919,14 @@ impl<'c, 'a> Walker<'c, 'a> {let blurred = self.ctx.scrub_image(&existing, ImageFallback::Placeholder);scan::write_json_string(&blurred, out);} else {+ let collected = is_fetchable_src_attr(name, tag_src_is_image)+ .then(|| self.ctx.collect_url(&existing))+ .flatten();let scrubbed = scrub_url(self.ctx, &existing).unwrap_or_else(|| existing.into_owned());- scan::write_json_string(PLACEHOLDER_SRC, out);+ match collected {+ Some(url_ref) => scan::write_json_string(&url_ref, out),+ None => scan::write_json_string(PLACEHOLDER_SRC, out),+ }stashes.push((format!("data-anon-original-{name}"), scrubbed));}self.changed = true;@@ -960,7 +978,9 @@ impl<'c, 'a> Walker<'c, 'a> {} else {TagKind::Other};- w.walk_attrs(vstart, kind, out)+ // Mutation attributes carry no tag, so a `src` here is not known to be+ // an image. Decline rather than guess.+ w.walk_attrs(vstart, kind, false, out)}_ => w.copy_value(vstart, out),},diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rsindex 64a144601760..6f12bf6b804b 100644--- a/rust/replay-anonymizer/src/collect.rs+++ b/rust/replay-anonymizer/src/collect.rs@@ -34,6 +34,19 @@ pub fn image_ref(pseudo_team: &str, hash: &str) -> String {format!("image:{pseudo_team}:{hash}")}+/// The prefix of a ref whose hash comes from a URL rather than from bytes.+///+/// Deliberately not `image:`. A content ref promises that the hash names the bytes behind it, which+/// is what lets a reader treat one as content-addressed. A URL ref promises only that the hash+/// names the URL the image came from, and the bytes at that URL can change. Sharing one prefix+/// would leave a reader unable to tell which promise it holds, and the failure would be a silent+/// mis-join rather than an error.+pub const URL_REF_PREFIX: &str = "imageurl";++pub fn url_ref(pseudo_team: &str, hash: &str) -> String {+ format!("{URL_REF_PREFIX}:{pseudo_team}:{hash}")+}+/// True for strings shaped like a content ref. The `image:` prefix cannot collide with a data URI,/// a URL (no scheme is registered as `image`), or base64 payloads (`:` is not in the alphabet).///@@ -51,7 +64,10 @@ pub fn is_image_ref(s: &str) -> bool {/// have it copied verbatim into anonymized output. This bounds what can survive to a fixed-width/// opaque token with no room for readable content.pub fn is_image_ref_strict(s: &str) -> bool {- let Some(rest) = s.strip_prefix("image:") else {+ let Some(rest) = s+ .strip_prefix("image:")+ .or_else(|| s.strip_prefix("imageurl:"))+ else {return false;};let Some((team, hash)) = rest.split_once(':') else {diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex b846cfd6a35a..cf4d95a3aca0 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -16,6 +16,7 @@ use crate::blur::{blank_image_data_uri, blur_image_data_uri, pixelate_raw_rgba};use crate::collect::{collectable_data_uri_bytes, CollectedImage, ImageCollection, ImageCollector};use crate::images::{ImageFallback, ImagePolicy, ImageQueue};use crate::timings::PhaseTimings;+use crate::url_collect::{CollectedUrl, UrlCollection, UrlCollector};/// Cumulative decompressed-bytes budget across all cv payloads in one message: the per-payload/// `compression::MAX_DECOMPRESSED_BYTES` cap bounds each field, this bounds their sum so many high-ratio@@ -36,6 +37,8 @@ pub struct Ctx<'a> {images: ImageQueue,// `Some` routes collectable images to the scrub lane instead of the blur (inline or pooled).collector: Option<RefCell<ImageCollector>>,+ // `Some` routes remote image URLs to the fetch lane instead of the media placeholder.+ url_collector: Option<RefCell<UrlCollector>>,// Whether a well-formed ref already present in the *input* is left alone. Off unless the// caller vouches for the input's provenance; see `preserving_image_refs`.preserve_image_refs: bool,@@ -73,6 +76,7 @@ impl<'a> Ctx<'a> {image_policy,images: ImageQueue::default(),collector: image_collection.map(|c| RefCell::new(ImageCollector::new(c))),+ url_collector: None,preserve_image_refs: false,}}@@ -143,6 +147,43 @@ impl<'a> Ctx<'a> {}}+ /// Route remote image URLs to the fetch lane. Off unless set, exactly like image collection,+ /// so a caller that does not opt in keeps the media placeholder it has today.+ pub fn collecting_urls(mut self, url_collection: Option<UrlCollection>) -> Self {+ self.url_collector = url_collection.map(|c| RefCell::new(UrlCollector::new(c)));+ self+ }++ /// The fetch lane's ref for a remote image URL.+ ///+ /// `None` when collection is off, when the URL is not fetchable, or when the per-message cap+ /// is reached. The caller then writes the placeholder, as before.+ pub(crate) fn collect_url(&self, original: &str) -> Option<String> {+ let collector = self.url_collector.as_ref()?;+ collector.borrow_mut().collect(original)+ }++ /// Drain the collected URLs (hash-sorted). Empty when URL collection was off.+ ///+ /// Takes the collector rather than `self`, because the caller drains the images afterwards and+ /// that call consumes the context. A second call therefore returns nothing, which is why this+ /// is not named `into_`.+ /// Counts by reason for the URLs the collector refused. Read before [`Self::take_collected_urls`],+ /// which takes the collector.+ pub fn take_url_declines(&self) -> Vec<(String, u32)> {+ match self.url_collector.as_ref() {+ Some(collector) => collector.borrow().into_declines(),+ None => Vec::new(),+ }+ }++ pub fn take_collected_urls(&mut self) -> Vec<CollectedUrl> {+ match self.url_collector.take() {+ Some(collector) => collector.into_inner().into_urls(),+ None => Vec::new(),+ }+ }+/// Drain the collected images (hash-sorted). Empty when collection was off.pub fn into_collected_images(self) -> Vec<CollectedImage> {match self.collector {diff --git a/rust/replay-anonymizer/src/dom.rs b/rust/replay-anonymizer/src/dom.rsindex ea9361c0c249..1e2b6536bdac 100644--- a/rust/replay-anonymizer/src/dom.rs+++ b/rust/replay-anonymizer/src/dom.rs@@ -96,7 +96,9 @@ pub fn scrub_mutation_attributes(ctx: &Ctx<'_>, attributes: &mut Vec<Value<'_>>)} else {TagKind::Other};- changed |= scrub_attrs(ctx, attrs, kind);+ // A mutation carries attributes with no tag, so a `src` here could belong to an+ // iframe or a script as easily as an image. Decline rather than guess.+ changed |= scrub_attrs(ctx, attrs, kind, false);}}}@@ -125,9 +127,14 @@ pub(crate) fn walk_node(ctx: &Ctx<'_>, node: &mut Value<'_>, parent: ParentKind)match obj.get("type").and_then(as_small_uint) {Some(NODE_ELEMENT) => {- let kind = classify_tag(obj.get("tagName").and_then(as_str).unwrap_or(""));+ let tag = obj+ .get("tagName")+ .and_then(as_str)+ .unwrap_or("")+ .to_string();+ let kind = classify_tag(&tag);if let Some(attrs) = obj.get_mut("attributes").and_then(as_object_mut) {- changed |= scrub_attrs(ctx, attrs, kind);+ changed |= scrub_attrs(ctx, attrs, kind, crate::assets::tag_src_is_image(&tag));}let child_parent = match kind {TagKind::Script => ParentKind::Script,@@ -196,7 +203,12 @@ pub(crate) fn classify_tag(tag: &str) -> TagKind {}}-fn scrub_attrs(ctx: &Ctx<'_>, attrs: &mut Object<'_>, kind: TagKind) -> bool {+fn scrub_attrs(+ ctx: &Ctx<'_>,+ attrs: &mut Object<'_>,+ kind: TagKind,+ tag_src_is_image: bool,+) -> bool {let mut changed = false;// Plain string scrubs mutate values in place while iterating — no per-element key Vec. Only the// helpers that need `&mut Object` (blur inserts sibling keys, css re-reads by key) defer their@@ -246,7 +258,7 @@ fn scrub_attrs(ctx: &Ctx<'_>, attrs: &mut Object<'_>, kind: TagKind) -> bool {}if kind == TagKind::Media {- changed |= apply_blur(ctx, attrs);+ changed |= apply_blur(ctx, attrs, tag_src_is_image);}changeddiff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 6908d43c20f7..9811ee43fed2 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -60,6 +60,10 @@ mod unwind;#[doc(hidden)]pub mod url;#[doc(hidden)]+pub mod url_collect;+#[doc(hidden)]+pub mod url_policy;+#[doc(hidden)]pub mod value;pub use allow_lists::AllowLists;@@ -71,12 +75,14 @@ pub use event::{};pub use images::ImagePolicy;pub use snapshot::{- anonymize_kafka_payload, anonymize_kafka_payload_opts, anonymize_kafka_payload_timed,- AnonymizeOpts, AnonymizedMessage, FailKind, Failure, Route,+ anonymize_kafka_payload, anonymize_kafka_payload_collecting, anonymize_kafka_payload_opts,+ anonymize_kafka_payload_timed, AnonymizeOpts, AnonymizedMessage, FailKind, Failure, Route,};pub use timings::{PhaseTimings, PhaseTimingsSnapshot};#[cfg(feature = "typed-parse")]pub use typed::{parse_scrubbed_event, parse_scrubbed_event_with_ctx};+pub use url_collect::{CollectedUrl, UrlCollection};+pub use url_policy::{canonicalize, is_public_host, CanonicalUrl};/// Shared helpers for the image-neutralization tests across modules.#[cfg(test)]diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex cf13a20b79c2..fad7ada3a84e 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -41,6 +41,7 @@ use crate::json::{};use crate::scan::{self, Span};use crate::timings::PhaseTimings;+use crate::url_collect::UrlCollection;/// Why a payload could not be anonymized; maps onto the TS pipeline's dlq/drop reasons so the fused/// step classifies failures exactly like the TS parse step does.@@ -134,6 +135,18 @@ pub struct ImageEntry {pub len: usize,}+/// One collected remote image URL, on its way to the fetch lane.+///+/// The payload travels inline, not in a side buffer like [`ImageEntry`]. A URL is small, and it is+/// the thing the fetcher needs, so there is nothing to pack.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct UrlEntry {+ pub hash: String,+ pub url: String,+ pub host: String,+ pub domain: String,+}+/// Message envelope + per-event metadata the TS scaffolding needs for routing/batching.#[derive(Debug, Serialize, PartialEq)]#[serde(rename_all = "camelCase")]@@ -156,6 +169,21 @@ pub struct SnapshotMeta {/// Collected original images (hash-sorted); non-empty only on the image-collection lane.#[serde(skip_serializing_if = "Vec::is_empty")]pub images: Vec<ImageEntry>,+ /// Collected remote image URLs (hash-sorted); non-empty only on the URL-collection lane.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub urls: Vec<UrlEntry>,+ /// Counts by reason for the URLs the collector refused. Every decline is otherwise invisible,+ /// and the phase that measures this lane would report a smaller URL set than the traffic holds+ /// with nothing to say why.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub url_declines: Vec<UrlDecline>,+}++/// One reason the collector refused a URL, and how many times it did.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct UrlDecline {+ pub reason: String,+ pub count: u32,}/// Which implementation produced the output (tree = the whole-message fallback fired). Both are@@ -257,9 +285,32 @@ pub fn anonymize_kafka_payload_timed(opts: AnonymizeOpts,timings: Option<&PhaseTimings>,image_collection: Option<ImageCollection>,+) -> SResult<AnonymizedMessage> {+ anonymize_kafka_payload_collecting(allow, payload, opts, timings, image_collection, None)+}++/// [`anonymize_kafka_payload_timed`] with the URL-collection lane as well.+///+/// A remote image's `src` becomes a ref, and its original URL comes back in `meta.urls`. The+/// caller passes those to the fetch lane. `None` leaves a remote image on the media placeholder,+/// which is what every other entry point here does.+pub fn anonymize_kafka_payload_collecting(+ allow: &AllowLists,+ payload: &mut [u8],+ opts: AnonymizeOpts,+ timings: Option<&PhaseTimings>,+ image_collection: Option<ImageCollection>,+ url_collection: Option<UrlCollection>,) -> SResult<AnonymizedMessage> {contain_panics(|| {- anonymize_kafka_payload_opts_impl(allow, payload, opts, timings, image_collection)+ anonymize_kafka_payload_opts_impl(+ allow,+ payload,+ opts,+ timings,+ image_collection,+ url_collection,+ )})}@@ -269,6 +320,7 @@ fn anonymize_kafka_payload_opts_impl(opts: AnonymizeOpts,timings: Option<&PhaseTimings>,image_collection: Option<ImageCollection>,+ url_collection: Option<UrlCollection>,) -> 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.@@ -279,6 +331,7 @@ fn anonymize_kafka_payload_opts_impl(opts,timings,image_collection,+ url_collection,);};let distinct_id = distinct_id.into_owned();@@ -304,9 +357,17 @@ fn anonymize_kafka_payload_opts_impl(opts,timings,image_collection,+ url_collection,);}- anonymize_kafka_payload_via_parse(allow, payload, opts, timings, image_collection)+ anonymize_kafka_payload_via_parse(+ allow,+ payload,+ opts,+ timings,+ image_collection,+ url_collection,+ )}/// Locate the `distinct_id` + `data` string spans by scanning the outer object. `None` means "let@@ -383,6 +444,7 @@ fn anonymize_kafka_payload_via_parse(opts: AnonymizeOpts,timings: Option<&PhaseTimings>,image_collection: Option<ImageCollection>,+ url_collection: Option<UrlCollection>,) -> SResult<AnonymizedMessage> {reject_if_too_deep(payload, "kafka payload").map_err(|e| Failure::new(FailKind::InvalidJson, e.to_string()))?;@@ -415,6 +477,7 @@ fn anonymize_kafka_payload_via_parse(opts,timings,image_collection,+ url_collection,)}@@ -437,7 +500,15 @@ pub fn anonymize_snapshot_data_opts(image_collection: Option<ImageCollection>,) -> SResult<AnonymizedMessage> {contain_panics(|| {- anonymize_snapshot_data_inner(allow, distinct_id, inner, opts, None, image_collection)+ anonymize_snapshot_data_inner(+ allow,+ distinct_id,+ inner,+ opts,+ None,+ image_collection,+ None,+ )})}@@ -448,17 +519,34 @@ fn anonymize_snapshot_data_inner(opts: AnonymizeOpts,timings: Option<&PhaseTimings>,image_collection: Option<ImageCollection>,+ url_collection: Option<UrlCollection>,) -> 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::with_options(allow, timings, opts.image_policy, image_collection);+ let mut ctx = Ctx::with_options(allow, timings, opts.image_policy, image_collection)+ .collecting_urls(url_collection);let mut msg = match stream_message(&ctx, distinct_id, inner, opts)? {Some(msg) => msg,// Escaped/duplicate envelope keys: only a real parse resolves them, and nothing was// consumed before the signal, so the tree path re-reads the intact buffer.None => anonymize_via_tree_mut(&ctx, distinct_id, inner)?,};+ msg.meta.url_declines = ctx+ .take_url_declines()+ .into_iter()+ .map(|(reason, count)| UrlDecline { reason, count })+ .collect();+ msg.meta.urls = ctx+ .take_collected_urls()+ .into_iter()+ .map(|u| UrlEntry {+ hash: u.hash,+ url: u.url,+ host: u.host,+ domain: u.domain,+ })+ .collect();let (entries, image_bytes) = pack_images(ctx.into_collected_images());msg.meta.images = entries;msg.image_bytes = image_bytes;@@ -895,6 +983,8 @@ fn finish(events: sink.events,// The collector lives on the Ctx, not the Sink; the entry point packs it in.images: Vec::new(),+ urls: Vec::new(),+ url_declines: Vec::new(),},image_bytes: Vec::new(),})diff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rsnew file mode 100644index 000000000000..1ae16e4c9379--- /dev/null+++ b/rust/replay-anonymizer/src/url_collect.rs@@ -0,0 +1,313 @@+//! Collect the original URLs of remote images, for the out-of-band fetch lane.+//!+//! The sibling of [`crate::collect`]. That module handles an image the page inlined into the+//! recording; this one handles an image the page referred to by URL. With collection enabled, a+//! media source attribute holding an `http(s)` URL is replaced by a content ref instead of the+//! media placeholder. The message then carries the original URL back to the caller.+//!+//! **Two URLs come out of this module. Do not confuse them.**+//!+//! The *dedup* URL is canonical, and its volatile parameters are removed. It is the only input to+//! the hash, so it sets the ref and the dedup key of the fetch lane.+//!+//! The *fetch* URL is canonical, and every parameter stays. The fetcher requests this one. A+//! signed URL works only in this form, and it dedups only in the first form.+//!+//! That split is what makes the ref stable. A URL that carries a fresh signature on each page+//! load would otherwise mint a new ref every time. A ref that appears once joins to nothing+//! downstream. Removing the volatile parameters matters more for that than it does for+//! the request count.+//!+//! The hash is a *keyed* HMAC, for the same reason as the image hash. The ML bucket is not+//! encrypted. An unkeyed digest of a URL would let a reader of the bucket learn which sites the+//! users of a team visited.+//!+//! The caller derives the per-team key from the same KMS-held secret as the team pseudonym.+//! Neither the secret nor the key leaves the ingester.++use std::collections::{HashMap, HashSet};++use base64::Engine;+use hmac::{Hmac, Mac};+use sha2::Sha256;++use crate::url_policy::{try_canonicalize, MAX_URL_LEN};+/// Distinct raw values one message may memoize.+///+/// Larger than [`MAX_URLS_PER_MESSAGE`] on purpose, because the memo also holds the values this+/// collector declined, and a decline is exactly what a repeat should not pay for twice. Past this+/// the memo stops growing and repeats fall back to the full check, which is slower and bounded+/// rather than unbounded.+const MAX_MEMO_ENTRIES: usize = 1024;++/// Distinct URLs collected from one message. A page with more media than this is already past the+/// point where the extra images teach a model anything, and the cap bounds the Kafka fan-out.+pub const MAX_URLS_PER_MESSAGE: usize = 256;++/// Enables URL collection for one anonymize call.+#[derive(Debug, Clone)]+pub struct UrlCollection {+ /// The non-reversible HMAC team pseudonym (32 hex chars), computed by the caller. Embedded+ /// verbatim in every emitted ref, exactly as on the image lane.+ pub pseudo_team: String,+ /// Per-team key for the URL HMAC. The caller derives it under its own domain separator, so a+ /// URL ref and an image ref stay distinct for one team.+ pub url_key: String,+}++/// One collected URL, on its way to the fetch topic.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CollectedUrl {+ /// First 22 base64url chars of `HMAC-SHA256(url_key, dedup_url)`.+ pub hash: String,+ /// The canonical URL with every parameter intact. This is what the fetcher requests.+ pub url: String,+ /// The host the request goes to. robots.txt and the connection limit are scoped to this.+ pub host: String,+ /// The registrable domain of `host`, which the fetch topic uses as its Kafka key so every URL+ /// of one operator lands on one partition. See `url_policy::politeness_key`.+ pub domain: String,+}++/// First 22 base64url chars of `HMAC-SHA256(url_key, dedup_url)`. Same construction and width as+/// [`crate::collect::hash_image_bytes`], but carried under the `imageurl:` prefix, because this+/// hash names a URL rather than the bytes behind it.+pub fn hash_url(url_key: &[u8], dedup_url: &str) -> String {+ let mut mac = Hmac::<Sha256>::new_from_slice(url_key).expect("hmac accepts any key length");+ mac.update(dedup_url.as_bytes());+ let digest = mac.finalize().into_bytes();+ let mut b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest);+ b64.truncate(22);+ b64+}++/// Accumulates the remote image URLs of one message, deduplicated on the hash.+pub struct UrlCollector {+ pseudo_team: String,+ url_key: String,+ urls: Vec<CollectedUrl>,+ seen: HashSet<String>,+ /// One image recurs many times in a message, so a repeat must not pay a parse and an HMAC+ /// again. A page controls these keys, hence [`MAX_MEMO_ENTRIES`].+ memo: HashMap<String, Option<String>>,+ /// A refusal is invisible in the collected count, so the lane would look like traffic carries+ /// fewer images than it does.+ declines: HashMap<&'static str, u32>,+}++impl UrlCollector {+ pub fn new(collection: UrlCollection) -> Self {+ Self {+ pseudo_team: collection.pseudo_team,+ url_key: collection.url_key,+ urls: Vec::new(),+ seen: HashSet::new(),+ memo: HashMap::new(),+ declines: HashMap::new(),+ }+ }++ /// Collect a remote image URL and return its ref, or `None` when the URL is not fetchable or a+ /// cap says this one stays on the placeholder path.+ pub fn collect(&mut self, raw: &str) -> Option<String> {+ if let Some(remembered) = self.memo.get(raw) {+ return remembered.clone();+ }+ if self.is_full() {+ self.decline("over_cap");+ return None;+ }+ let result = self.collect_uncached(raw);+ if self.is_worth_remembering(raw) {+ self.memo.insert(raw.to_string(), result.clone());+ }+ result+ }++ fn is_full(&self) -> bool {+ self.urls.len() >= MAX_URLS_PER_MESSAGE+ }++ /// An over-length value is refused by a length check alone, so remembering it would only store+ /// the longest strings a page offers.+ fn is_worth_remembering(&self, raw: &str) -> bool {+ raw.len() <= MAX_URL_LEN && self.memo.len() < MAX_MEMO_ENTRIES+ }++ fn decline(&mut self, reason: &'static str) {+ *self.declines.entry(reason).or_insert(0) += 1;+ }++ fn collect_uncached(&mut self, raw: &str) -> Option<String> {+ let canonical = match try_canonicalize(raw) {+ Ok(c) => c,+ Err(reason) => {+ self.decline(reason.label());+ return None;+ }+ };+ let hash = hash_url(self.url_key.as_bytes(), &canonical.dedup);+ if self.seen.contains(&hash) {+ return Some(crate::collect::url_ref(&self.pseudo_team, &hash));+ }+ self.seen.insert(hash.clone());+ self.urls.push(CollectedUrl {+ hash: hash.clone(),+ url: canonical.fetch,+ host: canonical.host,+ domain: canonical.domain,+ });+ Some(crate::collect::url_ref(&self.pseudo_team, &hash))+ }++ /// Counts by reason for the URLs this collector refused.+ pub fn into_declines(&self) -> Vec<(String, u32)> {+ let mut out: Vec<(String, u32)> = self+ .declines+ .iter()+ .map(|(k, v)| ((*k).to_string(), *v))+ .collect();+ out.sort_by(|a, b| a.0.cmp(&b.0));+ out+ }++ /// Drain, sorted by hash. A deterministic order that cannot depend on which engine walked the+ /// message, which is what lets the differential tests compare meta directly.+ pub fn into_urls(mut self) -> Vec<CollectedUrl> {+ self.urls.sort_by(|a, b| a.hash.cmp(&b.hash));+ self.urls+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ const TEST_KEY: &[u8] = b"0123456789abcdef0123456789abcdef";++ fn collector() -> UrlCollector {+ UrlCollector::new(UrlCollection {+ pseudo_team: "a".repeat(32),+ url_key: String::from_utf8(TEST_KEY.to_vec()).unwrap(),+ })+ }++ #[test]+ fn hash_is_22_base64url_chars_and_keyed() {+ let hash = hash_url(TEST_KEY, "https://example.com/a.png");+ assert_eq!(hash.len(), 22);+ assert!(hash+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));+ assert_ne!(hash, hash_url(b"another-key", "https://example.com/a.png"));+ }++ #[test]+ fn ref_matches_the_consumer_shape_and_says_it_came_from_a_url() {+ let mut c = collector();+ let r = c.collect("https://example.com/a.png").unwrap();+ assert!(crate::collect::is_image_ref_strict(&r));+ // The prefix is what tells a reader the hash names a URL, not the bytes behind it.+ assert!(r.starts_with("imageurl:"), "got {r}");+ }++ #[test]+ fn two_signatures_of_one_image_share_a_ref() {+ let mut c = collector();+ let first = c+ .collect("https://cdn.example.com/a.png?X-Amz-Signature=aaa")+ .unwrap();+ let second = c+ .collect("https://cdn.example.com/a.png?X-Amz-Signature=bbb")+ .unwrap();+ assert_eq!(first, second);+ // One entry, and it keeps the URL of the first sighting, which is a URL that still works.+ let urls = c.into_urls();+ assert_eq!(urls.len(), 1);+ assert!(urls[0].url.contains("X-Amz-Signature=aaa"));+ }++ #[test]+ fn a_resize_parameter_is_not_volatile() {+ // Collapsing these onto one ref would point one ref at two different images.+ let mut c = collector();+ let small = c.collect("https://cdn.example.com/a.png?w=100").unwrap();+ let large = c.collect("https://cdn.example.com/a.png?w=900").unwrap();+ assert_ne!(small, large);+ assert_eq!(c.into_urls().len(), 2);+ }++ #[test]+ fn collect_stops_at_the_cap_but_still_refs_a_url_it_already_holds() {+ let mut c = collector();+ for i in 0..MAX_URLS_PER_MESSAGE {+ assert!(c.collect(&format!("https://example.com/{i}.png")).is_some());+ }+ assert!(c.collect("https://example.com/one-too-many.png").is_none());+ assert!(c.collect("https://example.com/0.png").is_some());+ assert_eq!(c.into_urls().len(), MAX_URLS_PER_MESSAGE);+ }++ #[test]+ fn into_urls_sorts_by_hash() {+ let mut c = collector();+ c.collect("https://example.com/b.png");+ c.collect("https://example.com/a.png");+ let urls = c.into_urls();+ assert!(urls[0].hash < urls[1].hash);+ }++ #[test]+ fn a_repeated_url_is_hashed_once() {+ let mut c = collector();+ let first = c.collect("https://cdn.example.com/sprite.png").unwrap();+ let second = c.collect("https://cdn.example.com/sprite.png").unwrap();+ assert_eq!(first, second);+ assert_eq!(c.memo.len(), 1, "the second occurrence comes from the memo");+ assert_eq!(c.into_urls().len(), 1);+ }++ #[test]+ fn past_the_cap_a_new_url_costs_no_parse() {+ // A payload can carry far more distinct URLs than the cap. Each one used to pay a full+ // canonicalization and an HMAC before the cap rejected it.+ let mut c = collector();+ for i in 0..MAX_URLS_PER_MESSAGE {+ assert!(c.collect(&format!("https://example.com/{i}.png")).is_some());+ }+ // Declined without being canonicalized, so it never reaches the memo either.+ let before = c.memo.len();+ assert!(c.collect("https://example.com/past-the-cap.png").is_none());+ assert_eq!(+ c.memo.len(),+ before,+ "a declined URL past the cap is not memoized"+ );+ // A URL already held still resolves, because its raw value is in the memo.+ assert!(c.collect("https://example.com/0.png").is_some());+ }++ #[test]+ fn the_memo_is_bounded_against_attacker_controlled_values() {+ // Declined values are the vector: they never reach the URL cap, so only the memo's own cap+ // bounds them. A page can carry as many distinct unfetchable `src` values as it likes.+ let mut c = collector();+ for i in 0..(MAX_MEMO_ENTRIES + 500) {+ assert!(c.collect(&format!("http://10.0.0.5/{i}.png")).is_none());+ }+ assert_eq!(c.memo.len(), MAX_MEMO_ENTRIES);++ // An over-length value is rejected by an O(1) check, so it is never worth storing.+ let mut c = collector();+ let long = format!("https://example.com/{}", "a".repeat(MAX_URL_LEN));+ assert!(c.collect(&long).is_none());+ assert!(c.memo.is_empty());+ }++ #[test]+ fn a_declined_url_is_memoized_too() {+ let mut c = collector();+ assert!(c.collect("http://localhost/i.png").is_none());+ assert!(c.collect("http://localhost/i.png").is_none());+ assert_eq!(c.memo.len(), 1);+ }+}diff --git a/rust/replay-anonymizer/src/url_policy.rs b/rust/replay-anonymizer/src/url_policy.rsnew file mode 100644index 000000000000..0ae524f33725--- /dev/null+++ b/rust/replay-anonymizer/src/url_policy.rs@@ -0,0 +1,570 @@+//! The rules that decide whether a remote image URL may be fetched, and what its canonical forms+//! are.+//!+//! Separate from [`crate::url_collect`] on purpose. That module accumulates the URLs of one+//! message. This one holds the policy, and the policy has more than one consumer.+//!+//! The fetch lane applies the same host rule again at request time. It applies it to the resolved+//! address, and to every redirect hop, because a name that resolves publicly now can resolve+//! privately later. The fetch lane also canonicalizes what it fetched, to find its ledger entry.+//!+//! The fetch lane runs in another language. The registrable domain therefore travels with each+//! URL as data, so that lane reads the result and never repeats the rule.++use std::collections::HashSet;+use std::net::{IpAddr, Ipv4Addr};++use public_suffix::{EffectiveTLDProvider, DEFAULT_PROVIDER};++use url::Url;++/// Query parameters that change on each page load without changing the image behind the URL.+///+/// **This is an allow list of names. It must stay one.**+///+/// Never add a rule about the *shape* of a value. "Looks random" and "is long" both describe real+/// image parameters.+///+/// **Never add a name that also selects an image.** `w`, `h`, `q`, `fm`, `dpr`, `fit`, `auto`,+/// `format`, `resize`, `crop` and `quality` all do. Collapsing those onto one ref would point one+/// ref at several genuinely different images, and nothing downstream can detect it.+///+/// Only unambiguous names live here. A short name that one vendor uses for a signature and another+/// uses for a size belongs in [`SCOPED_VOLATILE_PARAMS`], where a marker keeps it honest.+///+/// `s` is the name that forced the split. imgix signs with it. Gravatar sizes with it. Removing it+/// everywhere made a 48-pixel avatar and a 200-pixel avatar the same image.+const VOLATILE_PARAMS: &[&str] = &[+ // AWS SigV4 presigned (S3, CloudFront). Long and vendor-prefixed, so unambiguous.+ "x-amz-algorithm",+ "x-amz-credential",+ "x-amz-date",+ "x-amz-expires",+ "x-amz-signedheaders",+ "x-amz-signature",+ "x-amz-security-token",+ // CloudFront canned policies. key-pair-id is vendor-specific enough to stand alone.+ "key-pair-id",+ // Google Cloud Storage V4.+ "x-goog-algorithm",+ "x-goog-credential",+ "x-goog-date",+ "x-goog-expires",+ "x-goog-signedheaders",+ "x-goog-signature",+ // Akamai token auth.+ "hdnts",+ "hdnea",+ "hdntl",+ "__token__",+ // Cache busters whose names say so.+ "cb",+ "rnd",+ "nocache",+];++/// Volatile names that are only volatile in a known context.+///+/// Each entry is `(marker, names)`. The names are removed only when the query also carries the+/// marker, which is a parameter the vendor always sends alongside them. Without the marker the+/// names are left alone, because on another host they select an image.+const SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] = &[+ // Azure Blob shared access signatures always carry sig, and sv alongside the rest.+ (+ "sig",+ &["sv", "st", "se", "sp", "sr", "sig", "spr", "skoid"],+ ),+ // Meta's CDN always carries _nc_ohc with the rest of its rotating set. stp encodes a crop, so+ // it is only safe to drop when the whole set is present and the URL is therefore one of theirs.+ ("_nc_ohc", &["_nc_ohc", "_nc_ht", "oh", "oe", "ccb", "stp"]),+ // CloudFront canned policies pair Signature with Expires and Policy. Both are ordinary words+ // elsewhere: `expires` is a real cache hint, and `policy=thumb` is a plausible image selector.+ ("signature", &["signature", "expires", "policy"]),+ ("key-pair-id", &["policy", "expires"]),+];++/// Hosts whose short signature parameter is safe to remove, because the vendor owns the host.+const HOST_SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] = &[(".imgix.net", &["s", "expires"])];++/// Longer than this and we neither collect nor fetch it. Well past what a real image URL needs,+/// and it bounds what one message can pin in memory alongside the count cap.+pub const MAX_URL_LEN: usize = 2048;++/// The politeness unit for a host: the registrable domain, or the host itself when it has none.+///+/// A rate limit protects the operator that answers the request, not a DNS label. A CDN that shards+/// over `img1..img8.cdn.example.com` would otherwise receive eight times the intended rate.+/// The fetch topic keys on this, so every URL of one operator lands on one partition and one pod+/// holds its budget without a distributed lock.+///+/// The public suffix list draws the boundary, and its private section is what makes this correct+/// for multi-tenant hosts. `d111.cloudfront.net`, `bucket.s3.amazonaws.com`, `user.github.io` and+/// `myapp.vercel.app` are each their own registrable domain, because `cloudfront.net`,+/// `s3.amazonaws.com`, `github.io` and `vercel.app` are all public suffixes. One tenant therefore+/// never shares a budget with an unrelated tenant of the same provider.+///+/// An IP literal has no registrable domain and returns unchanged, which is right: the address is+/// the operator.+pub fn politeness_key(host: &str) -> String {+ if host.parse::<IpAddr>().is_ok() || host.starts_with('[') {+ return host.to_string();+ }+ match DEFAULT_PROVIDER.effective_tld_plus_one(host) {+ Ok(domain) => domain.to_string(),+ // A host with no registrable domain is its own operator. `is_public_host` already declined+ // the bare names this could otherwise return.+ Err(_) => host.to_string(),+ }+}++/// The two forms of one URL. See the module docs for why both exist.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CanonicalUrl {+ pub fetch: String,+ pub dedup: String,+ pub host: String,+ /// The registrable domain of `host`. See [`politeness_key`].+ pub domain: String,+}++/// Whether one parameter of this URL is volatile.+///+/// The name set is built once per URL. A scan of the parameter list made this quadratic in the+/// parameter count, and a page controls both that count and the number of URLs.+fn is_volatile(name: &str, host: &str, names_on_this_url: &HashSet<String>) -> bool {+ if VOLATILE_PARAMS.iter().any(|p| p.eq_ignore_ascii_case(name)) {+ return true;+ }+ for (marker, names) in SCOPED_VOLATILE_PARAMS {+ if names.iter().any(|p| p.eq_ignore_ascii_case(name)) && names_on_this_url.contains(*marker)+ {+ return true;+ }+ }+ for (suffix, names) in HOST_SCOPED_VOLATILE_PARAMS {+ if host.ends_with(suffix) && names.iter().any(|p| p.eq_ignore_ascii_case(name)) {+ return true;+ }+ }+ false+}++/// Whether a host is one we would ever fetch from.+///+/// A page controls the URL set, and the set exists to be handed to something that makes outbound+/// requests from inside our network. A page carrying+/// `<img src="http://169.254.169.254/...">` must not become a fetch instruction for the cloud+/// metadata endpoint.+///+/// This is not a substitute for a check at fetch time. A name that resolves publicly now can+/// resolve privately later. The fetcher therefore validates the address DNS returns, on the first+/// request and on every redirect hop.+pub fn is_public_host(host: &str) -> bool {+ let host = without_brackets_or_trailing_dot(host);+ if let Ok(ip) = host.parse::<IpAddr>() {+ return is_public_ip(ip);+ }+ is_public_domain_name(&host.to_ascii_lowercase())+}++/// `[2606:4700::1111]` becomes `2606:4700::1111`, and `localhost.` becomes `localhost`.+///+/// A trailing dot makes a name fully qualified and resolves identically, so leaving it on let+/// `localhost.` past the name check below: the label after the final dot is empty and matches+/// nothing.+fn without_brackets_or_trailing_dot(host: &str) -> &str {+ let bare = host.trim_matches(|c| c == '[' || c == ']');+ bare.strip_suffix('.').unwrap_or(bare)+}++fn is_public_domain_name(lowercase_host: &str) -> bool {+ let has_no_dot = !lowercase_host.contains('.');+ let has_empty_label = lowercase_host.split('.').any(|label| label.is_empty());+ if has_no_dot || has_empty_label {+ return false;+ }+ !matches!(+ lowercase_host.rsplit('.').next(),+ Some(+ "localhost"+ | "local"+ | "internal"+ | "intranet"+ | "lan"+ | "home"+ | "corp"+ | "test"+ | "invalid"+ | "example"+ )+ )+}++/// IPv6 offers several ways to write an IPv4 address, and each one used to bypass most of the IPv4+/// rules. Every embedding is now judged by [`is_public_v4`].+fn is_public_ip(ip: IpAddr) -> bool {+ let v6 = match ip {+ IpAddr::V4(v4) => return is_public_v4(v4),+ IpAddr::V6(v6) => v6,+ };+ if v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() {+ return false;+ }+ let segments = v6.segments();+ let is_unique_local = (segments[0] & 0xfe00) == 0xfc00;+ let is_link_local = (segments[0] & 0xffc0) == 0xfe80;+ if is_unique_local || is_link_local {+ return false;+ }+ match v6+ .to_ipv4_mapped()+ .or_else(|| v6.to_ipv4())+ .or_else(|| ipv4_inside_6to4(segments))+ .or_else(|| ipv4_inside_nat64(segments))+ {+ Some(v4) => is_public_v4(v4),+ None => true,+ }+}++/// 6to4 carries the address in the two segments after the `2002::/16` prefix.+fn ipv4_inside_6to4(segments: [u16; 8]) -> Option<Ipv4Addr> {+ (segments[0] == 0x2002).then(|| ipv4_from_segments(segments[1], segments[2]))+}++/// The NAT64 well-known prefix `64:ff9b::/96` carries it in the last two segments.+fn ipv4_inside_nat64(segments: [u16; 8]) -> Option<Ipv4Addr> {+ let has_well_known_prefix = segments[0] == 0x0064+ && segments[1] == 0xff9b+ && segments[2] == 0+ && segments[3] == 0+ && segments[4] == 0;+ has_well_known_prefix.then(|| ipv4_from_segments(segments[6], segments[7]))+}++fn ipv4_from_segments(high: u16, low: u16) -> Ipv4Addr {+ Ipv4Addr::new((high >> 8) as u8, high as u8, (low >> 8) as u8, low as u8)+}++fn is_public_v4(v4: Ipv4Addr) -> bool {+ let [a, b, c, _] = v4.octets();+ let this_network = a == 0;+ let carrier_grade_nat = a == 100 && (64..128).contains(&b);+ let ietf_protocol_assignments = a == 192 && b == 0 && c == 0;+ let benchmarking = a == 198 && (b == 18 || b == 19);+ let reserved = a >= 240;++ !(v4.is_loopback()+ || v4.is_private()+ || v4.is_link_local()+ || v4.is_broadcast()+ || v4.is_documentation()+ || v4.is_unspecified()+ || v4.is_multicast()+ || this_network+ || carrier_grade_nat+ || ietf_protocol_assignments+ || benchmarking+ || reserved)+}++/// Why a URL was not collected. Each variant is a label on the decline counter. A lane+/// that collects less than it should then reads off a dashboard, rather than being guessed at.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Decline {+ /// Longer than [`MAX_URL_LEN`], before or after normalization.+ TooLong,+ /// Not parseable as an absolute URL. A relative `src` lands here, because the recording does+ /// not carry the base it would need to resolve against.+ NotAbsolute,+ /// A scheme we do not fetch, such as `data:`, `blob:` or `ftp:`.+ BadScheme,+ /// No host at all.+ NoHost,+ /// Loopback, private, link-local or an internal-only name. See [`is_public_host`].+ NonPublicHost,+}++impl Decline {+ /// The metric label. Stable, because a dashboard and an alert both key on it.+ pub fn label(self) -> &'static str {+ match self {+ Decline::TooLong => "too_long",+ Decline::NotAbsolute => "not_absolute",+ Decline::BadScheme => "bad_scheme",+ Decline::NoHost => "no_host",+ Decline::NonPublicHost => "non_public_host",+ }+ }+}++/// Canonicalize a remote image URL into its fetch and dedup forms, or say why it was refused.+pub fn canonicalize(raw: &str) -> Option<CanonicalUrl> {+ try_canonicalize(raw).ok()+}++pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {+ if raw.len() > MAX_URL_LEN {+ return Err(Decline::TooLong);+ }+ let mut url = Url::parse(raw).map_err(|_| Decline::NotAbsolute)?;+ if !matches!(url.scheme(), "http" | "https") {+ return Err(Decline::BadScheme);+ }+ let host = url.host_str().ok_or(Decline::NoHost)?.to_string();+ if !is_public_host(&host) {+ return Err(Decline::NonPublicHost);+ }++ remove_credentials_and_fragment(&mut url);+ let fetch = url.to_string();+ // Percent-encoding and IDNA can grow a URL, so the cap is re-checked on what we emit.+ if fetch.len() > MAX_URL_LEN {+ return Err(Decline::TooLong);+ }++ remove_volatile_params(&mut url, &host);+ let dedup = url.to_string();++ Ok(CanonicalUrl {+ fetch,+ dedup,+ domain: politeness_key(&host),+ host,+ })+}++fn remove_credentials_and_fragment(url: &mut Url) {+ // The setters fail only on a cannot-be-a-base URL, which the http(s) check already excluded.+ let _ = url.set_username("");+ let _ = url.set_password(None);+ url.set_fragment(None);+}++/// Rewrites the query of every URL that has one, whether or not it removed anything.+///+/// Rewriting only when something was removed made the result depend on an unrelated fact. Two+/// encodings of one query then hashed the same when a signature was present and differently when+/// it was absent, so one image could hold two refs.+fn remove_volatile_params(url: &mut Url, host: &str) {+ if url.query().is_none() {+ return;+ }+ let pairs: Vec<(String, String)> = url+ .query_pairs()+ .map(|(k, v)| (k.into_owned(), v.into_owned()))+ .collect();+ let names_on_this_url: HashSet<String> =+ pairs.iter().map(|(k, _)| k.to_ascii_lowercase()).collect();+ let kept: Vec<&(String, String)> = pairs+ .iter()+ .filter(|(k, _)| !is_volatile(k, host, &names_on_this_url))+ .collect();++ if kept.is_empty() {+ url.set_query(None);+ return;+ }+ let mut query = url.query_pairs_mut();+ query.clear();+ for (name, value) in kept {+ query.append_pair(name, value);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn volatile(name: &str, host: &str, others: &[&str]) -> bool {+ let present: HashSet<String> = others.iter().map(|o| o.to_ascii_lowercase()).collect();+ is_volatile(name, host, &present)+ }+ #[test]+ fn canonicalize_rejects_what_we_will_not_fetch() {+ for raw in [+ "ftp://example.com/a.png",+ "data:image/png;base64,aGk=",+ "/relative/a.png",+ "not a url",+ "//protocol-relative.example.com/a.png",+ ] {+ assert!(canonicalize(raw).is_none(), "{raw} should not canonicalize");+ }+ let long = format!("https://example.com/{}", "a".repeat(MAX_URL_LEN));+ assert!(canonicalize(&long).is_none());+ }++ #[test]+ fn canonicalize_normalizes_and_strips_credentials() {+ let c = canonicalize("HTTPS://User:[email protected]:443/A.png#frag").unwrap();+ assert_eq!(c.fetch, "https://example.com/A.png");+ assert_eq!(c.host, "example.com");+ assert!(!c.fetch.contains("User"));+ assert!(!c.fetch.contains("Pass"));+ }++ #[test]+ fn the_signature_stays_on_the_fetch_url_and_leaves_the_dedup_url() {+ let signed = "https://cdn.example.com/a.png?w=200&X-Amz-Signature=deadbeef&X-Amz-Date=20260810T000000Z";+ let c = canonicalize(signed).unwrap();+ // The fetcher needs the signature, or the request 403s.+ assert!(c.fetch.contains("X-Amz-Signature=deadbeef"));+ // The ref must not move when the signature does.+ assert_eq!(c.dedup, "https://cdn.example.com/a.png?w=200");+ }++ #[test]+ fn a_query_that_is_only_volatile_leaves_no_empty_question_mark() {+ let c = canonicalize("https://cdn.example.com/a.png?nocache=12345").unwrap();+ assert_eq!(c.dedup, "https://cdn.example.com/a.png");+ }++ #[test]+ fn a_generic_word_is_only_volatile_beside_its_vendor_marker() {+ // `policy=thumb` and `policy=full` are plausible image selectors on an ordinary host.+ let thumb = canonicalize("https://cdn.example.com/a.png?policy=thumb").unwrap();+ let full = canonicalize("https://cdn.example.com/a.png?policy=full").unwrap();+ assert_ne!(thumb.dedup, full.dedup);+ // Beside CloudFront's signature it is part of the signing set.+ assert!(volatile("policy", "cdn.example.com", &["signature"]));+ }++ #[test]+ fn an_ambiguous_cache_buster_is_kept() {+ // `v` and `t` are cache busters on some hosts and content-version or variant markers on+ // others. Keeping them costs a missed dedup. Removing them merges two different images.+ let a = canonicalize("https://cdn.example.com/a.png?v=thumb").unwrap();+ let b = canonicalize("https://cdn.example.com/a.png?v=full").unwrap();+ assert_ne!(a.dedup, b.dedup);+ }++ #[test]+ fn volatile_names_never_include_a_name_that_selects_an_image() {+ for name in [+ "w", "h", "q", "fm", "dpr", "fit", "auto", "format", "resize", "crop", "quality",+ ] {+ assert!(+ !volatile(name, "cdn.example.com", &[]),+ "{name} changes the image and must be kept"+ );+ }+ }++ #[test]+ fn a_short_name_is_only_volatile_where_the_vendor_owns_it() {+ // `s` sizes a Gravatar avatar and signs an imgix URL. Stripping it everywhere made a+ // 48-pixel avatar and a 200-pixel avatar the same image.+ assert!(!volatile("s", "www.gravatar.com", &[]));+ assert!(volatile("s", "images.imgix.net", &[]));+ // The Azure SAS names are volatile only when the signature of that set is also present.+ assert!(!volatile("sp", "cdn.example.com", &["w"]));+ assert!(volatile("sp", "acct.blob.core.windows.net", &["sig", "sv"]));+ // `expires` is a real cache hint until CloudFront's `signature` appears beside it.+ assert!(!volatile("expires", "cdn.example.com", &[]));+ assert!(volatile("expires", "cdn.example.com", &["signature"]));+ }++ #[test]+ fn the_politeness_key_is_the_operator_not_the_dns_label() {+ // A CDN that shards over numbered subdomains must share one budget.+ assert_eq!(politeness_key("img1.cdn.example.com"), "example.com");+ assert_eq!(politeness_key("img8.cdn.example.com"), "example.com");+ assert_eq!(politeness_key("example.com"), "example.com");+ }++ #[test]+ fn a_multi_tenant_host_keeps_its_tenants_apart() {+ // The private section of the public suffix list is what makes this correct. Without it,+ // every CloudFront distribution on the internet would share one budget and one partition.+ assert_eq!(politeness_key("d111.cloudfront.net"), "d111.cloudfront.net");+ assert_eq!(+ politeness_key("bucket.s3.amazonaws.com"),+ "bucket.s3.amazonaws.com"+ );+ assert_eq!(politeness_key("user.github.io"), "user.github.io");+ // The app-hosting case: a tenant subdomain is its own operator for our purposes.+ assert_eq!(politeness_key("myapp.vercel.app"), "myapp.vercel.app");+ assert_eq!(politeness_key("site.netlify.app"), "site.netlify.app");+ assert_eq!(politeness_key("worker.workers.dev"), "worker.workers.dev");+ }++ #[test]+ fn an_ip_literal_is_its_own_operator() {+ assert_eq!(politeness_key("203.0.113.7"), "203.0.113.7");+ assert_eq!(politeness_key("[2606:4700::1111]"), "[2606:4700::1111]");+ }++ #[test]+ fn canonicalize_carries_the_politeness_key() {+ let c = canonicalize("https://img3.cdn.example.co.uk/a.png").unwrap();+ assert_eq!(c.host, "img3.cdn.example.co.uk");+ // A multi-label public suffix, which is why this cannot be "the last two labels".+ assert_eq!(c.domain, "example.co.uk");+ }++ #[test]+ fn a_gravatar_size_is_not_stripped() {+ let big = canonicalize("https://www.gravatar.com/avatar/abc?s=200").unwrap();+ let small = canonicalize("https://www.gravatar.com/avatar/abc?s=48").unwrap();+ assert_ne!(+ big.dedup, small.dedup,+ "two avatar sizes are two images and must not share a ref"+ );+ }++ #[test]+ fn a_non_public_host_is_never_collected() {+ // The URL set comes from page content, and the fetch lane runs inside our network.+ for raw in [+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/",+ "http://localhost:8000/admin/export.png",+ "http://127.0.0.1/i.png",+ "http://10.0.0.5/i.png",+ "http://192.168.1.1/i.png",+ "http://172.16.0.1/i.png",+ "http://[::1]/i.png",+ "http://[fd00::1]/i.png",+ "http://metadata.internal/i.png",+ "http://buildserver/i.png",+ // A trailing dot makes a name fully qualified and resolves the same way. It used to+ // walk past the name list, because the label after the final dot is empty.+ "http://localhost./i.png",+ "http://metadata.internal./i.png",+ "http://LOCALHOST./i.png",+ // IPv6 offers several ways to write an IPv4 address. Each one used to skip the IPv4+ // rules entirely.+ "http://[::ffff:0.0.0.0]/i.png",+ "http://[::ffff:127.0.0.1]/i.png",+ "http://[::ffff:10.0.0.5]/i.png",+ "http://[::ffff:100.64.0.1]/i.png",+ "http://[::127.0.0.1]/i.png",+ "http://[2002:7f00:1::]/i.png",+ "http://[64:ff9b::7f00:1]/i.png",+ "http://[ff02::1]/i.png",+ // Ranges we would never legitimately fetch from.+ "http://224.0.0.1/i.png",+ "http://240.0.0.1/i.png",+ "http://198.18.0.1/i.png",+ "http://192.0.0.1/i.png",+ "http://0.0.0.0/i.png",+ ] {+ assert!(canonicalize(raw).is_none(), "{raw} must not be collected");+ }+ assert!(canonicalize("https://cdn.example.com/i.png").is_some());+ // A public name with a trailing dot is still public, so the fix must not over-reject.+ assert!(canonicalize("https://cdn.example.com./i.png").is_some());+ assert!(canonicalize("http://[2606:4700::1111]/i.png").is_some());+ assert!(canonicalize("http://8.8.8.8/i.png").is_some());+ }++ #[test]+ fn the_dedup_url_does_not_depend_on_whether_a_signature_rode_along() {+ // The query used to be re-encoded only when something was stripped, so one image could+ // hold two refs depending on an unrelated condition.+ let plain = canonicalize("https://cdn.example.com/a.png?a=1&b=2").unwrap();+ let signed =+ canonicalize("https://cdn.example.com/a.png?a=1&b=2&X-Amz-Signature=zz").unwrap();+ assert_eq!(plain.dedup, signed.dedup);+ }+}diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsnew file mode 100644index 000000000000..1398856d6fcc--- /dev/null+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -0,0 +1,341 @@+//! The URL-collection lane, end to end through a real Kafka payload.+//!+//! The unit tests in `url_collect` pin canonicalization and the collector in isolation. These pin+//! the parts only the whole pipeline can show: that a remote `src` comes out as a ref rather than+//! the placeholder, that the original URL reaches `meta.urls`, that the scrubbed copy is still+//! stashed alongside, and that a caller who does not opt in sees exactly what it saw before.++use posthog_replay_anonymizer::{+ anonymize_kafka_payload_collecting, AllowLists, AnonymizeOpts, ImagePolicy, UrlCollection,+};+use serde_json::{json, Value};++const TS0: f64 = 1_700_000_000_000.0;+const PSEUDO_TEAM: &str = "0123456789abcdef0123456789abcdef";+const URL_KEY: &str = "0123456789abcdef0123456789abcdef";++fn payload_tagged(tag: &str, attrs: Value) -> Vec<u8> {+ let inner = json!({+ "event": "$snapshot_items",+ "properties": {+ "$session_id": "s",+ "$window_id": "w",+ "$snapshot_items": [{+ "type": 3,+ "timestamp": TS0,+ "data": { "source": 0, "adds": [{+ "parentId": 1,+ "nextId": null,+ "node": {+ "type": 2, "tagName": tag, "id": 42,+ "attributes": attrs, "childNodes": []+ }+ }] }+ }]+ }+ });+ json!({ "distinct_id": "d", "data": inner.to_string() })+ .to_string()+ .into_bytes()+}++fn collect_urls_of(tag: &str, attrs: Value) -> Vec<String> {+ let allow = AllowLists::default();+ let mut hosts = Vec::new();+ for byte_walk in [true, false] {+ let mut bytes = payload_tagged(tag, attrs.clone());+ let msg = anonymize_kafka_payload_collecting(+ &allow,+ &mut bytes,+ AnonymizeOpts {+ byte_walk,+ image_policy: ImagePolicy::Inline,+ },+ None,+ None,+ Some(UrlCollection {+ pseudo_team: PSEUDO_TEAM.to_string(),+ url_key: URL_KEY.to_string(),+ }),+ )+ .expect("anonymize should succeed");+ hosts.push(format!("byte_walk={byte_walk}:{}", msg.meta.urls.len()));+ }+ hosts+}++#[test]+fn only_an_image_bearing_tag_has_its_src_collected() {+ // TagKind::Media also covers video, audio and track, whose src is a movie, a sound file, or a+ // WebVTT subtitle document. The fetch lane is sized to download images.+ for tag in ["img", "image", "picture"] {+ assert_eq!(+ collect_urls_of(tag, json!({ "src": "https://cdn.example.com/a.png" })),+ vec!["byte_walk=true:1", "byte_walk=false:1"],+ "{tag} src should be collected"+ );+ }+ for tag in ["video", "audio", "track", "source"] {+ assert_eq!(+ collect_urls_of(tag, json!({ "src": "https://cdn.example.com/movie.mp4" })),+ vec!["byte_walk=true:0", "byte_walk=false:0"],+ "{tag} src is not an image and must not be collected"+ );+ }+}++#[test]+fn a_video_poster_is_still_collected() {+ // poster only exists on a video and always names a still image.+ assert_eq!(+ collect_urls_of(+ "video",+ json!({ "poster": "https://cdn.example.com/poster.jpg" })+ ),+ vec!["byte_walk=true:1", "byte_walk=false:1"]+ );+}++fn payload(attrs: Value) -> Vec<u8> {+ let inner = json!({+ "event": "$snapshot_items",+ "properties": {+ "$session_id": "s",+ "$window_id": "w",+ "$snapshot_items": [{+ "type": 3,+ "timestamp": TS0,+ "data": { "source": 0, "adds": [{+ "parentId": 1,+ "nextId": null,+ "node": {+ "type": 2, "tagName": "img", "id": 42,+ "attributes": attrs, "childNodes": []+ }+ }] }+ }]+ }+ });+ json!({ "distinct_id": "d", "data": inner.to_string() })+ .to_string()+ .into_bytes()+}++/// Runs both engines, because the byte walk and the tree parse have separate media-attribute+/// paths and only a differential check keeps them writing the same thing.+fn run(attrs: Value, collect: bool) -> Vec<(String, Value)> {+ let allow = AllowLists::default();+ let mut out = Vec::new();+ for byte_walk in [true, false] {+ let mut bytes = payload(attrs.clone());+ let collection = collect.then(|| UrlCollection {+ pseudo_team: PSEUDO_TEAM.to_string(),+ url_key: URL_KEY.to_string(),+ });+ let msg = anonymize_kafka_payload_collecting(+ &allow,+ &mut bytes,+ AnonymizeOpts {+ byte_walk,+ image_policy: ImagePolicy::Inline,+ },+ None,+ None,+ collection,+ )+ .expect("anonymize should succeed");+ let line: Value = serde_json::from_slice(+ msg.lines+ .split(|b| *b == b'\n')+ .next()+ .expect("at least one line"),+ )+ .expect("line is json");+ let meta = serde_json::to_value(&msg.meta).expect("meta serializes");+ out.push((format!("byte_walk={byte_walk}"), json!([line, meta])));+ }+ out+}++fn attrs_of(line: &Value) -> &Value {+ &line[1]["data"]["adds"][0]["node"]["attributes"]+}++#[test]+fn a_remote_src_becomes_a_ref_and_its_url_reaches_meta() {+ for (engine, result) in run(+ json!({ "src": "https://cdn.example.com/hero.png?w=200" }),+ true,+ ) {+ let (line, meta) = (&result[0], &result[1]);+ let src = attrs_of(line)["src"].as_str().expect("src is a string");+ assert!(+ src.starts_with(&format!("imageurl:{PSEUDO_TEAM}:")),+ "{engine}: expected a url ref, got {src}"+ );++ let urls = meta["urls"].as_array().expect("meta.urls present");+ assert_eq!(urls.len(), 1, "{engine}");+ assert_eq!(urls[0]["url"], "https://cdn.example.com/hero.png?w=200");+ assert_eq!(urls[0]["host"], "cdn.example.com");+ assert!(+ src.ends_with(urls[0]["hash"].as_str().expect("hash is a string")),+ "{engine}: the ref must carry the hash meta reports"+ );++ // The scrubbed copy still rides along, so a reader that never resolves the ref keeps what+ // it has today.+ assert!(+ attrs_of(line)["data-anon-original-src"].is_string(),+ "{engine}: the scrubbed original should still be stashed"+ );+ }+}++#[test]+fn without_a_collection_a_remote_src_is_still_the_placeholder() {+ for (engine, result) in run(json!({ "src": "https://cdn.example.com/hero.png" }), false) {+ let (line, meta) = (&result[0], &result[1]);+ let src = attrs_of(line)["src"].as_str().expect("src is a string");+ assert!(+ src.starts_with("data:image/svg+xml"),+ "{engine}: expected the placeholder, got {src}"+ );+ assert!(+ meta.get("urls").is_none(),+ "{engine}: meta.urls should be absent when nothing was collected"+ );+ }+}++#[test]+fn an_inlined_image_is_untouched_by_the_url_lane() {+ // The two lanes must not fight over one attribute: a data URI has no URL to fetch, so it stays+ // on the image path even with URL collection on.+ let inlined = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";+ for (engine, result) in run(json!({ "src": inlined }), true) {+ let (line, meta) = (&result[0], &result[1]);+ let src = attrs_of(line)["src"].as_str().expect("src is a string");+ assert!(+ !src.starts_with("imageurl:"),+ "{engine}: an inlined image must not take the URL lane, got {src}"+ );+ assert!(meta.get("urls").is_none(), "{engine}");+ }+}++#[test]+fn a_non_fetchable_scheme_keeps_the_placeholder() {+ for (engine, result) in run(json!({ "src": "ftp://files.example.com/hero.png" }), true) {+ let (line, meta) = (&result[0], &result[1]);+ let src = attrs_of(line)["src"].as_str().expect("src is a string");+ assert!(+ src.starts_with("data:image/svg+xml"),+ "{engine}: expected the placeholder, got {src}"+ );+ assert!(meta.get("urls").is_none(), "{engine}");+ }+}++#[test]+fn srcset_stays_out_of_scope_and_keeps_the_placeholder() {+ // srcset holds several candidates with descriptors, so it needs a parse and a choice this lane+ // deliberately does not make yet. Pinned so adding it is a decision rather than an accident.+ for (engine, result) in run(+ json!({ "srcset": "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 2x" }),+ true,+ ) {+ let (line, meta) = (&result[0], &result[1]);+ let srcset = attrs_of(line)["srcset"]+ .as_str()+ .expect("srcset is a string");+ assert!(+ srcset.starts_with("data:image/svg+xml"),+ "{engine}: expected the placeholder, got {srcset}"+ );+ assert!(meta.get("urls").is_none(), "{engine}");+ }+}++#[test]+fn one_url_under_two_signatures_collects_once() {+ // The whole reason canonicalization splits the dedup URL from the fetch URL.+ let allow = AllowLists::default();+ let mut bytes = json!({+ "distinct_id": "d",+ "data": json!({+ "event": "$snapshot_items",+ "properties": {+ "$session_id": "s",+ "$window_id": "w",+ "$snapshot_items": [+ {"type": 3, "timestamp": TS0, "data": {"source": 0, "adds": [+ {"parentId": 1, "nextId": null, "node": {"type": 2, "tagName": "img", "id": 1,+ "attributes": {"src": "https://cdn.example.com/a.png?X-Amz-Signature=aaa"}, "childNodes": []}},+ {"parentId": 1, "nextId": null, "node": {"type": 2, "tagName": "img", "id": 2,+ "attributes": {"src": "https://cdn.example.com/a.png?X-Amz-Signature=bbb"}, "childNodes": []}}+ ]}}+ ]+ }+ }).to_string()+ })+ .to_string()+ .into_bytes();++ let msg = anonymize_kafka_payload_collecting(+ &allow,+ &mut bytes,+ AnonymizeOpts::default(),+ None,+ None,+ Some(UrlCollection {+ pseudo_team: PSEUDO_TEAM.to_string(),+ url_key: URL_KEY.to_string(),+ }),+ )+ .expect("anonymize should succeed");++ assert_eq!(+ msg.meta.urls.len(),+ 1,+ "two signatures of one image are one URL to fetch"+ );+}++#[test]+fn every_refusal_is_counted_with_a_reason() {+ // A silent decline makes the lane look like the traffic carries fewer images than it does,+ // which is exactly the number the measurement phase exists to produce.+ let allow = AllowLists::default();+ let mut bytes = payload_tagged(+ "img",+ json!({+ "src": "http://169.254.169.254/meta.png",+ "rr_src": "ftp://files.example.com/a.png",+ "poster": "/relative/a.png"+ }),+ );+ let msg = anonymize_kafka_payload_collecting(+ &allow,+ &mut bytes,+ AnonymizeOpts::default(),+ None,+ None,+ Some(UrlCollection {+ pseudo_team: PSEUDO_TEAM.to_string(),+ url_key: URL_KEY.to_string(),+ }),+ )+ .expect("anonymize should succeed");++ assert!(msg.meta.urls.is_empty(), "none of these are fetchable");+ let reasons: Vec<&str> = msg+ .meta+ .url_declines+ .iter()+ .map(|d| d.reason.as_str())+ .collect();+ assert!(reasons.contains(&"non_public_host"), "{reasons:?}");+ assert!(reasons.contains(&"bad_scheme"), "{reasons:?}");+ assert!(reasons.contains(&"not_absolute"), "{reasons:?}");+}