on main help sign in
fix(event): prevent panic on non-string telemetry keys (#2502)
8e743cbiceymoss
internal/event/event.go+5−1
@@ -127,7 +127,11 @@ func pairsToProps(props ...any) posthog.Properties {
127 }
127 }
128
128
129 for i := 0; i < len(props); i += 2 {
129 for i := 0; i < len(props); i += 2 {
130− key := props[i].(string)
130+ key, ok := props[i].(string)
131+ if !ok {
132+ slog.Error("Event property key must be a string", "key", props[i], "index", i)
133+ continue
134+ }
131 value := props[i+1]
135 value := props[i+1]
132 p = p.Set(key, value)
136 p = p.Set(key, value)
133 }
137 }
internal/event/event_test.go+30
@@ -4,7 +4,10 @@ package event
4// scenarios. These tests will not log anything.
4// scenarios. These tests will not log anything.
5
5
6import (
6import (
7+ "reflect"
7 "testing"
8 "testing"
9+
10+ "github.com/posthog/posthog-go"
8)
11)
9
12
10func TestError(t *testing.T) {
13func TestError(t *testing.T) {
@@ -59,6 +62,33 @@ func TestError(t *testing.T) {
59 })
62 })
60}
63}
61
64
65+func TestPairsToProps(t *testing.T) {
66+ t.Run("sets valid key value pairs", func(t *testing.T) {
67+ got := pairsToProps("foo", "bar", "count", 3)
68+ want := posthog.NewProperties().
69+ Set("foo", "bar").
70+ Set("count", 3)
71+ if !reflect.DeepEqual(got, want) {
72+ t.Fatalf("pairsToProps() = %#v, want %#v", got, want)
73+ }
74+ })
75+
76+ t.Run("returns empty properties for odd pairs", func(t *testing.T) {
77+ got := pairsToProps("foo", "bar", "count")
78+ if len(got) != 0 {
79+ t.Fatalf("pairsToProps() should return empty properties, got %#v", got)
80+ }
81+ })
82+
83+ t.Run("ignores non-string key and continues", func(t *testing.T) {
84+ got := pairsToProps(123, "bad", "ok", true)
85+ want := posthog.NewProperties().Set("ok", true)
86+ if !reflect.DeepEqual(got, want) {
87+ t.Fatalf("pairsToProps() = %#v, want %#v", got, want)
88+ }
89+ })
90+}
91+
62// newDefaultTestError creates a test error that mimics runtime panic
92// newDefaultTestError creates a test error that mimics runtime panic
63// errors. This helps us testing that the Error function can handle various
93// errors. This helps us testing that the Error function can handle various
64// error types, including those that might be passed from a panic recovery
94// error types, including those that might be passed from a panic recovery