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): recheck current project membership (#108135)

Paul D'Ambra187ce9001fd2
diff --git a/livestream/auth/access.go b/livestream/auth/access.go
new file mode 100644
index 000000000000..1089cc53ef62
--- /dev/null
+++ b/livestream/auth/access.go
@@ -0,0 +1,41 @@
+package auth
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/spf13/viper"
+)
+
+var authorizationClient = &http.Client{
+ Timeout: 3 * time.Second,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+}
+
+func CheckAccess(ctx context.Context, header http.Header) error {
+ url := viper.GetString("jwt.authorization_url")
+ if url == "" {
+ return nil
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
+ }
+ request.Header.Set("Authorization", header.Get("Authorization"))
+ response, err := authorizationClient.Do(request)
+ if err != nil {
+ return 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")
+ }
+ return echo.NewHTTPError(http.StatusServiceUnavailable, "live stream authorization unavailable")
+}
diff --git a/livestream/auth/access_test.go b/livestream/auth/access_test.go
new file mode 100644
index 000000000000..795dd6b73aa8
--- /dev/null
+++ b/livestream/auth/access_test.go
@@ -0,0 +1,65 @@
+package auth
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/labstack/echo/v4"
+ "github.com/spf13/viper"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestCheckAccess(t *testing.T) {
+ for _, test := range []struct {
+ status int
+ want int
+ }{
+ {http.StatusNoContent, 0},
+ {http.StatusOK, http.StatusServiceUnavailable},
+ {http.StatusFound, http.StatusServiceUnavailable},
+ {http.StatusUnauthorized, http.StatusUnauthorized},
+ {http.StatusForbidden, http.StatusUnauthorized},
+ {http.StatusInternalServerError, http.StatusServiceUnavailable},
+ } {
+ t.Run(http.StatusText(test.status), 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"))
+ if r.URL.Path == "/redirected" {
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ w.Header().Set("Location", "/redirected")
+ w.WriteHeader(test.status)
+ }))
+ 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"}})
+ if test.want == 0 {
+ require.NoError(t, err)
+ } else {
+ var httpError *echo.HTTPError
+ require.ErrorAs(t, err, &httpError)
+ assert.Equal(t, test.want, httpError.Code)
+ }
+ })
+ }
+}
+
+func TestCheckAccessFailsClosedOnConnectionFailure(t *testing.T) {
+ server := httptest.NewServer(http.NotFoundHandler())
+ server.Close()
+ 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)
+ 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{}))
+}
diff --git a/livestream/configs/configs.go b/livestream/configs/configs.go
index c185ae7afcfa..05525a408f4b 100644
--- a/livestream/configs/configs.go
+++ b/livestream/configs/configs.go
@@ -13,7 +13,8 @@ type MMDBConfig struct {
}
type JWTConfig struct {
- Secret string
+ Secret string
+ AuthorizationURL string `mapstructure:"authorization_url"`
// Previous secrets still accepted for verification (never used for signing),
// so tokens signed before a key rotation keep working until they expire.
SecretFallbacks []string `mapstructure:"secret_fallbacks"`
@@ -132,6 +133,7 @@ func InitConfigs(filename, configPath string) {
// JWT settings
_ = viper.BindEnv("jwt.secret") // LIVESTREAM_JWT_SECRET
_ = viper.BindEnv("jwt.secret_fallbacks") // LIVESTREAM_JWT_SECRET_FALLBACKS (comma-separated)
+ _ = viper.BindEnv("jwt.authorization_url")
// Session recording settings
_ = viper.BindEnv("session_recording.max_lru_entries") // LIVESTREAM_SESSION_RECORDING_MAX_LRU_ENTRIES
diff --git a/livestream/handlers/handlers.go b/livestream/handlers/handlers.go
index 3d398c8e7f0b..22053efdb3f1 100644
--- a/livestream/handlers/handlers.go
+++ b/livestream/handlers/handlers.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "context"
"encoding/json"
"fmt"
"log"
@@ -50,6 +51,9 @@ 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 {
+ return err
+ }
if redisStore != nil {
ctx := c.Request().Context()
@@ -92,6 +96,29 @@ 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 {
+ errors := make(chan error, 1)
+ go func() {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if err := auth.CheckAccess(ctx, header); err != nil {
+ select {
+ case errors <- err:
+ case <-ctx.Done():
+ }
+ return
+ }
+ }
+ }
+ }()
+ return errors
+}
+
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())
@@ -107,6 +134,9 @@ 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 {
+ return err
+ }
eventType := c.QueryParam("eventType")
distinctId := c.QueryParam("distinctId")
@@ -163,8 +193,14 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
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)
for {
select {
+ case err := <-accessErrors:
+ log.Warnf("Live stream authorization check failed: %v", err)
+ return nil
case <-timeout:
log.Debug("SSE connection to be terminated after timeout")
return nil
@@ -275,11 +311,15 @@ 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 {
+ return err
+ }
+ ctx, cancel := context.WithCancel(c.Request().Context())
+ defer cancel()
metrics.NotificationSubs.Inc()
defer metrics.NotificationSubs.Dec()
- ctx := c.Request().Context()
channel := fmt.Sprintf("notifications:%s", claims.OrganizationID)
// Absorbs publish-rate bursts; drops on overflow to avoid blocking rueidis.
@@ -307,6 +347,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)
for {
select {
@@ -319,6 +360,9 @@ func NotificationsHandler(redisClient rueidis.Client) func(c echo.Context) error
log.Printf("Redis subscription error: %v", err)
}
return nil
+ case err := <-accessErrors:
+ log.Printf("Live stream authorization check failed: %v", err)
+ return nil
case msg := <-msgCh:
cleaned, ok, reason := filterNotificationForUser(msg, claims.UserID)
if !ok {
diff --git a/livestream/handlers/handlers_test.go b/livestream/handlers/handlers_test.go
index 9cc45c63212d..378db4f848e1 100644
--- a/livestream/handlers/handlers_test.go
+++ b/livestream/handlers/handlers_test.go
@@ -5,7 +5,10 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "strings"
+ "sync/atomic"
"testing"
+ "testing/synctest"
"time"
"github.com/alicebob/miniredis/v2"
@@ -19,6 +22,42 @@ import (
"github.com/stretchr/testify/require"
)
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
+ return f(request)
+}
+
+type flushRecorder struct {
+ *httptest.ResponseRecorder
+ flushed chan string
+}
+
+func (r *flushRecorder) Flush() {
+ r.ResponseRecorder.Flush()
+ select {
+ case r.flushed <- r.Body.String():
+ default:
+ }
+}
+
+type notificationRedisClient struct {
+ rueidis.Client
+ receiveCallback chan func(rueidis.PubSubMessage)
+ receiveCanceled chan struct{}
+}
+
+func (c *notificationRedisClient) Receive(
+ ctx context.Context,
+ _ rueidis.Completed,
+ callback func(rueidis.PubSubMessage),
+) error {
+ c.receiveCallback <- callback
+ <-ctx.Done()
+ close(c.receiveCanceled)
+ return ctx.Err()
+}
+
func TestStreamEventsHandler_AuthValidation(t *testing.T) {
logger := echo.New().Logger
subChan := make(chan events.Subscription, 10)
@@ -160,6 +199,224 @@ func createJWTToken(audience string, claims jwt.MapClaims) string {
return tokenString
}
+func TestStreamEventsHandlerDeliversEventsDuringPeriodicAccessCheck(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ viper.Set("jwt.secret", "test-periodic-access-secret")
+ viper.Set("jwt.authorization_url", "http://authorization.test")
+ defer viper.Set("jwt.authorization_url", "")
+
+ var calls atomic.Int32
+ var activeCalls atomic.Int32
+ var maxActiveCalls atomic.Int32
+ periodicStarted := make(chan struct{})
+ periodicStatus := make(chan int)
+ originalTransport := http.DefaultTransport
+ http.DefaultTransport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
+ call := calls.Add(1)
+ active := activeCalls.Add(1)
+ for {
+ maxActive := maxActiveCalls.Load()
+ if active <= maxActive || maxActiveCalls.CompareAndSwap(maxActive, active) {
+ break
+ }
+ }
+ defer activeCalls.Add(-1)
+
+ if call == 1 {
+ return accessResponse(http.StatusNoContent), nil
+ }
+ if call == 2 {
+ close(periodicStarted)
+ }
+ select {
+ case status := <-periodicStatus:
+ return accessResponse(status), nil
+ case <-request.Context().Done():
+ return nil, request.Context().Err()
+ }
+ })
+ defer func() { http.DefaultTransport = originalTransport }()
+
+ requestContext, cancelRequest := context.WithCancel(context.Background())
+ defer cancelRequest()
+ request := httptest.NewRequest(http.MethodGet, "/events", nil).WithContext(requestContext)
+ request.Header.Set("Authorization", "Bearer "+createJWTToken(auth.ExpectedScope, jwt.MapClaims{
+ "team_id": 1, "api_token": "test-project-token",
+ }))
+ recorder := &flushRecorder{ResponseRecorder: httptest.NewRecorder(), flushed: make(chan string, 1)}
+ 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, recorder))
+ }()
+
+ subscription := <-subChan
+ time.Sleep(30 * time.Second)
+ <-periodicStarted
+
+ subscription.EventChan <- map[string]string{"event": "received"}
+ <-recorder.flushed
+ assert.Contains(t, recorder.Body.String(), `"event":"received"`)
+ assert.Equal(t, int32(2), calls.Load())
+ assert.Equal(t, int32(1), maxActiveCalls.Load())
+
+ periodicStatus <- http.StatusForbidden
+ require.NoError(t, <-done)
+ })
+}
+
+func TestNotificationsHandlerDeliversMessagesDuringPeriodicAccessCheck(t *testing.T) {
+ miniredisServer := miniredis.RunT(t)
+ client, err := rueidis.NewClient(rueidis.ClientOption{
+ InitAddress: []string{miniredisServer.Addr()},
+ DisableCache: true,
+ })
+ require.NoError(t, err)
+ defer client.Close()
+
+ synctest.Test(t, func(t *testing.T) {
+ viper.Set("jwt.secret", "test-notification-access-secret")
+ viper.Set("jwt.authorization_url", "http://authorization.test")
+ defer viper.Set("jwt.authorization_url", "")
+
+ var calls atomic.Int32
+ periodicStarted := make(chan struct{})
+ periodicStatus := make(chan int)
+ originalTransport := http.DefaultTransport
+ http.DefaultTransport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
+ if calls.Add(1) == 1 {
+ return accessResponse(http.StatusNoContent), nil
+ }
+ close(periodicStarted)
+ select {
+ case status := <-periodicStatus:
+ return accessResponse(status), nil
+ case <-request.Context().Done():
+ return nil, request.Context().Err()
+ }
+ })
+ defer func() { http.DefaultTransport = originalTransport }()
+
+ redisClient := &notificationRedisClient{
+ Client: client,
+ receiveCallback: make(chan func(rueidis.PubSubMessage), 1),
+ receiveCanceled: make(chan struct{}),
+ }
+
+ requestContext, cancelRequest := context.WithCancel(context.Background())
+ defer cancelRequest()
+ request := httptest.NewRequest(http.MethodGet, "/notifications", nil).WithContext(requestContext)
+ request.Header.Set("Authorization", "Bearer "+createJWTToken(auth.ExpectedScope, jwt.MapClaims{
+ "team_id": 1, "api_token": "test-project-token", "user_id": 42, "organization_id": "test-organization",
+ }))
+ recorder := &flushRecorder{ResponseRecorder: httptest.NewRecorder(), flushed: make(chan string, 2)}
+ e := echo.New()
+ done := make(chan error, 1)
+ go func() {
+ done <- NotificationsHandler(redisClient)(e.NewContext(request, recorder))
+ }()
+
+ receive := <-redisClient.receiveCallback
+ time.Sleep(15 * time.Second)
+ <-periodicStarted
+ receive(rueidis.PubSubMessage{Message: `{"resolved_user_ids":[42],"body":"delivered"}`})
+
+ for {
+ body := <-recorder.flushed
+ if strings.Contains(body, `"body":"delivered"`) {
+ break
+ }
+ }
+
+ periodicStatus <- http.StatusForbidden
+ require.NoError(t, <-done)
+ <-redisClient.receiveCanceled
+ })
+}
+
+func TestStreamEventsHandlerCancelsPeriodicAccessCheck(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ viper.Set("jwt.secret", "test-periodic-cancel-secret")
+ viper.Set("jwt.authorization_url", "http://authorization.test")
+ defer viper.Set("jwt.authorization_url", "")
+
+ var calls atomic.Int32
+ periodicStarted := make(chan struct{})
+ periodicCanceled := make(chan struct{})
+ originalTransport := http.DefaultTransport
+ http.DefaultTransport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
+ if calls.Add(1) == 1 {
+ return accessResponse(http.StatusNoContent), nil
+ }
+ close(periodicStarted)
+ <-request.Context().Done()
+ close(periodicCanceled)
+ return nil, request.Context().Err()
+ })
+ defer func() { http.DefaultTransport = originalTransport }()
+
+ requestContext, cancelRequest := context.WithCancel(context.Background())
+ request := httptest.NewRequest(http.MethodGet, "/events", nil).WithContext(requestContext)
+ 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)
+ <-periodicStarted
+ cancelRequest()
+
+ require.NoError(t, <-done)
+ <-periodicCanceled
+ })
+}
+
+func accessResponse(status int) *http.Response {
+ return &http.Response{
+ StatusCode: status,
+ Body: http.NoBody,
+ Header: make(http.Header),
+ }
+}
+
+func TestHandlersRejectRevokedAccess(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ }))
+ defer server.Close()
+ viper.Set("jwt.authorization_url", server.URL)
+ t.Cleanup(func() { viper.Set("jwt.authorization_url", "") })
+ viper.Set("jwt.secret", "test-revoked-access-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()
+ for name, handler := range map[string]echo.HandlerFunc{
+ "stats": StatsHandler(nil, nil, nil),
+ "events": StreamEventsHandler(e.Logger, make(chan events.Subscription, 1), make(chan events.Subscription, 1)),
+ "notifications": NotificationsHandler(nil),
+ } {
+ t.Run(name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ request := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
+ request.Header.Set("Authorization", "Bearer "+token)
+ var httpError *echo.HTTPError
+ require.ErrorAs(t, handler(e.NewContext(request, httptest.NewRecorder())), &httpError)
+ assert.Equal(t, http.StatusUnauthorized, httpError.Code)
+ })
+ }
+}
+
func TestStatsHandler_ReadsFromRedis(t *testing.T) {
viper.Set("jwt.secret", "test-secret-for-stats")
apiToken := "phx_test_token"
diff --git a/posthog/api/livestream.py b/posthog/api/livestream.py
new file mode 100644
index 000000000000..3e6539dd56e9
--- /dev/null
+++ b/posthog/api/livestream.py
@@ -0,0 +1,69 @@
+from typing import cast
+from uuid import UUID
+
+import jwt
+from drf_spectacular.utils import extend_schema
+from rest_framework.authentication import BaseAuthentication, get_authorization_header
+from rest_framework.exceptions import AuthenticationFailed, PermissionDenied
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.jwt import PosthogJwtAudience, decode_jwt
+from posthog.models import OrganizationMembership, Team, User
+from posthog.models.activity_logging.utils import ActivityCredentialMixin
+from posthog.permissions import ActiveOrganizationPermission, VerifiedDomainEnforcementPermission
+from posthog.user_permissions import UserPermissions
+
+
+class LivestreamAuthentication(ActivityCredentialMixin, BaseAuthentication):
+ activity_credential_type = "internal_jwt"
+
+ def authenticate_header(self, request: Request) -> str:
+ return "Bearer"
+
+ def authenticate(self, request: Request) -> tuple[User, Team] | None:
+ authorization = get_authorization_header(request).split()
+ if not authorization:
+ return None
+ if len(authorization) != 2 or authorization[0].lower() != b"bearer":
+ raise AuthenticationFailed("Invalid live stream token.")
+ try:
+ claims = decode_jwt(authorization[1].decode(), PosthogJwtAudience.LIVESTREAM)
+ if type(claims["user_id"]) is not int or type(claims["team_id"]) is not int:
+ raise ValueError("Invalid token identity")
+ if not isinstance(claims["api_token"], str) or not claims["api_token"]:
+ raise ValueError("Invalid project token")
+ user = User.objects.get(id=claims["user_id"], is_active=True)
+ team = Team.objects.select_related("organization").get(
+ id=claims["team_id"],
+ organization_id=UUID(str(claims["organization_id"])),
+ api_token=claims["api_token"],
+ )
+ except (jwt.PyJWTError, KeyError, TypeError, ValueError, User.DoesNotExist, Team.DoesNotExist):
+ raise AuthenticationFailed("Invalid live stream token.")
+ self.record_activity_actor(user)
+ return user, team
+
+
+class LivestreamOrganizationPermission(ActiveOrganizationPermission):
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return self._admits(cast(Team, request.auth).organization)
+
+
+class LivestreamVerifiedDomainPermission(VerifiedDomainEnforcementPermission):
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return self._admits(request, cast(Team, request.auth).organization)
+
+
+@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
+ 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"})
diff --git a/posthog/api/test/test_livestream.py b/posthog/api/test/test_livestream.py
new file mode 100644
index 000000000000..eb454b217cd3
--- /dev/null
+++ b/posthog/api/test/test_livestream.py
@@ -0,0 +1,88 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.jwt import PosthogJwtAudience, encode_jwt
+from posthog.models import OrganizationDomain, OrganizationMembership
+
+from products.access_control.backend.models.access_control import AccessControl
+
+
+class TestLivestreamAuthorization(APIBaseTest):
+ def _token(self, audience: PosthogJwtAudience = PosthogJwtAudience.LIVESTREAM) -> str:
+ return encode_jwt(
+ {
+ "user_id": self.user.id,
+ "team_id": self.team.id,
+ "organization_id": str(self.organization.id),
+ "api_token": self.team.api_token,
+ },
+ timedelta(days=7),
+ audience,
+ )
+
+ @parameterized.expand(
+ [
+ ("membership", 403),
+ ("project_access", 403),
+ ("user", 401),
+ ("project_token", 401),
+ ("inactive_organization", 403),
+ ("organization_with_unknown_active_state", 403),
+ ("organization_pending_deletion", 403),
+ ("unverified_email_domain", 403),
+ ]
+ )
+ def test_rechecks_current_access(self, revoked: str, expected_status: int) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ 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)
+ self.assertEqual(initial["Cache-Control"], "no-store")
+
+ if revoked == "membership":
+ self.organization_membership.delete()
+ elif revoked == "project_access":
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"
+ )
+ elif revoked == "user":
+ self.user.is_active = False
+ self.user.save(update_fields=["is_active"])
+ elif revoked == "project_token":
+ self.team.api_token = "test-rotated-project-token"
+ self.team.save(update_fields=["api_token"])
+ elif revoked == "inactive_organization":
+ self.organization.is_active = False
+ self.organization.save(update_fields=["is_active"])
+ elif revoked == "organization_with_unknown_active_state":
+ self.organization.is_active = None
+ self.organization.save(update_fields=["is_active"])
+ elif revoked == "organization_pending_deletion":
+ self.organization.is_pending_deletion = True
+ self.organization.save(update_fields=["is_pending_deletion"])
+ else:
+ OrganizationDomain.objects.create(
+ domain="example.com", organization=self.organization, verified_at=timezone.now()
+ )
+ self.organization.enforce_verified_domains = True
+ self.organization.save(update_fields=["enforce_verified_domains"])
+
+ self.assertEqual(
+ self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization).status_code, expected_status
+ )
+
+ @parameterized.expand([(None,), (PosthogJwtAudience.IMPERSONATED_USER,)])
+ def test_rejects_other_authentication(self, audience: PosthogJwtAudience | None) -> None:
+ authorization = f"Bearer {self._token(audience)}" if audience else ""
+ self.assertEqual(
+ self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization).status_code, 401
+ )
diff --git a/posthog/urls.py b/posthog/urls.py
index d3114a03a4bf..8ff80224d8f8 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -24,6 +24,7 @@ from posthog.api import (
)
from posthog.api.github_callback.views import github_oauth_callback, github_setup_callback
from posthog.api.integration_connect import integration_connect_redirect
+from posthog.api.livestream import LivestreamAuthorizationView
from posthog.api.oauth.connected_apps import ConnectedAppsViewSet
from posthog.api.oauth.toolbar_views import authorize_and_redirect
from posthog.api.sdk_health import sdk_health
@@ -97,6 +98,7 @@ from .views import (
github_app_webhook = build_webhook_view(build_github_provider("posthog"))
urlpatterns = [
+ path("api/livestream/authorize/", LivestreamAuthorizationView.as_view(), name="livestream-authorize"),
# EU spend must precede both the API router and the API fallback.
*(
[