Skip to content

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

feat(credentials-service): read github and slack app keys via service (#121024)

Tom Owersf3abf46f04b3
diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.py
index c196c47a26fb..0316ab0c27c3 100644
--- a/posthog/api/test/test_github_installation_webhook.py
+++ b/posthog/api/test/test_github_installation_webhook.py
@@ -145,7 +145,7 @@ class TestGitHubInstallationWebhook(TestCase):
user=self.user, kind="github", integration_id=installation_id, config={}, sensitive_config={}
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
def test_deleted_removes_all_rows_and_does_not_call_github(self, mock_client_request, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -166,7 +166,7 @@ class TestGitHubInstallationWebhook(TestCase):
# Inbound side must never call out to GitHub (loop prevention).
mock_client_request.assert_not_called()
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_deleted_with_no_matching_rows_is_idempotent(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -175,7 +175,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(response.status_code, 202)
@parameterized.expand([("suspend",), ("unsuspend",)])
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_reversible_action_does_not_delete_rows(self, action, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
self._team_integration("12345")
@@ -185,7 +185,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(response.status_code, 202)
self.assertTrue(Integration.objects.filter(kind="github", integration_id="12345").exists())
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_missing_installation_id_is_accepted(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -193,7 +193,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(response.status_code, 202)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_created_approves_the_requesters_pending_request_by_github_user_id(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
other_user = User.objects.create(email="[email protected]", distinct_id="other-requester-1")
@@ -232,7 +232,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(someone_else.status, GitHubInstallRequest.Status.PENDING)
self.assertIsNone(someone_else.installation_id)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_created_without_a_requester_is_a_noop(self, mock_get_secret):
# An owner installing for themselves sends no requester, and must not sweep up pending rows.
mock_get_secret.return_value = self.webhook_secret
@@ -249,7 +249,7 @@ class TestGitHubInstallationWebhook(TestCase):
pending.refresh_from_db()
self.assertEqual(pending.status, GitHubInstallRequest.Status.PENDING)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_installation_repositories_updates_selection_and_invalidates_caches(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
team_row = self._team_integration("12345")
@@ -282,7 +282,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(untouched.config["repository_selection"], "selected")
self.assertIsNotNone(untouched.repository_cache_updated_at)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_invalid_signature_returns_403_and_keeps_rows(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
self._team_integration("12345")
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 7c4e125a15a1..2432bc9efda4 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -1690,24 +1690,14 @@ class TestIntegrationAPIKeyAccess:
assert response.json()["kind"] == "twilio"
@patch(
- "posthog.models.integration.oauth.get_instance_settings",
+ "posthog.credentials_service.instance_settings.get_instance_settings",
return_value={
"SLACK_APP_CLIENT_ID": "test-client-id",
"SLACK_APP_CLIENT_SECRET": "test-client-secret",
"SLACK_APP_SIGNING_SECRET": "test-signing-secret",
},
)
- @patch(
- "posthog.models.integration.slack.get_instance_settings",
- return_value={
- "SLACK_APP_CLIENT_ID": "test-client-id",
- "SLACK_APP_CLIENT_SECRET": "test-client-secret",
- "SLACK_APP_SIGNING_SECRET": "test-signing-secret",
- },
- )
- def test_retrieve_slack_integration_with_scope_succeeds(
- self, _mock_settings, _mock_oauth_settings, client: HttpClient
- ):
+ def test_retrieve_slack_integration_with_scope_succeeds(self, _mock_settings, client: HttpClient):
slack_integration = Integration.objects.create(
team=self.team,
kind="slack",
@@ -7821,7 +7811,7 @@ class TestIntegrationSerializerFilesWriteRequestable(APIBaseTest):
integration = Integration.objects.create(team=self.team, kind=kind, config=config)
with (
patch(
- "posthog.models.integration.oauth.get_instance_settings",
+ "posthog.credentials_service.instance_settings.get_instance_settings",
return_value={
"SLACK_APP_CLIENT_ID": "test-client-id",
"SLACK_APP_CLIENT_SECRET": "test-client-secret",
diff --git a/posthog/credentials_service/callers.py b/posthog/credentials_service/callers.py
index 37b769c87ff4..746584021dfa 100644
--- a/posthog/credentials_service/callers.py
+++ b/posthog/credentials_service/callers.py
@@ -24,6 +24,9 @@ class CredentialsCaller(StrEnum):
MESSAGING = "messaging"
TASKS = "tasks"
WEB_ANALYTICS = "web-analytics"
+ STAMPHOG = "stamphog"
+ CONVERSATIONS = "conversations"
+ SKILLS = "skills"
# Shared integration plumbing (OAuth connect, token refresh, account listing) that runs on
# behalf of many products. The call sites cannot tell which product asked, so they say so.
INTEGRATIONS = "integrations"
diff --git a/posthog/credentials_service/instance_settings.py b/posthog/credentials_service/instance_settings.py
new file mode 100644
index 000000000000..8b3bd4d9a889
--- /dev/null
+++ b/posthog/credentials_service/instance_settings.py
@@ -0,0 +1,45 @@
+"""Platform credentials whose settings copy is an instance setting, not a Django setting.
+
+Self-hosted deployments edit these in the instance settings UI, and the value there wins over
+the environment variable it defaults from. With the service off, the client would read the
+environment variable directly and ignore that edit, so the service is only asked when it is on.
+With the service on, a key it does not hold falls back to the instance setting, per key, the same
+way `settings_fallback` falls back to a Django setting.
+
+Kept apart from `settings_fallback` so that module does not import a Django model.
+"""
+
+from posthog.models.instance_setting import get_instance_setting, get_instance_settings
+
+from .callers import CredentialsCaller
+from .client import CredentialsServiceClient, credentials_service_enabled
+from .settings_fallback import get_many_or_settings, get_or_settings
+
+
+def _instance_setting(key: str) -> str | None:
+ return get_instance_setting(key) or None
+
+
+def get_or_instance_setting(
+ key: str,
+ caller: CredentialsCaller,
+ *,
+ client: CredentialsServiceClient | None = None,
+) -> str:
+ """One instance-setting-backed credential, or "" when it is configured nowhere."""
+ if not credentials_service_enabled():
+ return get_instance_setting(key) or ""
+ return get_or_settings(key, caller, client=client, settings_lookup=_instance_setting)
+
+
+def get_many_or_instance_settings(
+ keys: list[str],
+ caller: CredentialsCaller,
+ *,
+ client: CredentialsServiceClient | None = None,
+) -> dict[str, str]:
+ """Several instance-setting-backed credentials, "" for each one configured nowhere."""
+ if not credentials_service_enabled():
+ values = get_instance_settings(keys)
+ return {key: values[key] or "" for key in keys}
+ return get_many_or_settings(keys, caller, client=client, settings_lookup=_instance_setting)
diff --git a/posthog/credentials_service/test/test_instance_settings.py b/posthog/credentials_service/test/test_instance_settings.py
new file mode 100644
index 000000000000..955e09b784a3
--- /dev/null
+++ b/posthog/credentials_service/test/test_instance_settings.py
@@ -0,0 +1,76 @@
+from collections.abc import Callable
+from typing import Any
+
+from unittest import mock
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.credentials_service import instance_settings
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.test.test_settings_fallback import (
+ FLAG,
+ POST,
+ SERVICE_SETTINGS,
+ _FakeResponse,
+ _keys_asked_for,
+ _missing,
+ _steady,
+)
+
+KEY = "SLACK_APP_SIGNING_SECRET"
+CALLER = CredentialsCaller.INTEGRATIONS
+UNCONFIGURED: dict[str, Any] = {"CREDENTIALS_SERVICE_URL": "", "CREDENTIALS_SERVICE_JWT_SECRET": ""}
+
+READS: dict[str, Callable[[], str]] = {
+ "one": lambda: instance_settings.get_or_instance_setting(KEY, CALLER),
+ "many": lambda: instance_settings.get_many_or_instance_settings([KEY], CALLER)[KEY],
+}
+
+
+class TestInstanceSettingsFallback(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (f"{read}_{name}", read, *case)
+ for read in READS
+ for name, *case in [
+ # An operator's edit in the instance settings UI must win over the environment variable
+ # it defaults from, so with the service off the environment is never read directly.
+ ("unconfigured_reads_the_instance_setting", UNCONFIGURED, True, None, "edited", "edited"),
+ ("flag_off_reads_the_instance_setting", SERVICE_SETTINGS, False, None, "edited", "edited"),
+ ("service_value_wins", SERVICE_SETTINGS, True, "from-service", "edited", "from-service"),
+ ("missing_falls_back_to_the_instance_setting", SERVICE_SETTINGS, True, None, "edited", "edited"),
+ ("configured_nowhere", SERVICE_SETTINGS, True, None, "", ""),
+ ]
+ ]
+ )
+ def test_reads(
+ self,
+ _name: str,
+ read: str,
+ service_settings: dict[str, Any],
+ flag_on: bool,
+ service_value: str | None,
+ instance_value: str,
+ expected: str,
+ ) -> None:
+ response = (
+ _FakeResponse({"secrets": {KEY: _steady(service_value)}, "missing": []})
+ if service_value is not None
+ else _missing(KEY)
+ )
+ with (
+ override_settings(**service_settings),
+ mock.patch(FLAG, return_value=flag_on),
+ mock.patch(POST, return_value=response) as post,
+ mock.patch.dict("os.environ", {KEY: "env-copy"}),
+ mock.patch.object(instance_settings, "get_instance_setting", return_value=instance_value),
+ mock.patch.object(instance_settings, "get_instance_settings", return_value={KEY: instance_value}),
+ ):
+ assert READS[read]() == expected
+
+ if service_settings is SERVICE_SETTINGS and flag_on:
+ assert _keys_asked_for(post.call_args.kwargs["headers"]["Authorization"]) == [KEY]
+ else:
+ post.assert_not_called()
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index a5c36564fa3e..6018048482a8 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -107,6 +107,7 @@ The HTTP response is a transport receipt: the verification result, the method, a
If a provider's protocol needs the response body to say something, the incarnation answers that handshake before dispatch.
A verification that could not run is its own answer rather than a verdict: a scheme with a network step returns `UNAVAILABLE` when that step fails on transport, and the view answers 503 with outcome `verify_unavailable`, so a sender that retries a server error sends the delivery again.
`BearerJwt` answers it when the JWKS could not be fetched, and `SnsSignature` when its verifier raises `VerifierUnavailable` because the signing certificate could not be fetched.
+`HmacSignature` answers it when its secret getter could not read the secret, because the database or the credentials service failed.
What the transport does decide is whether it can vouch that the delivery was taken.
It cannot when an ownership lookup failed, when the forward to the owning region failed, when a consumer raised, or when the budget skipped a consumer — in each case some of the work never ran, or ingress cannot tell whether it ran in the right region.
diff --git a/posthog/ingress/github/README.md b/posthog/ingress/github/README.md
index f3036f42a577..200d1b3c1e8d 100644
--- a/posthog/ingress/github/README.md
+++ b/posthog/ingress/github/README.md
@@ -23,8 +23,13 @@ The payload's `installation.id` goes into the delivery context as `installation_
Two apps share this incarnation, each subscribed to its own event types in GitHub.
-- `posthog`, the customer-facing App. Its secret is the instance setting `GITHUB_WEBHOOK_SECRET`, so an operator can rotate it without a deploy.
-- `stamphog`, the review App. Its secret is the Django setting `STAMPHOG_GITHUB_APP_WEBHOOK_SECRET`, because it is instance-wide infrastructure.
+- `posthog`, the customer-facing App. Its secret is `GITHUB_WEBHOOK_SECRET`, held as an instance setting so an operator can rotate it without a deploy.
+- `stamphog`, the review App. Its secret is `STAMPHOG_GITHUB_APP_WEBHOOK_SECRET`, held as a Django setting because it is instance-wide infrastructure.
+
+Both secrets are read from the credentials service first.
+A secret that the service does not hold comes from its setting, and with the service off only the setting is read.
+Each read is cached for five minutes, so a rotated secret reaches each process within five minutes.
+When the service cannot answer, the delivery gets 503, so GitHub can send it again.
A consumer registers against an app name, so the two apps share no consumers.
diff --git a/posthog/ingress/github/provider.py b/posthog/ingress/github/provider.py
index 91e83e6862af..d91bdfb1170d 100644
--- a/posthog/ingress/github/provider.py
+++ b/posthog/ingress/github/provider.py
@@ -2,20 +2,24 @@
Two apps share this incarnation: the customer-facing PostHog App (`posthog`, secret in
instance settings so an operator can rotate it without a deploy) and the Stamphog review App
-(`stamphog`, secret in env because it is instance-wide infrastructure).
+(`stamphog`, secret in env because it is instance-wide infrastructure). Both secrets are read from
+the credentials service first, and from those settings while the service does not hold them.
"""
from collections.abc import Callable, Mapping, Sequence
+from datetime import timedelta
from typing import Any
-from django.conf import settings
from django.http import HttpRequest
from django.utils import timezone
+from posthog.cache_utils import cache_for
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.instance_settings import get_or_instance_setting
+from posthog.credentials_service.settings_fallback import get_or_settings
from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
from posthog.ingress.providers import WebhookProvider, require_known_app
from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme
-from posthog.models.instance_setting import get_instance_setting
# What each App is subscribed to. A consumer for an event type outside its App's set fails
# registry validation, which is the point: it would never run. The two Apps are subscribed
@@ -36,13 +40,16 @@ GITHUB_EVENT_TYPES = frozenset(
STAMPHOG_EVENT_TYPES = frozenset({"pull_request", "installation", "installation_repositories"})
+# Every delivery is verified, so each secret is read under a cache and not once per request. A
+# rotation reaches each process within five minutes.
+@cache_for(timedelta(minutes=5))
def _posthog_app_secret() -> str | None:
- secret = get_instance_setting("GITHUB_WEBHOOK_SECRET")
- return secret if secret else None
+ return get_or_instance_setting("GITHUB_WEBHOOK_SECRET", CredentialsCaller.INTEGRATIONS) or None
+@cache_for(timedelta(minutes=5))
def _stamphog_app_secret() -> str | None:
- return getattr(settings, "STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", "") or None
+ return get_or_settings("STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", CredentialsCaller.STAMPHOG) or None
_SECRET_GETTERS: Mapping[str, Callable[[], str | None]] = {
diff --git a/posthog/ingress/slack/README.md b/posthog/ingress/slack/README.md
index d50d774eb4b8..03e88374bfa0 100644
--- a/posthog/ingress/slack/README.md
+++ b/posthog/ingress/slack/README.md
@@ -33,8 +33,11 @@ Two apps on one Slack app registration: `supporthog` for the Events API, and `su
They are separate here because they are separate endpoints with separate payload types, so each one's consumers are validated against only the types its own endpoint receives.
The signing secret is the same for both, and it belongs to the product that owns the Slack app, so `build_slack_provider()` and `build_slack_interactivity_provider()` take it as a getter.
Nothing under `posthog/ingress/` reads it.
+The conversations product reads `SUPPORT_SLACK_SIGNING_SECRET` from the credentials service first, and from the instance setting while the service does not hold it.
+It caches the secret for five minutes.
-The `slack_app` product runs a second Slack app registration with its own signing secret, held as the `SLACK_APP_SIGNING_SECRET` instance setting.
+The `slack_app` product runs a second Slack app registration with its own signing secret, `SLACK_APP_SIGNING_SECRET`.
+It is read the same way, through the five-minute cache of `SlackIntegration.slack_config()`.
Its endpoints answer Slack synchronously (a slash command, an interactivity ack, a cross-region workspace probe), so they keep their own views and verify through `build_slack_signature_scheme()` rather than through a provider.
`posthog.models.integration.validate_slack_request` is that call.
diff --git a/posthog/ingress/test/test_github.py b/posthog/ingress/test/test_github.py
index aac668b0c5ae..39abfbe19b69 100644
--- a/posthog/ingress/test/test_github.py
+++ b/posthog/ingress/test/test_github.py
@@ -1,13 +1,18 @@
import hmac
+from typing import Any
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
+import jwt
from parameterized import parameterized
+from posthog.credentials_service.test.test_settings_fallback import FLAG, POST, SERVICE_SETTINGS, _FakeResponse, _steady
+from posthog.ingress.github import provider
from posthog.ingress.github.provider import CORE_CONSUMERS, SPECS, build_github_provider
from posthog.ingress.verify.schemes import VerificationOutcome
+from posthog.jwt import PosthogJwtAudience
BODY = b'{"action":"created"}'
INSTANCE_SECRET = "posthog-app-secret"
@@ -29,7 +34,7 @@ class TestGitHubProvider(SimpleTestCase):
def test_each_app_only_accepts_its_own_secret(
self, _name: str, app: str, own_secret: str, other_secret: str
) -> None:
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=INSTANCE_SECRET):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=INSTANCE_SECRET):
scheme = build_github_provider(app).scheme()
self.assertEqual(
@@ -49,3 +54,42 @@ class TestGitHubProvider(SimpleTestCase):
self.assertLess(declared[("github", "stamphog")], declared[("github", "posthog")])
for consumer in CORE_CONSUMERS:
self.assertLessEqual(consumer.event_types, declared[(consumer.provider, consumer.app)])
+
+
+@override_settings(**SERVICE_SETTINGS)
+class TestGitHubWebhookSecretFromCredentialsService(SimpleTestCase):
+ def setUp(self) -> None:
+ for patcher in (patch(FLAG, return_value=True), patch("posthog.cache_utils.TEST", False)):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ for getter in (provider._posthog_app_secret, provider._stamphog_app_secret):
+ getter.clear_cache()
+ self.addCleanup(getter.clear_cache)
+
+ @parameterized.expand(
+ [
+ ("posthog_app", "posthog", "GITHUB_WEBHOOK_SECRET", "integrations"),
+ ("stamphog_app", "stamphog", "STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", "stamphog"),
+ ]
+ )
+ def test_deliveries_verify_against_one_cached_service_read(
+ self, _name: str, app: str, key: str, caller: str
+ ) -> None:
+ secret = f"{app}-secret-from-service"
+ response = _FakeResponse({"secrets": {key: _steady(secret)}, "missing": []})
+ scheme = build_github_provider(app).scheme()
+
+ with patch(POST, return_value=response) as post:
+ outcomes = [
+ scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(secret)}).outcome for _ in range(3)
+ ]
+
+ self.assertEqual(outcomes, [VerificationOutcome.VERIFIED] * 3)
+ self.assertEqual(post.call_count, 1)
+ claims: dict[str, Any] = jwt.decode(
+ post.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer "),
+ SERVICE_SETTINGS["CREDENTIALS_SERVICE_JWT_SECRET"],
+ algorithms=["HS256"],
+ audience=PosthogJwtAudience.CREDENTIALS_SERVICE.value,
+ )
+ self.assertEqual((claims["keys"], claims["caller"]), ([key], caller))
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index e7ca91486d3e..043b237ebc74 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -14,6 +14,7 @@ from cryptography.hazmat.primitives.asymmetric import rsa
from jwt.algorithms import RSAAlgorithm
from parameterized import parameterized
+from posthog.credentials_service.errors import CredentialsServiceUnreachableError, SecretInRecoveryError
from posthog.ingress.verify.errors import VerifierUnavailable
from posthog.ingress.verify.jwt import _JWKS_CLIENTS, SIGNING_KEY_FACT, BearerJwt, _jwks_client
from posthog.ingress.verify.schemes import HmacSha256, HmacSignature, SnsSignature, Verification, VerificationOutcome
@@ -119,9 +120,12 @@ class TestHmacSha256(SimpleTestCase):
[
("dropped_connection", OperationalError("server closed the connection unexpectedly")),
("closed_connection", InterfaceError("connection already closed")),
+ # Slack answers NOT_CONFIGURED with a 403 it does not retry, so an outage must not read as unset.
+ ("credentials_service_unreachable", CredentialsServiceUnreachableError("refused")),
+ ("credentials_service_recovery", SecretInRecoveryError("GITHUB_WEBHOOK_SECRET")),
]
)
- def test_a_database_failure_reading_the_secret_is_unavailable(self, _name: str, error: Exception) -> None:
+ def test_a_failed_secret_read_is_unavailable(self, _name: str, error: Exception) -> None:
def secret_getter() -> str:
raise error
@@ -132,6 +136,22 @@ class TestHmacSha256(SimpleTestCase):
VerificationOutcome.UNAVAILABLE,
)
+ def test_a_well_formed_delivery_reads_the_secret_once_when_the_read_fails(self) -> None:
+ calls = 0
+
+ def secret_getter() -> str:
+ nonlocal calls
+ calls += 1
+ raise CredentialsServiceUnreachableError("timed out")
+
+ scheme = HmacSha256(secret_getter=secret_getter, signature_header="X-Signature")
+ headers = {"X-Signature": _digest().hex()}
+
+ self.assertFalse(scheme.rejects_headers(headers))
+ self.assertEqual(scheme.verify(body=BODY, headers=headers).outcome, VerificationOutcome.UNAVAILABLE)
+ # One read across the header gate and the full check, so an outage costs one timeout.
+ self.assertEqual(calls, 1)
+
def test_any_other_failure_reading_the_secret_still_raises(self) -> None:
def secret_getter() -> str:
raise ValueError("boom")
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 0590c464ec1d..73952cfb8a02 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -158,7 +158,7 @@ class TestWebhookView(SimpleTestCase):
self.addCleanup(patcher.stop)
def _github_view(self):
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET):
provider = build_github_provider("posthog")
return build_webhook_view(provider)
@@ -171,7 +171,7 @@ class TestWebhookView(SimpleTestCase):
)
def test_a_non_post_is_refused_before_any_verification(self) -> None:
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET) as secret:
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET) as secret:
response = self._github_view()(self.factory.get("/webhooks/github/"))
self.assertEqual(response.status_code, 405)
secret.assert_not_called()
@@ -190,7 +190,7 @@ class TestWebhookView(SimpleTestCase):
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "issues"})
with (
- patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET) as secret,
+ patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET) as secret,
patch.object(_StubThrottle, "wait_seconds", wait_seconds),
patch("posthog.ingress.views.observe_delivery") as observe,
):
@@ -217,7 +217,7 @@ class TestWebhookView(SimpleTestCase):
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "issues"})
with (
- patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET),
+ patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET),
patch.object(_StubThrottle, "allowed", True),
):
response = build_webhook_view(_ThrottledGitHubProvider("posthog"))(request)
@@ -229,7 +229,7 @@ class TestWebhookView(SimpleTestCase):
body = json.dumps({"action": "opened"}).encode()
request = self._post(body, {"X-Hub-Signature-256": "sha256=" + "0" * 64, "X-GitHub-Event": "pull_request"})
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET):
response = self._github_view()(request)
self.assertEqual(response.status_code, 403)
@@ -262,7 +262,7 @@ class TestWebhookView(SimpleTestCase):
body = b"{not json"
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET):
with structlog.testing.capture_logs() as logs:
response = self._github_view()(request)
@@ -285,7 +285,7 @@ class TestWebhookView(SimpleTestCase):
},
)
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET):
response = self._github_view()(request)
self.assertEqual(response.status_code, 202)
@@ -324,7 +324,7 @@ class TestWebhookView(SimpleTestCase):
body = json.dumps({"action": "opened"}).encode()
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=""):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=""):
with structlog.testing.capture_logs() as logs:
response = build_webhook_view(build_github_provider("posthog"))(request)
@@ -360,7 +360,7 @@ class TestWebhookView(SimpleTestCase):
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
with (
- patch("posthog.ingress.github.provider.get_instance_setting", return_value=""),
+ patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=""),
patch("posthog.ingress.views.capture_exception") as capture,
):
response = build_webhook_view(provider_class("posthog"))(request)
@@ -401,7 +401,7 @@ class TestWebhookView(SimpleTestCase):
headers={"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "pull_request"},
)
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET):
response = build_webhook_view(_FormBodyGitHubProvider("posthog"))(request)
self.assertEqual(response.status_code, 202)
@@ -427,7 +427,7 @@ class TestWebhookView(SimpleTestCase):
with (
patch(
- "posthog.ingress.github.provider.get_instance_setting",
+ "posthog.credentials_service.instance_settings.get_instance_setting",
side_effect=OperationalError("server closed the connection unexpectedly"),
),
patch("posthog.ingress.views.observe_delivery") as observe,
@@ -443,7 +443,7 @@ class TestWebhookView(SimpleTestCase):
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
with (
- patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET),
+ patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET),
patch("posthog.ingress.views.logger") as logger,
):
response = build_webhook_view(_RefusingDeliveriesGitHubProvider("posthog"))(request)
@@ -536,7 +536,7 @@ class _DispatchingViewTestCase(SimpleTestCase):
self.factory = RequestFactory()
self.handler = Mock()
- secret = patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET)
+ secret = patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=SECRET)
secret.start()
self.addCleanup(secret.stop)
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index 9d7cf79cee74..ea64ea02cf6c 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -2,8 +2,8 @@
A scheme whose lookup step fails answers `UNAVAILABLE` rather than judging the signature, because
a step that never completed proves nothing about the caller. `BearerJwt` does this for a JWKS
-fetch failure, `HmacSha256` for a secret read that the database refuses, and `SnsSignature` for
-a signing certificate its verifier could not fetch.
+fetch failure, `HmacSha256` for a secret read that the database or the credentials service refuses,
+and `SnsSignature` for a signing certificate its verifier could not fetch.
"""
import re
@@ -20,6 +20,7 @@ from django.db import DatabaseError, InterfaceError
import structlog
+from posthog.credentials_service.errors import CredentialsServiceFailure
from posthog.dataclasses import frozen
from posthog.ingress.verify.errors import VerifierUnavailable
from posthog.ingress.verify.sns_signature import verify_sns_message
@@ -32,6 +33,10 @@ SignatureEncoding = Literal["hex", "base64"]
# making for a new one. Reach for `HmacSha256` unless the provider leaves no option.
HmacDigest = Literal["sha256", "sha1"]
+# A secret getter that raises one of these could not read the secret, which says nothing about the
+# caller. Any other exception is a bug and still raises.
+_SECRET_READ_FAILURES = (DatabaseError, InterfaceError, CredentialsServiceFailure)
+
class VerificationOutcome(StrEnum):
VERIFIED = "verified"
@@ -176,23 +181,27 @@ class HmacSignature:
return not timestamp or not self._timestamp_is_fresh(timestamp)
def rejects_headers(self, headers: Mapping[str, str]) -> bool:
+ # Well-shaped headers go straight to `_outcome` without a secret read here, so a delivery
+ # reads the secret once: during a credentials-service outage a second read would wait out
+ # a second timeout before answering UNAVAILABLE.
+ if not self._headers_fail(headers):
+ return False
# An unconfigured endpoint keeps answering NOT_CONFIGURED, whatever the headers carry.
try:
secret = self.secret_getter()
- except (DatabaseError, InterfaceError):
+ except _SECRET_READ_FAILURES:
# Leave a failed read to `_outcome`, which answers UNAVAILABLE for it.
return False
- if not secret:
- return False
- return self._headers_fail(headers)
+ return bool(secret)
def _outcome(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
try:
secret = self.secret_getter()
- except (DatabaseError, InterfaceError) as error:
- # A getter that keeps its secret in Postgres reads it here, so a dropped connection
- # leaves the signature unchecked. Letting the error out answers 500, which asks no
- # sender to come back and leaves the lost delivery uncounted.
+ except _SECRET_READ_FAILURES as error:
+ # A getter that keeps its secret in Postgres or in the credentials service reads it here,
+ # so a dropped connection or a service outage leaves the signature unchecked. Letting the
+ # error out answers 500, which asks no sender to come back and leaves the lost delivery
+ # uncounted.
logger.warning(
"ingress_secret_unavailable",
signature_header=self.signature_header,
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 661f68a61fb3..6aeca753b99d 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -11,12 +11,11 @@ import time
import uuid
from collections import deque
from collections.abc import Callable, Collection, Iterable, Mapping
-from dataclasses import dataclass
-from datetime import datetime
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
from typing import Any, Literal, TypedDict, cast
from urllib.parse import urlparse
-from django.conf import settings
from django.core.cache import cache
from django.db.models import Count, F, Func, JSONField, Value
from django.db.models.functions import Cast
@@ -27,6 +26,10 @@ import requests
import structlog
from prometheus_client import Counter
+from posthog.cache_utils import cache_for
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.errors import CredentialsServiceFailure
+from posthog.credentials_service.settings_fallback import get_many_or_settings
from posthog.dataclasses import frozen
from posthog.egress.github.limiter import github_installation_pace_seconds, remember_observed_core_limit
from posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limited
@@ -47,6 +50,54 @@ github_cache_access_counter = Counter(
labelnames=["integration_id", "cache", "repository", "result"],
)
+CREDENTIALS_CALLER = CredentialsCaller.INTEGRATIONS
+
+
+@frozen
+class GitHubAppJwtCredentials:
+ """What PostHog's GitHub App signs its App JWT with."""
+
+ client_id: str
+ private_key: str = field(repr=False)
+
+ @property
+ def configured(self) -> bool:
+ return bool(self.client_id and self.private_key)
+
+
+@frozen
+class GitHubAppOauthCredentials:
+ """What PostHog's GitHub App exchanges a user authorization code or refresh token with."""
+
+ client_id: str
+ client_secret: str = field(repr=False)
+
+
+@cache_for(timedelta(minutes=5))
+def github_app_jwt_credentials() -> GitHubAppJwtCredentials:
+ """The App's client id and private key, read from the credentials service.
+
+ Cached because an App JWT is signed for every installation token and every App API call. A
+ rotated key reaches each process within five minutes, and GitHub accepts more than one private
+ key per App, so the old key stays valid for that time.
+ """
+ values = get_many_or_settings(["GITHUB_APP_CLIENT_ID", "GITHUB_APP_PRIVATE_KEY"], CREDENTIALS_CALLER)
+ return GitHubAppJwtCredentials(
+ client_id=values["GITHUB_APP_CLIENT_ID"], private_key=values["GITHUB_APP_PRIVATE_KEY"]
+ )
+
+
+def github_app_oauth_credentials() -> GitHubAppOauthCredentials:
+ """The App's client id and secret, read from the credentials service.
+
+ Not cached: they are read only when a person authorizes the App or a user token is refreshed.
+ """
+ values = get_many_or_settings(["GITHUB_APP_CLIENT_ID", "GITHUB_APP_CLIENT_SECRET"], CREDENTIALS_CALLER)
+ return GitHubAppOauthCredentials(
+ client_id=values["GITHUB_APP_CLIENT_ID"], client_secret=values["GITHUB_APP_CLIENT_SECRET"]
+ )
+
+
# Repository cache: 1-hour staleness window.
GITHUB_REPOSITORY_CACHE_TTL_SECONDS = 60 * 60
@@ -278,8 +329,9 @@ class GitHubIntegrationBase:
"""
from rest_framework.exceptions import ValidationError
- github_app_client_id = settings.GITHUB_APP_CLIENT_ID
- github_app_private_key = settings.GITHUB_APP_PRIVATE_KEY
+ credentials = github_app_jwt_credentials()
+ github_app_client_id = credentials.client_id
+ github_app_private_key = credentials.private_key
if not github_app_client_id:
raise ValidationError("GITHUB_APP_CLIENT_ID is not configured")
@@ -406,7 +458,12 @@ class GitHubIntegrationBase:
"""
if not installation_id:
return "skipped"
- if not settings.GITHUB_APP_CLIENT_ID or not settings.GITHUB_APP_PRIVATE_KEY:
+ try:
+ app_configured = github_app_jwt_credentials().configured
+ except CredentialsServiceFailure:
+ logger.warning("GitHubIntegration: uninstall failed, GitHub App credentials unavailable", exc_info=True)
+ return "failed"
+ if not app_configured:
logger.warning("GitHubIntegration: uninstall skipped, GitHub App not configured")
return "skipped"
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index b922b2c0bfff..11cc061ca850 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -8,7 +8,6 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
-from django.conf import settings
from django.core.cache import cache
import requests
@@ -21,6 +20,7 @@ from posthog.models.github_integration_base import (
GitHubIntegrationBase,
GitHubIntegrationError,
_is_safe_github_repo_path,
+ github_app_oauth_credentials,
)
from posthog.models.integration.github_audit import GitHubAudit
from posthog.models.user import User
@@ -267,8 +267,9 @@ class GitHubIntegration(GitHubIntegrationBase):
user-to-server access/refresh tokens and their expirations, or ``None`` if
the exchange fails or the response lacks an id/login.
"""
- client_id = settings.GITHUB_APP_CLIENT_ID
- client_secret = settings.GITHUB_APP_CLIENT_SECRET
+ credentials = github_app_oauth_credentials()
+ client_id = credentials.client_id
+ client_secret = credentials.client_secret
if not client_id or not client_secret:
logger.warning("GitHubIntegration: GITHUB_APP_CLIENT_ID/SECRET not configured, cannot exchange code")
return None
diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.py
index 72dee88270bf..ea4272bdd039 100644
--- a/posthog/models/integration/oauth.py
+++ b/posthog/models/integration/oauth.py
@@ -19,11 +19,10 @@ from rest_framework.exceptions import ValidationError
from posthog.cache_utils import cache_for
from posthog.credentials_service.callers import CredentialsCaller
-from posthog.credentials_service.client import credentials_service_enabled
+from posthog.credentials_service.instance_settings import get_many_or_instance_settings
from posthog.credentials_service.settings_fallback import get_many_or_settings
from posthog.dataclasses import frozen
from posthog.egress.slack.observability import record_slack_api_response
-from posthog.models.instance_setting import get_instance_settings
from posthog.models.user import User
from posthog.plugins.plugin_server_api import reload_integrations_on_workers
from posthog.schema_enums import SlackIntegrationScope
@@ -482,25 +481,6 @@ OAUTH_CLIENT_FALLBACK_KEYS: dict[str, tuple[str, str]] = {
SLACK_APP_CLIENT_CREDENTIAL_KEYS = ["SLACK_APP_CLIENT_ID", "SLACK_APP_CLIENT_SECRET"]
-def _slack_instance_setting(key: str) -> str | None:
- return get_instance_settings([key])[key] or None
-
-
-def _slack_app_client_credentials() -> dict[str, str]:
- """Slack's app credentials, with instance settings in place of Django settings.
-
- Self-hosted deployments edit these in the instance settings UI, and the value there wins over
- the environment variable it defaults from. With the service off, the client would read the
- environment variable directly and ignore that edit, so the service is only asked when it is on.
- """
- if not credentials_service_enabled():
- values = get_instance_settings(SLACK_APP_CLIENT_CREDENTIAL_KEYS)
- return {key: values[key] or "" for key in SLACK_APP_CLIENT_CREDENTIAL_KEYS}
- return get_many_or_settings(
- SLACK_APP_CLIENT_CREDENTIAL_KEYS, CREDENTIALS_CALLER, settings_lookup=_slack_instance_setting
- )
-
-
class OauthIntegration:
supported_kinds = [
"slack",
@@ -563,7 +543,7 @@ class OauthIntegration:
client_id, client_secret = values[target.client_id_key], values[target.client_secret_key]
not_configured = f"PostHog connect app not configured for region {target.region}"
elif kind == "slack":
- values = _slack_app_client_credentials()
+ values = get_many_or_instance_settings(SLACK_APP_CLIENT_CREDENTIAL_KEYS, CREDENTIALS_CALLER)
client_id, client_secret = values["SLACK_APP_CLIENT_ID"], values["SLACK_APP_CLIENT_SECRET"]
not_configured = "Slack app not configured"
elif kind == "apple-ads":
diff --git a/posthog/models/integration/slack.py b/posthog/models/integration/slack.py
index 17158370bfb1..f51d54a2dd55 100644
--- a/posthog/models/integration/slack.py
+++ b/posthog/models/integration/slack.py
@@ -20,6 +20,8 @@ from rest_framework.request import Request
from slack_sdk.errors import SlackApiError
from posthog.cache_utils import cache_for
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.instance_settings import get_many_or_instance_settings
from posthog.egress.slack.client import SlackWebClient as WebClient
from posthog.ingress.slack.provider import build_slack_signature_scheme
from posthog.ingress.verify.schemes import VerificationOutcome, hmac_sha256_signature
@@ -393,21 +395,36 @@ class SlackIntegration:
@classmethod
@cache_for(timedelta(minutes=5))
- def slack_config(cls):
- # Span only fires on cache miss (cache_for is process-local in-memory).
- # If preflight.slack_config_main is fast in production traces, this span
- # will be absent; if it appears, it tells us the DB hit was slow.
+ def slack_config(cls) -> dict[str, str]:
+ # Every Slack request to this app is verified with the signing secret, so the credentials are
+ # read here, under the cache, and not once per request. A rotation reaches each process
+ # within five minutes.
with tracer.start_as_current_span("slack_integration.slack_config_db"):
- config = get_instance_settings(
+ config = get_many_or_instance_settings(
[
"SLACK_APP_CLIENT_ID",
"SLACK_APP_CLIENT_SECRET",
"SLACK_APP_SIGNING_SECRET",
- ]
+ ],
+ CredentialsCaller.INTEGRATIONS,
)
return config
+ @classmethod
+ @cache_for(timedelta(minutes=5))
+ def slack_client_id(cls) -> str:
+ """The app's public client id, for preflight.
+
+ Preflight runs on every page load. It reads the instance setting and never the credentials
+ service, so an outage of the service cannot break page loads for a value that is not secret.
+ """
+ # Span only fires on cache miss (cache_for is process-local in-memory).
+ # If preflight.slack_config_main is fast in production traces, this span
+ # will be absent; if it appears, it tells us the DB hit was slow.
+ with tracer.start_as_current_span("slack_integration.slack_client_id_db"):
+ return get_instance_settings(["SLACK_APP_CLIENT_ID"])["SLACK_APP_CLIENT_ID"] or ""
+
@frozen
class SlackRequestSignature:
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index c6827c61bba5..34a771e92e63 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -12,13 +12,24 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, call, patch
from django.core.cache import cache
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
+import jwt
import requests
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from prometheus_client import REGISTRY
+from posthog.credentials_service.test.test_settings_fallback import (
+ FLAG,
+ POST,
+ SERVICE_SETTINGS,
+ _FakeResponse,
+ _keys_asked_for,
+ _steady,
+)
from posthog.egress.github.transport import (
GitHubEgressBudgetExhausted,
GitHubRateLimitError,
@@ -32,6 +43,7 @@ from posthog.models.github_integration_base import (
GITHUB_REPOSITORY_CACHE_TTL_SECONDS,
GitHubIntegrationBase,
PullRequestRef,
+ github_app_jwt_credentials,
)
from posthog.models.integration import (
GitHubInstallationAccessFetchError,
@@ -222,6 +234,43 @@ class TestPullRequestCommentMarker(SimpleTestCase):
assert github.get_pull_request_merge_queue_state("example/repo", 1) == MergeQueueState.TESTING
+@override_settings(**SERVICE_SETTINGS)
+class TestGitHubAppJwtCredentials(SimpleTestCase):
+ def setUp(self) -> None:
+ for patcher in (patch(FLAG, return_value=True), patch("posthog.cache_utils.TEST", False)):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ github_app_jwt_credentials.clear_cache()
+ self.addCleanup(github_app_jwt_credentials.clear_cache)
+
+ def test_app_requests_sign_with_one_cached_service_read(self) -> None:
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ pem = private_key.private_bytes(
+ serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()
+ ).decode()
+ response = _FakeResponse(
+ {
+ "secrets": {"GITHUB_APP_CLIENT_ID": _steady("Iv-from-service"), "GITHUB_APP_PRIVATE_KEY": _steady(pem)},
+ "missing": [],
+ }
+ )
+
+ with (
+ patch(POST, return_value=response) as post,
+ patch("posthog.models.github_integration_base.github_request") as github_request,
+ ):
+ for _ in range(3):
+ GitHubIntegrationBase.app_request("app")
+
+ assert post.call_count == 1
+ assert _keys_asked_for(post.call_args.kwargs["headers"]["Authorization"]) == [
+ "GITHUB_APP_CLIENT_ID",
+ "GITHUB_APP_PRIVATE_KEY",
+ ]
+ app_jwt = github_request.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")
+ assert jwt.decode(app_jwt, private_key.public_key(), algorithms=["RS256"])["iss"] == "Iv-from-service"
+
+
class TestGitHubIntegrationModel(BaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.py
index 3b2b96cbf747..d6c2471bced8 100644
--- a/posthog/models/user_integration.py
+++ b/posthog/models/user_integration.py
@@ -3,7 +3,6 @@ from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from uuid import UUID, uuid4
-from django.conf import settings
from django.db import models, transaction
from django.utils.functional import Promise
@@ -13,7 +12,7 @@ import structlog
from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
from posthog.egress.limiter.policies import Priority
from posthog.helpers.encrypted_fields import EncryptedJSONField
-from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.github_integration_base import GitHubIntegrationBase, github_app_oauth_credentials
from posthog.models.integration import github_account_type, invalidate_github_repository_caches_for_installation
from posthog.models.integration.github_audit import GitHubAudit
from posthog.models.utils import UUIDModel
@@ -319,8 +318,9 @@ class UserGitHubIntegration(GitHubIntegrationBase):
Strips the stored tokens and raises :class:`ReauthorizationRequired` when GitHub
signals the refresh token can't produce a new access token.
"""
- client_id = settings.GITHUB_APP_CLIENT_ID
- client_secret = settings.GITHUB_APP_CLIENT_SECRET
+ credentials = github_app_oauth_credentials()
+ client_id = credentials.client_id
+ client_secret = credentials.client_secret
refresh_token = self.user_refresh_token
if not client_id or not client_secret:
raise Exception("GITHUB_APP_CLIENT_ID / GITHUB_APP_CLIENT_SECRET not configured, cannot refresh user token")
diff --git a/posthog/views.py b/posthog/views.py
index 06a12318036d..c9ba26fcc746 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -183,7 +183,7 @@ def render_query(request: HttpRequest) -> HttpResponse:
@never_cache
def preflight_check(request: HttpRequest) -> JsonResponse:
with tracer.start_as_current_span("preflight.slack_config_main"):
- slack_client_id = SlackIntegration.slack_config().get("SLACK_APP_CLIENT_ID")
+ slack_client_id = SlackIntegration.slack_client_id()
hubspot_client_id = settings.HUBSPOT_APP_CLIENT_ID
salesforce_client_id = settings.SALESFORCE_CONSUMER_KEY
diff --git a/products/commands/backend/tests/test_dispatch.py b/products/commands/backend/tests/test_dispatch.py
index fc0c117b0a26..9e783b82d0ae 100644
--- a/products/commands/backend/tests/test_dispatch.py
+++ b/products/commands/backend/tests/test_dispatch.py
@@ -679,7 +679,7 @@ class TestDispatchCommentCommand(BaseTest):
assert issue.status == expected_status
assert (issue.assignee.type if issue.assignee else None) == expected_assignee
- @patch("posthog.ingress.github.provider.get_instance_setting", return_value="test-webhook-secret")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value="test-webhook-secret")
def test_a_signed_comment_with_a_command_is_queued(self, _secret: MagicMock) -> None:
reset_consumer_registry()
self.addCleanup(reset_consumer_registry)
diff --git a/products/conversations/backend/api/slack_oauth.py b/products/conversations/backend/api/slack_oauth.py
index cf206e354fdd..6c2761b31418 100644
--- a/products/conversations/backend/api/slack_oauth.py
+++ b/products/conversations/backend/api/slack_oauth.py
@@ -11,6 +11,9 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.errors import CredentialsServiceFailure
+from posthog.credentials_service.instance_settings import get_many_or_instance_settings
from posthog.egress.slack.transport import slack_request
from posthog.helpers.impersonation import is_impersonated
from posthog.models.instance_setting import get_instance_settings
@@ -168,9 +171,14 @@ def support_slack_oauth_callback(request: HttpRequest) -> HttpResponse:
if not code:
return _error_response(next_path, "missing_code", 400)
- support_settings = get_instance_settings(["SUPPORT_SLACK_APP_CLIENT_ID", "SUPPORT_SLACK_APP_CLIENT_SECRET"])
- client_id = str(support_settings.get("SUPPORT_SLACK_APP_CLIENT_ID") or "")
- client_secret = str(support_settings.get("SUPPORT_SLACK_APP_CLIENT_SECRET") or "")
+ try:
+ support_settings = get_many_or_instance_settings(
+ ["SUPPORT_SLACK_APP_CLIENT_ID", "SUPPORT_SLACK_APP_CLIENT_SECRET"], CredentialsCaller.CONVERSATIONS
+ )
+ except CredentialsServiceFailure:
+ return _error_response(next_path, "support_slack_unavailable", 503)
+ client_id = str(support_settings["SUPPORT_SLACK_APP_CLIENT_ID"])
+ client_secret = str(support_settings["SUPPORT_SLACK_APP_CLIENT_SECRET"])
if not client_id or not client_secret:
return _error_response(next_path, "support_slack_not_configured", 503)
diff --git a/products/conversations/backend/api/tests/test_slack_oauth.py b/products/conversations/backend/api/tests/test_slack_oauth.py
index d6e21f4c412a..4adb5a9062fa 100644
--- a/products/conversations/backend/api/tests/test_slack_oauth.py
+++ b/products/conversations/backend/api/tests/test_slack_oauth.py
@@ -1,10 +1,15 @@
+import json
+
from unittest.mock import patch
+from django.core import signing
from django.test import RequestFactory, SimpleTestCase
+from posthog.credentials_service.errors import CredentialsServiceUnreachableError
+from posthog.models.user import User
from posthog.rate_limit import SupportSlackOAuthCallbackThrottle
-from products.conversations.backend.api.slack_oauth import support_slack_oauth_callback
+from products.conversations.backend.api.slack_oauth import STATE_SALT, support_slack_oauth_callback
class TestSupportSlackOAuthCallbackThrottle(SimpleTestCase):
@@ -17,3 +22,22 @@ class TestSupportSlackOAuthCallbackThrottle(SimpleTestCase):
assert response.status_code == 429
mock_post.assert_not_called()
+
+
+class TestSupportSlackOAuthCallbackCredentialsOutage(SimpleTestCase):
+ @patch("products.conversations.backend.api.slack_oauth.slack_request")
+ @patch(
+ "products.conversations.backend.api.slack_oauth.get_many_or_instance_settings",
+ side_effect=CredentialsServiceUnreachableError("refused"),
+ )
+ @patch.object(SupportSlackOAuthCallbackThrottle, "allow_request", return_value=True)
+ def test_credentials_service_failure_returns_retryable_error(self, _mock_allow, _mock_settings, mock_post):
+ state = signing.dumps({"user_id": 1, "team_id": 1}, salt=STATE_SALT)
+ request = RequestFactory().get("/api/conversations/v1/slack/callback", {"state": state, "code": "y"})
+ request.user = User(id=1)
+
+ response = support_slack_oauth_callback(request)
+
+ assert response.status_code == 503
+ assert json.loads(response.content) == {"error": "support_slack_unavailable"}
+ mock_post.assert_not_called()
diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.py
index 24b2ba02d8d8..f3ede863a48e 100644
--- a/products/conversations/backend/support_slack.py
+++ b/products/conversations/backend/support_slack.py
@@ -1,9 +1,12 @@
+from datetime import timedelta
from typing import TYPE_CHECKING, cast
from django.db import transaction
+from posthog.cache_utils import cache_for
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.instance_settings import get_many_or_instance_settings
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
-from posthog.models.instance_setting import get_instance_settings
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import mask_key_value
@@ -25,11 +28,15 @@ SUPPORT_SLACK_FILE_SCOPES = frozenset({SUPPORT_SLACK_FILE_READ_SCOPE, SUPPORT_SL
SUPPORT_SLACK_CUSTOM_IDENTITY_SCOPE = "chat:write.customize"
-def get_support_slack_settings() -> dict:
- return get_instance_settings(
+# Every SupportHog delivery is verified with the signing secret, so the read is cached and not made
+# once per request. A rotation reaches each process within five minutes.
+@cache_for(timedelta(minutes=5))
+def get_support_slack_settings() -> dict[str, str]:
+ return get_many_or_instance_settings(
[
"SUPPORT_SLACK_SIGNING_SECRET",
- ]
+ ],
+ CredentialsCaller.CONVERSATIONS,
)
diff --git a/products/customer_analytics/backend/test/test_feature_request_github.py b/products/customer_analytics/backend/test/test_feature_request_github.py
index cbe78340bfb8..2f644eab1ca3 100644
--- a/products/customer_analytics/backend/test/test_feature_request_github.py
+++ b/products/customer_analytics/backend/test/test_feature_request_github.py
@@ -179,7 +179,7 @@ class TestFeatureRequestGitHubIngress(SimpleTestCase):
@patch("products.workflows.backend.facade.api.accept_github_event")
@patch("products.conversations.backend.facade.api.accept_github_event")
@patch("products.customer_analytics.backend.facade.api.process_feature_request_github_delivery")
- @patch("posthog.ingress.github.provider.get_instance_setting", return_value="test-webhook-secret")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value="test-webhook-secret")
def test_signed_issue_delivery_enqueues_only_feature_request_work(
self,
_get_secret: Mock,
diff --git a/products/error_tracking/backend/test/test_github_external_references.py b/products/error_tracking/backend/test/test_github_external_references.py
index 65447ea252b7..e7bf491e29ea 100644
--- a/products/error_tracking/backend/test/test_github_external_references.py
+++ b/products/error_tracking/backend/test/test_github_external_references.py
@@ -114,7 +114,7 @@ class TestErrorTrackingGitHubWebhook(SimpleTestCase):
]
)
@patch("products.error_tracking.backend.tasks.github.process_github_external_reference.delay")
- @patch("posthog.ingress.github.provider.get_instance_setting", return_value="webhook-secret")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value="webhook-secret")
def test_verified_delivery_enqueues_supported_events(
self,
_name: str,
diff --git a/products/review_hog/backend/tests/test_automatic_reviews.py b/products/review_hog/backend/tests/test_automatic_reviews.py
index b87af44d19ee..85318cd0c0e5 100644
--- a/products/review_hog/backend/tests/test_automatic_reviews.py
+++ b/products/review_hog/backend/tests/test_automatic_reviews.py
@@ -105,7 +105,7 @@ class TestAuthoredPRWebhook(SimpleTestCase):
dispatcher = WebhookDispatcher(ConsumerRegistry(providers=SPECS, consumers=WEBHOOK_CONSUMERS))
self.enterContext(patch("posthog.ingress.views.get_dispatcher", return_value=dispatcher))
self.secret = self.enterContext(
- patch("posthog.ingress.github.provider.get_instance_setting", return_value=_SECRET)
+ patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=_SECRET)
)
def _cache_summary(
diff --git a/products/skills/backend/api/community_publish_services.py b/products/skills/backend/api/community_publish_services.py
index ba428366bf35..f57def2ea472 100644
--- a/products/skills/backend/api/community_publish_services.py
+++ b/products/skills/backend/api/community_publish_services.py
@@ -20,6 +20,8 @@ import yaml
import requests
import structlog
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.settings_fallback import get_many_or_settings
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError, github_request
from posthog.egress.limiter.policies import Priority
@@ -505,8 +507,11 @@ def _publisher_app_jwt() -> str | None:
cannot sign: a key GitHub would reject is a deployment nobody can retry their way out of, so it
has to read as "this instance cannot publish" rather than as a GitHub outage.
"""
- client_id = settings.COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID
- private_key = settings.COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY
+ values = get_many_or_settings(
+ ["COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID", "COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY"], CredentialsCaller.SKILLS
+ )
+ client_id = values["COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID"]
+ private_key = values["COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY"]
if not client_id or not private_key:
return None
diff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.py
index 5189e958f9a1..fc27ed46ae99 100644
--- a/products/slack_app/backend/services/slack_user_oauth.py
+++ b/products/slack_app/backend/services/slack_user_oauth.py
@@ -33,8 +33,10 @@ import structlog
from pydantic import BaseModel, ValidationError
from slack_sdk.errors import SlackApiError, SlackClientError
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.errors import CredentialsServiceFailure
+from posthog.credentials_service.instance_settings import get_many_or_instance_settings
from posthog.egress.slack.client import SlackWebClient as WebClient
-from posthog.models.instance_setting import get_instance_settings
from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
@@ -285,9 +287,15 @@ def _credentials() -> tuple[str, str]:
"""Resolve Slack app credentials at call time so dev/test overrides via
instance settings work the same way the workspace install flow does.
"""
- from_settings = get_instance_settings(["SLACK_APP_CLIENT_ID", "SLACK_APP_CLIENT_SECRET"])
- client_id = from_settings.get("SLACK_APP_CLIENT_ID") or ""
- client_secret = from_settings.get("SLACK_APP_CLIENT_SECRET") or ""
+ try:
+ from_settings = get_many_or_instance_settings(
+ ["SLACK_APP_CLIENT_ID", "SLACK_APP_CLIENT_SECRET"], CredentialsCaller.INTEGRATIONS
+ )
+ except CredentialsServiceFailure as exc:
+ # The views catch SlackUserOAuthError and redirect back to settings, rather than answering 500.
+ raise SlackUserOAuthError("Slack app credentials temporarily unavailable") from exc
+ client_id = from_settings["SLACK_APP_CLIENT_ID"]
+ client_secret = from_settings["SLACK_APP_CLIENT_SECRET"]
if not client_id or not client_secret:
raise SlackUserOAuthError("Slack app credentials not configured")
return client_id, client_secret
diff --git a/products/slack_app/backend/tests/services/test_slack_user_oauth.py b/products/slack_app/backend/tests/services/test_slack_user_oauth.py
index aad06f9a536d..243e796dc5cf 100644
--- a/products/slack_app/backend/tests/services/test_slack_user_oauth.py
+++ b/products/slack_app/backend/tests/services/test_slack_user_oauth.py
@@ -14,6 +14,7 @@ from unittest.mock import MagicMock, patch
from slack_sdk.errors import SlackApiError
+from posthog.credentials_service.errors import CredentialsServiceUnreachableError
from posthog.models.integration import SlackIntegration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
@@ -323,7 +324,7 @@ class TestExchangeCode:
@pytest.fixture(autouse=True)
def credentials(self):
with patch(
- "products.slack_app.backend.services.slack_user_oauth.get_instance_settings",
+ "posthog.credentials_service.instance_settings.get_instance_settings",
return_value={"SLACK_APP_CLIENT_ID": "cid", "SLACK_APP_CLIENT_SECRET": "csecret"},
):
yield
@@ -362,6 +363,15 @@ class TestExchangeCode:
with pytest.raises(SlackUserOAuthError, match="missing user or team id"):
exchange_code(code="abc", redirect_uri="https://ph.example/complete/slack-link/")
+ def test_credentials_service_failure_raises_oauth_error(self, slack_client):
+ with patch(
+ "products.slack_app.backend.services.slack_user_oauth.get_many_or_instance_settings",
+ side_effect=CredentialsServiceUnreachableError("refused"),
+ ):
+ with pytest.raises(SlackUserOAuthError, match="temporarily unavailable"):
+ exchange_code(code="abc", redirect_uri="https://ph.example/complete/slack-link/")
+ slack_client.return_value.openid_connect_token.assert_not_called()
+
@pytest.mark.django_db(transaction=False)
class TestInviteToken:
diff --git a/products/slack_app/backend/tests/views/test_slack_user_link.py b/products/slack_app/backend/tests/views/test_slack_user_link.py
index f5e3c45e515f..c387fee877fd 100644
--- a/products/slack_app/backend/tests/views/test_slack_user_link.py
+++ b/products/slack_app/backend/tests/views/test_slack_user_link.py
@@ -85,7 +85,7 @@ class TestAuthorizeView:
with (
patch("products.slack_app.backend.views.slack_user_link.is_slack_app_oauth_enabled", return_value=True),
patch(
- "products.slack_app.backend.services.slack_user_oauth.get_instance_settings",
+ "posthog.credentials_service.instance_settings.get_instance_settings",
return_value={"SLACK_APP_CLIENT_ID": "cid", "SLACK_APP_CLIENT_SECRET": "csecret"},
),
):
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index f56356f1027b..19236f749ce2 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -12,7 +12,8 @@ just supplies its own ``Authorization`` header and the installation id as the bu
import time
import base64
import binascii
-from datetime import datetime
+from dataclasses import field
+from datetime import datetime, timedelta
from typing import Any
from urllib.parse import quote
@@ -23,6 +24,9 @@ import jwt
import requests
import structlog
+from posthog.cache_utils import cache_for
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.settings_fallback import get_many_or_settings
from posthog.dataclasses import frozen
from posthog.egress.github.limiter import remember_observed_core_limit
from posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limited
@@ -194,9 +198,31 @@ def _parse_review_thread_comments(comment_nodes: list) -> list[dict]:
]
-def _app_private_key() -> str:
+@frozen
+class _AppJwtCredentials:
+ client_id: str
+ private_key: str = field(repr=False)
+
+
+@cache_for(timedelta(minutes=5))
+def _app_jwt_credentials() -> _AppJwtCredentials:
+ """The App's client id and private key, read from the credentials service.
+
+ Cached because an App JWT is signed for every installation token. A rotated key reaches each
+ process within five minutes, and GitHub accepts more than one private key per App, so the old key
+ stays valid for that time.
+ """
+ values = get_many_or_settings(
+ ["STAMPHOG_GITHUB_APP_CLIENT_ID", "STAMPHOG_GITHUB_APP_PRIVATE_KEY"], CredentialsCaller.STAMPHOG
+ )
+ return _AppJwtCredentials(
+ client_id=values["STAMPHOG_GITHUB_APP_CLIENT_ID"], private_key=values["STAMPHOG_GITHUB_APP_PRIVATE_KEY"]
+ )
+
+
+def _app_private_key(credentials: _AppJwtCredentials) -> str:
"""The Stamphog App private key, with escaped newlines restored (env vars often carry ``\\n``)."""
- key = settings.STAMPHOG_GITHUB_APP_PRIVATE_KEY
+ key = credentials.private_key
if not key:
raise StamphogGitHubError("STAMPHOG_GITHUB_APP_PRIVATE_KEY is not configured")
return key.replace("\\n", "\n").strip()
@@ -212,14 +238,15 @@ def _build_app_jwt() -> str:
# Client id is the preferred issuer (matches the core GitHub integration); the app id fallback
# covers workers whose chart predates the client id env. Drop the fallback once every worker
# deploy ships STAMPHOG_GITHUB_APP_CLIENT_ID.
- issuer = settings.STAMPHOG_GITHUB_APP_CLIENT_ID or settings.STAMPHOG_GITHUB_APP_ID
+ credentials = _app_jwt_credentials()
+ issuer = credentials.client_id or settings.STAMPHOG_GITHUB_APP_ID
if not issuer:
raise StamphogGitHubError("Neither STAMPHOG_GITHUB_APP_CLIENT_ID nor STAMPHOG_GITHUB_APP_ID is configured")
now = int(time.time())
try:
return jwt.encode(
{"iat": now - 60, "exp": now + 540, "iss": str(issuer)},
- _app_private_key(),
+ _app_private_key(credentials),
algorithm="RS256",
)
except Exception as exc:
@@ -241,8 +268,11 @@ def exchange_oauth_code_for_user_token(code: str) -> str | None:
Stamphog's *own* client id/secret. Returns the user access token, or ``None`` when the creds are
unset or GitHub rejects the code — callers must treat ``None`` as "unverified" and fail closed.
"""
- client_id = settings.STAMPHOG_GITHUB_APP_CLIENT_ID
- client_secret = settings.STAMPHOG_GITHUB_APP_CLIENT_SECRET
+ values = get_many_or_settings(
+ ["STAMPHOG_GITHUB_APP_CLIENT_ID", "STAMPHOG_GITHUB_APP_CLIENT_SECRET"], CredentialsCaller.STAMPHOG
+ )
+ client_id = values["STAMPHOG_GITHUB_APP_CLIENT_ID"]
+ client_secret = values["STAMPHOG_GITHUB_APP_CLIENT_SECRET"]
if not client_id or not client_secret:
# No creds means we can't verify ownership, so we must not bind anything.
logger.warning("stamphog github: STAMPHOG_GITHUB_APP_CLIENT_ID/SECRET unset, cannot verify installation")
diff --git a/products/tasks/backend/logic/services/infrastructure_status.py b/products/tasks/backend/logic/services/infrastructure_status.py
index a6594255f6c4..3864f96a6d7e 100644
--- a/products/tasks/backend/logic/services/infrastructure_status.py
+++ b/products/tasks/backend/logic/services/infrastructure_status.py
@@ -23,7 +23,7 @@ from temporalio.service import RPCError, RPCStatusCode
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_request
from posthog.egress.limiter.policies import Priority
-from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.github_integration_base import GitHubIntegrationBase, github_app_jwt_credentials
from posthog.temporal.common.client import async_connect
from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME
@@ -89,7 +89,7 @@ class InfrastructureStatus:
@cached_property
def _github_installation_id(self) -> str | None:
- if not (settings.GITHUB_APP_CLIENT_ID and settings.GITHUB_APP_PRIVATE_KEY):
+ if not github_app_jwt_credentials().configured:
return None
response = GitHubIntegrationBase.app_request("repos/PostHog/posthog/installation", timeout=5)
response.raise_for_status()
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index acf8e9ecbce6..04486d7ac9a2 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -116,7 +116,7 @@ class TestGitHubPRWebhook(TestCase):
headers={"x-hub-signature-256": signature, "x-github-event": event_type},
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_webhook(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -151,7 +151,7 @@ class TestGitHubPRWebhook(TestCase):
("unresolvable_login", "stranger", None, "user-123"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_attributes_to_merger(
self, _name, merged_by_login, expected_property, expected_distinct_id, mock_capture, mock_get_secret
@@ -180,7 +180,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(call_kwargs["properties"].get("pr_merged_by_distinct_id"), expected_property)
@patch("products.signals.backend.facade.github.resolve_github_login_distinct_id", side_effect=RuntimeError("boom"))
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_by_resolution_failure_keeps_webhook_successful(
self, mock_capture, mock_get_secret, _mock_resolve
@@ -208,7 +208,7 @@ class TestGitHubPRWebhook(TestCase):
"products.signals.backend.facade.github.resolve_github_login_distinct_id",
side_effect=OperationalError("canceling statement due to statement timeout"),
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_attribution_timeout_keeps_webhook_successful(self, mock_capture, mock_get_secret, _mock_resolve):
# A slow member lookup must degrade to no attribution, never cost the delivery:
@@ -243,7 +243,7 @@ class TestGitHubPRWebhook(TestCase):
"products.signals.backend.facade.github.resolve_github_login_distinct_id",
side_effect=OperationalError("server closed the connection unexpectedly"),
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_attribution_connection_error_is_not_counted_as_timeout(
self, mock_capture, mock_get_secret, _mock_resolve
@@ -274,7 +274,7 @@ class TestGitHubPRWebhook(TestCase):
_sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"}), timeouts
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture", side_effect=RuntimeError("capture down"))
def test_task_backed_capture_failure_increments_drop_counter(self, _mock_capture, mock_get_secret):
# Capture failures must still count as dropped events for Task-owned PRs.
@@ -292,7 +292,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 202)
self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_delivery_without_installation_matches_no_run(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -313,7 +313,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertNotIn("pr_merged", self.task_run.output)
self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_publishes_stream_events(self, mock_capture, mock_get_secret):
# A live installation-progress view only learns about the merge through the stream;
@@ -336,7 +336,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(len(progress), 1)
self.assertEqual(progress[0]["notification"]["params"]["label"], "Pull request merged")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_from_fork_does_not_record_pr_merged(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -364,7 +364,7 @@ class TestGitHubPRWebhook(TestCase):
run.refresh_from_db()
self.assertEqual(run.output, output)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_for_other_pr_on_same_branch_does_not_record_pr_merged(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -421,7 +421,7 @@ class TestGitHubPRWebhook(TestCase):
("already_terminal_run", {"wizard_config": {}}, TaskRun.Status.COMPLETED, {}, 0),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_signals_wizard_workflow_completion(
self, _name, state, status, extra_output, expected_signals, _mock_capture, mock_get_secret
@@ -445,7 +445,7 @@ class TestGitHubPRWebhook(TestCase):
if expected_signals:
mock_signal.assert_called_once_with(run.id, TaskRun.Status.COMPLETED, None)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_resolves_to_active_run_when_resume_shares_pr(self, _mock_capture, mock_get_secret):
# A resumed wizard run shares its predecessor's PR; the merge must land on the
@@ -484,7 +484,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertIs(active_run.output.get("pr_merged"), True)
self.assertNotIn("pr_merged", terminal_run.output)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_merged_signal_failure_keeps_webhook_successful(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -527,7 +527,7 @@ class TestGitHubPRWebhook(TestCase):
("local_run", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, TaskRun.Environment.LOCAL, 0),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_closed_cancels_wizard_run(
self, _name, state, status, environment, expected_cancels, _mock_capture, mock_get_secret
@@ -565,7 +565,7 @@ class TestGitHubPRWebhook(TestCase):
("unannounced_pr_closed", "https://github.com/posthog/posthog/pull/791", False, 0),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_closed_queues_slack_thread_notice(
self, _name, pr_url, merged, expected_enqueues, _mock_capture, mock_get_secret
@@ -598,7 +598,7 @@ class TestGitHubPRWebhook(TestCase):
if expected_enqueues:
mock_delay.assert_called_once_with(str(run.id), pr_url, merged=merged)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_closed_cancel_failure_keeps_webhook_successful(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -620,7 +620,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 202)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -641,7 +641,7 @@ class TestGitHubPRWebhook(TestCase):
call_kwargs = mock_capture.call_args[1]
self.assertEqual(call_kwargs["event"], "pr_closed")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_webhook(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -680,7 +680,7 @@ class TestGitHubPRWebhook(TestCase):
("over_the_cap", _PR_BODY_MAX_CHARS + 1, True),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_body_is_capped(self, _name, body_length, expected_truncated, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -713,7 +713,7 @@ class TestGitHubPRWebhook(TestCase):
("closed", {"merged": True}, "merged"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_action_records_pr_state(self, action_name, pr_fields, expected_state, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -734,7 +734,7 @@ class TestGitHubPRWebhook(TestCase):
assert self.task_run.output is not None
self.assertEqual(self.task_run.output.get("pr_state"), expected_state)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_state_only_action_records_state_without_analytics(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -755,7 +755,7 @@ class TestGitHubPRWebhook(TestCase):
assert self.task_run.output is not None
self.assertEqual(self.task_run.output.get("pr_state"), "draft")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_state_not_recorded_for_unclaimed_pr(self, _mock_capture, mock_get_secret):
"""A same-branch webhook for a different PR must not restate this run's PR."""
@@ -778,7 +778,7 @@ class TestGitHubPRWebhook(TestCase):
assert self.task_run.output is not None
self.assertNotIn("pr_state", self.task_run.output)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_backfills_pr_url_on_signed_head_branch_match(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -810,7 +810,7 @@ class TestGitHubPRWebhook(TestCase):
@parameterized.expand([("primary_url", False), ("additional_url", True)])
@patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_repairs_missing_artifact_for_existing_pr_url(
self, _name, additional_url, mock_capture, mock_get_secret, mock_feature_enabled
@@ -843,7 +843,7 @@ class TestGitHubPRWebhook(TestCase):
run.refresh_from_db()
self.assertEqual(run.state["verified_pr_urls"], [pr_url])
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_backfills_pr_url_on_wizard_head_branch_match(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -873,7 +873,7 @@ class TestGitHubPRWebhook(TestCase):
assert run.output is not None
self.assertEqual(run.output["pr_url"], pr_url)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_from_fork_does_not_backfill_pr_url(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -901,7 +901,7 @@ class TestGitHubPRWebhook(TestCase):
run.refresh_from_db()
self.assertEqual(run.output, output)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_prefers_self_driving_run_over_newer_reviewhog_run(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -960,7 +960,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(review_run.output, {})
self.assertNotIn("verified_pr_urls", review_run.state or {})
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_opened_does_not_overwrite_existing_pr_url(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -996,7 +996,7 @@ class TestGitHubPRWebhook(TestCase):
[existing, "https://github.com/posthog/posthog/pull/901"],
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_invalid_signature_rejected(self, mock_get_secret):
"""Test that requests with invalid signatures are rejected."""
mock_get_secret.return_value = self.webhook_secret
@@ -1013,7 +1013,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 403)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_missing_signature_rejected(self, mock_get_secret):
"""Test that requests without signatures are rejected."""
mock_get_secret.return_value = self.webhook_secret
@@ -1029,7 +1029,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 403)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_unmatched_pr_without_installation_not_captured(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1047,7 +1047,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 202)
mock_capture.assert_not_called()
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_non_pr_non_issue_event_ignored(self, mock_get_secret):
"""Test that events other than pull_request/issues/issue_comment are acknowledged but ignored."""
mock_get_secret.return_value = self.webhook_secret
@@ -1058,7 +1058,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 202)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("products.tasks.backend.webhooks.refresh_pull_request_review_decisions")
def test_ignored_pr_actions(self, refresh_review_decisions, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1080,7 +1080,7 @@ class TestGitHubPRWebhook(TestCase):
def test_webhook_secret_not_configured(self):
"""Test that webhook returns 500 if secret is not configured."""
- with patch("posthog.ingress.github.provider.get_instance_setting", return_value=None):
+ with patch("posthog.credentials_service.instance_settings.get_instance_setting", return_value=None):
payload = {"action": "closed", "pull_request": {"html_url": "https://github.com/org/repo/pull/1"}}
response = self.client.post(
@@ -1097,7 +1097,7 @@ class TestGitHubPRWebhook(TestCase):
response = self.client.get("/webhooks/github/pr/")
self.assertEqual(response.status_code, 405)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_webhook_does_not_attribute_foreign_repo_pr_to_unrelated_run(self, mock_capture, mock_get_secret):
# Regression: a PR opened on a repo that has no matching TaskRun must
@@ -1187,7 +1187,7 @@ class TestGitHubPRReviewWebhook(TestCase):
("unresolvable_login", "stranger", None, "user-123"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_review_submission_attributes_to_reviewer(
self, _name, reviewer_login, expected_property, expected_distinct_id, mock_capture, mock_get_secret
@@ -1219,7 +1219,7 @@ class TestGitHubPRReviewWebhook(TestCase):
("non_submitted_action", {"login": "octocat", "id": 583231, "type": "User"}, "dismissed"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
@patch("products.tasks.backend.webhooks.refresh_pull_request_review_decisions")
def test_review_events_not_captured(
@@ -1287,7 +1287,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
("research", True, None, "research", SignalReport.Status.READY),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_event_falls_back_to_task_links(
self, _name, merged, actor_kind, relationship, expected_status, _mock_capture, mock_get_secret
@@ -1317,7 +1317,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
self.assertEqual(pr.state, "merged" if merged else "closed")
self.assertIs(pr.merged, merged)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_secondary_task_pr_webhook_persists_only_matching_link_and_reads_the_stack(self, _capture, get_secret):
from products.signals.backend.models import SignalReportPullRequest
@@ -1396,7 +1396,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_event_transitions_linked_report(
self,
@@ -1429,7 +1429,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
"2026-09-20T12:30:00+00:00" if merged else None,
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_merge_without_matching_assignment_is_a_noop(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1447,7 +1447,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
("closed", False, SignalReport.Status.SUPPRESSED, SignalReportAssignment.PrState.CLOSED),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_event_transitions_every_report_linked_to_the_pr(
self, _name, merged, expected_status, expected_pr_state, _mock_capture, mock_get_secret
@@ -1507,7 +1507,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
legacy_report.refresh_from_db()
self.assertEqual(legacy_report.status, expected_status)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_event_does_not_transition_assignment_for_another_pr(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1526,7 +1526,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.OPEN)
self.assertFalse(self.assignment.pr_merged)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_event_only_updates_teams_connected_to_the_installation(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1576,7 +1576,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
("www_host_trailing_slash", "https://www.github.com/posthog/posthog/pull/42/"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pr_url_variants_match_by_repository_and_number(self, _name, stored_pr_url, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1658,7 +1658,7 @@ class TestExternalPRWebhook(TestCase):
}
@patch("products.signals.backend.tasks.link_report_tracker_issues.delay")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_promotion_prs_do_not_attach_to_a_completed_report_discussion(
self, mock_capture: MagicMock, mock_get_secret: MagicMock, mock_link_report: MagicMock
@@ -1728,7 +1728,7 @@ class TestExternalPRWebhook(TestCase):
("merged", "closed", True, "pr_merged"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_external_pr_event_attributes_to_installation_team(
self, _name, action, merged, expected_event, mock_capture, mock_get_secret
@@ -1763,7 +1763,7 @@ class TestExternalPRWebhook(TestCase):
for key in ("pr_title", "pr_body", "pr_labels", "pr_requested_reviewers", "pr_is_draft"):
self.assertIsNone(props[key])
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_external_pr_event_is_deduplicated_per_action(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1777,7 +1777,7 @@ class TestExternalPRWebhook(TestCase):
second_uuid = mock_capture.call_args_list[1][1]["uuid"]
self.assertEqual(first_uuid, second_uuid)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_external_pr_without_resolvable_installation_is_dropped(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1790,7 +1790,7 @@ class TestExternalPRWebhook(TestCase):
self.assertEqual(response.status_code, 202)
mock_capture.assert_not_called()
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_external_pr_unresolved_installation_increments_drop_counter(self, mock_capture, mock_get_secret):
# The silent drop is now a counter, so a webhook-side event loss shows up as an
@@ -1806,7 +1806,7 @@ class TestExternalPRWebhook(TestCase):
mock_capture.assert_not_called()
self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture", side_effect=RuntimeError("capture down"))
def test_external_pr_capture_exception_increments_drop_counter(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1841,7 +1841,7 @@ class TestExternalPRWebhook(TestCase):
# Attribution still resolves off the Integration rows alone.
self.assertEqual(installation_team_ids(payload), [self.team.id])
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_run_in_another_team_does_not_claim_the_delivery(self, mock_capture, mock_get_secret):
# The run lookup is scoped to the installation's teams, so a run belonging to an
@@ -1880,7 +1880,7 @@ class TestExternalPRWebhook(TestCase):
self.assertIsNone(properties["run_id"])
self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_external_pr_shared_installation_resolves_deterministically(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -1896,7 +1896,7 @@ class TestExternalPRWebhook(TestCase):
distinct_ids = {call[1]["distinct_id"] for call in mock_capture.call_args_list}
self.assertEqual(distinct_ids, {str(expected_team.uuid)})
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_external_pr_without_installation_block_is_dropped(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -2442,7 +2442,7 @@ class TestGitHubWebhookFanout(TestCase):
]
)
@patch("products.conversations.backend.services.github_events.process_github_event")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_issues_event_dispatched_to_conversations(self, _name, url, mock_secret, mock_task):
mock_secret.return_value = self.webhook_secret
mock_task.delay = MagicMock()
@@ -2465,7 +2465,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(call_kwargs["repo"], "myorg/myrepo")
@patch("products.conversations.backend.services.github_events.process_github_event")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_issue_comment_event_dispatched_to_conversations(self, mock_secret, mock_task):
mock_secret.return_value = self.webhook_secret
mock_task.delay = MagicMock()
@@ -2486,7 +2486,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(mock_task.delay.call_args[1]["event_type"], "issue_comment")
@patch("products.conversations.backend.services.github_events.process_github_event")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_issues_event_without_matching_team_is_not_dispatched(self, mock_secret, mock_task):
mock_secret.return_value = self.webhook_secret
mock_task.delay = MagicMock()
@@ -2510,7 +2510,7 @@ class TestGitHubWebhookFanout(TestCase):
("unified_url", "/webhooks/github/"),
]
)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
@patch("posthog.github.pull_request_events.posthoganalytics.capture")
def test_pull_request_routed(self, _name, url, mock_capture, mock_secret):
mock_secret.return_value = self.webhook_secret
@@ -2530,7 +2530,7 @@ class TestGitHubWebhookFanout(TestCase):
mock_capture.assert_called_once()
self.assertEqual(mock_capture.call_args[1]["event"], "pr_merged")
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_unified_url_unknown_event_is_accepted(self, mock_secret):
mock_secret.return_value = self.webhook_secret
@@ -2539,7 +2539,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(response.status_code, 202)
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_failed_handler_releases_dedup_so_redelivery_is_processed(self, mock_secret):
# The dedup mark is set before the handler runs; a handler failure must release it so
# GitHub's redelivery of the same GUID gets processed instead of silently skipped for
@@ -2566,7 +2566,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(third.status_code, 202)
mock_handler.assert_called_once()
- @patch("posthog.ingress.github.provider.get_instance_setting")
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
def test_unified_url_bad_signature_returns_403(self, mock_secret):
mock_secret.return_value = self.webhook_secret