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(exports): preserve authorization in worker requests (#86637)

Matt Pua4abe0282200c
diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.py
index bbfe720a8663..698f6b7da938 100644
--- a/posthog/api/advanced_activity_logs/viewset.py
+++ b/posthog/api/advanced_activity_logs/viewset.py
@@ -33,6 +33,7 @@ from posthog.permissions import PremiumFeaturePermission
from posthog.tasks import exporter
from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.source_authentication import get_export_source_authentication
from .field_discovery import AdvancedActivityLogFieldDiscovery
from .filters import AdvancedActivityLogFilterManager, validate_detail_filters
@@ -675,7 +676,7 @@ class AdvancedActivityLogsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
available_filters = self.field_discovery.get_available_filters(queryset)
return Response(available_filters)
- @action(detail=False, methods=["POST"])
+ @action(detail=False, methods=["POST"], required_scopes=["activity_log:read"])
def export(self, request, **kwargs):
export_format = request.data.get("format", "csv")
@@ -707,6 +708,12 @@ class AdvancedActivityLogsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
try:
serializable_filters = self._make_filters_serializable(filters_serializer.validated_data)
filename = self._generate_export_filename(serializable_filters, export_format)
+ source_authentication = get_export_source_authentication(request.successful_authenticator)
+ if source_authentication is None:
+ return Response(
+ {"error": "Exports from API endpoints do not support this authentication method."},
+ status=400,
+ )
exported_asset = ExportedAsset.objects.create(
team=self.team,
@@ -718,6 +725,7 @@ class AdvancedActivityLogsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"filename": filename,
},
created_by=request.user,
+ **source_authentication,
)
exporter.export_asset.delay(exported_asset.id)
diff --git a/posthog/api/query.py b/posthog/api/query.py
index e5ad534330f1..29cc5cc779ee 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -184,7 +184,7 @@ _QUERY_KIND_SCOPES: dict[str, list[str]] = {
}
-def _required_scopes_for_query_payload(query: object) -> list[str] | None:
+def required_scopes_for_query_payload(query: object) -> list[str] | None:
current_query = query
while isinstance(current_query, dict):
kind = current_query.get("kind")
@@ -211,7 +211,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
if getattr(view, "action", None) != "create":
return None
query = request.data.get("query") if isinstance(request.data, dict) else None
- return _required_scopes_for_query_payload(query)
+ return required_scopes_for_query_payload(query)
def get_throttles(self):
if self.action == "draft_sql":
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index 12dc9db8fd7f..e60aa367a6ea 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -14,6 +14,8 @@ from rest_framework_extensions.settings import extensions_api_settings
from posthog.api.utils import get_token
from posthog.auth import (
+ DelegatedOAuthAccessTokenAuthentication,
+ DelegatedPersonalAPIKeyAuthentication,
IDJagAccessTokenAuthentication,
InternalAPIAuthentication,
JwtAuthentication,
@@ -299,6 +301,8 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
# rejected before its own authenticator could run. IDJagAccessTokenAuthentication
# has a strict `typ == "at+jwt"` precheck and cleanly defers for other JWTs.
IDJagAccessTokenAuthentication,
+ DelegatedPersonalAPIKeyAuthentication,
+ DelegatedOAuthAccessTokenAuthentication,
JwtAuthentication,
OAuthAccessTokenAuthentication,
PersonalAPIKeyAuthentication,
diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.py
index 3a9ab6914de6..92f7cb28bdc2 100644
--- a/posthog/api/test/test_activity_log.py
+++ b/posthog/api/test/test_activity_log.py
@@ -18,6 +18,8 @@ from posthog.models.activity_logging.activity_log import ActivityLog, Detail, lo
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from products.exports.backend.models.exported_asset import ExportedAsset
+
def _feature_flag_json_payload(key: str) -> dict:
return {
@@ -491,3 +493,20 @@ class TestActivityLogBearerAuthAttribution(APIBaseTest):
assert log.user == self.user
assert log.was_impersonated is True
+
+ @patch("posthog.api.advanced_activity_logs.viewset.exporter.export_asset.delay")
+ def test_activity_log_export_preserves_oauth_authorization(self, _mock_exporter_task) -> None:
+ token = self._create_oauth_token()
+ token.scope = "activity_log:read"
+ token.save(update_fields=["scope"])
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/advanced_activity_logs/export/",
+ {"format": "csv"},
+ headers={"authorization": f"Bearer {token.token}"},
+ )
+
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ exported_asset = ExportedAsset.objects.get(id=response.json()["id"])
+ assert exported_asset.source_authentication == ExportedAsset.SourceAuthentication.OAUTH_ACCESS_TOKEN
+ assert exported_asset.source_credential_id == str(token.id)
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index 805e711b26a8..06e775c921c5 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -959,7 +959,7 @@ class TestPersonalAPIKeysWithActivityLogCustomActions(PersonalAPIKeysBaseTest):
response = self._do_request(f"/api/projects/{self.team.id}/advanced_activity_logs/available_filters/")
assert response.status_code == status.HTTP_200_OK
- def test_forbids_export_even_with_write_scope(self):
+ def test_allows_export_with_write_scope(self):
self.key.scopes = ["activity_log:write"]
self.key.save()
response = self.client.post(
@@ -968,8 +968,7 @@ class TestPersonalAPIKeysWithActivityLogCustomActions(PersonalAPIKeysBaseTest):
headers={"authorization": f"Bearer {self.value}"},
content_type="application/json",
)
- assert response.status_code == status.HTTP_403_FORBIDDEN
- assert response.json()["detail"] == "This action does not support personal API key access"
+ assert response.status_code == status.HTTP_202_ACCEPTED
def test_denies_available_filters_with_unrelated_scope(self):
self.key.scopes = ["feature_flag:read"]
diff --git a/posthog/auth.py b/posthog/auth.py
index 521f2b2c3fc5..852aa6916d70 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -484,8 +484,7 @@ class JwtAuthentication(authentication.BaseAuthentication):
keyword = "Bearer"
- @classmethod
- def authenticate(cls, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
+ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
with tracer.start_as_current_span("posthog.auth.jwt"):
if "authorization" in request.headers:
authorization_match = re.match(rf"^Bearer\s+(\S.+)$", request.headers["authorization"])
@@ -495,6 +494,8 @@ class JwtAuthentication(authentication.BaseAuthentication):
info = decode_jwt(token, PosthogJwtAudience.IMPERSONATED_USER)
user = User.objects.get(pk=info["id"])
return (user, None)
+ except AuthenticationFailed:
+ raise
except jwt.DecodeError:
# If it doesn't look like a JWT then we allow the PersonalAPIKeyAuthentication to have a go
return None
@@ -958,6 +959,84 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
return self.keyword
+def _decode_delegated_user_token(request: Union[HttpRequest, Request]) -> dict[str, Any] | None:
+ authorization = request.headers.get("authorization")
+ if not authorization:
+ return None
+ authorization_match = re.match(r"^Bearer\s+(\S.+)$", authorization)
+ if not authorization_match:
+ return None
+ try:
+ return decode_jwt(authorization_match.group(1).strip(), PosthogJwtAudience.DELEGATED_USER)
+ except (jwt.DecodeError, jwt.InvalidAudienceError):
+ return None
+ except jwt.InvalidTokenError as error:
+ raise AuthenticationFailed(detail="Token invalid.") from error
+
+
+class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):
+ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
+ claims = _decode_delegated_user_token(request)
+ if claims is None:
+ return None
+ personal_api_key_id = claims.get("personal_api_key_id")
+ if not personal_api_key_id:
+ return None
+ try:
+ personal_api_key = PersonalAPIKey.objects.select_related("user").get(
+ id=personal_api_key_id,
+ user_id=claims["id"],
+ user__is_active=True,
+ )
+ except (KeyError, PersonalAPIKey.DoesNotExist) as error:
+ raise AuthenticationFailed(detail="Source personal API key is no longer valid.") from error
+
+ self.personal_api_key = personal_api_key
+ tag_authentication(
+ user_id=personal_api_key.user.pk,
+ team_id=personal_api_key.user.current_team_id,
+ access_method=AccessMethod.PERSONAL_API_KEY,
+ api_key_mask=personal_api_key.mask_value,
+ api_key_label=personal_api_key.label,
+ )
+ if activity_storage.is_request_scoped():
+ activity_storage.set_user(personal_api_key.user)
+ return personal_api_key.user, None
+
+
+class DelegatedOAuthAccessTokenAuthentication(OAuthAccessTokenAuthentication):
+ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
+ claims = _decode_delegated_user_token(request)
+ if claims is None:
+ return None
+ oauth_access_token_id = claims.get("oauth_access_token_id")
+ if not oauth_access_token_id:
+ return None
+ try:
+ access_token = OAuthAccessToken.objects.select_related("user", "application").get(
+ id=oauth_access_token_id,
+ user_id=claims["id"],
+ user__is_active=True,
+ application__isnull=False,
+ expires__gt=timezone.now(),
+ )
+ except (KeyError, OAuthAccessToken.DoesNotExist) as error:
+ raise AuthenticationFailed(detail="Source OAuth access token is no longer valid.") from error
+
+ self._enforce_toolbar_access(access_token)
+ self.access_token = access_token
+ tag_authentication(
+ user_id=access_token.user.pk,
+ team_id=access_token.user.current_team_id,
+ access_method=AccessMethod.OAUTH,
+ )
+ if activity_storage.is_request_scoped():
+ activity_storage.set_user(access_token.user)
+ if access_token.impersonated_by_id is not None:
+ activity_storage.set_was_impersonated(True)
+ return access_token.user, None
+
+
class WidgetAuthentication(authentication.BaseAuthentication):
"""
Authenticate widget requests via conversations_settings.widget_public_token.
diff --git a/posthog/jwt.py b/posthog/jwt.py
index edc257ea15ce..d7c2c0a4e906 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -15,6 +15,7 @@ class PosthogJwtAudience(Enum):
UNSUBSCRIBE = "posthog:unsubscribe"
EXPORTED_ASSET = "posthog:exported_asset"
IMPERSONATED_USER = "posthog:impersonted_user"
+ DELEGATED_USER = "posthog:delegated_user"
EXPORT_RENDERER = "posthog:export_renderer"
LIVESTREAM = "posthog:livestream"
SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"
diff --git a/posthog/permissions.py b/posthog/permissions.py
index bbcac70d574c..3947eda90930 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -17,6 +17,7 @@ from rest_framework.viewsets import ViewSet
from posthog.auth import (
IDJagAccessTokenAuthentication,
+ JwtAuthentication,
OAuthAccessTokenAuthentication,
PersonalAPIKeyAuthentication,
ProjectSecretAPIKeyAuthentication,
@@ -30,6 +31,8 @@ from posthog.constants import AvailableFeature
from posthog.exceptions import Conflict, EnterpriseFeatureException, PaidFeatureException
from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, is_enforcement_disable_request
from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Project, Team, User
+from posthog.models.oauth import OAuthAccessToken
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl, ordered_access_levels
from posthog.scopes import (
INTERNAL_API_SCOPE_OBJECTS,
@@ -611,6 +614,14 @@ class ScopeBasePermission(BasePermission):
return None
+def get_authenticator_user_credential(authenticator: object) -> PersonalAPIKey | OAuthAccessToken | None:
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ return authenticator.personal_api_key
+ if isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return authenticator.access_token
+ return None
+
+
def get_authenticator_scopes(authenticator) -> list[str] | None:
"""The API scopes carried by a scoped-token authenticator, or None for session and
other non-token auth. Single source of truth for the token->scopes mapping, shared by
@@ -619,7 +630,6 @@ def get_authenticator_scopes(authenticator) -> list[str] | None:
if isinstance(authenticator, PersonalAPIKeyAuthentication):
return list(authenticator.personal_api_key.scopes or [])
if isinstance(authenticator, OAuthAccessTokenAuthentication):
- # OAuth tokens store scopes as a space-separated string.
return str(authenticator.access_token.scope or "").split()
if isinstance(authenticator, IDJagAccessTokenAuthentication):
return list(authenticator.scopes or [])
@@ -635,10 +645,9 @@ def get_authenticator_scoped_organization_ids(authenticator) -> list[str] | None
The organization-level counterpart of `get_authenticator_scoped_team_ids`. Both exist so that a
check outside `TeamAndOrgViewSetMixin` reads a credential's reach from one place.
"""
- if isinstance(authenticator, PersonalAPIKeyAuthentication):
- return list(authenticator.personal_api_key.scoped_organizations or []) or None
- if isinstance(authenticator, OAuthAccessTokenAuthentication):
- return list(authenticator.access_token.scoped_organizations or []) or None
+ credential = get_authenticator_user_credential(authenticator)
+ if credential is not None:
+ return list(credential.scoped_organizations or []) or None
if isinstance(authenticator, IDJagAccessTokenAuthentication):
# An ID-JAG access token is bound to the one PostHog organization whose OrganizationDomain
# pinned the trusted IdP, carried in the `org_id` claim. Confining it to that organization
@@ -656,10 +665,9 @@ def get_authenticator_scoped_team_ids(authenticator) -> list[int] | None:
check that has to re-derive a credential's reach outside `TeamAndOrgViewSetMixin` reads both
legs from one place.
"""
- if isinstance(authenticator, PersonalAPIKeyAuthentication):
- return list(authenticator.personal_api_key.scoped_teams or []) or None
- if isinstance(authenticator, OAuthAccessTokenAuthentication):
- return list(authenticator.access_token.scoped_teams or []) or None
+ credential = get_authenticator_user_credential(authenticator)
+ if credential is not None:
+ return list(credential.scoped_teams or []) or None
return None
@@ -782,7 +790,10 @@ class APIScopePermission(ScopeBasePermission):
authenticator = request.successful_authenticator
if not isinstance(
authenticator,
- OAuthAccessTokenAuthentication | PersonalAPIKeyAuthentication | IDJagAccessTokenAuthentication,
+ OAuthAccessTokenAuthentication
+ | PersonalAPIKeyAuthentication
+ | JwtAuthentication
+ | IDJagAccessTokenAuthentication,
):
raise ValueError("Unexpected authentication type")
@@ -821,7 +832,8 @@ class APIScopePermission(ScopeBasePermission):
Admins can always use personal API keys regardless of the organization setting.
"""
# Only applies to personal API keys — OAuth tokens are exempt.
- if not isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication):
+ credential = get_authenticator_user_credential(request.successful_authenticator)
+ if not isinstance(credential, PersonalAPIKey):
return
try:
diff --git a/posthog/tasks/exporter.py b/posthog/tasks/exporter.py
index 1d4212440c8c..e67d4f890a06 100644
--- a/posthog/tasks/exporter.py
+++ b/posthog/tasks/exporter.py
@@ -12,6 +12,7 @@ from posthog.tasks.utils import CeleryQueue
from products.exports.backend.facade.exporters import get_export_format_handler
from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.source_authentication import assert_export_authorization
from products.exports.backend.tasks.failure_handler import (
USER_QUERY_ERRORS,
InvalidExportContext,
@@ -120,6 +121,7 @@ def export_asset_direct(
export_source = source or EventSource.EXPORT
try:
+ assert_export_authorization(exported_asset)
if exported_asset.export_format in (ExportedAsset.ExportFormat.CSV, ExportedAsset.ExportFormat.XLSX):
csv_exporter.export_tabular(exported_asset, limit=limit, source=export_source)
elif exported_asset.export_format == ExportedAsset.ExportFormat.JSONL:
diff --git a/posthog/tasks/test/test_exporter.py b/posthog/tasks/test/test_exporter.py
index 15d410d98efe..8f91fd0065d9 100644
--- a/posthog/tasks/test/test_exporter.py
+++ b/posthog/tasks/test/test_exporter.py
@@ -11,6 +11,8 @@ from parameterized import parameterized
from posthog.hogql.errors import QueryError
from posthog.exceptions import ClickHouseAtCapacity
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.tasks import exporter
from products.dashboards.backend.models.dashboard import Dashboard
@@ -81,6 +83,33 @@ class TestExporterTask(APIBaseTest):
assert self.exported_asset.content is None
assert self.exported_asset.content_location is not None
+ @patch("products.exports.backend.tasks.image_exporter.export_image")
+ def test_exporter_rechecks_typed_export_scopes(self, mock_export: MagicMock, mock_uuid: MagicMock) -> None:
+ personal_api_key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="typed export key",
+ secure_value=hash_key_value(generate_random_token_personal()),
+ scopes=["export:write"],
+ scoped_teams=[self.team.id],
+ )
+ asset = ExportedAsset.objects.create(
+ team=self.team,
+ dashboard=self.exported_asset.dashboard,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ created_by=self.user,
+ source_authentication=ExportedAsset.SourceAuthentication.PERSONAL_API_KEY,
+ source_credential_id=personal_api_key.id,
+ )
+
+ exporter.export_asset(asset.id)
+
+ mock_export.assert_not_called()
+ asset.refresh_from_db()
+ assert (
+ asset.exception
+ == "This export could not verify its original authorization. Create a new export and try again."
+ )
+
@patch("products.exports.backend.tasks.image_exporter.export_image")
def test_export_stores_exception_type_on_failure(self, mock_export: MagicMock, mock_uuid: MagicMock) -> None:
mock_export.side_effect = QueryError("Unknown table 'foo'")
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
index 306f4ec434d2..9c119be4143e 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -14,6 +14,7 @@ from posthog.storage import object_storage
from products.exports.backend.analytics import capture_export_event
from products.exports.backend.models.exported_asset import ExportedAsset, is_valid_session_recording_id
+from products.exports.backend.source_authentication import assert_export_authorization
from ..types import (
RASTERIZE_RENDER_MAX_ATTEMPTS,
@@ -55,6 +56,10 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
close_old_connections()
asset = ExportedAsset.objects.select_related("team__organization", "created_by").get(pk=exported_asset_id)
+ try:
+ assert_export_authorization(asset)
+ except ValueError as error:
+ raise ApplicationError(str(error), non_retryable=True) from error
ctx = asset.export_context or {}
session_id = ctx.get("session_recording_id")
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
index c14f20202fce..26d1c395102e 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -51,6 +51,7 @@ def _make_asset(
asset.export_context = export_context
asset.export_format = export_format
asset.content_location = content_location
+ asset.source_authentication = None
asset.save = MagicMock()
return asset
diff --git a/posthog/test/test_auth_spans.py b/posthog/test/test_auth_spans.py
index 3fd25f3b58d1..dec489ace4db 100644
--- a/posthog/test/test_auth_spans.py
+++ b/posthog/test/test_auth_spans.py
@@ -76,7 +76,7 @@ class TestAuthSpans(BaseTest):
(
"jwt_no_authorization_header",
lambda factory: factory.get("/api/users/@me/"),
- lambda req: JwtAuthentication.authenticate(req),
+ lambda req: JwtAuthentication().authenticate(req),
"posthog.auth.jwt",
),
(
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index 4cc7a182ccbe..a18c2bd8bc9c 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -9,13 +9,17 @@ from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
+from rest_framework import status
from rest_framework.test import APIRequestFactory
from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, TeamSecretTokenAuthentication
from posthog.constants import AvailableFeature
+from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import Organization, Team, User
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.permissions import AccessControlPermission, PostHogFeatureFlagPermission
from posthog.rbac.user_access_control import UserAccessControl
@@ -676,6 +680,115 @@ class TestTeamMemberAccessPermission(BaseTest):
self.assertTrue(result)
+class TestDelegatedJwtPermissions(BaseTest):
+ def _create_delegated_token(
+ self,
+ source_authentication: str,
+ scopes: list[str],
+ scoped_teams: list[int] | None = None,
+ scoped_organizations: list[str] | None = None,
+ ) -> tuple[str, PersonalAPIKey | OAuthAccessToken]:
+ token_payload: dict[str, str | int] = {"id": self.user.id}
+ if source_authentication == "personal_api_key":
+ credential: PersonalAPIKey | OAuthAccessToken = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="delegated credential",
+ secure_value=hash_key_value(generate_random_token_personal()),
+ scopes=scopes,
+ scoped_teams=scoped_teams,
+ scoped_organizations=scoped_organizations,
+ )
+ token_payload["personal_api_key_id"] = credential.id
+ else:
+ application = OAuthApplication.objects.create(
+ name="Delegated credential test",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ credential = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token="pha_delegated_credential_test",
+ expires=timezone.now() + timedelta(hours=1),
+ scope=" ".join(scopes),
+ scoped_teams=scoped_teams,
+ scoped_organizations=scoped_organizations,
+ )
+ token_payload["oauth_access_token_id"] = str(credential.id)
+
+ worker_token = encode_jwt(
+ token_payload,
+ timedelta(minutes=15),
+ PosthogJwtAudience.DELEGATED_USER,
+ )
+ return worker_token, credential
+
+ @parameterized.expand([("personal_api_key",), ("oauth_access_token",)])
+ def test_delegated_jwt_cannot_exceed_source_scope(self, source_authentication: str) -> None:
+ worker_token, _credential = self._create_delegated_token(
+ source_authentication,
+ scopes=["export:write"],
+ scoped_teams=[self.team.id],
+ )
+
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/invites/",
+ {"target_email": "[email protected]", "level": 8, "send_email": False},
+ headers={"authorization": f"Bearer {worker_token}"},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_delegated_jwt_fails_after_source_personal_api_key_is_revoked(self) -> None:
+ worker_token, credential = self._create_delegated_token(
+ "personal_api_key",
+ scopes=["feature_flag:read"],
+ )
+ credential.delete()
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ headers={"authorization": f"Bearer {worker_token}"},
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_delegated_jwt_cannot_exceed_source_project_restriction(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+ worker_token, _credential = self._create_delegated_token(
+ "personal_api_key",
+ scopes=["*"],
+ scoped_teams=[self.team.id],
+ )
+
+ response = self.client.get(
+ f"/api/projects/{other_team.id}/feature_flags/",
+ headers={"authorization": f"Bearer {worker_token}"},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_delegated_personal_api_key_filters_organization_list(self) -> None:
+ other_organization, _, _ = Organization.objects.bootstrap(self.user)
+ worker_token, _credential = self._create_delegated_token(
+ "personal_api_key",
+ scopes=["*"],
+ scoped_organizations=[str(other_organization.id)],
+ )
+
+ response = self.client.get(
+ "/api/organizations/",
+ headers={"authorization": f"Bearer {worker_token}"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert {organization["id"] for organization in response.json()["results"]} == {str(other_organization.id)}
+
+
class TestOAuthAccessTokenAPIScopePermission(BaseTest):
"""Test that OAuth access tokens properly enforce API scopes via APIScopePermission"""
diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.py
index ece9496ca829..01a0f4c9276e 100644
--- a/products/exports/backend/api/exports.py
+++ b/products/exports/backend/api/exports.py
@@ -41,6 +41,10 @@ from products.exports.backend.models.exported_asset import (
get_content_response,
is_valid_session_recording_id,
)
+from products.exports.backend.source_authentication import (
+ get_export_source_authentication,
+ required_scopes_for_export_target,
+)
from products.exports.backend.stuck_exports import STUCK_EXPORT_MESSAGE, is_stuck_export
from products.product_analytics.backend.facade.models import Insight
@@ -118,6 +122,12 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
raise ValidationError({"insight": ["This insight does not belong to your team."]})
export_context = data.get("export_context") or {}
+ if export_context.get("path") and (
+ str(export_context.get("method", "GET")).upper() != "GET" or export_context.get("body") is not None
+ ):
+ raise ValidationError(
+ {"export_context": ["Exports from API endpoints only support GET requests without a request body."]}
+ )
# Truthiness, not `is not None`: an absent or empty id is a no-op everywhere downstream,
# and rejecting it here would 400 exports that never touch a recording.
session_recording_id = export_context.get("session_recording_id")
@@ -195,6 +205,13 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode
def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> ExportedAsset:
request = self.context["request"]
+ source_authentication = get_export_source_authentication(request.successful_authenticator)
+ if source_authentication is not None:
+ validated_data.update(source_authentication)
+ else:
+ raise ValidationError(
+ {"export_context": ["Exports from API endpoints do not support this authentication method."]}
+ )
self._assert_may_export_session_recording(validated_data)
return self._create_asset(validated_data, user=request.user, reason=None)
@@ -480,6 +497,16 @@ class ExportedAssetViewSet(
queryset = ExportedAsset.objects.select_related("dashboard", "insight").order_by("-created_at")
serializer_class = ExportedAssetSerializer
+ def dangerously_get_required_scopes(self, request: Request, view) -> list[str] | None:
+ if self.action != "create":
+ return None
+ export_context = request.data.get("export_context") if isinstance(request.data, dict) else None
+ return required_scopes_for_export_target(
+ insight_id=request.data.get("insight") if isinstance(request.data, dict) else None,
+ dashboard_id=request.data.get("dashboard") if isinstance(request.data, dict) else None,
+ export_context=export_context if isinstance(export_context, dict) else None,
+ )
+
def get_serializer_class(self) -> type[serializers.BaseSerializer]:
return ExportedAssetCreateSerializer if self.action == "create" else ExportedAssetSerializer
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index d47e0c06deba..5bcfc4fda9aa 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -1,6 +1,6 @@
from contextlib import nullcontext
from datetime import datetime, timedelta
-from typing import Optional
+from typing import Literal, Optional
import pytest
from freezegun import freeze_time
@@ -22,8 +22,10 @@ from posthog.hogql.errors import QueryError
from posthog.exceptions import ClickHouseAtCapacity
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.filters.filter import Filter
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.settings import (
HOGQL_INCREASED_MAX_EXECUTION_TIME,
OBJECT_STORAGE_ACCESS_KEY_ID,
@@ -38,6 +40,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.exports.backend.facade.api import EXPORT_WORKFLOW_TIMEOUT
from products.exports.backend.models.exported_asset import DATASET_EXPORT_KIND, ExportedAsset
+from products.exports.backend.source_authentication import required_scopes_for_export_target
from products.exports.backend.tasks.failure_handler import FAILURE_TYPE_SYSTEM, FAILURE_TYPE_USER
from products.exports.backend.tasks.image_exporter import export_image
from products.product_analytics.backend.facade.models import Insight
@@ -76,6 +79,13 @@ class TestExports(APIBaseTest):
bucket = s3.Bucket(OBJECT_STORAGE_BUCKET)
bucket.objects.filter(Prefix=TEST_ROOT_BUCKET).delete()
+ def test_heatmap_export_requires_heatmap_scope(self) -> None:
+ assert required_scopes_for_export_target(
+ insight_id=None,
+ dashboard_id=None,
+ export_context={"heatmap_url": "https://example.com/page"},
+ ) == ["export:write", "heatmap:read"]
+
insight_filter_dict = {
"events": [{"id": "$pageview"}],
"properties": [{"key": "$browser", "value": "Mac OS X"}],
@@ -97,6 +107,122 @@ class TestExports(APIBaseTest):
team=cls.team, dashboard_id=cls.dashboard.id, export_format="image/png", created_by=cls.user
)
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_api_path_export_rejects_mutating_requests(self, mock_exporter_task) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports/",
+ {
+ "export_format": "text/csv",
+ "export_context": {
+ "path": f"/api/organizations/{self.organization.id}/invites/",
+ "method": "POST",
+ "body": {"target_email": "[email protected]", "level": 8},
+ },
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_exporter_task.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("missing_query_scope", ["export:write"], status.HTTP_403_FORBIDDEN),
+ ("query_scope", ["export:write", "query:read"], status.HTTP_201_CREATED),
+ ]
+ )
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_query_export_requires_query_scope(
+ self, _name: str, scopes: list[str], expected_status: int, mock_exporter_task
+ ) -> None:
+ token = generate_random_token_personal()
+ personal_api_key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="query export key",
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ scoped_teams=[self.team.id],
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports/",
+ {
+ "export_format": "text/csv",
+ "export_context": {"source": {"kind": "HogQLQuery", "query": "select 1"}},
+ },
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == expected_status
+ if expected_status == status.HTTP_201_CREATED:
+ exported_asset = ExportedAsset.objects.get(id=response.json()["id"])
+ assert exported_asset.source_authentication == ExportedAsset.SourceAuthentication.PERSONAL_API_KEY
+ assert exported_asset.source_credential_id == personal_api_key.id
+ mock_exporter_task.assert_called_once()
+ else:
+ mock_exporter_task.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("insight_missing_scope", "insight", ["export:write"], status.HTTP_403_FORBIDDEN),
+ (
+ "insight_read_scope",
+ "insight",
+ ["export:write", "insight:read"],
+ status.HTTP_201_CREATED,
+ ),
+ ("dashboard_missing_scope", "dashboard", ["export:write"], status.HTTP_403_FORBIDDEN),
+ (
+ "dashboard_read_scope",
+ "dashboard",
+ ["export:write", "dashboard:read"],
+ status.HTTP_201_CREATED,
+ ),
+ ("recording_missing_scope", "recording", ["export:write"], status.HTTP_403_FORBIDDEN),
+ (
+ "recording_read_scope",
+ "recording",
+ ["export:write", "session_recording:read"],
+ status.HTTP_201_CREATED,
+ ),
+ ]
+ )
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_typed_export_requires_resource_read_scope(
+ self,
+ _name: str,
+ target: Literal["insight", "dashboard", "recording"],
+ scopes: list[str],
+ expected_status: int,
+ mock_exporter_task,
+ ) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="typed export key",
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ scoped_teams=[self.team.id],
+ )
+ payload: dict[str, object] = {"export_format": ExportedAsset.ExportFormat.PNG}
+ if target == "insight":
+ payload["insight"] = self.insight.id
+ elif target == "dashboard":
+ payload["dashboard"] = self.dashboard.id
+ else:
+ payload["export_context"] = {"session_recording_id": "typed-export-recording"}
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/exports/",
+ payload,
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == expected_status
+ if expected_status == status.HTTP_201_CREATED:
+ mock_exporter_task.assert_called_once()
+ else:
+ mock_exporter_task.assert_not_called()
+
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
def test_can_create_new_valid_export_dashboard(self, mock_exporter_task) -> None:
# add filter to dashboard
@@ -172,9 +298,7 @@ class TestExports(APIBaseTest):
assert mock_exporter_task.call_args[0][0].id == data["id"]
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
- def test_swallow_missing_schema_and_allow_front_end_to_poll(self, mock_exporter_task) -> None:
- # regression test see https://github.com/PostHog/posthog/issues/11204
-
+ def test_accepts_legacy_insight_api_path_export(self, mock_exporter_task) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/exports",
{
@@ -184,14 +308,8 @@ class TestExports(APIBaseTest):
},
},
)
- self.assertEqual(
- response.status_code,
- status.HTTP_201_CREATED,
- msg=f"was not HTTP 201 😱 - {response.json()}",
- )
- data = response.json()
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
mock_exporter_task.assert_called_once()
- assert mock_exporter_task.call_args[0][0].id == data["id"]
@patch("products.exports.backend.tasks.image_exporter._export_to_png")
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
@@ -458,9 +576,8 @@ class TestExports(APIBaseTest):
},
)
- @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
@patch("products.exports.backend.tasks.csv_exporter.requests.request")
- def test_can_download_a_csv(self, patched_request, _mock_workflow) -> None:
+ def test_can_download_a_csv(self, patched_request) -> None:
with self.settings(SITE_URL="http://testserver", OBJECT_STORAGE_ENABLED=False):
_create_event(
event="event_name",
@@ -502,36 +619,29 @@ class TestExports(APIBaseTest):
patched_request.side_effect = requests_side_effect
- response = self.client.post(
- f"/api/projects/{self.team.id}/exports",
- {
- "export_format": "text/csv",
- "export_context": {
- "path": "&".join(
- [
- f"/api/projects/{self.team.id}/events?orderBy=%5B%22-timestamp%22%5D",
- "properties=%5B%7B%22key%22%3A%22%24browser%22%2C%22value%22%3A%5B%22Safari%22%5D%2C%22operator%22%3A%22exact%22%2C%22type%22%3A%22event%22%7D%5D",
- f"after={after}",
- ]
- )
- },
- },
+ path = "&".join(
+ [
+ f"/api/projects/{self.team.id}/events?orderBy=%5B%22-timestamp%22%5D",
+ "properties=%5B%7B%22key%22%3A%22%24browser%22%2C%22value%22%3A%5B%22Safari%22%5D%2C%22operator%22%3A%22exact%22%2C%22type%22%3A%22event%22%7D%5D",
+ f"after={after}",
+ ]
)
- self.assertEqual(
- response.status_code,
- status.HTTP_201_CREATED,
- msg=f"was not HTTP 201 😱 - {response.json()}",
+ instance = ExportedAsset.objects.create(
+ team=self.team,
+ created_by=self.user,
+ export_format=ExportedAsset.ExportFormat.CSV,
+ export_context={"path": path},
+ source_authentication=ExportedAsset.SourceAuthentication.SESSION,
)
- instance = response.json()
# limit the query to force it to page against the API
- exporter.export_asset(instance["id"], limit=1)
+ exporter.export_asset(instance.id, limit=1)
download_response: Optional[HttpResponse] = None
attempt_count = 0
while attempt_count < 10 and not download_response:
download_response = self.client.get(
- f"/api/projects/{self.team.id}/exports/{instance['id']}/content?download=true"
+ f"/api/projects/{self.team.id}/exports/{instance.id}/content?download=true"
)
attempt_count += 1
@@ -1776,11 +1886,9 @@ class TestExportMixin(APIBaseTest):
"""
Use this function to test the CSV output of exports in other tests
"""
+ path = "/" + path.lstrip("/")
with self.settings(SITE_URL="http://testserver", OBJECT_STORAGE_ENABLED=False):
- with (
- patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request,
- patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow"),
- ):
+ with patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request:
def requests_side_effect(*args, **kwargs):
response = self.client.get(kwargs["url"], kwargs["json"], **kwargs["headers"])
@@ -1794,21 +1902,17 @@ class TestExportMixin(APIBaseTest):
patched_request.side_effect = requests_side_effect
- response = self.client.post(
- f"/api/projects/{self.team.pk}/exports/",
- {
- "export_context": {
- "path": path,
- },
- "export_format": "text/csv",
- },
+ asset = ExportedAsset.objects.create(
+ team=self.team,
+ created_by=self.user,
+ export_context={"path": path},
+ export_format=ExportedAsset.ExportFormat.CSV,
+ source_authentication=ExportedAsset.SourceAuthentication.SESSION,
)
- # Workflow is mocked so the export content isn't generated during
- # the POST. Run the exporter directly to produce CSV content.
- exporter.export_asset(response.json()["id"])
+ exporter.export_asset(asset.id)
download_response = self.client.get(
- f"/api/projects/{self.team.id}/exports/{response.json()['id']}/content?download=true"
+ f"/api/projects/{self.team.id}/exports/{asset.id}/content?download=true"
)
return [str(x) for x in download_response.content.splitlines()]
diff --git a/products/exports/backend/migrations/0008_exportedasset_source_authentication.py b/products/exports/backend/migrations/0008_exportedasset_source_authentication.py
new file mode 100644
index 000000000000..71aecb15a7d7
--- /dev/null
+++ b/products/exports/backend/migrations/0008_exportedasset_source_authentication.py
@@ -0,0 +1,27 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("exports", "0007_alter_exportedasset_export_format")]
+
+ operations = [
+ migrations.AddField(
+ model_name="exportedasset",
+ name="source_authentication",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("session", "Session"),
+ ("personal_api_key", "Personal API key"),
+ ("oauth_access_token", "OAuth access token"),
+ ],
+ max_length=32,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="exportedasset",
+ name="source_credential_id",
+ field=models.CharField(blank=True, max_length=50, null=True),
+ ),
+ ]
diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txt
index 8c588ff14210..36df3d5c6719 100644
--- a/products/exports/backend/migrations/max_migration.txt
+++ b/products/exports/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_alter_exportedasset_export_format
+0008_exportedasset_source_authentication
diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.py
index 8ea55a428c8e..8629f02f1a00 100644
--- a/products/exports/backend/models/exported_asset.py
+++ b/products/exports/backend/models/exported_asset.py
@@ -59,6 +59,11 @@ class ExportedAssetManager(models.Manager):
class ExportedAsset(models.Model):
+ class SourceAuthentication(models.TextChoices):
+ SESSION = "session"
+ PERSONAL_API_KEY = "personal_api_key", "Personal API key"
+ OAUTH_ACCESS_TOKEN = "oauth_access_token", "OAuth access token"
+
class ExportFormat(models.TextChoices):
PNG = "image/png", "image/png"
PDF = "application/pdf", "application/pdf"
@@ -108,6 +113,8 @@ class ExportedAsset(models.Model):
# to allow for lazy deletes
expires_after = models.DateTimeField(null=True, blank=True)
created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True)
+ source_authentication = models.CharField(max_length=32, choices=SourceAuthentication.choices, null=True, blank=True)
+ source_credential_id = models.CharField(max_length=50, null=True, blank=True)
# for example holds filters for CSV exports
export_context = models.JSONField(null=True, blank=True)
# path in object storage or some other location identifier for the asset
diff --git a/products/exports/backend/source_authentication.py b/products/exports/backend/source_authentication.py
new file mode 100644
index 000000000000..77bb7259fd38
--- /dev/null
+++ b/products/exports/backend/source_authentication.py
@@ -0,0 +1,127 @@
+from typing import NoReturn
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.api.query import required_scopes_for_query_payload
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models.oauth import OAuthAccessToken
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.user_permissions import UserPermissions
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+
+logger = structlog.get_logger(__name__)
+
+
+def get_export_source_authentication(authenticator: object) -> dict[str, str] | None:
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ return {
+ "source_authentication": ExportedAsset.SourceAuthentication.PERSONAL_API_KEY,
+ "source_credential_id": authenticator.personal_api_key.id,
+ }
+ if isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return {
+ "source_authentication": ExportedAsset.SourceAuthentication.OAUTH_ACCESS_TOKEN,
+ "source_credential_id": str(authenticator.access_token.id),
+ }
+ if isinstance(authenticator, SessionAuthentication):
+ return {"source_authentication": ExportedAsset.SourceAuthentication.SESSION}
+ return None
+
+
+def required_scopes_for_export_target(
+ *, insight_id: object, dashboard_id: object, export_context: dict | None
+) -> list[str]:
+ scopes = ["export:write"]
+ if insight_id is not None:
+ scopes.append("insight:read")
+ if dashboard_id is not None:
+ scopes.append("dashboard:read")
+
+ context = export_context or {}
+ if context.get("session_recording_id"):
+ scopes.append("session_recording:read")
+ if context.get("heatmap_url"):
+ scopes.append("heatmap:read")
+ source = context.get("source")
+ if source is not None:
+ scopes.extend(required_scopes_for_query_payload(source) or ["query:read"])
+ return list(dict.fromkeys(scopes))
+
+
+def required_scopes_for_export(exported_asset: ExportedAsset) -> list[str]:
+ return required_scopes_for_export_target(
+ insight_id=exported_asset.insight_id,
+ dashboard_id=exported_asset.dashboard_id,
+ export_context=exported_asset.export_context,
+ )
+
+
+def _credential_has_required_scopes(granted_scopes: list[str], required_scopes: list[str]) -> bool:
+ if "*" in granted_scopes:
+ return True
+ for required_scope in required_scopes:
+ valid_scopes = [required_scope]
+ if required_scope.endswith(":read"):
+ valid_scopes.append(required_scope.replace(":read", ":write"))
+ if not any(scope in granted_scopes for scope in valid_scopes):
+ return False
+ return True
+
+
+def _raise_invalid_export_authorization(exported_asset: ExportedAsset, reason: str) -> NoReturn:
+ logger.error(
+ "export.invalid_authentication_source",
+ exported_asset_id=exported_asset.id,
+ reason=reason,
+ )
+ raise ValueError("This export could not verify its original authorization. Create a new export and try again.")
+
+
+def assert_export_authorization(exported_asset: ExportedAsset) -> None:
+ source_authentication = exported_asset.source_authentication
+ if source_authentication is None:
+ return
+ created_by = exported_asset.created_by
+ if created_by is None or not created_by.is_active:
+ _raise_invalid_export_authorization(exported_asset, "missing_export_creator")
+
+ if source_authentication == ExportedAsset.SourceAuthentication.PERSONAL_API_KEY:
+ credential = PersonalAPIKey.objects.filter(
+ id=exported_asset.source_credential_id,
+ user_id=created_by.id,
+ user__is_active=True,
+ ).first()
+ granted_scopes = list(credential.scopes or []) if credential is not None else []
+ elif source_authentication == ExportedAsset.SourceAuthentication.OAUTH_ACCESS_TOKEN:
+ credential = OAuthAccessToken.objects.filter(
+ id=exported_asset.source_credential_id,
+ user_id=created_by.id,
+ user__is_active=True,
+ application__isnull=False,
+ expires__gt=timezone.now(),
+ ).first()
+ granted_scopes = str(credential.scope or "").split() if credential is not None else []
+ elif source_authentication == ExportedAsset.SourceAuthentication.SESSION:
+ credential = None
+ granted_scopes = []
+ else:
+ _raise_invalid_export_authorization(exported_asset, "unsupported_authentication_source")
+
+ if source_authentication != ExportedAsset.SourceAuthentication.SESSION:
+ if credential is None:
+ _raise_invalid_export_authorization(exported_asset, "source_credential_invalid")
+ if not _credential_has_required_scopes(granted_scopes, required_scopes_for_export(exported_asset)):
+ _raise_invalid_export_authorization(exported_asset, "source_credential_lacks_required_scope")
+ if credential.scoped_teams and exported_asset.team_id not in credential.scoped_teams:
+ _raise_invalid_export_authorization(exported_asset, "source_credential_excludes_project")
+ if (
+ credential.scoped_organizations
+ and str(exported_asset.team.organization_id) not in credential.scoped_organizations
+ ):
+ _raise_invalid_export_authorization(exported_asset, "source_credential_excludes_organization")
+
+ if UserPermissions(user=created_by, team=exported_asset.team).current_team.effective_membership_level is None:
+ _raise_invalid_export_authorization(exported_asset, "creator_lacks_project_access")
diff --git a/products/exports/backend/tasks/csv_exporter.py b/products/exports/backend/tasks/csv_exporter.py
index 08f4438d933e..c0c4eba97d54 100644
--- a/products/exports/backend/tasks/csv_exporter.py
+++ b/products/exports/backend/tasks/csv_exporter.py
@@ -7,7 +7,7 @@ from collections import OrderedDict
from collections.abc import Generator, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
-from typing import Any, Optional, Protocol
+from typing import Any, NoReturn, Optional, Protocol
from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlunparse
from django.http import QueryDict
@@ -399,15 +399,51 @@ class UnexpectedEmptyJsonResponse(Exception):
pass
+def _raise_invalid_export_authorization(exported_asset: ExportedAsset, reason: str) -> NoReturn:
+ logger.error(
+ "csv_exporter.invalid_authentication_source",
+ exported_asset_id=exported_asset.id,
+ reason=reason,
+ )
+ raise ValueError("This export could not verify its original authorization. Create a new export and try again.")
+
+
def get_from_insights_api(exported_asset: ExportedAsset, limit: int, resource: dict) -> Generator[Any]:
path: str = resource["path"]
method: str = resource.get("method", "GET")
body = resource.get("body", None)
+ if method.upper() != "GET" or body is not None:
+ logger.error(
+ "csv_exporter.unsupported_api_request",
+ exported_asset_id=exported_asset.id,
+ method=method,
+ has_body=body is not None,
+ )
+ raise ValueError("This export request is no longer supported. Create a new export and try again.")
+ source_authentication = exported_asset.source_authentication
+ if source_authentication is None:
+ _raise_invalid_export_authorization(exported_asset, "missing_authentication_source")
next_url = None
+ token_payload: dict[str, int | str | None] = {"id": exported_asset.created_by_id}
+ if source_authentication == ExportedAsset.SourceAuthentication.PERSONAL_API_KEY:
+ if not exported_asset.source_credential_id:
+ _raise_invalid_export_authorization(exported_asset, "missing_personal_api_key")
+ token_payload["personal_api_key_id"] = exported_asset.source_credential_id
+ elif source_authentication == ExportedAsset.SourceAuthentication.OAUTH_ACCESS_TOKEN:
+ if not exported_asset.source_credential_id:
+ _raise_invalid_export_authorization(exported_asset, "missing_oauth_access_token")
+ token_payload["oauth_access_token_id"] = exported_asset.source_credential_id
+ elif source_authentication != ExportedAsset.SourceAuthentication.SESSION:
+ _raise_invalid_export_authorization(exported_asset, "unsupported_authentication_source")
+ token_audience = (
+ PosthogJwtAudience.IMPERSONATED_USER
+ if source_authentication == ExportedAsset.SourceAuthentication.SESSION
+ else PosthogJwtAudience.DELEGATED_USER
+ )
access_token = encode_jwt(
- {"id": exported_asset.created_by_id},
+ token_payload,
datetime.timedelta(minutes=15),
- PosthogJwtAudience.IMPERSONATED_USER,
+ token_audience,
)
total = 0
while total < CSV_EXPORT_LIMIT:
diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.py
index ae8dd90310b2..7821dce21407 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter.py
@@ -13,6 +13,7 @@ from unittest.mock import ANY, MagicMock, Mock, patch
from django.test import override_settings
from django.utils.timezone import now
+import jwt
from boto3 import resource
from botocore.client import Config
from dateutil.relativedelta import relativedelta
@@ -21,7 +22,9 @@ from requests.exceptions import HTTPError
from posthog.hogql.constants import CSV_EXPORT_BREAKDOWN_LIMIT_INITIAL
-from posthog.models.utils import UUIDT
+from posthog.jwt import PosthogJwtAudience, decode_jwt
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import UUIDT, generate_random_token_personal, hash_key_value
from posthog.security.spreadsheet_safety import sanitize_formula_injection
from posthog.settings import (
OBJECT_STORAGE_ACCESS_KEY_ID,
@@ -36,6 +39,7 @@ from posthog.utils import absolute_uri
from products.actions.backend.models.action import Action
from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.source_authentication import assert_export_authorization
from products.exports.backend.tasks import csv_exporter
from products.exports.backend.tasks.csv_exporter import (
CsvWriter,
@@ -113,13 +117,14 @@ class TestCSVExporter(APIBaseTest):
yield patched_request
def _create_asset(self, extra_context: Optional[dict] = None) -> ExportedAsset:
- if extra_context is None:
- extra_context = {}
+ extra_context = extra_context or {}
asset = ExportedAsset(
team=self.team,
+ created_by=self.user,
export_format=ExportedAsset.ExportFormat.CSV,
export_context={"path": "/api/literally/anything", **extra_context},
+ source_authentication=ExportedAsset.SourceAuthentication.SESSION,
)
asset.save()
return asset
@@ -346,6 +351,82 @@ class TestCSVExporter(APIBaseTest):
with pytest.raises(Exception, match="HTTP 403 Forbidden"):
csv_exporter.export_tabular(exported_asset)
+ @patch("products.exports.backend.tasks.csv_exporter.make_api_call")
+ def test_path_based_export_delegates_source_personal_api_key(self, patched_api_call: MagicMock) -> None:
+ exported_asset = self._create_asset()
+ exported_asset.source_authentication = ExportedAsset.SourceAuthentication.PERSONAL_API_KEY
+ exported_asset.source_credential_id = "source-key-id"
+ response = Mock()
+ response.json.return_value = {"next": None, "results": []}
+ patched_api_call.return_value = response
+
+ csv_exporter.export_tabular(exported_asset)
+
+ access_token = patched_api_call.call_args.args[0]
+ claims = decode_jwt(access_token, PosthogJwtAudience.DELEGATED_USER)
+ assert claims["personal_api_key_id"] == "source-key-id"
+ with pytest.raises(jwt.InvalidAudienceError):
+ decode_jwt(access_token, PosthogJwtAudience.IMPERSONATED_USER)
+
+ def test_path_based_export_rejects_missing_authentication_source(self) -> None:
+ exported_asset = self._create_asset()
+ exported_asset.source_authentication = None
+
+ with pytest.raises(ValueError, match="could not verify its original authorization"):
+ csv_exporter.export_tabular(exported_asset)
+
+ @patch("products.exports.backend.tasks.csv_exporter.make_api_call")
+ def test_path_based_session_export_uses_impersonated_user_audience(self, patched_api_call: MagicMock) -> None:
+ response = Mock()
+ response.json.return_value = {"next": None, "results": []}
+ patched_api_call.return_value = response
+
+ csv_exporter.export_tabular(self._create_asset())
+
+ access_token = patched_api_call.call_args.args[0]
+ decode_jwt(access_token, PosthogJwtAudience.IMPERSONATED_USER)
+ with pytest.raises(jwt.InvalidAudienceError):
+ decode_jwt(access_token, PosthogJwtAudience.DELEGATED_USER)
+ authentication_response = self.client.get(
+ f"/api/projects/{self.team.id}/persons/",
+ HTTP_AUTHORIZATION=f"Bearer {access_token}",
+ )
+ assert authentication_response.status_code == 200
+
+ def test_query_export_rechecks_source_personal_api_key(self) -> None:
+ personal_api_key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="query export key",
+ secure_value=hash_key_value(generate_random_token_personal()),
+ scopes=["export:write", "query:read"],
+ scoped_teams=[self.team.id],
+ )
+ exported_asset = ExportedAsset.objects.create(
+ team=self.team,
+ created_by=self.user,
+ export_format=ExportedAsset.ExportFormat.CSV,
+ export_context={"source": {"kind": "HogQLQuery", "query": "select 1"}},
+ source_authentication=ExportedAsset.SourceAuthentication.PERSONAL_API_KEY,
+ source_credential_id=personal_api_key.id,
+ )
+
+ assert_export_authorization(exported_asset)
+
+ personal_api_key.scopes = ["export:write"]
+ personal_api_key.save(update_fields=["scopes"])
+ with pytest.raises(ValueError, match="could not verify its original authorization"):
+ assert_export_authorization(exported_asset)
+
+ personal_api_key.scopes = ["export:write", "query:read"]
+ personal_api_key.scoped_teams = [self.team.id + 1]
+ personal_api_key.save(update_fields=["scopes", "scoped_teams"])
+ with pytest.raises(ValueError, match="could not verify its original authorization"):
+ assert_export_authorization(exported_asset)
+
+ personal_api_key.delete()
+ with pytest.raises(ValueError, match="could not verify its original authorization"):
+ assert_export_authorization(exported_asset)
+
@patch("products.exports.backend.tasks.csv_exporter.logger")
def test_failing_export_api_is_reported_query_size_exceeded(self, _mock_logger: MagicMock) -> None:
with patch("products.exports.backend.tasks.csv_exporter.make_api_call") as patched_make_api_call:
@@ -1621,6 +1702,7 @@ class TestCSVExporter(APIBaseTest):
team=self.team,
export_format=ExportedAsset.ExportFormat.XLSX,
export_context={"path": "/api/test/endpoint"},
+ source_authentication=ExportedAsset.SourceAuthentication.SESSION,
)
exported_asset.save()
mocked_uuidt.return_value = "a-guid"
diff --git a/products/exports/backend/tasks/test/test_csv_exporter_renders.py b/products/exports/backend/tasks/test/test_csv_exporter_renders.py
index 618e2bea5f32..22acdd3d5ed1 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter_renders.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter_renders.py
@@ -42,6 +42,7 @@ def test_csv_rendering(
team=team,
export_format=ExportedAsset.ExportFormat.CSV,
export_context={"path": "/api/literally/anything"},
+ source_authentication=ExportedAsset.SourceAuthentication.SESSION,
)
export_context = cast(dict[str, Any], asset.export_context)
if fixture["response"].get("columns"):