: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
fix(auth): refuse deactivated users in all authentication classes (#114081)
Felipe Rosa de Almeida1998cf3d7d04
diff --git a/.agents/security.md b/.agents/security.mdindex 2ed129f3fb81..0fb8d66bbe75 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -50,6 +50,14 @@ Default to the smallest permission, narrowest field set, and shortest scope that- **Unique value per environment — including prod US and prod EU.** Never share a key value across environments; provision each (dev, prod-US, prod-EU) independently so one region can rotate without breaking another and a leak in one doesn't compromise the rest. Enforced at provisioning, not in code — so never hardcode a shared prod default. Fail closed when a prod key is unset (mirror the `SECRET_KEY` startup guard in `posthog/settings/access.py` and `RECORDING_API_JWT_SECRET`'s empty-in-prod default).- **Don't extend `INTERNAL_API_SECRET` to new service-to-service calls.** It's a single fleet-wide shared secret already trusted by many services across Django, Node, and Rust — one leak reaches all of them — so it must not grow new callers or protected endpoints (it's being actively retired edge-by-edge; adding one moves it backwards). For a new internal call, in order of preference: (1) **mint a scoped JWT (strongly preferred)** — a dedicated per-audience signing key (never `INTERNAL_API_SECRET`/`SECRET_KEY`/`JWT_SIGNING_KEY`) with claims pinning the token to its team and operation, verified per-route; use the shared machinery instead of hand-rolling: `ScopedServiceJwtPurpose` + `ScopedServiceJWTAuthentication` in `posthog/scoped_service_jwt.py` (Django mint/verify) and `ScopedServiceJwt` in `nodejs/src/cdp/utils/scoped-service-jwt.ts` (Node mint/verify); worked examples: the conversations ticket route (`products/conversations/backend/api/internal.py`) and its minting worker (`nodejs/src/cdp/async-functions/internal-api-call.ts`). (2) If a JWT genuinely doesn't fit, **a dedicated static secret** scoped to that one caller→callee pair (`<PURPOSE>_API_SECRET`, its own env var, rotatable, empty-in-prod-fail-closed) — never reuse `INTERNAL_API_SECRET`. The goal is blast radius: no single "master" credential that authenticates to a dozen services — a scoped JWT limits a leak to one team + operation; a dedicated secret limits it to one hop.+## Authentication classes++In a test marked with `@covers_authentication(<class>)`, when the class returns a `User`, the same request runs again with that user deactivated and then blocked, and the test fails if either run lets the user in.++- **Mark one test per DRF authentication class.** Decorate a test that authenticates a request through the class with `@covers_authentication(<class>)` from `posthog/test/authentication_checks.py`. `test_authentication_credential_types.py` fails when a class has no marked test.+- **Refuse inactive and blocked users.** Filter on `is_active` and call `refuse_blocked_account()`.+- **A new Django authentication backend** must return `None` from `get_user()` for an inactive user. `TestSessionBackendsRefuseInactiveUsers` checks every backend in `AUTHENTICATION_BACKENDS`.+## SQL Security- **Never** use f-strings with user-controlled values in SQL queries - this creates SQL injection vulnerabilitiesdiff --git a/conftest.py b/conftest.pyindex 40ff8864898a..584a97f6bb60 100644--- a/conftest.py+++ b/conftest.py@@ -240,6 +240,9 @@ def pytest_configure(config) -> None:_cache_drf_field_info()_cache_url_resolution()_cache_fixture_parent_nodeids()+ from posthog.test import authentication_checks # noqa: PLC0415 — deferred until pytest_configure++ authentication_checks.install()if record_path := os.environ.get("POSTHOG_EVENTS_SCHEMA_RECORD_PATH"):from posthog.test.events_schema_recorder import ( # noqa: PLC0415 - keeps the Temporal client off other runsEventsSchemaRecorder,@@ -254,6 +257,23 @@ def pytest_collection_finish() -> None:_end_gc_boot_window()+def pytest_runtest_setup(item: pytest.Item) -> None:+ from posthog.test import authentication_checks # noqa: PLC0415++ marker = item.get_closest_marker("covers_authentication")+ authentication_checks.start_test(marker.args if marker else ())++[email protected](wrapper=True)+def pytest_runtest_call(item: pytest.Item) -> Generator[None]:+ from posthog.test import authentication_checks # noqa: PLC0415++ result = yield+ if problems := authentication_checks.finish_test():+ pytest.fail("\n".join(problems))+ return result++@pytest.hookimpl(hookwrapper=True, tryfirst=True)def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo[None]) -> Generator[None]:outcome = yielddiff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex dbd81af97c1e..dc7154781a91 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -16,8 +16,10 @@ from posthog.models.organization import Organizationfrom posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.user import User+from posthog.test.authentication_checks import covers_authenticationfrom ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.authentication import ProvisioningAuthenticationfrom ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase, provisioning_config@@ -46,6 +48,7 @@ class TestAccountRequests(ProvisioningTestBase):assert data["type"] == "error"assert data["error"]["code"] == "unauthorized"+ @covers_authentication(ProvisioningAuthentication)def test_new_user_returns_oauth_type_with_code(self):res = self._post_account_request(self._account_request_payload())assert res.status_code == 200diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.pyindex a80a9902aa41..b47363bf47f7 100644--- a/ee/api/agentic_provisioning/test/test_github_grants.py+++ b/ee/api/agentic_provisioning/test/test_github_grants.py@@ -9,9 +9,11 @@ from parameterized import parameterizedfrom posthog.models.integration import GitHubUserAuthorizationfrom posthog.models.oauth import OAuthApplication+from posthog.test.authentication_checks import covers_authenticationfrom posthog.token_bucket import Budgetfrom ee.api.agentic_provisioning import github_grants+from ee.api.agentic_provisioning.authentication import ConfidentialPartnerAuthentication, GitHubGrantsAuthenticationfrom ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import (TEST_PARTNER_CLIENT_SECRET,@@ -88,6 +90,7 @@ class TestGitHubGrants(ProvisioningTestBase):{"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},)+ @covers_authentication(ConfidentialPartnerAuthentication, GitHubGrantsAuthentication)def test_create_grant_happy_path(self):with (patch(diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.pyindex 940187bb4e9e..1e2ac8355430 100644--- a/ee/api/agentic_provisioning/test/test_resources.py+++ b/ee/api/agentic_provisioning/test/test_resources.py@@ -6,13 +6,16 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.test.authentication_checks import covers_authentication+from ee.api.agentic_provisioning.authentication import ProvisioningBearerAuthenticationfrom ee.api.agentic_provisioning.credentials import maybe_create_provisioned_patfrom ee.api.agentic_provisioning.ratelimits import RATE_LIMITED_MESSAGEfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase, provisioning_configclass TestProvisioningResources(ProvisioningTestBase):+ @covers_authentication(ProvisioningBearerAuthentication)def test_create_resource_returns_complete(self):token = self._get_bearer_token()res = self._post_with_bearer(diff --git a/ee/api/scim/test/test_scim_api.py b/ee/api/scim/test/test_scim_api.pyindex 14801f19a5ef..4ba2a2dd04a5 100644--- a/ee/api/scim/test/test_scim_api.py+++ b/ee/api/scim/test/test_scim_api.py@@ -7,10 +7,11 @@ 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.test.authentication_checks import covers_authenticationfrom products.access_control.backend.models.role import Role-from ee.api.scim.auth import generate_scim_token+from ee.api.scim.auth import SCIMBearerTokenAuthentication, generate_scim_tokenfrom ee.api.scim.user import PostHogSCIMUserfrom ee.api.scim.utils import get_scim_base_urlfrom ee.api.test.base import APILicensedTest@@ -184,6 +185,7 @@ class TestSCIMAPI(APILicensedTest):assert data["status"] == 403assert "detail" in data+ @covers_authentication(SCIMBearerTokenAuthentication)def test_scim_users_endpoint(self):"""Test that SCIM Users endpoint works with valid license"""self.client.credentials(**self.scim_headers)diff --git a/ee/api/vercel/test/test_vercel_authentication.py b/ee/api/vercel/test/test_vercel_authentication.pyindex b2f7beedc1fe..72e0632b8560 100644--- a/ee/api/vercel/test/test_vercel_authentication.py+++ b/ee/api/vercel/test/test_vercel_authentication.py@@ -16,6 +16,7 @@ from rest_framework.exceptions import AuthenticationFailedfrom rest_framework.test import APIRequestFactoryfrom posthog.models.activity_logging.utils import ActivityCredential, activity_storage+from posthog.test.authentication_checks import covers_authenticationfrom ee.api.authentication import VercelAuthenticationfrom ee.api.vercel.types import VercelUser, VercelUserClaims@@ -106,6 +107,7 @@ class TestVercelAuthentication(SimpleTestCase):def _exp(self, seconds: int = 3600) -> float:return timezone.now().timestamp() + seconds+ @covers_authentication(VercelAuthentication)def test_user_auth_valid_token(self, mock_get_jwks):mock_get_jwks.return_value = self.mock_jwkstoken = self._token()diff --git a/ee/api/vercel/test/test_vercel_proxy.py b/ee/api/vercel/test/test_vercel_proxy.pyindex 1cbb8c8455c6..ce0d0381fbca 100644--- a/ee/api/vercel/test/test_vercel_proxy.py+++ b/ee/api/vercel/test/test_vercel_proxy.py@@ -10,6 +10,7 @@ from rest_framework.test import APIClientfrom posthog.models.organization import Organizationfrom posthog.models.organization_integration import OrganizationIntegration+from posthog.test.authentication_checks import covers_authenticationfrom ee.api.authentication import BillingServiceAuthenticationfrom ee.models import License@@ -390,6 +391,7 @@ class TestBillingServiceAuthentication(BaseTest):return jwt.encode(payload, secret, algorithm="HS256")+ @covers_authentication(BillingServiceAuthentication)def test_valid_token_authenticates(self, mock_license):mock_license.return_value = self.licensediff --git a/ee/partners/stripe/api/provisioning/test/test_resources.py b/ee/partners/stripe/api/provisioning/test/test_resources.pyindex a09ec9523722..8001563c11a4 100644--- a/ee/partners/stripe/api/provisioning/test/test_resources.py+++ b/ee/partners/stripe/api/provisioning/test/test_resources.py@@ -14,10 +14,12 @@ from posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.utils import generate_random_oauth_access_token+from posthog.test.authentication_checks import covers_authenticationfrom products.access_control.backend.models.access_control import AccessControlfrom ee.models.license import License+from ee.partners.stripe.api.provisioning.authentication import StripeBearerAuthenticationfrom ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBaseRESOURCES_URL = f"{BASE_PATH}/provisioning/resources"@@ -210,6 +212,7 @@ class TestResources(StripeProvisioningTestBase):assert res.status_code == expected_status, res.json()assert [call.kwargs["json"] for call in billing_post.call_args_list] == expected_billing_payloads+ @covers_authentication(StripeBearerAuthentication)def test_detail_returns_resource(self):token = self._get_bearer_token()res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.pyindex 8211e3832103..cd4fabbd985c 100644--- a/posthog/api/test/test_activity_log.py+++ b/posthog/api/test/test_activity_log.py@@ -14,6 +14,7 @@ from rest_framework import statusfrom posthog.api.advanced_activity_logs import ActivityLogSerializerfrom posthog.api.my_notifications import MyNotificationsSerializer+from posthog.auth import JwtAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User@@ -22,6 +23,7 @@ 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_valuefrom posthog.session.activity import session_public_id+from posthog.test.authentication_checks import covers_authenticationfrom posthog.test.insight_queries import default_pageview_queryfrom products.exports.backend.models.exported_asset import ExportedAsset@@ -583,6 +585,7 @@ class TestActivityLogBearerAuthAttribution(APIBaseTest):assert session_key is not Noneassert (log.credential_type, log.credential_id) == ("session", str(session_public_id(session_key)))+ @covers_authentication(JwtAuthentication)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)diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 35f4904ce8de..3cef6cc38eee 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -10,7 +10,7 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import ANY, MagicMock, patchfrom django.conf import settings-from django.contrib.auth import BACKEND_SESSION_KEY+from django.contrib.auth import BACKEND_SESSION_KEY, load_backendfrom django.contrib.sessions.middleware import SessionMiddlewarefrom django.core import mailfrom django.core.asgi import get_asgi_application@@ -20,6 +20,7 @@ from django.http import HttpRequest, HttpResponsefrom django.test import RequestFactory, SimpleTestCase, override_settingsfrom django.test.utils import CaptureQueriesContextfrom django.utils import timezone+from django.utils.module_loading import import_stringfrom asgiref.sync import sync_to_asyncfrom django_otp.oath import totp@@ -71,6 +72,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.test.authentication_checks import covers_authenticationfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -877,6 +879,19 @@ class TestInternalTokensRefuseBlockedAccounts(APIBaseTest):assert result is not None and result[0] == self.user+class TestSessionBackendsRefuseInactiveUsers(APIBaseTest):+ @parameterized.expand(+ [(path,) for path in settings.AUTHENTICATION_BACKENDS if hasattr(import_string(path), "get_user")]+ )+ def test_get_user_refuses_inactive_user(self, backend_path: str) -> None:+ backend = load_backend(backend_path)+ assert backend.get_user(self.user.pk) == self.user++ User.objects.filter(pk=self.user.pk).update(is_active=False)++ assert backend.get_user(self.user.pk) is None++class TestLogoutRedirect(APIBaseTest):"""Tests that /logout preserves a safe `next` param so users return to where they were@@ -2470,6 +2485,7 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):self.team.save()self.factory = APIRequestFactory() # Use APIRequestFactory instead of RequestFactory+ @covers_authentication(TeamSecretTokenAuthentication)def test_authenticate_with_valid_secret_api_key_in_header(self):# Simulate a request with a valid team secret tokenwsgi_request = self.factory.get(@@ -2694,6 +2710,7 @@ class TestProjectSecretAPIKeyAuthentication(APIBaseTest):wsgi_request = self.factory.get("/", HTTP_AUTHORIZATION=f"Bearer {token}")return Request(wsgi_request)+ @covers_authentication(ProjectSecretAPIKeyAuthentication)def test_authenticate_with_valid_psak_in_header(self):authenticator = ProjectSecretAPIKeyAuthentication()result = authenticator.authenticate(self._request_with_header(self.token))@@ -2853,6 +2870,7 @@ class TestOAuthAccessTokenAuthentication(APIBaseTest):scope="openid profile",)+ @covers_authentication(OAuthAccessTokenAuthentication)def test_authenticate_with_valid_oauth_token(self):wsgi_request = self.factory.get("/",diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex f28e27947fd1..41879d4ce0b9 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -51,6 +51,7 @@ from posthog.models.organization_domain import OrganizationDomainfrom posthog.models.user import User as UserModelfrom posthog.permissions import get_authenticator_clientfrom posthog.settings.utils import generate_rsa_private_key_pem+from posthog.test.authentication_checks import covers_authentication# rsa operations are expensive, keep this at the module-level to avoid slow tests_IDP_PRIVATE_KEY_PEM = generate_rsa_private_key_pem()@@ -1094,6 +1095,7 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):get_authenticator_client(authenticator), {"credential_type": "id_jag", "client_id": "agent_client_id"})+ @covers_authentication(IDJagAccessTokenAuthentication)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_livestream.py b/posthog/api/test/test_livestream.pyindex 24d91abb5363..832ac024c98c 100644--- a/posthog/api/test/test_livestream.py+++ b/posthog/api/test/test_livestream.py@@ -7,9 +7,11 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.api.livestream import LivestreamAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import OrganizationDomain, OrganizationMembership, PropertyDefinition+from posthog.test.authentication_checks import covers_authenticationfrom posthog.test.persons import create_group_type_mappingfrom products.access_control.backend.models.access_control import AccessControl@@ -100,6 +102,7 @@ class TestLivestreamAuthorization(APIBaseTest):self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization).status_code, 401)+ @covers_authentication(LivestreamAuthentication)def test_lists_the_properties_hidden_from_the_user(self) -> None:self.organization.available_product_features = [{"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex b026b62a78b9..407dfd7cd774 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -23,6 +23,7 @@ from posthog.api.llm_prompt_serializers import (validate_prompt_label_name_value,)from posthog.api.services.llm_prompt import MAX_PROMPT_VERSION+from posthog.auth import DelegatedOAuthAccessTokenAuthenticationfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import PersonalAPIKeyfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -35,6 +36,7 @@ from posthog.rate_limit import (SustainedRateThrottle,)from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache+from posthog.test.authentication_checks import covers_authenticationfrom products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabelfrom products.ai_observability.backend.prompt_references import (@@ -1592,6 +1594,7 @@ class TestLLMPromptLabelsAPI(APIBaseTest):@override_settings(TEST=False)@patch("posthog.api.llm_prompt.capture_internal")@patch("posthog.api.llm_prompt.report_team_action")+ @covers_authentication(DelegatedOAuthAccessTokenAuthentication)def test_list_reports_one_fetch_per_request_unless_the_caller_is_the_ui(self, mock_report: Any, mock_capture: Any) -> None:diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex 7523bf975605..967745548e70 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -14,6 +14,7 @@ from rest_framework import statusfrom posthog.schema import EventsQueryfrom posthog.api.personal_api_key import PersonalAPIKeySerializer+from posthog.auth import PersonalAPIKeyAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.helpers.dev_api_key import get_local_dev_api_key_valuefrom posthog.jwt import PosthogJwtAudience, encode_jwt@@ -24,6 +25,7 @@ from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, Personfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value, mask_key_value+from posthog.test.authentication_checks import covers_authenticationfrom products.product_analytics.backend.facade.models import Insight@@ -544,6 +546,7 @@ class TestPersonalAPIKeysAPIAuthentication(PersonalAPIKeysBaseTest):)assert response.status_code == status.HTTP_401_UNAUTHORIZED+ @covers_authentication(PersonalAPIKeyAuthentication)def test_user_endpoint(self):# NOTE: This is not actually supported currently by new scopes but needs to work for pre-scoped api keysresponse = self.client.get("/api/users/@me/", headers={"authorization": f"Bearer {self.value}"})diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex b368ed1f94c3..94a3e9091538 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -24,6 +24,7 @@ from posthog.api.sharing import (check_can_access_sharing_configuration,shared_url_as_png,)+from posthog.auth import SharingPasswordProtectedAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, decode_jwtfrom posthog.models import ActivityLog, OrganizationMembership@@ -31,6 +32,7 @@ from posthog.models.data_color_theme import DataColorThemefrom posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import User+from posthog.test.authentication_checks import covers_authenticationfrom posthog.test.insight_queries import browser_filtered_pageview_queryfrom products.access_control.backend.models.access_control import AccessControl@@ -177,6 +179,7 @@ class TestSharing(APIBaseTest):mock_record_access.assert_called_once_with(expected_access_method)@patch("posthog.api.sharing.render_template")+ @covers_authentication(SharingPasswordProtectedAuthentication)def test_password_protected_dashboard_does_not_add_social_metadata(self, mock_render_template: Mock) -> None:sharing_configuration = SharingConfiguration.objects.create(team=self.team,diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex bce292ab91f3..9887d72ba50b 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -30,6 +30,7 @@ from social_django.models import UserSocialAuthfrom posthog.api.email_verification import email_verification_code_verifierfrom posthog.api.oauth.toolbar_service import ToolbarOAuthState, build_toolbar_oauth_state, new_state_noncefrom posthog.api.user import MAX_PRODUCT_INTROS_SEEN, UserSerializer+from posthog.auth import SessionAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.helpers.two_factor_session import code_based_verification_token_generatorfrom posthog.models import Team, User@@ -42,6 +43,7 @@ from posthog.models.user import default_ui_configuration_for_new_usersfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.temporal.tests.delete_teams.inline import execute_deletion_workflows_inline+from posthog.test.authentication_checks import covers_authenticationfrom products.access_control.backend.models.access_control import AccessControlfrom products.dashboards.backend.models.dashboard import Dashboard@@ -92,6 +94,7 @@ class TestUserAPI(APIBaseTest):# RETRIEVING USER+ @covers_authentication(SessionAuthentication)def test_retrieve_current_user(self):response = self.client.get("/api/users/@me/")diff --git a/posthog/auth.py b/posthog/auth.pyindex 004012614069..a0aea9c0f097 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -585,7 +585,7 @@ class JwtAuthentication(ActivityCredentialMixin, authentication.BaseAuthenticatitry:token = authorization_match.group(1).strip()info = decode_jwt(token, PosthogJwtAudience.IMPERSONATED_USER)- user = User.objects.get(pk=info["id"])+ user = User.objects.get(pk=info["id"], is_active=True)refuse_blocked_account(request, user, call_site="jwt", impersonated=False)self.record_activity_actor(user)return (user, None)@@ -846,7 +846,7 @@ class ExportRendererAuthentication(ActivityCredentialMixin, authentication.BaseAself.team_id = team_idself.exported_asset_id = exported_asset_idself.export_context = export_context- user = User.objects.get(pk=user_id)+ user = User.objects.get(pk=user_id, is_active=True)except (jwt.DecodeError, jwt.InvalidAudienceError):return Noneexcept Exception:diff --git a/posthog/test/authentication_checks.py b/posthog/test/authentication_checks.pynew file mode 100644index 000000000000..42afadec276c--- /dev/null+++ b/posthog/test/authentication_checks.py@@ -0,0 +1,121 @@+import functools+import threading+from typing import Any++import pytest+from unittest.mock import NonCallableMock, patch++from django.db import transaction++from rest_framework.authentication import BaseAuthentication+from rest_framework.exceptions import AuthenticationFailed++from posthog.models import User++_covered_classes: tuple[type, ...] = ()+_authenticated_classes: set[type] = set()+_replayed_classes: set[type] = set()+_problems: list[str] = []+_state = threading.local()+++def install() -> None:+ for cls in _subclasses(BaseAuthentication):+ _wrap(cls)+ BaseAuthentication.__init_subclass__ = classmethod(lambda cls, **kwargs: _wrap(cls)) # type: ignore[method-assign,assignment] # ty: ignore[invalid-assignment]+++def covers_authentication(*classes: type) -> pytest.MarkDecorator:+ return pytest.mark.covers_authentication.with_args(*classes)+++def start_test(covered_classes: tuple[type, ...]) -> None:+ global _covered_classes+ _covered_classes = covered_classes+ _authenticated_classes.clear()+ _replayed_classes.clear()+ _problems.clear()+++def finish_test() -> list[str]:+ problems = list(_problems)+ for cls in _covered_classes:+ if not any(issubclass(seen, cls) for seen in _authenticated_classes):+ problems.append(f"{cls.__qualname__} did not authenticate a request in this test.")+ return problems+++def _subclasses(cls: type) -> set[type]:+ found: set[type] = set()+ for subclass in cls.__subclasses__():+ found |= {subclass, *_subclasses(subclass)}+ return found+++def _wrap(cls: type) -> None:+ original = vars(cls).get("authenticate")+ if original is None or getattr(original, "_checked", False):+ return++ @functools.wraps(original)+ def authenticate(self: BaseAuthentication, request: Any) -> Any:+ if getattr(_state, "active", False):+ return original(self, request)+ _state.active = True+ try:+ result = original(self, request)+ if result is not None:+ _authenticated_classes.add(type(self))+ _replay(type(self), request, result[0])+ return result+ finally:+ _state.active = False++ authenticate._checked = True # type: ignore[attr-defined]+ cls.authenticate = authenticate # type: ignore[attr-defined]+++def _attempt(authentication_class: type, request: Any) -> tuple[Any, Exception | None]:+ try:+ result = authentication_class().authenticate(request)+ except Exception as error:+ return None, error+ return (result[0] if result else None), None+++def _replay(authentication_class: type, request: Any, user: Any) -> None:+ if not isinstance(user, User):+ return+ name = authentication_class.__qualname__+ if not user.is_active:+ _problems.append(f"{name}.authenticate() accepted a deactivated user.")+ return+ if authentication_class in _replayed_classes or not issubclass(authentication_class, _covered_classes):+ return+ _replayed_classes.add(authentication_class)+ if isinstance(user, NonCallableMock) or user.pk is None:+ _problems.append(+ f"{name} authenticated a mock or unsaved user in its covering test, so its refusal was not checked."+ )+ return++ with transaction.atomic():+ try:+ User.objects.filter(pk=user.pk).update(is_active=False)+ user.is_active = False+ principal, _error = _attempt(authentication_class, request)+ finally:+ user.is_active = True+ transaction.set_rollback(True)+ if isinstance(principal, User):+ _problems.append(f"{name}.authenticate() accepted a deactivated user.")++ with transaction.atomic(), patch("posthog.auth.security_access_refused", return_value=True):+ try:+ principal, error = _attempt(authentication_class, request)+ finally:+ transaction.set_rollback(True)+ if isinstance(principal, User):+ _problems.append(f"{name}.authenticate() accepted a blocked account.")+ elif isinstance(error, AuthenticationFailed) and error.get_codes() != "access_blocked":+ _problems.append(f"{name}.authenticate() refused a blocked account without the access_blocked code.")diff --git a/posthog/test/repo_invariants/test_authentication_credential_types.py b/posthog/test/repo_invariants/test_authentication_credential_types.pyindex 8a7bf80fdc1a..f88c298ca0ad 100644--- a/posthog/test/repo_invariants/test_authentication_credential_types.py+++ b/posthog/test/repo_invariants/test_authentication_credential_types.py@@ -147,3 +147,28 @@ def test_every_credential_type_has_a_declaring_class() -> None:f"No authentication class declares {sorted(DECLARED_TYPES - declared)}. ""Remove the value from DeclaredCredentialType, or check that the walk still finds the classes.")+++def _classes_named_in_covers_authentication_markers() -> set[str]:+ names: set[str] = set()+ for root in SCANNED_ROOTS:+ for path in (REPO_ROOT / root).rglob("test_*.py"):+ if SKIPPED_DIRS.intersection(path.parts):+ continue+ source = path.read_text(encoding="utf-8", errors="ignore")+ if "covers_authentication" not in source:+ continue+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.Call) and _base_name(node.func) == "covers_authentication":+ names.update(_base_name(arg) for arg in node.args)+ return names+++def test_every_authentication_class_has_a_covering_test() -> None:+ covered = _classes_named_in_covers_authentication_markers()+ uncovered = sorted(_dotted_name(cls) for cls in _owned_classes() if cls.__name__ not in covered)++ assert not uncovered, (+ "Mark one test that authenticates a request through each of these classes with "+ "`@covers_authentication(<class>)` from posthog.test.authentication_checks:\n" + "\n".join(uncovered)+ )diff --git a/posthog/test/test_export_renderer_auth.py b/posthog/test/test_export_renderer_auth.pyindex 3356aaaafcc1..436c2af6e978 100644--- a/posthog/test/test_export_renderer_auth.py+++ b/posthog/test/test_export_renderer_auth.py@@ -7,8 +7,10 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient+from posthog.auth import ExportRendererAuthenticationfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models.team import Team+from posthog.test.authentication_checks import covers_authenticationfrom products.cohorts.backend.models.cohort import Cohortfrom products.exports.backend.models.exported_asset import ExportedAsset@@ -126,6 +128,7 @@ class TestExportRendererAuthentication(APIBaseTest):assert response.status_code == status.HTTP_200_OK+ @covers_authentication(ExportRendererAuthentication)def test_screenshot_token_accepts_content_and_heatmap_data(self) -> None:export_context = {"heatmap_url": f"https://example.com/api/environments/{self.team.id}/heatmap_screenshots/42/content/?width=1400",diff --git a/posthog/test/test_internal_api_auth.py b/posthog/test/test_internal_api_auth.pyindex 0755f649eb52..896cce110d78 100644--- a/posthog/test/test_internal_api_auth.py+++ b/posthog/test/test_internal_api_auth.py@@ -11,6 +11,7 @@ from rest_framework.request import Requestfrom posthog.auth import InternalAPIAuthenticationfrom posthog.settings import LOCAL_DEV_INTERNAL_API_SECRET+from posthog.test.authentication_checks import covers_authenticationclass TestInternalAPIAuthWithoutDatabase(SimpleTestCase):@@ -19,6 +20,7 @@ class TestInternalAPIAuthWithoutDatabase(SimpleTestCase):self.authentication = InternalAPIAuthentication()@override_settings(INTERNAL_API_SECRET="test-secret-123")+ @covers_authentication(InternalAPIAuthentication)def test_valid_secret_allows_access(self):request = Request(self.factory.get("/internal/endpoint", HTTP_X_INTERNAL_API_SECRET="test-secret-123"))user, auth = self.authentication.authenticate(request)diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex f3ec2f388e24..2a854f90cfee 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -15,6 +15,7 @@ from rest_framework.exceptions import ErrorDetail, PermissionDeniedfrom rest_framework.test import APIRequestFactoryfrom posthog.auth import (+ DelegatedPersonalAPIKeyAuthentication,ExportRendererAuthentication,IDJagAccessTokenAuthentication,JwtAuthentication,@@ -42,6 +43,7 @@ from posthog.permissions import (extract_organization,get_authenticator_client,)+from posthog.test.authentication_checks import covers_authenticationfrom products.access_control.backend.facade.contracts import ObjectAccessReffrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -812,6 +814,7 @@ class TestDelegatedJwtPermissions(BaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN+ @covers_authentication(DelegatedPersonalAPIKeyAuthentication)def test_delegated_personal_api_key_filters_organization_list(self) -> None:other_organization, _, _ = Organization.objects.bootstrap(self.user)worker_token, _credential = self._create_delegated_token(diff --git a/posthog/test/test_scoped_service_jwt.py b/posthog/test/test_scoped_service_jwt.pyindex 26ef0576c682..bb4864003e55 100644--- a/posthog/test/test_scoped_service_jwt.py+++ b/posthog/test/test_scoped_service_jwt.py@@ -17,6 +17,7 @@ from rest_framework.request import Requestfrom posthog.auth import ScopedServiceJWTAuthenticationfrom posthog.jwt import PosthogJwtAudiencefrom posthog.scoped_service_jwt import ScopedServiceJwtPurpose+from posthog.test.authentication_checks import covers_authenticationTEST_PURPOSE = ScopedServiceJwtPurpose(audience=PosthogJwtAudience.RECORDING_API,@@ -131,6 +132,7 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):assert result is not Nonereturn result+ @covers_authentication(ScopedServiceJWTAuthentication)def test_valid_token_authenticates_as_the_token_team(self):token = TEST_PURPOSE.mint({"team_id": self.team.id})diff --git a/products/ai_observability/backend/api/test/test_personal_spend.py b/products/ai_observability/backend/api/test/test_personal_spend.pyindex 23d7b25eea78..b8b3ce96189e 100644--- a/products/ai_observability/backend/api/test/test_personal_spend.py+++ b/products/ai_observability/backend/api/test/test_personal_spend.py@@ -30,10 +30,12 @@ from posthog.models import Teamfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.test.authentication_checks import covers_authenticationfrom products.ai_observability.backend.api.personal_spend import (CROSS_REGION_SIGNATURE_HEADER,CROSS_REGION_TIMESTAMP_HEADER,+ PersonalSpendCrossRegionAuthentication,PersonalSpendEUProxyViewSet,sign_cross_region_spend_request,)@@ -944,6 +946,7 @@ class TestPersonalSpendInternalEndpoint(ClickhouseTestMixin, APIBaseTest):response = self._post(body, _signed_headers(body))assert response.status_code == status.HTTP_400_BAD_REQUEST+ @covers_authentication(PersonalSpendCrossRegionAuthentication)def test_signed_request_computes_spend_for_asserted_email(self) -> None:_create_person(distinct_ids=["eu-user"], team=self.team, properties={"email": "[email protected]"})_create_event(diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.pyindex fb1c9d33c3f8..d18c0487ff82 100644--- a/products/conversations/backend/api/tests/test_external.py+++ b/products/conversations/backend/api/tests/test_external.py@@ -16,7 +16,9 @@ from rest_framework.test import APIClientfrom posthog.models import ActivityLog, Comment, Teamfrom posthog.models.utils import generate_random_token_secretfrom posthog.test.api_keys import create_project_secret_api_key+from posthog.test.authentication_checks import covers_authentication+from products.conversations.backend.api.external import ExternalTicketProjectSecretAPIKeyAuthenticationfrom products.conversations.backend.api.ticket_actions import _truncate_bytesfrom products.conversations.backend.models import Ticketfrom products.conversations.backend.models.constants import Priority, Status@@ -50,6 +52,7 @@ class TestExternalTicketAPI(BaseTest):# -- Authentication ---------------------------------------------------+ @covers_authentication(ExternalTicketProjectSecretAPIKeyAuthentication)def test_get_accepts_project_secret_api_key_with_support_ticket_read_scope(self):response = self.client.get(self.url, **self._auth_headers(self._create_psak_token(["support_ticket:read"])))self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/products/conversations/backend/api/tests/test_internal.py b/products/conversations/backend/api/tests/test_internal.pyindex 6d0ee077c935..87b92fb10bd2 100644--- a/products/conversations/backend/api/tests/test_internal.py+++ b/products/conversations/backend/api/tests/test_internal.py@@ -14,8 +14,12 @@ from posthog.jwt import PosthogJwtAudiencefrom posthog.models import Commentfrom posthog.models.utils import generate_random_token_secretfrom posthog.scoped_service_jwt import ScopedServiceJwtPurpose+from posthog.test.authentication_checks import covers_authentication-from products.conversations.backend.api.internal import CONVERSATIONS_TICKETS_PURPOSE+from products.conversations.backend.api.internal import (+ CONVERSATIONS_TICKETS_PURPOSE,+ ConversationsTicketJWTAuthentication,+)from products.conversations.backend.models import Ticketfrom products.conversations.backend.models.constants import WORKFLOW_AUTHOR_NAME, WORKFLOW_AUTHOR_TYPE, Status@@ -53,6 +57,7 @@ class TestInternalTicketAPI(BaseTest):def _bearer(token: str) -> dict:return {"HTTP_AUTHORIZATION": f"Bearer {token}"}+ @covers_authentication(ConversationsTicketJWTAuthentication)def test_get_returns_ticket_for_minted_token(self):response = self.client.get(self.url, **self._headers())self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.pyindex 82a39b7938dd..85e5a8301034 100644--- a/products/conversations/backend/api/tests/test_widget.py+++ b/products/conversations/backend/api/tests/test_widget.py@@ -13,8 +13,10 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient+from posthog.auth import WidgetAuthenticationfrom posthog.models.comment import Commentfrom posthog.rate_limit import WidgetTeamPollThrottle+from posthog.test.authentication_checks import covers_authenticationfrom products.conversations.backend.api.serializers import WidgetMessageSerializer, WidgetTicketsQuerySerializerfrom products.conversations.backend.models import SigningSecret, Ticket@@ -80,6 +82,7 @@ class TestWidgetAPI(BaseTest):)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ @covers_authentication(WidgetAuthentication)def test_create_message_creates_ticket(self):response = self.client.post("/api/conversations/v1/widget/message",diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 1e8b87edee86..eb64428d53a2 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -16,6 +16,7 @@ from posthog.models import Organization, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.utils import generate_random_token_secretfrom posthog.test.api_keys import create_project_secret_api_key+from posthog.test.authentication_checks import covers_authenticationfrom posthog.test.persons import create_groupfrom products.customer_analytics.backend.models import (@@ -27,6 +28,9 @@ from products.customer_analytics.backend.models import (DisplayType,)from products.customer_analytics.backend.models.account import AccountProperties+from products.customer_analytics.backend.presentation.views.external import (+ ExternalAccountProjectSecretAPIKeyAuthentication,+)from products.customer_analytics.backend.test.factories import (create_account,create_custom_property_definition,@@ -133,6 +137,7 @@ class TestExternalAccountAPI(APIBaseTest):self.assertEqual(response.json(), {"error": "Invalid API key"})self.assertFalse(Account.objects.for_team(self.team.id).filter(external_id="acme-2").exists())+ @covers_authentication(ExternalAccountProjectSecretAPIKeyAuthentication)def test_get_accepts_project_secret_api_key_with_account_read_scope(self):response = self._get(token=self._create_psak_token(scopes=["account:read"]))self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/products/customer_analytics/backend/test/test_external_list.py b/products/customer_analytics/backend/test/test_external_list.pyindex 3b97b5902493..8d1aa4498684 100644--- a/products/customer_analytics/backend/test/test_external_list.py+++ b/products/customer_analytics/backend/test/test_external_list.py@@ -18,10 +18,12 @@ from posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, Userfrom posthog.models.utils import generate_random_token_personal, generate_random_token_secret, hash_key_valuefrom posthog.test.api_keys import create_project_secret_api_key+from posthog.test.authentication_checks import covers_authenticationfrom products.access_control.backend.models.access_control import AccessControlfrom products.customer_analytics.backend.facade import api as facadefrom products.customer_analytics.backend.models import AccountRelationship, AccountRelationshipDefinition+from products.customer_analytics.backend.presentation.views.external import ExternalAccountPersonalAPIKeyAuthenticationfrom products.customer_analytics.backend.test.factories import create_account, enroll_accountENDED_AT = datetime(2026, 1, 1, tzinfo=UTC)@@ -146,6 +148,7 @@ class TestExternalAccountListAPI(APIBaseTest):response = self._get(params={} if project_id is None else {"project_id": project_id}, token=token)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ @covers_authentication(ExternalAccountPersonalAPIKeyAuthentication)def test_personal_key_returns_not_found_for_deleted_project(self) -> None:project = Team.objects.create(organization=self.organization, name="Deleted project")project_id = project.iddiff --git a/products/customer_analytics/backend/test/test_internal.py b/products/customer_analytics/backend/test/test_internal.pyindex 9a2d05e6d905..f91ec62aac73 100644--- a/products/customer_analytics/backend/test/test_internal.py+++ b/products/customer_analytics/backend/test/test_internal.py@@ -13,10 +13,14 @@ from rest_framework.test import APIClientfrom posthog.jwt import PosthogJwtAudiencefrom posthog.models.utils import generate_random_token_secretfrom posthog.scoped_service_jwt import ScopedServiceJwtPurpose+from posthog.test.authentication_checks import covers_authenticationfrom products.customer_analytics.backend.facade import contractsfrom products.customer_analytics.backend.models import CustomPropertyValue-from products.customer_analytics.backend.presentation.views.internal import CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE+from products.customer_analytics.backend.presentation.views.internal import (+ CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE,+ CustomerAnalyticsAccountJWTAuthentication,+)from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition# Signed with this route's key but carrying another surface's audience — a token minted for a@@ -52,6 +56,7 @@ class TestInternalAccountAPI(APIBaseTest):def _bearer(token: str) -> dict:return {"HTTP_AUTHORIZATION": f"Bearer {token}"}+ @covers_authentication(CustomerAnalyticsAccountJWTAuthentication)def test_get_returns_account_for_minted_token(self):response = self.client.get(self.url, data={"external_id": "acme-1"}, **self._headers())self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex df6c1346b3a1..18eb922e2e00 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -24,6 +24,7 @@ from posthog.models.instance_setting import override_instance_configfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import OrganizationMembershipfrom posthog.security.url_validation import PinnedUrlVerdict+from posthog.test.authentication_checks import covers_authenticationfrom products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agentsfrom products.mcp_store.backend.catalog import MCP_SERVER_CATALOG@@ -42,6 +43,7 @@ from products.mcp_store.backend.models import (TeamMCPGatewayConfig,)from products.mcp_store.backend.oauth import DcrClientRegistration, DCRRegistrationRejectedError+from products.mcp_store.backend.presentation.agent_views import GatewayAgentAuthenticationfrom products.mcp_store.backend.presentation.gateway_views import (MAX_TOOL_POLICIES_PER_REQUEST,GatewayPoliciesUpsertSerializer,@@ -2057,6 +2059,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):account.save(update_fields=["status", "updated_at"])assert client.get("/api/mcp_store/gateway/servers/").status_code == status.HTTP_401_UNAUTHORIZED+ @covers_authentication(GatewayAgentAuthentication)def test_agent_endpoint_does_not_gate_on_product_state(self) -> None:account = self._active_scout_account()client = self._agent_client(account)diff --git a/products/messaging/backend/tests/api/test_customerio_webhook.py b/products/messaging/backend/tests/api/test_customerio_webhook.pyindex 0844a4dbd30c..8f9046dbba17 100644--- a/products/messaging/backend/tests/api/test_customerio_webhook.py+++ b/products/messaging/backend/tests/api/test_customerio_webhook.py@@ -6,7 +6,9 @@ import hashlibfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from posthog.auth import WebhookSignatureAuthenticationfrom posthog.models.integration import Integration+from posthog.test.authentication_checks import covers_authenticationfrom products.messaging.backend.models.message_category import MessageCategoryfrom products.messaging.backend.models.message_preferences import (@@ -15,6 +17,7 @@ from products.messaging.backend.models.message_preferences import (PreferenceStatus,)from products.messaging.backend.models.optout_sync_config import OptOutSyncConfig+from products.messaging.backend.presentation.views.customerio_webhook import CustomerIOWebhookAuthenticationclass TestCustomerIOWebhook(APIBaseTest):@@ -173,6 +176,7 @@ class TestCustomerIOWebhook(APIBaseTest):self.assertEqual(response.status_code, 200)self.assertEqual(MessageRecipientPreference.objects.filter(team=self.team).count(), 0)+ @covers_authentication(WebhookSignatureAuthentication, CustomerIOWebhookAuthentication)def test_hmac_auth_works_without_session(self):self.client.logout()body = {"metric": "unsubscribed", "data": {"email_address": "[email protected]"}}diff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.pyindex 922ebad033ea..b5e0c68de2e5 100644--- a/products/notebooks/backend/test/test_sharing.py+++ b/products/notebooks/backend/test/test_sharing.py@@ -7,7 +7,9 @@ from unittest import TestCasefrom parameterized import parameterizedfrom rest_framework import status+from posthog.auth import SharingAccessTokenAuthenticationfrom posthog.models import SharingConfiguration+from posthog.test.authentication_checks import covers_authenticationfrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.util import (@@ -683,6 +685,7 @@ class TestNotebookSharingGrantsInsightAccess(APIBaseTest):[self.referenced_insight.id, self.unreferenced_insight.id],)+ @covers_authentication(SharingAccessTokenAuthentication)def test_anonymous_request_with_share_token_can_load_referenced_insight(self) -> None:self.client.logout()response = self.client.get(diff --git a/products/security/backend/tests/test_hub_api.py b/products/security/backend/tests/test_hub_api.pyindex 1714f4d2762a..658fc9599ae3 100644--- a/products/security/backend/tests/test_hub_api.py+++ b/products/security/backend/tests/test_hub_api.py@@ -12,6 +12,9 @@ from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.models import User+from posthog.test.authentication_checks import covers_authentication++from products.security.backend.presentation.hub_api import SecurityHubAuthenticationSECRET = "in-us"SETTINGS = {"SECURITY_HUB_REGION": "us", "SECURITY_HUB_INBOUND_JWT_SECRETS": [SECRET]}@@ -44,6 +47,7 @@ class TestHubApi(BaseTest):headers: dict[str, Any] = {"HTTP_AUTHORIZATION": f"Bearer {token(op, **claims)}"} if op else {}return self.client.post(f"/api/security/{path}/", body, format="json", **headers)+ @covers_authentication(SecurityHubAuthentication)def test_resolve(self) -> None:user = User.objects.create_and_join(self.organization, "[email protected]", "password1234")response = self.post("resolve", {"query": "[email protected]"}, "subject:resolve")diff --git a/products/skills/backend/api/test/test_marketplace_endpoints.py b/products/skills/backend/api/test/test_marketplace_endpoints.pyindex ce07c5e7f1d5..4c2eb2a8ea8c 100644--- a/products/skills/backend/api/test/test_marketplace_endpoints.py+++ b/products/skills/backend/api/test/test_marketplace_endpoints.py@@ -24,8 +24,10 @@ from posthog.models import PersonalAPIKey, Userfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.utils import hash_key_value+from posthog.test.authentication_checks import covers_authenticationfrom products.access_control.backend.models.access_control import AccessControl+from products.skills.backend.marketplace.auth import MarketplaceGitBasicAuthenticationfrom ...api import skill_servicesfrom ...api.skill_serializers import validate_skill_file_path@@ -595,6 +597,7 @@ class TestSkillMarketplaceGit(APIBaseTest):assert response.status_code == status.HTTP_401_UNAUTHORIZEDassert response.get("WWW-Authenticate", "").startswith("Basic")+ @covers_authentication(MarketplaceGitBasicAuthentication)def test_info_refs_with_pak_advertises_refs(self):self._create_skill()_mint_pak(self.user, scopes=["llm_skill:read"], scoped_teams=[self.team.id])diff --git a/products/tasks/backend/tests/test_task_usage_api.py b/products/tasks/backend/tests/test_task_usage_api.pyindex 603d7ad49c49..b943c6cb8fd4 100644--- a/products/tasks/backend/tests/test_task_usage_api.py+++ b/products/tasks/backend/tests/test_task_usage_api.py@@ -15,13 +15,18 @@ from rest_framework.parsers import JSONParserfrom rest_framework.request import Requestfrom rest_framework.test import APIRequestFactory+from posthog.test.authentication_checks import covers_authentication+from products.tasks.backend.logic.services.task_usage import (TASK_USAGE_INTERNAL_PATH,TASK_USAGE_SIGNATURE_HEADER,TASK_USAGE_TIMESTAMP_HEADER,sign_task_usage_request,)-from products.tasks.backend.presentation.views.task_usage_api import InternalTaskUsageViewSet+from products.tasks.backend.presentation.views.task_usage_api import (+ InternalTaskUsageViewSet,+ TaskUsageCrossRegionAuthentication,+)CROSS_REGION_SECRET = "test-cross-region-secret"@@ -115,6 +120,7 @@ class TestInternalTaskUsageAuthentication(APIBaseTest):assert response.status_code == status.HTTP_401_UNAUTHORIZEDself.get_token_cost.assert_not_called()+ @covers_authentication(TaskUsageCrossRegionAuthentication)def test_signed_request_authenticates_and_returns_the_token_cost(self) -> None:response = self._post(self._signed_headers())diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.pyindex 1a6d22ec2c11..9c8d508aa9f8 100644--- a/products/tasks/backend/tests/test_workflow_tasks_api.py+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py@@ -22,6 +22,7 @@ from posthog.models.organization import OrganizationMembershipfrom posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV+from posthog.test.authentication_checks import covers_authenticationfrom products.cdp.backend.workflow_step_resume import RESULT_STRING_CAPfrom products.skills.backend.models.skills import LLMSkill@@ -34,6 +35,7 @@ from products.tasks.backend.models import Channel, Task, TaskRunfrom products.tasks.backend.visibility import task_control_q, task_visibility_qfrom products.workflows.backend.facade.team_extension import TeamWorkflowsConfigfrom products.workflows.backend.facade.testing import create_workflow_for_test+from products.workflows.backend.presentation.views.workflow_tasks import WorkflowTasksJWTAuthenticationSECRET = "test-tasks-create-jwt"@@ -108,6 +110,7 @@ class TestWorkflowTasksAPI(APIBaseTest):])+ @covers_authentication(WorkflowTasksJWTAuthentication)def test_creates_a_task_and_run_attributed_to_the_workflow_and_its_owner(self) -> None:response = self._post()diff --git a/products/workflows/backend/test/test_workflow_customer_tasks.py b/products/workflows/backend/test/test_workflow_customer_tasks.pyindex 876083aaee61..8268a73d6e1b 100644--- a/products/workflows/backend/test/test_workflow_customer_tasks.py+++ b/products/workflows/backend/test/test_workflow_customer_tasks.py@@ -15,12 +15,16 @@ from posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import OrganizationMembership, Team, Userfrom posthog.models.team.team import DEPRECATED_ATTRS+from posthog.test.authentication_checks import covers_authenticationfrom posthog.test.db_context_capturing import capture_db_queriesfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.access_control.backend.models.access_control import AccessControlfrom products.customer_analytics.backend.facade import api, contractsfrom products.customer_analytics.backend.facade.workflow_customer_tasks import get_workflow_customer_task_id+from products.customer_analytics.backend.presentation.views.workflow_customer_tasks import (+ WorkflowCustomerTasksJWTAuthentication,+)from products.workflows.backend.models import HogFlowSECRET = "test-customer-tasks-workflow-key"@@ -86,6 +90,7 @@ class TestWorkflowCustomerTasks(APIBaseTest):HTTP_AUTHORIZATION=f"Bearer {token or self._token()}",)+ @covers_authentication(WorkflowCustomerTasksJWTAuthentication)def test_creates_assigned_account_task_once_and_distinguishes_steps(self) -> None:account = api.create_account_for_view(team=self.team,diff --git a/products/workflows/backend/tests/api/test_workflow_classifications_api.py b/products/workflows/backend/tests/api/test_workflow_classifications_api.pyindex 33a60f660c2f..35b2f62afd80 100644--- a/products/workflows/backend/tests/api/test_workflow_classifications_api.py+++ b/products/workflows/backend/tests/api/test_workflow_classifications_api.py@@ -13,6 +13,7 @@ from rest_framework import statusfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.llm.gateway_client import GatewayNotConfiguredError+from posthog.test.authentication_checks import covers_authenticationfrom products.ml_inference.backend.facade.contracts import (DEFAULT_DECISION_MODEL,@@ -25,6 +26,7 @@ from products.ml_inference.backend.facade.contracts import (NoulAnswer,)from products.ml_inference.backend.facade.enums import DecisionQuestionType+from products.workflows.backend.presentation.views.workflow_classifications import WorkflowClassifyJWTAuthenticationSECRET = "test-workflow-classify-jwt"_DECIDE = "products.ml_inference.backend.facade.api.decide_when_available"@@ -89,6 +91,7 @@ class TestWorkflowClassificationsAPI(APIBaseTest):("jev", {"model": "jev"}, DEFAULT_DECISION_MODEL),])+ @covers_authentication(WorkflowClassifyJWTAuthentication)def test_returns_the_chosen_category(self, _name: str, body: dict, expected_model: str) -> None:answer = ChoiceAnswer(choice="spam", confidence=0.9, probabilities={"spam": 0.9, "support": 0.1})with patch(_DECIDE, return_value=_result(answer)) as decide:diff --git a/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py b/products/workflows/backend/tests/api/test_workflow_scout_runs_api.pyindex d7d23c037f20..da5b16bdadf5 100644--- a/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py+++ b/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py@@ -11,10 +11,12 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.test.authentication_checks import covers_authenticationfrom products.signals.backend.facade.api import ScoutRunRejectionKind, WorkflowScoutRunRejected, WorkflowScoutRunStartedfrom products.signals.backend.scout_harness.run_gates import ScoutRunRejectionfrom products.workflows.backend.models import HogFlow+from products.workflows.backend.presentation.views.workflow_scout_runs import WorkflowScoutRunsJWTAuthenticationSECRET = "test-workflow-scout-run-jwt"SCOUT = "signals-scout-error-tracking"@@ -55,6 +57,7 @@ class TestWorkflowScoutRunsAPI(APIBaseTest):HTTP_AUTHORIZATION=f"Bearer {token or _token(self.team.id, str(self.hog_flow.id))}",)+ @covers_authentication(WorkflowScoutRunsJWTAuthentication)def test_dispatches_a_scout_run(self) -> None:started = WorkflowScoutRunStarted(skill_name=SCOUT, workflow_id="signals-scout-workflow-run-1")with patch(_START_SCOUT, return_value=started) as start:diff --git a/pytest.ini b/pytest.iniindex d8700749c64a..8bacd7307b1a 100644--- a/pytest.ini+++ b/pytest.ini@@ -33,6 +33,7 @@ markers =requires_vendor_credentials(*env_vars, check=None): test talks to a real cloud vendor; CI deselects it, local runs skip it unless every env var is set and check() passesquarantine: applied automatically to tests quarantined via .test_quarantine.json (hogli test:quarantine)persons_db_direct: test exercises the persons DB directly and must not have the personhog fake / ORM block active+ covers_authentication(*classes): test authenticates a request through each authentication class; every class needs one such testasyncio_mode = autoasyncio_default_fixture_loop_scope = module