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.

feat(activity-log): require a credential type on each auth class (#107173)

Tom Piccirellof28d31f5551d
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index 3f33d11f8591..461919dbea8d 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -193,32 +193,42 @@ See `posthog/models/scoping/README.md`.
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`.
+Every other authentication class that succeeds replaces the session with its own credential through `record_activity_actor` from `ActivityCredentialMixin` in `posthog/models/activity_logging/utils.py`.
+The session also 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`.
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.
+| `credential_type` | user | `credential_id` |
+| ------------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
+| `session` | the session user | the session's public id, from `session_public_id` |
+| `personal_api_key` | the key owner | the key id |
+| `oauth` | the token user | the OAuth application UUID |
+| `project_secret_key` | none | the key id |
+| `team_secret_token` | none | none |
+| `id_jag` | the token user | the `client_id` claim |
+| `internal_jwt` | the token user | none |
+| `service_jwt` | none | the audience of the scoped service JWT |
+| `internal_api_secret` | none | none |
+| `scim` | none | the SCIM identity provider config id |
+| `vercel` | none | the Vercel installation id |
+| `partner` | none | the partner's OAuth application UUID when it proved itself with a secret or a signed assertion, none for a public client |
+| `sharing_access_token` | none | the sharing configuration id |
+| `sharing_password` | none | the share password id |
+| `widget_token` | none | none |
+| `billing_service` | none | none |
+| `gateway_agent` | none | the gateway agent's service account id |
+| `export_renderer` | the export's creator | the exported asset id |
+| `webhook` | none | none |
+| `cross_region_signature` | none | none |
+| `unattributed` | the session user, if any | none |
+
+- A credential without a user 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.
+- Every authentication class inherits `ActivityCredentialMixin` and sets `activity_credential_type`. A class that defines its own `authenticate` sets it again, even when the parent's value is correct. `posthog/test/repo_invariants/test_authentication_credential_types.py` enforces both rules.
+- The class calls `self.record_activity_actor(user, credential_id)` after every check of the credential passed, and the type comes from the declaration. `SessionAuthentication` is the exception, because the middleware records the session. A class that declares a type but never calls the recorder writes `unattributed` rows.
+- A partner OAuth class declares `oauth` and passes the token's application id and `impersonated_by_id` to the recorder, as the main OAuth path does, so its rows read the same.
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.
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index 1536dd58fce7..3e9828d79292 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -18,7 +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_actor
+from posthog.models.activity_logging.utils import ActivityCredentialMixin
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_token
from posthog.models.user import User
@@ -67,7 +67,7 @@ def resolve_bearer_access_token(request: Request) -> OAuthAccessToken:
return access_token
-class ProvisioningAuthentication(BaseAuthentication):
+class ProvisioningAuthentication(ActivityCredentialMixin, BaseAuthentication):
"""Authenticates provisioning requests from any registered partner.
Partners are OAuthApplications with ``is_provisioning_partner`` set. The OAuthApplication
@@ -82,6 +82,8 @@ class ProvisioningAuthentication(BaseAuthentication):
partner is identified.
"""
+ activity_credential_type = "partner"
+
def authenticate(self, request: Request) -> tuple[None, OAuthApplication] | None:
app = self._identify_partner(request)
if app is None:
@@ -90,9 +92,7 @@ class ProvisioningAuthentication(BaseAuthentication):
capture_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)
- )
+ self.record_activity_actor(None, str(app.id) if app.requires_client_authentication else None)
return (None, app)
def _identify_partner(self, request: Request) -> OAuthApplication | None:
@@ -203,7 +203,7 @@ class ProvisioningAuthentication(BaseAuthentication):
return self._resolve_partner(client_id)
-class ProvisioningBearerAuthentication(BaseAuthentication):
+class ProvisioningBearerAuthentication(ActivityCredentialMixin, BaseAuthentication):
"""Authenticate a provisioning partner via an OAuth bearer token, for the
resource and deep-link endpoints.
@@ -211,6 +211,8 @@ class ProvisioningBearerAuthentication(BaseAuthentication):
Raises :class:`ProvisioningError` (rendered in the view's envelope) on failure.
"""
+ activity_credential_type = "oauth"
+
def authenticate(self, request: Request) -> tuple[User, OAuthAccessToken]:
try:
access_token = resolve_bearer_access_token(request)
@@ -237,7 +239,9 @@ 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))
+ self.record_activity_actor(
+ user, str(access_token.application_id), impersonated_by_id=access_token.impersonated_by_id
+ )
return user, access_token
def authenticate_header(self, request: Request) -> str:
@@ -278,7 +282,7 @@ def authenticate_confidential_partner(request: Request, *, capability: str) -> O
return partner
-class ConfidentialPartnerAuthentication(BaseAuthentication):
+class ConfidentialPartnerAuthentication(ActivityCredentialMixin, BaseAuthentication):
"""DRF form of :func:`authenticate_confidential_partner`, so confidential
endpoints declare it in ``authentication_classes`` and can't ship without
it. The partner rides ``request.auth``; these endpoints act for the partner,
@@ -287,6 +291,8 @@ class ConfidentialPartnerAuthentication(BaseAuthentication):
Subclassed per capability rather than parameterized, because DRF instantiates
authentication classes with no arguments."""
+ # `ProvisioningAuthentication` records the partner, because this class authenticates through it.
+ activity_credential_type = "partner"
capability: str
def authenticate(self, request: Request) -> tuple[AnonymousUser, OAuthApplication]:
diff --git a/ee/api/authentication.py b/ee/api/authentication.py
index 1b439cba527a..e91719f8bda0 100644
--- a/ee/api/authentication.py
+++ b/ee/api/authentication.py
@@ -37,11 +37,7 @@ from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import EmailLookupHandler
from 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.activity_logging.utils import ActivityCredentialMixin
from posthog.models.identity_provider_config import IdentityProviderConfig, has_verified_organization_domain_q
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -504,7 +500,7 @@ def _get_bearer_token(request: Request) -> str | None:
return None
-class VercelAuthentication(authentication.BaseAuthentication):
+class VercelAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Implements Vercel Marketplace API authentication.
This authentication uses the OpenID Connect Protocol (OIDC).
@@ -515,6 +511,7 @@ class VercelAuthentication(authentication.BaseAuthentication):
https://vercel.com/docs/integrations/create-integration/marketplace-api#marketplace-partner-api-authentication
"""
+ activity_credential_type = "vercel"
VercelAuthType = Literal["user", "system"]
VERCEL_AUTH_TYPES: tuple[VercelAuthType, ...] = ("user", "system")
@@ -531,12 +528,7 @@ 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]
- ),
- )
+ self.record_activity_actor(None, str(payload.installation_id))
return VercelUser(claims=payload), None
except jwt.InvalidTokenError as e:
logger.warning("Vercel auth failed", auth_type=auth_type, error=str(e), integration="vercel")
@@ -667,7 +659,7 @@ class BillingServiceUser:
return True
-class BillingServiceAuthentication(authentication.BaseAuthentication):
+class BillingServiceAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticates requests from the billing service to PostHog.
@@ -675,6 +667,7 @@ class BillingServiceAuthentication(authentication.BaseAuthentication):
uses when calling the billing service, but in reverse direction).
"""
+ activity_credential_type = "billing_service"
EXPECTED_AUDIENCE = "billing:posthog-proxy"
def authenticate(self, request: Request) -> tuple[BillingServiceUser, None] | None:
@@ -703,6 +696,7 @@ class BillingServiceAuthentication(authentication.BaseAuthentication):
logger.warning("Billing service token missing organization_id")
raise AuthenticationFailed("Missing organization_id in token")
+ self.record_activity_actor(None)
return BillingServiceUser(organization_id=organization_id), None
def _validate_jwt_token(self, token: str) -> BillingServiceJWTPayload:
diff --git a/ee/api/scim/auth.py b/ee/api/scim/auth.py
index d302d2695760..24f7ea097d82 100644
--- a/ee/api/scim/auth.py
+++ b/ee/api/scim/auth.py
@@ -9,7 +9,7 @@ from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
from posthog.constants import AvailableFeature
-from posthog.models.activity_logging.utils import ActivityCredential, record_activity_actor
+from posthog.models.activity_logging.utils import ActivityCredentialMixin
from posthog.models.identity_provider_config import IdentityProviderConfig
@@ -30,12 +30,14 @@ class SCIMAuthToken:
return f"SCIMAuth({self.config.scim_slug})"
-class SCIMBearerTokenAuthentication(BaseAuthentication):
+class SCIMBearerTokenAuthentication(ActivityCredentialMixin, BaseAuthentication):
"""
SCIM authentication using bearer tokens.
Each IdentityProviderConfig has its own SCIM bearer token and `scim_slug` for tenant isolation.
"""
+ activity_credential_type = "scim"
+
def authenticate(self, request: Request) -> Optional[tuple[SCIMAuthToken, IdentityProviderConfig]]:
if not request.path.startswith("/scim/"):
return None
@@ -74,7 +76,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)))
+ self.record_activity_actor(None, str(config.id))
return (SCIMAuthToken(config), config)
def _extract_scim_slug_from_path(self, path: str) -> Optional[str]:
diff --git a/ee/partners/stripe/api/provisioning/authentication.py b/ee/partners/stripe/api/provisioning/authentication.py
index 78bd5c1fb213..e1bd8210554f 100644
--- a/ee/partners/stripe/api/provisioning/authentication.py
+++ b/ee/partners/stripe/api/provisioning/authentication.py
@@ -17,7 +17,7 @@ from django.utils import timezone
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
-from posthog.models.activity_logging.utils import oauth_activity_credential, record_activity_actor
+from posthog.models.activity_logging.utils import ActivityCredentialMixin
from posthog.models.oauth import OAuthAccessToken, find_oauth_access_token
from posthog.models.user import User
@@ -25,13 +25,15 @@ from ee.partners.stripe.api.provisioning.core import is_stripe_oauth_app
from ee.partners.stripe.api.provisioning.exceptions import SpecError
-class StripeBearerAuthentication(BaseAuthentication):
+class StripeBearerAuthentication(ActivityCredentialMixin, BaseAuthentication):
"""Authenticate the Stripe orchestrator via an OAuth bearer token.
Returns ``(user, access_token)`` so views read the token off ``request.auth``.
Raises :class:`SpecError` (rendered in the view's envelope) on failure.
"""
+ activity_credential_type = "oauth"
+
def authenticate(self, request: Request) -> tuple[User, OAuthAccessToken]:
auth_header = request.headers.get("authorization", "")
if not auth_header.startswith("Bearer "):
@@ -64,7 +66,9 @@ 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))
+ self.record_activity_actor(
+ user, str(access_token.application_id), impersonated_by_id=access_token.impersonated_by_id
+ )
return user, access_token
def authenticate_header(self, request: Request) -> str:
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index cb1b34b8dc6f..ff0d8ab56b38 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -37,6 +37,7 @@ from posthog.api.id_jag import (
from posthog.auth import IDJagAccessTokenAuthentication
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.activity_logging.utils import ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH
from posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfig
from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization import Organization, OrganizationMembership
@@ -843,6 +844,11 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
[
("plain client id", _RESOURCE_CLIENT_ID, _RESOURCE_CLIENT_ID),
("client id with a NUL", "mcp\x00erase", "mcperase"),
+ (
+ "client id longer than the column",
+ "c" * (ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH + 1),
+ "c" * ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH,
+ ),
]
)
def test_write_is_attributed_to_the_resolved_user(
diff --git a/posthog/auth.py b/posthog/auth.py
index a383d21d3367..b943b1788588 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -37,11 +37,9 @@ from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_mat
from posthog.internal_api_secret import usable_internal_api_secrets
from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, get_oidc_verification_keys
from posthog.models.activity_logging.utils import (
- ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH,
- ActivityCredential,
+ ActivityCredentialMixin,
+ DeclaredCredentialType,
activity_storage,
- oauth_activity_credential,
- record_activity_actor,
record_agent_intent,
)
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrand
@@ -172,7 +170,7 @@ class ZxcvbnValidator:
)
-class SessionAuthentication(authentication.SessionAuthentication):
+class SessionAuthentication(ActivityCredentialMixin, authentication.SessionAuthentication):
"""
This class is needed, because REST Framework's default SessionAuthentication does never return 401's,
because they cannot fill the WWW-Authenticate header with a valid value in the 401 response. As a
@@ -185,6 +183,10 @@ class SessionAuthentication(authentication.SessionAuthentication):
This class is also used to enforce Two-Factor Authentication for session-based authentication.
"""
+ # ActivityLoggingMiddleware records the session credential, not this class, so that views
+ # outside DRF get it too.
+ activity_credential_type = "session"
+
def authenticate(self, request):
with tracer.start_as_current_span("posthog.auth.session"):
auth_result = super().authenticate(request)
@@ -214,7 +216,7 @@ class SessionAuthentication(authentication.SessionAuthentication):
return "Session"
-class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
+class PersonalAPIKeyAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""A way of authenticating with personal API keys.
Only the first key candidate found in the request is tried, and the order is:
1. Request Authorization header of type Bearer.
@@ -223,6 +225,7 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
"""
keyword = "Bearer"
+ activity_credential_type = "personal_api_key"
personal_api_key: PersonalAPIKey
personal_api_key_source: Optional[str] = None
# Set once the key is validated, so rate limiting can identify the key without re-reading the
@@ -361,10 +364,7 @@ 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.
- record_activity_actor(
- personal_api_key_object.user,
- ActivityCredential(type="personal_api_key", id=personal_api_key_object.id),
- )
+ self.record_activity_actor(personal_api_key_object.user, personal_api_key_object.id)
record_agent_intent(request)
self.personal_api_key = personal_api_key_object
@@ -404,7 +404,7 @@ class TeamSecretTokenUser(SyntheticUser):
super().__init__(team, distinct_id=f"team-secret-token-{team.id}")
-class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
+class TeamSecretTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticates using the legacy team-level Team.secret_api_token field.
@@ -420,6 +420,7 @@ class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
"""
keyword = "Bearer"
+ activity_credential_type = "team_secret_token"
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
secret_api_token = _extract_phs_token(request)
@@ -439,7 +440,7 @@ class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
team_id=team.id,
access_method=AccessMethod.TEAM_SECRET_TOKEN,
)
- record_activity_actor(None, ActivityCredential(type="team_secret_token"))
+ self.record_activity_actor(None)
return (TeamSecretTokenUser(team), None)
except Team.DoesNotExist:
@@ -467,7 +468,7 @@ class ProjectSecretAPIKeyUser(SyntheticUser):
return {scope.split(":", 1)[0] for scope in self.project_secret_api_key.scopes or [] if ":" in scope}
-class ProjectSecretAPIKeyAuthentication(authentication.BaseAuthentication):
+class ProjectSecretAPIKeyAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticates a ProjectSecretAPIKey (PSAK) model record via its SHA256 hash.
@@ -479,6 +480,7 @@ class ProjectSecretAPIKeyAuthentication(authentication.BaseAuthentication):
"""
keyword = "Bearer"
+ activity_credential_type = "project_secret_key"
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
token = _extract_phs_token(request)
@@ -504,7 +506,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))
+ self.record_activity_actor(None, psak.id)
return (ProjectSecretAPIKeyUser(psak), None)
@@ -513,12 +515,13 @@ class ProjectSecretAPIKeyAuthentication(authentication.BaseAuthentication):
return cls.keyword
-class JwtAuthentication(authentication.BaseAuthentication):
+class JwtAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
A way of authenticating with a JWT, primarily by background jobs impersonating a User
"""
keyword = "Bearer"
+ activity_credential_type = "internal_jwt"
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
with tracer.start_as_current_span("posthog.auth.jwt"):
@@ -529,7 +532,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"))
+ self.record_activity_actor(user)
return (user, None)
except AuthenticationFailed:
raise
@@ -549,7 +552,7 @@ class JwtAuthentication(authentication.BaseAuthentication):
return cls.keyword
-class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
+class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticates inbound API requests using an access token minted by the
ID-JAG (XAA) JWT Bearer grant served from the OAuth token endpoint
@@ -566,6 +569,7 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
_ID_JAG_ACCESS_TOKEN_TYPE = "at+jwt"
keyword = "Bearer"
+ activity_credential_type = "id_jag"
id_jag_claims: dict[str, Any]
scopes: list[str]
@@ -723,10 +727,7 @@ 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]),
- )
+ self.record_activity_actor(user, str(claims["client_id"]))
record_agent_intent(request)
return user, None
@@ -753,12 +754,13 @@ def mint_export_renderer_token(*, user_id: int, team_id: int, exported_asset_id:
)
-class ExportRendererAuthentication(authentication.BaseAuthentication):
+class ExportRendererAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Scoped JWT auth for the export renderer. Only accepted on viewsets that opt in.
"""
keyword = "Bearer"
+ activity_credential_type = "export_renderer"
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
if request.method not in ("GET", "HEAD"):
@@ -796,6 +798,7 @@ class ExportRendererAuthentication(authentication.BaseAuthentication):
self.exported_asset_id = exported_asset_id
self.export_context = export_context
user = User.objects.get(pk=user_id)
+ self.record_activity_actor(user, str(exported_asset_id))
return user, None
except (jwt.DecodeError, jwt.InvalidAudienceError):
return None
@@ -820,11 +823,12 @@ def _organization_disallows_public_sharing(sharing_configuration: SharingConfigu
)
-class SharingAccessTokenAuthentication(authentication.BaseAuthentication):
+class SharingAccessTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""Limited access for sharing views e.g. insights/dashboards for refreshing.
Remember to add access restrictions based on `sharing_configuration` using `SharingTokenPermission` or manually.
"""
+ activity_credential_type = "sharing_access_token"
sharing_configuration: SharingConfiguration
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, Any]]:
@@ -848,17 +852,19 @@ class SharingAccessTokenAuthentication(authentication.BaseAuthentication):
raise AuthenticationFailed(detail="Sharing access token is invalid.")
self.sharing_configuration = sharing_configuration
+ self.record_activity_actor(None, str(sharing_configuration.id))
return (SharedLinkUser(sharing_configuration), None)
return None
-class SharingPasswordProtectedAuthentication(authentication.BaseAuthentication):
+class SharingPasswordProtectedAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
JWT-based authentication for password-protected shared resources.
Supports both Bearer token (for API calls) and cookie (for rendering decisions).
"""
keyword = "Bearer"
+ activity_credential_type = "sharing_password"
sharing_configuration: SharingConfiguration
share_password: "SharePassword"
@@ -910,6 +916,7 @@ class SharingPasswordProtectedAuthentication(authentication.BaseAuthentication):
self.sharing_configuration = sharing_configuration
self.share_password = share_password
+ self.record_activity_actor(None, str(share_password.id))
return (SharedLinkUser(sharing_configuration), None)
except jwt.InvalidTokenError:
@@ -946,12 +953,13 @@ def _record_agent_attribution(request: Union[HttpRequest, Request], access_token
record_agent_intent(request)
-class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
+class OAuthAccessTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
OAuth 2.0 Bearer token authentication using access tokens
"""
keyword = "Bearer"
+ activity_credential_type = "oauth"
access_token: OAuthAccessToken
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
@@ -1002,7 +1010,9 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
# before DRF auth), so signal-driven activity logging would otherwise record
# 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))
+ self.record_activity_actor(
+ user, str(access_token.application_id), impersonated_by_id=access_token.impersonated_by_id
+ )
if activity_storage.is_request_scoped():
_record_agent_attribution(request, access_token)
self._set_scout_activity_client(access_token)
@@ -1112,6 +1122,8 @@ def _decode_delegated_user_token(request: Union[HttpRequest, Request]) -> dict[s
class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):
+ activity_credential_type = "personal_api_key"
+
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
claims = _decode_delegated_user_token(request)
if claims is None:
@@ -1136,14 +1148,14 @@ class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):
api_key_mask=personal_api_key.mask_value,
api_key_label=personal_api_key.label,
)
- record_activity_actor(
- personal_api_key.user, ActivityCredential(type="personal_api_key", id=personal_api_key.id)
- )
+ self.record_activity_actor(personal_api_key.user, personal_api_key.id)
record_agent_intent(request)
return personal_api_key.user, None
class DelegatedOAuthAccessTokenAuthentication(OAuthAccessTokenAuthentication):
+ activity_credential_type = "oauth"
+
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
claims = _decode_delegated_user_token(request)
if claims is None:
@@ -1165,13 +1177,15 @@ class DelegatedOAuthAccessTokenAuthentication(OAuthAccessTokenAuthentication):
return self._authenticate_access_token(request, access_token)
-class WidgetAuthentication(authentication.BaseAuthentication):
+class WidgetAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticate widget requests via conversations_settings.widget_public_token.
This provides team-level authentication only. User-level scoping
is enforced via widget_session_id validation in each endpoint.
"""
+ activity_credential_type = "widget_token"
+
def authenticate(self, request: Request) -> Optional[tuple[None, Any]]:
"""
Returns (None, team) on success.
@@ -1187,6 +1201,7 @@ class WidgetAuthentication(authentication.BaseAuthentication):
except Team.DoesNotExist:
raise AuthenticationFailed("Invalid token or conversations not enabled")
+ self.record_activity_actor(None)
return (None, team)
@@ -1209,10 +1224,11 @@ class InternalAPIUser:
return False
-class InternalAPIAuthentication(authentication.BaseAuthentication):
+class InternalAPIAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""DRF authentication backend for internal API calls."""
keyword = "InternalApiSecret"
+ activity_credential_type = "internal_api_secret"
HEADER_NAME = "X-Internal-Api-Secret"
def _get_team_id_from_request(self, request: Request) -> str | None:
@@ -1284,14 +1300,14 @@ class InternalAPIAuthentication(authentication.BaseAuthentication):
)
raise AuthenticationFailed("Invalid internal API authentication.")
- record_activity_actor(None, ActivityCredential(type="internal_api_secret"))
+ self.record_activity_actor(None)
return (self._get_internal_api_user(request), None)
def authenticate_header(self, request: HttpRequest) -> str:
return self.keyword
-class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
+class ScopedServiceJWTAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""DRF authentication for internal routes called by other PostHog services, verifying the
scoped per-purpose JWTs of posthog.scoped_service_jwt (the blessed replacement for
INTERNAL_API_SECRET). Subclass per purpose:
@@ -1310,6 +1326,7 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
claim fails closed instead of authenticating unscoped.
"""
+ activity_credential_type = "service_jwt"
purpose: ClassVar[ScopedServiceJwtPurpose]
require_team: ClassVar[bool] = True
@@ -1345,7 +1362,7 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
raise AuthenticationFailed("Invalid or expired service token.")
principal, verified_claims = self._authenticate_claims(request, claims)
- record_activity_actor(None, ActivityCredential(type="service_jwt", id=self.purpose.audience.value))
+ self.record_activity_actor(None, self.purpose.audience.value)
return principal, verified_claims
def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, dict[str, Any]]:
@@ -1526,7 +1543,7 @@ class WebauthnBackend(BaseBackend):
return None
-class WebhookSignatureAuthentication(authentication.BaseAuthentication):
+class WebhookSignatureAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Base HMAC-SHA256 webhook signature authentication.
@@ -1538,6 +1555,8 @@ class WebhookSignatureAuthentication(authentication.BaseAuthentication):
- Stripe: signature header "Stripe-Signature", input format "{ts}.{body}"
"""
+ # Annotated so that a subclass can declare another type. Without it, mypy infers `Literal["webhook"]`.
+ activity_credential_type: ClassVar[DeclaredCredentialType] = "webhook"
timestamp_tolerance: int = 300 # seconds
@abstractmethod
@@ -1610,6 +1629,7 @@ class WebhookSignatureAuthentication(authentication.BaseAuthentication):
if abs(time.time() - ts) > self.timestamp_tolerance:
raise AuthenticationFailed("Webhook timestamp too old.")
+ self.record_activity_actor(None)
# Return AnonymousUser (not None) so DRF throttles can safely access request.user.is_authenticated.
return (AnonymousUser(), self.get_auth_context(request))
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 7bd7f3f4c30d..1769de1daa61 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1301,8 +1301,9 @@ def _session_credential(request: HttpRequest, session_user_pk: object) -> Activi
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.
+ An authentication class that records its own credential replaces this resolver. Another
+ principal here means that a class authenticated the request without recording a credential,
+ 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.
"""
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index fc5cc54f5d93..5dbc6e88de93 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -1,6 +1,6 @@
import traceback
from collections.abc import Callable
-from typing import TYPE_CHECKING, Any, Literal, Optional, cast
+from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional, cast
from django.db import models
from django.db.models import Q, QuerySet
@@ -12,7 +12,6 @@ from posthog.dataclasses import frozen
if TYPE_CHECKING:
from posthog.models.activity_logging.activity_log import ActivityLog, Trigger
- from posthog.models.oauth import OAuthAccessToken
from posthog.models.user import User
logger = structlog.get_logger(__name__)
@@ -38,7 +37,7 @@ SCOUT_CLIENT_PREFIX = "scout:"
SERVER_DERIVED_CLIENT_PREFIXES = (SCOUT_CLIENT_PREFIX,)
-CredentialType = Literal[
+DeclaredCredentialType = Literal[
"session",
"personal_api_key",
"oauth",
@@ -51,8 +50,18 @@ CredentialType = Literal[
"scim",
"vercel",
"partner",
- "unattributed",
+ "sharing_access_token",
+ "sharing_password",
+ "widget_token",
+ "billing_service",
+ "gateway_agent",
+ "export_renderer",
+ "webhook",
+ "cross_region_signature",
]
+# `log_activity` writes `unattributed` for a row in a request where no authentication class recorded
+# a credential, so no class may declare it.
+CredentialType = Literal[DeclaredCredentialType, "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
@@ -67,10 +76,8 @@ class ActivityCredential:
"""
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.
+ # None when the credential has no id of its own. The table under "Credential attribution" in
+ # docs/internal/activity-logging.md lists the id that each credential type records.
id: str | None = None
impersonated_by_id: int | None = None
@@ -269,29 +276,44 @@ class ActivityLoggingStorage:
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.
+class ActivityCredentialMixin:
+ """Declares the credential type of an authentication class, and records that credential on the
+ request's activity rows.
- 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.
+ `posthog/test/repo_invariants/test_authentication_credential_types.py` fails when a PostHog
+ authentication class does not declare a type.
"""
- 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,
- )
+
+ activity_credential_type: ClassVar[DeclaredCredentialType]
+
+ @classmethod
+ def record_activity_actor(
+ cls,
+ user: "User | None",
+ credential_id: str | None = None,
+ *,
+ impersonated_by_id: int | None = None,
+ ) -> None:
+ """Attribute the request's activity rows to the credential this class verified, and to its
+ user. Call it only after every check of the credential passed.
+
+ 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(impersonated_by_id is not None)
+ activity_storage.set_credential(
+ ActivityCredential(
+ type=cls.activity_credential_type,
+ id=credential_id[:ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH] if credential_id else None,
+ impersonated_by_id=impersonated_by_id,
+ )
+ )
class ActivityLogVisibilityManager:
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index 0adaadc7aca2..4861f7541e50 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -10,6 +10,7 @@ from unittest.mock import patch
from django.db import transaction
from django.db.utils import IntegrityError
+from django.http import HttpRequest
from django.test import override_settings
from django.utils import timezone
@@ -19,14 +20,19 @@ from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from posthog.auth import (
+ ExportRendererAuthentication,
InternalAPIAuthentication,
OAuthAccessTokenAuthentication,
PersonalAPIKeyAuthentication,
ProjectSecretAPIKeyAuthentication,
ScopedServiceJWTAuthentication,
+ SharingAccessTokenAuthentication,
+ SharingPasswordProtectedAuthentication,
+ WidgetAuthentication,
+ mint_export_renderer_token,
)
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models import User
+from posthog.models import SharePassword, SharingConfiguration, User
from posthog.models.activity_logging.activity_log import (
ActivityLog,
Change,
@@ -51,6 +57,7 @@ from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from posthog.test.api_keys import create_project_secret_api_key
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
+from products.exports.backend.models.exported_asset import ExportedAsset
class TestActivityLogModel(BaseTest):
@@ -476,36 +483,84 @@ class _ServiceJWTAuthentication(ScopedServiceJWTAuthentication):
INTERNAL_API_SECRET_FALLBACKS=[],
)
class TestBearerAuthenticationReplacesSessionActor(BaseTest):
- def _authenticator_and_headers(
+ def _authenticator_and_request(
self, credential_type: str
- ) -> tuple[BaseAuthentication, dict[str, str], User | None, str | None]:
+ ) -> tuple[BaseAuthentication, HttpRequest, User | None, str | None]:
+ factory = APIRequestFactory()
+
+ def bearer(token: str) -> HttpRequest:
+ return factory.get("/", headers={"Authorization": f"Bearer {token}"})
+
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
+ return ProjectSecretAPIKeyAuthentication(), 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
+ return PersonalAPIKeyAuthentication(), 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
+ return _ServiceJWTAuthentication(), bearer(token), None, PosthogJwtAudience.RECORDING_API.value
+ if credential_type == "sharing_access_token":
+ sharing_configuration = SharingConfiguration.objects.create(team=self.team, enabled=True)
+ request = factory.get(f"/?sharing_access_token={sharing_configuration.access_token}")
+ return SharingAccessTokenAuthentication(), request, None, str(sharing_configuration.id)
+ if credential_type == "sharing_password":
+ sharing_configuration = SharingConfiguration.objects.create(
+ team=self.team, enabled=True, password_required=True
+ )
+ share_password = SharePassword.objects.create(
+ sharing_configuration=sharing_configuration, created_by=self.user, password_hash="unused"
+ )
+ token = sharing_configuration.generate_password_protected_token(share_password)
+ return SharingPasswordProtectedAuthentication(), bearer(token), None, str(share_password.id)
+ if credential_type == "export_renderer":
+ exported_asset = ExportedAsset.objects.create(
+ team=self.team,
+ created_by=self.user,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ export_context={"session_recording_id": "recording-id"},
+ )
+ token = mint_export_renderer_token(
+ user_id=self.user.id,
+ team_id=self.team.id,
+ exported_asset_id=exported_asset.id,
+ scope="session_recording:read",
+ )
+ return ExportRendererAuthentication(), bearer(token), self.user, str(exported_asset.id)
+ if credential_type == "widget_token":
+ self.team.conversations_enabled = True
+ self.team.conversations_settings = {"widget_public_token": "widget-token"}
+ self.team.save()
+ request = factory.get("/", headers={"X-Conversations-Token": "widget-token"})
+ return WidgetAuthentication(), request, None, None
+ request = factory.get("/", headers={"X-Internal-Api-Secret": "activity-log-test-internal-secret"})
+ return InternalAPIAuthentication(), request, None, None
- @parameterized.expand([("project_secret_key",), ("personal_api_key",), ("service_jwt",), ("internal_api_secret",)])
+ @parameterized.expand(
+ [
+ ("project_secret_key",),
+ ("personal_api_key",),
+ ("service_jwt",),
+ ("internal_api_secret",),
+ ("sharing_access_token",),
+ ("sharing_password",),
+ ("export_renderer",),
+ ("widget_token",),
+ ]
+ )
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)
+ authenticator, request, expected_user, expected_id = self._authenticator_and_request(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)))
+ authenticator.authenticate(Request(request))
log = log_activity(
organization_id=self.organization.id,
team_id=self.team.id,
diff --git a/posthog/test/repo_invariants/test_authentication_credential_types.py b/posthog/test/repo_invariants/test_authentication_credential_types.py
new file mode 100644
index 000000000000..ecc6ec17056e
--- /dev/null
+++ b/posthog/test/repo_invariants/test_authentication_credential_types.py
@@ -0,0 +1,152 @@
+"""Every authentication class declares the credential type that its activity rows record.
+
+`ActivityCredentialMixin.record_activity_actor` takes the type from `activity_credential_type`, so
+the declaration and the recorded value cannot disagree. A class without a declaration raises
+`AttributeError` when it records, and a class that never records leaves its rows `unattributed`.
+
+A class that defines its own `authenticate` can verify a different credential from its parent, as
+the delegated key classes do. So it declares its type again instead of inheriting it, even when the
+value is the same.
+
+To clear a violation, inherit `ActivityCredentialMixin`, set `activity_credential_type`, and call
+`self.record_activity_actor(user, credential_id)` after every check of the credential passed. A new
+kind of credential needs a new value in `DeclaredCredentialType`. See "Credential attribution" in
+`docs/internal/activity-logging.md`.
+
+ pytest posthog/test/repo_invariants/test_authentication_credential_types.py
+"""
+
+import ast
+import functools
+import importlib
+from pathlib import Path
+from typing import get_args
+
+from rest_framework import authentication
+from rest_framework.authentication import BaseAuthentication
+from rest_framework.schemas.generators import EndpointEnumerator
+from rest_framework.views import APIView
+
+from posthog.models.activity_logging.utils import ActivityCredentialMixin, DeclaredCredentialType
+
+REPO_ROOT = Path(__file__).parents[3]
+SCANNED_ROOTS = ("posthog", "ee", "products", "common")
+SKIPPED_DIRS = {"node_modules", ".venv", "venv", "__pycache__", ".git", ".mypy_cache"}
+OWNED_MODULE_PREFIXES = tuple(f"{root}." for root in SCANNED_ROOTS)
+DECLARED_TYPES = frozenset(get_args(DeclaredCredentialType))
+# `ActivityLoggingMiddleware` records the session for any class that authenticates the session's
+# user, so DRF's own session class records `session` too.
+UNOWNED_ROUTE_CLASSES = frozenset({authentication.SessionAuthentication})
+
+
+def _dotted_name(cls: type) -> str:
+ return f"{cls.__module__}.{cls.__qualname__}"
+
+
+def _is_test_module(module: str) -> bool:
+ return any(part in ("test", "tests") or part.startswith("test_") for part in module.split("."))
+
+
+def _is_owned(cls: type) -> bool:
+ return cls.__module__.startswith(OWNED_MODULE_PREFIXES) and not _is_test_module(cls.__module__)
+
+
+def _base_name(base: ast.expr) -> str:
+ if isinstance(base, ast.Attribute):
+ return base.attr
+ return base.id if isinstance(base, ast.Name) else ""
+
+
+def _may_be_authentication_class(node: ast.stmt) -> bool:
+ # The method check catches a class whose base is imported under an alias.
+ return isinstance(node, ast.ClassDef) and (
+ any(_base_name(base).endswith("Authentication") for base in node.bases)
+ or any(isinstance(item, ast.FunctionDef) and item.name == "authenticate" for item in node.body)
+ )
+
+
+def _modules_that_may_define_authentication_classes() -> set[str]:
+ modules = set()
+ for root in SCANNED_ROOTS:
+ for path in (REPO_ROOT / root).rglob("*.py"):
+ if SKIPPED_DIRS.intersection(path.parts):
+ continue
+ source = path.read_text(encoding="utf-8", errors="ignore")
+ if "Authentication" not in source and "def authenticate" not in source:
+ continue
+ parts = path.relative_to(REPO_ROOT).with_suffix("").parts
+ module = ".".join(parts[:-1] if parts[-1] == "__init__" else parts)
+ if _is_test_module(module):
+ continue
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+ if any(_may_be_authentication_class(node) for node in tree.body):
+ modules.add(module)
+ return modules
+
+
+def _subclasses(cls: type) -> set[type]:
+ found: set[type] = set()
+ for subclass in cls.__subclasses__():
+ found |= {subclass, *_subclasses(subclass)}
+ return found
+
+
+def _route_classes() -> frozenset[type]:
+ # A view that sets no authentication classes uses DRF's default ones.
+ classes: set[type] = set(APIView.authentication_classes)
+ for _path, _method, callback in EndpointEnumerator().get_api_endpoints():
+ view_class = getattr(callback, "cls", None)
+ classes.update(getattr(view_class, "authentication_classes", None) or [])
+ # An `@action(authentication_classes=...)` overrides the view's classes for its own route.
+ classes.update((getattr(callback, "initkwargs", None) or {}).get("authentication_classes") or [])
+ return frozenset(classes)
+
+
+def _owned_classes() -> tuple[type, ...]:
+ # `__subclasses__()` sees only the classes of imported modules. The routes import the view
+ # modules, and the source scan imports the modules that no route reaches.
+ _route_classes()
+ for module in sorted(_modules_that_may_define_authentication_classes()):
+ importlib.import_module(module)
+ return tuple(sorted((cls for cls in _subclasses(BaseAuthentication) if _is_owned(cls)), key=_dotted_name))
+
+
+def test_every_authentication_class_declares_a_credential_type() -> None:
+ violations = []
+ for cls in _owned_classes():
+ name = _dotted_name(cls)
+ if not issubclass(cls, ActivityCredentialMixin):
+ violations.append(f"{name} does not inherit ActivityCredentialMixin")
+ continue
+ declared = getattr(cls, "activity_credential_type", None)
+ if declared not in DECLARED_TYPES:
+ violations.append(f"{name} declares {declared!r}, which is not a DeclaredCredentialType")
+ elif "authenticate" in vars(cls) and "activity_credential_type" not in vars(cls):
+ violations.append(f"{name} defines authenticate() but inherits activity_credential_type")
+
+ assert not violations, "\n".join(violations)
+
+
+def test_routes_use_only_authentication_classes_that_declare_a_credential_type() -> None:
+ unowned = sorted(
+ _dotted_name(cls) for cls in _route_classes() if not _is_owned(cls) and cls not in UNOWNED_ROUTE_CLASSES
+ )
+
+ assert not unowned, (
+ "Routes use authentication classes that no PostHog module defines, so they declare no credential "
+ "type. Wrap each one in a PostHog subclass:\n" + "\n".join(unowned)
+ )
+
+
+def test_every_credential_type_has_a_declaring_class() -> None:
+ declared = {getattr(cls, "activity_credential_type", None) for cls in _owned_classes()}
+
+ assert DECLARED_TYPES <= declared, (
+ f"No authentication class declares {sorted(DECLARED_TYPES - declared)}. "
+ "Remove the value from DeclaredCredentialType, or check that the walk still finds the classes."
+ )
diff --git a/products/ai_observability/backend/api/personal_spend.py b/products/ai_observability/backend/api/personal_spend.py
index 62d5f66c6ae1..f3a3813e5bd6 100644
--- a/products/ai_observability/backend/api/personal_spend.py
+++ b/products/ai_observability/backend/api/personal_spend.py
@@ -1175,6 +1175,8 @@ class PersonalSpendCrossRegionAuthentication(WebhookSignatureAuthentication):
fails closed on missing headers, unset secret, stale timestamp, or digest
mismatch; the asserted identity lives in the signed body, not `request.user`."""
+ activity_credential_type = "cross_region_signature"
+
def get_signature_header(self) -> str:
return CROSS_REGION_SIGNATURE_HEADER
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 1597b7b324fe..207c61e602a6 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -45,9 +45,8 @@ from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import ErrorResponseSerializer
-from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication
+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, TeamSecretTokenAuthentication
from posthog.models import Team
-from posthog.models.activity_logging.utils import ActivityCredential, record_activity_actor
from posthog.permissions import get_authenticator_scopes, is_authenticated_via_project_secret_api_key
from posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle
@@ -141,6 +140,8 @@ class ExternalAccountProjectSecretAPIKeyAuthentication(ProjectSecretAPIKeyAuthen
key for a disabled team is indistinguishable from an unknown token and the response
cannot reveal that the key exists or which scopes it carries."""
+ activity_credential_type = "project_secret_key"
+
def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
result = super().authenticate(request)
if result is None or not _customer_analytics_enabled(self.project_secret_api_key.team):
@@ -149,6 +150,8 @@ class ExternalAccountProjectSecretAPIKeyAuthentication(ProjectSecretAPIKeyAuthen
class ExternalAccountPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):
+ activity_credential_type = "personal_api_key"
+
def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
try:
return super().authenticate(request)
@@ -194,7 +197,7 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Resp
if 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"))
+ TeamSecretTokenAuthentication.record_activity_actor(None)
return team, None
diff --git a/products/mcp_store/backend/presentation/agent_views.py b/products/mcp_store/backend/presentation/agent_views.py
index efd53dafa2a6..c99c60a4ef6d 100644
--- a/products/mcp_store/backend/presentation/agent_views.py
+++ b/products/mcp_store/backend/presentation/agent_views.py
@@ -33,6 +33,7 @@ from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView
+from posthog.models.activity_logging.utils import ActivityCredentialMixin
from posthog.rate_limit import MCPProxyBurstThrottle, MCPProxySustainedThrottle
from ..agents import GatewayAgentPrincipal, resolve_gateway_agent_token
@@ -75,12 +76,14 @@ class MCPGatewayAgentSustainedThrottle(_MCPGatewayAgentThrottle):
rate = MCPProxySustainedThrottle.rate
-class GatewayAgentAuthentication(BaseAuthentication):
+class GatewayAgentAuthentication(ActivityCredentialMixin, BaseAuthentication):
"""Resolves `Authorization: Bearer mcp_gw_...` to an active service account.
Returns no user — the agent is the principal; downstream code reads it from
`request.auth`."""
+ activity_credential_type = "gateway_agent"
+
def authenticate(self, request: Request) -> tuple[Any, GatewayAgentPrincipal] | None:
header = request.headers.get("Authorization", "")
if not header.startswith("Bearer "):
@@ -91,6 +94,7 @@ class GatewayAgentAuthentication(BaseAuthentication):
raise AuthenticationFailed("Invalid gateway token.")
if principal.account.status != "active":
raise AuthenticationFailed("This agent is paused.")
+ self.record_activity_actor(None, str(principal.account.id))
return (None, principal)
def authenticate_header(self, request: Request) -> str:
diff --git a/products/tasks/backend/presentation/views/task_usage_api.py b/products/tasks/backend/presentation/views/task_usage_api.py
index fa894c5f669b..adf2d63e6927 100644
--- a/products/tasks/backend/presentation/views/task_usage_api.py
+++ b/products/tasks/backend/presentation/views/task_usage_api.py
@@ -22,6 +22,8 @@ from products.tasks.backend.presentation.serializers import (
class TaskUsageCrossRegionAuthentication(WebhookSignatureAuthentication):
+ activity_credential_type = "cross_region_signature"
+
def get_signature_header(self) -> str:
return TASK_USAGE_SIGNATURE_HEADER