: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(session-replay): refuse advertising pixels in the image fetch lane (#96073)
Robbie04b428219aba
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.mdindex 2d5400dd85ca..4a92a89675b3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md@@ -6,7 +6,7 @@ The [README](./README.md) is the normative specification. This file records the### URL collection and identity-The shared Rust URL policy performs admission, canonicalization, and global ref creation. It refuses private targets, credentials, userinfo, and known signed URLs.+The shared Rust URL policy performs admission, canonicalization, and global ref creation. It refuses private targets, credentials, userinfo, known signed URLs, and the beacons listed in `tracking_beacons.txt`. The anonymizer also refuses an `img` that is hidden or at most one pixel before the URL reaches the policy, in both the tree walk and the byte walk. The policy marks a beacon as unwanted rather than invalid. The fetcher reads that mark through the addon and skips an unwanted job on its own, because a rejected job would send its whole record to the dead-letter topic. The list is compiled into both lanes, so a list change ships only with an image build of the mirror and the fetcher.The mirror emits versioned frontier jobs. Each job carries the original ref, current URL, remaining hops, timing, and amplification counters.@@ -94,30 +94,31 @@ The optional fetch dead-letter topic stores each rejected frontier record with iThe lane uses bounded labels for all signals. The dashboards group failures by a fixed operation, reason, outcome, stage, or destination.-| Failure mode | Primary signal | Dashboard or alert | Response |-| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| The 40-second pass budget is too short. | `ml_image_fetch_republished_total{reason="pass_deadline"}` divided by completed URLs plus all republishes | Fetch dashboard: **Pass deadline deferral rate**. Alert: `IngestionSessionReplayImageFetchPassDeadlineSaturated`. | Increase capacity first. Increase the pass budget only if active batch age keeps enough margin below Kafka's 300-second poll limit. |-| A fetch batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Fetch dashboard: **Poll batch duration**. Alert: `IngestionSessionReplayImageFetchBatchNearPollLimit`. | Check store latency and request scheduling. Scale the lane before changing the pass budget. |-| The fetch lane cannot drain its frontier topic. | Frontier lag exceeds 1,000 records and stays flat or projects more than 10% growth in one hour. | Fetch dashboard: Kafka lag and drain time. Alert: `IngestionSessionReplayImageFetchNotDraining`. | Check consumer members, pod capacity, request waits, and deadline deferrals. |-| DynamoDB is slow, or a DynamoDB or Kafka request fails. | Crawl-history duration by operation and outcome, a store error, a republish failure, or a failed retry release. A durable consumer-loop error log covers a pod that exits before a metrics scrape. | Fetch dashboard: **Store health and delivery failures**. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the failed or slow operation. Do not discard or manually commit the affected offsets. |-| Kafka republishing consumes a large part of the poll interval. | Total republish flush duration and per-topic delivery time increase. Records and registrable-domain keys per topic show whether the cause is volume, redirect fan-out, or delivery latency. A finalization-deadline counter records batches that stop before all records start. | Fetch dashboard: **Republish messages and registrable domains per batch**, **Republish batch duration**, **Store health and delivery failures**, and **Poll batch duration**. | Check Kafka producer latency and target-domain fan-out. Keep the active batch below Kafka's poll limit. |-| The fetch lane is alive but the input is empty. | Polls increase, consumer members remain present, and batch utilization is zero. | Fetch dashboard: lane liveness and poll batch utilization. | Check the version 2 mirror producer and the input-topic production rate. |-| Poll batches contain few distinct origins or registrable domains, or the pod reaches request capacity. | Distinct counts, top 1, 5, and 10 URL shares, effective counts, immediately schedulable slots, scheduler waits, requests in flight, deadline deferrals, and `not_ready` republishes. | Fetch dashboard: batch diversity, request capacity, scheduler waits, origin policy, registrable-domain state, request outcomes, and republishes. | Increase batch size only when low diversity coincides with low request use, scoped scheduler wait, and sufficient Kafka poll margin. Scale pods for pod saturation. |-| One frontier partition accumulates lag. | Per-partition input, fetchable, HTTP request, completion, republish, scheduler-wait, top-share, and effective-count metrics. | Fetch dashboard: partition flow, outcomes, scheduler waits, and concentration. | Separate high input volume from store filtering, HTTP work, politeness waits, and republish churn before changing capacity. |-| A registrable domain repeatedly fails, or an origin refuses access. | Request outcomes, bounded retry causes, registrable-domain block state, origin-policy decisions, and terminal refusal reasons change. | Fetch dashboard: request outcomes, retry causes, policy and budget decisions, and refused URLs. | Check the origin policy and response status. Do not override an opt-out signal. |-| Retry release cannot return work to the frontier. | `ml_image_fetch_retry_released_total{outcome="failed"}` and a durable consumer-loop error log. | Fetch dashboard: delivery failures. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the frontier producer and Kafka connectivity. |-| Retry input is invalid. | `ml_image_fetch_retry_released_total` increases with a `malformed` or `invalid_timestamp` outcome. Missing content is committed and dropped. An invalid timestamp leaves the offset uncommitted and writes a durable consumer-loop error log. | Fetch dashboard: delivery failures. Alerts: `IngestionSessionReplayImageFetchRetryInputRejected` for missing content and `IngestionSessionReplayImageFetchConsumerLoopFailed` for an invalid timestamp. | Check the retry producer and the delay topic's `LogAppendTime` configuration. |-| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dead_lettered_total` increases after Kafka acknowledges the original record. `ml_image_fetch_consumer_dropped_total` counts the rejected jobs. | Fetch dashboard: quarantine activity and **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected` for a sustained rate. | Check the mirror and fetch versions and the frontier record schema. Inspect the restricted dead-letter topic only when necessary. |-| The fetch consumer cannot quarantine rejected input. | `ml_image_fetch_consumer_dead_letter_failed_total` increases and `ml_image_fetch_dead_letter_publish_failed` logs before the consumer fails the batch. The source offsets remain uncommitted. | Fetch dashboard: quarantine activity. Alerts: `IngestionSessionReplayImageFetchDeadLetterPublishFailed` and the durable-log `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the dead-letter topic, producer connectivity, and message-size configuration. |-| A retry worker shuts down during a deliberate wait. | `ml_image_fetch_retry_released_total{outcome="abandoned"}` increases. The consumer does not commit that offset. | Fetch dashboard only. This expected shutdown outcome does not alert. | Check pod lifecycle only if the rate does not match a rollout or scale-down. |-| The scrub sidecar is saturated or unreachable. | Scrub waits increase by `busy`, `timeout`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check pod health for `transport`. |-| The scrub consumer rejects input. | `ml_mirror_image_scrub_consumer_invalid_key_total` increases. The consumer commits and drops the record. | Scrub dashboard: invalid-key events. Alert: `IngestionSessionReplayImageScrubInputRejected`. | Check the fetch and scrub versions, the content-ref format, and the scrub topic. |-| One image blocks later offsets. | Stuck-image events increase, batch retired ratio falls, or batch duration approaches 300 seconds. | Scrub dashboard: batch progress, batch duration, and quarantine events. | Find the image ref in logs. Check if dead-letter publication succeeds. |-| Scrub output cannot reach S3 or the dead-letter topic. | A write batch failure or dead-letter publication failure occurs. Durable error logs cover a pod that exits before a metrics scrape. | Scrub dashboard: consumer delivery failures. Loki alerts: `IngestionSessionReplayImageScrubConsumerLoopFailed` and `IngestionSessionReplayImageScrubDeadLetterPublishFailed`. | Check bucket access, topic configuration, and maximum Kafka message size. |-| A dead-letter replay cannot recover an image. | The replay emits `image_scrub_replay_exhausted`. The process metric is also visible if a scrape catches the bounded replay run. | Scrub dashboard: quarantine events. Loki alert: `IngestionSessionReplayImageScrubReplayExhausted`. | Fix or accept the permanent sidecar refusal before Kafka retention removes the parked bytes. |-| A scrub batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Scrub dashboard: **Image and batch duration**. Alert: `IngestionSessionReplayImageScrubBatchNearPollLimit`. | Check the retired ratio, stuck images, waits, CPU, and memory. |-| Inline image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for inline images exceeds one hour for 30 minutes. | Scrub dashboard: end-to-end latency. Alert: `IngestionSessionReplayInlineImageScrubNotDraining`. | Check sidecar waits, CPU, memory, and consumer restarts. |-| URL image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for URL images exceeds three days for 30 minutes. | Fetch and scrub dashboards: frontier health and end-to-end latency. Alert: `IngestionSessionReplayURLImageScrubNotDraining`. | Check the image-fetch frontier, retries, request outcomes, and sidecar waits. |+| Failure mode | Primary signal | Dashboard or alert | Response |+| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| The 40-second pass budget is too short. | `ml_image_fetch_republished_total{reason="pass_deadline"}` divided by completed URLs plus all republishes | Fetch dashboard: **Pass deadline deferral rate**. Alert: `IngestionSessionReplayImageFetchPassDeadlineSaturated`. | Increase capacity first. Increase the pass budget only if active batch age keeps enough margin below Kafka's 300-second poll limit. |+| A fetch batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Fetch dashboard: **Poll batch duration**. Alert: `IngestionSessionReplayImageFetchBatchNearPollLimit`. | Check store latency and request scheduling. Scale the lane before changing the pass budget. |+| The fetch lane cannot drain its frontier topic. | Frontier lag exceeds 1,000 records and stays flat or projects more than 10% growth in one hour. | Fetch dashboard: Kafka lag and drain time. Alert: `IngestionSessionReplayImageFetchNotDraining`. | Check consumer members, pod capacity, request waits, and deadline deferrals. |+| DynamoDB is slow, or a DynamoDB or Kafka request fails. | Crawl-history duration by operation and outcome, a store error, a republish failure, or a failed retry release. A durable consumer-loop error log covers a pod that exits before a metrics scrape. | Fetch dashboard: **Store health and delivery failures**. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the failed or slow operation. Do not discard or manually commit the affected offsets. |+| Kafka republishing consumes a large part of the poll interval. | Total republish flush duration and per-topic delivery time increase. Records and registrable-domain keys per topic show whether the cause is volume, redirect fan-out, or delivery latency. A finalization-deadline counter records batches that stop before all records start. | Fetch dashboard: **Republish messages and registrable domains per batch**, **Republish batch duration**, **Store health and delivery failures**, and **Poll batch duration**. | Check Kafka producer latency and target-domain fan-out. Keep the active batch below Kafka's poll limit. |+| The fetch lane is alive but the input is empty. | Polls increase, consumer members remain present, and batch utilization is zero. | Fetch dashboard: lane liveness and poll batch utilization. | Check the version 2 mirror producer and the input-topic production rate. |+| Poll batches contain few distinct origins or registrable domains, or the pod reaches request capacity. | Distinct counts, top 1, 5, and 10 URL shares, effective counts, immediately schedulable slots, scheduler waits, requests in flight, deadline deferrals, and `not_ready` republishes. | Fetch dashboard: batch diversity, request capacity, scheduler waits, origin policy, registrable-domain state, request outcomes, and republishes. | Increase batch size only when low diversity coincides with low request use, scoped scheduler wait, and sufficient Kafka poll margin. Scale pods for pod saturation. |+| One frontier partition accumulates lag. | Per-partition input, fetchable, HTTP request, completion, republish, scheduler-wait, top-share, and effective-count metrics. | Fetch dashboard: partition flow, outcomes, scheduler waits, and concentration. | Separate high input volume from store filtering, HTTP work, politeness waits, and republish churn before changing capacity. |+| A registrable domain repeatedly fails, or an origin refuses access. | Request outcomes, bounded retry causes, registrable-domain block state, origin-policy decisions, and terminal refusal reasons change. | Fetch dashboard: request outcomes, retry causes, policy and budget decisions, and refused URLs. | Check the origin policy and response status. Do not override an opt-out signal. |+| Retry release cannot return work to the frontier. | `ml_image_fetch_retry_released_total{outcome="failed"}` and a durable consumer-loop error log. | Fetch dashboard: delivery failures. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the frontier producer and Kafka connectivity. |+| Retry input is invalid. | `ml_image_fetch_retry_released_total` increases with a `malformed` or `invalid_timestamp` outcome. Missing content is committed and dropped. An invalid timestamp leaves the offset uncommitted and writes a durable consumer-loop error log. | Fetch dashboard: delivery failures. Alerts: `IngestionSessionReplayImageFetchRetryInputRejected` for missing content and `IngestionSessionReplayImageFetchConsumerLoopFailed` for an invalid timestamp. | Check the retry producer and the delay topic's `LogAppendTime` configuration. |+| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dead_lettered_total` increases after Kafka acknowledges the original record. `ml_image_fetch_consumer_dropped_total` counts the rejected jobs. | Fetch dashboard: quarantine activity and **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected` for a sustained rate. | Check the mirror and fetch versions and the frontier record schema. Inspect the restricted dead-letter topic only when necessary. |+| The fetch consumer skips unwanted frontier jobs. | `ml_image_fetch_consumer_skipped_total` increases by decline reason. After a beacon-list change it rises at the backlog's parse rate until the queued beacons drain. `ml_image_fetch_consumer_dropped_total` does not move. | Fetch dashboard: **Unwanted URLs skipped** and **Skipped share of parsed URLs**. | No action. A skipped job is counted after the batch finishes its durable work, so a failed batch is not counted twice. A crash before the offset store can count it once more, like every counter in this consumer. |+| The fetch consumer cannot quarantine rejected input. | `ml_image_fetch_consumer_dead_letter_failed_total` increases and `ml_image_fetch_dead_letter_publish_failed` logs before the consumer fails the batch. The source offsets remain uncommitted. | Fetch dashboard: quarantine activity. Alerts: `IngestionSessionReplayImageFetchDeadLetterPublishFailed` and the durable-log `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the dead-letter topic, producer connectivity, and message-size configuration. |+| A retry worker shuts down during a deliberate wait. | `ml_image_fetch_retry_released_total{outcome="abandoned"}` increases. The consumer does not commit that offset. | Fetch dashboard only. This expected shutdown outcome does not alert. | Check pod lifecycle only if the rate does not match a rollout or scale-down. |+| The scrub sidecar is saturated or unreachable. | Scrub waits increase by `busy`, `timeout`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check pod health for `transport`. |+| The scrub consumer rejects input. | `ml_mirror_image_scrub_consumer_invalid_key_total` increases. The consumer commits and drops the record. | Scrub dashboard: invalid-key events. Alert: `IngestionSessionReplayImageScrubInputRejected`. | Check the fetch and scrub versions, the content-ref format, and the scrub topic. |+| One image blocks later offsets. | Stuck-image events increase, batch retired ratio falls, or batch duration approaches 300 seconds. | Scrub dashboard: batch progress, batch duration, and quarantine events. | Find the image ref in logs. Check if dead-letter publication succeeds. |+| Scrub output cannot reach S3 or the dead-letter topic. | A write batch failure or dead-letter publication failure occurs. Durable error logs cover a pod that exits before a metrics scrape. | Scrub dashboard: consumer delivery failures. Loki alerts: `IngestionSessionReplayImageScrubConsumerLoopFailed` and `IngestionSessionReplayImageScrubDeadLetterPublishFailed`. | Check bucket access, topic configuration, and maximum Kafka message size. |+| A dead-letter replay cannot recover an image. | The replay emits `image_scrub_replay_exhausted`. The process metric is also visible if a scrape catches the bounded replay run. | Scrub dashboard: quarantine events. Loki alert: `IngestionSessionReplayImageScrubReplayExhausted`. | Fix or accept the permanent sidecar refusal before Kafka retention removes the parked bytes. |+| A scrub batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Scrub dashboard: **Image and batch duration**. Alert: `IngestionSessionReplayImageScrubBatchNearPollLimit`. | Check the retired ratio, stuck images, waits, CPU, and memory. |+| Inline image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for inline images exceeds one hour for 30 minutes. | Scrub dashboard: end-to-end latency. Alert: `IngestionSessionReplayInlineImageScrubNotDraining`. | Check sidecar waits, CPU, memory, and consumer restarts. |+| URL image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for URL images exceeds three days for 30 minutes. | Fetch and scrub dashboards: frontier health and end-to-end latency. Alert: `IngestionSessionReplayURLImageScrubNotDraining`. | Check the image-fetch frontier, retries, request outcomes, and sidecar waits. |The pass-budget alert is inactive in dry-run mode. Delay-topic lag has no alert because queued delay records are expected. Generic Kubernetes alerts cover pod crash loops and unavailable replicas.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.mdindex e4fc9089e91f..0a56acc2bae8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md@@ -104,6 +104,8 @@ Path patterns:**1.5** The producer collects only the `src` attribute on `img`, `image`, and `picture` elements. Other source attributes are out of scope until this specification adds them.+**1.6** The lane does not collect or fetch an advertising or analytics beacon. A beacon is a URL whose host and decoded path match an entry in the shared list [`tracking_beacons.txt`](../../../../../../rust/replay-anonymizer/src/tracking_beacons.txt). An entry is a host pattern followed by a path prefix. The host pattern is an exact host, `*.` followed by a domain to match every host below it, or `*` to match every host. The path prefix is compared case-insensitively with the start of the decoded path, after runs of `/` collapse to one. A prefix that does not end with `/` must end at a segment boundary, which is the end of the path, a `/`, or a `;`. A prefix of `/` alone matches every path on the host, and a whole-host entry therefore refuses every image on that host, including a visible ad creative, because nothing on an ad-serving host is a customer's content. The list refuses `*/` as an entry. The producer applies the list when it collects a URL. The fetcher applies the same list, through the shared URL policy, to every job it reads from the frontier and to every redirect target. A frontier job that matches is dropped without a request, a crawl-history write, or a dead-letter record, and `ml_image_fetch_consumer_skipped_total` counts it by decline reason, so a beacon queued before its entry existed leaves the backlog at parse speed. A redirect target that matches ends the URL as a terminal `bad_redirect` result in crawl history, after the request that returned the redirect. Nobody sees the one-pixel image a beacon serves, so it has no value as training data, and a fetch of it reports a conversion or a visit to the network behind it. A credential refusal under requirement 1.2 takes precedence over this list. A list change ships only with an image build of both the mirror and the fetcher.+### 2. Opt-out signals**2.1** Sites can refuse fetching by signaling this via these files:@@ -455,7 +457,7 @@ A fetch batch can publish more frontier records than it consumed. This can occur**11.6** Every metric label defined by this lane uses a fixed set of values or the bounded integer partition set of the frontier topic. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destination classes use `frontier` or `delay`. Republish topic classes use `frontier`, `retry_1m`, `retry_10m`, or `retry_1h`. Image scrub sources use `inline` or `url`. Unexpected scrub source formats use `other`. No label defined by this lane contains a configured Kafka topic name, registrable domain, provider domain, origin, host, URL, image ref, team, project, exception message, or other external value.-**11.7** The lane counts republished URLs by reason and bounded destination class. For each used topic class in a fetch batch, it observes the number of Kafka record delivery attempts, the number of attempted registrable-domain keys, and the wall time from topic-class scheduling until all started delivery attempts settle. It also observes total republish flush wall time and counts batches that reached the republish finalization deadline.+**11.7** The lane counts frontier jobs it skips as unwanted, by decline reason, separately from invalid frontier input. The lane counts republished URLs by reason and bounded destination class. For each used topic class in a fetch batch, it observes the number of Kafka record delivery attempts, the number of attempted registrable-domain keys, and the wall time from topic-class scheduling until all started delivery attempts settle. It also observes total republish flush wall time and counts batches that reached the republish finalization deadline.It counts transient retry causes as `timeout`, `error`, `rate_limited`, or `server_error`. It also counts republish failures, crawl-history keys affected by failed operations, and retry records by outcome.@@ -529,6 +531,8 @@ The fetch URL keeps the original query verbatim. The global ref uses a canonical**13.13** The mirror processes inline base64 images and remote URLs in image-bearing CSS properties. It keeps same-document fragment URLs unchanged and does not collect font or import URLs.+**13.14** The mirror does not collect the `src`, `rr_src`, or `srcset` of an `img` element that nobody can see. An element cannot be seen when it has the `hidden` attribute, when its inline style sets `display` to `none`, or when its width and height are both at most one pixel. The mirror reads each dimension from the inline style first and from the `width` or `height` attribute second. A dimension that is not a pixel length, for example `100%`, is unknown and does not count as one pixel. The element keeps the media placeholder, and the mirror counts the decline as `hidden_pixel`. The fetcher cannot apply this rule, because the frontier carries only the URL.+### 14. HTTP request/response**14.1** The lane accepts up to 4 `identity`, `gzip`, `deflate`, `br`, and `zstd` content codings and refuses every other coding. It sends `gzip, deflate, br, zstd` in `Accept-Encoding`; `identity` remains acceptable as HTTP defines.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.tsindex 21af346ba912..ed906cfc2346 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts@@ -52,7 +52,7 @@ describe('frontier record', () => {const durableCandidate = candidate({ lastBlockReason: 'configuration_unreachable' })const parsed = parseCollectedUrlsRecord(serializeFrontierRecord([durableCandidate]), 'example.com')- expect(parsed).toEqual({ ok: true, candidates: [durableCandidate], urlCount: 1, rejected: [] })+ expect(parsed).toEqual({ ok: true, candidates: [durableCandidate], urlCount: 1, rejected: [], skipped: [] })})it('does not persist source partition attribution', () => {@@ -61,7 +61,7 @@ describe('frontier record', () => {'example.com')- expect(parsed).toEqual({ ok: true, candidates: [candidate()], urlCount: 1, rejected: [] })+ expect(parsed).toEqual({ ok: true, candidates: [candidate()], urlCount: 1, rejected: [], skipped: [] })})it('accepts and removes the legacy low-origin-diversity marker', () => {@@ -70,6 +70,7 @@ describe('frontier record', () => {candidates: [candidate()],urlCount: 1,rejected: [],+ skipped: [],})})@@ -111,6 +112,58 @@ describe('frontier record', () => {expect(parsed).toEqual({ ok: false, reason })})+ it('skips a tracking beacon job and keeps the rest of the record', () => {+ const beacon = candidate({+ originalRef: `imageurl:${'b'.repeat(22)}`,+ currentUrl: 'https://analytics.twitter.com/i/adsct?txn_id=abc&p_id=Twitter',+ host: 'analytics.twitter.com',+ origin: 'https://analytics.twitter.com',+ registrableDomain: 'twitter.com',+ })+ const image = candidate({+ currentUrl: 'https://cdn.twitter.com/logo.png',+ host: 'cdn.twitter.com',+ origin: 'https://cdn.twitter.com',+ registrableDomain: 'twitter.com',+ })++ const parsed = parseCollectedUrlsRecord(serializeFrontierRecord([beacon, image]), 'twitter.com')++ expect(parsed).toEqual({+ ok: true,+ candidates: [image],+ urlCount: 2,+ rejected: [],+ skipped: [{ reason: 'tracking_beacon' }],+ })+ })++ it('skips a tracking beacon in a retained v1 record', () => {+ const pseudoTeam = 'b'.repeat(32)+ const value = Buffer.from(+ JSON.stringify({+ v: 1,+ pseudoTeam,+ capturedAtMs: 1_700_000_000_000,+ urls: [+ {+ ref: `imageurl:${pseudoTeam}:${'c'.repeat(22)}`,+ url: 'https://t.co/i/adsct?txn_id=abc',+ host: 't.co',+ },+ ],+ })+ )++ expect(parseCollectedUrlsRecord(value, 't.co')).toEqual({+ ok: true,+ candidates: [],+ urlCount: 1,+ rejected: [],+ skipped: [{ reason: 'tracking_beacon' }],+ })+ })+it('drops a job placed on another registrable-domain partition', () => {const parsed = parseCollectedUrlsRecord(record(), 'other.net')@@ -148,6 +201,7 @@ describe('frontier record', () => {],urlCount: 1,rejected: [],+ skipped: [],})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.tsindex 343ff5efdf84..ce1b5bcd389e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts@@ -1,8 +1,10 @@+import type { UrlPolicyDecline } from '@posthog/replay-anonymizer'+import { parseJSON } from '~/common/utils/json-parse'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'import { ImageFetchBlockReason, isImageFetchBlockReason } from './block-reason'-import { canonicalizeUrl } from './politeness-key'+import { tryCanonicalizeUrl } from './politeness-key'export const MAX_HOPS = 10export const MAX_JOBS_PER_RECORD = 1_000@@ -15,6 +17,8 @@ export type UrlDropReason =| 'bad_url'| 'foreign_domain'| 'oversized_record'+/** Why the parser dropped a job on its own, without rejecting the record that carries it. */+export type UrlSkipReason = UrlPolicyDeclineexport type StoredRepublishReason =| 'redirect'| 'retry'@@ -59,7 +63,13 @@ export interface FrontierRecord {}export type RecordParse =- | { ok: true; candidates: FetchCandidate[]; urlCount: number; rejected: { reason: UrlDropReason }[] }+ | {+ ok: true+ candidates: FetchCandidate[]+ urlCount: number+ rejected: { reason: UrlDropReason }[]+ skipped: { reason: UrlSkipReason }[]+ }| {ok: falsereason: Extract<@@ -120,14 +130,19 @@ export function parseCollectedUrlsRecord(value: Buffer | null, key: string | nulconst candidates: FetchCandidate[] = []const rejected: { reason: UrlDropReason }[] = []+ const skipped: { reason: UrlSkipReason }[] = []for (const job of parsed.jobs) {const parsedJob = parseJob(job, key)- if (!parsedJob.ok) {+ if (parsedJob.kind === 'rejected') {return { ok: false, reason: parsedJob.reason }}+ if (parsedJob.kind === 'skipped') {+ skipped.push({ reason: parsedJob.reason })+ continue+ }candidates.push(parsedJob.candidate)}- return { ok: true, candidates, urlCount: parsed.jobs.length, rejected }+ return { ok: true, candidates, urlCount: parsed.jobs.length, rejected, skipped }}function parseLegacyRecord(parsed: Record<string, unknown>, kafkaKey: string): RecordParse {@@ -148,6 +163,7 @@ function parseLegacyRecord(parsed: Record<string, unknown>, kafkaKey: string): Rconst readyAtMs = isNonNegativeSafeInteger(notBeforeMs) ? notBeforeMs : 0const candidates: FetchCandidate[] = []const rejected: { reason: UrlDropReason }[] = []+ const skipped: { reason: UrlSkipReason }[] = []for (const entry of urls) {if (!isRecord(entry) || typeof entry.ref !== 'string' || typeof entry.url !== 'string') {rejected.push({ reason: 'bad_url' })@@ -158,11 +174,16 @@ function parseLegacyRecord(parsed: Record<string, unknown>, kafkaKey: string): Rrejected.push({ reason: 'bad_ref' })continue}- const canonical = canonicalizeUrl(entry.url)- if (!canonical) {- rejected.push({ reason: 'bad_url' })+ const verdict = tryCanonicalizeUrl(entry.url)+ if (!verdict.ok) {+ if (verdict.unwanted) {+ skipped.push({ reason: verdict.decline })+ } else {+ rejected.push({ reason: 'bad_url' })+ }continue}+ const canonical = verdict.urlif (canonical.domain !== kafkaKey.replace(/\.$/, '')) {rejected.push({ reason: 'foreign_domain' })continue@@ -181,17 +202,17 @@ function parseLegacyRecord(parsed: Record<string, unknown>, kafkaKey: string): RlastRepublishReason: null,})}- return { ok: true, candidates, urlCount: urls.length, rejected }+ return { ok: true, candidates, urlCount: urls.length, rejected, skipped }}-function parseJob(- job: unknown,- kafkaKey: string-):- | { ok: true; candidate: FetchCandidate }- | { ok: false; reason: Extract<UrlDropReason, 'bad_ref' | 'bad_url' | 'foreign_domain'> } {+type ParsedJob =+ | { kind: 'candidate'; candidate: FetchCandidate }+ | { kind: 'rejected'; reason: Extract<UrlDropReason, 'bad_ref' | 'bad_url' | 'foreign_domain'> }+ | { kind: 'skipped'; reason: UrlSkipReason }++function parseJob(job: unknown, kafkaKey: string): ParsedJob {if (!isRecord(job)) {- return { ok: false, reason: 'bad_url' }+ return { kind: 'rejected', reason: 'bad_url' }}const {originalRef,@@ -218,21 +239,27 @@ function parseJob((lastBlockReason !== undefined && !isImageFetchBlockReason(lastBlockReason)) ||(lowOriginDiversityDeferred !== undefined && typeof lowOriginDiversityDeferred !== 'boolean')) {- return { ok: false, reason: 'bad_url' }+ return { kind: 'rejected', reason: 'bad_url' }}const ref = parseImageRef(originalRef)if (!ref || ref.source !== 'url' || ref.pseudoTeam !== undefined) {- return { ok: false, reason: 'bad_ref' }+ return { kind: 'rejected', reason: 'bad_ref' }+ }+ const verdict = tryCanonicalizeUrl(currentUrl)+ if (!verdict.ok) {+ // A rejected job sends its whole record to the dead-letter topic, and a record can hold an+ // unwanted URL next to real images, so an unwanted URL is skipped on its own instead.+ return verdict.unwanted ? { kind: 'skipped', reason: verdict.decline } : { kind: 'rejected', reason: 'bad_url' }}- const canonical = canonicalizeUrl(currentUrl)- if (!canonical || canonical.fetch !== currentUrl) {- return { ok: false, reason: 'bad_url' }+ const canonical = verdict.url+ if (canonical.fetch !== currentUrl) {+ return { kind: 'rejected', reason: 'bad_url' }}if (canonical.domain !== kafkaKey) {- return { ok: false, reason: 'foreign_domain' }+ return { kind: 'rejected', reason: 'foreign_domain' }}return {- ok: true,+ kind: 'candidate',candidate: {originalRef,currentUrl,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.tsindex 0688611d8eaf..a26c944d5bff 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts@@ -1,6 +1,6 @@import { Counter, Gauge, Histogram } from 'prom-client'-import type { RepublishReason, UrlDropReason } from './collected-urls-record'+import type { RepublishReason, UrlDropReason, UrlSkipReason } from './collected-urls-record'import type { AttemptOutcome } from './fetch-runner'import type { FrontierDeadLetterReason } from './frontier-dead-letter-sink'import type { FetchRefusalReason, RequestScheduleBlockReason, TransientFetchOutcome } from './image-fetcher'@@ -51,6 +51,15 @@ export class ImageFetchConsumerMetrics {help: 'URLs refused before dedup because the versioned record, URL, ref, or registrable-domain key was invalid. When a dead-letter topic is configured, its Kafka acknowledgement precedes this increment and the source commit',labelNames: ['reason'],})+ /**+ * A sustained rate here is expected after a beacon-list change, while the fetcher drains the+ * queued beacons at parse speed. It is not the invalid-input signal that `dropped` carries.+ */+ private static readonly skipped = new Counter({+ name: 'ml_image_fetch_consumer_skipped_total',+ help: 'Frontier jobs the parser dropped on their own because the URL policy refuses the URL as unwanted, by decline reason. The record and its other jobs proceed and no dead-letter record is written. The count lands after the batch finishes its durable work, so a failed batch is not counted twice; a crash before the offset store can count it once more, like every counter in this consumer',+ labelNames: ['reason'],+ })private static readonly deadLettered = new Counter({name: 'ml_image_fetch_consumer_dead_lettered_total',help: 'Rejected frontier records acknowledged by the dead-letter topic before the source offset can advance',@@ -168,6 +177,9 @@ export class ImageFetchConsumerMetrics {public static incDropped(reason: UrlDropReason, count: number): void {this.dropped.labels(reason).inc(count)}+ public static incSkipped(reason: UrlSkipReason, count: number): void {+ this.skipped.labels(reason).inc(count)+ }public static incDeadLettered(reason: FrontierDeadLetterReason): void {this.deadLettered.labels(reason).inc()}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.tsindex 5d5d00aa1ac0..43d234ca74ec 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts@@ -14,7 +14,7 @@ function addon(): typeof import('@posthog/replay-anonymizer') {if (typeof loaded.politenessKey !== 'function' ||typeof loaded.isPublicHost !== 'function' ||- typeof loaded.canonicalizeUrl !== 'function'+ typeof loaded.tryCanonicalizeUrl !== 'function') {throw new Error('the replay-anonymizer addon is missing the url policy: rebuild index.node')}@@ -24,12 +24,15 @@ function addon(): typeof import('@posthog/replay-anonymizer') {}/**- * Load the addon now, so a stale `index.node` stops the pod at startup.+ * Load the addon now and run one URL through it, so a stale `index.node` stops the pod at startup.** The parser calls into it for every URL. A stale addon must stop the pod before it reads a batch.*/export function assertUrlPolicyLoaded(): void {- addon()+ const verdict = addon().tryCanonicalizeUrl('https://example.com/probe.png')+ if (!verdict.ok) {+ throw new Error(`the replay-anonymizer addon refused a plain URL (${verdict.decline}): rebuild index.node`)+ }}export function politenessKey(host: string): string {@@ -50,3 +53,7 @@ export function isPublicHost(host: string): boolean {export function canonicalizeUrl(url: string): import('@posthog/replay-anonymizer').CanonicalUrl | null {return addon().canonicalizeUrl(url)}++export function tryCanonicalizeUrl(url: string): import('@posthog/replay-anonymizer').UrlPolicyVerdict {+ return addon().tryCanonicalizeUrl(url)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.tsindex 77172d1e0cc1..77b85bc93927 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts@@ -562,6 +562,58 @@ describe('UrlFetchConsumer', () => {expect(harness.run).not.toHaveBeenCalled()})+ it('drops a tracking beacon job without quarantining its record', async () => {+ const harness = build()+ const beacon = candidate('beacon', {+ currentUrl: 'https://analytics.twitter.com/i/adsct?txn_id=abc&p_id=Twitter',+ host: 'analytics.twitter.com',+ origin: 'https://analytics.twitter.com',+ registrableDomain: 'twitter.com',+ })+ const image = candidate('logo', {+ currentUrl: 'https://cdn.twitter.com/logo.png',+ host: 'cdn.twitter.com',+ origin: 'https://cdn.twitter.com',+ registrableDomain: 'twitter.com',+ })+ const dropped = jest.spyOn(ImageFetchConsumerMetrics, 'incDropped')+ const skipped = jest.spyOn(ImageFetchConsumerMetrics, 'incSkipped')++ await expect(+ harness.consumer.handleBatch([message([beacon, image], 'twitter.com')], NOW_MS)+ ).resolves.toBeUndefined()++ expect(harness.park).not.toHaveBeenCalled()+ expect(harness.run).toHaveBeenCalledTimes(1)+ expect(harness.run.mock.calls[0][0].map((fetched) => fetched.originalRef)).toEqual([image.originalRef])+ expect(skipped).toHaveBeenCalledWith('tracking_beacon', 1)+ expect(dropped).not.toHaveBeenCalled()+ })++ it('does not count a skipped beacon when the batch fails before its commit', async () => {+ const harness = build()+ const beacon = candidate('beacon', {+ currentUrl: 'https://analytics.twitter.com/i/adsct?txn_id=abc&p_id=Twitter',+ host: 'analytics.twitter.com',+ origin: 'https://analytics.twitter.com',+ registrableDomain: 'twitter.com',+ })+ const image = candidate('logo', {+ currentUrl: 'https://cdn.twitter.com/logo.png',+ host: 'cdn.twitter.com',+ origin: 'https://cdn.twitter.com',+ registrableDomain: 'twitter.com',+ })+ harness.history.readError = new Error('read failed')+ const skipped = jest.spyOn(ImageFetchConsumerMetrics, 'incSkipped')++ await expect(harness.consumer.handleBatch([message([beacon, image], 'twitter.com')], NOW_MS)).rejects.toThrow(+ 'read failed'+ )++ expect(skipped).not.toHaveBeenCalled()+ })+it('rejects a whole multi-job record when one job belongs to another partition', async () => {const harness = build()const foreign = candidate('foreign', {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.tsindex fa744dece5f2..8bc5dd175fe5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts@@ -3,7 +3,13 @@ import pLimit from 'p-limit'import { logger } from '~/common/utils/logger'-import { FetchCandidate, MAX_HOPS, UrlDropReason, parseCollectedUrlsRecord } from './collected-urls-record'+import {+ FetchCandidate,+ MAX_HOPS,+ UrlDropReason,+ UrlSkipReason,+ parseCollectedUrlsRecord,+} from './collected-urls-record'import { CrawlHistoryItem, CrawlHistoryStore, UrlCrawlHistoryItem, configurationCacheKey } from './crawl-history'import { mergeDuplicateFetchCandidates } from './fetch-candidate-queue'import {@@ -56,6 +62,7 @@ export class UrlFetchConsumer {const startedAt = process.hrtime.bigint()const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MSconst drops = new Map<UrlDropReason, number>()+ const skips = new Map<UrlSkipReason, number>()const rejectedRecords: RejectedFrontierRecord[] = []const candidatesByRef = new Map<string, FetchCandidate>()let dedupedInBatch = 0@@ -84,6 +91,9 @@ export class UrlFetchConsumer {reasons: parsed.rejected.map((rejected) => rejected.reason),})}+ for (const { reason } of parsed.skipped) {+ skips.set(reason, (skips.get(reason) ?? 0) + 1)+ }for (const candidate of parsed.candidates) {const partitionCandidate = { ...candidate, sourcePartitions: [message.partition] }const existing = candidatesByRef.get(partitionCandidate.originalRef)@@ -131,6 +141,7 @@ export class UrlFetchConsumer {if (this.options.dryRun || candidates.length === 0) {await this.parkRejectedRecords(rejectedRecords, drops)+ this.countSkippedJobs(skips)return}@@ -207,6 +218,7 @@ export class UrlFetchConsumer {throw new Error(`the image fetch lane could not account for ${lost} URLs`)}await this.parkRejectedRecords(rejectedRecords, drops)+ this.countSkippedJobs(skips)} finally {ImageFetchConsumerMetrics.finishBatch(activeBatchId)this.recordMetrics(@@ -232,6 +244,13 @@ export class UrlFetchConsumer {}}+ /** Runs after the batch's durable work, so a batch that fails and is redelivered counts its skips once. */+ private countSkippedJobs(skips: Map<UrlSkipReason, number>): void {+ for (const [reason, count] of skips) {+ ImageFetchConsumerMetrics.incSkipped(reason, count)+ }+ }+private async parkRejectedRecords(records: RejectedFrontierRecord[],drops: Map<UrlDropReason, number>diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 361141cf3b8a..c4cb2cfb809f 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -9301,7 +9301,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.8"+version = "0.5.0"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 8a550342f30b..8f5f1caa215a 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -214,6 +214,36 @@ export interface CanonicalUrl {domain: string}+/** The labels of the Rust `Decline` enum. The fetch lane reports them as metric reasons. */+export type UrlPolicyDecline =+ | 'too_long'+ | 'not_absolute'+ | 'bad_scheme'+ | 'bad_port'+ | 'no_host'+ | 'non_public_host'+ | 'credential'+ | 'invalid_query'+ | 'tracking_beacon'++/**+ * The canonical forms of a URL the policy accepts, or the rule that refused it. `unwanted` is true+ * when the URL is well formed and safe but nobody wants it fetched, so a queue consumer drops only+ * that job instead of rejecting the record that carries it.+ */+export type UrlPolicyVerdict =+ | { ok: true; url: CanonicalUrl }+ | { ok: false; decline: UrlPolicyDecline; unwanted: boolean }++export function tryCanonicalizeUrl(url: string): UrlPolicyVerdict {+ const result = native.tryCanonicalizeUrl(url)+ if (typeof result.decline === 'string') {+ return { ok: false, decline: result.decline, unwanted: result.unwanted === true }+ }+ return { ok: true, url: result }+}+export function canonicalizeUrl(url: string): CanonicalUrl | null {- return native.canonicalizeUrl(url)+ const verdict = tryCanonicalizeUrl(url)+ return verdict.ok ? verdict.url : null}diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 8e44fcecc336..2efaa5b752cc 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -12,8 +12,8 @@ use std::sync::RwLock;use neon::prelude::*;use neon::types::buffer::TypedArray;use posthog_replay_anonymizer::{- canonicalize, is_public_host, politeness_key, snapshot, AllowLists, FailKind, ImageCollection,- ImagePolicy, PhaseTimings, UrlCollection,+ is_public_host, politeness_key, snapshot, try_canonicalize, AllowLists, FailKind,+ ImageCollection, ImagePolicy, PhaseTimings, UrlCollection,};use serde::Deserialize;@@ -242,21 +242,31 @@ fn is_public_host_ffi(mut cx: FunctionContext) -> JsResult<JsBoolean> {Ok(cx.boolean(is_public_host(&host)))}-fn canonicalize_url_ffi(mut cx: FunctionContext) -> JsResult<JsValue> {+/// The URL policy's verdict for one URL: its canonical forms, or under `decline` the label of the+/// rule that refused it. The fetch lane reads the label so that it can drop a beacon job without+/// rejecting the record that carries it.+fn try_canonicalize_url_ffi(mut cx: FunctionContext) -> JsResult<JsObject> {let raw = cx.argument::<JsString>(0)?.value(&mut cx);- let Some(canonical) = canonicalize(&raw) else {- return Ok(cx.null().upcast());- };let result = cx.empty_object();- let fetch = cx.string(canonical.fetch);- result.set(&mut cx, "fetch", fetch)?;- let dedup = cx.string(canonical.dedup);- result.set(&mut cx, "dedup", dedup)?;- let host = cx.string(canonical.host);- result.set(&mut cx, "host", host)?;- let domain = cx.string(canonical.domain);- result.set(&mut cx, "domain", domain)?;- Ok(result.upcast())+ match try_canonicalize(&raw) {+ Ok(canonical) => {+ let fetch = cx.string(canonical.fetch);+ result.set(&mut cx, "fetch", fetch)?;+ let dedup = cx.string(canonical.dedup);+ result.set(&mut cx, "dedup", dedup)?;+ let host = cx.string(canonical.host);+ result.set(&mut cx, "host", host)?;+ let domain = cx.string(canonical.domain);+ result.set(&mut cx, "domain", domain)?;+ }+ Err(decline) => {+ let label = cx.string(decline.label());+ result.set(&mut cx, "decline", label)?;+ let unwanted = cx.boolean(decline.is_unwanted());+ result.set(&mut cx, "unwanted", unwanted)?;+ }+ }+ Ok(result)}#[neon::main]@@ -265,6 +275,6 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {cx.export_function("anonymizeKafkaPayload", anonymize_kafka_payload_ffi)?;cx.export_function("politenessKey", politeness_key_ffi)?;cx.export_function("isPublicHost", is_public_host_ffi)?;- cx.export_function("canonicalizeUrl", canonicalize_url_ffi)?;+ cx.export_function("tryCanonicalizeUrl", try_canonicalize_url_ffi)?;Ok(())}diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex eb6b9f4f3ba8..50d4afcf5c20 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.8"+version = "0.5.0"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rsindex 779650760b1a..763f6ff15b25 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -10,7 +10,7 @@ use crate::blur::is_image_data_uri;use crate::collect::is_image_ref_strict;use crate::context::{Ctx, ImageSource};use crate::images::ImageFallback;-use crate::json::{as_str, string_value};+use crate::json::{as_f64, as_str, string_value};use crate::srcset::largest_candidate;use crate::url::scrub_url;@@ -69,6 +69,71 @@ pub(crate) fn is_fetchable_image_attr(name: &str, tag: &str, parent_is_picture:}}+/// A CSS or HTML length read as pixels. `1`, `1px`, and `1.0` all read as one pixel. A percentage or+/// another unit reads as unknown.+pub(crate) fn px_length(text: &str) -> Option<f64> {+ let text = text.trim().to_ascii_lowercase();+ let number = text.strip_suffix("px").map_or(text.as_str(), str::trim);+ number.parse::<f64>().ok()+}++/// Both dimensions are known and neither is larger than one pixel. A negative length is not a+/// small box: the browser ignores it and renders the natural size.+pub(crate) fn is_at_most_one_pixel(width: Option<f64>, height: Option<f64>) -> bool {+ let at_most_one = |length: f64| (0.0..=1.0).contains(&length);+ matches!((width, height), (Some(width), Some(height)) if at_most_one(width) && at_most_one(height))+}++/// The last value an inline style gives one property, lowercased and without `!important`.+fn inline_style_declaration(style: &str, property: &str) -> Option<String> {+ style+ .split(';')+ .filter_map(|declaration| declaration.split_once(':'))+ .filter(|(name, _)| name.trim().eq_ignore_ascii_case(property))+ .map(|(_, value)| without_important(&value.trim().to_ascii_lowercase()).to_string())+ .next_back()+}++/// CSS allows white space between the `!` and `important`.+fn without_important(value: &str) -> &str {+ let Some(before_keyword) = value.strip_suffix("important") else {+ return value;+ };+ match before_keyword.trim_end().strip_suffix('!') {+ Some(declared_value) => declared_value.trim_end(),+ None => value,+ }+}++/// The inline style wins over the `width` and `height` attributes, as it does in the browser, so+/// a declared style that is not a pixel length leaves the dimension unknown.+fn dimension_px(attrs: &Object<'_>, style: Option<&str>, name: &str) -> Option<f64> {+ if let Some(declared) = style.and_then(|style| inline_style_declaration(style, name)) {+ return px_length(&declared);+ }+ let attribute = attrs.get(name)?;+ as_str(attribute).map_or_else(|| as_f64(attribute), px_length)+}++/// An `img` nobody can see: hidden by the `hidden` attribute or by `display: none`, or a box of+/// at most one pixel on each side. Such an element is a tracking pixel or a spacer, so its URL has+/// no value to the fetch lane, and a fetch of it reports a visit to whoever serves it. The byte+/// walker mirrors the attribute half of this rule in `bytewalk::attrs_hide_pixel`.+pub(crate) fn is_hidden_pixel(attrs: &Object<'_>) -> bool {+ if attrs.contains_key("hidden") {+ return true;+ }+ let style = attrs.get("style").and_then(as_str);+ let display = style.and_then(|style| inline_style_declaration(style, "display"));+ if display.as_deref() == Some("none") {+ return true;+ }+ is_at_most_one_pixel(+ dimension_px(attrs, style, "width"),+ dimension_px(attrs, style, "height"),+ )+}+/// 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))@@ -103,6 +168,9 @@ pub fn apply_blur(parent_is_picture: bool,) -> bool {let mut acted = false;+ // Computed only when a remote image is about to be collected, because the inline style is+ // parsed for it and most elements never reach that branch.+ let mut hidden_pixel: Option<bool> = None;for key in MEDIA_SRC_ATTRS {let Some(existing) = attrs.get(*key).and_then(as_str).map(str::to_string) else {continue;@@ -136,9 +204,17 @@ pub fn apply_blur();attrs.insert(Cow::Borrowed(*key), string_value(blurred));} else {- let collected = is_fetchable_image_attr(key, tag, parent_is_picture)- .then(|| ctx.collect_url_from(&selected, ImageSource::HtmlAttribute(key)))- .flatten();+ let collected =+ if !ctx.collects_urls() || !is_fetchable_image_attr(key, tag, parent_is_picture) {+ None+ } else if *hidden_pixel.get_or_insert_with(|| {+ tag.eq_ignore_ascii_case("img") && is_hidden_pixel(attrs)+ }) {+ ctx.decline_url(&selected, "hidden_pixel");+ None+ } else {+ ctx.collect_url_from(&selected, ImageSource::HtmlAttribute(key))+ };let scrubbed = scrub_url(ctx, &selected).unwrap_or_else(|| selected.clone());// Fetch completion must not change how an ordinary replay renders this element.attrs.insert(diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex 35bc563d6170..2ecf3c766b1d 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -14,8 +14,8 @@//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.use crate::assets::{- is_fetchable_image_attr, is_image_ref_attr, is_media_src_attr, IMAGE_REF_ATTR_PREFIX,- INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC,+ is_at_most_one_pixel, is_fetchable_image_attr, is_image_ref_attr, is_media_src_attr, px_length,+ IMAGE_REF_ATTR_PREFIX, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC,};use crate::blur::is_image_data_uri;use crate::collect::is_image_ref_strict;@@ -756,7 +756,17 @@ impl<'c, 'a> Walker<'c, 'a> {return self.redo_node(start, end, parent, node_mark, out);}emit_deferred_key(bytes, key, &mut emitted, out);- self.walk_attrs(v.0, kind, &tag, parent == ParentKind::Picture, out)?;+ let hidden_pixel = tag.eq_ignore_ascii_case("img")+ && self.ctx.collects_urls()+ && self.attrs_hide_pixel(v.0).ok()?;+ self.walk_attrs(+ v.0,+ kind,+ &tag,+ parent == ParentKind::Picture,+ hidden_pixel,+ 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);@@ -842,6 +852,83 @@ impl<'c, 'a> Walker<'c, 'a> {Some(end)}+ /// One pass over an object for several keys. An escaped key or a repeated wanted key makes the+ /// tree path decide, because that path sees the decoded key and keeps the last duplicate, and a+ /// side effect taken here on a different reading could not be rolled back.+ fn find_members<const N: usize>(+ &self,+ obj_start: usize,+ names: [&[u8]; N],+ ) -> Result<[Option<Span>; N], Fallback> {+ const PRESCAN_BUDGET: usize = 4096;+ let bytes = self.bytes;+ let budget_end = obj_start.saturating_add(PRESCAN_BUDGET);+ let mut found: [Option<Span>; N] = [None; N];+ let mut pos = obj_start + 1;+ let mut first = true;+ loop {+ pos = scan::skip_ws(bytes, pos);+ if bytes.get(pos) == Some(&b'}') {+ return Ok(found);+ }+ if pos >= budget_end {+ return Err(Fallback);+ }+ if !first {+ if bytes.get(pos) != Some(&b',') {+ return Ok(found);+ }+ pos = scan::skip_ws(bytes, pos + 1);+ }+ first = false;+ if bytes.get(pos) != Some(&b'"') {+ return Ok(found);+ }+ let key_end = scan::skip_string(bytes, pos).map_err(|_| Fallback)?;+ let key = &bytes[pos + 1..key_end - 1];+ if key.contains(&b'\\') {+ return Err(Fallback);+ }+ pos = scan::skip_ws(bytes, key_end);+ if bytes.get(pos) != Some(&b':') {+ return Ok(found);+ }+ let vspan = scan::locate_value(bytes, pos + 1).map_err(|_| Fallback)?;+ if let Some(index) = names.iter().position(|name| *name == key) {+ if found[index].is_some() {+ return Err(Fallback);+ }+ found[index] = Some(vspan);+ }+ pos = vspan.1;+ }+ }++ /// The attribute half of `assets::is_hidden_pixel`. The style half never reaches this walker,+ /// because `walk_node` sends every element with a `style` attribute to the tree path first.+ fn attrs_hide_pixel(&self, obj_start: usize) -> Result<bool, Fallback> {+ let [hidden, width, height] =+ self.find_members(obj_start, [b"hidden", b"width", b"height"])?;+ if hidden.is_some() {+ return Ok(true);+ }+ Ok(is_at_most_one_pixel(+ self.px_length_at(width)?,+ self.px_length_at(height)?,+ ))+ }++ fn px_length_at(&self, span: Option<Span>) -> Result<Option<f64>, Fallback> {+ let Some(span) = span else {+ return Ok(None);+ };+ if scan::is_string(self.bytes, span) {+ let text = scan::unescape(self.bytes, span).map_err(|_| Fallback)?;+ return Ok(px_length(&text));+ }+ Ok(scan::parse_number(self.bytes, span))+ }+/// An element's `attributes` object (mirrors `dom::scrub_attrs`, including the media blur)./// Namespaced attrs are appended before the closing brace; the tree path inserts them into the/// map instead, which is the same object semantically.@@ -851,6 +938,7 @@ impl<'c, 'a> Walker<'c, 'a> {kind: TagKind,tag: &str,parent_is_picture: bool,+ hidden_pixel: bool,out: &mut Vec<u8>,) -> Option<usize> {if self.bytes.get(start) != Some(&b'{') {@@ -868,7 +956,15 @@ impl<'c, 'a> Walker<'c, 'a> {return None;}if kind == TagKind::Media && is_media_src_attr(name) {- return w.blur_media_src(name, vstart, tag, parent_is_picture, out, stashes);+ return w.blur_media_src(+ name,+ vstart,+ tag,+ parent_is_picture,+ hidden_pixel,+ out,+ stashes,+ );}if name == INLINE_IMAGE_ATTR {return w.scrub_string_value(vstart, out, |w, s| {@@ -923,12 +1019,16 @@ impl<'c, 'a> Walker<'c, 'a> {/// One media source attribute (mirrors `assets::apply_blur` for a single key): data images are/// blurred; a remote URL becomes the placeholder. Its fetch-lane ref, when collected, and its/// host-scrubbed original are stashed alongside.+ /// `hidden_pixel` is true for an `img` nobody can see. The collector counts that refusal once+ /// per URL, so `src` and `srcset` naming one URL, and a re-walk after a fallback, count once.+ #[allow(clippy::too_many_arguments)]fn blur_media_src(&mut self,name: &str,vstart: usize,tag: &str,parent_is_picture: bool,+ hidden_pixel: bool,out: &mut Vec<u8>,stashes: &mut Vec<(String, String)>,) -> Option<usize> {@@ -963,12 +1063,15 @@ impl<'c, 'a> Walker<'c, 'a> {);scan::write_json_string(&blurred, out);} else {- let collected = is_fetchable_image_attr(name, tag, parent_is_picture)- .then(|| {- self.ctx- .collect_url_from(&selected, ImageSource::HtmlAttribute(property))- })- .flatten();+ let collected = if !is_fetchable_image_attr(name, tag, parent_is_picture) {+ None+ } else if hidden_pixel {+ self.ctx.decline_url(&selected, "hidden_pixel");+ None+ } else {+ self.ctx+ .collect_url_from(&selected, ImageSource::HtmlAttribute(property))+ };let scrubbed = scrub_url(self.ctx, &selected).unwrap_or_else(|| selected.clone());scan::write_json_string(PLACEHOLDER_SRC, out);if let Some(url_ref) = collected {@@ -1027,7 +1130,7 @@ impl<'c, 'a> Walker<'c, 'a> {};// 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.walk_attrs(vstart, kind, "", false, false, out)}_ => w.copy_value(vstart, out),},diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex 1c1924bc4ca2..7bf0738677ea 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -195,6 +195,21 @@ impl<'a> Ctx<'a> {collector.borrow_mut().collect(original)}+ pub(crate) fn collects_urls(&self) -> bool {+ self.url_collector.is_some()+ }++ /// Count a URL the walker refused before it reached the policy, in the collector's own decline+ /// metric, so that the walker's refusals and the policy's refusals read on one panel. Like the+ /// policy's memoized declines it counts once per distinct URL in a message, so a repeated+ /// spacer, and a re-walk after the byte walker hands an event to the tree path, do not count+ /// twice.+ pub(crate) fn decline_url(&self, raw: &str, reason: &'static str) {+ if let Some(collector) = self.url_collector.as_ref() {+ collector.borrow_mut().decline_once(raw, reason);+ }+ }+pub(crate) fn collect_url_from(&self, original: &str, source: ImageSource) -> Option<String> {let reference = self.collect_url(original)?;self.record_image_source(source, "url");diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex c2f7aa2f5a3b..d4d0d2fcb609 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -85,7 +85,10 @@ 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, politeness_key, CanonicalUrl};+pub use url_policy::{+ canonicalize, is_public_host, is_tracking_beacon, politeness_key, try_canonicalize,+ CanonicalUrl, Decline,+};/// Shared helpers for the image-neutralization tests across modules.#[cfg(test)]diff --git a/rust/replay-anonymizer/src/tracking_beacons.txt b/rust/replay-anonymizer/src/tracking_beacons.txtnew file mode 100644index 000000000000..6f96a2e6a09b--- /dev/null+++ b/rust/replay-anonymizer/src/tracking_beacons.txt@@ -0,0 +1,142 @@+# Advertising and analytics beacons. The replay collector and the image fetcher refuse these.+#+# One entry per line: <host pattern><path prefix>+# host pattern an exact host, "*.example.com" for every host below example.com, or "*" for every host+# path prefix starts with "/" and is compared case-insensitively with the start of the decoded+# request path. A prefix that does not end with "/" must end at a segment boundary,+# so "host/tr" refuses "/tr" and "/tr/x" but not "/trending/x". "/" alone matches+# every path on the host, and "*/" alone is refused.+# A line that starts with "#" and a blank line are ignored.+#+# url_policy.rs embeds this file. The mirror refuses a match when it collects a URL, and the+# fetcher refuses a match again for every job it reads from the frontier, so an entry added here+# also drains the queued backlog for that beacon without a request. A change here ships only with+# an image build of both lanes. A malformed line fails the crate's tests.++# X / Twitter Ads conversion pixel+analytics.twitter.com/i/adsct+t.co/i/adsct++# Microsoft Advertising UET and Clarity+bat.bing.com/action+bat.bing.net/action+c.bing.com/c.gif+c.clarity.ms/c.gif++# Meta pixel+www.facebook.com/tr++# Google Ads, Floodlight, and Analytics+www.google.com/pagead/1p-user-list+www.google.com/pagead/1p-conversion+www.google.com/ads/ga-audiences+www.googleadservices.com/pagead/conversion+googleads.g.doubleclick.net/pagead+ad.doubleclick.net/ddm/activity+*.fls.doubleclick.net/activityi+cm.g.doubleclick.net/+stats.g.doubleclick.net/+securepubads.g.doubleclick.net/pcs+google-analytics.com/+*.google-analytics.com/++# LinkedIn Insight Tag+px.ads.linkedin.com/+dc.ads.linkedin.com/+www.linkedin.com/px++# TikTok, Pinterest, Snap, Quora, and Reddit pixels+analytics.tiktok.com/+ct.pinterest.com/+tr.snapchat.com/+q.quora.com/_/ad+alb.reddit.com/++# Shopify storefront pixel+v.shopify.com/last_shop++# HubSpot, WordPress, Segment, and Mixpanel image beacons+track.hubspot.com/__ptq.gif+pixel.wp.com/+api.segment.io/v1/pixel+api.mixpanel.com/track++# Yandex Metrica, VK, and Mail.ru+mc.yandex.ru/watch+mc.yandex.ru/pixel+mc.yandex.com/watch+mc.yandex.com/pixel+vk.com/rtrg+top-fwz1.mail.ru/++# Adobe Analytics and Audience Manager, on Adobe hosts and on customer CNAMEs+*.omtrdc.net/b/ss+*.2o7.net/b/ss+*/b/ss/+*.demdex.net/+cm.everesttech.net/++# Legacy Google Analytics, Matomo, and Piwik image beacons at the site root of any host+*/__utm.gif+*/matomo.php+*/piwik.php++# Retargeting, cookie sync, and bidder pixels+d.adroll.com/+*.bidr.io/+insight.adsrvr.org/+*.adnxs.com/+*.criteo.com/+trc.taboola.com/+trc-events.taboola.com/+tr.outbrain.com/+sp.analytics.yahoo.com/+pixel.advertising.com/+*.amazon-adsystem.com/+*.rubiconproject.com/+*.casalemedia.com/+*.pubmatic.com/+*.openx.net/+p.adsymptotic.com/+*.mathtag.com/+*.rlcdn.com/+*.agkn.com/+*.bluekai.com/+*.exelator.com/+*.krxd.net/+pixel.tapad.com/+*.3lift.com/+match.sharethrough.com/+*.teads.tv/+*.smartadserver.com/+*.liadm.com/+*.id5-sync.com/+*.bidswitch.net/+tags.srv.stackadapt.com/+creativecdn.com/tags+*.creativecdn.com/tags+*.zemanta.com/+tag.perfectaudience.com/+pixel.sitescout.com/+bh.contextweb.com/+*.sonobi.com/+rtb.gumgum.com/+ap.lijit.com/+*.pippio.com/+*.semasio.net/+*.dotomi.com/+*.bttrack.com/++# Sales intelligence trackers+serve.albacross.com/+b.6sc.co/+epsilon.6sense.com/++# Affiliate network pixels+www.awin1.com/sread.img+www.emjcd.com/+track.linksynergy.com/++# Email open pixels rendered inside web apps+mandrillapp.com/track/open.php+*.ct.sendgrid.net/wf/opendiff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rsindex 37d2a12d815d..67201399a98c 100644--- a/rust/replay-anonymizer/src/url_collect.rs+++ b/rust/replay-anonymizer/src/url_collect.rs@@ -92,6 +92,10 @@ pub struct UrlCollector {/// 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>,+ /// URLs the walker refused before they reached the policy. A repeat, or a re-walk after the+ /// byte walker hands an event to the tree path, must not count twice. The memo cannot hold+ /// these, because a `None` there would also stop a later visible use of the same URL.+ walker_declined: HashSet<String>,}impl UrlCollector {@@ -102,9 +106,24 @@ impl UrlCollector {seen: HashSet::new(),memo: HashMap::new(),declines: HashMap::new(),+ walker_declined: HashSet::new(),}}+ /// Count a refusal the walker made for `raw`, once per distinct URL in this message. Past the+ /// memo cap, or for an over-length URL, the refusal counts every time, because a second count+ /// costs less than unbounded memory.+ pub(crate) fn decline_once(&mut self, raw: &str, reason: &'static str) {+ let remember = raw.len() <= MAX_URL_LEN && self.walker_declined.len() < MAX_MEMO_ENTRIES;+ if self.walker_declined.contains(raw) {+ return;+ }+ if remember {+ self.walker_declined.insert(raw.to_string());+ }+ self.decline(reason);+ }+/// 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> {@@ -132,7 +151,7 @@ impl UrlCollector {raw.len() <= MAX_URL_LEN && self.memo.len() < MAX_MEMO_ENTRIES}- fn decline(&mut self, reason: &'static str) {+ pub(crate) fn decline(&mut self, reason: &'static str) {*self.declines.entry(reason).or_insert(0) += 1;}diff --git a/rust/replay-anonymizer/src/url_policy.rs b/rust/replay-anonymizer/src/url_policy.rsindex 180577e6736b..91576f13baa6 100644--- a/rust/replay-anonymizer/src/url_policy.rs+++ b/rust/replay-anonymizer/src/url_policy.rs@@ -13,6 +13,7 @@use std::collections::HashSet;use std::net::IpAddr;+use std::sync::LazyLock;use percent_encoding::percent_decode_str;use public_suffix::{EffectiveTLDProvider, DEFAULT_PROVIDER};@@ -65,6 +66,111 @@ const CREDENTIAL_PARAMS: &[&str] = &[const SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] =&[("_nc_ohc", &["_nc_ohc", "_nc_ht", "ccb", "oe", "oh", "stp"])];+/// The advertising and analytics beacons the lane refuses. The file documents its own format.+const TRACKING_BEACONS: &str = include_str!("tracking_beacons.txt");++enum BeaconHost {+ Any,+ /// `*.example.com`: every host below the suffix, never the suffix itself.+ Below(String),+ Exact(String),+}++struct BeaconPattern {+ host: BeaconHost,+ path_prefix: String,+}++impl BeaconPattern {+ /// A prefix that does not end with `/` must end at a segment boundary, so that `host/tr` refuses+ /// `/tr` and `/tr/x` but not `/trending/x.png`. A `;` also ends the segment, because Floodlight+ /// puts its parameters after one (`/activityi;src=...`).+ fn matches(&self, host: &str, path: &str) -> bool {+ let host_matches = match &self.host {+ BeaconHost::Any => true,+ BeaconHost::Below(suffix) => host.ends_with(suffix.as_str()),+ BeaconHost::Exact(exact) => host == exact,+ };+ let Some(rest) = path.strip_prefix(self.path_prefix.as_str()) else {+ return false;+ };+ host_matches+ && (self.path_prefix.ends_with('/')+ || rest.is_empty()+ || rest.starts_with('/')+ || rest.starts_with(';'))+ }+}++static TRACKING_BEACON_PATTERNS: LazyLock<Vec<BeaconPattern>> = LazyLock::new(|| {+ parse_beacon_list(TRACKING_BEACONS)+ .unwrap_or_else(|line| panic!("tracking_beacons.txt has a malformed entry: {line:?}"))+});++fn parse_beacon_list(text: &str) -> Result<Vec<BeaconPattern>, String> {+ let mut patterns = Vec::new();+ for line in text.lines().map(str::trim) {+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ let Some(slash) = line.find('/') else {+ return Err(line.to_string());+ };+ let (host, path) = line.split_at(slash);+ // A scheme, port, space, or trailing dot in the host, or a comment, query, or percent-encoding+ // in the path, would parse as an entry that can never match, so it is refused instead of+ // shipping as a silent no-op. A catch-all entry is refused too, because it would stop the+ // whole lane with only a counter as evidence.+ let host_is_malformed = host.contains(|c: char| c == ':' || c.is_whitespace())+ || (host != "*" && (!host.contains('.') || host.ends_with('.')));+ let path_is_malformed =+ path.contains(|c: char| c.is_whitespace() || matches!(c, '#' | '?' | '%'));+ if host_is_malformed || path_is_malformed || (host == "*" && path == "/") {+ return Err(line.to_string());+ }+ let host = match host {+ "*" => BeaconHost::Any,+ _ if host.starts_with("*.") && host.len() > 2 && !host[1..].contains('*') => {+ BeaconHost::Below(host[1..].to_ascii_lowercase())+ }+ _ if !host.is_empty() && !host.contains('*') => {+ BeaconHost::Exact(host.to_ascii_lowercase())+ }+ _ => return Err(line.to_string()),+ };+ patterns.push(BeaconPattern {+ host,+ path_prefix: path.to_ascii_lowercase(),+ });+ }+ Ok(patterns)+}++/// Whether a host and decoded path name an entry in `tracking_beacons.txt`.+pub fn is_tracking_beacon(host: &str, path: &str) -> bool {+ let host = host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase();+ matches_beacon_list(&host, &collapse_slashes(&path.to_ascii_lowercase()))+}++/// `host` and `path` must already be lowercase, and the path decoded with its slashes collapsed.+fn matches_beacon_list(host: &str, path: &str) -> bool {+ TRACKING_BEACON_PATTERNS+ .iter()+ .any(|pattern| pattern.matches(host, path))+}++/// Origin servers collapse a doubled slash, so `//adsct` and `/adsct` name one resource to them.+fn collapse_slashes(path: &str) -> String {+ let mut collapsed = String::with_capacity(path.len());+ for character in path.chars() {+ if character == '/' && collapsed.ends_with('/') {+ continue;+ }+ collapsed.push(character);+ }+ collapsed+}+/// 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;@@ -179,6 +285,7 @@ fn is_public_domain_name(lowercase_host: &str) -> bool {/// 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)]+#[non_exhaustive]pub enum Decline {/// Longer than [`MAX_URL_LEN`], before or after normalization.TooLong,@@ -197,9 +304,19 @@ pub enum Decline {Credential,/// A query parameter name could not be percent-decoded as UTF-8.InvalidQuery,+ /// An advertising or analytics beacon from `tracking_beacons.txt`. Nobody sees the one-pixel+ /// image, and a fetch of it reports a conversion or a visit to the network that serves it.+ TrackingBeacon,}impl Decline {+ /// True for a URL the policy refuses because nobody wants it fetched, not because it is+ /// malformed or unsafe. A consumer that reads jobs from a queue drops only that job for such a+ /// decline, and rejects the whole record for every other one.+ pub fn is_unwanted(self) -> bool {+ matches!(self, Decline::TrackingBeacon)+ }+/// The metric label. Stable, because a dashboard and an alert both key on it.pub fn label(self) -> &'static str {match self {@@ -211,6 +328,7 @@ impl Decline {Decline::NonPublicHost => "non_public_host",Decline::Credential => "credential",Decline::InvalidQuery => "invalid_query",+ Decline::TrackingBeacon => "tracking_beacon",}}}@@ -255,9 +373,13 @@ pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {if host != host_str {url.set_host(Some(&host)).map_err(|_| Decline::NoHost)?;}- if has_credential_query(&url)? || has_credential_path(&url, &host)? {+ let lowercase_path = decoded_lowercase_path(&url)?;+ if has_credential_query(&url)? || has_credential_path(&lowercase_path, &host) {return Err(Decline::Credential);}+ if matches_beacon_list(&host, &collapse_slashes(&lowercase_path)) {+ return Err(Decline::TrackingBeacon);+ }let original_query = original_query(raw);url.set_fragment(None);@@ -335,14 +457,20 @@ fn has_valid_percent_encoding(value: &str) -> bool {true}-fn has_credential_path(url: &Url, host: &str) -> Result<bool, Decline> {+/// The request path with percent-encoding removed and ASCII lowercased. A path that cannot be+/// decoded is refused as a credential, because the lane cannot prove it carries none.+fn decoded_lowercase_path(url: &Url) -> Result<String, Decline> {if !has_valid_percent_encoding(url.path()) {return Err(Decline::Credential);}- let path = percent_decode_str(url.path())+ Ok(percent_decode_str(url.path()).decode_utf8().map_err(|_| Decline::Credential)?- .to_ascii_lowercase();+ .to_ascii_lowercase())+}++/// `path` is the decoded lowercase path from [`decoded_lowercase_path`].+fn has_credential_path(path: &str, host: &str) -> bool {let segments: Vec<&str> = path.split('/').collect();let first_segment_has_bunny_token = segments.get(1)@@ -370,11 +498,11 @@ fn has_credential_path(url: &Url, host: &str) -> Result<bool, Decline> {.is_some_and(|token| !token.is_empty())});- Ok(first_segment_has_bunny_token+ first_segment_has_bunny_token|| has_oracle_token|| has_cloudinary_signature|| has_supabase_signature- || has_session_token)+ || has_session_token}fn remove_volatile_params(raw_query: Option<&str>) -> Result<Option<String>, Decline> {@@ -430,6 +558,69 @@ mod tests {assert!(canonicalize(&long).is_none());}+ #[test]+ fn tracking_beacons_are_refused_by_host_pattern_and_path_prefix() {+ for raw in [+ "https://analytics.twitter.com/i/adsct?txn_id=abc&p_id=Twitter",+ "https://ANALYTICS.twitter.com/I/ADSCT",+ "https://analytics.twitter.com/i/%61dsct",+ "https://analytics.twitter.com/i//adsct",+ "https://www.facebook.com//tr?id=1",+ "https://www.facebook.com/tr?id=1&ev=PageView",+ "https://bat.bing.com/action/0?ti=123&Ver=2",+ "https://123456.fls.doubleclick.net/activityi;src=1;type=a",+ "https://metrics.example.com/b/ss/rsid/1/JS-2.0/s123",+ "https://ct.pinterest.com/v3/?tid=1&noscript=1",+ ] {+ assert_eq!(try_canonicalize(raw), Err(Decline::TrackingBeacon), "{raw}");+ }+ for raw in [+ "https://pbs.twimg.com/media/abc.jpg",+ "https://analytics.twitter.com/transparency/logo.png",+ "https://notanalytics.twitter.com/i/adsct",+ "https://fls.doubleclick.net/activityi",+ "https://example.com/b/ss.png",+ "https://www.facebook.com/trending/x.png",+ "https://bat.bing.com/actions/x.png",+ "https://example.com/matomo.php.png",+ "https://cdn.shopify.com/s/files/1/photo.png",+ "https://d111.cloudfront.net/photo.png",+ ] {+ assert!(canonicalize(raw).is_some(), "{raw} is not a beacon");+ }+ assert_eq!(+ try_canonicalize("https://analytics.twitter.com/i/adsct?token=abc"),+ Err(Decline::Credential),+ "a credential is refused before the beacon list is consulted"+ );+ }++ #[test]+ fn the_beacon_list_parses_and_refuses_a_malformed_entry() {+ assert!(!TRACKING_BEACON_PATTERNS.is_empty());+ for malformed in [+ "no-slash",+ "/path-only",+ "*x.example.com/",+ "a.*.example.com/",+ "*.example.com",+ "*/",+ "https://host.example.com/path",+ "host.example.com:443/path",+ "host.example.com/path # note",+ "host example.com/path",+ "host.example.com./path",+ "localhost/path",+ "host.example.com/path?x=1",+ "host.example.com/%61",+ ] {+ assert!(+ parse_beacon_list(malformed).is_err(),+ "{malformed:?} must not parse"+ );+ }+ }+#[test]fn canonicalize_normalizes_and_removes_the_fragment() {let c = canonicalize("HTTPS://Example.COM:443/A.png#frag").unwrap();diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex 0f5e97bceee1..a8ea625e0a3d 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -288,6 +288,137 @@ fn a_remote_src_keeps_its_placeholder_and_stashes_the_ref() {}}+#[test]+fn a_hidden_pixel_or_a_beacon_keeps_its_placeholder_and_is_declined() {+ let src = "https://cdn.example.com/spacer.gif";+ for (attrs, reason) in [+ (+ json!({ "src": src, "width": "1", "height": "1" }),+ "hidden_pixel",+ ),+ (+ json!({ "src": src, "width": 1, "height": 1 }),+ "hidden_pixel",+ ),+ (+ json!({ "src": src, "width": "0px", "height": "1PX" }),+ "hidden_pixel",+ ),+ (+ json!({ "src": src, "style": "width: 1px; height:1px !important" }),+ "hidden_pixel",+ ),+ (+ json!({ "src": src, "style": "display:none" }),+ "hidden_pixel",+ ),+ (+ json!({ "src": src, "style": "display: none ! important" }),+ "hidden_pixel",+ ),+ (+ json!({ "src": src, "width": "1", "height": "1", "style": "display: block" }),+ "hidden_pixel",+ ),+ (json!({ "src": src, "hidden": "" }), "hidden_pixel"),+ (+ json!({ "src": src, "srcset": format!("{src} 2x"), "width": "1", "height": "1" }),+ "hidden_pixel",+ ),+ (+ json!({ "src": "https://analytics.twitter.com/i/adsct?txn_id=abc&p_id=Twitter" }),+ "tracking_beacon",+ ),+ ] {+ for (engine, result) in run(attrs.clone(), true) {+ let (line, meta) = (&result[0], &result[1]);+ let attributes = attrs_of(line);+ let src = attributes["src"].as_str().expect("src is a string");+ assert!(+ src.starts_with("data:image/svg+xml"),+ "{engine}: {attrs} should keep the placeholder, got {src}"+ );+ assert!(+ attributes.get("data-anon-image-ref-src").is_none(),+ "{engine}: {attrs} must not carry a ref"+ );+ assert!(+ meta.get("urls").is_none(),+ "{engine}: {attrs} must not be collected"+ );+ assert_eq!(+ meta["urlDeclines"],+ json!([{ "reason": reason, "count": 1 }]),+ "{engine}: {attrs}"+ );+ }+ }+ for attrs in [+ json!({ "src": src, "width": "2", "height": "2" }),+ json!({ "src": src, "width": "1" }),+ json!({ "src": src, "width": "1", "height": "100%" }),+ json!({ "src": src, "width": "1", "height": "1", "style": "width: 100%" }),+ json!({ "src": src, "width": "-1", "height": "-1" }),+ json!({ "src": "https://analytics.twitter.com/transparency/logo.png" }),+ ] {+ for (engine, result) in run(attrs.clone(), true) {+ let meta = &result[1];+ assert_eq!(+ meta["urls"].as_array().map(Vec::len),+ Some(1),+ "{engine}: {attrs} is a visible image and must be collected"+ );+ assert!(meta.get("urlDeclines").is_none(), "{engine}: {attrs}");+ }+ }+}++/// The byte walker reads attribute keys as raw bytes and takes the first of a repeated key, while+/// the tree path decodes keys and keeps the last one. Both must reach the tree's answer, and no URL+/// may leak into the collection before the hand-off.+#[test]+fn an_escaped_or_repeated_dimension_key_still_declines_a_hidden_pixel() {+ for attributes_json in [+ r#"{"src":"https://cdn.example.com/spacer.gif","w\u0069dth":"1","height":"1"}"#,+ r#"{"src":"https://cdn.example.com/spacer.gif","width":"100","width":"1","height":"1"}"#,+ r#"{"src":"https://cdn.example.com/spacer.gif","src":"https://cdn.example.com/spacer.gif","width":"1","height":"1"}"#,+ ] {+ let inner = format!(+ r#"{{"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":{attributes_json},"childNodes":[]}}}}]}}}}]}}}}"#+ );+ let payload = json!({ "distinct_id": "d", "data": inner })+ .to_string()+ .into_bytes();+ for byte_walk in [true, false] {+ let mut bytes = payload.clone();+ let message = anonymize_kafka_payload_collecting(+ &AllowLists::default(),+ &mut bytes,+ AnonymizeOpts {+ byte_walk,+ image_policy: ImagePolicy::Inline,+ },+ None,+ None,+ Some(UrlCollection {+ url_key: URL_KEY.to_string(),+ }),+ )+ .expect("anonymize should succeed");+ let meta = serde_json::to_value(&message.meta).expect("meta serializes");+ assert!(+ meta.get("urls").is_none(),+ "byte_walk={byte_walk}: {attributes_json} must not be collected"+ );+ assert_eq!(+ meta["urlDeclines"],+ json!([{ "reason": "hidden_pixel", "count": 1 }]),+ "byte_walk={byte_walk}: {attributes_json}"+ );+ }+ }+}+#[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) {