: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(web-analytics): clean pathnames in the livestream service (#87294)
Lucas Ricoy8c7a5c7b3788
diff --git a/livestream/README.md b/livestream/README.mdindex 4407bdcf7ba1..ebd9d13155dd 100644--- a/livestream/README.md+++ b/livestream/README.md@@ -19,6 +19,13 @@ Hog 3000 powers live event stream on PostHog: https://us.posthog.com/project/0/a- `property` - repeatable; each value is `key=value` for exact-matchfiltering on top-level event properties. Multiple params with the samekey OR together, different keys AND together.+ - `pathCleaning` - JSON array of `{"alias", "regex"}` path cleaning rules+ (the team's `path_cleaning_filters`). Each streamed event carrying a+ `$pathname` gains a `$virt_cleaned_pathname` property with the rules+ applied in list order using RE2 semantics. Entries that are malformed,+ fail to compile, or exceed per-rule size limits are skipped individually;+ a ruleset of more than 100 rules is ignored entirely, so subscribers can+ fall back to cleaning client-side with the full set.- `/debug` - dummy html for SSE testing,- `/debug/sse/` - backend for `/debug` generating a server side events,- `/metrics` - exposes metrics in Prometheus formatdiff --git a/livestream/events/filter.go b/livestream/events/filter.goindex bd08059b221e..669a91463764 100644--- a/livestream/events/filter.go+++ b/livestream/events/filter.go@@ -83,6 +83,9 @@ type Subscription struct {Geo boolColumns []string+ // Transformations+ PathCleaner *PathCleaner+// ChannelsEventChan chan interface{}ShouldClose *atomic.Bool@@ -131,10 +134,23 @@ func convertToResponseGeoEvent(event PostHogEvent) *ResponseGeoEvent {}}-func convertToResponsePostHogEvent(event PostHogEvent, teamId int, columns []string) *ResponsePostHogEvent {+func convertToResponsePostHogEvent(+ event PostHogEvent,+ teamId int,+ columns []string,+ pathCleaner *PathCleaner,+) *ResponsePostHogEvent {var properties map[string]interface{}if columns == nil {properties = event.Properties+ if pathCleaner != nil {+ // About to inject a per-subscriber property; copy so the shared+ // event map never carries one subscription's cleaning into another.+ properties = make(map[string]interface{}, len(event.Properties)+1)+ for k, v := range event.Properties {+ properties[k] = v+ }+ }} else {properties = make(map[string]interface{})for _, key := range columns {@@ -152,6 +168,12 @@ func convertToResponsePostHogEvent(event PostHogEvent, teamId int, columns []str}}+ if pathCleaner != nil {+ if pathname, ok := event.Properties["$pathname"].(string); ok {+ properties["$virt_cleaned_pathname"] = pathCleaner.Clean(pathname)+ }+ }+return &ResponsePostHogEvent{Uuid: event.Uuid,Timestamp: event.Timestamp,@@ -356,7 +378,7 @@ func deliverEvent(event PostHogEvent, subs []Subscription) {}}} else {- responseEvent := convertToResponsePostHogEvent(event, sub.TeamId, sub.Columns)+ responseEvent := convertToResponsePostHogEvent(event, sub.TeamId, sub.Columns, sub.PathCleaner)select {case sub.EventChan <- *responseEvent:diff --git a/livestream/events/filter_test.go b/livestream/events/filter_test.goindex 31a7a69ba07b..362bc37a588e 100644--- a/livestream/events/filter_test.go+++ b/livestream/events/filter_test.go@@ -76,7 +76,7 @@ func TestConvertToResponsePostHogEvent(t *testing.T) {Properties: map[string]interface{}{"url": "https://example.com"},}- result := convertToResponsePostHogEvent(event, 1, nil)+ result := convertToResponsePostHogEvent(event, 1, nil, nil)assert.Equal(t, "123", result.Uuid)assert.Equal(t, "2023-01-01T00:00:00Z", result.Timestamp)@@ -693,7 +693,7 @@ func TestIncludeProperties_NilIncludesAllProperties(t *testing.T) {Properties: properties,}- result := convertToResponsePostHogEvent(event, 1, nil)+ result := convertToResponsePostHogEvent(event, 1, nil, nil)assert.Equal(t, properties, result.Properties)}@@ -710,7 +710,7 @@ func TestIncludeProperties_EmptySliceIncludesNoProperties(t *testing.T) {},}- result := convertToResponsePostHogEvent(event, 1, []string{})+ result := convertToResponsePostHogEvent(event, 1, []string{}, nil)assert.Equal(t, map[string]interface{}{}, result.Properties)}@@ -728,7 +728,7 @@ func TestIncludeProperties_SpecificPropertiesFiltersCorrectly(t *testing.T) {},}- result := convertToResponsePostHogEvent(event, 1, []string{"url", "$device_type"})+ result := convertToResponsePostHogEvent(event, 1, []string{"url", "$device_type"}, nil)assert.Equal(t, map[string]interface{}{"url": "https://example.com",@@ -747,7 +747,7 @@ func TestIncludeProperties_NonExistentPropertiesAreIgnored(t *testing.T) {},}- result := convertToResponsePostHogEvent(event, 1, []string{"url", "nonexistent"})+ result := convertToResponsePostHogEvent(event, 1, []string{"url", "nonexistent"}, nil)assert.Equal(t, map[string]interface{}{"url": "https://example.com",diff --git a/livestream/events/path_cleaner.go b/livestream/events/path_cleaner.gonew file mode 100644index 000000000000..b7d68e494dc2--- /dev/null+++ b/livestream/events/path_cleaner.go@@ -0,0 +1,188 @@+package events++import (+ "encoding/json"+ "log"+ "regexp"+ "strings"+)++// Bounds on subscriber-supplied rules, so one subscription can't compile+// unbounded regex work into the event fan-out loop.+const (+ maxPathCleaningRules = 100+ maxPathCleaningRegexLen = 1000+ maxPathCleaningAliasLen = 1000+ // Sizing a replacement walks every capture group of every match+ // (replacementOverflows), so a rule packed with hundreds of empty groups+ // could allocate tens of megabytes of match indexes per event. Aliases can+ // only reference groups 1-9, so this cap costs real rules nothing.+ maxPathCleaningCaptureGroups = 30+ // Ceiling on the working path while cleaning. A rule can amplify output (a+ // `(.) -> \1\1` rule doubles the string) and rules chain each fed the+ // previous output, so N of them grow it 2^N. Bailing once the path passes a+ // size no real $pathname reaches keeps one subscription from exhausting+ // memory/CPU in the shared fan-out loop.+ maxCleanedPathLen = 8 * 1024+)++type pathCleaningRule struct {+ regex *regexp.Regexp+ replacement string+}++// PathCleaner applies a team's path cleaning rules the way ClickHouse's+// chained replaceRegexpAll calls do: every rule in list order, each fed the+// previous rule's output. Go's regexp is RE2, the same engine ClickHouse+// uses, so results match the query-side cleaning exactly.+type PathCleaner struct {+ rules []pathCleaningRule+}++// NewPathCleanerFromJSON parses a JSON array of {alias, regex} rules, the wire+// shape of team.path_cleaning_filters (the array is already ordered; other+// fields are ignored). Returns nil when there is nothing to apply. Rules that+// don't compile are skipped, matching how the query side skips rules that fail+// validation.+func NewPathCleanerFromJSON(rawJSON string) *PathCleaner {+ rawJSON = strings.TrimSpace(rawJSON)+ if rawJSON == "" {+ return nil+ }+ var elements []json.RawMessage+ if err := json.Unmarshal([]byte(rawJSON), &elements); err != nil {+ log.Printf("WARNING: ignoring unparseable pathCleaning rules: %v", err)+ return nil+ }+ // Applying only a prefix of the ruleset would group paths differently from+ // the query side, so past the cap emit nothing and let the frontend fall+ // back to cleaning with the full ruleset.+ if len(elements) > maxPathCleaningRules {+ log.Printf("WARNING: ignoring pathCleaning rules: %d exceeds the cap of %d", len(elements), maxPathCleaningRules)+ return nil+ }++ rules := make([]pathCleaningRule, 0, len(elements))+ for _, element := range elements {+ var p struct {+ Alias string `json:"alias"`+ Regex string `json:"regex"`+ }+ // Stored rulesets may contain malformed legacy entries; Django skips+ // each invalid element individually, so one bad entry must not disable+ // the valid rules around it.+ if err := json.Unmarshal(element, &p); err != nil {+ continue+ }+ if p.Regex == "" || len(p.Regex) > maxPathCleaningRegexLen {+ continue+ }+ // A long alias packed with backreferences amplifies each match, so cap+ // it alongside the regex. Without this a single rule could still blow the+ // path up in one pass.+ if len(p.Alias) > maxPathCleaningAliasLen {+ continue+ }+ re, err := regexp.Compile(p.Regex)+ if err != nil {+ log.Printf("WARNING: ignoring invalid path cleaning regex %q: %v", p.Regex, err)+ continue+ }+ if re.NumSubexp() > maxPathCleaningCaptureGroups {+ continue+ }+ rules = append(rules, pathCleaningRule{regex: re, replacement: translateAlias(p.Alias)})+ }+ if len(rules) == 0 {+ return nil+ }+ return &PathCleaner{rules: rules}+}++func (pc *PathCleaner) Clean(path string) string {+ // Cleaning is best-effort normalization: if the raw path already exceeds the+ // ceiling, or a rule amplifies it past one, abandon cleaning and return the+ // raw path rather than let an abusive ruleset grow it unbounded. Bounding each+ // rule's output also caps the next rule's input, so the chain can't compound.+ if len(path) > maxCleanedPathLen {+ return path+ }+ cleaned := path+ for _, rule := range pc.rules {+ // Size the result from the match and group lengths before running the+ // replacement, so a rule that would amplify the path bails here instead of+ // letting ReplaceAllString allocate the whole blown-up string first. The+ // replacement itself stays stdlib, so cleaned output matches the query side+ // exactly.+ if replacementOverflows(rule.regex, rule.replacement, cleaned) {+ return path+ }+ cleaned = rule.regex.ReplaceAllString(cleaned, rule.replacement)+ }+ return cleaned+}++// replacementOverflows reports whether applying the rule to src would produce+// more than maxCleanedPathLen bytes, computed from match offsets and group+// lengths without building the (possibly amplified) result. `replacement` is+// translateAlias output: `${0}`-`${9}` backreferences, `$$` for a literal `$`,+// everything else literal — so the byte count matches what ReplaceAllString+// would emit.+func replacementOverflows(re *regexp.Regexp, replacement, src string) bool {+ total := 0+ last := 0+ for _, m := range re.FindAllStringSubmatchIndex(src, -1) {+ total += m[0] - last+ last = m[1]+ for i := 0; i < len(replacement); i++ {+ c := replacement[i]+ if c == '$' && i+1 < len(replacement) {+ if replacement[i+1] == '$' {+ total+++ i+++ continue+ }+ if replacement[i+1] == '{' && i+3 < len(replacement) &&+ replacement[i+2] >= '0' && replacement[i+2] <= '9' && replacement[i+3] == '}' {+ if g := int(replacement[i+2] - '0'); 2*g+1 < len(m) && m[2*g] >= 0 {+ total += m[2*g+1] - m[2*g]+ }+ i += 3+ continue+ }+ }+ total+++ }+ if total > maxCleanedPathLen {+ return true+ }+ }+ return total+(len(src)-last) > maxCleanedPathLen+}++// translateAlias converts a replaceRegexpAll replacement string (`\0`-`\9`+// backreferences, `\\` literal backslash, everything else literal) into Go's+// ReplaceAllString syntax. Backreferences become `${N}` rather than `$N` so a+// digit following the reference stays literal, and literal `$` becomes `$$`+// so Go never reads it as an expansion.+func translateAlias(alias string) string {+ var b strings.Builder+ for i := 0; i < len(alias); i++ {+ ch := alias[i]+ switch {+ case ch == '\\' && i+1 < len(alias) && alias[i+1] == '\\':+ b.WriteByte('\\')+ i+++ case ch == '\\' && i+1 < len(alias) && alias[i+1] >= '0' && alias[i+1] <= '9':+ b.WriteString("${")+ b.WriteByte(alias[i+1])+ b.WriteByte('}')+ i+++ case ch == '$':+ b.WriteString("$$")+ default:+ b.WriteByte(ch)+ }+ }+ return b.String()+}diff --git a/livestream/events/path_cleaner_test.go b/livestream/events/path_cleaner_test.gonew file mode 100644index 000000000000..118f813cc5a9--- /dev/null+++ b/livestream/events/path_cleaner_test.go@@ -0,0 +1,201 @@+package events++import (+ "fmt"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestPathCleanerClean(t *testing.T) {+ tests := []struct {+ name string+ rules string+ path string+ want string+ }{+ {+ name: "id segment collapses to alias",+ rules: `[{"alias": "/classes/:id", "regex": "/classes/[^/]+"}]`,+ path: "/classes/928q3hr9paw8hfe",+ want: "/classes/:id",+ },+ {+ name: "backreference expands the captured group",+ rules: `[{"alias": "/item/\\1", "regex": "/item/(\\d+)-.*"}]`,+ path: "/item/42-blue-widget",+ want: "/item/42",+ },+ {+ name: "digit after a backreference stays literal, not group 10",+ rules: `[{"alias": "/v\\10/x", "regex": "/version/(\\d)"}]`,+ path: "/version/7",+ want: "/v70/x",+ },+ {+ name: "dollar sign in alias stays literal",+ rules: `[{"alias": "/$price", "regex": "/cost/.*"}]`,+ path: "/cost/123",+ want: "/$price",+ },+ {+ name: "escaped backslash in alias is one literal backslash",+ rules: `[{"alias": "/a\\\\b", "regex": "/raw/.*"}]`,+ path: "/raw/x",+ want: `/a\b`,+ },+ {+ name: "rules chain in list order, each fed the previous output",+ rules: `[{"alias": "/classes/:id", "regex": "/classes/[^/]+"}, {"alias": "/c/:id", "regex": "/classes/:id"}]`,+ path: "/classes/abc123",+ want: "/c/:id",+ },+ {+ name: "invalid regex is skipped, later rules still apply",+ rules: `[{"alias": "x", "regex": "("}, {"alias": "/classes/:id", "regex": "/classes/[^/]+"}]`,+ path: "/classes/abc123",+ want: "/classes/:id",+ },+ {+ name: "malformed legacy entry is skipped, later rules still apply",+ rules: `["legacy", {"alias": "/users/:id", "regex": "/users/\\d+"}]`,+ path: "/users/42",+ want: "/users/:id",+ },+ {+ name: "inline re2 flags work",+ rules: `[{"alias": "/docs", "regex": "(?i)/DOCS/.*"}]`,+ path: "/docs/setup",+ want: "/docs",+ },+ {+ name: "missing alias replaces with empty string",+ rules: `[{"regex": "/classes/[^/]+"}]`,+ path: "/classes/abc123",+ want: "",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ cleaner := NewPathCleanerFromJSON(tt.rules)+ require.NotNil(t, cleaner)+ assert.Equal(t, tt.want, cleaner.Clean(tt.path))+ })+ }+}++func TestNewPathCleanerFromJSONReturnsNilWhenNothingApplies(t *testing.T) {+ // Truncating past the cap would clean with a prefix of the ruleset and+ // group paths differently from the backfill query, so it must be all or+ // nothing: the frontend falls back to full client-side cleaning on nil.+ tooManyRules := "[" + strings.Repeat(`{"alias": "/x", "regex": "/x/.*"},`, maxPathCleaningRules) + `{"alias": "/x", "regex": "/x/.*"}]`+ for name, raw := range map[string]string{+ "empty string": "",+ "whitespace": " ",+ "not json": "not-json",+ "empty array": "[]",+ "only invalid rules": `[{"alias": "x", "regex": "("}, {"alias": "y", "regex": ""}]`,+ "more rules than cap": tooManyRules,+ } {+ t.Run(name, func(t *testing.T) {+ assert.Nil(t, NewPathCleanerFromJSON(raw))+ })+ }+}++func TestPathCleanerSkipsCaptureGroupBomb(t *testing.T) {+ // Sizing a replacement materializes indexes for every capture group per+ // match, so a rule stuffed with empty groups forces large allocations per+ // event. Such a rule is dropped at compile time; the valid rule still applies.+ bomb := strings.Repeat("()", maxPathCleaningCaptureGroups+1)+ rules := fmt.Sprintf(`[{"alias": "x", "regex": %q}, {"alias": "/b", "regex": "/a/.*"}]`, bomb)+ cleaner := NewPathCleanerFromJSON(rules)+ require.NotNil(t, cleaner)++ assert.Equal(t, "/b", cleaner.Clean("/a/123"))+}++func TestPathCleanerBoundsOutputAmplification(t *testing.T) {+ // A `(.) -> \1\1` rule doubles the path, and rules chain each fed the+ // previous output, so enough of them would grow a short path past any memory+ // limit. Cleaning must bail and return the raw path instead of amplifying+ // unbounded in the shared fan-out loop. Without the size cap this Clean call+ // allocates gigabytes and never returns.+ // 14 doublings of a 4-char path cross the ceiling at rule 12, so cleaning+ // bails there. Kept just past the bail point: if the cap regresses, the+ // fallback is a 64 KiB string that fails the assert cleanly, not a multi-+ // terabyte allocation that OOMs the runner.+ doubling := `{"alias": "\\1\\1", "regex": "(.)"}`+ rules := "[" + strings.Repeat(doubling+",", 13) + doubling + "]"+ cleaner := NewPathCleanerFromJSON(rules)+ require.NotNil(t, cleaner)++ path := "/abc"+ got := cleaner.Clean(path)+ assert.Equal(t, path, got, "amplifying ruleset must fall back to the raw path")+ assert.LessOrEqual(t, len(got), maxCleanedPathLen)+}++func TestPathCleanerBoundsSingleRuleAmplification(t *testing.T) {+ // One rule whose replacement repeats a full-input capture many times would, under a+ // plain ReplaceAllString, allocate a multi-megabyte string before any size check.+ // Cleaning must size the result up front and fall back to the raw path instead.+ alias := strings.Repeat(`\1`, 400)+ rules := fmt.Sprintf(`[{"alias": %q, "regex": "(.*)"}]`, alias)+ cleaner := NewPathCleanerFromJSON(rules)+ require.NotNil(t, cleaner)++ path := "/" + strings.Repeat("a", 4000)+ got := cleaner.Clean(path)+ assert.Equal(t, path, got, "amplifying single rule must fall back to the raw path")+ assert.LessOrEqual(t, len(got), maxCleanedPathLen)+}++func TestPathCleanerReturnsOversizedInputUnchanged(t *testing.T) {+ cleaner := NewPathCleanerFromJSON(`[{"alias": "/x", "regex": "/.*"}]`)+ require.NotNil(t, cleaner)++ path := "/" + strings.Repeat("a", maxCleanedPathLen)+ assert.Equal(t, path, cleaner.Clean(path), "a path over the ceiling must skip cleaning, not run rules on it")+}++func TestPathCleanerSkipsOverlongAlias(t *testing.T) {+ longAlias := strings.Repeat("x", maxPathCleaningAliasLen+1)+ // The over-long alias rule is dropped; the valid rule after it still applies.+ rules := fmt.Sprintf(`[{"alias": %q, "regex": "/a/.*"}, {"alias": "/b", "regex": "/a/.*"}]`, longAlias)+ cleaner := NewPathCleanerFromJSON(rules)+ require.NotNil(t, cleaner)++ assert.Equal(t, "/b", cleaner.Clean("/a/123"))+}++func TestConvertInjectsCleanedPathnameWithoutMutatingSharedEvent(t *testing.T) {+ cleaner := NewPathCleanerFromJSON(`[{"alias": "/classes/:id", "regex": "/classes/[^/]+"}]`)+ require.NotNil(t, cleaner)++ event := PostHogEvent{+ Uuid: "uuid-1",+ DistinctId: "user-1",+ Event: "$pageview",+ Properties: map[string]interface{}{"$pathname": "/classes/928q3hr9paw8hfe"},+ }++ // columns == nil normally aliases the shared event map; the cleaner must+ // copy so its per-subscriber property never leaks into other subscriptions.+ response := convertToResponsePostHogEvent(event, 1, nil, cleaner)+ assert.Equal(t, "/classes/:id", response.Properties["$virt_cleaned_pathname"])+ assert.Equal(t, "/classes/928q3hr9paw8hfe", response.Properties["$pathname"])+ assert.NotContains(t, event.Properties, "$virt_cleaned_pathname")++ // With a column allowlist the property is injected after filtering, so+ // subscribers don't need to request it explicitly.+ withColumns := convertToResponsePostHogEvent(event, 1, []string{"$pathname"}, cleaner)+ assert.Equal(t, "/classes/:id", withColumns.Properties["$virt_cleaned_pathname"])++ // No cleaner, no property.+ withoutCleaner := convertToResponsePostHogEvent(event, 1, nil, nil)+ assert.NotContains(t, withoutCleaner.Properties, "$virt_cleaned_pathname")+}diff --git a/livestream/handlers/handlers.go b/livestream/handlers/handlers.goindex b2453a09c56c..3d398c8e7f0b 100644--- a/livestream/handlers/handlers.go+++ b/livestream/handlers/handlers.go@@ -135,6 +135,7 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu}propertyFilters := parsePropertyFilters(c.QueryParam("properties"), c.QueryParams()["property"])+ pathCleaner := events.NewPathCleanerFromJSON(c.QueryParam("pathCleaning"))subscription := events.Subscription{SubID: atomic.AddUint64(&subID, 1),@@ -145,6 +146,7 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSuColumns: columns,EventTypes: eventTypes,PropertyFilters: propertyFilters,+ PathCleaner: pathCleaner,EventChan: make(chan interface{}, 100),ShouldClose: &atomic.Bool{},DroppedEvents: &atomic.Uint64{},