Skip to content

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

fix(ai-research): treat a non-array tdmrep.json body as absent (#110719)

Robbie9f2f7fca93e4
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.md
index 5dec0a29d88f..76eaf1b886e6 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
@@ -173,9 +173,9 @@ XMP is an opt-out for that image when it has one of these values:
**3.12** TDMRep does not specify a maximum size for tdmrep.json. The lane refuses a tdmrep.json file larger than 500KiB. It treats this result as unreachable.
-**3.13** The lane parses and applies tdmrep.json according to the [TDMRep Community Group Final Report](https://www.w3.org/community/reports/tdmrep/CG-FINAL-tdmrep-20240510/). A matching reservation of `1` refuses the URL.
+**3.13** The lane parses and applies tdmrep.json according to the [TDMRep Community Group Final Report](https://www.w3.org/community/reports/tdmrep/CG-FINAL-tdmrep-20240510/). The first rule whose `location` matches the URL path applies. A reservation of `1`, `"1"`, or `true` in that rule refuses the URL. [TDMRep section 5.1](https://www.w3.org/community/reports/tdmrep/CG-FINAL-tdmrep-20240510/#sec-tdm-reservation) reads `"1"` and `true` as protocol errors, which mean no reservation. The lane reads them as a reservation, because a site that writes them intends to reserve. Any other value is no reservation.
-**3.14** A 404 or a 410 while fetching robots.txt or tdmrep.json means the origin does not have that file
+**3.14** A 404 or a 410 while fetching robots.txt or tdmrep.json means the origin does not have that file. A 200 for tdmrep.json also means the origin does not have that file when the body cannot start a JSON array. This is the case when the first byte after an optional UTF-8 byte order mark and JSON whitespace is not `[`. Examples are an HTML page, an empty body, and a JSON object. [TDMRep section 6.1](https://www.w3.org/community/reports/tdmrep/CG-FINAL-tdmrep-20240510/#sec-tdm-file) says that a server that does not return a machine-readable representation does not implement the protocol. The lane makes this check before requirements 3.12 and 3.23, so an oversized or non-UTF-8 HTML page also means that the file is absent. If the 500KiB prefix contains only a byte order mark and whitespace, requirement 3.12 applies, because the `[` can come after the prefix. If the cache holds an available tdmrep.json for the origin, the lane keeps that file as requirement 3.19 describes, and does not record an absence. A server can return an HTML error page with a 200 for a short time, and this rule keeps a cached reservation during that time. A body that starts with `[` but is not a valid JSON array makes tdmrep.json unreachable, because it can be a damaged reservation.
**3.15** No robots.txt or tdmrep.json means that no restrictions on fetching are applied by that file (there might be signals from other sources)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
index 3af346ed1042..ae63e66e7887 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
@@ -316,6 +316,53 @@ describe('ConfigurationPolicyService', () => {
})
})
+ it.each([
+ ['1', true],
+ [true, true],
+ [0, false],
+ ])('reads a TDMRep reservation of %p as %p', async (reservation, tdmrepReservation) => {
+ const { policy } = service()
+ const cache = new Map([
+ [configurationCacheKey(ORIGIN, 'robots'), cached('robots', 'absent')],
+ [
+ configurationCacheKey(ORIGIN, 'tdmrep'),
+ cached('tdmrep', 'available', JSON.stringify([{ location: '/', 'tdm-reservation': reservation }])),
+ ],
+ ])
+
+ await expect(policy.check(`${ORIGIN}/image.png`, cache, NOW_MS)).resolves.toMatchObject({
+ allowed: true,
+ tdmrepReservation,
+ })
+ })
+
+ it.each([
+ {
+ description: 'keeps a cached TDMRep file',
+ cachedTdmrep: [
+ [
+ configurationCacheKey(ORIGIN, 'tdmrep'),
+ {
+ ...cached('tdmrep', 'available', JSON.stringify([{ location: '/', 'tdm-reservation': 1 }])),
+ refreshAtMs: NOW_MS - 1,
+ },
+ ] as const,
+ ],
+ status: 'available',
+ tdmrepReservation: true,
+ },
+ { description: 'records an absent TDMRep file', cachedTdmrep: [], status: 'absent', tdmrepReservation: false },
+ ])('$description when a refresh returns a non-array body', async ({ cachedTdmrep, status, tdmrepReservation }) => {
+ const { policy } = service({ tdmrep: { outcome: 'absent', nonArrayBody: true } })
+ const cache = new Map([[configurationCacheKey(ORIGIN, 'robots'), cached('robots', 'absent')], ...cachedTdmrep])
+
+ await expect(policy.check(`${ORIGIN}/image.png`, cache, NOW_MS)).resolves.toMatchObject({
+ allowed: true,
+ tdmrepReservation,
+ updates: [expect.objectContaining({ kind: 'tdmrep', status })],
+ })
+ })
+
it('keeps a previous usable file when its refresh is unreachable', async () => {
const { policy } = service({ robots: { outcome: 'unreachable' } })
const previous = { ...cached('robots', 'absent'), refreshAtMs: NOW_MS - 1 }
@@ -419,26 +466,85 @@ describe('HttpConfigurationFetcher', () => {
await expect(httpFetcher().fetch(ORIGIN, 'robots')).resolves.toMatchObject({ outcome: 'unreachable' })
})
- it('treats an oversized or invalid TDMRep document as unreachable', async () => {
- fetchStreamedMock
- .mockResolvedValueOnce(response(200, [], { bytes: Buffer.from('[]'), overLimit: true }))
- .mockResolvedValueOnce(response(200, [], { bytes: Buffer.from('{invalid'), overLimit: false }))
+ it.each([
+ {
+ description: 'a string reservation',
+ bytes: Buffer.from('[{"location": "/", "tdm-reservation": "1"}]'),
+ overLimit: false,
+ result: { outcome: 'available' },
+ reason: 'available',
+ },
+ {
+ description: 'a byte order mark and leading whitespace',
+ bytes: Buffer.from('\uFEFF\n []'),
+ overLimit: false,
+ result: { outcome: 'available' },
+ reason: 'available',
+ },
+ {
+ description: 'a damaged array',
+ bytes: Buffer.from('[{"location": "/",'),
+ overLimit: false,
+ result: { outcome: 'unreachable' },
+ reason: 'invalid_document',
+ },
+ {
+ description: 'an oversized array',
+ bytes: Buffer.from('[]'),
+ overLimit: true,
+ result: { outcome: 'unreachable' },
+ reason: 'body_limit',
+ },
+ {
+ description: 'an oversized whitespace prefix',
+ bytes: Buffer.from('\uFEFF \n\t '),
+ overLimit: true,
+ result: { outcome: 'unreachable' },
+ reason: 'body_limit',
+ },
+ {
+ description: 'an empty body',
+ bytes: Buffer.alloc(0),
+ overLimit: false,
+ result: { outcome: 'absent', nonArrayBody: true },
+ reason: 'not_json_array',
+ },
+ {
+ description: 'an HTML page',
+ bytes: Buffer.from('<!doctype html><title>Home</title>'),
+ overLimit: false,
+ result: { outcome: 'absent', nonArrayBody: true },
+ reason: 'not_json_array',
+ },
+ {
+ description: 'a JSON object',
+ bytes: Buffer.from('{"error": "not found"}'),
+ overLimit: false,
+ result: { outcome: 'absent', nonArrayBody: true },
+ reason: 'not_json_array',
+ },
+ {
+ description: 'an oversized HTML page',
+ bytes: Buffer.from('<!doctype html>'),
+ overLimit: true,
+ result: { outcome: 'absent', nonArrayBody: true },
+ reason: 'not_json_array',
+ },
+ {
+ description: 'a Latin-1 HTML page',
+ bytes: Buffer.from('<p>caf\u00e9</p>', 'latin1'),
+ overLimit: false,
+ result: { outcome: 'absent', nonArrayBody: true },
+ reason: 'not_json_array',
+ },
+ ])('maps a TDMRep body with $description to $result.outcome', async ({ bytes, overLimit, result, reason }) => {
+ fetchStreamedMock.mockResolvedValue(response(200, [], { bytes, overLimit }))
- await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toMatchObject({ outcome: 'unreachable' })
- await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toMatchObject({ outcome: 'unreachable' })
+ await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toEqual(expect.objectContaining(result))
const fetches = await register.getSingleMetric('ml_image_fetch_configuration_fetches_total')!.get()
- expect(fetches.values).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- labels: { file: 'tdmrep', outcome: 'unreachable', reason: 'body_limit' },
- value: 1,
- }),
- expect.objectContaining({
- labels: { file: 'tdmrep', outcome: 'unreachable', reason: 'invalid_document' },
- value: 1,
- }),
- ])
- )
+ expect(fetches.values).toEqual([
+ expect.objectContaining({ labels: { file: 'tdmrep', outcome: result.outcome, reason }, value: 1 }),
+ ])
})
it('treats repeated Location field lines as unreachable', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
index 337a719fe22a..05e1a667a051 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
@@ -20,10 +20,14 @@ const CONFIG_REFRESH_MS = 23 * 60 * 60 * 1000
const CONFIG_RETRY_MS = 60 * 60 * 1000
const CONFIG_STORAGE_MS = 30 * 24 * 60 * 60 * 1000
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
+const UTF8_BYTE_ORDER_MARK = [0xef, 0xbb, 0xbf]
+const JSON_WHITESPACE_BYTES = new Set([' ', '\t', '\n', '\r'].map((character) => character.charCodeAt(0)))
+const JSON_ARRAY_START_BYTE = '['.charCodeAt(0)
export type ConfigurationFetchResult =
| { outcome: 'available'; body: string; cache: HttpCacheMetadata }
- | { outcome: 'absent' | 'refused' | 'unreachable'; cache?: HttpCacheMetadata }
+ | { outcome: 'absent'; cache?: HttpCacheMetadata; nonArrayBody?: boolean }
+ | { outcome: 'refused' | 'unreachable'; cache?: HttpCacheMetadata }
| { outcome: 'deferred'; reason: ConfigurationRequestBlockReason }
export type ConfigurationRequestBlockReason =
@@ -176,6 +180,14 @@ export class HttpConfigurationFetcher {
return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'unexpected_status' })
}
const body = await response.read(CONFIG_BODY_LIMIT)
+ // This check comes before the size and UTF-8 checks, so that an oversized or non-UTF-8 HTML page also means that the origin has no tdmrep.json (README 3.14).
+ if (file === 'tdmrep' && cannotBeJsonArray(body)) {
+ return complete({
+ kind: 'done',
+ result: { outcome: 'absent', cache, nonArrayBody: true },
+ reason: 'not_json_array',
+ })
+ }
if (body.overLimit && file === 'tdmrep') {
return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'body_limit' })
}
@@ -185,7 +197,7 @@ export class HttpConfigurationFetcher {
} catch {
return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'invalid_utf8' })
}
- if (file === 'tdmrep' && !isValidTdmrepDocument(text)) {
+ if (file === 'tdmrep' && !Array.isArray(parseTdmrepDocument(text))) {
return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'invalid_document' })
}
return complete({ kind: 'done', result: { outcome: 'available', body: text, cache } })
@@ -357,7 +369,13 @@ export class ConfigurationPolicyService {
deferredReason: fetched.reason,
}
}
- if (fetched.outcome === 'unreachable' && previous && previous.status !== 'unreachable') {
+ const nonArrayBodyReplacesFile =
+ fetched.outcome === 'absent' && fetched.nonArrayBody === true && previous?.status === 'available'
+ if (
+ (fetched.outcome === 'unreachable' || nonArrayBodyReplacesFile) &&
+ previous &&
+ previous.status !== 'unreachable'
+ ) {
const retained = {
...previous,
refreshAtMs: nowMs + CONFIG_RETRY_MS,
@@ -549,23 +567,35 @@ function tdmrepRefuses(parsed: unknown, url: URL): boolean {
continue
}
if (wildcardPatternMatchesPathname(rule.location, url.pathname)) {
- return rule['tdm-reservation'] === 1
+ return isTdmReservation(rule['tdm-reservation'])
}
}
return false
}
-function isValidTdmrepDocument(body: string): boolean {
- const parsed = parseTdmrepDocument(body)
- return (
- Array.isArray(parsed) &&
- parsed.every(
- (rule) =>
- isObject(rule) &&
- typeof rule.location === 'string' &&
- (rule['tdm-reservation'] === 0 || rule['tdm-reservation'] === 1)
- )
- )
+function isTdmReservation(value: unknown): boolean {
+ // TDMRep reads "1" and true as protocol errors, which mean no reservation. README 3.13 reads them as a reservation, because a site that writes them intends to reserve.
+ return value === 1 || value === '1' || value === true
+}
+
+function cannotBeJsonArray(body: { bytes: Uint8Array; overLimit: boolean }): boolean {
+ const firstByte = firstByteAfterJsonWhitespace(body.bytes)
+ if (firstByte === undefined) {
+ return !body.overLimit
+ }
+ return firstByte !== JSON_ARRAY_START_BYTE
+}
+
+function firstByteAfterJsonWhitespace(bytes: Uint8Array): number | undefined {
+ let index = hasUtf8ByteOrderMark(bytes) ? UTF8_BYTE_ORDER_MARK.length : 0
+ while (index < bytes.length && JSON_WHITESPACE_BYTES.has(bytes[index])) {
+ index++
+ }
+ return index < bytes.length ? bytes[index] : undefined
+}
+
+function hasUtf8ByteOrderMark(bytes: Uint8Array): boolean {
+ return UTF8_BYTE_ORDER_MARK.every((byte, index) => bytes[index] === byte)
}
async function parsedRobotsConfiguration(
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts
index 0f7827ba7a78..1e8a2f85758f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts
@@ -42,6 +42,7 @@ export type ConfigurationFetchReason =
| 'body_limit'
| 'invalid_utf8'
| 'invalid_document'
+ | 'not_json_array'
export class ImageFetchProcessingMetrics {
private static readonly active = new Map<ProcessingStage, Map<symbol, number>>()