Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay): index page URLs for JSON-LD and full snapshots (#97197)

Robbief1cd38c6932b
diff --git a/docs/internal/session-replay-structured-data-index.md b/docs/internal/session-replay-structured-data-index.md
index d1335cc2742a..21b185a35903 100644
--- a/docs/internal/session-replay-structured-data-index.md
+++ b/docs/internal/session-replay-structured-data-index.md
@@ -23,7 +23,8 @@ Timestamps use doubles so fractional milliseconds survive an exact join.
Window IDs match the IDs in the scrubbed recording lines.
The index contains no DOM nodes or JSON-LD payload text.
-A `json_ld` row contains an optional `full_snapshot_ts_ms` reference and up to 64 distinct root types.
+A `json_ld` row contains an optional `url` and up to 64 distinct root types.
+The schema also accepts `full_snapshot_ts_ms`, but the URL-only SDK change does not send this optional reference.
Types come from root objects, root arrays, and `@graph` members.
Nested entity properties, such as a product's offers, do not contribute types.
The types help select candidates; read the payload before deciding which label to use.
@@ -35,50 +36,142 @@ The index omits non-v7 session IDs and starts outside the interval from seven da
Normal replay storage and block metadata continue for those sessions.
For an event-time search, include the preceding seven session-start dates and filter `event_ts_ms`.
+## Full snapshot URLs
+
+The ML-mirror metadata consumer enriches index rows before writing Parquet.
+For JSON-LD, it copies the URL from the `page` entry at the same event index, then omits that duplicate page row.
+For a full snapshot, it uses a URL entry at the same event index or the immediately preceding event index.
+The URL entry must belong to the same window and have a timestamp no later than the snapshot.
+An explicit URL already on the index entry takes precedence.
+
+This uses the block metadata that the shared recorder already produces.
+It adds no state or behavior to the shared replay recorder and does not change stored rrweb events.
+Payload boundaries within a block do not affect the lookup, but any intervening event prevents the preceding-event association.
+A block boundary or reversed timestamps can leave the snapshot without a URL.
+Readers can use durable `page` rows to find candidates across blocks, without an ingestion-side session cache.
+
+The sparse index identifies URL-bearing events, not their original rrweb types.
+An adjacent URL is useful candidate metadata, but does not prove that the source was a Meta event.
+The shared recorder omits Meta events without URLs, so the index cannot reliably identify every unknown-URL boundary.
+Payload validation must account for this limit.
+
## Pairing labels with snapshots
Read the requested session-start partitions into DuckDB views named `labels`, `snapshots`, and `pages`.
Use `union_by_name=true` when reading Parquet files across schema versions.
-A label with a reference can join a snapshot in another payload or block:
+The following query finds candidates by URL and time, including separate blocks and out-of-order arrivals.
+Its one-second Meta gap and two-second label gap are example selection parameters, not SDK guarantees.
+Measure match coverage and audit payloads before choosing the final thresholds.
```sql
+WITH page_urls AS (
+ SELECT team_id, session_id, window_id, event_ts_ms,
+ CASE WHEN count(url) = count(*) AND count(DISTINCT url) = 1
+ THEN min(url) END AS url
+ FROM pages
+ GROUP BY team_id, session_id, window_id, event_ts_ms
+), snapshot_urls AS (
+ SELECT s.* EXCLUDE (url),
+ coalesce(s.url, CASE WHEN s.event_ts_ms - p.event_ts_ms <= 1000
+ THEN p.url END) AS url
+ FROM (SELECT DISTINCT * FROM snapshots) s
+ ASOF LEFT JOIN page_urls p
+ ON s.team_id = p.team_id
+ AND s.session_id = p.session_id
+ AND s.window_id = p.window_id
+ AND s.event_ts_ms >= p.event_ts_ms
+), incomplete_sessions AS (
+ SELECT team_id, session_id FROM labels WHERE block_index_truncated
+ UNION
+ SELECT team_id, session_id FROM snapshots WHERE block_index_truncated
+ UNION
+ SELECT team_id, session_id FROM pages WHERE block_index_truncated
+)
SELECT DISTINCT
- j.team_id, j.session_id, j.window_id, j.full_snapshot_ts_ms,
- j.root_types,
+ j.team_id, j.session_id, j.window_id, j.url, j.root_types,
+ j.event_ts_ms AS label_ts_ms, s.event_ts_ms AS snapshot_ts_ms,
j.block_s3_key AS label_block, j.block_byte_start AS label_start,
j.block_byte_end AS label_end, j.event_index AS label_event_index,
s.block_s3_key AS snapshot_block, s.block_byte_start AS snapshot_start,
s.block_byte_end AS snapshot_end, s.event_index AS snapshot_event_index
FROM labels j
-JOIN snapshots s
+JOIN snapshot_urls s
ON j.team_id = s.team_id
AND j.session_id = s.session_id
AND j.window_id = s.window_id
- AND j.full_snapshot_ts_ms = s.event_ts_ms
-WHERE NOT j.block_index_truncated AND NOT s.block_index_truncated;
+ AND j.url = s.url
+ AND abs(j.event_ts_ms - s.event_ts_ms) <= 2000
+WHERE j.url IS NOT NULL AND j.url <> ''
+ AND NOT EXISTS (
+ SELECT 1 FROM incomplete_sessions i
+ WHERE i.team_id = j.team_id AND i.session_id = j.session_id
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM page_urls p
+ WHERE p.team_id = j.team_id AND p.session_id = j.session_id
+ AND p.window_id = j.window_id
+ AND p.event_ts_ms BETWEEN least(j.event_ts_ms, s.event_ts_ms)
+ AND greatest(j.event_ts_ms, s.event_ts_ms)
+ AND p.url IS DISTINCT FROM j.url
+ );
```
-This query returns candidates. A timestamp is not a unique rrweb event ID.
-Fetch the referenced blocks, check the event kind and timestamp at each index, and deduplicate identical snapshots by content.
-Reject a join if distinct full snapshots still share its team, session, window, and timestamp.
-Several JSON-LD scripts can label one snapshot. Combine their labels only after that validation.
-Do not count them as separate training examples.
-
-Older SDK events and mutation captures have no explicit snapshot reference.
-They still appear in the label index, but proximity matching is approximate and must stay separate from explicitly linked pairs.
-Out-of-order arrivals need no ingestion-side session cache: a later query can join both entries once both blocks exist.
+This query returns candidates, not verified pairs.
+A matching scrubbed URL and timestamp gap cannot prove that a JSON-LD mutation describes an earlier DOM snapshot.
+The index cannot prove adjacency across blocks because it omits most event kinds.
+Missing events, masked Meta events, and URL collisions can also conceal a navigation.
+Neither an adjacent URL nor a temporal fallback proves the label describes that snapshot.
+A later query can find late arrivals once both blocks exist; record the input object list to make a dataset run reproducible.
+
+Fetch each distinct block key and inclusive byte range once, then decompress its Snappy JSONL recording lines.
+Check the window, event kind, and timestamp at each event index before using its payload.
+Reject ambiguous matches, including distinct full snapshots that share a timestamp or several plausible snapshots for one label.
+A timestamp is not a unique rrweb event ID.
+Deduplicate repeated snapshots by content before resolving such ambiguity.
+Several JSON-LD scripts can label one snapshot; combine their labels after validation instead of counting separate examples.
+Define a label policy for multiple root types and `@graph` entities before training a single-root classifier.
+
+The query excludes sessions with visible truncated index rows, but cannot detect a missing block or an entirely absent index.
+For strict examples, inspect the surrounding replay events and reject pairs whose page state cannot be established.
+Exclude JSON-LD rows without URLs; do not infer those URLs from older SDK navigation events.
## Domain and page coverage
-Use the latest preceding `page` event in the same team, session, and window as provisional URL context.
-Page entries are independent rows because a URL change and a snapshot can arrive in separate payloads.
-Check that context when fetching the recording; missing navigation events or truncated index blocks can leave it incomplete.
-
-URLs come from the anonymizer's post-scrub metadata.
-Their hostnames permit site grouping, but redacted paths can merge distinct pages.
-Report unique scrubbed URLs as a lower bound on page diversity.
-Exact page counts need a separately reviewed fingerprint of the original page identity.
-For domain-disjoint datasets, normalize hostnames to registrable domains with a public suffix list before assigning train, dev, and test groups.
+Use the `url` on each `json_ld` row for site and page coverage.
+The SDK captures it in `data.href` at the same time as the label, after applying replay URL masking and hash settings.
+The shared recorder emits a label entry and a URL entry for that event; the ML-mirror consumer combines them by event index.
+The anonymizer scrubs it again before extracting index metadata.
+This works when navigation events and JSON-LD arrive in separate payloads and needs no session URL cache.
+
+Exclude rows without a usable URL from coverage counts and dataset selection.
+Older SDKs do not send this field; URL masking can also omit it.
+The index retains those rows, but coverage queries do not infer their URLs from `page` events.
+JSON-LD events with a URL do not also create a `page` row in Parquet.
+
+Count distinct normalized scrubbed URLs as page families.
+Scrubbing can group similar paths, which helps deduplicate similar pages.
+These counts do not measure distinct DOM structures.
+For domain-disjoint datasets, normalize hostnames to registrable domains with a pinned public suffix list, including its private suffix rules.
+Store a deterministic domain-to-split assignment before sampling examples.
+Never split individual sessions at random, because sessions from the same site would leak across splits.
+
+The index supplies candidate types, URLs, timestamps, and fetch locations; it does not supply DOM hashes or verified training labels.
+A dataset builder still needs to:
+
+1. Deduplicate index retries, validate candidate pairs, and consolidate their labels.
+2. Normalize scrubbed URLs and select a representative per page family, with a per-domain cap.
+3. Deduplicate DOM content globally so copies under different domains cannot leak across splits.
+4. Balance sampling within the fixed domain splits, then save the selection parameters and source locations in a manifest.
+5. Report usable examples, sessions, unique page families, domains, and root-type counts for each split, plus rejected and ambiguous candidates.
+
+Keep split assignment stable across resampling and dataset versions.
+Audit examples where one scrubbed URL has different labels; URL deduplication alone must not silently choose a conflicting label.
+Exclude cross-split content duplicates or keep their domain groups together before freezing the final split.
+
+This layout supports a bounded-date Parquet scan followed by selective block fetches.
+It does not provide an S3 point lookup by domain or URL: those filters still scan the selected date partitions.
+Cache the selected index locally for repeated sampling and split experiments.
+A compacted metadata table can reduce file-listing overhead later without changing SDK capture or replay storage.
## Delivery and limits
@@ -100,3 +193,11 @@ The consumer can deploy before the producer because index metadata is optional.
Deploy the consumer first: an older consumer accepts new metadata but does not write the index.
Confirm that the sink's S3 permissions and bucket lifecycle policy cover the new sibling prefix before rollout.
This change does not backfill old recordings.
+
+## JSON-LD URL rollout
+
+Deploy the anonymizer that scrubs `data.href` before releasing the SDK change that sends it.
+Deploy the updated ML-mirror metadata consumer to populate URLs on JSON-LD and full-snapshot Parquet rows.
+The existing schema and shared recorder already provide the fields needed by that consumer.
+Full-snapshot URL enrichment also works with older SDKs that send Meta events; JSON-LD coverage still requires the SDK URL addition.
+Existing events without `data.href` remain readable and do not contribute to URL-based coverage.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
index 6b135d418191..d368bfb3fb0e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
@@ -3,6 +3,7 @@ import { ParquetReader } from '@dsnp/parquetjs'
import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
import { MlBlockMetadataRow } from './block-metadata-row'
+import { replayIndexPartitions } from './replay-index'
const row = (sessionId: string, teamId: string): MlBlockMetadataRow => ({
session_id: sessionId,
@@ -58,6 +59,68 @@ describe('BlockMetadataParquetStore', () => {
} as unknown as S3Client
})
+ it.each([
+ { name: 'adjacent URL', pageIndex: 0, pageTime: 1000, window: 'w1', expected: 'https://example.com/page' },
+ { name: 'same timestamp', pageIndex: 0, pageTime: 1100, window: 'w1', expected: 'https://example.com/page' },
+ { name: 'intervening event', pageIndex: 0, pageTime: 1000, window: 'w1', expected: null },
+ { name: 'different window', pageIndex: 0, pageTime: 1000, window: 'w2', expected: null },
+ { name: 'reversed timestamps', pageIndex: 0, pageTime: 1200, window: 'w1', expected: null },
+ { name: 'later URL', pageIndex: 4, pageTime: 1200, window: 'w1', expected: null },
+ ])('enriches snapshot URLs from block metadata: $name', ({ name, pageIndex, pageTime, window, expected }) => {
+ const block: MlBlockMetadataRow = {
+ ...row('s1', 't1'),
+ session_start_ts_ms: 1000,
+ event_count: 6,
+ replay_index_entries: [
+ {
+ kind: 'full_snapshot',
+ windowId: 'w1',
+ eventIndex: name === 'intervening event' ? 2 : 1,
+ eventTimestamp: 1100,
+ },
+ {
+ kind: 'page',
+ windowId: window,
+ eventIndex: pageIndex,
+ eventTimestamp: pageTime,
+ url: 'https://example.com/page',
+ },
+ ],
+ }
+ const entries = [...replayIndexPartitions([block]).values()].flat()
+ expect(entries.find((entry) => entry.kind === 'full_snapshot')?.url).toBe(expected)
+ })
+
+ it('does not carry URLs between blocks', () => {
+ const source = {
+ ...row('s1', 't1'),
+ session_start_ts_ms: 1000,
+ }
+ const entries = [
+ ...replayIndexPartitions([
+ {
+ ...source,
+ replay_index_entries: [
+ {
+ kind: 'page',
+ windowId: 'w1',
+ eventIndex: 0,
+ eventTimestamp: 1000,
+ url: 'https://example.com/page',
+ },
+ ],
+ },
+ {
+ ...source,
+ replay_index_entries: [
+ { kind: 'full_snapshot', windowId: 'w1', eventIndex: 1, eventTimestamp: 1100 },
+ ],
+ },
+ ]).values(),
+ ].flat()
+ expect(entries.find((entry) => entry.kind === 'full_snapshot')?.url).toBeNull()
+ })
+
it('writes one dt-partitioned Parquet object that round-trips', async () => {
const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
await store.write([row('s1', 't1'), row('s2', 't1')])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts
index 42f98304da1d..e7a0b1d55a83 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts
@@ -30,15 +30,30 @@ const block = (sessionId: string, teamId: number, distinctId: string): SessionBl
urls: ['https://example.com/[redacted]'],
snapshotSource: 'web',
replayIndexEntries: [
- { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1_700_000_000_001.5, eventIndex: 0 },
+ {
+ kind: 'page',
+ windowId: 'w1',
+ eventTimestamp: 1_700_000_000_001.5,
+ eventIndex: 0,
+ url: 'https://example.com/[redacted]',
+ },
+ { kind: 'full_snapshot', windowId: 'w1', eventTimestamp: 1_700_000_000_001.5, eventIndex: 1 },
{
kind: 'json_ld',
windowId: 'w1',
eventTimestamp: 1_700_000_000_001.5,
- eventIndex: 1,
+ eventIndex: 2,
fullSnapshotTimestamp: 1_700_000_000_001.5,
rootTypes: ['Product'],
},
+ {
+ kind: 'page',
+ windowId: 'w1',
+ eventTimestamp: 1_700_000_000_001.5,
+ eventIndex: 2,
+ url: 'https://example.com/[redacted]',
+ },
+ { kind: 'json_ld', windowId: 'w1', eventTimestamp: 1_700_000_000_001.5, eventIndex: 3, rootTypes: ['Article'] },
],
})
@@ -91,18 +106,25 @@ describe('ML metadata producer → sink round-trip', () => {
await batcher.handleBatch(messages, 0)
await batcher.flush(1) // force the window out
- expect(puts).toHaveLength(3)
+ expect(puts).toHaveLength(4)
const labelPut = puts.find((put) => put.Key!.includes('kind=json_ld'))!
expect(labelPut.Key).toContain('session_start_date=2023-11-14')
const labels = await readRows(labelPut.Body)
- expect(labels).toHaveLength(1)
+ expect(labels).toHaveLength(2)
+ expect(labels[1].url ?? null).toBeNull()
expect(labels[0]).toMatchObject({
session_id: pseudonymize(SECRET, PSEUDONYM_SESSION, SESSION_A),
window_id: 'w1',
- event_index: 1,
+ event_index: 2,
full_snapshot_ts_ms: 1_700_000_000_001.5,
root_types: ['Product'],
+ url: 'https://example.com/[redacted]',
})
+ const snapshots = await readRows(puts.find((put) => put.Key!.includes('kind=full_snapshot'))!.Body)
+ expect(snapshots[0]).toMatchObject({ event_index: 1, url: 'https://example.com/[redacted]' })
+ const pages = await readRows(puts.find((put) => put.Key!.includes('kind=page'))!.Body)
+ expect(pages).toHaveLength(1)
+ expect(pages[0].event_index).toBe(0)
const rows = await readRows(puts.find((put) => put.Key!.startsWith('block-metadata/dt='))!.Body)
expect(rows).toHaveLength(2)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
index 9bf9c8d8c6b6..c74821ae0585 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
@@ -166,6 +166,7 @@ describe('ml-mirror-pipeline', () => {
timestamp: now.plus({ milliseconds: 1 }).toMillis(),
data: {
tag: '$json_ld',
+ href: 'https://example.com/private-name?email=private#secret',
payload: {
'@context': 'https://schema.org',
'@type': 'Product',
@@ -274,6 +275,7 @@ describe('ml-mirror-pipeline', () => {
expect(event.data.text).toBe('Hello **********')
expect(recordedEvents()[1][1].data).toEqual({
tag: '$json_ld',
+ href: 'https://example.com/[redacted]?[key]=private',
payload: {
'@context': 'https://schema.org',
'@type': 'Product',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts
index 83b714bd4fdb..cb883224f7fc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/replay-index.ts
@@ -1,6 +1,9 @@
import { ParquetSchema } from '@dsnp/parquetjs'
-import { ReplayIndexEntrySchema } from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'
+import {
+ ReplayIndexEntry,
+ ReplayIndexEntrySchema,
+} from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'
import { parquetRecordsToBuffer } from '~/ingestion/pipelines/sessionreplay/shared/parquet'
import { MlBlockMetadataRow } from './block-metadata-row'
@@ -46,6 +49,7 @@ export function replayIndexPartitions(rows: MlBlockMetadataRow[]): Map<string, R
continue
}
const date = new Date(started).toISOString().slice(0, 10)
+ const entries: ReplayIndexEntry[] = []
for (const value of row.replay_index_entries) {
const result = ReplayIndexEntrySchema.safeParse(value)
if (
@@ -57,7 +61,24 @@ export function replayIndexPartitions(rows: MlBlockMetadataRow[]): Map<string, R
MlParquetSinkMetrics.incReplayIndexSkipped('invalid_entry')
continue
}
- const entry = result.data
+ entries.push(result.data)
+ }
+ const pagesByEvent = new Map(
+ entries.filter((entry) => entry.kind === 'page').map((entry) => [entry.eventIndex, entry])
+ )
+ const nonPageEvents = new Set(entries.filter((entry) => entry.kind !== 'page').map((entry) => entry.eventIndex))
+ for (const entry of entries) {
+ if (entry.kind === 'page' && nonPageEvents.has(entry.eventIndex)) {
+ continue
+ }
+ const page =
+ pagesByEvent.get(entry.eventIndex) ??
+ (entry.kind === 'full_snapshot' ? pagesByEvent.get(entry.eventIndex - 1) : undefined)
+ const url =
+ entry.url ??
+ (page?.windowId === entry.windowId && page.eventTimestamp <= entry.eventTimestamp
+ ? page.url
+ : undefined)
const key = `kind=${entry.kind}/session_start_date=${date}`
let records = partitions.get(key)
if (!records) {
@@ -75,7 +96,7 @@ export function replayIndexPartitions(rows: MlBlockMetadataRow[]): Map<string, R
block_index_truncated: row.replay_index_truncated === true,
full_snapshot_ts_ms: entry.fullSnapshotTimestamp ?? null,
root_types: entry.rootTypes ?? [],
- url: entry.url ?? null,
+ url: url ?? null,
block_s3_key: row.block_s3_key,
block_byte_start: row.block_byte_start,
block_byte_end: row.block_byte_end,
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index a30e0ff2e2e4..b7ec1d79798d 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9332,7 +9332,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.6.0"
+version = "0.6.1"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 0c11d7db50fe..a5600c2670f1 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.6.0"
+version = "0.6.1"
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/event.rs b/rust/replay-anonymizer/src/event.rs
index 413205581d69..35989f701781 100644
--- a/rust/replay-anonymizer/src/event.rs
+++ b/rust/replay-anonymizer/src/event.rs
@@ -243,7 +243,19 @@ pub fn route_data(
}
Some(TYPE_CUSTOM) => match as_object_mut(data) {
Some(data) if data.get("tag").and_then(as_str) == Some(JSON_LD_EVENT_TAG) => {
- Ok(scrub_json_ld_payload(data))
+ let mut changed = scrub_json_ld_payload(data);
+ if let Some(href) = data.get("href") {
+ if let Some(href) = as_str(href) {
+ if let Some(scrubbed) = scrub_url(ctx, href) {
+ data.insert(key("href"), string_value(scrubbed));
+ changed = true;
+ }
+ } else {
+ data.remove("href");
+ changed = true;
+ }
+ }
+ Ok(changed)
}
Some(data) => Ok(scrub_generic_field(ctx, data, "payload")),
None => Ok(false),
diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rs
index 489bb0b5e1d0..76c2e178fec4 100644
--- a/rust/replay-anonymizer/tests/snapshot.rs
+++ b/rust/replay-anonymizer/tests/snapshot.rs
@@ -174,6 +174,43 @@ fn replay_index_metadata_tracks_snapshots_and_root_types() {
}
}
+#[test]
+fn json_ld_page_url_is_scrubbed_before_metadata_extraction() {
+ let allow = AllowLists::new(Vec::<String>::new(), ["products"]);
+ for (href, expected) in [
+ (
+ json!("https://user:[email protected]/products/private-name?email=private#secret"),
+ Some("https://example.com/products/[redacted]"),
+ ),
+ (
+ json!("https://example.com/products"),
+ Some("https://example.com/products"),
+ ),
+ (json!({"secret": "private"}), None),
+ (json!(42), None),
+ (Value::Null, None),
+ ] {
+ let inner = snapshot_message(json!([
+ {"type":5,"timestamp":TS0,"data":{"tag":"$json_ld","href":href,"payload":{"@context":"https://schema.org","@type":"Product"}}}
+ ]));
+ assert_stream_matches_tree(&allow, &inner.to_string(), "JSON-LD page URL");
+ let out = run(&allow, &payload_of(&inner)).unwrap();
+ assert_eq!(out.meta.events[0].href.as_deref(), expected);
+ let lines = parse_lines(&out.lines);
+ assert_eq!(
+ lines[0][1]["data"].get("href").and_then(Value::as_str),
+ expected
+ );
+ if expected.is_none() {
+ assert!(lines[0][1]["data"].get("href").is_none());
+ }
+ assert_eq!(
+ out.meta.events[0].json_ld.as_ref().unwrap().root_types,
+ ["Product"]
+ );
+ }
+}
+
#[test]
fn failure_classification_matches_the_ts_parse_step() {
let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());