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.

test(oauth): self-provision OIDC RSA key in test settings (#62729)

Phil Haack7dffe62b524b
diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.py
index 051e0bb7a494..e85090e614bf 100644
--- a/ee/api/agentic_provisioning/test/base.py
+++ b/ee/api/agentic_provisioning/test/base.py
@@ -2,17 +2,13 @@ import json
import time
from urllib.parse import urlencode
-import pytest
from posthog.test.base import APIBaseTest
-from django.conf import settings
from django.core.cache import cache
from django.test import override_settings
from rest_framework.test import APIClient
-from posthog.test.oauth_test_utils import TEST_RSA_PRIVATE_KEY as _RSA_KEY
-
from ee.api.agentic_provisioning.signature import compute_signature
from ee.api.agentic_provisioning.views import AUTH_CODE_CACHE_PREFIX
@@ -20,12 +16,9 @@ HMAC_SECRET = "test_hmac_secret"
TEST_STRIPE_OAUTH_CLIENT_ID = "test_stripe_oauth_client_id"
@override_settings(
STRIPE_SIGNING_SECRET=HMAC_SECRET,
STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
- OIDC_RSA_PRIVATE_KEY=_RSA_KEY,
- OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _RSA_KEY},
)
class ProvisioningTestBase(APIBaseTest):
def setUp(self):
diff --git a/ee/api/agentic_provisioning/test/test_authorize.py b/ee/api/agentic_provisioning/test/test_authorize.py
index 428c45b4f405..488a91b1e6f0 100644
--- a/ee/api/agentic_provisioning/test/test_authorize.py
+++ b/ee/api/agentic_provisioning/test/test_authorize.py
@@ -2,11 +2,9 @@ import json
import time
from urllib.parse import quote
-import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.conf import settings
from django.core.cache import cache
from django.test import override_settings
@@ -16,7 +14,7 @@ from posthog.models.user import User
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX
from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import _RSA_KEY, HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID
+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID
DUMMY_CALLBACK = "https://marketplace.stripe.com/oauth/callback"
@@ -83,18 +81,13 @@ class TestAgenticAuthorize(APIBaseTest):
assert code_data["team_id"] == self.team.id
assert code_data["scopes"] == ["query:read", "project:read"]
- @pytest.mark.requires_secrets
@override_settings(
STRIPE_SIGNING_SECRET=HMAC_SECRET,
- STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK,
STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
- OIDC_RSA_PRIVATE_KEY=_RSA_KEY,
- OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _RSA_KEY},
)
def test_full_a1_flow_with_token_exchange(self):
# The token exchange resolves the legacy Stripe OAuth app by client_id and now
- # hard-fails if it's missing, so the e2e flow needs the app row to exist. The
- # model enforces RS256, which requires OIDC_RSA_PRIVATE_KEY to be set.
+ # hard-fails if it's missing, so the e2e flow needs the app row to exist.
OAuthApplication.objects.create(
name="PostHog Stripe App",
client_id=TEST_STRIPE_OAUTH_CLIENT_ID,
@@ -188,13 +181,6 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):
)
assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_consume") is None
- # Creating an RS256 app requires OIDC_RSA_PRIVATE_KEY. The env-level key can be cleared by
- # other OAuth tests overriding OAUTH2_PROVIDER (django-oauth-toolkit caches its settings), so
- # pin it here too.
- @override_settings(
- OIDC_RSA_PRIVATE_KEY=_RSA_KEY,
- OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _RSA_KEY},
- )
@patch("ee.api.agentic_provisioning.views._capture_provisioning_event")
def test_confirm_success_attributes_partner(self, mock_capture_event):
partner = OAuthApplication.objects.create(
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index dcb7ae937f5a..ce5d157800ec 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -5,18 +5,15 @@ import hashlib
import secrets
from urllib.parse import urlencode
-import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.conf import settings
from django.core.cache import cache as real_cache
from django.test import override_settings
from rest_framework.test import APIClient
from posthog.models.oauth import OAuthApplication
-from posthog.test.oauth_test_utils import TEST_RSA_PRIVATE_KEY as _RSA_KEY
from ee.api.agentic_provisioning.signature import compute_signature
@@ -32,13 +29,10 @@ def _pkce_pair():
return verifier, challenge
@override_settings(
STRIPE_SIGNING_SECRET=HMAC_SECRET,
STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
STRIPE_ORCHESTRATOR_CALLBACK_URL="https://stripe.com/callback",
- OIDC_RSA_PRIVATE_KEY=_RSA_KEY,
- OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _RSA_KEY},
)
class TestProvisioningAuthentication(APIBaseTest):
def setUp(self):
@@ -630,14 +624,11 @@ def _cimd_mock_response(metadata: dict | None, status_code: int = 200):
return resp
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
@override_settings(
STRIPE_APP_SECRET_KEY=HMAC_SECRET,
STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
STRIPE_ORCHESTRATOR_CALLBACK_URL="https://stripe.com/callback",
- OIDC_RSA_PRIVATE_KEY=_RSA_KEY,
- OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _RSA_KEY},
)
class TestCimdProvisioningAutoRegistration(APIBaseTest):
def setUp(self):
diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.py
index d454b7009a67..76af26fe21b4 100644
--- a/posthog/admin/test_oauth_admin.py
+++ b/posthog/admin/test_oauth_admin.py
@@ -4,25 +4,16 @@ from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import patch
-from django.conf import settings
from django.contrib.admin import AdminSite
-from django.test import RequestFactory, override_settings
+from django.test import RequestFactory
from django.utils import timezone
from parameterized import parameterized
from posthog.admin.admins.oauth_admin import OAuthApplicationAdmin, OAuthApplicationForm
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
-from posthog.test.oauth_test_utils import TEST_RSA_PRIVATE_KEY
-# Creating an RS256 app requires OIDC_RSA_PRIVATE_KEY, which isn't available on fork/external PR CI and
-# can be cleared by other OAuth tests overriding OAUTH2_PROVIDER (django-oauth-toolkit caches its
-# settings). Pin a test key so these tests pass regardless of environment and ordering.
-@override_settings(
- OIDC_RSA_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY,
- OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": TEST_RSA_PRIVATE_KEY},
-)
class TestOAuthApplicationAdmin(BaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/oauth/test_application.py b/posthog/api/oauth/test_application.py
index 87bc327934e2..3508bc34af51 100644
--- a/posthog/api/oauth/test_application.py
+++ b/posthog/api/oauth/test_application.py
@@ -1,4 +1,3 @@
-import pytest
from posthog.test.base import APIBaseTest
from parameterized import parameterized
@@ -9,7 +8,6 @@ from posthog.models.oauth import OAuthApplication
from posthog.models.organization import Organization
class TestOrganizationOAuthApplicationViewSet(APIBaseTest):
expected_fields = {"id", "name", "client_id", "redirect_uris_list", "is_verified", "created", "updated"}
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index 34f233adc309..a24be17adb2d 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -8,13 +8,10 @@ import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.conf import settings
from django.core.cache import cache as real_cache
-from django.test import SimpleTestCase, override_settings
+from django.test import SimpleTestCase
import requests
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from rest_framework.test import APIClient
@@ -38,17 +35,6 @@ from posthog.api.oauth.cimd import (
from posthog.models.oauth import OAuthApplication, create_cimd_verification_token
from posthog.scopes import OAUTH_HIDDEN_SCOPES, PRIVILEGED_SCOPES
-
-def generate_rsa_key() -> str:
- private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096)
- pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.TraditionalOpenSSL,
- encryption_algorithm=serialization.NoEncryption(),
- )
- return pem.decode("utf-8")
-
-
VALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"
@@ -251,12 +237,6 @@ class TestFetchCimdMetadata(APIBaseTest):
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestFetchAndUpsertCimdApplication(APIBaseTest):
"""Tests for fetch_and_upsert_cimd_application — the core fetch+create/update function."""
@@ -332,12 +312,6 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestGetOrCreateCimdApplication(APIBaseTest):
"""Tests for get_or_create_cimd_application — the orchestration layer."""
@@ -400,12 +374,6 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
self.assertEqual(app.name, "Original Name")
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestGetApplicationByClientId(APIBaseTest):
def setUp(self):
super().setUp()
@@ -447,12 +415,6 @@ class TestGetApplicationByClientId(APIBaseTest):
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestGetOrCreateCimdProvisioningApplication(APIBaseTest):
@patch("posthog.api.oauth.cimd.requests.get")
def test_creates_new_app_with_provisioning_defaults(self, mock_get, _url_mock):
@@ -557,12 +519,6 @@ class TestGetOrCreateCimdProvisioningApplication(APIBaseTest):
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestCIMDVerificationToken(APIBaseTest):
@patch("posthog.api.oauth.cimd.requests.get")
def test_valid_verification_token_links_app_to_organization(self, mock_get, _url_mock):
@@ -752,12 +708,6 @@ class TestCIMDVerificationToken(APIBaseTest):
self.assertEqual(refreshed.provisioning_rate_limit_account_requests_source, "admin")
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestAuthorizationServerMetadata(APIBaseTest):
def test_advertises_cimd_support(self):
client = APIClient()
@@ -767,12 +717,6 @@ class TestAuthorizationServerMetadata(APIBaseTest):
self.assertTrue(data.get("client_id_metadata_document_supported"))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
class TestCIMDAuthorizeIntegration(APIBaseTest):
"""Integration tests for the CIMD flow through /oauth/authorize/."""
@@ -878,12 +822,6 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestCIMDComPostHogNamespace(APIBaseTest):
"""Tests for the com.posthog namespace: scopes and nested verification_token."""
diff --git a/posthog/api/oauth/test_connected_apps.py b/posthog/api/oauth/test_connected_apps.py
index 6e7743d45f21..0420868c86c8 100644
--- a/posthog/api/oauth/test_connected_apps.py
+++ b/posthog/api/oauth/test_connected_apps.py
@@ -4,12 +4,8 @@ from datetime import timedelta
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
-from django.conf import settings
-from django.test import override_settings
from django.utils import timezone
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import rsa
from rest_framework import status
from rest_framework.test import APIClient
@@ -17,23 +13,7 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant,
from posthog.models.user import User
-def _generate_rsa_key() -> str:
- private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
- pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.TraditionalOpenSSL,
- encryption_algorithm=serialization.NoEncryption(),
- )
- return pem.decode("utf-8")
-
-
@freeze_time("2024-06-15T12:00:00Z")
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": _generate_rsa_key(),
- }
-)
class TestConnectedAppsViewSet(APIBaseTest):
def _create_app(self, name: str = "Test App", **kwargs) -> OAuthApplication:
return OAuthApplication.objects.create(
diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.py
index 9f7964476fd5..b27bfc711cf4 100644
--- a/posthog/api/oauth/test_dcr.py
+++ b/posthog/api/oauth/test_dcr.py
@@ -3,11 +3,6 @@ import hashlib
from posthog.test.base import APIBaseTest
-from django.conf import settings
-from django.test import override_settings
-
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
@@ -15,22 +10,6 @@ from rest_framework.test import APIClient
from posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLevel
-def generate_rsa_key() -> str:
- private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096)
- pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.TraditionalOpenSSL,
- encryption_algorithm=serialization.NoEncryption(),
- )
- return pem.decode("utf-8")
-
-
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestDynamicClientRegistration(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index a75dda33eab4..8043570d25ff 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -35,22 +35,7 @@ from posthog.models.oauth import (
revoke_application_sessions,
)
from posthog.models.team.team import Team
-
-
-def generate_rsa_key() -> str:
- # Generate a new RSA private key
- private_key = rsa.generate_private_key(
- public_exponent=65537,
- key_size=4096,
- )
- # Serialize the private key to PEM format
- pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.TraditionalOpenSSL,
- encryption_algorithm=serialization.NoEncryption(),
- )
-
- return pem.decode("utf-8")
+from posthog.settings.utils import generate_rsa_private_key_pem
def jwks_entry_to_public_key(key_data: dict):
@@ -73,12 +58,6 @@ def private_pem_to_public_pem(private_key_pem: str) -> str:
return public_pem(private_key.public_key())
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestOAuthAPI(APIBaseTest):
def setUp(self):
super().setUp()
@@ -904,8 +883,8 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(public_pem(jwks_entry_to_public_key(jwks["keys"][0])), self.public_key)
def test_jwks_endpoint_publishes_active_and_inactive_keys(self):
- inactive_key_1 = generate_rsa_key()
- inactive_key_2 = generate_rsa_key()
+ inactive_key_1 = generate_rsa_private_key_pem()
+ inactive_key_2 = generate_rsa_private_key_pem()
with override_settings(
OAUTH2_PROVIDER={
@@ -940,7 +919,7 @@ class TestOAuthAPI(APIBaseTest):
def test_token_signed_with_inactive_key_still_verifies_via_jwks(self):
# Simulates a rotation: a token signed by the previous active key keeps verifying
# because that key is still published as an inactive key in the JWKS.
- previous_key = generate_rsa_key()
+ previous_key = generate_rsa_private_key_pem()
previous_kid = jwk_from_pem(previous_key).thumbprint()
token = jwt.encode(
@@ -3470,12 +3449,6 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["scoped_teams"], [self.team.pk])
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestLocalhostLoopbackRedirectUri(APIBaseTest):
"""
Tests for RFC 8252 Section 7.3 — loopback redirect URIs must allow any port.
@@ -3703,3 +3676,20 @@ class TestOIDCInactiveKeysSetting(SimpleTestCase):
# Restore module attributes to the real environment (patch.dict has already
# restored os.environ by this point, so this reload sees the original vars).
importlib.reload(web_settings)
+
+ def test_generates_ephemeral_key_when_env_key_missing(self):
+ # Internal CI injects OIDC_RSA_PRIVATE_KEY, so the TEST-mode fallback in web.py
+ # only ever runs where the env key is absent (fork PRs, bare local runs). Pin it
+ # here so a settings refactor can't silently drop the fallback or reorder it
+ # below the OAUTH2_PROVIDER dict that must inherit the generated key.
+ web_settings = importlib.import_module("posthog.settings.web")
+ try:
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("OIDC_RSA_PRIVATE_KEY", None)
+ importlib.reload(web_settings)
+ self.assertIn("-----BEGIN RSA PRIVATE KEY-----", web_settings.OIDC_RSA_PRIVATE_KEY)
+ self.assertEqual(
+ web_settings.OAUTH2_PROVIDER["OIDC_RSA_PRIVATE_KEY"], web_settings.OIDC_RSA_PRIVATE_KEY
+ )
+ finally:
+ importlib.reload(web_settings)
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 44d29a463120..4eb371956d30 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -34,7 +34,6 @@ from social_django.models import UserSocialAuth
from two_factor.utils import totp_digits
from posthog.api.authentication import password_reset_token_generator, post_login, social_login_notification
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.auth import (
InternalAPIUser,
OAuthAccessTokenAuthentication,
@@ -2283,12 +2282,6 @@ class TestProjectSecretAPIKeyAuthentication(APIBaseTest):
self.assertGreater(self.psak.last_used_at, old + timedelta(hours=1))
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestOAuthAccessTokenAuthentication(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/test/test_github.py b/posthog/api/test/test_github.py
index 293657746f85..c2637247bc07 100644
--- a/posthog/api/test/test_github.py
+++ b/posthog/api/test/test_github.py
@@ -869,26 +869,16 @@ class TestSecretAlertRegionTracking(APIBaseTest):
class TestOAuthTokenSecretAlert(APIBaseTest):
def _create_oauth_app(self):
- from django.conf import settings
-
- from posthog.models.test.test_oauth import generate_rsa_key
-
- with self.settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
- ):
- return OAuthApplication.objects.create(
- name="Test OAuth App",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://example.com/callback",
- algorithm="RS256",
- skip_authorization=False,
- organization=self.organization,
- user=self.user,
- )
+ return OAuthApplication.objects.create(
+ name="Test OAuth App",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ skip_authorization=False,
+ organization=self.organization,
+ user=self.user,
+ )
@patch("posthog.api.github.verify_github_signature")
@patch("posthog.api.github.send_oauth_token_exposed")
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 4958a62ca702..2330d15f5587 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -22,7 +22,6 @@ from django.utils import timezone
import jwt
from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import rsa
from oauth2_provider.utils import jwk_from_pem
from rest_framework import status
@@ -39,21 +38,11 @@ from posthog.constants import AvailableFeature
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User as UserModel
-
-
-def _generate_rsa_pem() -> str:
- private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
- pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.TraditionalOpenSSL,
- encryption_algorithm=serialization.NoEncryption(),
- )
- return pem.decode("utf-8")
-
+from posthog.settings.utils import generate_rsa_private_key_pem
# rsa operations are expensive, keep this at the module-level to avoid slow tests
-_IDP_PRIVATE_KEY_PEM = _generate_rsa_pem()
-_AS_PRIVATE_KEY_PEM = _generate_rsa_pem()
+_IDP_PRIVATE_KEY_PEM = generate_rsa_private_key_pem()
+_AS_PRIVATE_KEY_PEM = generate_rsa_private_key_pem()
_IDP_ISSUER = "https://idp.example.com"
_VERIFIED_DOMAIN = "example.com"
@@ -535,7 +524,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.assertIn("active member", resp.json()["error_description"])
def test_rejects_signature_from_unrecognized_key(self) -> None:
- other_pem = _generate_rsa_pem()
+ other_pem = generate_rsa_private_key_pem()
assertion = _make_id_jag(signing_pem=other_pem)
resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
@@ -875,7 +864,7 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
def test_invalid_signature_rejected(self) -> None:
- other_pem = _generate_rsa_pem()
+ other_pem = generate_rsa_private_key_pem()
token = self._mint_access_token(scope="user:read", signing_pem=other_pem)
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
@@ -885,7 +874,7 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
# that key is demoted to inactive and a freshly generated key takes over signing.
token = self._mint_access_token(scope="user:read", signing_pem=_AS_PRIVATE_KEY_PEM)
with override_settings(
- OIDC_RSA_PRIVATE_KEY=_generate_rsa_pem(),
+ OIDC_RSA_PRIVATE_KEY=generate_rsa_private_key_pem(),
OIDC_RSA_PRIVATE_KEYS_INACTIVE=[_AS_PRIVATE_KEY_PEM],
):
resp = self._call_authenticated(token)
@@ -893,10 +882,10 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
self.assertEqual(resp.json()["email"], self.user.email)
def test_token_signed_with_neither_active_nor_inactive_key_rejected(self) -> None:
- token = self._mint_access_token(scope="user:read", signing_pem=_generate_rsa_pem())
+ token = self._mint_access_token(scope="user:read", signing_pem=generate_rsa_private_key_pem())
with override_settings(
OIDC_RSA_PRIVATE_KEY=_AS_PRIVATE_KEY_PEM,
- OIDC_RSA_PRIVATE_KEYS_INACTIVE=[_generate_rsa_pem()],
+ OIDC_RSA_PRIVATE_KEYS_INACTIVE=[generate_rsa_private_key_pem()],
):
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 778394072fb9..476a9e9052cb 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -18,7 +18,6 @@ from parameterized import parameterized
from rest_framework import status
from posthog.api.integration import IntegrationSerializer, IntegrationViewSet
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.models.integration import (
ERROR_TOKEN_REFRESH_FAILED,
GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,
@@ -2051,13 +2050,6 @@ class TestStripeIntegration:
class TestStripeIntegrationOAuthTokens:
- @pytest.fixture(autouse=True)
- def _override_oidc_key(self, settings):
- settings.OAUTH2_PROVIDER = {
- **django_settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-
@pytest.fixture(autouse=True)
def setup(self, db):
self.organization = Organization.objects.create(name="Test Org")
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index d3b36d75ddce..317d95e4a596 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -5,16 +5,13 @@ from uuid import uuid4
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, patch
-from django.conf import settings
from django.core.cache import cache
-from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIRequestFactory
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.organization import OrganizationSerializer, _fetch_member_count, _org_serializer_cache_version
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, Team
@@ -359,12 +356,6 @@ class TestOrganizationAPI(APIBaseTest):
"Only the scoped organization should be listed, the other one should be excluded",
)
- @override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
- )
def test_projects_outside_oauth_scoped_organizations_causes_401(self):
# TODO: This should filter out the organizations to the scoped organizations, but it causes a 401 due to a bug in APIScopePermission for list endpoints.
other_org, _, _ = Organization.objects.bootstrap(self.user)
@@ -398,12 +389,6 @@ class TestOrganizationAPI(APIBaseTest):
("is_ai_training_opted_in",),
]
)
- @override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
- )
def test_org_scoped_oauth_token_can_patch_current_organization(self, field: str):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index 0bb46f2ae93b..cb96bafd78f1 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -1,6 +1,5 @@
from datetime import timedelta
-import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -474,7 +473,6 @@ class TestPersonalAPIKeysAPIAuthentication(PersonalAPIKeysBaseTest):
response = self.client.get("/api/users/@me/", headers={"authorization": f"Bearer {self.value}"})
assert response.status_code == status.HTTP_200_OK
- @pytest.mark.requires_secrets
def test_does_not_interfere_with_other_auth_methods(self):
from django.utils import timezone
diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.py
index 7b99ac31ed5f..83268c2b0a77 100644
--- a/posthog/api/test/test_routing.py
+++ b/posthog/api/test/test_routing.py
@@ -8,7 +8,6 @@ import pytest
from posthog.test.base import APIBaseTest
from django.apps import apps
-from django.conf import settings
from django.test import override_settings
from django.urls import include, path
from django.utils import timezone
@@ -17,7 +16,6 @@ from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry, TeamAndOrgViewSetMixin
from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
@@ -183,13 +181,7 @@ class TestTeamAndOrgViewSetMixin(APIBaseTest):
)
-@override_settings(
- ROOT_URLCONF=__name__,
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
+@override_settings(ROOT_URLCONF=__name__)
class TestOAuthAccessTokenAuthentication(APIBaseTest):
"""Test that OAuth access tokens work through the routing layer with proper permissions"""
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 55abf35358c1..5d867a0bcf7c 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -18,7 +18,6 @@ from parameterized import parameterized
from rest_framework import status, test
from temporalio.service import RPCError
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.team import (
TEAM_CONFIG_FIELDS_SET,
TEAM_CONFIG_MEMBER_FIELDS_SET,
@@ -2929,12 +2928,6 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore
"Only the team belonging to the scoped organization should be listed, the other one should be excluded",
)
- @override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
- )
def test_teams_outside_oauth_scoped_teams_causes_403(self):
# TODO: This should filter out the teams to the scoped teams, but it causes a 403 due to a bug in APIScopePermission for list endpoints.
other_team_in_project = Team.objects.create(organization=self.organization, project=self.project)
@@ -2965,12 +2958,6 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- @override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
- )
def test_teams_outside_oauth_scoped_organizations_not_listed(self):
other_org, __, team_in_other_org = Organization.objects.bootstrap(self.user)
diff --git a/posthog/api/test/test_toolbar_hash_routing_repro.py b/posthog/api/test/test_toolbar_hash_routing_repro.py
index c3fa53bd43b3..efc2ccb8ce70 100644
--- a/posthog/api/test/test_toolbar_hash_routing_repro.py
+++ b/posthog/api/test/test_toolbar_hash_routing_repro.py
@@ -10,16 +10,11 @@ from urllib.parse import urlparse
from posthog.test.base import APIBaseTest
-from django.conf import settings
-from django.test.utils import override_settings
-
from parameterized import parameterized
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.test.test_toolbar_oauth_primitives import ToolbarOAuthAuthorizeMixin
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarHashRoutingRepro(ToolbarOAuthAuthorizeMixin, APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/test/test_toolbar_oauth_authorize.py b/posthog/api/test/test_toolbar_oauth_authorize.py
index 0fc0c3c96476..f8de9f66087a 100644
--- a/posthog/api/test/test_toolbar_oauth_authorize.py
+++ b/posthog/api/test/test_toolbar_oauth_authorize.py
@@ -3,13 +3,7 @@ from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.conf import settings
-from django.test import override_settings
-from posthog.api.oauth.test_dcr import generate_rsa_key
-
-
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarOAuthAuthorize(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/test/test_toolbar_oauth_endpoint_auth.py b/posthog/api/test/test_toolbar_oauth_endpoint_auth.py
index 6fca07fe56f2..45934a414506 100644
--- a/posthog/api/test/test_toolbar_oauth_endpoint_auth.py
+++ b/posthog/api/test/test_toolbar_oauth_endpoint_auth.py
@@ -13,12 +13,10 @@ from datetime import timedelta
from posthog.test.base import APIBaseTest
from django.conf import settings
-from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.constants import AvailableFeature
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import OrganizationMembership
@@ -49,7 +47,6 @@ def _make_token(user, app, token_str, scope="*", delta_hours=1):
)
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarEndpointOAuthAuth(APIBaseTest):
"""
Every toolbar-consumed endpoint should accept OAuth access tokens
@@ -187,7 +184,6 @@ class TestToolbarEndpointOAuthAuth(APIBaseTest):
assert response.status_code in (401, 403)
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarOAuthBypassesPersonalApiKeyRestriction(APIBaseTest):
"""
When an organization disables personal API keys for members,
@@ -242,7 +238,6 @@ class TestToolbarOAuthBypassesPersonalApiKeyRestriction(APIBaseTest):
assert response.status_code == 403, f"Personal API key should still be blocked, got {response.status_code}"
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestUploadedMediaOAuthAuth(APIBaseTest):
"""uploaded_media is tested separately — its only toolbar action is POST (upload)."""
@@ -289,7 +284,6 @@ class TestUploadedMediaOAuthAuth(APIBaseTest):
assert response.status_code in (401, 403)
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestHedgehogConfigOAuthAuth(APIBaseTest):
"""hedgehog_config uses /api/users/@me/ path, not team-scoped, so tested separately."""
@@ -340,7 +334,6 @@ class TestHedgehogConfigOAuthAuth(APIBaseTest):
assert response.status_code in (401, 403)
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarOAuthScopesConfig(APIBaseTest):
"""Verify TOOLBAR_OAUTH_SCOPES covers every toolbar endpoint scope."""
diff --git a/posthog/api/test/test_toolbar_oauth_primitives.py b/posthog/api/test/test_toolbar_oauth_primitives.py
index 8ab3fd8ff7d6..364f2e3a72e6 100644
--- a/posthog/api/test/test_toolbar_oauth_primitives.py
+++ b/posthog/api/test/test_toolbar_oauth_primitives.py
@@ -11,7 +11,6 @@ from django.test import override_settings
import requests
from parameterized import parameterized
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.oauth.toolbar_service import (
CALLBACK_PATH,
ToolbarOAuthError,
@@ -27,7 +26,6 @@ from posthog.api.oauth.toolbar_service import (
from posthog.models import Organization, Team, User
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarOAuthPrimitives(APIBaseTest):
def setUp(self):
super().setUp()
@@ -320,7 +318,6 @@ class ToolbarOAuthAuthorizeMixin:
return qs["state"][0]
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
class TestToolbarOAuthCallbackExchange(ToolbarOAuthAuthorizeMixin, APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 71bfcd7557fd..d78c4e074ff8 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -9,11 +9,9 @@ from posthog.test.base import APIBaseTest
from unittest import mock
from unittest.mock import ANY, patch
-from django.conf import settings
from django.contrib.auth.tokens import default_token_generator
from django.core import mail
from django.core.cache import cache
-from django.test import override_settings
from django.utils import timezone
from django.utils.text import slugify
@@ -24,7 +22,6 @@ from rest_framework import status
from social_django.models import UserSocialAuth
from posthog.api.email_verification import email_verification_token_generator
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.models import Team, User
from posthog.models.instance_setting import set_instance_setting
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
@@ -2858,12 +2855,6 @@ class TestUserTwoFactor(APIBaseTest):
# Verify email was triggered
mock_send_email.delay.assert_called_once_with(self.user.id)
- @override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
- )
def test_team_scoped_oauth_token_with_user_read_can_access_me_endpoint(self):
oauth_app = OAuthApplication.objects.create(
name="Test OAuth App",
diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.py
index 092c8a15b432..e7231117c2b7 100644
--- a/posthog/models/test/test_oauth.py
+++ b/posthog/models/test/test_oauth.py
@@ -3,14 +3,12 @@ from datetime import timedelta
from freezegun import freeze_time
-from django.conf import settings
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings
from django.utils import timezone
from parameterized import parameterized
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.models import Organization, User
from posthog.models.oauth import (
OAuthAccessToken,
@@ -23,12 +21,6 @@ from posthog.models.oauth import (
)
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestOAuthModels(TestCase):
def setUp(self):
self.organization = Organization.objects.create(name="Test Org")
diff --git a/posthog/settings/utils.py b/posthog/settings/utils.py
index b370d7c318eb..8bcedebaaf32 100644
--- a/posthog/settings/utils.py
+++ b/posthog/settings/utils.py
@@ -6,7 +6,23 @@ from django.core.exceptions import ImproperlyConfigured
from posthog.utils import str_to_bool
-__all__ = ["get_from_env", "get_list", "str_to_bool"]
+__all__ = ["generate_rsa_private_key_pem", "get_from_env", "get_list", "str_to_bool"]
+
+
+def generate_rsa_private_key_pem() -> str:
+ """Generate an ephemeral RSA private key in PEM format. Used to self-provision
+ OIDC_RSA_PRIVATE_KEY in test runs that don't get one from the environment."""
+ # Keeps cryptography off the settings import path outside of test runs.
+ from cryptography.hazmat.primitives import serialization # noqa: PLC0415
+ from cryptography.hazmat.primitives.asymmetric import rsa # noqa: PLC0415
+
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ pem = private_key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.TraditionalOpenSSL,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ return pem.decode("utf-8")
def get_from_env(
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index b56cf9868058..56f1760074ad 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -7,7 +7,7 @@ from corsheaders.defaults import default_headers
from posthog.scopes import get_scope_descriptions
from posthog.settings.base_variables import BASE_DIR, CLOUD_DEPLOYMENT, DEBUG, TEST
-from posthog.settings.utils import get_from_env, get_list, str_to_bool
+from posthog.settings.utils import generate_rsa_private_key_pem, get_from_env, get_list, str_to_bool
from posthog.utils_cors import CORS_ALLOWED_TRACING_HEADERS
logger = structlog.get_logger(__name__)
@@ -753,6 +753,12 @@ ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS = get_list(get_from_env("ERROR_TRACK
OIDC_RSA_PRIVATE_KEY = os.getenv("OIDC_RSA_PRIVATE_KEY", "").replace("\\n", "\n")
+# Saving an RS256 OAuthApplication validates that this key is set, so a test run without one
+# (fork PRs, bare local environments) fails in every test that creates an OAuth app. Generate
+# an ephemeral key so tests never depend on an env-provided key.
+if TEST and not OIDC_RSA_PRIVATE_KEY:
+ OIDC_RSA_PRIVATE_KEY = generate_rsa_private_key_pem()
+
OIDC_RSA_PRIVATE_KEY_INACTIVE_1 = os.getenv("OIDC_RSA_PRIVATE_KEY_INACTIVE_1", "").replace("\\n", "\n")
OIDC_RSA_PRIVATE_KEY_INACTIVE_2 = os.getenv("OIDC_RSA_PRIVATE_KEY_INACTIVE_2", "").replace("\\n", "\n")
OIDC_RSA_PRIVATE_KEYS_INACTIVE = [
diff --git a/posthog/test/oauth_test_utils.py b/posthog/test/oauth_test_utils.py
deleted file mode 100644
index 4d12333402f8..000000000000
--- a/posthog/test/oauth_test_utils.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import rsa
-
-
-def generate_rsa_private_key_pem() -> str:
- private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
- pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.TraditionalOpenSSL,
- encryption_algorithm=serialization.NoEncryption(),
- )
- return pem.decode("utf-8")
-
-
-# Generated once so test modules pinning OIDC_RSA_PRIVATE_KEY share a single key.
-TEST_RSA_PRIVATE_KEY = generate_rsa_private_key_pem()
diff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.py
index 82c87fd6b21f..90a2bfe34d62 100644
--- a/posthog/test/test_oauth_impersonation.py
+++ b/posthog/test/test_oauth_impersonation.py
@@ -11,25 +11,18 @@ from django.contrib.auth import logout
from django.contrib.sessions.backends.db import SessionStore
from django.core.signing import TimestampSigner
from django.http import HttpRequest
-from django.test import RequestFactory, override_settings
+from django.test import RequestFactory
from django.utils import timezone
from loginas import settings as la_settings
from parameterized import parameterized
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.oauth.views import _impersonation_ai_processing_block, _impersonator_id_for_request
from posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEY
from posthog.models import OAuthApplication, Organization, OrganizationMembership, Team, User
from posthog.models.oauth import OAuthAccessToken, OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken
-TEST_OAUTH2_PROVIDER_WITH_RSA = {
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
-}
-
-@override_settings(OAUTH2_PROVIDER=TEST_OAUTH2_PROVIDER_WITH_RSA)
class TestImpersonationOAuthRevocation(BaseTest):
def test_user_logged_out_revokes_only_impersonated_tokens(self) -> None:
admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")
@@ -106,7 +99,6 @@ class TestImpersonationOAuthRevocation(BaseTest):
self.assertTrue(OAuthAccessToken.objects.filter(pk=customer_owned.pk).exists())
-@override_settings(OAUTH2_PROVIDER=TEST_OAUTH2_PROVIDER_WITH_RSA)
class TestImpersonationOAuthTokenIssuance(APIBaseTest):
"""Code-exchange flow: tokens minted from an impersonation-tagged grant must be
short-lived and refresh-less, so they expire at the impersonation idle timeout
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index a871abe47931..c10128671c03 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -4,14 +4,12 @@ from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import Mock, PropertyMock, patch
-from django.conf import settings
-from django.test import SimpleTestCase, override_settings
+from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
from rest_framework.test import APIRequestFactory
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, TeamSecretTokenAuthentication
from posthog.constants import AvailableFeature
from posthog.models import Organization, Team, User
@@ -677,12 +675,6 @@ class TestTeamMemberAccessPermission(BaseTest):
self.assertTrue(result)
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
class TestOAuthAccessTokenAPIScopePermission(BaseTest):
"""Test that OAuth access tokens properly enforce API scopes via APIScopePermission"""
@@ -861,12 +853,6 @@ class TestOAuthAccessTokenAPIScopePermission(BaseTest):
self.assertEqual(response.status_code, 200)
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
class TestOAuthAccessTokenWithOrganizationScoping(BaseTest):
"""Test that OAuth access tokens properly enforce organization scoping"""
@@ -920,12 +906,6 @@ class TestOAuthAccessTokenWithOrganizationScoping(BaseTest):
self.assertEqual(response.status_code, 404)
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
class TestOAuthAccessTokenWithTeamScoping(BaseTest):
"""Test that OAuth access tokens properly enforce team scoping"""
@@ -974,12 +954,6 @@ class TestOAuthAccessTokenWithTeamScoping(BaseTest):
self.assertIn("does not have access to the requested project", response.json()["detail"])
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
class TestOAuthAccessTokenWithBothTeamAndOrgScoping(BaseTest):
"""Test that OAuth access tokens properly enforce scoping when both teams and orgs are defined"""
@@ -1044,12 +1018,6 @@ class TestOAuthAccessTokenWithBothTeamAndOrgScoping(BaseTest):
self.assertIn("only supported on project-based endpoints", response.json()["detail"])
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
class TestOAuthAccessTokenExpiration(BaseTest):
"""Test that expired OAuth access tokens are properly rejected"""
@@ -1112,12 +1080,6 @@ class TestOAuthAccessTokenExpiration(BaseTest):
self.assertEqual(response.status_code, 401)
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- },
-)
class TestOAuthAccessTokenUserMembership(BaseTest):
"""Test that OAuth tokens respect current user membership (not historical)"""
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 db8e19b68c4a..635d16c9594f 100644
--- a/products/ai_observability/backend/api/test/test_personal_spend.py
+++ b/products/ai_observability/backend/api/test/test_personal_spend.py
@@ -14,14 +14,12 @@ from posthog.test.base import (
)
from unittest.mock import patch
-from django.conf import settings
from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.api.oauth.test_dcr import generate_rsa_key
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
@@ -403,12 +401,6 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
assert rows["Read"]["share_of_scoped"] == 0.5
-@override_settings(
- OAUTH2_PROVIDER={
- **settings.OAUTH2_PROVIDER,
- "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
- }
-)
class TestPersonalSpendNonSessionAuth(APIBaseTest):
"""
Pins down what scopes the MCP and OAuth-token paths need to reach
diff --git a/products/growth/dags/tests/test_oauth.py b/products/growth/dags/tests/test_oauth.py
index a0ef8ab1c013..41370dbf0bed 100644
--- a/products/growth/dags/tests/test_oauth.py
+++ b/products/growth/dags/tests/test_oauth.py
@@ -1,6 +1,5 @@
from datetime import timedelta
-import pytest
import unittest.mock
from freezegun import freeze_time
@@ -21,7 +20,6 @@ from products.growth.dags.oauth import (
)
class TestOAuthTokenCleanup(TestCase):
def setUp(self):
self.organization = Organization.objects.create(name="Test Org")
@@ -70,7 +68,6 @@ class TestOAuthTokenCleanup(TestCase):
self.assertTrue(OAuthAccessToken.objects.filter(id=valid_token.id).exists())
class TestBatchDeleteFunctionality(TestCase):
"""Test the new DRY batch delete functionality."""
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index d8c6fc009ffc..4592e522f584 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -3,13 +3,9 @@ from __future__ import annotations
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
-from django.conf import settings
-from django.test import override_settings
-
from parameterized import parameterized
from rest_framework import status
-from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.models import OAuthApplication
from posthog.models.team.team import Team
from posthog.temporal.oauth import (
@@ -29,10 +25,6 @@ from products.signals.backend.models import (
from products.signals.backend.scout_harness.tools.profile import compute_project_profile
from products.tasks.backend.models import Task, TaskRun
-# Fresh RSA key so RS256 OAuth apps validate in tests (OIDC_RSA_PRIVATE_KEY is unset by
-# default). Same pattern as `posthog/test/test_permissions.py` and the OAuth provider tests.
-_OIDC_RSA_KEY = generate_rsa_key()
-
def _authenticate_as_scout(test: APIBaseTest) -> None:
"""Auth the test client with a scout-internal token, mirroring how the harness sandbox
@@ -52,8 +44,7 @@ def _authenticate_as_scout(test: APIBaseTest) -> None:
"client_type": OAuthApplication.CLIENT_PUBLIC,
"authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
"redirect_uris": "https://app.posthog.com/callback",
- # RS256 is enforced by the `enforce_rs256_algorithm` DB constraint; the
- # `_OIDC_RSA_KEY` override on the test class satisfies the signing-key requirement.
+ # RS256 is enforced by the `enforce_rs256_algorithm` DB constraint.
"algorithm": "RS256",
},
)
@@ -246,7 +237,6 @@ class TestScoutHarnessRunEmissionsAPI(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})
class TestScoutHarnessEmitFindingAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -327,7 +317,6 @@ class TestScoutHarnessEmitFindingAPI(APIBaseTest):
)
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})
class TestScoutHarnessScratchpadAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -440,7 +429,6 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})
class TestAgentHarnessProjectProfileAPI(APIBaseTest):
"""The project profile is the scout's orientation surface — read once at run start.