:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(activity-log): record the credential behind each change (#105540)
Tom Piccirello5339766ba3b6
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex 5d300569bf2a..3f33d11f8591 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -189,6 +189,40 @@ The mixin's before-update read is by primary key without a team filter (`unscopeYour own reads in the same path still need `with team_scope(team_id):` or `Model.objects.for_team(team_id)`.See `posthog/models/scoping/README.md`.+## Credential attribution++A row written during a request also records the credential that authenticated the request, in `credential_type`, `credential_id` and `impersonated_by_id`.+`ActivityLoggingMiddleware` records the session, resolved again for each row.+The session applies only while `request.user` is still the session's user: DRF writes the principal of the authentication class that succeeded back onto the request, so a class that authenticates someone else and records nothing leaves the row `unattributed`.+A bearer authentication class that succeeds replaces the session with its own credential through `record_activity_actor` in `posthog/models/activity_logging/utils.py`.+The values come from the authenticated object, never from a request header, so a caller cannot choose them.+Unlike `client`, they are evidence of which credential made a change.++| `credential_type` | `credential_id` |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------ |+| `session` | the session's public id, from `session_public_id` |+| `personal_api_key` | the key id |+| `oauth` | the OAuth application UUID |+| `project_secret_key` | the key id |+| `team_secret_token` | none |+| `id_jag` | the `client_id` claim |+| `internal_jwt` | none |+| `service_jwt` | the audience of the scoped service JWT |+| `internal_api_secret` | none |+| `scim` | the SCIM identity provider config id |+| `vercel` | the Vercel installation id |+| `partner` | the partner's OAuth application UUID when it proved itself with a secret or a signed assertion, none for a public client |+| `unattributed` | none |++- A credential without a user (a project secret key, the legacy team secret token, a service JWT, the internal API secret or a SCIM token) clears any user the middleware took from a session cookie. The row has `user=None` and `is_system=True`, and it keeps the credential.+- `impersonated_by_id` holds the staff user behind an impersonated session or an OAuth token minted during impersonation.+- The fields are null outside a request. A row written inside a request that recorded no credential has `credential_type` `unattributed`: the request was anonymous, or its authentication class records nothing.+- The fields are internal. The advanced activity log serializer and the notifications serializer list their fields explicitly and leave them out. The advanced serializer also builds `$activity_log_entry_created` for customer destinations.+- A new authentication class that writes activity rows must call `record_activity_actor` when it succeeds. Otherwise its rows read `unattributed`. A partner OAuth class passes `oauth_activity_credential(access_token)`, so its rows read the same as the main OAuth path.++To match a row to a session, compare `credential_id` with `session_public_id(session_key)` from `posthog/session/activity.py`.+The login sessions API (`/api/users/@me/login_sessions/`) returns the same id and revokes a session by it.+## Product models on a separate database`ActivityLog` lives on the main database.diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.pyindex 3b7bb7a28816..1536dd58fce7 100644--- a/ee/api/agentic_provisioning/authentication.py+++ b/ee/api/agentic_provisioning/authentication.py@@ -18,6 +18,7 @@ from posthog.api.oauth.client_assertion import (verify_client_assertion,)from posthog.api.oauth.client_auth import ClientCredentials, extract_client_credentials, verify_client_secret+from posthog.models.activity_logging.utils import ActivityCredential, oauth_activity_credential, record_activity_actorfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_tokenfrom posthog.models.user import User@@ -87,6 +88,11 @@ class ProvisioningAuthentication(BaseAuthentication):return Nonecapture_auth_event(app, "success", endpoint=request.path)+ # A public partner is named by a client_id that anyone can send, so only a partner that proved+ # itself with a secret or a signed assertion is recorded by id.+ record_activity_actor(+ None, ActivityCredential(type="partner", id=str(app.id) if app.requires_client_authentication else None)+ )return (None, app)def _identify_partner(self, request: Request) -> OAuthApplication | None:@@ -231,6 +237,7 @@ class ProvisioningBearerAuthentication(BaseAuthentication):if user is None or not user.is_active:raise ProvisioningError("unauthorized", "Authentication failed", status=401)+ record_activity_actor(user, oauth_activity_credential(access_token))return user, access_tokendef authenticate_header(self, request: Request) -> str:diff --git a/ee/api/agentic_provisioning/test/test_e2e_flow.py b/ee/api/agentic_provisioning/test/test_e2e_flow.pyindex 75509f886e04..016dd9d88fd8 100644--- a/ee/api/agentic_provisioning/test/test_e2e_flow.py+++ b/ee/api/agentic_provisioning/test/test_e2e_flow.py@@ -3,6 +3,7 @@ from urllib.parse import parse_qs, urlparsefrom django.utils import timezone+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.oauth import OAuthApplicationfrom posthog.models.user import User@@ -73,6 +74,8 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):assert res.json()["id"] == resource_idrotated_api_key = res.json()["complete"]["access_configuration"]["api_key"]assert rotated_api_key != original_api_key+ rotation = ActivityLog.objects.filter(scope="Team", activity="updated").latest("created_at")+ assert (rotation.credential_type, rotation.credential_id) == ("oauth", str(self.partner.id))# 6. Deep link — create and use it to loginres = self._post_with_bearer(diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex 57579fa2f1cc..a2fb1bb53c4e 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -6,8 +6,12 @@ from unittest.mock import MagicMock, patchfrom django.core.cache import cache as real_cachefrom parameterized import parameterized+from rest_framework.parsers import JSONParser+from rest_framework.request import Request+from rest_framework.test import APIRequestFactoryfrom posthog.api.oauth.cimd import _cache_key, fetch_and_upsert_cimd_application+from posthog.models.activity_logging.utils import ActivityCredential, activity_storagefrom posthog.models.oauth import OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.user import User@@ -78,6 +82,34 @@ class TestProvisioningAuthentication(ProvisioningTestBase):assert res.status_code == 200assert res.json()["type"] == "oauth"+ @parameterized.expand([("proven by its secret", True), ("public client id only", False)])+ def test_partner_is_recorded_by_id_only_when_it_proved_itself(self, _name, confidential):+ if confidential:+ partner = self.partner+ data = self._client_credentials(partner)+ else:+ partner = OAuthApplication.objects.create(+ client_id="activity-log-public-partner",+ name="Public partner",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://partner.example.com/callback",+ algorithm="RS256",+ is_provisioning_partner=True,+ _provisioning_config=provisioning_config(),+ )+ data = {"client_id": partner.client_id}+ request = Request(APIRequestFactory().post("/", data, format="json"), parsers=[JSONParser()])++ activity_storage.mark_request_scoped()+ try:+ assert ProvisioningAuthentication().authenticate(request) == (None, partner)+ credential = activity_storage.get_credential()+ finally:+ activity_storage.clear_all()++ assert credential == ActivityCredential(type="partner", id=str(partner.id) if confidential else None)+@parameterized.expand([("wrong_secret", "not-the-real-secret"),diff --git a/ee/api/authentication.py b/ee/api/authentication.pyindex fc8512c4b1b4..1b439cba527a 100644--- a/ee/api/authentication.py+++ b/ee/api/authentication.py@@ -37,6 +37,11 @@ from posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.helpers.sso import UNVERIFIED_SOCIAL_EMAIL_ERROR+from posthog.models.activity_logging.utils import (+ ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH,+ ActivityCredential,+ record_activity_actor,+)from posthog.models.identity_provider_config import IdentityProviderConfig, has_verified_organization_domain_qfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain@@ -526,6 +531,12 @@ class VercelAuthentication(authentication.BaseAuthentication):try:payload = self._validate_jwt_token(token, auth_type)+ record_activity_actor(+ None,+ ActivityCredential(+ type="vercel", id=str(payload.installation_id)[:ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH]+ ),+ )return VercelUser(claims=payload), Noneexcept jwt.InvalidTokenError as e:logger.warning("Vercel auth failed", auth_type=auth_type, error=str(e), integration="vercel")diff --git a/ee/api/scim/auth.py b/ee/api/scim/auth.pyindex f681b29d36c4..d302d2695760 100644--- a/ee/api/scim/auth.py+++ b/ee/api/scim/auth.py@@ -9,6 +9,7 @@ from rest_framework.authentication import BaseAuthenticationfrom rest_framework.request import Requestfrom posthog.constants import AvailableFeature+from posthog.models.activity_logging.utils import ActivityCredential, record_activity_actorfrom posthog.models.identity_provider_config import IdentityProviderConfig@@ -73,6 +74,7 @@ class SCIMBearerTokenAuthentication(BaseAuthentication):if not check_password(token, hashed_token):raise exceptions.AuthenticationFailed("Invalid bearer token")+ record_activity_actor(None, ActivityCredential(type="scim", id=str(config.id)))return (SCIMAuthToken(config), config)def _extract_scim_slug_from_path(self, path: str) -> Optional[str]:diff --git a/ee/api/scim/test/test_scim_api.py b/ee/api/scim/test/test_scim_api.pyindex 7ffc8c2d7e50..14801f19a5ef 100644--- a/ee/api/scim/test/test_scim_api.py+++ b/ee/api/scim/test/test_scim_api.py@@ -636,6 +636,7 @@ class TestSCIMAuditLogging(APILicensedTest):assert log is not None, f"Expected activity log with activity='{expected_activity}'"assert log.is_system is Trueassert log.user is None+ assert (log.credential_type, log.credential_id) == ("scim", str(self.config.id))assert log.organization_id == self.organization.idassert log.detail is not Noneassert log.detail.get("context", {}).get("identity_provider_config_id") == str(self.config.id)diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex 10661a5b1ef3..c01af71f6df9 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -38,6 +38,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomain+from posthog.session.activity import session_public_idfrom ee.api.authentication import CustomGoogleOAuth2, MultitenantSAMLAuthfrom ee.api.test.base import APILicensedTest@@ -900,6 +901,11 @@ class TestEEAuthenticationAPI(APILicensedTest):login_context = cast(dict, login_activity.detail)["context"]self.assertEqual(login_context["reauth"], True)self.assertEqual(login_context["login_method"], "Google OAuth")+ # The row has to name the session the rotation created, not the one it retired.+ self.assertEqual(login_activity.credential_type, "session")+ self.assertEqual(+ login_activity.credential_id, str(session_public_id(cast(str, self.client.session.session_key)))+ )# Opening the sensitive-action window has to retire the session id that existed before it,# so a cookie copied earlier can't ride the window the victim just opened.diff --git a/ee/api/vercel/test/test_vercel_authentication.py b/ee/api/vercel/test/test_vercel_authentication.pyindex 5e23177b299a..2545fbbfe682 100644--- a/ee/api/vercel/test/test_vercel_authentication.py+++ b/ee/api/vercel/test/test_vercel_authentication.py@@ -11,9 +11,12 @@ from django.utils import timezoneimport jwtfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa+from parameterized import parameterizedfrom rest_framework.exceptions import AuthenticationFailedfrom rest_framework.test import APIRequestFactory+from posthog.models.activity_logging.utils import ActivityCredential, activity_storage+from ee.api.authentication import VercelAuthenticationfrom ee.api.vercel.types import VercelUser, VercelUserClaims@@ -129,6 +132,20 @@ class TestVercelAuthentication(SimpleTestCase):assert user.claims.account_id == self.account_idassert user.claims.installation_id == self.installation_id+ @parameterized.expand([("user",), ("system",)])+ def test_valid_token_records_the_installation_as_the_activity_credential(self, mock_get_jwks, auth_type):+ mock_get_jwks.return_value = self.mock_jwks+ request = self._make_request(self._token(user=auth_type == "user"), auth_type)++ activity_storage.mark_request_scoped()+ try:+ self.auth.authenticate(request)+ credential = activity_storage.get_credential()+ finally:+ activity_storage.clear_all()++ assert credential == ActivityCredential(type="vercel", id=self.installation_id)+def test_missing_authorization_header(self, mock_get_jwks):request = self.factory.get("/", HTTP_X_VERCEL_AUTH="user")with self.assertRaises(AuthenticationFailed):diff --git a/ee/partners/stripe/api/provisioning/authentication.py b/ee/partners/stripe/api/provisioning/authentication.pyindex d7f636fb294a..78bd5c1fb213 100644--- a/ee/partners/stripe/api/provisioning/authentication.py+++ b/ee/partners/stripe/api/provisioning/authentication.py@@ -17,6 +17,7 @@ from django.utils import timezonefrom rest_framework.authentication import BaseAuthenticationfrom rest_framework.request import Request+from posthog.models.activity_logging.utils import oauth_activity_credential, record_activity_actorfrom posthog.models.oauth import OAuthAccessToken, find_oauth_access_tokenfrom posthog.models.user import User@@ -63,6 +64,7 @@ class StripeBearerAuthentication(BaseAuthentication):if user is None or not user.is_active:raise SpecError("unauthorized", "Authentication failed", status=401)+ record_activity_actor(user, oauth_activity_credential(access_token))return user, access_tokendef authenticate_header(self, request: Request) -> str:diff --git a/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py b/ee/partners/stripe/api/provisioning/test/test_e2e_flow.pyindex e7eac8f422b3..3162fb252b5f 100644--- a/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py+++ b/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py@@ -4,6 +4,7 @@ from urllib.parse import parse_qs, urlencode, urlparsefrom django.utils import timezone+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.user import Userfrom ee.partners.stripe.api.provisioning.test.base import (@@ -91,6 +92,8 @@ class TestE2EProvisioningFlow(StripeProvisioningTestBase):assert res.json()["status"] == "complete"rotated_api_key = res.json()["complete"]["access_configuration"]["api_key"]assert rotated_api_key != original_api_key+ rotation = ActivityLog.objects.filter(scope="Team", activity="updated").latest("created_at")+ assert (rotation.credential_type, rotation.credential_id) == ("oauth", str(self.stripe_app.id))res = self._post_signed_with_bearer(f"{BASE_PATH}/provisioning/resources/{resource_id}/update_service",diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.pyindex ca862bc12af9..152b780617c6 100644--- a/posthog/api/advanced_activity_logs/viewset.py+++ b/posthog/api/advanced_activity_logs/viewset.py@@ -150,7 +150,25 @@ class ActivityLogSerializer(serializers.ModelSerializer):class Meta:model = ActivityLog- fields = "__all__"+ # An explicit list, so that a new internal column such as `credential_id` stays out. This+ # serializer also builds the `$activity_log_entry_created` event, so a field listed here+ # reaches the advanced API, the export and customer destinations at the same time.+ fields = [+ "id",+ "user",+ "unread",+ "team_id",+ "organization_id",+ "was_impersonated",+ "is_system",+ "client",+ "ip_address",+ "activity",+ "item_id",+ "scope",+ "detail",+ "created_at",+ ]def get_unread(self, obj: ActivityLog) -> bool:"""is the date of this log item newer than the user's bookmark"""diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.pyindex acf88f5d170c..54c923cd75a6 100644--- a/posthog/api/my_notifications.py+++ b/posthog/api/my_notifications.py@@ -46,7 +46,23 @@ class MyNotificationsSerializer(serializers.ModelSerializer):class Meta:model = ActivityLog- exclude = ["team_id"]+ # An explicit list, so that a new internal column such as `credential_id` stays out of the+ # teammate feed.+ fields = [+ "id",+ "user",+ "unread",+ "organization_id",+ "was_impersonated",+ "is_system",+ "client",+ "ip_address",+ "activity",+ "item_id",+ "scope",+ "detail",+ "created_at",+ ]def get_unread(self, obj: ActivityLog) -> bool:"""is the date of this log item newer than the user's bookmark"""diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambrindex 417e07698b43..b8dac13e2219 100644--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr@@ -1573,6 +1573,9 @@"posthog_activitylog"."is_system","posthog_activitylog"."client","posthog_activitylog"."ip_address",+ "posthog_activitylog"."credential_type",+ "posthog_activitylog"."credential_id",+ "posthog_activitylog"."impersonated_by_id","posthog_activitylog"."activity","posthog_activitylog"."item_id","posthog_activitylog"."scope",diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.pyindex 299659aaf6c1..33dd48843e31 100644--- a/posthog/api/test/test_activity_log.py+++ b/posthog/api/test/test_activity_log.py@@ -6,16 +6,22 @@ import time_machinefrom posthog.test.base import APIBaseTest, QueryMatchingTestfrom unittest.mock import patch+from django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.api.advanced_activity_logs import ActivityLogSerializer+from posthog.api.my_notifications import MyNotificationsSerializerfrom posthog.constants import AvailableFeature+from posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLog, Detail, log_activity+from posthog.models.activity_logging.utils import activity_storagefrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.session.activity import session_public_idfrom posthog.test.insight_queries import default_pageview_queryfrom products.exports.backend.models.exported_asset import ExportedAsset@@ -439,23 +445,86 @@ class TestOrganizationAdvancedActivityLogsAvailableFilters(APIBaseTest):class TestActivityLogBearerAuthAttribution(APIBaseTest):CONFIG_AUTO_LOGIN = False- def _create_experiment_and_get_activity(self, auth_header: str, flag_key: str) -> ActivityLog:+ def _create_experiment_and_get_activity(+ self, auth_header: str | None, flag_key: str, extra_headers: dict[str, str] | None = None+ ) -> ActivityLog:+ headers = dict(extra_headers or {})+ if auth_header:+ headers["authorization"] = auth_headerresponse = self.client.post(f"/api/projects/{self.team.id}/experiments/",{"name": "Bearer auth experiment", "feature_flag_key": flag_key},- headers={"authorization": auth_header},+ headers=headers,)assert response.status_code == status.HTTP_201_CREATED, response.json()return ActivityLog.objects.get(scope="Experiment", activity="created", item_id=str(response.json()["id"]))- def test_personal_api_key_write_is_attributed_to_key_owner(self) -> None:+ def _create_personal_api_key(self) -> tuple[str, PersonalAPIKey]:value = generate_random_token_personal()- PersonalAPIKey.objects.create(label="Test", user=self.user, secure_value=hash_key_value(value), scopes=["*"])+ key = PersonalAPIKey.objects.create(+ label="Test", user=self.user, secure_value=hash_key_value(value), scopes=["*"]+ )+ return value, key++ def test_personal_api_key_write_is_attributed_to_key_owner(self) -> None:+ value, key = self._create_personal_api_key()log = self._create_experiment_and_get_activity(f"Bearer {value}", "pat-attribution-flag")assert log.is_system is Falseassert log.user == self.user+ assert (log.credential_type, log.credential_id, log.impersonated_by_id) == ("personal_api_key", key.id, None)++ def test_session_write_records_the_session_public_id(self) -> None:+ self.client.force_login(self.user)++ log = self._create_experiment_and_get_activity(None, "session-attribution-flag")++ session_key = self.client.session.session_key+ assert session_key is not None+ assert log.user == self.user+ assert (log.credential_type, log.credential_id) == ("session", str(session_public_id(session_key)))+ assert activity_storage.get_credential() is None++ @parameterized.expand([("personal_api_key",), ("oauth",)])+ def test_bearer_credential_replaces_the_session_credential(self, credential_type: str) -> None:+ self.client.force_login(self.user)+ if credential_type == "personal_api_key":+ value, key = self._create_personal_api_key()+ auth_header, expected_id = f"Bearer {value}", key.id+ else:+ token = self._create_oauth_token()+ auth_header, expected_id = f"Bearer {token.token}", str(token.application_id)++ log = self._create_experiment_and_get_activity(+ auth_header,+ f"{credential_type}-over-session-flag",+ extra_headers={"x-posthog-client": "session"},+ )++ assert (log.credential_type, log.credential_id) == (credential_type, expected_id)+ assert log.client == "session"++ def test_login_records_the_session_it_creates(self) -> None:+ self.user.is_email_verified = True+ self.user.save()++ response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})+ assert response.status_code == status.HTTP_200_OK, response.json()++ log = ActivityLog.objects.get(scope="User", activity="logged_in", item_id=str(self.user.id))+ session_key = self.client.session.session_key+ assert session_key is not None+ assert (log.credential_type, log.credential_id) == ("session", str(session_public_id(session_key)))++ def test_internal_jwt_write_is_attributed_to_the_token_user(self) -> None:+ token = encode_jwt({"id": self.user.id}, timedelta(minutes=15), PosthogJwtAudience.IMPERSONATED_USER)++ log = self._create_experiment_and_get_activity(f"Bearer {token}", "internal-jwt-attribution-flag")++ assert log.is_system is False+ assert log.user == self.user+ assert (log.credential_type, log.credential_id) == ("internal_jwt", None)def _create_oauth_token(self, impersonated_by: User | None = None) -> OAuthAccessToken:application = OAuthApplication.objects.create(@@ -484,6 +553,11 @@ class TestActivityLogBearerAuthAttribution(APIBaseTest):assert log.is_system is Falseassert log.user == self.userassert log.was_impersonated is False+ assert (log.credential_type, log.credential_id, log.impersonated_by_id) == (+ "oauth",+ str(token.application_id),+ None,+ )def test_impersonation_minted_oauth_token_write_is_marked_impersonated(self) -> None:staff_user = User.objects.create_and_join(self.organization, "[email protected]", None)@@ -493,6 +567,7 @@ class TestActivityLogBearerAuthAttribution(APIBaseTest):assert log.user == self.userassert log.was_impersonated is True+ assert log.impersonated_by_id == staff_user.id@patch("posthog.api.advanced_activity_logs.viewset.exporter.export_asset.delay")def test_activity_log_export_preserves_oauth_authorization(self, _mock_exporter_task) -> None:@@ -510,3 +585,19 @@ class TestActivityLogBearerAuthAttribution(APIBaseTest):exported_asset = ExportedAsset.objects.get(id=response.json()["id"])assert exported_asset.source_authentication == ExportedAsset.SourceAuthentication.OAUTH_ACCESS_TOKENassert exported_asset.source_credential_id == str(token.id)+++class TestActivityLogSerializerFields(SimpleTestCase):+ @parameterized.expand([("advanced", ActivityLogSerializer), ("my_notifications", MyNotificationsSerializer)])+ def test_credential_fields_are_not_serialized(self, _name: str, serializer_class: type) -> None:+ log = ActivityLog(+ scope="Experiment",+ activity="created",+ credential_type="personal_api_key",+ credential_id="key-id",+ impersonated_by_id=1,+ )++ data = serializer_class(log).data++ assert {"credential_type", "credential_id", "impersonated_by_id"}.isdisjoint(data)diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex 7badcd25f432..cb1b34b8dc6f 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -36,6 +36,7 @@ from posthog.api.id_jag import ()from posthog.auth import IDJagAccessTokenAuthenticationfrom posthog.constants import AvailableFeature+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfigfrom posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfigfrom posthog.models.organization import Organization, OrganizationMembership@@ -838,6 +839,32 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):def _call_authenticated(self, token: str) -> Any:return self.client.get("/api/users/@me/", HTTP_AUTHORIZATION=f"Bearer {token}")+ @parameterized.expand(+ [+ ("plain client id", _RESOURCE_CLIENT_ID, _RESOURCE_CLIENT_ID),+ ("client id with a NUL", "mcp\x00erase", "mcperase"),+ ]+ )+ def test_write_is_attributed_to_the_resolved_user(+ self, _name: str, client_id: str, expected_credential_id: str+ ) -> None:+ token = self._mint_access_token(scope="experiment:write feature_flag:write", client_id=client_id)++ resp = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {"name": "ID-JAG experiment", "feature_flag_key": "id-jag-attribution-flag"},+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )++ self.assertEqual(resp.status_code, status.HTTP_201_CREATED, resp.content)+ log = ActivityLog.objects.get(scope="Experiment", activity="created", item_id=str(resp.json()["id"]))+ assert (log.user, log.is_system, log.credential_type, log.credential_id) == (+ self.user,+ False,+ "id_jag",+ expected_credential_id,+ )+def test_valid_token_authenticates_user(self) -> None:token = self._mint_access_token(scope="user:read")resp = self._call_authenticated(token)diff --git a/posthog/api/test/test_team_deletion.py b/posthog/api/test/test_team_deletion.pyindex 62974d1c8e25..0eb1f33dd438 100644--- a/posthog/api/test/test_team_deletion.py+++ b/posthog/api/test/test_team_deletion.py@@ -87,6 +87,9 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):"client": None,"created_at": ANY,"ip_address": None,+ "credential_type": None,+ "credential_id": None,+ "impersonated_by_id": None,},{# The env→project rewrite routes the delete through the project-delete path, which cascades@@ -114,6 +117,9 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):"was_impersonated": False,"client": None,"ip_address": "127.0.0.1",+ "credential_type": "session",+ "credential_id": ANY,+ "impersonated_by_id": None,},{"_state": ANY,@@ -137,6 +143,9 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):"was_impersonated": False,"client": None,"ip_address": "127.0.0.1",+ "credential_type": "session",+ "credential_id": ANY,+ "impersonated_by_id": None,},]diff --git a/posthog/auth.py b/posthog/auth.pyindex 4dfb5a3565bb..a383d21d3367 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -36,7 +36,14 @@ from posthog.helpers.verified_domain_enforcement import enforce_verified_domainfrom posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_matchfrom posthog.internal_api_secret import usable_internal_api_secretsfrom posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, get_oidc_verification_keys-from posthog.models.activity_logging.utils import activity_storage, record_agent_intent+from posthog.models.activity_logging.utils import (+ ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH,+ ActivityCredential,+ activity_storage,+ oauth_activity_credential,+ record_activity_actor,+ record_agent_intent,+)from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrandfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.personal_api_key import (@@ -353,11 +360,12 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):# ActivityLoggingMiddleware only captures session-authenticated users (it runs before# DRF auth), so signal-driven activity logging would otherwise record bearer-token- # requests as system actions. Only write when the middleware owns cleanup: outside a- # request cycle (e.g. authenticate() called directly) the thread-local would leak.- if activity_storage.is_request_scoped():- activity_storage.set_user(personal_api_key_object.user)- record_agent_intent(request)+ # requests as system actions.+ record_activity_actor(+ personal_api_key_object.user,+ ActivityCredential(type="personal_api_key", id=personal_api_key_object.id),+ )+ record_agent_intent(request)self.personal_api_key = personal_api_key_objectself.personal_api_key_source = source@@ -431,6 +439,7 @@ class TeamSecretTokenAuthentication(authentication.BaseAuthentication):team_id=team.id,access_method=AccessMethod.TEAM_SECRET_TOKEN,)+ record_activity_actor(None, ActivityCredential(type="team_secret_token"))return (TeamSecretTokenUser(team), None)except Team.DoesNotExist:@@ -495,6 +504,7 @@ class ProjectSecretAPIKeyAuthentication(authentication.BaseAuthentication):api_key_mask=psak.mask_value,api_key_label=psak.label,)+ record_activity_actor(None, ActivityCredential(type="project_secret_key", id=psak.id))return (ProjectSecretAPIKeyUser(psak), None)@@ -519,6 +529,7 @@ class JwtAuthentication(authentication.BaseAuthentication):token = authorization_match.group(1).strip()info = decode_jwt(token, PosthogJwtAudience.IMPERSONATED_USER)user = User.objects.get(pk=info["id"])+ record_activity_actor(user, ActivityCredential(type="internal_jwt"))return (user, None)except AuthenticationFailed:raise@@ -712,6 +723,12 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):access_method=AccessMethod.ID_JAG,)+ record_activity_actor(+ user,+ ActivityCredential(type="id_jag", id=str(claims["client_id"])[:ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH]),+ )+ record_agent_intent(request)+return user, Nonedef authenticate_header(self, request) -> str:@@ -983,15 +1000,10 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):# ActivityLoggingMiddleware only captures session-authenticated users (it runs# before DRF auth), so signal-driven activity logging would otherwise record- # bearer-token requests as system actions. Only write when the middleware owns- # cleanup: outside a request cycle (e.g. authenticate() called directly) the- # thread-local would leak.+ # bearer-token requests as system actions. A token minted during staff+ # impersonation keeps the impersonation marker through `impersonated_by_id`.+ record_activity_actor(user, oauth_activity_credential(access_token))if activity_storage.is_request_scoped():- activity_storage.set_user(user)- # Tokens minted during staff impersonation must keep the impersonation- # marker in the audit trail.- if access_token.impersonated_by_id is not None:- activity_storage.set_was_impersonated(True)_record_agent_attribution(request, access_token)self._set_scout_activity_client(access_token)@@ -1124,9 +1136,10 @@ class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):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)- record_agent_intent(request)+ record_activity_actor(+ personal_api_key.user, ActivityCredential(type="personal_api_key", id=personal_api_key.id)+ )+ record_agent_intent(request)return personal_api_key.user, None@@ -1271,6 +1284,7 @@ class InternalAPIAuthentication(authentication.BaseAuthentication):)raise AuthenticationFailed("Invalid internal API authentication.")+ record_activity_actor(None, ActivityCredential(type="internal_api_secret"))return (self._get_internal_api_user(request), None)def authenticate_header(self, request: HttpRequest) -> str:@@ -1330,7 +1344,9 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):except jwt.PyJWTError:raise AuthenticationFailed("Invalid or expired service token.")- return self._authenticate_claims(request, claims)+ principal, verified_claims = self._authenticate_claims(request, claims)+ record_activity_actor(None, ActivityCredential(type="service_jwt", id=self.purpose.audience.value))+ return principal, verified_claimsdef _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, dict[str, Any]]:claim_team_id = claims.get("team_id")diff --git a/posthog/helpers/impersonation.py b/posthog/helpers/impersonation.pyindex a92e26855215..9e40ee90c852 100644--- a/posthog/helpers/impersonation.py+++ b/posthog/helpers/impersonation.py@@ -37,14 +37,28 @@ def is_impersonated(request: Optional[HttpRequest]) -> bool:return False-def get_original_user_from_session(request):- """Extract the original staff user from an impersonated session."""+def get_original_user_id_from_session(request) -> int | None:+ """The original staff user's id in an impersonated session, read from the signed session value+ alone, so that callers on every request make no query."""try:- signer = TimestampSigner()original_session = request.session.get(la_settings.USER_SESSION_FLAG)+ if original_session is None:+ return None+ signer = TimestampSigner()original_user_pk = signer.unsign(original_session, max_age=timedelta(days=la_settings.USER_SESSION_DAYS_TIMESTAMP))+ return int(original_user_pk)+ except Exception:+ return None+++def get_original_user_from_session(request):+ """Extract the original staff user from an impersonated session."""+ original_user_pk = get_original_user_id_from_session(request)+ if original_user_pk is None:+ return None+ try:User = get_user_model()return User.objects.get(pk=original_user_pk)except Exception:diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 1d38e092cd02..84d5672812f5 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -45,17 +45,19 @@ from posthog.cloud_utils import is_cloud, is_dev_modefrom posthog.constants import AUTH_BACKEND_KEYSfrom posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_valuefrom posthog.geoip import get_geoip_properties-from posthog.helpers.impersonation import get_original_user_from_session+from posthog.helpers.impersonation import get_original_user_from_session, get_original_user_id_from_sessionfrom posthog.helpers.sso import sso_failure_redirect_urlfrom posthog.helpers.user_devices import set_known_device_cookiefrom posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_matchfrom posthog.models import Organization, Team, Userfrom posthog.models.activity_logging.utils import (ACTIVITY_LOG_CLIENT_HEADER,+ ActivityCredential,activity_storage,client_from_header,record_agent_intent,)+from posthog.session.activity import session_activity_credentialfrom posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URLfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_ip_address, get_trusted_client_ip@@ -1293,6 +1295,21 @@ class OAuthCoopMiddleware:return response+def _session_credential(request: HttpRequest, session_user_pk: object) -> ActivityCredential | None:+ """The session credential for a row written now, or None when the session did not authenticate+ the request.++ DRF writes the principal of the authentication class that succeeded back onto `request.user`.+ Another principal there means that a class which records no credential of its own (a sharing+ link, a widget token) authenticated the request, so the row must not name the session cookie.+ The check compares primary keys, not objects, because later middleware such as django-otp's+ wraps the same user in a new object.+ """+ if getattr(request.user, "pk", None) != session_user_pk:+ return None+ return session_activity_credential(request, get_original_user_id_from_session(request))++class ActivityLoggingMiddleware:"""Middleware that sets the current user and impersonation status in activity storage@@ -1309,8 +1326,10 @@ class ActivityLoggingMiddleware:# Set user in activity storage if authenticatedif request.user.is_authenticated:+ session_user_pk = request.user.pkactivity_storage.set_user(request.user)activity_storage.set_was_impersonated(is_impersonated_session(request))+ activity_storage.set_credential_resolver(lambda: _session_credential(request, session_user_pk))record_agent_intent(request)client_header = request.headers.get(ACTIVITY_LOG_CLIENT_HEADER)diff --git a/posthog/migrations/1388_activitylog_credential.py b/posthog/migrations/1388_activitylog_credential.pynew file mode 100644index 000000000000..0050e45e216f--- /dev/null+++ b/posthog/migrations/1388_activitylog_credential.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.17 on 2026-09-23 20:14++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1387_user_gmail_canonical_index")]++ operations = [+ migrations.AddField(+ model_name="activitylog",+ name="credential_id",+ field=models.CharField(blank=True, max_length=256, null=True),+ ),+ migrations.AddField(+ model_name="activitylog",+ name="credential_type",+ field=models.CharField(blank=True, max_length=32, null=True),+ ),+ migrations.AddField(+ model_name="activitylog",+ name="impersonated_by_id",+ field=models.BigIntegerField(blank=True, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex b6020554d824..4628db640b0d 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1387_user_gmail_canonical_index+1388_activitylog_credentialdiff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 2527246772aa..70b2698b7608 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -19,7 +19,12 @@ import structlogfrom prometheus_client import Counterfrom posthog.exceptions_capture import capture_exception-from posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_MAX_LENGTH, activity_storage+from posthog.models.activity_logging.utils import (+ ACTIVITY_LOG_CLIENT_MAX_LENGTH,+ ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH,+ ActivityCredential,+ activity_storage,+)from posthog.models.utils import ActivityDetailEncoder, UUIDTModelif TYPE_CHECKING:@@ -249,6 +254,15 @@ class ActivityLog(UUIDTModel):client = models.CharField(max_length=ACTIVITY_LOG_CLIENT_MAX_LENGTH, null=True, blank=True)# Client IP captured at request time. Null for non-HTTP activity (system, Celery).ip_address = models.GenericIPAddressField(null=True, blank=True)+ # The credential that authenticated the request, from `ActivityCredential`. Unlike `client`,+ # the caller cannot set these, so they answer which key, OAuth application or session made a+ # change. Null outside a request. A project secret key row has no user but keeps its credential.+ credential_type = models.CharField(max_length=32, null=True, blank=True)+ credential_id = models.CharField(max_length=ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH, null=True, blank=True)+ # The staff user behind an impersonated change. A plain integer rather than a foreign key:+ # `SET_NULL` would make every user deletion update this table through a full scan, because+ # nothing indexes the column.+ impersonated_by_id = models.BigIntegerField(null=True, blank=True)activity = models.fields.CharField(max_length=79, null=False)# if scoped to a model this activity log holds the id of the model being logged@@ -1268,6 +1282,11 @@ def log_activity(client = activity_storage.get_client()if ip_address is None:ip_address = activity_storage.get_ip_address()+ credential = activity_storage.get_credential()+ if credential is None and activity_storage.is_request_scoped():+ # The request was anonymous, or an authentication class that records no credential verified+ # it. Say so, so that the row does not read like one written outside a request.+ credential = ActivityCredential(type="unattributed")if detail.trigger is None:# A product that sets its own trigger already says what drove the write.detail = _with_agent_trigger(detail)@@ -1292,39 +1311,30 @@ def log_activity()return None- def _create_activity_log_instance():- return ActivityLog(- organization_id=organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- is_system=user is None,- item_id=str(item_id),- scope=scope,- activity=activity,- detail=detail,- client=client,- ip_address=ip_address,- )+ fields: dict[str, Any] = {+ "organization_id": organization_id,+ "team_id": team_id,+ "user": user,+ "was_impersonated": was_impersonated,+ "is_system": user is None,+ "item_id": str(item_id),+ "scope": scope,+ "activity": activity,+ "detail": detail,+ "client": client,+ "ip_address": ip_address,+ "credential_type": credential.type if credential else None,+ # Postgres rejects a NUL in text, and a failed insert drops the whole audit row. An ID-JAG+ # client id is a claim from the organization's identity provider, so it can carry one.+ "credential_id": credential.id.replace("\x00", "") if credential and credential.id else None,+ "impersonated_by_id": credential.impersonated_by_id if credential else None,+ }def _do_log_activity():- log = _create_activity_log_instance()- return ActivityLog.objects.create(- organization_id=log.organization_id,- team_id=log.team_id,- user=log.user,- was_impersonated=log.was_impersonated,- is_system=log.is_system,- item_id=log.item_id,- scope=log.scope,- activity=log.activity,- detail=log.detail,- client=log.client,- ip_address=log.ip_address,- )+ return ActivityLog.objects.create(**fields)if instance_only:- return _create_activity_log_instance()+ return ActivityLog(**fields)return _handle_activity_log_transaction(_do_log_activity,diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex e593551a9d38..dd66319186d2 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -20,7 +20,11 @@ from prometheus_client import Counterfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMESfrom posthog.exceptions_capture import capture_exception-from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated+from posthog.helpers.impersonation import (+ get_original_user_from_session,+ get_original_user_id_from_session,+ is_impersonated,+)from posthog.models import Organization, PersonalAPIKey, Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import (ActivityContextBase,@@ -49,6 +53,7 @@ from posthog.models.organization_invite import OrganizationInvitefrom posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import User+from posthog.session.activity import session_activity_credentialfrom posthog.session.models import Sessionfrom posthog.utils import get_ip_address, get_short_user_agent@@ -140,6 +145,20 @@ def _determine_login_method(request, was_impersonated):return login_method+def _record_current_session_credential(request: HttpRequest, *, impersonated_by_id: int | None = None) -> None:+ """Record the session that the login leaves behind.++ The session resolver of `ActivityLoggingMiddleware` does not cover a login. A fresh sign-in was+ anonymous when the middleware ran, so the middleware set no resolver. A login that switches+ users fails the resolver's user check, so the resolver returns no credential.+ """+ if not activity_storage.is_request_scoped():+ return+ activity_storage.set_credential(+ session_activity_credential(request, impersonated_by_id or get_original_user_id_from_session(request))+ )++def log_login_activity(user,request: HttpRequest,@@ -161,6 +180,11 @@ def log_login_activity(logger.info("Skipping login activity log - user has no organization", user_id=user.id)return+ # `login_as` fires `user_logged_in` before it stores the staff user in the session, so on the+ # row that starts an impersonation only the detected staff user can name the impersonator.+ impersonated_by_id = log_user.pk if was_impersonated and log_user is not None and log_user.pk != user.pk else None+ _record_current_session_credential(request, impersonated_by_id=impersonated_by_id)+log_activity(organization_id=organization_id,team_id=None,diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.pyindex f9418cb5548f..fc5cc54f5d93 100644--- a/posthog/models/activity_logging/utils.py+++ b/posthog/models/activity_logging/utils.py@@ -1,6 +1,6 @@import tracebackfrom collections.abc import Callable-from typing import TYPE_CHECKING, Any, Optional, cast+from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom django.db import modelsfrom django.db.models import Q, QuerySet@@ -12,6 +12,8 @@ from posthog.dataclasses import frozenif TYPE_CHECKING:from posthog.models.activity_logging.activity_log import ActivityLog, Trigger+ from posthog.models.oauth import OAuthAccessToken+ from posthog.models.user import Userlogger = structlog.get_logger(__name__)@@ -36,6 +38,43 @@ SCOUT_CLIENT_PREFIX = "scout:"SERVER_DERIVED_CLIENT_PREFIXES = (SCOUT_CLIENT_PREFIX,)+CredentialType = Literal[+ "session",+ "personal_api_key",+ "oauth",+ "project_secret_key",+ "team_secret_token",+ "id_jag",+ "internal_jwt",+ "service_jwt",+ "internal_api_secret",+ "scim",+ "vercel",+ "partner",+ "unattributed",+]+# Sized for an ID-JAG `client_id`, the longest value: the identity provider config accepts client+# ids up to 256 characters. Key ids, OAuth application UUIDs and session public ids are much shorter.+ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH = 256+++@frozen+class ActivityCredential:+ """The credential that authenticated a request, recorded on every activity row it writes.++ Only `ActivityLoggingMiddleware` and the authentication classes set it, from the objects+ they authenticated, so no request header can change it.+ """++ type: CredentialType+ # The personal or project secret key id, the OAuth application UUID, the ID-JAG client id, the+ # SCIM identity provider config id, the service JWT audience, the Vercel installation id, the+ # partner application UUID, or `session_public_id` for a session. None when the credential has+ # no id of its own.+ id: str | None = None+ impersonated_by_id: int | None = None++def client_from_header(value: str) -> Optional[str]:"""The client to store for a self-reported header, or None when the value cannot be stored.@@ -178,6 +217,33 @@ class ActivityLoggingStorage:if hasattr(self._local, "ip_address"):delattr(self._local, "ip_address")+ def set_credential(self, credential: ActivityCredential) -> None:+ self.set_credential_resolver(lambda: credential)++ def set_credential_resolver(self, resolver: Callable[[], Optional[ActivityCredential]]) -> None:+ """Hand over a credential to resolve again for each row. The last one set wins.++ `ActivityLoggingMiddleware` sets a resolver for the session because it runs before the view,+ so it cannot know yet whether the session authenticates the request, or whether the view+ rotates the session key. An authentication class that succeeds later replaces it.+ """+ self._local.credential_resolver = resolver++ def get_credential(self) -> Optional[ActivityCredential]:+ resolver = getattr(self._local, "credential_resolver", None)+ if resolver is None:+ return None+ try:+ return resolver()+ except Exception:+ # Attribution is not worth failing a write for.+ logger.warning("activity_log.credential_resolver_failed", exc_info=True)+ return None++ def clear_credential(self) -> None:+ if hasattr(self._local, "credential_resolver"):+ delattr(self._local, "credential_resolver")+def set_trigger(self, trigger: Optional["Trigger"]) -> None:self._local.trigger = trigger@@ -196,12 +262,38 @@ class ActivityLoggingStorage:self.clear_agent_intent()self.clear_agent_task_id()self.clear_ip_address()+ self.clear_credential()self.clear_trigger()activity_storage = ActivityLoggingStorage()+def record_activity_actor(user: "User | None", credential: ActivityCredential) -> None:+ """Attribute the request's activity rows to the credential an authentication class verified,+ and to its user.++ ActivityLoggingMiddleware runs before DRF authentication, so it can already hold a user, an+ impersonation flag and a session credential from a cookie on the same request. Replace all+ three, so that a row never pairs this credential with the session's user or flag. Pass+ `user=None` for a credential that has no user. Only write when the middleware owns cleanup:+ outside a request cycle (e.g. authenticate() called directly) the thread-local would leak.+ """+ if not activity_storage.is_request_scoped():+ return+ activity_storage.set_user(user)+ activity_storage.set_was_impersonated(credential.impersonated_by_id is not None)+ activity_storage.set_credential(credential)+++def oauth_activity_credential(access_token: "OAuthAccessToken") -> ActivityCredential:+ return ActivityCredential(+ type="oauth",+ id=str(access_token.application_id),+ impersonated_by_id=access_token.impersonated_by_id,+ )++class ActivityLogVisibilityManager:"""Manages visibility restrictions for activity logs.diff --git a/posthog/session/activity.py b/posthog/session/activity.pyindex 0b0101c25b89..e5c810add5f1 100644--- a/posthog/session/activity.py+++ b/posthog/session/activity.py@@ -14,6 +14,7 @@ from loginas.utils import is_impersonated_sessionfrom posthog.constants import AUTH_BACKEND_KEYSfrom posthog.geoip import get_geoip_propertiesfrom posthog.models import User+from posthog.models.activity_logging.utils import ActivityCredentialfrom posthog.session.models import Sessionfrom posthog.utils import _is_valid_ip_address, get_ip_address, get_short_user_agent@@ -32,6 +33,19 @@ def session_public_id(session_key: str) -> uuid.UUID:return uuid.uuid5(SESSION_PUBLIC_ID_NAMESPACE, session_key)+def session_activity_credential(request: HttpRequest, impersonated_by_id: int | None) -> ActivityCredential:+ """The session credential for an activity row. Its id is the public id that the login sessions+ API lists and revokes by, so an investigator can go from a row to the live session."""+ # A login that switches users flushes the session, and the new key exists only once the+ # response saves it. The row then names the session without an id, rather than the old one.+ session_key = getattr(getattr(request, "session", None), "session_key", None)+ return ActivityCredential(+ type="session",+ id=str(session_public_id(session_key)) if session_key else None,+ impersonated_by_id=impersonated_by_id,+ )++def _location_from_ip(ip: Optional[str]) -> Optional[str]:properties = get_geoip_properties(ip)parts = [properties.get("$geoip_city_name"), properties.get("$geoip_country_name")]diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex c5da96060f30..340047cc4fb4 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -9,17 +9,35 @@ from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patchfrom django.db.utils import IntegrityError+from django.test import override_settingsfrom django.utils import timezonefrom parameterized import parameterized--from posthog.auth import OAuthAccessTokenAuthentication+from rest_framework.authentication import BaseAuthentication+from rest_framework.request import Request+from rest_framework.test import APIRequestFactory++from posthog.auth import (+ InternalAPIAuthentication,+ OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,+ ProjectSecretAPIKeyAuthentication,+ ScopedServiceJWTAuthentication,+)from posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import User-from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity+from posthog.models.activity_logging.activity_log import (+ ActivityLog,+ Change,+ Detail,+ Trigger,+ bulk_log_activity,+ log_activity,+)from posthog.models.activity_logging.model_activity import ActivityTriggerContextfrom posthog.models.activity_logging.utils import (ACTIVITY_LOG_INTENT_MAX_LENGTH,+ ActivityCredential,activity_storage,activity_visibility_manager,)@@ -27,7 +45,9 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.scoping import team_scopefrom posthog.models.utils import UUIDT, generate_random_token_personal, hash_key_value+from posthog.scoped_service_jwt import ScopedServiceJwtPurposefrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV+from posthog.test.api_keys import create_project_secret_api_keyfrom products.dashboards.backend.models.dashboard_widget import DashboardWidget@@ -61,6 +81,7 @@ class TestActivityLogModel(BaseTest):self.assertEqual(log.activity, "updated")assert log.detail is not Noneself.assertEqual(log.detail["changes"], [change.__dict__])+ self.assertEqual((log.credential_type, log.credential_id, log.impersonated_by_id), (None, None, None))def test_can_save_a_log_that_has_no_model_changes(self) -> None:log_activity(@@ -297,6 +318,51 @@ class TestActivityLogModel(BaseTest):log: ActivityLog = ActivityLog.objects.latest("id")self.assertIsNone(log.ip_address)+ def test_a_request_that_recorded_no_credential_is_marked_unattributed(self) -> None:+ activity_storage.mark_request_scoped()+ try:+ log = log_activity(+ organization_id=self.organization.id,+ team_id=self.team.id,+ user=self.user,+ was_impersonated=False,+ item_id=13,+ scope="FeatureFlag",+ activity="created",+ detail=Detail(),+ )+ finally:+ activity_storage.clear_all()++ assert log is not None+ assert (log.credential_type, log.credential_id) == ("unattributed", None)++ def test_bulk_log_activity_records_the_request_credential(self) -> None:+ activity_storage.set_credential(ActivityCredential(type="personal_api_key", id="key-id", impersonated_by_id=7))+ try:+ bulk_log_activity(+ [+ {+ "organization_id": self.organization.id,+ "team_id": self.team.id,+ "user": self.user,+ "was_impersonated": False,+ "item_id": item_id,+ "scope": "FeatureFlag",+ "activity": "created",+ "detail": Detail(),+ }+ for item_id in (11, 12)+ ]+ )+ finally:+ activity_storage.clear_credential()++ rows = list(ActivityLog.objects.filter(team_id=self.team.id, scope="FeatureFlag", item_id__in=["11", "12"]))+ assert [(row.credential_type, row.credential_id, row.impersonated_by_id) for row in rows] == [+ ("personal_api_key", "key-id", 7)+ ] * 2+def test_does_not_save_impersonated_activity_without_user(self) -> None:log_activity(organization_id=self.organization.id,@@ -380,6 +446,72 @@ class TestActivityLogModel(BaseTest):self.assertIsInstance(warning.kwargs["exception"], ValueError)+class _ServiceJWTAuthentication(ScopedServiceJWTAuthentication):+ purpose = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.RECORDING_API, settings_name="ACTIVITY_LOG_TEST_SERVICE_JWT_KEYS"+ )+++@override_settings(+ ACTIVITY_LOG_TEST_SERVICE_JWT_KEYS="activity-log-test-signing-key",+ INTERNAL_API_SECRET="activity-log-test-internal-secret",+ INTERNAL_API_SECRET_FALLBACKS=[],+)+class TestBearerAuthenticationReplacesSessionActor(BaseTest):+ def _authenticator_and_headers(+ self, credential_type: str+ ) -> tuple[BaseAuthentication, dict[str, str], User | None, str | None]:+ if credential_type == "project_secret_key":+ psak, token = create_project_secret_api_key(self.team, scopes=["endpoint:read"])+ return ProjectSecretAPIKeyAuthentication(), {"Authorization": f"Bearer {token}"}, None, psak.id+ if credential_type == "personal_api_key":+ token = generate_random_token_personal()+ pak = PersonalAPIKey.objects.create(+ label="pak", user=self.user, secure_value=hash_key_value(token), scopes=["*"]+ )+ return PersonalAPIKeyAuthentication(), {"Authorization": f"Bearer {token}"}, self.user, pak.id+ if credential_type == "service_jwt":+ token = _ServiceJWTAuthentication.purpose.mint({"team_id": self.team.id})+ headers = {"Authorization": f"Bearer {token}"}+ return _ServiceJWTAuthentication(), headers, None, PosthogJwtAudience.RECORDING_API.value+ headers = {"X-Internal-Api-Secret": "activity-log-test-internal-secret"}+ return InternalAPIAuthentication(), headers, None, None++ @parameterized.expand([("project_secret_key",), ("personal_api_key",), ("service_jwt",), ("internal_api_secret",)])+ def test_rows_name_the_bearer_credential_not_an_impersonated_session(self, credential_type: str) -> None:+ session_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ authenticator, headers, expected_user, expected_id = self._authenticator_and_headers(credential_type)+ # ActivityLoggingMiddleware has already recorded an impersonated session on the same request.+ activity_storage.mark_request_scoped()+ activity_storage.set_user(session_user)+ activity_storage.set_was_impersonated(True)+ activity_storage.set_credential(ActivityCredential(type="session", id="session-id", impersonated_by_id=1))+ try:+ authenticator.authenticate(Request(APIRequestFactory().get("/", headers=headers)))+ log = log_activity(+ organization_id=self.organization.id,+ team_id=self.team.id,+ user=activity_storage.get_user(),+ was_impersonated=activity_storage.get_was_impersonated(),+ item_id=1,+ scope="Loop",+ activity="updated",+ detail=Detail(),+ force_save=True,+ )+ finally:+ activity_storage.clear_all()++ assert log is not None+ assert (log.user, log.was_impersonated, log.credential_type, log.credential_id, log.impersonated_by_id) == (+ expected_user,+ False,+ credential_type,+ expected_id,+ None,+ )++class TestModelActivityMixinTeamScoping(BaseTest):def test_update_outside_team_scope_still_logs_the_change(self) -> None:# DashboardWidget reads through a fail-closed manager, and a save from a Celery task or adiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex bb5089439957..13f42212edcf 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -35,6 +35,7 @@ from posthog.middleware import (SignedClientIPOutcome,per_request_logging_context_middleware,)+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import Organizationfrom posthog.models.organization_invite import OrganizationInvitefrom posthog.models.team import Team@@ -1175,6 +1176,17 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):self.login_as_other_user()+ start = ActivityLog.objects.filter(scope="User", activity="logged_in", item_id=str(self.other_user.id)).latest(+ "created_at"+ )+ assert (+ start.user_id,+ start.was_impersonated,+ start.credential_type,+ start.credential_id,+ start.impersonated_by_id,+ ) == (self.user.id, True, "session", None, self.user.id)+# Verify we're logged in as the other userassert self.client.get("/api/users/@me").json()["email"] == "[email protected]"@@ -1191,6 +1203,14 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):dashboard.refresh_from_db()assert dashboard.name == "Updated Dashboard"+ log = ActivityLog.objects.filter(scope="Dashboard", item_id=str(dashboard.id)).latest("created_at")+ assert (log.user, log.was_impersonated, log.credential_type, log.impersonated_by_id) == (+ self.other_user,+ True,+ "session",+ self.user.id,+ )+def test_impersonation_blocked_when_user_disallows(self):"""Verify regular impersonation fails when target user has allow_impersonation=False."""self.other_user.allow_impersonation = False@@ -2122,6 +2142,39 @@ class TestActivityLoggingMiddleware(APIBaseTest):self.middleware = ActivityLoggingMiddleware(get_response)+ @parameterized.expand(+ [+ ("the session authenticates", "unchanged", "session"),+ ("a later middleware rewraps the same user", "rewrapped", "session"),+ ("another class authenticates", "replaced", None),+ ]+ )+ def test_session_credential_applies_only_while_the_session_user_is_the_request_user(+ self, _name: str, request_user: str, expected_type: str | None+ ):+ from django.contrib.auth.models import AnonymousUser+ from django.http import HttpResponse+ from django.utils.functional import SimpleLazyObject++ from posthog.middleware import ActivityLoggingMiddleware++ def get_response(request):+ if request_user == "rewrapped":+ request.user = SimpleLazyObject(lambda: self.user)+ elif request_user == "replaced":+ # DRF writes the principal of the class that authenticated back onto the request.+ request.user = AnonymousUser()+ self.captured["credential"] = self.activity_storage.get_credential()+ return HttpResponse()++ request = self.factory.get("/")+ request.user = self.user+ ActivityLoggingMiddleware(get_response)(request)++ credential = self.captured["credential"]+ assert (credential.type if credential else None) == expected_type+ assert self.activity_storage.get_credential() is None+def test_captures_x_posthog_client_header(self):request = self.factory.get("/", HTTP_X_POSTHOG_CLIENT="posthog-js/1.234.0")request.user = self.userdiff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 4835f9338870..a100241ac43f 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -46,6 +46,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import ErrorResponseSerializerfrom posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthenticationfrom posthog.models import Team+from posthog.models.activity_logging.utils import ActivityCredential, record_activity_actorfrom posthog.permissions import get_authenticator_scopes, is_authenticated_via_project_secret_api_keyfrom posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle@@ -190,6 +191,7 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Respif not _customer_analytics_enabled(team):return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)+ record_activity_actor(None, ActivityCredential(type="team_secret_token"))return team, Nonediff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 8bd0d0ee1d9c..b2d2177b4230 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -560,6 +560,7 @@ class TestExternalAccountAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_201_CREATED)log = ActivityLog.objects.get(team_id=self.team.id, scope="Account", activity="created")self.assertIsNone(log.user)+ self.assertEqual(log.credential_type, "team_secret_token")detail = log.detailassert detail is not Noneself.assertEqual(detail["trigger"]["job_type"], "hog_flow")