Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(auth): refuse deactivated users in all authentication classes (#114081)

Felipe Rosa de Almeida1998cf3d7d04
diff --git a/.agents/security.md b/.agents/security.md
index 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 vulnerabilities
diff --git a/conftest.py b/conftest.py
index 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 runs
EventsSchemaRecorder,
@@ -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 = yield
diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.py
index 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 Organization
from posthog.models.organization_provisioning import OrganizationProvisioning
from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.user import User
+from posthog.test.authentication_checks import covers_authentication
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
+from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication
from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX
from 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 == 200
diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.py
index 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 parameterized
from posthog.models.integration import GitHubUserAuthorization
from posthog.models.oauth import OAuthApplication
+from posthog.test.authentication_checks import covers_authentication
from posthog.token_bucket import Budget
from ee.api.agentic_provisioning import github_grants
+from ee.api.agentic_provisioning.authentication import ConfidentialPartnerAuthentication, GitHubGrantsAuthentication
from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX
from 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.py
index 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, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.test.authentication_checks import covers_authentication
+from ee.api.agentic_provisioning.authentication import ProvisioningBearerAuthentication
from ee.api.agentic_provisioning.credentials import maybe_create_provisioned_pat
from ee.api.agentic_provisioning.ratelimits import RATE_LIMITED_MESSAGE
from ee.api.agentic_provisioning.test.base import ProvisioningTestBase, provisioning_config
class 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.py
index 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 ActivityLog
from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
+from posthog.test.authentication_checks import covers_authentication
from 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_token
from ee.api.scim.user import PostHogSCIMUser
from ee.api.scim.utils import get_scim_base_url
from ee.api.test.base import APILicensedTest
@@ -184,6 +185,7 @@ class TestSCIMAPI(APILicensedTest):
assert data["status"] == 403
assert "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.py
index 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 AuthenticationFailed
from rest_framework.test import APIRequestFactory
from posthog.models.activity_logging.utils import ActivityCredential, activity_storage
+from posthog.test.authentication_checks import covers_authentication
from ee.api.authentication import VercelAuthentication
from 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_jwks
token = self._token()
diff --git a/ee/api/vercel/test/test_vercel_proxy.py b/ee/api/vercel/test/test_vercel_proxy.py
index 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 APIClient
from posthog.models.organization import Organization
from posthog.models.organization_integration import OrganizationIntegration
+from posthog.test.authentication_checks import covers_authentication
from ee.api.authentication import BillingServiceAuthentication
from 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.license
diff --git a/ee/partners/stripe/api/provisioning/test/test_resources.py b/ee/partners/stripe/api/provisioning/test/test_resources.py
index 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 OrganizationProvisioning
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.utils import generate_random_oauth_access_token
+from posthog.test.authentication_checks import covers_authentication
from products.access_control.backend.models.access_control import AccessControl
from ee.models.license import License
+from ee.partners.stripe.api.provisioning.authentication import StripeBearerAuthentication
from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
RESOURCES_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.py
index 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 status
from posthog.api.advanced_activity_logs import ActivityLogSerializer
from posthog.api.my_notifications import MyNotificationsSerializer
+from posthog.auth import JwtAuthentication
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User
@@ -22,6 +23,7 @@ from posthog.models.activity_logging.utils import activity_storage
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.session.activity import session_public_id
+from posthog.test.authentication_checks import covers_authentication
from posthog.test.insight_queries import default_pageview_query
from products.exports.backend.models.exported_asset import ExportedAsset
@@ -583,6 +585,7 @@ class TestActivityLogBearerAuthAttribution(APIBaseTest):
assert session_key is not None
assert (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.py
index 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 APIBaseTest
from unittest.mock import ANY, MagicMock, patch
from django.conf import settings
-from django.contrib.auth import BACKEND_SESSION_KEY
+from django.contrib.auth import BACKEND_SESSION_KEY, load_backend
from django.contrib.sessions.middleware import SessionMiddleware
from django.core import mail
from django.core.asgi import get_asgi_application
@@ -20,6 +20,7 @@ from django.http import HttpRequest, HttpResponse
from django.test import RequestFactory, SimpleTestCase, override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
+from django.utils.module_loading import import_string
from asgiref.sync import sync_to_async
from django_otp.oath import totp
@@ -71,6 +72,7 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.authentication_checks import covers_authentication
from products.exports.backend.models.exported_asset import ExportedAsset
from 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 token
wsgi_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.py
index 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 OrganizationDomain
from posthog.models.user import User as UserModel
from posthog.permissions import get_authenticator_client
from 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.py
index 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 timezone
from parameterized import parameterized
+from posthog.api.livestream import LivestreamAuthentication
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import OrganizationDomain, OrganizationMembership, PropertyDefinition
+from posthog.test.authentication_checks import covers_authentication
from posthog.test.persons import create_group_type_mapping
from 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.py
index 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 DelegatedOAuthAccessTokenAuthentication
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import PersonalAPIKey
from 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_authentication
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabel
from 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.py
index 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 status
from posthog.schema import EventsQuery
from posthog.api.personal_api_key import PersonalAPIKeySerializer
+from posthog.auth import PersonalAPIKeyAuthentication
from posthog.constants import AvailableFeature
from posthog.helpers.dev_api_key import get_local_dev_api_key_value
from posthog.jwt import PosthogJwtAudience, encode_jwt
@@ -24,6 +25,7 @@ from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, Person
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value, mask_key_value
+from posthog.test.authentication_checks import covers_authentication
from 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 keys
response = 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.py
index 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 SharingPasswordProtectedAuthentication
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, decode_jwt
from posthog.models import ActivityLog, OrganizationMembership
@@ -31,6 +32,7 @@ from posthog.models.data_color_theme import DataColorTheme
from posthog.models.share_password import SharePassword
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.user import User
+from posthog.test.authentication_checks import covers_authentication
from posthog.test.insight_queries import browser_filtered_pageview_query
from 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.py
index 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 UserSocialAuth
from posthog.api.email_verification import email_verification_code_verifier
from posthog.api.oauth.toolbar_service import ToolbarOAuthState, build_toolbar_oauth_state, new_state_nonce
from posthog.api.user import MAX_PRODUCT_INTROS_SEEN, UserSerializer
+from posthog.auth import SessionAuthentication
from posthog.constants import AvailableFeature
from posthog.helpers.two_factor_session import code_based_verification_token_generator
from posthog.models import Team, User
@@ -42,6 +43,7 @@ from posthog.models.user import default_ui_configuration_for_new_users
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.temporal.tests.delete_teams.inline import execute_deletion_workflows_inline
+from posthog.test.authentication_checks import covers_authentication
from products.access_control.backend.models.access_control import AccessControl
from 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.py
index 004012614069..a0aea9c0f097 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -585,7 +585,7 @@ class JwtAuthentication(ActivityCredentialMixin, authentication.BaseAuthenticati
try:
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.BaseA
self.team_id = team_id
self.exported_asset_id = exported_asset_id
self.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 None
except Exception:
diff --git a/posthog/test/authentication_checks.py b/posthog/test/authentication_checks.py
new file mode 100644
index 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.py
index 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.py
index 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 parameterized
from rest_framework import status
from rest_framework.test import APIClient
+from posthog.auth import ExportRendererAuthentication
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models.team import Team
+from posthog.test.authentication_checks import covers_authentication
from products.cohorts.backend.models.cohort import Cohort
from 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.py
index 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 Request
from posthog.auth import InternalAPIAuthentication
from posthog.settings import LOCAL_DEV_INTERNAL_API_SECRET
+from posthog.test.authentication_checks import covers_authentication
class 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.py
index 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, PermissionDenied
from rest_framework.test import APIRequestFactory
from 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_authentication
from products.access_control.backend.facade.contracts import ObjectAccessRef
from 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.py
index 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 Request
from posthog.auth import ScopedServiceJWTAuthentication
from posthog.jwt import PosthogJwtAudience
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
+from posthog.test.authentication_checks import covers_authentication
TEST_PURPOSE = ScopedServiceJwtPurpose(
audience=PosthogJwtAudience.RECORDING_API,
@@ -131,6 +132,7 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):
assert result is not None
return 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.py
index 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 Team
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.authentication_checks import covers_authentication
from 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.py
index 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 APIClient
from posthog.models import ActivityLog, Comment, Team
from posthog.models.utils import generate_random_token_secret
from 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 ExternalTicketProjectSecretAPIKeyAuthentication
from products.conversations.backend.api.ticket_actions import _truncate_bytes
from products.conversations.backend.models import Ticket
from 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.py
index 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 PosthogJwtAudience
from posthog.models import Comment
from posthog.models.utils import generate_random_token_secret
from 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 Ticket
from 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.py
index 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 parameterized
from rest_framework import status
from rest_framework.test import APIClient
+from posthog.auth import WidgetAuthentication
from posthog.models.comment import Comment
from posthog.rate_limit import WidgetTeamPollThrottle
+from posthog.test.authentication_checks import covers_authentication
from products.conversations.backend.api.serializers import WidgetMessageSerializer, WidgetTicketsQuerySerializer
from 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.py
index 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, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.utils import generate_random_token_secret
from posthog.test.api_keys import create_project_secret_api_key
+from posthog.test.authentication_checks import covers_authentication
from posthog.test.persons import create_group
from 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.py
index 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 AvailableFeature
from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User
from posthog.models.utils import generate_random_token_personal, generate_random_token_secret, hash_key_value
from posthog.test.api_keys import create_project_secret_api_key
+from posthog.test.authentication_checks import covers_authentication
from products.access_control.backend.models.access_control import AccessControl
from products.customer_analytics.backend.facade import api as facade
from products.customer_analytics.backend.models import AccountRelationship, AccountRelationshipDefinition
+from products.customer_analytics.backend.presentation.views.external import ExternalAccountPersonalAPIKeyAuthentication
from products.customer_analytics.backend.test.factories import create_account, enroll_account
ENDED_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.id
diff --git a/products/customer_analytics/backend/test/test_internal.py b/products/customer_analytics/backend/test/test_internal.py
index 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 APIClient
from posthog.jwt import PosthogJwtAudience
from posthog.models.utils import generate_random_token_secret
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
+from posthog.test.authentication_checks import covers_authentication
from products.customer_analytics.backend.facade import contracts
from 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.py
index 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_config
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import OrganizationMembership
from posthog.security.url_validation import PinnedUrlVerdict
+from posthog.test.authentication_checks import covers_authentication
from products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agents
from 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 GatewayAgentAuthentication
from 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.py
index 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 hashlib
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from posthog.auth import WebhookSignatureAuthentication
from posthog.models.integration import Integration
+from posthog.test.authentication_checks import covers_authentication
from products.messaging.backend.models.message_category import MessageCategory
from 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 CustomerIOWebhookAuthentication
class 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.py
index 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 TestCase
from parameterized import parameterized
from rest_framework import status
+from posthog.auth import SharingAccessTokenAuthentication
from posthog.models import SharingConfiguration
+from posthog.test.authentication_checks import covers_authentication
from products.notebooks.backend.models import Notebook
from 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.py
index 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 parameterized
from rest_framework.test import APIClient
from posthog.models import User
+from posthog.test.authentication_checks import covers_authentication
+
+from products.security.backend.presentation.hub_api import SecurityHubAuthentication
SECRET = "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.py
index 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, User
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team import Team
from posthog.models.utils import hash_key_value
+from posthog.test.authentication_checks import covers_authentication
from products.access_control.backend.models.access_control import AccessControl
+from products.skills.backend.marketplace.auth import MarketplaceGitBasicAuthentication
from ...api import skill_services
from ...api.skill_serializers import validate_skill_file_path
@@ -595,6 +597,7 @@ class TestSkillMarketplaceGit(APIBaseTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert 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.py
index 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 JSONParser
from rest_framework.request import Request
from 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_UNAUTHORIZED
self.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.py
index 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 OrganizationMembership
from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
+from posthog.test.authentication_checks import covers_authentication
from products.cdp.backend.workflow_step_resume import RESULT_STRING_CAP
from products.skills.backend.models.skills import LLMSkill
@@ -34,6 +35,7 @@ from products.tasks.backend.models import Channel, Task, TaskRun
from products.tasks.backend.visibility import task_control_q, task_visibility_q
from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig
from products.workflows.backend.facade.testing import create_workflow_for_test
+from products.workflows.backend.presentation.views.workflow_tasks import WorkflowTasksJWTAuthentication
SECRET = "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.py
index 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 AvailableFeature
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import OrganizationMembership, Team, User
from posthog.models.team.team import DEPRECATED_ATTRS
+from posthog.test.authentication_checks import covers_authentication
from posthog.test.db_context_capturing import capture_db_queries
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
from products.customer_analytics.backend.facade import api, contracts
from 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 HogFlow
SECRET = "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.py
index 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 status
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.llm.gateway_client import GatewayNotConfiguredError
+from posthog.test.authentication_checks import covers_authentication
from 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 WorkflowClassifyJWTAuthentication
SECRET = "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.py
index 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 parameterized
from rest_framework import status
from posthog.jwt import PosthogJwtAudience, encode_jwt
+from posthog.test.authentication_checks import covers_authentication
from products.signals.backend.facade.api import ScoutRunRejectionKind, WorkflowScoutRunRejected, WorkflowScoutRunStarted
from products.signals.backend.scout_harness.run_gates import ScoutRunRejection
from products.workflows.backend.models import HogFlow
+from products.workflows.backend.presentation.views.workflow_scout_runs import WorkflowScoutRunsJWTAuthentication
SECRET = "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.ini
index 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() passes
quarantine: 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 test
asyncio_mode = auto
asyncio_default_fixture_loop_scope = module