: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
fix(session-replay): match policy wildcards in linear time (#87752)
Robbiefbd0da0bc83d
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.tsindex 4caa5263e0a5..42ef18c9c5b8 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@@ -8,6 +8,7 @@ import { ConfigurationCacheItem, ConfigurationFile, HttpCacheMetadata, configuraimport { ImageFetchRequestMetrics } from './metrics'import { canonicalizeUrl, politenessKey } from './politeness-key'import { WebBotAuthRequestSigner } from './web-bot-auth'+import { wildcardPatternMatchesPathname } from './wildcard-pattern'const BOT_NAME = 'PostHogImageFetcherBot'const USER_AGENT = `${BOT_NAME}/1.0 (+https://posthog.com/docs/ai-research/image-fetcher-bot)`@@ -518,7 +519,7 @@ function tdmrepRefuses(parsed: unknown, url: URL): boolean {if (!isObject(rule) || typeof rule.location !== 'string') {continue}- if (tdmLocationMatches(rule.location, url.pathname)) {+ if (wildcardPatternMatchesPathname(rule.location, url.pathname)) {return rule['tdm-reservation'] === 1}}@@ -563,26 +564,6 @@ function configurationRevision(item: ConfigurationCacheItem): string {return `${item.key}\0${item.fetchedAtMs}`}-function tdmLocationMatches(pattern: string, pathname: string): boolean {- const decodedPattern = decodeUnreserved(pattern)- const endAnchored = decodedPattern.endsWith('$')- const matchPattern = endAnchored ? decodedPattern.slice(0, -1) : decodedPattern- const escaped = matchPattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')- const source = endAnchored ? `${escaped}$` : `${escaped}.*`- try {- return new RegExp(`^${source}`).test(decodeUnreserved(pathname))- } catch {- return false- }-}--function decodeUnreserved(value: string): string {- return value.replace(/%[0-9A-Fa-f]{2}/g, (encoded) => {- const character = String.fromCharCode(Number.parseInt(encoded.slice(1), 16))- return /^[A-Za-z0-9._~-]$/.test(character) ? character : encoded.toUpperCase()- })-}-function isObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)}@@ -604,7 +585,7 @@ function contentUsageRefuses(values: string[]): boolean {function contentSignalRefuses(value: string, url: string): boolean {const trimmed = value.trim()const pathEnd = trimmed.startsWith('/') ? trimmed.search(/\s/) : -1- if (pathEnd > 0 && !tdmLocationMatches(trimmed.slice(0, pathEnd), new URL(url).pathname)) {+ if (pathEnd > 0 && !wildcardPatternMatchesPathname(trimmed.slice(0, pathEnd), new URL(url).pathname)) {return false}const preferences = (pathEnd > 0 ? trimmed.slice(pathEnd) : trimmed)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/wildcard-pattern.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/wildcard-pattern.test.tsnew file mode 100644index 000000000000..f33e8423d5e7--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/wildcard-pattern.test.ts@@ -0,0 +1,28 @@+import { wildcardPatternMatchesPathname } from './wildcard-pattern'++describe('wildcardPatternMatchesPathname', () => {+ it.each([+ ['a prefix', '/images/', '/images/photo.png', true],+ ['an exact path', '/images/photo.png$', '/images/photo.png', true],+ ['an exact path mismatch', '/images/photo.png$', '/images/photo.png/preview', false],+ ['a middle wildcard', '/images/*/preview$', '/images/v1/preview', true],+ ['an anchored suffix mismatch', '/images/*/preview$', '/images/v1/preview/more', false],+ ['a leading wildcard', '*/private/*', '/v1/private/image.png', true],+ ['literal regular expression characters', '/literal.+(item)$', '/literal.+(item)', true],+ ['an unreserved percent encoding', '/asset%7Ename$', '/asset~name', true],+ ['consecutive wildcards', '/asset/**/preview$', '/asset//preview', true],+ ['overlapping anchored segments', '*a*a$', '/aaa', true],+ ])('matches %s', (_name, pattern, pathname, expected) => {+ expect(wildcardPatternMatchesPathname(pattern, pathname)).toBe(expected)+ })++ it('does not compile wildcard patterns as regular expressions', () => {+ const regexpConstructor = jest.spyOn(globalThis, 'RegExp').mockReturnValue(/$a/)+ try {+ expect(wildcardPatternMatchesPathname(`${'*a'.repeat(64)}*b$`, `/${'a'.repeat(128)}c`)).toBe(false)+ expect(regexpConstructor).not.toHaveBeenCalled()+ } finally {+ regexpConstructor.mockRestore()+ }+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/wildcard-pattern.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/wildcard-pattern.tsnew file mode 100644index 000000000000..460f5d984695--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/wildcard-pattern.ts@@ -0,0 +1,86 @@+export function wildcardPatternMatchesPathname(pattern: string, pathname: string): boolean {+ const decodedPattern = decodeUnreserved(pattern)+ const endAnchored = decodedPattern.endsWith('$')+ const matchPattern = endAnchored ? decodedPattern.slice(0, -1) : decodedPattern+ const decodedPathname = decodeUnreserved(pathname)++ if (!matchPattern.includes('*')) {+ return endAnchored ? decodedPathname === matchPattern : decodedPathname.startsWith(matchPattern)+ }++ const literalSegments = matchPattern.split('*').filter(Boolean)+ if (literalSegments.length === 0) {+ return true+ }++ let nextSearchIndex = 0+ let nextSegmentIndex = 0+ if (!matchPattern.startsWith('*')) {+ const firstSegment = literalSegments[0]+ if (!decodedPathname.startsWith(firstSegment)) {+ return false+ }+ nextSearchIndex = firstSegment.length+ nextSegmentIndex = 1+ }++ let segmentSearchEnd = literalSegments.length+ let pathnameSearchEnd = decodedPathname.length+ if (endAnchored && !matchPattern.endsWith('*')) {+ const finalSegmentIndex = literalSegments.length - 1+ const finalSegment = literalSegments[finalSegmentIndex]+ if (!decodedPathname.endsWith(finalSegment)) {+ return false+ }+ segmentSearchEnd = finalSegmentIndex+ pathnameSearchEnd = decodedPathname.length - finalSegment.length+ }++ for (; nextSegmentIndex < segmentSearchEnd; nextSegmentIndex++) {+ const segment = literalSegments[nextSegmentIndex]+ const matchIndex = findLiteralSegment(decodedPathname, segment, nextSearchIndex, pathnameSearchEnd)+ if (matchIndex === -1) {+ return false+ }+ nextSearchIndex = matchIndex + segment.length+ }++ return nextSearchIndex <= pathnameSearchEnd+}++function findLiteralSegment(value: string, segment: string, startIndex: number, endIndex: number): number {+ const prefixLengths = buildPrefixLengths(segment)+ for (let index = startIndex, matchedLength = 0; index < endIndex; index++) {+ while (matchedLength > 0 && value[index] !== segment[matchedLength]) {+ matchedLength = prefixLengths[matchedLength - 1]+ }+ if (value[index] === segment[matchedLength]) {+ matchedLength+++ }+ if (matchedLength === segment.length) {+ return index - segment.length + 1+ }+ }+ return -1+}++function buildPrefixLengths(value: string): number[] {+ const prefixLengths = Array<number>(value.length).fill(0)+ for (let index = 1, matchedLength = 0; index < value.length; index++) {+ while (matchedLength > 0 && value[index] !== value[matchedLength]) {+ matchedLength = prefixLengths[matchedLength - 1]+ }+ if (value[index] === value[matchedLength]) {+ matchedLength+++ }+ prefixLengths[index] = matchedLength+ }+ return prefixLengths+}++function decodeUnreserved(value: string): string {+ return value.replace(/%[0-9A-Fa-f]{2}/g, (encoded) => {+ const character = String.fromCharCode(Number.parseInt(encoded.slice(1), 16))+ return /^[A-Za-z0-9._~-]$/.test(character) ? character : encoded.toUpperCase()+ })+}