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.

refactor(integrations): move posthog and ee call sites to the integrations SDK (#125005)

Tom Owersf4804154864f
diff --git a/ee/api/vercel/tasks.py b/ee/api/vercel/tasks.py
index 40e1139c570f..34d28a3c0395 100644
--- a/ee/api/vercel/tasks.py
+++ b/ee/api/vercel/tasks.py
@@ -14,7 +14,7 @@ logger = structlog.get_logger(__name__)
def backfill_vercel_connectable_resources() -> None:
"""One-shot task to create missing Integration resources for connectable Vercel installations."""
from ee.vercel.client import VercelAPIClient
- from ee.vercel.integration import VercelIntegration
+ from ee.vercel.integration import VercelIntegration, get_or_create_connectable_resource
installations = OrganizationIntegration.objects.filter(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
@@ -33,12 +33,7 @@ def backfill_vercel_connectable_resources() -> None:
for team in teams_without_resources:
try:
- resource, created = Integration.objects.get_or_create(
- team=team,
- kind=Integration.IntegrationKind.VERCEL,
- integration_id=str(team.pk),
- defaults={"config": {"type": "connectable"}},
- )
+ resource, created = get_or_create_connectable_resource(team)
if not created:
continue
@@ -49,7 +44,7 @@ def backfill_vercel_connectable_resources() -> None:
client = VercelAPIClient(bearer_token=access_token)
client.import_resource(
integration_config_id=installation.integration_id,
- resource_id=str(resource.pk),
+ resource_id=str(resource.id),
product_id="posthog",
name=team.name,
secrets=VercelIntegration._build_secrets(team),
diff --git a/ee/api/vercel/test/test_vercel_connect.py b/ee/api/vercel/test/test_vercel_connect.py
index 0032b48997c4..afceac51e5c9 100644
--- a/ee/api/vercel/test/test_vercel_connect.py
+++ b/ee/api/vercel/test/test_vercel_connect.py
@@ -10,6 +10,7 @@ from django.test import Client, SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.integrations import IntegrationManager
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_integration import OrganizationIntegration
@@ -935,14 +936,8 @@ class TestVercelConnectComplete(VercelConnectTestBase):
def test_rollback_on_integration_create_failure(self):
session_token = self._seed_session()
- original_create = Integration.objects.create
- def failing_create(**kwargs):
- if kwargs.get("kind") == Integration.IntegrationKind.VERCEL:
- raise Exception("db error")
- return original_create(**kwargs)
-
- with patch.object(Integration.objects, "create", side_effect=failing_create):
+ with patch.object(IntegrationManager.vercel.oauth, "create", side_effect=Exception("db error")):
response = self.client.post(
self.url,
{
diff --git a/ee/api/vercel/vercel_connect.py b/ee/api/vercel/vercel_connect.py
index 4fc774b07b15..fcab5d6f4627 100644
--- a/ee/api/vercel/vercel_connect.py
+++ b/ee/api/vercel/vercel_connect.py
@@ -18,6 +18,7 @@ from rest_framework.response import Response
from posthog.exceptions_capture import capture_exception
from posthog.helpers.oauth_pending_connection import shared_cookie_domain
+from posthog.integrations import IntegrationManager, IntegrationRecord
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_integration import OrganizationIntegration
@@ -444,7 +445,7 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):
raise exceptions.ValidationError(f"Project {tid} does not belong to this organization.")
for tid in unique_team_ids:
- if Integration.objects.filter(team_id=tid, kind=Integration.IntegrationKind.VERCEL).exists():
+ if IntegrationManager.vercel.oauth.exists(tid):
raise exceptions.ValidationError(f"Project '{teams_by_id[tid].name}' already has a Vercel integration.")
production_team = teams_by_id[production_team_id]
@@ -478,14 +479,13 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):
created_by=user,
)
- resources: dict[int, Integration] = {}
+ resources: dict[int, IntegrationRecord] = {}
for tid, team in teams_by_id.items():
- resources[tid] = Integration.objects.create(
- team=team,
- kind=Integration.IntegrationKind.VERCEL,
- integration_id=str(team.pk),
+ resources[tid] = IntegrationManager.vercel.oauth.create(
+ team.pk,
+ external_id=str(team.pk),
config={"type": "connectable"},
- created_by=user,
+ created_by_id=user.pk,
)
from ee.vercel.integration import VercelIntegration
@@ -496,13 +496,13 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):
client = VercelAPIClient(bearer_token=cached_data["access_token"])
import_result = client.import_resource(
integration_config_id=installation_id,
- resource_id=str(production_resource.pk),
+ resource_id=str(production_resource.id),
product_id="posthog",
name=production_team.name,
secrets=env_secrets,
)
if not import_result.success:
- resource_id = str(production_resource.pk)
+ resource_id = str(production_resource.id)
logger.error(
"Failed to import resource to Vercel",
error=import_result.error,
@@ -515,7 +515,7 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):
with transaction.atomic():
org_integration.delete()
for resource in resources.values():
- resource.delete()
+ IntegrationManager.vercel.oauth.delete(resource.team_id, resource.id, ignore_usages=True)
capture_exception(
VercelImportError("Vercel did not accept the resource import"),
{
diff --git a/ee/tasks/slack.py b/ee/tasks/slack.py
index 1a4c7e3e3c3c..5843c9837f87 100644
--- a/ee/tasks/slack.py
+++ b/ee/tasks/slack.py
@@ -4,7 +4,8 @@ from urllib.parse import urlparse
import structlog
-from posthog.models.integration import Integration, SlackIntegration
+from posthog.integrations import IntegrationManager
+from posthog.models.integration import SlackIntegration
from posthog.models.sharing_configuration import SharingConfiguration
from products.subscriptions.backend.facade.api import render_shared_insight_image
@@ -45,13 +46,19 @@ def _handle_slack_event(event_payload: Any) -> None:
team_id = sharing_config.team_id
# Now we try and get the SlackIntegration for the specificed PostHog team and Slack Team
- try:
- integration = Integration.objects.get(kind="slack", team=team_id, config__team__id=slack_team_id)
- slack_integration = SlackIntegration(integration)
-
- except Integration.DoesNotExist:
+ # `where` compares top-level config keys only, so match the nested Slack team id here.
+ integration = next(
+ (
+ row
+ for row in IntegrationManager.slack.oauth.list(team_id)
+ if ((row.config or {}).get("team") or {}).get("id") == slack_team_id
+ ),
+ None,
+ )
+ if integration is None:
logger.info("No SlackIntegration found for this team")
continue
+ slack_integration = SlackIntegration(integration)
# With both the integration and the resource we are good to go!!
diff --git a/ee/tasks/test/test_slack.py b/ee/tasks/test/test_slack.py
index 8970e053d2a5..eb92f8996682 100644
--- a/ee/tasks/test/test_slack.py
+++ b/ee/tasks/test/test_slack.py
@@ -2,6 +2,8 @@ import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
+
from posthog import settings
from posthog.models.integration import Integration
from posthog.models.sharing_configuration import SharingConfiguration
@@ -94,3 +96,30 @@ class TestSlackSubscriptionsTasks(APIBaseTest):
"channel": "",
"ts": "",
}
+
+ @parameterized.expand([("second_workspace_of_the_team", "T99999", True), ("unknown_workspace", "T00000", False)])
+ def test_unfurl_uses_the_integration_of_the_event_workspace(
+ self,
+ MockSlackIntegration: MagicMock,
+ mock_render_shared_insight_image: MagicMock,
+ _name: str,
+ slack_team_id: str,
+ expect_unfurl: bool,
+ ) -> None:
+ second_workspace = Integration.objects.create(
+ team=self.team, kind="slack", integration_id="T99999", config={"team": {"id": "T99999"}}
+ )
+ mock_render_shared_insight_image.return_value = SharedInsightImage(
+ title="My Test subscription", image_url="https://example.com/insight.png", alt_text="My Test subscription"
+ )
+
+ handle_slack_event(
+ create_mock_unfurl_event(slack_team_id, [f"{settings.SITE_URL}/shared/{self.sharingconfig.access_token}"])
+ )
+
+ if expect_unfurl:
+ MockSlackIntegration.assert_called_once()
+ assert MockSlackIntegration.call_args.args[0].pk == second_workspace.pk
+ MockSlackIntegration.return_value.client.chat_unfurl.assert_called_once()
+ else:
+ MockSlackIntegration.assert_not_called()
diff --git a/ee/vercel/integration.py b/ee/vercel/integration.py
index 09bde727fafa..0db984aee87c 100644
--- a/ee/vercel/integration.py
+++ b/ee/vercel/integration.py
@@ -25,6 +25,7 @@ from posthog.event_usage import report_user_signed_up
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import EmailLookupHandler
from posthog.helpers.two_factor_session import has_passkeys
+from posthog.integrations import IntegrationConflict, IntegrationManager, IntegrationRecord
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -142,6 +143,24 @@ class SSOExperimentationConfig:
url_template: str
+def get_or_create_connectable_resource(team: Team) -> tuple[IntegrationRecord, bool]:
+ """The team's Vercel resource, created as a connectable resource when the team has none."""
+ resources = IntegrationManager.vercel.oauth
+ existing = resources.find(team.pk, external_id=str(team.pk))
+ if existing is not None:
+ return existing, False
+ try:
+ created = resources.create(team.pk, external_id=str(team.pk), config={"type": "connectable"})
+ return created, True
+ except IntegrationConflict:
+ # A concurrent request created the row between the read and the insert. The SDK creates in a
+ # savepoint, so the caller's transaction stays usable for the second read.
+ existing = resources.find(team.pk, external_id=str(team.pk))
+ if existing is None:
+ raise
+ return existing, False
+
+
class VercelIntegration:
SSO_PATH_REDIRECT_MAP = {
"billing": "/organization/billing/overview",
@@ -568,28 +587,27 @@ class VercelIntegration:
user=installation.created_by,
)
- resource = Integration.objects.create(
- team=team,
- kind=Integration.IntegrationKind.VERCEL,
- integration_id=str(team.pk),
+ resource = IntegrationManager.vercel.oauth.create(
+ team.pk,
+ external_id=str(team.pk),
config=asdict(config),
- created_by=installation.created_by,
+ created_by_id=installation.created_by_id,
)
logger.info(
"Successfully created Vercel resource",
installation_id=installation_id,
- resource_id=resource.pk,
+ resource_id=resource.id,
team_id=team.pk,
integration="vercel",
)
- return VercelIntegration._build_resource_response(resource, installation)
+ return VercelIntegration._build_resource_response(resource, team, installation)
@staticmethod
def get_resource(resource_id: str) -> dict[str, Any]:
resource, installation = VercelIntegration._get_resource_with_installation(resource_id)
- return VercelIntegration._build_resource_response(resource, installation)
+ return VercelIntegration._build_resource_response(resource, resource.team, installation)
@staticmethod
def update_resource(resource_id: str, resource_data: dict[str, Any]) -> dict[str, Any]:
@@ -604,7 +622,7 @@ class VercelIntegration:
resource.save(update_fields=["config"])
logger.info("Successfully updated Vercel resource", resource_id=resource_id, integration="vercel")
- return VercelIntegration._build_resource_response(resource, installation)
+ return VercelIntegration._build_resource_response(resource, resource.team, installation)
@staticmethod
def delete_resource(resource_id: str) -> None:
@@ -614,18 +632,20 @@ class VercelIntegration:
logger.info("Successfully deleted Vercel resource", resource_id=resource_id, integration="vercel")
@staticmethod
- def _build_resource_response(resource: Integration, installation: OrganizationIntegration) -> dict[str, Any]:
+ def _build_resource_response(
+ resource: IntegrationRecord, team: Team, installation: OrganizationIntegration
+ ) -> dict[str, Any]:
billing_plans = VercelIntegration.get_vercel_plans()
current_plan_id = installation.config.get("billing_plan_id", "posthog-usage-based")
current_plan = next((plan for plan in billing_plans if plan["id"] == current_plan_id), None)
return {
- "id": str(resource.pk),
+ "id": str(resource.id),
"productId": resource.config.get("productId", ""),
- "name": resource.config.get("name", resource.team.name),
+ "name": resource.config.get("name", team.name),
"metadata": resource.config.get("metadata", {}),
"status": "ready",
- "secrets": VercelIntegration._build_secrets(resource.team),
+ "secrets": VercelIntegration._build_secrets(team),
"billingPlan": current_plan,
}
@@ -642,11 +662,8 @@ class VercelIntegration:
]
@staticmethod
- def _get_vercel_resource_for_team(team: Team) -> Integration | None:
- try:
- return Integration.objects.get(team=team, kind=Integration.IntegrationKind.VERCEL)
- except Integration.DoesNotExist:
- return None
+ def _get_vercel_resource_for_team(team: Team) -> IntegrationRecord | None:
+ return IntegrationManager.vercel.oauth.find(team.pk)
@staticmethod
def _get_installation_for_organization(organization: Organization) -> OrganizationIntegration | None:
@@ -727,7 +744,7 @@ class VercelIntegration:
)
return None
- resource_id = str(resource.pk)
+ resource_id = str(resource.id)
logger.debug(
"Successfully set up Vercel client",
@@ -1432,12 +1449,7 @@ def _safe_vercel_sync(
if not installation:
return
try:
- resource, created = Integration.objects.get_or_create(
- team=team,
- kind=Integration.IntegrationKind.VERCEL,
- integration_id=str(team.pk),
- defaults={"config": {"type": "connectable"}},
- )
+ resource, created = get_or_create_connectable_resource(team)
if created:
logger.info(
"Auto-created Vercel resource for connectable installation",
@@ -1449,7 +1461,7 @@ def _safe_vercel_sync(
client = VercelAPIClient(bearer_token=access_token)
client.import_resource(
integration_config_id=installation.integration_id,
- resource_id=str(resource.pk),
+ resource_id=str(resource.id),
product_id="posthog",
name=team.name,
secrets=VercelIntegration._build_secrets(team),
diff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.py
index 250143ad5a01..a0f62d90814e 100644
--- a/ee/vercel/test/test_integration.py
+++ b/ee/vercel/test/test_integration.py
@@ -7,7 +7,7 @@ from unittest.mock import Mock, patch
from django.contrib.auth import SESSION_KEY
from django.contrib.sessions.middleware import SessionMiddleware
-from django.db import IntegrityError
+from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.test import RequestFactory, TestCase, override_settings
from django.utils import timezone
@@ -17,6 +17,7 @@ from parameterized import parameterized
from rest_framework import exceptions
from rest_framework.exceptions import NotFound, ValidationError
+from posthog.integrations import IntegrationConflict, IntegrationReader
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -30,7 +31,13 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from ee.api.vercel.types import VercelUserClaims
-from ee.vercel.integration import RequiresExistingUserLogin, SSOParams, VercelIntegration, _safe_vercel_sync
+from ee.vercel.integration import (
+ RequiresExistingUserLogin,
+ SSOParams,
+ VercelIntegration,
+ _safe_vercel_sync,
+ get_or_create_connectable_resource,
+)
# Hardcoded independently of ee.vercel.integration.CLIENT_ENV_PREFIXES so a dropped prefix fails these tests.
EXPECTED_PREFIXES = ["NEXT_PUBLIC_", "VITE_", "NUXT_PUBLIC_", "PUBLIC_"]
@@ -1595,3 +1602,51 @@ class TestPushSecretsToVercel(TestCase):
VercelIntegration.push_secrets_to_vercel(self.team)
mock_capture.assert_called_once()
+
+
+class TestGetOrCreateConnectableResource(TestCase):
+ def setUp(self):
+ self.organization = Organization.objects.create(name="Connectable Org")
+ self.team = Team.objects.create(organization=self.organization, name="Connectable Team")
+
+ def _vercel_row(self, config: dict[str, Any]) -> Integration:
+ return Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.VERCEL, integration_id=str(self.team.pk), config=config
+ )
+
+ def test_creates_a_connectable_resource_when_the_team_has_none(self):
+ resource, created = get_or_create_connectable_resource(self.team)
+
+ assert created
+ assert (resource.team_id, resource.integration_id, resource.config) == (
+ self.team.pk,
+ str(self.team.pk),
+ {"type": "connectable"},
+ )
+
+ @parameterized.expand([("found_on_first_read", False), ("created_by_a_concurrent_request", True)])
+ def test_returns_the_existing_resource(self, _name: str, hidden_from_first_read: bool):
+ existing = self._vercel_row({"type": "connectable"})
+ real_find = IntegrationReader.find
+ calls = 0
+
+ def find(reader, *args, **kwargs):
+ nonlocal calls
+ calls += 1
+ # A concurrent request inserts the row after this request's first read.
+ if hidden_from_first_read and calls == 1:
+ return None
+ return real_find(reader, *args, **kwargs)
+
+ with transaction.atomic(), patch.object(IntegrationReader, "find", autospec=True, side_effect=find):
+ resource, created = get_or_create_connectable_resource(self.team)
+ # The failed insert must leave the caller's transaction usable.
+ assert Integration.objects.filter(pk=existing.pk).exists()
+
+ assert (resource.id, created) == (existing.id, False)
+
+ def test_a_conflicting_row_outside_the_accessor_scope_raises(self):
+ self._vercel_row({"type": "connectable", "warehouse_source_type": "Vercel"})
+
+ with pytest.raises(IntegrationConflict):
+ get_or_create_connectable_resource(self.team)
diff --git a/posthog/api/comments.py b/posthog/api/comments.py
index 93d2f7bfbd1d..f8f02114ee39 100644
--- a/posthog/api/comments.py
+++ b/posthog/api/comments.py
@@ -26,6 +26,7 @@ from posthog.comment.access import task_comment_target_is_accessible
from posthog.event_usage import groups
from posthog.exceptions import Conflict
from posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_user
+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.activity_logging.model_activity import get_was_impersonated
@@ -46,7 +47,7 @@ from posthog.models.comment.utils import (
produce_discussion_mention_events,
send_mention_notifications,
)
-from posthog.models.integration import Integration, SlackIntegration
+from posthog.models.integration import SlackIntegration
from posthog.oauth_provenance import get_oauth_access_token, is_sandbox_oauth_request
from posthog.permissions import is_scout_sandbox_request
from posthog.tasks.comment_slack_sync import backfill_comment_slack_thread
@@ -1191,7 +1192,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
serializer = CommentSerializer(comment, context=self.get_serializer_context())
return Response(serializer.data)
- def _resolve_slack_channel_name(self, integration: Integration, channel_id: str, user: User) -> str:
+ def _resolve_slack_channel_name(self, integration: IntegrationRecord, channel_id: str, user: User) -> str:
"""Resolve the target channel server-side — the caller-supplied id is never paired with a
caller-supplied label. Private channels are restricted to the workspace connector (matching
the channel picker, which hides them from everyone else) and their names are never persisted,
@@ -1247,8 +1248,9 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
integration_id = params.validated_data["integration_id"]
channel_id = params.validated_data["channel_id"]
- integration = Integration.objects.filter(team=team, id=integration_id, kind="slack").first()
- if integration is None:
+ try:
+ integration = IntegrationManager.slack.oauth.get(team.id, integration_id)
+ except IntegrationNotFound:
raise exceptions.ValidationError("Slack integration not found")
channel_name = self._resolve_slack_channel_name(integration, channel_id, cast(User, request.user))
@@ -1262,7 +1264,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
defaults={
"scope": comment.scope,
"item_id": comment.item_id,
- "integration": integration,
+ "integration_id": integration.id,
"slack_channel_id": channel_id,
"slack_channel_name": channel_name,
"slack_team_id": integration.integration_id,
@@ -1284,7 +1286,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
# A reservation this old with no root message is a crashed send that would otherwise
# block the discussion forever. Adopt it and retry the post; resetting created_at
# re-bounds the reply backfill to this attempt.
- slack_thread.integration = integration
+ slack_thread.integration_id = integration.id
slack_thread.slack_channel_id = channel_id
slack_thread.slack_channel_name = channel_name
slack_thread.slack_team_id = integration.integration_id
diff --git a/posthog/api/github_callback/installation_events.py b/posthog/api/github_callback/installation_events.py
index 38bd50d65aa9..604e9c63f59d 100644
--- a/posthog/api/github_callback/installation_events.py
+++ b/posthog/api/github_callback/installation_events.py
@@ -20,12 +20,14 @@ row for the installation mirrors so the UI can say "all repositories" instead of
from typing import Any
+from django.db import transaction
from django.http import HttpResponse
from django.utils import timezone
import structlog
-from posthog.models.integration import Integration, invalidate_github_repository_caches_for_installation
+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationPatch
+from posthog.models.integration import invalidate_github_repository_caches_for_installation
from posthog.models.integration.github_audit import GitHubAudit
from posthog.models.user_integration import GitHubInstallRequest, UserIntegration
@@ -54,21 +56,29 @@ def handle_installation_event(payload: dict) -> HttpResponse:
installation_id = str(installation_id)
- integrations = list(Integration.objects.filter(kind="github", integration_id=installation_id))
+ github = IntegrationManager.github.oauth
+ integrations = github.list_by_external_id(installation_id)
project_audits = [GitHubAudit.project(row) for row in integrations]
personal_rows = list(UserIntegration.objects.filter(kind="github", integration_id=installation_id))
personal_audits = [GitHubAudit.personal(row) for row in personal_rows]
+ deleted_audits: list[GitHubAudit] = []
try:
- # nosemgrep: idor-lookup-without-team (a verified installation webhook removes this installation across projects)
- team_deleted, _ = Integration.objects.filter(
- kind="github", integration_id=installation_id, pk__in=[row.pk for row in integrations]
- ).delete()
+ # A verified installation webhook removes this installation across projects. Delete the listed
+ # rows by id, so the audit names exactly the rows that this request deleted, and all or none.
+ with transaction.atomic():
+ for row, audit in zip(integrations, project_audits):
+ try:
+ github.delete(row.team_id, row.id, ignore_usages=True)
+ except IntegrationNotFound:
+ continue
+ deleted_audits.append(audit)
except Exception as exc:
for audit in project_audits:
audit.record("webhook_cleanup_failed", stage="project_deletion", failure_type=type(exc).__name__)
raise
- for audit in project_audits:
+ team_deleted = len(deleted_audits)
+ for audit in deleted_audits:
audit.record("deleted", after_commit=True, customer_visible=True, outcome="disconnected")
audit.record("webhook_cleanup", after_commit=True, outcome="already_absent", completed_deletion=True)
try:
@@ -141,29 +151,22 @@ def handle_installation_repositories_event(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
installation_id = str(installation_id)
- # Load only the columns we touch. The unbounded repository_cache blob and the encrypted
- # sensitive_config (decrypted eagerly on load) are skipped so a widely shared installation
- # can't spike a web worker's memory here. Writes go out as one bulk_update per model instead
- # of a save per row — which also skips the (no-op for github) push-config post_save signal,
- # avoiding a per-row lazy load of the deferred `kind`.
- team_changed = [
- row
- for row in Integration.objects.filter(kind="github", integration_id=installation_id).only("id", "config")
- if row.config.get("repository_selection") != repository_selection
- ]
+ team_updated = IntegrationManager.github.oauth.update_by_external_id(
+ installation_id, IntegrationPatch(config_patch={"repository_selection": repository_selection})
+ )
+ # For the personal rows, load only the columns we touch. The encrypted sensitive_config
+ # (decrypted eagerly on load) is skipped so a widely shared installation can't spike a web
+ # worker's memory here. Like the SDK call above, the write is one bulk_update of the changed rows.
user_changed = [
row
for row in UserIntegration.objects.filter(kind="github", integration_id=installation_id).only("id", "config")
if row.config.get("repository_selection") != repository_selection
]
- changed: list[Integration | UserIntegration] = [*team_changed, *user_changed]
- for row in changed:
+ for row in user_changed:
row.config = {**row.config, "repository_selection": repository_selection}
- if team_changed:
- Integration.objects.bulk_update(team_changed, ["config"])
if user_changed:
UserIntegration.objects.bulk_update(user_changed, ["config"])
- updated = len(changed)
+ updated = team_updated + len(user_changed)
invalidate_github_repository_caches_for_installation(installation_id)
diff --git a/posthog/api/github_callback/personal_finish.py b/posthog/api/github_callback/personal_finish.py
index 1e24516f7f2c..b952d8da9787 100644
--- a/posthog/api/github_callback/personal_finish.py
+++ b/posthog/api/github_callback/personal_finish.py
@@ -21,8 +21,9 @@ from posthog.api.github_callback.types import (
)
from posthog.egress.github.transport import github_request
from posthog.egress.limiter.policies import Priority
+from posthog.integrations import IntegrationManager, IntegrationRecord
from posthog.models import User
-from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integration
+from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration
from posthog.models.user_integration import (
UserIntegration,
refresh_user_github_installation_access,
@@ -96,9 +97,9 @@ def finish_personal(request: HttpRequest) -> FinishResult:
installation_id = authorize_state.installation_id
if not installation_id:
return _error("missing_params")
- if not Integration.objects.filter(
- kind="github", integration_id=installation_id, team__in=user.teams.all()
- ).exists():
+ if not IntegrationManager.github.oauth.exists(
+ team_ids=user.teams.values_list("id", flat=True), external_id=str(installation_id)
+ ):
return _error("invalid_installation")
installation_ids = [installation_id]
case FlowKind.TEAM_OAUTH:
@@ -211,7 +212,7 @@ def finish_personal(request: HttpRequest) -> FinishResult:
if flow.creates_team_integration and authorize_state.team_id is not None:
installation_id = str(installation_ids[0])
try:
- team_integration = GitHubIntegration.integration_from_installation_id(
+ team_integration: IntegrationRecord = GitHubIntegration.integration_from_installation_id(
installation_id, authorize_state.team_id, user
)
except (GitHubInstallationAccessFetchError, requests.RequestException):
@@ -223,8 +224,11 @@ def finish_personal(request: HttpRequest) -> FinishResult:
)
return _error("integration_create_failed")
- team_integration.config["connecting_user_github_login"] = authorization.gh_login
- team_integration.save(update_fields=["config"])
+ team_integration = IntegrationManager.github.oauth.update(
+ team_integration.team_id,
+ team_integration.id,
+ config_patch={"connecting_user_github_login": authorization.gh_login},
+ )
return FinishResult(
redirect_kind="team_oauth_success",
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
index 16bd3e93c6da..a8b95adcbeb1 100644
--- a/posthog/api/github_callback/team_services.py
+++ b/posthog/api/github_callback/team_services.py
@@ -36,6 +36,7 @@ from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubEgressBudgetExhausted
from posthog.egress.limiter.policies import Priority
from posthog.event_usage import report_user_action
+from posthog.integrations import IntegrationManager, IntegrationRecord
from posthog.models import Team
from posthog.models.integration import (
GitHubInstallationAccess,
@@ -65,7 +66,7 @@ PERSONAL_GITHUB_REQUIRED_MESSAGE = (
class TeamGitHubFinishSetupResult:
next_url: str
installation_id: str
- integration: Integration | None = None
+ integration: IntegrationRecord | None = None
oauth_url: str | None = None
@@ -265,7 +266,7 @@ def finish_team_github_setup_update(
team_id: int,
request: Request,
installation_id: str,
- existing: Integration,
+ existing: IntegrationRecord,
state_raw: str | None,
fallback_next_url: str | None,
) -> TeamGitHubFinishSetupResult:
@@ -310,14 +311,8 @@ def execute_team_github_finish_setup(
if is_already_installed:
try:
organization = team.organization
- existing_install = (
- Integration.objects.filter(
- team__organization_id=organization.id,
- kind="github",
- )
- .for_github_installation_id(installation_id_str)
- .order_by("id")
- .first()
+ existing_install = IntegrationManager.github.oauth.find(
+ team_ids=organization.teams.values_list("id", flat=True), external_id=installation_id_str
)
if existing_install is None:
raise ValidationError(
@@ -333,12 +328,15 @@ def execute_team_github_finish_setup(
user=user, team=team, source_installation_id=str(source_installation_id)
)
- integration = GitHubIntegration.integration_from_installation_id(str(source_installation_id), team.id, user)
+ integration: IntegrationRecord = GitHubIntegration.integration_from_installation_id(
+ str(source_installation_id), team.id, user
+ )
source_login = (existing_install.config or {}).get("connecting_user_github_login")
if source_login and not (integration.config or {}).get("connecting_user_github_login"):
- integration.config["connecting_user_github_login"] = source_login
- integration.save(update_fields=["config"])
+ integration = IntegrationManager.github.oauth.update(
+ integration.team_id, integration.id, config_patch={"connecting_user_github_login": source_login}
+ )
except ValidationError as exc:
error_code = _validation_error_code(exc)
if error_code not in (
@@ -395,8 +393,8 @@ def refresh_team_github_integration(
team_id: int,
installation_id: str,
*,
- existing: Integration,
-) -> Integration:
+ existing: IntegrationRecord,
+) -> IntegrationRecord:
try:
return GitHubIntegration.integration_from_installation_id(installation_id, team_id, user)
except GitHubInstallationAccessFetchError:
@@ -493,7 +491,7 @@ def link_existing_team_github_integration(
source_team_id: Any | None,
installation_id_param: Any | None,
discovery_id: str | None = None,
-) -> Integration:
+) -> IntegrationRecord:
if installation_id_param and not is_valid_github_installation_id(installation_id_param):
raise ValidationError("Invalid installation_id")
@@ -511,26 +509,14 @@ def link_existing_team_github_integration(
if source_team_id_int not in accessible_team_ids:
raise ValidationError("Source team not found in your organization")
- qs = Integration.objects.filter(team_id=source_team_id_int, kind="github")
- if installation_id_param:
- qs = qs.for_github_installation_id(str(installation_id_param))
-
- source = defer_repository_cache_fields(qs).order_by("id").first()
+ source = IntegrationManager.github.oauth.find(
+ source_team_id_int, external_id=str(installation_id_param) if installation_id_param else None
+ )
if source is None:
raise ValidationError("Source team does not have a GitHub integration")
elif installation_id_param:
installation_id_str = str(installation_id_param)
- existing = (
- defer_repository_cache_fields(
- Integration.objects.filter(
- team__organization_id=organization.id,
- team_id__in=accessible_team_ids,
- kind="github",
- ).for_github_installation_id(installation_id_str)
- )
- .order_by("id")
- .first()
- )
+ existing = IntegrationManager.github.oauth.find(team_ids=accessible_team_ids, external_id=installation_id_str)
if existing is None:
if installation_id_str in _org_linked_github_installation_ids(organization):
# Linked to a team elsewhere in the org that this user can't access — not an orphan,
@@ -594,12 +580,15 @@ def link_existing_team_github_integration(
).record("link_path", path="sibling", source_team_id=source.team_id, discovery_id=discovery_id)
authorize_link_existing_installation(user=user, team=target_team, source_installation_id=str(installation_id))
- instance = GitHubIntegration.integration_from_installation_id(str(installation_id), team_id, user)
+ instance: IntegrationRecord = GitHubIntegration.integration_from_installation_id(
+ str(installation_id), team_id, user
+ )
source_login = (source.config or {}).get("connecting_user_github_login")
if source_login and not (instance.config or {}).get("connecting_user_github_login"):
- instance.config["connecting_user_github_login"] = source_login
- instance.save(update_fields=["config"])
+ instance = IntegrationManager.github.oauth.update(
+ instance.team_id, instance.id, config_patch={"connecting_user_github_login": source_login}
+ )
return instance
@@ -798,9 +787,11 @@ def finish_team_setup(http_request) -> FinishResult:
installation_id_str = str(installation_id)
if setup_action == "update" and team_id is None and is_valid_github_installation_id(installation_id):
- existing_for_user = Integration.objects.first_github_for_user_installation(user, installation_id_str)
- if existing_for_user is not None:
- team_id = existing_for_user.team_id
+ user_install = IntegrationManager.github.oauth.find(
+ team_ids=user.teams.values_list("id", flat=True), external_id=installation_id_str
+ )
+ if user_install is not None:
+ team_id = user_install.team_id
if team_id is None:
return FinishResult(
@@ -821,7 +812,7 @@ def finish_team_setup(http_request) -> FinishResult:
# already exists — only create the team's first link for this installation. State-token
# validation downstream still guards against forged callbacks regardless of membership level.
existing_team_integration = (
- Integration.objects.first_github_for_team_installation(team.id, installation_id_str)
+ IntegrationManager.github.oauth.find(team.id, external_id=installation_id_str)
if is_valid_github_installation_id(installation_id_str)
else None
)
@@ -851,7 +842,7 @@ def finish_team_setup(http_request) -> FinishResult:
error="invalid_installation_id",
)
- existing = Integration.objects.first_github_for_team_installation(team.id, installation_id_str)
+ existing = IntegrationManager.github.oauth.find(team.id, external_id=installation_id_str)
if existing is not None:
update_result = finish_team_github_setup_update(
user=user,
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 3017847779c0..a84e8a925b9c 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -71,6 +71,7 @@ from posthog.egress.limiter.policies import Priority
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.fuzzy_search import fuzzy_filter
+from posthog.integrations import IntegrationNotFound, IntegrationRecord
from posthog.models import OrganizationMembership, User
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import (
@@ -2579,7 +2580,7 @@ class IntegrationViewSet(
"link_completed",
discovery_id=discovery_id,
installation_id=instance.integration_id,
- linked_integration_id=instance.pk,
+ linked_integration_id=instance.id,
after_commit=True,
)
return Response(self.get_serializer(instance).data)
@@ -2773,7 +2774,7 @@ class IntegrationViewSet(
integration = self.get_object()
if not push_channel_app_id(integration):
raise ValidationError("Device tokens can only be imported into an APNs or Firebase push channel.")
- result = import_push_tokens(integration, request.validated_data["subscriptions"])
+ result = import_push_tokens(integration, request.validated_data["subscriptions"], integration.team.api_token)
return Response(
PushTokenImportResponseSerializer(
{"imported": result.imported, "failed_distinct_ids": result.failed_distinct_ids}
@@ -2836,7 +2837,7 @@ class IntegrationViewSet(
raise EmailProviderUnavailable() from error
return Response(EmailDomainStatusSerializer(report).data)
- def _report_email_domain_verified(self, request: Request, instance: Integration) -> None:
+ def _report_email_domain_verified(self, request: Request, instance: IntegrationRecord) -> None:
report_user_action(
request.user,
"email domain verified",
@@ -2848,7 +2849,7 @@ class IntegrationViewSet(
)
@staticmethod
- def _email_domain_setup_method(request: Request, instance: Integration) -> str:
+ def _email_domain_setup_method(request: Request, instance: IntegrationRecord) -> str:
if isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication | OAuthAccessTokenAuthentication):
return "agent"
return instance.config.get("setup_method", "manual")
@@ -2925,6 +2926,8 @@ class IntegrationViewSet(
self.team_id,
on_domain_verified=lambda instance: self._report_email_domain_verified(request, instance),
)
+ except IntegrationNotFound:
+ raise NotFound("Email integration not found.")
except ValueError as e:
capture_exception(e, {"integration_id": integration_id, "team_id": self.team_id, "context": context})
raise ValidationError(
diff --git a/posthog/api/integration_push_tokens.py b/posthog/api/integration_push_tokens.py
index 82c75e1c8d99..0be13bf69d7d 100644
--- a/posthog/api/integration_push_tokens.py
+++ b/posthog/api/integration_push_tokens.py
@@ -6,7 +6,7 @@ from rest_framework import serializers
from posthog.api.capture import capture_batch_internal
from posthog.dataclasses import frozen
from posthog.helpers.encrypted_fields import EncryptedFieldMixin
-from posthog.models.integration import Integration
+from posthog.integrations import IntegrationRecord
DEVICE_SUBSCRIPTION_PREFIX = "$device_push_subscription_"
MAX_SUBSCRIPTIONS_PER_REQUEST = 1000
@@ -48,7 +48,7 @@ class _TokenCipher(EncryptedFieldMixin):
pass
-def push_channel_app_id(integration: Integration) -> str | None:
+def push_channel_app_id(integration: IntegrationRecord) -> str | None:
if integration.kind == "apns":
return integration.config.get("bundle_id") or None
if integration.kind == "firebase":
@@ -62,7 +62,9 @@ def device_subscription_key(app_id: str, device_token: str) -> str:
return f"{DEVICE_SUBSCRIPTION_PREFIX}{app_id}:{digest}"
-def import_push_tokens(integration: Integration, subscriptions: list[dict[str, str]]) -> PushTokenImportResult:
+def import_push_tokens(
+ integration: IntegrationRecord, subscriptions: list[dict[str, str]], team_api_token: str
+) -> PushTokenImportResult:
app_id = push_channel_app_id(integration)
if not app_id:
raise ValueError("This integration is not a push channel.")
@@ -91,7 +93,7 @@ def import_push_tokens(integration: Integration, subscriptions: list[dict[str, s
result = capture_batch_internal(
events=events,
- token=integration.team.api_token,
+ token=team_api_token,
event_source=EVENT_SOURCE,
process_person_profile=True,
)
diff --git a/posthog/api/organization_integration.py b/posthog/api/organization_integration.py
index eb86860e3f8d..e974ab32a15e 100644
--- a/posthog/api/organization_integration.py
+++ b/posthog/api/organization_integration.py
@@ -11,6 +11,7 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.exceptions_capture import capture_exception
+from posthog.integrations import IntegrationRecord
from posthog.models.integration import Integration
from posthog.models.organization_integration import OrganizationIntegration
from posthog.permissions import OrganizationAdminWritePermissions
@@ -159,20 +160,14 @@ class OrganizationIntegrationViewSet(
if not Team.objects.filter(pk=tid, organization=org).exists():
return Response({"detail": f"Project {tid} does not belong to this organization."}, status=400)
- from posthog.models.integration import Integration as TeamIntegration
-
from ee.vercel.client import VercelAPIClient
+ from ee.vercel.integration import get_or_create_connectable_resource
teams_by_id: dict[int, Team] = {}
- resources: dict[int, TeamIntegration] = {}
+ resources: dict[int, IntegrationRecord] = {}
for tid in {production_id, preview_id, development_id}:
teams_by_id[tid] = Team.objects.get(pk=tid, organization=org)
- resources[tid], _ = TeamIntegration.objects.get_or_create(
- team=teams_by_id[tid],
- kind=TeamIntegration.IntegrationKind.VERCEL,
- integration_id=str(tid),
- defaults={"config": {"type": "connectable"}},
- )
+ resources[tid], _ = get_or_create_connectable_resource(teams_by_id[tid])
integration.config["environment_mapping"] = {
"production": production_id,
@@ -196,7 +191,7 @@ class OrganizationIntegrationViewSet(
client = VercelAPIClient(bearer_token=access_token)
client.import_resource(
integration_config_id=integration.integration_id,
- resource_id=str(production_resource.pk),
+ resource_id=str(production_resource.id),
product_id="posthog",
name=production_team.name,
secrets=secrets,
diff --git a/posthog/api/posthog_connection.py b/posthog/api/posthog_connection.py
index dfd7088348c6..ab8de00a905d 100644
--- a/posthog/api/posthog_connection.py
+++ b/posthog/api/posthog_connection.py
@@ -39,7 +39,8 @@ from posthog.auth import (
is_mcp_request,
)
from posthog.clickhouse.query_tagging import tag_queries
-from posthog.models.integration import POSTHOG_CONNECT_KIND, Integration, OauthIntegration, posthog_connect_base_url
+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord
+from posthog.models.integration import posthog_connect_base_url
from posthog.oauth_provenance import SANDBOX_ORIGIN_HEADER, is_sandbox_origin_request
from posthog.permissions import get_authenticator_scopes
from posthog.rate_limit import PostHogConnectionForwardThrottle
@@ -82,18 +83,15 @@ class ForwardResult:
gateway_error: bool = False
-def _connection_access_token(integration: Integration) -> str:
- oauth = OauthIntegration(integration)
- if oauth.access_token_expired():
- oauth.refresh_access_token()
- integration.refresh_from_db()
- token = integration.sensitive_config.get("access_token")
+def _connection_access_token(integration: IntegrationRecord) -> str:
+ refreshed = IntegrationManager.posthog.oauth.refresh_access_token(integration.team_id, integration.id)
+ token = refreshed.sensitive_config.get("access_token")
if not token:
raise ValidationError("This PostHog connection has no usable access token — reconnect it.")
return token
-def _enforce_caller_covers_connection_scopes(request: Request, integration: Integration) -> None:
+def _enforce_caller_covers_connection_scopes(request: Request, integration: IntegrationRecord) -> None:
"""A connection acts with the creator's stored grant, which may be broader than the API key making
this call. Require that key to itself carry the scopes the connection was granted, so a narrowly
scoped (or leaked) key can't wield the connection to exceed its own authority. Session auth and
@@ -154,7 +152,7 @@ def _inflight_slot(integration_id: int) -> Iterator[bool]:
def _forward_through_connection(
- integration: Integration,
+ integration: IntegrationRecord,
method: str,
path: str,
*,
@@ -297,7 +295,7 @@ class PostHogConnectionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return [PostHogConnectionForwardThrottle(), *super().get_throttles()]
return super().get_throttles()
- def _authorized_connection(self, request: Request, pk: str | None) -> Integration:
+ def _authorized_connection(self, request: Request, pk: str | None) -> IntegrationRecord:
# Refuse to forward a request that itself arrived through a connection, so a same-region (or
# cross-region) connection can't be chained into itself and tie up workers one hop at a time.
if request.headers.get(CONNECTION_MARKER_HEADER):
@@ -306,12 +304,12 @@ class PostHogConnectionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
_enforce_caller_covers_connection_scopes(request, integration)
return integration
- def _get_connection(self, pk: str | None) -> Integration:
+ def _get_connection(self, pk: str | None) -> IntegrationRecord:
if pk is None:
raise NotFound("No PostHog connection with that id in this project.")
try:
- integration = Integration.objects.get(team_id=self.team_id, id=pk, kind=POSTHOG_CONNECT_KIND)
- except (Integration.DoesNotExist, ValueError, ValidationError):
+ integration = IntegrationManager.posthog.oauth.get(self.team_id, int(pk))
+ except (IntegrationNotFound, ValueError):
raise NotFound("No PostHog connection with that id in this project.")
# A connection acts as the user who consented to it. Restrict use to that user so a broad,
# any-scope grant can't become a team-wide confused deputy in the target project.
diff --git a/posthog/api/team/team_config.py b/posthog/api/team/team_config.py
index eb0b9bd87fcb..757bc8eeae60 100644
--- a/posthog/api/team/team_config.py
+++ b/posthog/api/team/team_config.py
@@ -5,9 +5,9 @@ from typing import Any
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
+from posthog.integrations import IntegrationManager, IntegrationNotFound
from posthog.models import Team, TeamRevenueAnalyticsConfig
from posthog.models.filters.utils import validate_group_type_index
-from posthog.models.integration.model import Integration
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
from products.customer_analytics.backend.facade.account_property_pins import (
@@ -420,11 +420,12 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
def validate_default_email_integration_id(self, value: int | None) -> int | None:
if self.parent or value is None:
return value
- sender = (
- Integration.objects.filter(team_id=self.instance.team_id, kind="email", id=value).only("config").first()
- if self.instance is not None
- else None
- )
+ sender = None
+ if self.instance is not None:
+ try:
+ sender = IntegrationManager.email.credentials.get(self.instance.team_id, value)
+ except IntegrationNotFound:
+ pass
if sender is None:
raise serializers.ValidationError("Choose an email sender from this project.")
if not sender.config.get("verified"):
diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.py
index 0316ab0c27c3..e6e9789b6722 100644
--- a/posthog/api/test/test_github_installation_webhook.py
+++ b/posthog/api/test/test_github_installation_webhook.py
@@ -10,6 +10,7 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework.test import APIClient
+from posthog.integrations import IntegrationReader
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration, Integration
@@ -166,6 +167,38 @@ class TestGitHubInstallationWebhook(TestCase):
# Inbound side must never call out to GitHub (loop prevention).
mock_client_request.assert_not_called()
+ @parameterized.expand([("row_added_after_listing",), ("row_removed_after_listing",)])
+ @patch("posthog.credentials_service.instance_settings.get_instance_setting")
+ def test_deleted_audits_exactly_the_rows_it_deleted(self, case, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ listed = self._team_integration("12345")
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ racing = Integration.objects.create(
+ team=other_team, kind="github", integration_id="12345", config={}, sensitive_config={}
+ )
+ real_list = IntegrationReader.list_by_external_id
+
+ def list_then_race(reader, external_id, **kwargs):
+ rows = real_list(reader, external_id, **kwargs)
+ if case == "row_added_after_listing":
+ return [row for row in rows if row.id != racing.pk]
+ Integration.objects.filter(pk=racing.pk).delete()
+ return rows
+
+ with (
+ patch.object(IntegrationReader, "list_by_external_id", autospec=True, side_effect=list_then_race),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ response = self._post({"action": "deleted", "installation": {"id": 12345}})
+
+ self.assertEqual(response.status_code, 202)
+ audited = set(
+ ActivityLog.objects.filter(scope="Integration", activity="deleted").values_list("item_id", flat=True)
+ )
+ self.assertEqual(audited, {str(listed.pk)})
+ self.assertFalse(Integration.objects.filter(pk=listed.pk).exists())
+ self.assertEqual(Integration.objects.filter(pk=racing.pk).exists(), case == "row_added_after_listing")
+
@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
@@ -259,19 +292,31 @@ class TestGitHubInstallationWebhook(TestCase):
row.config = {**row.config, "repository_selection": "selected"}
row.repository_cache_updated_at = timezone.now()
row.save()
-
- response = self._post(
- {
- "action": "added",
- "installation": {"id": 12345},
- "repository_selection": "all",
- "repositories_added": [{"full_name": "posthog/posthog"}],
- "repositories_removed": [],
- },
- event_type="installation_repositories",
+ already_all = Integration.objects.create(
+ team=Team.objects.create(organization=self.organization, name="Other Team"),
+ kind="github",
+ integration_id="12345",
+ config={"repository_selection": "all"},
+ sensitive_config={},
)
+ with patch("posthog.api.github_callback.installation_events.logger") as mock_logger:
+ response = self._post(
+ {
+ "action": "added",
+ "installation": {"id": 12345},
+ "repository_selection": "all",
+ "repositories_added": [{"full_name": "posthog/posthog"}],
+ "repositories_removed": [],
+ },
+ event_type="installation_repositories",
+ )
+
self.assertEqual(response.status_code, 202)
+ mock_logger.info.assert_called_once()
+ self.assertEqual(mock_logger.info.call_args.kwargs["rows_updated"], 2)
+ already_all.refresh_from_db()
+ self.assertEqual(already_all.config["repository_selection"], "all")
team_row.refresh_from_db()
user_row.refresh_from_db()
untouched.refresh_from_db()
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 484434f7c17e..eb698f4c11ed 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -61,6 +61,7 @@ from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentic
from posthog.egress.github.transport import GitHubRateLimitError
from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
+from posthog.integrations import IntegrationManager
from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, GitHubIntegrationError, Integration
from posthog.models.integration.github_audit import GitHubAudit
from posthog.models.user import User
@@ -389,10 +390,9 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
return set()
installation_ids: set[str] = set()
- for ti in Integration.objects.filter(team=team, kind="github").values("integration_id"):
- iid = ti["integration_id"]
- if iid:
- installation_ids.add(str(iid))
+ for ti in IntegrationManager.github.oauth.list(team.id):
+ if ti.integration_id:
+ installation_ids.add(str(ti.integration_id))
return installation_ids
@extend_schema(
@@ -824,10 +824,9 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
# the resolved team (the simple "Link my Slack account" path).
body: Any = request.data if isinstance(request.data, dict) else {}
slack_team_id_hint = body.get("slack_team_id")
- workspace_query = Integration.objects.filter(team=team, kind="slack")
- if slack_team_id_hint:
- workspace_query = workspace_query.filter(integration_id=slack_team_id_hint)
- workspace = workspace_query.first()
+ workspace = IntegrationManager.slack.oauth.find(
+ team.id, external_id=str(slack_team_id_hint) if slack_team_id_hint else None
+ )
if workspace is None:
raise exceptions.ValidationError(
"This project has no Slack workspace connected. Ask an admin to install the Slack app first."
@@ -845,7 +844,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
install_url = build_invite_url(
slack_user_id=None,
- slack_team_id=workspace.integration_id,
+ slack_team_id=workspace.integration_id or "",
posthog_team_id=team.id,
channel=None,
thread_ts=None,
@@ -969,14 +968,8 @@ def _has_unlinked_github_installations(user: User) -> bool | None:
def _team_github_installation_id(team: Any) -> str | None:
if team is None:
return None
- team_row = (
- Integration.objects.filter(team=team, kind="github")
- .exclude(integration_id__isnull=True)
- .exclude(integration_id="")
- .order_by("id")
- .first()
- )
- return str(team_row.integration_id) if team_row is not None and team_row.integration_id else None
+ team_row = next((row for row in IntegrationManager.github.oauth.list(team.id) if row.integration_id), None)
+ return str(team_row.integration_id) if team_row is not None else None
def _attempt_app_oauth_fast_path(
diff --git a/posthog/domain_connect.py b/posthog/domain_connect.py
index 1f04b87ce59f..e253b77e8a6b 100644
--- a/posthog/domain_connect.py
+++ b/posthog/domain_connect.py
@@ -30,7 +30,7 @@ from posthog.schema import DomainConnectProviderName
from posthog.dataclasses import frozen
if TYPE_CHECKING:
- from posthog.models.integration import Integration
+ from posthog.integrations import IntegrationRecord
logger = logging.getLogger(__name__)
@@ -253,18 +253,20 @@ def resolve_email_context(
integration_id: int,
team_id: int,
*,
- on_domain_verified: Callable[["Integration"], None] | None = None,
+ on_domain_verified: Callable[["IntegrationRecord"], None] | None = None,
) -> DomainConnectContext:
"""Resolve Domain Connect parameters for an email integration.
Triggers SES verification to get current tokens, then extracts the
template variables needed for the email-verification template.
+
+ Raises `IntegrationNotFound` before any SES call when the team has no email
+ integration with this id.
"""
- from posthog.models.integration import EmailIntegration, Integration
+ from posthog.integrations import IntegrationManager
+ from posthog.models.integration import EmailIntegration
- instance = Integration.objects.get(id=integration_id, team_id=team_id)
- if instance.kind != "email":
- raise ValueError("Integration must be of kind 'email'")
+ instance = IntegrationManager.email.credentials.get(team_id, integration_id)
email_integration = EmailIntegration(instance)
verification_result = email_integration.verify(
diff --git a/posthog/integrations/model_access_baseline.txt b/posthog/integrations/model_access_baseline.txt
index ea3da4b65320..043ac04f673f 100644
--- a/posthog/integrations/model_access_baseline.txt
+++ b/posthog/integrations/model_access_baseline.txt
@@ -2,23 +2,15 @@
# file has. Rule: .semgrep/rules/devex/integration-model-through-sdk.yaml. The count only goes down:
# after you move a file to the SDK, lower its count or remove its line.
ee/api/integration.py 2
-ee/api/vercel/tasks.py 3
-ee/api/vercel/vercel_connect.py 5
+ee/api/vercel/tasks.py 2
+ee/api/vercel/vercel_connect.py 3
ee/api/vercel/vercel_sso.py 2
ee/management/commands/backfill_vercel_secrets.py 2
-ee/tasks/slack.py 2
-ee/vercel/integration.py 6
-posthog/api/comments.py 2
-posthog/api/github_callback/installation_events.py 5
-posthog/api/github_callback/personal_finish.py 3
-posthog/api/github_callback/team_services.py 11
+ee/vercel/integration.py 3
+posthog/api/github_callback/team_services.py 4
posthog/api/integration.py 7
-posthog/api/integration_push_tokens.py 1
-posthog/api/organization_integration.py 5
-posthog/api/posthog_connection.py 2
-posthog/api/team/team_config.py 2
-posthog/api/user_integration.py 5
-posthog/domain_connect.py 3
+posthog/api/organization_integration.py 3
+posthog/api/user_integration.py 2
posthog/github/attribution.py 1
posthog/github/installations.py 2
posthog/management/commands/flag_legacy_oauth_integrations.py 3
@@ -28,14 +20,11 @@ posthog/models/comment/slack_thread.py 1
posthog/models/integration_repository_cache.py 2
posthog/models/user.py 1
posthog/models/user_integration.py 1
-posthog/ownership/github_files.py 2
posthog/session_recordings/models/session_recording_external_reference.py 2
posthog/session_recordings/session_recording_api.py 1
-posthog/session_recordings/session_recording_external_reference_api.py 2
-posthog/slack/channels.py 1
+posthog/session_recordings/session_recording_external_reference_api.py 1
posthog/tasks/comment_slack_sync.py 3
posthog/tasks/integrations.py 11
-posthog/temporal/ai_observability/eval_reports/delivery.py 2
products/ai_observability/backend/api/evaluation_reports.py 2
products/alerts/backend/presentation/views/alert.py 2
products/alerts_platform/backend/delivery/slack.py 2
@@ -121,7 +110,6 @@ products/slack_app/backend/analytics.py 1
products/slack_app/backend/api.py 28
products/slack_app/backend/discussion_replies.py 1
products/slack_app/backend/facade/api.py 3
-products/slack_app/backend/feature_flags.py 1
products/slack_app/backend/inbox_channel.py 1
products/slack_app/backend/logic/feature_tips/catalog.py 3
products/slack_app/backend/logic/feature_tips/interactivity.py 2
@@ -132,7 +120,6 @@ products/slack_app/backend/logic/thread_join.py 1
products/slack_app/backend/models.py 3
products/slack_app/backend/onboarding.py 2
products/slack_app/backend/services/commands.py 3
-products/slack_app/backend/services/followup_invite.py 1
products/slack_app/backend/services/inbox_interactivity.py 2
products/slack_app/backend/services/integration_resolver.py 6
products/slack_app/backend/services/project_picker.py 1
@@ -140,7 +127,6 @@ products/slack_app/backend/services/slack_app_home.py 6
products/slack_app/backend/services/slack_app_home_stats.py 1
products/slack_app/backend/services/slack_auth.py 1
products/slack_app/backend/services/slack_messages.py 2
-products/slack_app/backend/services/slack_scopes.py 1
products/slack_app/backend/services/slack_settings.py 1
products/slack_app/backend/services/slack_user_info.py 3
products/slack_app/backend/services/slack_welcome_messages.py 1
diff --git a/posthog/models/integration/github_audit.py b/posthog/models/integration/github_audit.py
index 15240595a552..4898c438dc7a 100644
--- a/posthog/models/integration/github_audit.py
+++ b/posthog/models/integration/github_audit.py
@@ -9,9 +9,10 @@ import structlog
from posthog.dataclasses import frozen
from posthog.models.activity_logging.utils import activity_storage
+from posthog.models.team.team import Team
if TYPE_CHECKING:
- from posthog.models.integration import Integration
+ from posthog.integrations import IntegrationRecord
from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
@@ -146,11 +147,11 @@ class GitHubAudit:
personal_metadata: dict[str, Any] | None = None
@classmethod
- def project(cls, integration: Integration, user: User | None = None) -> GitHubAudit:
+ def project(cls, integration: IntegrationRecord, user: User | None = None) -> GitHubAudit:
return cls(
- organization_id=integration.team.organization_id,
+ organization_id=Team.objects.values_list("organization_id", flat=True).get(id=integration.team_id),
team_id=integration.team_id,
- integration_id=str(integration.pk),
+ integration_id=str(integration.id),
installation_id=integration.integration_id,
owner=(integration.config.get("account") or {}).get("name"),
user=user,
diff --git a/posthog/ownership/github_files.py b/posthog/ownership/github_files.py
index e07a4b4beec9..92ec16707c19 100644
--- a/posthog/ownership/github_files.py
+++ b/posthog/ownership/github_files.py
@@ -23,8 +23,9 @@ from posthog.egress.github.transport import GitHubRateLimitError, github_request
from posthog.egress.limiter.policies import Priority
from posthog.egress.observability.observability import scope_fingerprint
from posthog.egress.transport.transport import EgressBudgetExhausted
+from posthog.integrations import IntegrationManager, IntegrationNotFound
from posthog.models.github_integration_base import GitHubIntegrationBase
-from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.integration import GitHubIntegration
from posthog.models.integration.github import _is_safe_github_repo_path, _is_safe_github_sha
from posthog.ownership.repo_files import (
_ABSENT,
@@ -542,9 +543,12 @@ def _covering_integration(team_id: int, repository: str, *, priority: Priority)
if isinstance(cached, int):
if cached == _NO_COVERING_INTEGRATION:
return None
- integration = Integration.objects.filter(team_id=team_id, id=cached, kind="github").first()
# A disconnected integration falls through to a fresh lookup rather than to no reader.
- if integration is not None:
+ try:
+ integration = IntegrationManager.github.oauth.get(team_id, cached)
+ except IntegrationNotFound:
+ pass
+ else:
return GitHubIntegration(integration, source=EGRESS_SOURCE, priority=priority)
covering = GitHubIntegration.first_for_team_repository(team_id, repository, source=EGRESS_SOURCE, priority=priority)
decision = covering.integration.pk if covering is not None else _NO_COVERING_INTEGRATION
diff --git a/posthog/session_recordings/session_recording_external_reference_api.py b/posthog/session_recordings/session_recording_external_reference_api.py
index 4114768f73c9..6fc3a292999c 100644
--- a/posthog/session_recordings/session_recording_external_reference_api.py
+++ b/posthog/session_recordings/session_recording_external_reference_api.py
@@ -10,9 +10,10 @@ from rest_framework.exceptions import ValidationError
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.egress.limiter.policies import Priority
from posthog.event_usage import groups
+from posthog.integrations import IntegrationRecord
+from posthog.integrations.fields import IntegrationReferenceField
from posthog.models.integration import (
GitHubIntegration,
GitLabIntegration,
@@ -45,8 +46,15 @@ class SessionRecordingExternalReferenceSerializer(serializers.ModelSerializer):
config = serializers.JSONField(write_only=True)
session_recording_id = serializers.CharField(write_only=True)
integration = SessionRecordingExternalReferenceIntegrationSerializer(read_only=True)
- integration_id = TeamScopedPrimaryKeyRelatedField(
- write_only=True, queryset=Integration.objects.all(), source="integration"
+ integration_id = IntegrationReferenceField(
+ kinds=[
+ Integration.IntegrationKind.LINEAR,
+ Integration.IntegrationKind.GITHUB,
+ Integration.IntegrationKind.GITLAB,
+ Integration.IntegrationKind.JIRA,
+ ],
+ write_only=True,
+ source="integration",
)
external_url = serializers.SerializerMethodField()
title = serializers.SerializerMethodField()
@@ -151,7 +159,7 @@ class SessionRecordingExternalReferenceSerializer(serializers.ModelSerializer):
"""
team = self.context["get_team"]()
session_recording: SessionRecording = validated_data.get("session_recording")
- integration: Integration = validated_data.get("integration")
+ integration: IntegrationRecord = validated_data.get("integration")
config: dict[str, Any] = validated_data.get("config")
recording_url = self._build_recording_url(team.pk, session_recording.session_id, config)
@@ -198,7 +206,7 @@ class SessionRecordingExternalReferenceSerializer(serializers.ModelSerializer):
instance = SessionRecordingExternalReference.objects.create(
session_recording=session_recording,
- integration=integration,
+ integration_id=integration.id,
external_context=external_context,
)
diff --git a/posthog/slack/channels.py b/posthog/slack/channels.py
index cf3278af1a97..1f3e17798675 100644
--- a/posthog/slack/channels.py
+++ b/posthog/slack/channels.py
@@ -15,7 +15,8 @@ from slack_sdk.errors import SlackApiError
from slack_sdk.web import SlackResponse
from posthog.dataclasses import frozen
-from posthog.models.integration import Integration, SlackIntegration
+from posthog.integrations import IntegrationRecord
+from posthog.models.integration import SlackIntegration
logger = structlog.get_logger(__name__)
@@ -114,7 +115,7 @@ def is_shared_channel(channel: dict) -> bool:
return any(channel.get(flag) for flag in SHARED_CHANNEL_FLAGS)
-def fetch_channel_map(integration: Integration, *, source: str) -> dict[str, SlackChannel]:
+def fetch_channel_map(integration: IntegrationRecord, *, source: str) -> dict[str, SlackChannel]:
"""Public channel name -> channel, for one Slack integration.
Private channels are skipped: listing them needs a real authed Slack user, and this runs from a
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index 262e99026415..244433831b86 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -32,18 +32,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.10
@@ -287,18 +288,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.17
@@ -1196,18 +1198,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39
diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.py
index 03ac58a98180..2c1b4af5d2dc 100644
--- a/posthog/temporal/ai_observability/eval_reports/delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py
@@ -14,6 +14,7 @@ import structlog
from markdown_it import MarkdownIt
from markdown_to_mrkdwn import SlackMarkdownConverter
+from posthog.models.team import Team
from posthog.slack.formatting import channel_id_from_target
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
METRICS_UNAVAILABLE_MESSAGE,
@@ -352,7 +353,8 @@ def deliver_slack_report(
Main message = agent title (Block Kit header) + metrics context + first section.
Thread replies = sections[1:]. If there's only one section, no thread replies.
"""
- from posthog.models.integration import Integration, SlackIntegration
+ from posthog.integrations import IntegrationManager
+ from posthog.models.integration import SlackIntegration
from products.slack_app.backend.facade.api import slack_followup_invite
@@ -369,6 +371,10 @@ def deliver_slack_report(
f"*{evaluation_name}* · {_format_period_for_display(period_start)} → {_format_period_for_display(period_end)}"
)
+ team = Team.objects.select_related("organization").get(id=team_id)
+ # Read rather than assumed: nothing on this path enforces consent before generation.
+ ai_enabled = bool(team.organization.is_ai_data_processing_approved)
+
for target in targets:
if target.get("type") != "slack":
continue
@@ -386,11 +392,7 @@ def deliver_slack_report(
continue
try:
- # The organization comes along because the follow-up invite below reads its AI consent
- # flag, and this query already runs once per target.
- integration = Integration.objects.select_related("team__organization").get(
- id=integration_id, team_id=team_id, kind="slack"
- )
+ integration = IntegrationManager.slack.oauth.get(team_id, integration_id)
client = SlackIntegration(integration, source="eval_reports").client
# Main message: header + context + metrics grid + first section (if any)
@@ -418,8 +420,6 @@ def deliver_slack_report(
}
)
- # Read rather than assumed: nothing on this path enforces consent before generation.
- ai_enabled = bool(integration.team.organization.is_ai_data_processing_approved)
if invite := slack_followup_invite(integration, utm_tags=_INVITE_UTM_TAGS, ai_enabled=ai_enabled):
blocks.append(invite)
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
index 4b74346136c4..2ce62e1c5cbb 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
@@ -535,6 +535,13 @@ class TestDeliverReport(SimpleTestCase):
class TestDeliverSlackReport(SimpleTestCase):
"""Tests for the Slack delivery path, with the Slack client mocked."""
+ def setUp(self):
+ team_patcher = patch("posthog.temporal.ai_observability.eval_reports.delivery.Team")
+ self.mock_team = team_patcher.start()
+ self.addCleanup(team_patcher.stop)
+ self.team_get = self.mock_team.objects.select_related.return_value.get
+ self.team_get.return_value.organization.is_ai_data_processing_approved = True
+
def _make_report_run(self, sections=None):
if sections is None:
sections = [ReportSection(title="Summary", content="All good.")]
@@ -563,7 +570,7 @@ class TestDeliverSlackReport(SimpleTestCase):
]
)
@patch("posthog.models.integration.SlackIntegration")
- @patch("posthog.models.integration.Integration")
+ @patch("posthog.integrations.IntegrationManager")
def test_channel_id_is_used(self, _name, sections, expected_call_count, mock_integration, mock_slack_integration):
# Regression: the channel picker stores "<id>|#<name>" (e.g. "C0B5CHB0JQH|#tech-devops-cron").
# chat.postMessage only accepts the channel ID, so the "|#name" suffix must be stripped or
@@ -573,24 +580,54 @@ class TestDeliverSlackReport(SimpleTestCase):
client.chat_postMessage.return_value = {"ts": "123.456"}
mock_slack_integration.return_value.client = client
- targets = [{"type": "slack", "integration_id": 1, "channel": "C0B5CHB0JQH|#tech-devops-cron"}]
+ targets = [{"type": "slack", "integration_id": 3, "channel": "C0B5CHB0JQH|#tech-devops-cron"}]
errors = deliver_slack_report(
self._make_report_run(sections=sections),
targets,
evaluation_name="Test Eval",
- team_id=1,
+ team_id=7,
project_id=1,
period_start="2026-03-01T00:00:00+00:00",
period_end="2026-03-02T00:00:00+00:00",
)
self.assertEqual(errors, [])
+ mock_integration.slack.oauth.get.assert_called_once_with(7, 3)
self.assertEqual(client.chat_postMessage.call_count, expected_call_count)
for call in client.chat_postMessage.call_args_list:
self.assertEqual(call.kwargs["channel"], "C0B5CHB0JQH")
@patch("posthog.models.integration.SlackIntegration")
- @patch("posthog.models.integration.Integration")
+ @patch("posthog.integrations.IntegrationManager")
+ def test_several_targets_read_the_team_once(self, mock_integration, mock_slack_integration):
+ client = MagicMock()
+ client.chat_postMessage.return_value = {"ts": "123.456"}
+ mock_slack_integration.return_value.client = client
+
+ targets = [
+ {"type": "slack", "integration_id": 3, "channel": "C0B5CHB0JQH|#evals"},
+ {"type": "slack", "integration_id": 4, "channel": "C0B5CHB0JQI|#evals-2"},
+ ]
+ errors = deliver_slack_report(
+ self._make_report_run(),
+ targets,
+ evaluation_name="Test Eval",
+ team_id=7,
+ project_id=1,
+ period_start="2026-03-01T00:00:00+00:00",
+ period_end="2026-03-02T00:00:00+00:00",
+ )
+
+ self.assertEqual(errors, [])
+ self.team_get.assert_called_once_with(id=7)
+ self.assertEqual(
+ [call.args for call in mock_integration.slack.oauth.get.call_args_list],
+ [(7, 3), (7, 4)],
+ )
+ self.assertEqual(client.chat_postMessage.call_count, 2)
+
+ @patch("posthog.models.integration.SlackIntegration")
+ @patch("posthog.integrations.IntegrationManager")
def test_root_message_carries_the_followup_invite(self, mock_integration, mock_slack_integration):
# The invite goes on the root message only, so a reader meets it once per report rather
# than under every section. Which of its two variants renders is the shared builder's
@@ -621,7 +658,7 @@ class TestDeliverSlackReport(SimpleTestCase):
self.assertNotIn("blocks", client.chat_postMessage.call_args_list[1].kwargs)
@patch("posthog.models.integration.SlackIntegration")
- @patch("posthog.models.integration.Integration")
+ @patch("posthog.integrations.IntegrationManager")
def test_empty_channel_id_fails_gracefully(self, mock_integration, mock_slack_integration):
# A malformed target like "|#name" passes the non-empty channel check but splits to an
# empty channel ID, which Slack rejects with channel_not_found. Skip the send, record an
diff --git a/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr b/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr
index 78aef96b3c42..1f2a46b61372 100644
--- a/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr
+++ b/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr
@@ -32,18 +32,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestPreviewList.test_early_access_features.10
@@ -284,18 +285,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestPreviewList.test_early_access_features.5
@@ -452,18 +454,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestPreviewList.test_early_access_features_includes_payload_in_preview.2
@@ -881,18 +884,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestPreviewList.test_early_access_features_with_cached_team.3
@@ -1114,18 +1118,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestPreviewList.test_early_access_features_with_pre_env_cached_team.2
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index e95941f512d8..f52523b86928 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -374,18 +374,19 @@
"posthog_integration"."integration_id",
"posthog_integration"."config",
"posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
"posthog_integration"."errors",
"posthog_integration"."created_at",
"posthog_integration"."created_by_id"
FROM "posthog_integration"
- WHERE ((("posthog_integration"."config" -> 'auth_type') IS NULL
- OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb)
+ WHERE (("posthog_integration"."kind" = 'vercel'
+ AND (("posthog_integration"."config" -> 'auth_type') IS NULL
+ OR ("posthog_integration"."config" -> 'auth_type') = 'null'::jsonb
+ OR ("posthog_integration"."config" -> 'auth_type') = '"oauth"'::jsonb))
AND NOT ("posthog_integration"."config" ? 'warehouse_source_type')
- AND "posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
+ ORDER BY "posthog_integration"."created_at" ASC,
+ "posthog_integration"."id" ASC
+ LIMIT 1
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.2
diff --git a/products/slack_app/backend/facade/api.py b/products/slack_app/backend/facade/api.py
index 322d201e4853..d9c18c9a1eb3 100644
--- a/products/slack_app/backend/facade/api.py
+++ b/products/slack_app/backend/facade/api.py
@@ -24,6 +24,7 @@ from typing import Any
import structlog
+from posthog.integrations import IntegrationRecord
from posthog.models.integration import Integration
from products.slack_app.backend.logic.feature_tips.features import SlackFeature
@@ -114,7 +115,7 @@ def slack_channel_is_approved(slack_workspace_id: str, slack_channel_id: str) ->
return SlackChannel.approval_granted(slack_workspace_id, slack_channel_id)
-def slack_artifact_delivery_state_updates(integration: Integration) -> dict[str, str | bool]:
+def slack_artifact_delivery_state_updates(integration: IntegrationRecord) -> dict[str, str | bool]:
"""State that tells a task agent which Slack artifact adapters can deliver, and whether to
share a chart as an insight link rather than render it through the chart endpoint."""
mode = "canvas_file" if has_scopes(integration, _SLACK_CANVAS_FILE_ADAPTER_SCOPES) else "message"
@@ -125,7 +126,7 @@ def slack_artifact_delivery_state_updates(integration: Integration) -> dict[str,
}
-def slack_followup_invite_text(integration: Integration | None, *, utm_tags: str, ai_enabled: bool) -> str | None:
+def slack_followup_invite_text(integration: IntegrationRecord | None, *, utm_tags: str, ai_enabled: bool) -> str | None:
"""The mrkdwn line inviting a reader to ask the bot a follow-up about this message.
Returns ``None`` when there is nothing to invite: no Slack install, or an organization that has
@@ -138,7 +139,9 @@ def slack_followup_invite_text(integration: Integration | None, *, utm_tags: str
return build_followup_invite_text(integration, utm_tags=utm_tags, ai_enabled=ai_enabled)
-def slack_followup_invite(integration: Integration | None, *, utm_tags: str, ai_enabled: bool) -> dict[str, Any] | None:
+def slack_followup_invite(
+ integration: IntegrationRecord | None, *, utm_tags: str, ai_enabled: bool
+) -> dict[str, Any] | None:
"""``slack_followup_invite_text`` as a Slack context block, for a caller that appends blocks."""
return build_followup_invite(integration, utm_tags=utm_tags, ai_enabled=ai_enabled)
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index 8725b6e15c9f..d2033fe9ac8c 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -37,7 +37,8 @@ from __future__ import annotations
import structlog
import posthoganalytics
-from posthog.models.integration import Integration
+from posthog.integrations import IntegrationRecord
+from posthog.models.team import Team
from posthog.utils import get_instance_region
from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES, has_scopes
@@ -65,9 +66,13 @@ def _region_properties() -> dict[str, str]:
return {"region": get_instance_region() or "dev"}
+def _organization_id(integration: IntegrationRecord) -> str:
+ return str(Team.objects.values_list("organization_id", flat=True).get(id=integration.team_id))
+
+
def _workspace_flag_enabled(
flag: str,
- integration: Integration,
+ integration: IntegrationRecord,
*,
failure_log_key: str,
distinct_id: str | None = None,
@@ -80,7 +85,7 @@ def _workspace_flag_enabled(
``distinct_id`` identifies the PostHog user the check is being made for, and becomes
the identity the flag resolves against. It is a distinct ID rather than a user id so
- a caller can pass what it already holds, and so deciding a gate costs no query here.
+ a caller can pass what it already holds.
Without one the gate falls back to the Slack workspace, which no person rule can
match.
"""
@@ -89,7 +94,7 @@ def _workspace_flag_enabled(
posthoganalytics.feature_enabled(
flag,
distinct_id or f"slack_workspace:{integration.integration_id}",
- groups={"organization": str(integration.team.organization_id)},
+ groups={"organization": _organization_id(integration)},
person_properties=_region_properties(),
only_evaluate_locally=False,
send_feature_flag_events=False,
@@ -100,7 +105,7 @@ def _workspace_flag_enabled(
return False
-def is_slack_app_oauth_enabled(integration: Integration) -> bool:
+def is_slack_app_oauth_enabled(integration: IntegrationRecord) -> bool:
"""Gate for the Slack user-identity OAuth link feature, covering both backend
(offering the invite button, accepting the link callback, listing/starting
from settings) and frontend (rendering the Slack card in Personal
@@ -109,7 +114,7 @@ def is_slack_app_oauth_enabled(integration: Integration) -> bool:
return has_scopes(integration, OAUTH_REQUIRED_SCOPES)
-def is_slack_app_agent_design_enabled(integration: Integration, distinct_id: str | None = None) -> bool:
+def is_slack_app_agent_design_enabled(integration: IntegrationRecord, distinct_id: str | None = None) -> bool:
"""Gate for the agent-design plan-block streaming surface on Slack task runs.
Posts through the ``chat:write`` the mention flow already requires, so this is the
flag alone.
@@ -126,7 +131,9 @@ def is_slack_app_agent_design_enabled(integration: Integration, distinct_id: str
)
-def is_slack_app_byos_enabled(integration: Integration, distinct_id: str | None, *, adapter: str = "codex") -> bool:
+def is_slack_app_byos_enabled(
+ integration: IntegrationRecord, distinct_id: str | None, *, adapter: str = "codex"
+) -> bool:
"""Gate for Slack runs that bill to the user's own plan.
Depends on the tasks rollout flag for that plan, which is checked first. A Slack run
@@ -136,7 +143,7 @@ def is_slack_app_byos_enabled(integration: Integration, distinct_id: str | None,
from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415 — keeps tasks off this import path
if not tasks_facade.own_subscription_cloud_enabled(
- adapter, distinct_id=distinct_id, organization_id=str(integration.team.organization_id)
+ adapter, distinct_id=distinct_id, organization_id=_organization_id(integration)
):
return False
return _workspace_flag_enabled(
@@ -147,14 +154,14 @@ def is_slack_app_byos_enabled(integration: Integration, distinct_id: str | None,
)
-def is_slack_app_assistant_enabled(integration: Integration) -> bool:
+def is_slack_app_assistant_enabled(integration: IntegrationRecord) -> bool:
"""Gate for the DM assistant: the install must hold the scopes the DM surface
calls — ``im:history`` in particular, without which the assistant would answer
once and then go deaf to follow-ups."""
return has_scopes(integration, ASSISTANT_REQUIRED_SCOPES)
-def is_slack_app_forking_enabled(integration: Integration) -> bool:
+def is_slack_app_forking_enabled(integration: IntegrationRecord) -> bool:
"""Gate for the "Fork to DM" menu under a reply.
A fork lands in a DM and is answered there, so it inherits the assistant
diff --git a/products/slack_app/backend/services/followup_invite.py b/products/slack_app/backend/services/followup_invite.py
index 7568b1c7e783..271207e9a5e0 100644
--- a/products/slack_app/backend/services/followup_invite.py
+++ b/products/slack_app/backend/services/followup_invite.py
@@ -7,7 +7,7 @@ these through ``facade.api``.
from typing import Any
-from posthog.models.integration import Integration
+from posthog.integrations import IntegrationRecord
from products.slack_app.backend.services.slack_scopes import bot_is_ready
@@ -15,7 +15,7 @@ BOT_SETUP_DOCS_URL = "https://posthog.com/docs/slack-app"
def build_followup_invite_text(
- integration: Integration | None,
+ integration: IntegrationRecord | None,
*,
utm_tags: str,
ai_enabled: bool,
@@ -47,7 +47,7 @@ def build_followup_invite_text(
def build_followup_invite(
- integration: Integration | None,
+ integration: IntegrationRecord | None,
*,
utm_tags: str,
ai_enabled: bool,
diff --git a/products/slack_app/backend/services/slack_scopes.py b/products/slack_app/backend/services/slack_scopes.py
index d691ba8369d9..aed34acea6ab 100644
--- a/products/slack_app/backend/services/slack_scopes.py
+++ b/products/slack_app/backend/services/slack_scopes.py
@@ -9,7 +9,8 @@ from collections.abc import Iterable
import structlog
-from posthog.models.integration import Integration, SlackIntegration
+from posthog.integrations import IntegrationRecord
+from posthog.models.integration import SlackIntegration
logger = structlog.get_logger(__name__)
@@ -37,7 +38,7 @@ SLACK_FILE_SCOPE = "files:write"
SLACK_CANVAS_SCOPE = "canvases:write"
-def has_scopes(integration: Integration, required: Iterable[str]) -> bool:
+def has_scopes(integration: IntegrationRecord, required: Iterable[str]) -> bool:
"""Whether the install granted these bot scopes. Fails closed, so an install whose
granted set can't be read never enables anything."""
try:
@@ -47,6 +48,6 @@ def has_scopes(integration: Integration, required: Iterable[str]) -> bool:
return False
-def bot_is_ready(integration: Integration) -> bool:
+def bot_is_ready(integration: IntegrationRecord) -> bool:
"""True when the install has every scope the @PostHog bot needs to answer mentions."""
return has_scopes(integration, REQUIRED_SLACK_SCOPES)
diff --git a/products/workflows/backend/test/test_email_domain_connect_api.py b/products/workflows/backend/test/test_email_domain_connect_api.py
index c7fae9b448e7..d8dd6a114249 100644
--- a/products/workflows/backend/test/test_email_domain_connect_api.py
+++ b/products/workflows/backend/test/test_email_domain_connect_api.py
@@ -2,6 +2,7 @@ from collections.abc import Callable
from typing import Any
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from django.core.cache import cache
from django.test import override_settings
@@ -11,6 +12,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models.integration import EmailIntegration, Integration
+from posthog.models.team import Team
from products.workflows.backend.test.email_domain_api_test_case import (
ALL_KINDS,
@@ -104,6 +106,41 @@ class TestOneClickEmailDomainSetup(EmailDomainConnectTestCase):
assert self.config(sender)["setup_method"] == "auto"
assert self.verified_event_methods() == ["auto"]
+ @parameterized.expand(
+ [
+ ("unknown_id", lambda test: 999_999_999),
+ (
+ "sender_of_another_team",
+ lambda test: (
+ Integration.objects.create(
+ team=Team.objects.create(organization=test.organization, name="Other project"),
+ kind="email",
+ config={"email": f"hello@{DOMAIN}", "domain": DOMAIN, "provider": "ses"},
+ ).id
+ ),
+ ),
+ (
+ "integration_of_another_kind",
+ lambda test: Integration.objects.create(team=test.team, kind="slack", config={}).id,
+ ),
+ ]
+ )
+ def test_apply_url_for_an_unknown_sender_answers_404_without_calling_ses(
+ self, _name: str, arrange: Callable[[EmailDomainConnectTestCase], int]
+ ) -> None:
+ integration_id = arrange(self)
+ writes_before = list(self.world.ses.writes)
+
+ with patch("posthog.api.integration.capture_exception") as capture_exception:
+ response = self.apply_url(integration_id)
+
+ assert (response.status_code, response.json()["detail"]) == (
+ status.HTTP_404_NOT_FOUND,
+ "Email integration not found.",
+ )
+ assert self.world.ses.writes == writes_before
+ capture_exception.assert_not_called()
+
def test_approved_setup_keeps_an_existing_dmarc_record(self) -> None:
existing_dmarc = "v=DMARC1; p=reject; rua=mailto:[email protected]"
self.world.dns.publish_txt(f"_dmarc.{DOMAIN}", existing_dmarc)