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(livestream): apply property access control to the live events stream (#113953)

Alex Lider397fc8862e1c
diff --git a/livestream/auth/access.go b/livestream/auth/access.go
index 1089cc53ef62..02db6d7ea073 100644
--- a/livestream/auth/access.go
+++ b/livestream/auth/access.go
@@ -2,7 +2,10 @@ package auth
import (
"context"
+ "encoding/json"
+ "io"
"net/http"
+ "strings"
"time"
"github.com/labstack/echo/v4"
@@ -16,26 +19,144 @@ var authorizationClient = &http.Client{
},
}
-func CheckAccess(ctx context.Context, header http.Header) error {
+// A nil *PropertyRestrictions restricts nothing, so callers never special-case a user without rules.
+type PropertyRestrictions struct {
+ EventProperties map[string]struct{}
+ PersonProperties map[string]struct{}
+ // Keyed by group type name, the value `$group_type` carries on a $groupidentify event.
+ GroupProperties map[string]map[string]struct{}
+}
+
+// The geo stream derives its coordinates and country from the event's IP, the same lookup
+// that fills every $geoip_* property, so it stays hidden while any of those is.
+const (
+ ipProperty = "$ip"
+ geoipPropertyPrefix = "$geoip_"
+ // Group restrictions the authorize endpoint could not attribute to a group type apply to every type.
+ AnyGroupType = "*"
+)
+
+func (r *PropertyRestrictions) RestrictsEventProperty(key string) bool {
+ if r == nil {
+ return false
+ }
+ _, restricted := r.EventProperties[key]
+ return restricted
+}
+
+func (r *PropertyRestrictions) RestrictsPersonProperty(key string) bool {
+ if r == nil {
+ return false
+ }
+ _, restricted := r.PersonProperties[key]
+ return restricted
+}
+
+func (r *PropertyRestrictions) HasPersonRestrictions() bool {
+ return r != nil && len(r.PersonProperties) > 0
+}
+
+func (r *PropertyRestrictions) HasGroupRestrictions() bool {
+ return r != nil && len(r.GroupProperties) > 0
+}
+
+// RestrictsGroupProperty reports whether key is hidden for groupType. An empty groupType
+// means the type is unknown, so the key is hidden if any group type hides it.
+func (r *PropertyRestrictions) RestrictsGroupProperty(groupType, key string) bool {
+ if r == nil {
+ return false
+ }
+ if _, restricted := r.GroupProperties[AnyGroupType][key]; restricted {
+ return true
+ }
+ if groupType != "" {
+ _, restricted := r.GroupProperties[groupType][key]
+ return restricted
+ }
+ for _, keys := range r.GroupProperties {
+ if _, restricted := keys[key]; restricted {
+ return true
+ }
+ }
+ return false
+}
+
+func (r *PropertyRestrictions) RestrictsGeo() bool {
+ if r == nil {
+ return false
+ }
+ for key := range r.EventProperties {
+ if key == ipProperty || strings.HasPrefix(key, geoipPropertyPrefix) {
+ return true
+ }
+ }
+ return false
+}
+
+type authorizationResponse struct {
+ RestrictedEventProperties []string `json:"restricted_event_properties"`
+ RestrictedPersonProperties []string `json:"restricted_person_properties"`
+ RestrictedGroupProperties map[string][]string `json:"restricted_group_properties"`
+}
+
+func toSet(keys []string) map[string]struct{} {
+ if len(keys) == 0 {
+ return nil
+ }
+ set := make(map[string]struct{}, len(keys))
+ for _, key := range keys {
+ set[key] = struct{}{}
+ }
+ return set
+}
+
+// Fails closed: anything other than an explicit allow or refusal is reported as unavailable.
+func CheckAccess(ctx context.Context, header http.Header) (*PropertyRestrictions, error) {
url := viper.GetString("jwt.authorization_url")
if url == "" {
- return nil
+ return nil, nil
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
- return echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
+ return nil, echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
}
request.Header.Set("Authorization", header.Get("Authorization"))
+ // Django answers 204 to a client that does not ask for JSON, so an older service keeps working.
+ request.Header.Set("Accept", "application/json")
response, err := authorizationClient.Do(request)
if err != nil {
- return echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
+ return nil, echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
}
defer func() { _ = response.Body.Close() }()
- if response.StatusCode == http.StatusNoContent {
- return nil
- }
- if response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden {
- return echo.NewHTTPError(http.StatusUnauthorized, "live stream access denied")
+ switch response.StatusCode {
+ case http.StatusNoContent:
+ // Django builds that predate the restriction payload still answer 204.
+ return nil, nil
+ case http.StatusOK:
+ var payload authorizationResponse
+ if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&payload); err != nil {
+ return nil, echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
+ }
+ var groups map[string]map[string]struct{}
+ for groupType, keys := range payload.RestrictedGroupProperties {
+ if set := toSet(keys); set != nil {
+ if groups == nil {
+ groups = make(map[string]map[string]struct{})
+ }
+ groups[groupType] = set
+ }
+ }
+ if len(payload.RestrictedEventProperties) == 0 && len(payload.RestrictedPersonProperties) == 0 && groups == nil {
+ return nil, nil
+ }
+ return &PropertyRestrictions{
+ EventProperties: toSet(payload.RestrictedEventProperties),
+ PersonProperties: toSet(payload.RestrictedPersonProperties),
+ GroupProperties: groups,
+ }, nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil, echo.NewHTTPError(http.StatusUnauthorized, "live stream access denied")
+ default:
+ return nil, echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
}
- return echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
}
diff --git a/livestream/auth/access_test.go b/livestream/auth/access_test.go
index 795dd6b73aa8..04289118bcf9 100644
--- a/livestream/auth/access_test.go
+++ b/livestream/auth/access_test.go
@@ -14,36 +14,54 @@ import (
func TestCheckAccess(t *testing.T) {
for _, test := range []struct {
- status int
- want int
+ name string
+ status int
+ body string
+ want int
+ wantRestrictions *PropertyRestrictions
}{
- {http.StatusNoContent, 0},
- {http.StatusOK, http.StatusServiceUnavailable},
- {http.StatusFound, http.StatusServiceUnavailable},
- {http.StatusUnauthorized, http.StatusUnauthorized},
- {http.StatusForbidden, http.StatusUnauthorized},
- {http.StatusInternalServerError, http.StatusServiceUnavailable},
+ {name: "no content allows", status: http.StatusNoContent},
+ {name: "empty restrictions allow", status: http.StatusOK, body: `{"restricted_event_properties": [], "restricted_person_properties": []}`},
+ {
+ name: "restrictions are parsed",
+ status: http.StatusOK,
+ body: `{"restricted_event_properties": ["$ip"], "restricted_person_properties": ["email"], "restricted_group_properties": {"organization": ["email"], "project": []}}`,
+ wantRestrictions: &PropertyRestrictions{
+ EventProperties: map[string]struct{}{"$ip": {}},
+ PersonProperties: map[string]struct{}{"email": {}},
+ GroupProperties: map[string]map[string]struct{}{"organization": {"email": {}}},
+ },
+ },
+ {name: "malformed restrictions fail closed", status: http.StatusOK, body: `not json`, want: http.StatusServiceUnavailable},
+ {name: "redirect fails closed", status: http.StatusFound, want: http.StatusServiceUnavailable},
+ {name: "unauthorized denies", status: http.StatusUnauthorized, want: http.StatusUnauthorized},
+ {name: "forbidden denies", status: http.StatusForbidden, want: http.StatusUnauthorized},
+ {name: "server error fails closed", status: http.StatusInternalServerError, want: http.StatusServiceUnavailable},
} {
- t.Run(http.StatusText(test.status), func(t *testing.T) {
+ t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "Bearer test-live-stream-token", r.Header.Get("Authorization"))
+ assert.Equal(t, "application/json", r.Header.Get("Accept"))
if r.URL.Path == "/redirected" {
w.WriteHeader(http.StatusNoContent)
return
}
w.Header().Set("Location", "/redirected")
w.WriteHeader(test.status)
+ _, _ = w.Write([]byte(test.body))
}))
defer server.Close()
viper.Set("jwt.authorization_url", server.URL)
t.Cleanup(func() { viper.Set("jwt.authorization_url", "") })
- err := CheckAccess(context.Background(), http.Header{"Authorization": {"Bearer test-live-stream-token"}})
+ restrictions, err := CheckAccess(context.Background(), http.Header{"Authorization": {"Bearer test-live-stream-token"}})
if test.want == 0 {
require.NoError(t, err)
+ assert.Equal(t, test.wantRestrictions, restrictions)
} else {
var httpError *echo.HTTPError
require.ErrorAs(t, err, &httpError)
assert.Equal(t, test.want, httpError.Code)
+ assert.Nil(t, restrictions)
}
})
}
@@ -55,11 +73,34 @@ func TestCheckAccessFailsClosedOnConnectionFailure(t *testing.T) {
viper.Set("jwt.authorization_url", server.URL)
t.Cleanup(func() { viper.Set("jwt.authorization_url", "") })
var httpError *echo.HTTPError
- require.ErrorAs(t, CheckAccess(context.Background(), http.Header{}), &httpError)
+ _, err := CheckAccess(context.Background(), http.Header{})
+ require.ErrorAs(t, err, &httpError)
assert.Equal(t, http.StatusServiceUnavailable, httpError.Code)
}
func TestCheckAccessBeforeRollout(t *testing.T) {
viper.Set("jwt.authorization_url", "")
- require.NoError(t, CheckAccess(context.Background(), http.Header{}))
+ restrictions, err := CheckAccess(context.Background(), http.Header{})
+ require.NoError(t, err)
+ assert.Nil(t, restrictions)
+}
+
+func TestRestrictsGeo(t *testing.T) {
+ for key, want := range map[string]bool{"$ip": true, "$geoip_city_name": true, "$browser": false} {
+ restrictions := &PropertyRestrictions{EventProperties: map[string]struct{}{key: {}}}
+ assert.Equal(t, want, restrictions.RestrictsGeo(), key)
+ }
+ var none *PropertyRestrictions
+ assert.False(t, none.RestrictsGeo())
+}
+
+func TestRestrictsGroupPropertyForAnyType(t *testing.T) {
+ restrictions := &PropertyRestrictions{GroupProperties: map[string]map[string]struct{}{
+ AnyGroupType: {"email": {}},
+ "organization": {"plan": {}},
+ }}
+ assert.True(t, restrictions.RestrictsGroupProperty("organization", "email"))
+ assert.True(t, restrictions.RestrictsGroupProperty("project", "email"))
+ assert.True(t, restrictions.RestrictsGroupProperty("organization", "plan"))
+ assert.False(t, restrictions.RestrictsGroupProperty("project", "plan"))
}
diff --git a/livestream/events/filter.go b/livestream/events/filter.go
index 669a91463764..198ce43915bb 100644
--- a/livestream/events/filter.go
+++ b/livestream/events/filter.go
@@ -10,6 +10,7 @@ import (
"sync/atomic"
"github.com/gofrs/uuid/v5"
+ "github.com/posthog/posthog/livestream/auth"
"github.com/posthog/posthog/livestream/metrics"
"github.com/prometheus/client_golang/prometheus"
)
@@ -134,6 +135,82 @@ func convertToResponseGeoEvent(event PostHogEvent) *ResponseGeoEvent {
}
}
+// Person and group properties ride along on events under these keys, so a
+// restricted person or group property has to be removed from inside them as well.
+var (
+ personPropertyContainers = []string{"$set", "$set_once"}
+ groupPropertyContainer = "$group_set"
+ groupTypeProperty = "$group_type"
+)
+
+// A filter on a hidden key would let the subscriber infer its values from which events match.
+// Filters match the whole stringified $set / $set_once map, so those are hidden too once any person key is.
+func RestrictedFilterKey(filters []CompiledPropertyFilter, restrictions *auth.PropertyRestrictions) string {
+ for i := range filters {
+ key := filters[i].Key
+ if restrictions.RestrictsEventProperty(key) {
+ return key
+ }
+ if restrictions.HasPersonRestrictions() && slices.Contains(personPropertyContainers, key) {
+ return key
+ }
+ if restrictions.HasGroupRestrictions() && key == groupPropertyContainer {
+ return key
+ }
+ }
+ return ""
+}
+
+func groupTypeOf(properties map[string]interface{}) string {
+ groupType, _ := properties[groupTypeProperty].(string)
+ return groupType
+}
+
+// StripRestricted removes hidden properties from a built response. The handler calls it at
+// write time, off the fan-out goroutine, with whatever rules the latest re-check returned.
+func (e *ResponsePostHogEvent) StripRestricted(restrictions *auth.PropertyRestrictions) {
+ if restrictions == nil {
+ return
+ }
+ properties := make(map[string]interface{}, len(e.Properties))
+ groupType := groupTypeOf(e.Properties)
+ for k, v := range e.Properties {
+ if visible, ok := visibleProperty(k, v, groupType, restrictions); ok {
+ properties[k] = visible
+ }
+ }
+ if restrictions.RestrictsEventProperty("$pathname") {
+ delete(properties, "$virt_cleaned_pathname")
+ }
+ e.Properties = properties
+}
+
+func visibleProperty(key string, value interface{}, groupType string, restrictions *auth.PropertyRestrictions) (interface{}, bool) {
+ if restrictions.RestrictsEventProperty(key) {
+ return nil, false
+ }
+ var hidden func(string) bool
+ switch {
+ case restrictions.HasPersonRestrictions() && slices.Contains(personPropertyContainers, key):
+ hidden = restrictions.RestrictsPersonProperty
+ case restrictions.HasGroupRestrictions() && key == groupPropertyContainer:
+ hidden = func(k string) bool { return restrictions.RestrictsGroupProperty(groupType, k) }
+ default:
+ return value, true
+ }
+ nested, ok := value.(map[string]interface{})
+ if !ok {
+ return value, true
+ }
+ stripped := make(map[string]interface{}, len(nested))
+ for k, v := range nested {
+ if !hidden(k) {
+ stripped[k] = v
+ }
+ }
+ return stripped, true
+}
+
func convertToResponsePostHogEvent(
event PostHogEvent,
teamId int,
diff --git a/livestream/events/filter_test.go b/livestream/events/filter_test.go
index 362bc37a588e..12e73f77768d 100644
--- a/livestream/events/filter_test.go
+++ b/livestream/events/filter_test.go
@@ -7,6 +7,7 @@ import (
"sync/atomic"
+ "github.com/posthog/posthog/livestream/auth"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -753,3 +754,82 @@ func TestIncludeProperties_NonExistentPropertiesAreIgnored(t *testing.T) {
"url": "https://example.com",
}, result.Properties)
}
+
+func TestStripRestrictedHidesRestrictedProperties(t *testing.T) {
+ restrictions := &auth.PropertyRestrictions{
+ EventProperties: map[string]struct{}{"$ip": {}, "$pathname": {}},
+ PersonProperties: map[string]struct{}{"email": {}},
+ GroupProperties: map[string]map[string]struct{}{
+ "organization": {"email": {}},
+ "project": {"owner": {}},
+ },
+ }
+ groupSet := map[string]interface{}{"email": "[email protected]", "owner": "someone", "name": "Acme"}
+ properties := map[string]interface{}{
+ "$ip": "203.0.113.7",
+ "$pathname": "/classes/928q3hr9paw8hfe",
+ "$browser": "Chrome",
+ "$set": map[string]interface{}{"email": "[email protected]", "name": "Test User"},
+ "$set_once": map[string]interface{}{"email": "[email protected]"},
+ "$group_type": "organization",
+ "$group_set": groupSet,
+ "$virt_is_bot": false,
+ }
+ event := PostHogEvent{Uuid: "123", DistinctId: "user1", Event: "$groupidentify", Properties: properties}
+ cleaner := NewPathCleanerFromJSON(`[{"alias": "/classes/:id", "regex": "/classes/[^/]+"}]`)
+ require.NotNil(t, cleaner)
+
+ for name, test := range map[string]struct {
+ columns []string
+ want map[string]interface{}
+ }{
+ "all properties": {
+ columns: nil,
+ want: map[string]interface{}{
+ "$browser": "Chrome",
+ "$set": map[string]interface{}{"name": "Test User"},
+ "$set_once": map[string]interface{}{},
+ "$group_type": "organization",
+ "$group_set": map[string]interface{}{"owner": "someone", "name": "Acme"},
+ "$virt_is_bot": false,
+ },
+ },
+ // Without $group_type in the response the group type is unknown, so every type's keys go.
+ "requested columns": {
+ columns: []string{"$ip", "$browser", "$set", "$group_set"},
+ want: map[string]interface{}{
+ "$browser": "Chrome",
+ "$set": map[string]interface{}{"name": "Test User"},
+ "$group_set": map[string]interface{}{"name": "Acme"},
+ "$virt_is_bot": false,
+ },
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ result := convertToResponsePostHogEvent(event, 1, test.columns, cleaner)
+ result.StripRestricted(restrictions)
+ assert.Equal(t, test.want, result.Properties)
+ })
+ }
+
+ // The shared event map must keep every property for subscribers without rules.
+ assert.Equal(t, "203.0.113.7", properties["$ip"])
+ assert.Equal(t, "[email protected]", properties["$set"].(map[string]interface{})["email"])
+ assert.Equal(t, "[email protected]", groupSet["email"])
+ unrestricted := convertToResponsePostHogEvent(event, 1, nil, cleaner)
+ unrestricted.StripRestricted(nil)
+ assert.Equal(t, "/classes/:id", unrestricted.Properties["$virt_cleaned_pathname"])
+}
+
+func TestRestrictedFilterKeyHidesPropertyContainers(t *testing.T) {
+ filters := []CompiledPropertyFilter{
+ NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"}),
+ NewCompiledPropertyFilter("$set", OpIContains, []string{"[email protected]"}),
+ NewCompiledPropertyFilter("$group_set", OpIContains, []string{"acme"}),
+ }
+ personOnly := &auth.PropertyRestrictions{PersonProperties: map[string]struct{}{"email": {}}}
+ groupOnly := &auth.PropertyRestrictions{GroupProperties: map[string]map[string]struct{}{"organization": {"email": {}}}}
+ assert.Equal(t, "$set", RestrictedFilterKey(filters, personOnly))
+ assert.Equal(t, "$group_set", RestrictedFilterKey(filters, groupOnly))
+ assert.Equal(t, "", RestrictedFilterKey(filters, nil))
+}
diff --git a/livestream/handlers/handlers.go b/livestream/handlers/handlers.go
index 22053efdb3f1..f7f1e0e304fe 100644
--- a/livestream/handlers/handlers.go
+++ b/livestream/handlers/handlers.go
@@ -51,7 +51,7 @@ func StatsHandler(stats *events.Stats, sessionStats *events.SessionStats, redisS
if err != nil {
return c.JSON(http.StatusUnauthorized, resp{Error: "wrong token claims"})
}
- if err := auth.CheckAccess(c.Request().Context(), c.Request().Header); err != nil {
+ if _, err := auth.CheckAccess(c.Request().Context(), c.Request().Header); err != nil {
return err
}
@@ -96,7 +96,13 @@ func StatsHandler(stats *events.Stats, sessionStats *events.SessionStats, redisS
var subID uint64 = 1
-func periodicAccessChecks(ctx context.Context, header http.Header, interval time.Duration) <-chan error {
+// An error from apply ends the stream the same way a denied check does.
+func periodicAccessChecks(
+ ctx context.Context,
+ header http.Header,
+ interval time.Duration,
+ apply func(*auth.PropertyRestrictions) error,
+) <-chan error {
errors := make(chan error, 1)
go func() {
ticker := time.NewTicker(interval)
@@ -106,7 +112,11 @@ func periodicAccessChecks(ctx context.Context, header http.Header, interval time
case <-ctx.Done():
return
case <-ticker.C:
- if err := auth.CheckAccess(ctx, header); err != nil {
+ restrictions, err := auth.CheckAccess(ctx, header)
+ if err == nil && apply != nil {
+ err = apply(restrictions)
+ }
+ if err != nil {
select {
case errors <- err:
case <-ctx.Done():
@@ -119,6 +129,10 @@ func periodicAccessChecks(ctx context.Context, header http.Header, interval time
return errors
}
+func restrictedFilterError(key string) error {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("property filter references a restricted property: %s", key))
+}
+
func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSubChan chan events.Subscription) func(c echo.Context) error {
return func(c echo.Context) error {
log.Debugf("SSE client connected, ip: %v", c.RealIP())
@@ -134,7 +148,8 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
if err != nil || token == "" || teamID == 0 {
return echo.NewHTTPError(http.StatusUnauthorized, "wrong token")
}
- if err := auth.CheckAccess(c.Request().Context(), c.Request().Header); err != nil {
+ restrictions, err := auth.CheckAccess(c.Request().Context(), c.Request().Header)
+ if err != nil {
return err
}
@@ -165,8 +180,14 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
}
propertyFilters := parsePropertyFilters(c.QueryParam("properties"), c.QueryParams()["property"])
+ if key := events.RestrictedFilterKey(propertyFilters, restrictions); key != "" {
+ return restrictedFilterError(key)
+ }
pathCleaner := events.NewPathCleanerFromJSON(c.QueryParam("pathCleaning"))
+ currentRestrictions := &atomic.Pointer[auth.PropertyRestrictions]{}
+ currentRestrictions.Store(restrictions)
+
subscription := events.Subscription{
SubID: atomic.AddUint64(&subID, 1),
TeamId: teamID,
@@ -195,7 +216,14 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
timeout := time.After(30 * time.Minute)
accessContext, cancelAccessCheck := context.WithCancel(c.Request().Context())
defer cancelAccessCheck()
- accessErrors := periodicAccessChecks(accessContext, c.Request().Header.Clone(), 30*time.Second)
+ accessErrors := periodicAccessChecks(accessContext, c.Request().Header.Clone(), 30*time.Second,
+ func(fresh *auth.PropertyRestrictions) error {
+ currentRestrictions.Store(fresh)
+ if key := events.RestrictedFilterKey(propertyFilters, fresh); key != "" {
+ return restrictedFilterError(key)
+ }
+ return nil
+ })
for {
select {
case err := <-accessErrors:
@@ -208,6 +236,21 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
log.Debugf("SSE client disconnected, ip: %v", c.RealIP())
return nil
case payload := <-subscription.EventChan:
+ // Enforced here, on the subscriber's own goroutine, rather than in the fan-out:
+ // a queued event always goes out under the rules the latest re-check returned.
+ restrictions := currentRestrictions.Load()
+ if events.RestrictedFilterKey(propertyFilters, restrictions) != "" {
+ return nil
+ }
+ switch response := payload.(type) {
+ case events.ResponsePostHogEvent:
+ response.StripRestricted(restrictions)
+ payload = response
+ case events.ResponseGeoEvent:
+ if restrictions.RestrictsGeo() {
+ continue
+ }
+ }
jsonData, err := json.Marshal(payload)
if err != nil {
// TODO capture error to PostHog
@@ -311,7 +354,7 @@ func NotificationsHandler(redisClient rueidis.Client) func(c echo.Context) error
// Old tokens without organization_id/user_id — no-op until all tokens refresh
return c.NoContent(http.StatusNoContent)
}
- if err := auth.CheckAccess(c.Request().Context(), c.Request().Header); err != nil {
+ if _, err := auth.CheckAccess(c.Request().Context(), c.Request().Header); err != nil {
return err
}
ctx, cancel := context.WithCancel(c.Request().Context())
@@ -347,7 +390,7 @@ func NotificationsHandler(redisClient rueidis.Client) func(c echo.Context) error
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()
timeout := time.After(30 * time.Minute)
- accessErrors := periodicAccessChecks(ctx, c.Request().Header.Clone(), 15*time.Second)
+ accessErrors := periodicAccessChecks(ctx, c.Request().Header.Clone(), 15*time.Second, nil)
for {
select {
diff --git a/livestream/handlers/handlers_test.go b/livestream/handlers/handlers_test.go
index 378db4f848e1..31c9b7bf4df4 100644
--- a/livestream/handlers/handlers_test.go
+++ b/livestream/handlers/handlers_test.go
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"encoding/json"
+ "io"
"net/http"
"net/http/httptest"
"strings"
@@ -690,3 +691,96 @@ func TestParsePropertyFilters(t *testing.T) {
})
}
}
+
+func restrictionsResponse(body string) *http.Response {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(body)),
+ Header: make(http.Header),
+ }
+}
+
+func TestStreamEventsHandlerAppliesPropertyRestrictions(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`{"restricted_event_properties": ["email", "$ip"], "restricted_person_properties": ["email"]}`))
+ }))
+ defer server.Close()
+ viper.Set("jwt.authorization_url", server.URL)
+ t.Cleanup(func() { viper.Set("jwt.authorization_url", "") })
+ viper.Set("jwt.secret", "test-property-restrictions-secret")
+ token := createJWTToken(auth.ExpectedScope, jwt.MapClaims{
+ "team_id": 1, "api_token": "test-project-token", "user_id": 1, "organization_id": "test-organization",
+ })
+ e := echo.New()
+
+ t.Run("refuses a filter on a restricted property", func(t *testing.T) {
+ request := httptest.NewRequest(http.MethodGet, `/events?properties=[{"key":"email","operator":"icontains","value":"@example.com"}]`, nil)
+ request.Header.Set("Authorization", "Bearer "+token)
+ handler := StreamEventsHandler(e.Logger, make(chan events.Subscription, 1), make(chan events.Subscription, 1))
+ var httpError *echo.HTTPError
+ require.ErrorAs(t, handler(e.NewContext(request, httptest.NewRecorder())), &httpError)
+ assert.Equal(t, http.StatusBadRequest, httpError.Code)
+ })
+
+ t.Run("writes each event under the restrictions", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ request := httptest.NewRequest(http.MethodGet, "/events?property=$browser=Chrome", nil).WithContext(ctx)
+ request.Header.Set("Authorization", "Bearer "+token)
+ recorder := &flushRecorder{ResponseRecorder: httptest.NewRecorder(), flushed: make(chan string, 2)}
+ subChan := make(chan events.Subscription, 1)
+ done := make(chan error, 1)
+ go func() {
+ done <- StreamEventsHandler(e.Logger, subChan, make(chan events.Subscription, 1))(e.NewContext(request, recorder))
+ }()
+ subscription := <-subChan
+ // The geo event is dropped, so only the stripped event reaches the response.
+ subscription.EventChan <- events.ResponseGeoEvent{Lat: 40.7, Lng: -74.0, CountryCode: "US"}
+ subscription.EventChan <- events.ResponsePostHogEvent{Event: "pageview", Properties: map[string]interface{}{
+ "email": "[email protected]", "$browser": "Chrome", "$set": map[string]interface{}{"email": "[email protected]"},
+ }}
+ <-recorder.flushed
+ body := recorder.Body.String()
+ assert.Contains(t, body, `"$browser":"Chrome"`)
+ assert.NotContains(t, body, "[email protected]")
+ assert.NotContains(t, body, `"lat"`)
+ cancel()
+ require.NoError(t, <-done)
+ })
+}
+
+func TestStreamEventsHandlerEndsStreamWhenRecheckRestrictsFilteredProperty(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ viper.Set("jwt.secret", "test-periodic-restriction-secret")
+ viper.Set("jwt.authorization_url", "http://authorization.test")
+ defer viper.Set("jwt.authorization_url", "")
+
+ var calls atomic.Int32
+ originalTransport := http.DefaultTransport
+ http.DefaultTransport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
+ if calls.Add(1) == 1 {
+ return restrictionsResponse(`{"restricted_event_properties": [], "restricted_person_properties": []}`), nil
+ }
+ return restrictionsResponse(`{"restricted_event_properties": ["email"], "restricted_person_properties": []}`), nil
+ })
+ defer func() { http.DefaultTransport = originalTransport }()
+
+ request := httptest.NewRequest(http.MethodGet, "/[email protected]", nil)
+ request.Header.Set("Authorization", "Bearer "+createJWTToken(auth.ExpectedScope, jwt.MapClaims{
+ "team_id": 1, "api_token": "test-project-token",
+ }))
+ e := echo.New()
+ subChan := make(chan events.Subscription, 1)
+ unSubChan := make(chan events.Subscription, 1)
+ done := make(chan error, 1)
+ go func() {
+ done <- StreamEventsHandler(e.Logger, subChan, unSubChan)(e.NewContext(request, httptest.NewRecorder()))
+ }()
+
+ <-subChan
+ time.Sleep(30 * time.Second)
+
+ require.NoError(t, <-done)
+ assert.Equal(t, int32(2), calls.Load())
+ })
+}
diff --git a/posthog/api/livestream.py b/posthog/api/livestream.py
index 59eb93ec1779..200f72205e33 100644
--- a/posthog/api/livestream.py
+++ b/posthog/api/livestream.py
@@ -3,6 +3,7 @@ from uuid import UUID
import jwt
from drf_spectacular.utils import extend_schema
+from rest_framework import serializers
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed, PermissionDenied
from rest_framework.permissions import IsAuthenticated
@@ -10,13 +11,23 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.hogql.property_access_types import RestrictedProperty
+
from posthog.auth import refuse_blocked_account
from posthog.jwt import PosthogJwtAudience, decode_jwt
-from posthog.models import OrganizationMembership, Team, User
+from posthog.models import OrganizationMembership, PropertyDefinition, Team, User
from posthog.models.activity_logging.utils import ActivityCredentialMixin
+from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.permissions import ActiveOrganizationPermission, VerifiedDomainEnforcementPermission
from posthog.user_permissions import UserPermissions
+from products.access_control.backend.property_access_control import (
+ get_restricted_properties_with_group_type_index_for_team,
+)
+
+# Mirrors AnyGroupType in the livestream service.
+ANY_GROUP_TYPE = "*"
+
class LivestreamAuthentication(ActivityCredentialMixin, BaseAuthentication):
activity_credential_type = "internal_jwt"
@@ -60,13 +71,67 @@ class LivestreamVerifiedDomainPermission(VerifiedDomainEnforcementPermission):
return self._admits(request, cast(Team, request.auth).organization)
+class LivestreamAuthorizationSerializer(serializers.Serializer):
+ restricted_event_properties = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Event property names the livestream service must remove before streaming to this user.",
+ )
+ restricted_person_properties = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Person property names the livestream service must remove from $set and $set_once.",
+ )
+ restricted_group_properties = serializers.DictField(
+ child=serializers.ListField(child=serializers.CharField()),
+ help_text="Group property names to remove from $group_set, keyed by the group type name $group_type carries, or by * for every type.",
+ )
+
+
@extend_schema(exclude=True)
class LivestreamAuthorizationView(APIView):
authentication_classes = [LivestreamAuthentication]
permission_classes = [IsAuthenticated, LivestreamOrganizationPermission, LivestreamVerifiedDomainPermission]
def get(self, request: Request) -> Response:
- level = UserPermissions(cast(User, request.user)).team(cast(Team, request.auth)).effective_membership_level
+ user = cast(User, request.user)
+ team = cast(Team, request.auth)
+ level = UserPermissions(user).team(team).effective_membership_level
if level is None or level < OrganizationMembership.Level.MEMBER:
raise PermissionDenied("Live stream access is no longer available.")
- return Response(status=204, headers={"Cache-Control": "no-store"})
+ if "application/json" not in request.headers.get("Accept", ""):
+ # A livestream service that predates the restriction payload treats anything but 204 as an outage.
+ return Response(status=204, headers={"Cache-Control": "no-store"})
+ restricted = get_restricted_properties_with_group_type_index_for_team(user=user, team=team)
+ payload = LivestreamAuthorizationSerializer(
+ {
+ "restricted_event_properties": sorted(
+ p.name for p in restricted if p.property_type == PropertyDefinition.Type.EVENT
+ ),
+ "restricted_person_properties": sorted(
+ p.name for p in restricted if p.property_type == PropertyDefinition.Type.PERSON
+ ),
+ "restricted_group_properties": self._restricted_group_properties_by_type_name(team, restricted),
+ }
+ ).data
+ return Response(payload, headers={"Cache-Control": "no-store"})
+
+ @staticmethod
+ def _restricted_group_properties_by_type_name(
+ team: Team, restricted: set[RestrictedProperty]
+ ) -> dict[str, list[str]]:
+ # Rules carry the group type index; a $groupidentify event carries the group type name.
+ by_index: dict[int, list[str]] = {}
+ for p in restricted:
+ if p.property_type == PropertyDefinition.Type.GROUP and p.group_type_index is not None:
+ by_index.setdefault(p.group_type_index, []).append(p.name)
+ if not by_index:
+ return {}
+ by_name = {
+ mapping["group_type"]: sorted(by_index.pop(mapping["group_type_index"]))
+ for mapping in get_group_types_for_project(team.project_id, caller_tag="livestream_authorize")
+ if mapping["group_type_index"] in by_index
+ }
+ if by_index:
+ # The lookup failed or the type is gone, so these names cannot be attributed to a type.
+ # Fail closed: the service hides them on every group type rather than on none.
+ by_name[ANY_GROUP_TYPE] = sorted({name for names in by_index.values() for name in names})
+ return by_name
diff --git a/posthog/api/test/test_livestream.py b/posthog/api/test/test_livestream.py
index cd482a2e39f3..24d91abb5363 100644
--- a/posthog/api/test/test_livestream.py
+++ b/posthog/api/test/test_livestream.py
@@ -9,9 +9,12 @@ from parameterized import parameterized
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models import OrganizationDomain, OrganizationMembership
+from posthog.models import OrganizationDomain, OrganizationMembership, PropertyDefinition
+from posthog.test.persons import create_group_type_mapping
from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
class TestLivestreamAuthorization(APIBaseTest):
@@ -45,9 +48,18 @@ class TestLivestreamAuthorization(APIBaseTest):
self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]
self.organization.save()
authorization = f"Bearer {self._token()}"
- initial = self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization)
- self.assertEqual(initial.status_code, 204)
+ initial = self.client.get(
+ "/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization, HTTP_ACCEPT="application/json"
+ )
+ self.assertEqual(initial.status_code, 200)
self.assertEqual(initial["Cache-Control"], "no-store")
+ self.assertEqual(
+ initial.json(),
+ {"restricted_event_properties": [], "restricted_person_properties": [], "restricted_group_properties": {}},
+ )
+ legacy = self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization)
+ self.assertEqual(legacy.status_code, 204)
+ self.assertEqual(legacy["Cache-Control"], "no-store")
if revoked == "membership":
self.organization_membership.delete()
@@ -88,6 +100,52 @@ class TestLivestreamAuthorization(APIBaseTest):
self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization).status_code, 401
)
+ def test_lists_the_properties_hidden_from_the_user(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ create_group_type_mapping(
+ team=self.team, project=self.team.project, group_type="organization", group_type_index=0
+ )
+ for name, property_type, group_type_index in (
+ ("$ip", PropertyDefinition.Type.EVENT, None),
+ ("email", PropertyDefinition.Type.PERSON, None),
+ ("$browser", PropertyDefinition.Type.EVENT, None),
+ ("email", PropertyDefinition.Type.GROUP, 0),
+ ):
+ definition = PropertyDefinition.objects.create(
+ team=self.team, name=name, type=property_type, group_type_index=group_type_index
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=definition,
+ access_level=PropertyAccessLevel.NONE.value if name != "$browser" else PropertyAccessLevel.READ.value,
+ )
+
+ response = self.client.get(
+ "/api/livestream/authorize/", HTTP_AUTHORIZATION=f"Bearer {self._token()}", HTTP_ACCEPT="application/json"
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(),
+ {
+ "restricted_event_properties": ["$ip"],
+ "restricted_person_properties": ["email"],
+ "restricted_group_properties": {"organization": ["email"]},
+ },
+ )
+
+ # When the group types cannot be loaded the rule still applies, to every type.
+ with patch("posthog.api.livestream.get_group_types_for_project", return_value=[]):
+ response = self.client.get(
+ "/api/livestream/authorize/",
+ HTTP_AUTHORIZATION=f"Bearer {self._token()}",
+ HTTP_ACCEPT="application/json",
+ )
+ self.assertEqual(response.json()["restricted_group_properties"], {"*": ["email"]})
+
def test_refuses_an_account_an_access_rule_blocks(self) -> None:
with patch("posthog.auth.security_access_refused", return_value=True):
response = self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=f"Bearer {self._token()}")